Make improvements

- Every unit test now passes on Apple Silicon. The final piece of this
  puzzle was porting our POSIX threads cancelation support, since that
  works differently on ARM64 XNU vs. AMD64. Our semaphore support on
  Apple Silicon is also superior now compared to AMD64, thanks to the
  grand central dispatch library which lets *NSYNC locks go faster.

- The Cosmopolitan runtime is now more stable, particularly on Windows.
  To do this, thread local storage is mandatory at all runtime levels,
  and the innermost packages of the C library is no longer being built
  using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
  process startup phase, and then later on the runtime re-allocates it
  either statically or dynamically to support code using _Thread_local.
  fork() and execve() now do a better job cooperating with threads. We
  can now check how much stack memory is left in the process or thread
  when functions like kprintf() / execve() etc. call alloca(), so that
  ENOMEM can be raised, reduce a buffer size, or just print a warning.

- POSIX signal emulation is now implemented the same way kernels do it
  with pthread_kill() and raise(). Any thread can interrupt any other
  thread, regardless of what it's doing. If it's blocked on read/write
  then the killer thread will cancel its i/o operation so that EINTR can
  be returned in the mark thread immediately. If it's doing a tight CPU
  bound operation, then that's also interrupted by the signal delivery.
  Signal delivery works now by suspending a thread and pushing context
  data structures onto its stack, and redirecting its execution to a
  trampoline function, which calls SetThreadContext(GetCurrentThread())
  when it's done.

- We're now doing a better job managing locks and handles. On NetBSD we
  now close semaphore file descriptors in forked children. Semaphores on
  Windows can now be canceled immediately, which means mutexes/condition
  variables will now go faster. Apple Silicon semaphores can be canceled
  too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
  syscalls are now used on XNU when appropriate to ensure pthread_cancel
  requests aren't lost. The MbedTLS library has been updated to support
  POSIX thread cancelations. See tool/build/runitd.c for an example of
  how it can be used for production multi-threaded tls servers. Handles
  on Windows now leak less often across processes. All i/o operations on
  Windows are now overlapped, which means file pointers can no longer be
  inherited across dup() and fork() for the time being.

- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
  which means, for example, that posix_spawn() now goes 3x faster. POSIX
  spawn is also now more correct. Like Musl, it's now able to report the
  failure code of execve() via a pipe although our approach favors using
  shared memory to do that on systems that have a true vfork() function.

- We now spawn a thread to deliver SIGALRM to threads when setitimer()
  is used. This enables the most precise wakeups the OS makes possible.

- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
  it turned out the kernel would actually commit the PT_GNU_STACK size
  which caused RSS to be 6mb for every process. Now it's down to ~4kb.
  On Apple Silicon, we reduce the mandatory upstream thread size to the
  smallest possible size to reduce the memory overhead of Cosmo threads.
  The examples directory has a program called greenbean which can spawn
  a web server on Linux with 10,000 worker threads and have the memory
  usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
  thread-local storage is now optional; it won't be allocated until the
  pthread_setspecific/getspecific functions are called. On Windows, the
  threads that get spawned which are internal to the libc implementation
  use reserve rather than commit memory, which shaves a few hundred kb.

- sigaltstack() is now supported on Windows, however it's currently not
  able to be used to handle stack overflows, since crash signals are
  still generated by WIN32. However the crash handler will still switch
  to the alt stack, which is helpful in environments with tiny threads.

- Test binaries are now smaller. Many of the mandatory dependencies of
  the test runner have been removed. This ensures many programs can do a
  better job only linking the the thing they're testing. This caused the
  test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb

- long double is no longer used in the implementation details of libc,
  except in the APIs that define it. The old code that used long double
  for time (instead of struct timespec) has now been thoroughly removed.

- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
  backtraces itself, it'll just print a command you can run on the shell
  using our new `cosmoaddr2line` program to view the backtrace.

- Crash report signal handling now works in a much better way. Instead
  of terminating the process, it now relies on SA_RESETHAND so that the
  default SIG_IGN behavior can terminate the process if necessary.

- Our pledge() functionality has now been fully ported to AARCH64 Linux.
This commit is contained in:
Justine Tunney 2023-09-18 20:44:45 -07:00
parent c4eb838516
commit ec480f5aa0
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
638 changed files with 7925 additions and 8282 deletions

View file

@ -0,0 +1,21 @@
#ifndef COSMOPOLITAN_LIBC_TESTLIB_ASPECT_INTERNAL_H_
#define COSMOPOLITAN_LIBC_TESTLIB_ASPECT_INTERNAL_H_
#include "libc/intrin/dll.h"
#include "libc/testlib/testlib.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define TESTASPECT_CONTAINER(e) DLL_CONTAINER(struct TestAspect, elem, e)
struct TestAspect {
bool once;
void (*setup)(const testfn_t *);
void (*teardown)(const testfn_t *);
struct Dll elem;
};
extern struct Dll *testlib_aspects;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_TESTLIB_ASPECT_INTERNAL_H_ */

View file

@ -17,11 +17,15 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "ape/sections.internal.h"
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/log/log.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/mlock.h"
#include "libc/sysv/consts/o.h"
@ -50,11 +54,15 @@ void testlib_benchwarmup(void) {
void EnableCruiseControlForCool(void) {
int fd, micros = 10;
if ((fd = open("/dev/cpu_dma_latency", O_WRONLY)) != -1) {
write(fd, &micros, sizeof(micros));
fcntl(fd, F_DUPFD_CLOEXEC, 123);
close(fd);
if (!IsLinux()) return;
BLOCK_CANCELLATIONS;
if ((fd = __sys_openat(AT_FDCWD, "/dev/cpu_dma_latency", O_WRONLY, 0)) !=
-1) {
sys_write(fd, &micros, sizeof(micros));
sys_fcntl(fd, F_DUPFD_CLOEXEC, 123, __sys_fcntl);
sys_close(fd);
}
ALLOW_CANCELLATIONS;
}
/**

View file

@ -1,41 +0,0 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/macros.internal.h"
// Decentralized section for test combo registration.
//
// @see ape/ape.lds
.section .piro.relo.sort.combo.1,"aw",@progbits
.type __combo_start,@object
.type __combo_end,@object
.globl __combo_start,__combo_end
.hidden __combo_start,__combo_end
.byte 0
.balign __SIZEOF_POINTER__
.underrun
__combo_start:
.previous/*
...
decentralized content
...
*/.section .piro.relo.sort.combo.3,"aw",@progbits
__combo_end:
.quad 0
.overrun
.previous

View file

@ -1,99 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/safemacros.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
struct ComboGroup {
unsigned entry;
unsigned i;
unsigned n;
};
struct ComboProduct {
unsigned n;
struct ComboGroup groups[];
};
mallocesque struct ComboProduct *testlib_setupcomboproduct(
const struct TestFixture *start, const struct TestFixture *end) {
unsigned i, j, entrycount;
struct ComboProduct *product;
entrycount = testlib_countfixtures(start, end);
product = calloc(
sizeof(struct ComboProduct) + entrycount * sizeof(struct ComboGroup), 1);
for (j = i = 0; i < entrycount; ++i) {
if (j && strcmp(start[product->groups[j - 1].entry].group,
start[i].group) == 0) {
product->groups[j - 1].n++;
} else {
++j;
product->groups[j - 1].entry = i;
product->groups[j - 1].n = 1;
}
}
product->n = j;
return product;
}
static void testlib_describecombo(struct ComboProduct *product,
const struct TestFixture *combos) {
char *p = &g_fixturename[0];
char *pe = p + sizeof(g_fixturename);
for (unsigned i = 0; i < product->n && p < pe; ++i) {
const char *sep = i ? ", " : "";
const struct TestFixture *e =
&combos[product->groups[i].entry + product->groups[i].i];
p += max(0, snprintf(p, pe - p, "%s%s=%s", sep, e->group, e->name));
}
}
static void testlib_callcombos(struct ComboProduct *product,
const struct TestFixture *combos,
const testfn_t *test_start,
const testfn_t *test_end) {
for (;;) {
testlib_describecombo(product, combos);
for (unsigned i = 0; i < product->n; ++i) {
combos[product->groups[i].entry + product->groups[i].i].fn();
}
for (unsigned i = product->n;; --i) {
if (!i) return;
if (++product->groups[i - 1].i < product->groups[i - 1].n) break;
product->groups[i - 1].i = 0;
}
testlib_runtestcases(test_start, test_end, NULL);
}
}
/**
* Runs Cartesian product of COMBO() fixtures registered with linker.
* @see ape/ape.lds
* @see libc/testlib/testlib.h
*/
void testlib_runcombos(const testfn_t *test_start, const testfn_t *test_end,
const struct TestFixture *combo_start,
const struct TestFixture *combo_end) {
struct ComboProduct *product;
product = testlib_setupcomboproduct(combo_start, combo_end);
testlib_callcombos(product, combo_start, test_start, test_end);
free(product);
}

View file

@ -16,8 +16,9 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/kprintf.h"
#include "libc/stdio/stdio.h"
#include "libc/testlib/ezbench.h"
#include "libc/testlib/testlib.h"
@ -25,8 +26,9 @@ static bool once;
static double g_ezbenchcontrol;
double __testlib_ezbenchcontrol(void) {
char ibuf[12];
int Core, Tries, Interrupts;
if (!once) {
int Core, Tries, Interrupts;
Tries = 0;
do {
__testlib_yield();
@ -37,10 +39,11 @@ double __testlib_ezbenchcontrol(void) {
} while (++Tries < 10 && (__testlib_getcore() != Core &&
__testlib_getinterrupts() > Interrupts));
if (Tries == 10) {
fputs("warning: failed to accurately benchmark control\n", stderr);
tinyprint(2, "warning: failed to accurately benchmark control\n");
}
kprintf("will subtract benchmark overhead of %g cycles\n\n",
g_ezbenchcontrol);
FormatInt32(ibuf, g_ezbenchcontrol);
tinyprint(2, "will subtract benchmark overhead of ", ibuf, " cycles\n\n",
NULL);
once = true;
}
return g_ezbenchcontrol;

View file

@ -16,74 +16,57 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/fmt/fmt.h"
#include "libc/intrin/kprintf.h"
#include "libc/math.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/testlib/testlib.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
__static_yoink("strnwidth");
void __testlib_ezbenchreport(const char *form, double c1, double c2) {
long ns1, ns2;
__warn_if_powersave();
ns1 = lrintl(ConvertTicksToNanos(c1));
ns2 = lrintl(ConvertTicksToNanos(c2));
(fprintf)(stderr,
__veil("r", " * %-19s l: %,9luc %,9luns m: %,9luc %,9luns\n"),
form, lrint(c1), ns1, lrint(c2), ns2);
kprintf(" * %-19s l: %,9luc %,9luns m: %,9luc %,9luns\n", form,
lrint(c1), lrint(c1 / 3), lrint(c2), lrint(c2 / 3));
}
void __testlib_ezbenchreport_n(const char *form, char z, size_t n, double c) {
char msg[128];
long cn, lat;
uint64_t bps;
long double cn, lat;
char msg[128];
__warn_if_powersave();
(snprintf)(msg, sizeof(msg), "%s %c=%d", form, z, n);
cn = ConvertTicksToNanos(c);
ksnprintf(msg, sizeof(msg), "%s %c=%d", form, z, n);
cn = lrint(c / 3);
if (!n) {
(fprintf)(stderr, "\n");
(fprintf)(stderr, " * %-28s", msg);
kprintf("\n");
kprintf(" * %-28s", msg);
if (cn < 1) {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)(cn * 1024),
"picoseconds");
kprintf(" %'9lu %-12s", (int64_t)(cn * 1024), "picoseconds");
} else if (cn > 1024) {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)(cn / 1024),
"microseconds");
kprintf(" %'9lu %-12s", (int64_t)(cn / 1024), "microseconds");
} else {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)cn,
"nanoseconds");
kprintf(" %'9lu %-12s", (int64_t)cn, "nanoseconds");
}
} else {
(fprintf)(stderr, " * %-28s", msg);
kprintf(" * %-28s", msg);
bps = n / cn * 1e9;
lat = cn / n;
if (lat < 1e-3) {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"),
(int64_t)(lat * 1024 * 1024), "fs/byte");
kprintf(" %'9lu %-12s", (int64_t)(lat * 1024 * 1024), "fs/byte");
} else if (lat < 1) {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)(lat * 1024),
"ps/byte");
kprintf(" %'9lu %-12s", (int64_t)(lat * 1024), "ps/byte");
} else if (lat > 1024) {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)(lat / 1024),
"µs/byte");
kprintf(" %'9lu %-12s", (int64_t)(lat / 1024), "µs/byte");
} else {
(fprintf)(stderr, __veil("r", " %,9lu %-12s"), (int64_t)lat, "ns/byte");
kprintf(" %'9lu %-12s", (int64_t)lat, "ns/byte");
}
if (bps < 10 * 1000) {
(fprintf)(stderr, __veil("r", " %,9lu b/s"), bps);
kprintf(" %'9lu b/s", bps);
} else if (bps < 10 * 1000 * 1024) {
(fprintf)(stderr, __veil("r", " %,9lu kb/s"), bps / 1024);
kprintf(" %'9lu kb/s", bps / 1024);
} else if (bps < 10ul * 1000 * 1024 * 1024) {
(fprintf)(stderr, __veil("r", " %,9lu mb/s"), bps / (1024 * 1024));
kprintf(" %'9lu mb/s", bps / (1024 * 1024));
} else if (bps < 10ul * 1000 * 1024 * 1024 * 1024) {
(fprintf)(stderr, __veil("r", " %,9lu GB/s"), bps / (1024 * 1024 * 1024));
kprintf(" %'9lu GB/s", bps / (1024 * 1024 * 1024));
} else {
(fprintf)(stderr, __veil("r", " %,9lu TB/s"),
bps / (1024ul * 1024 * 1024 * 1024));
kprintf(" %'9lu TB/s", bps / (1024ul * 1024 * 1024 * 1024));
}
}
(fprintf)(stderr, "\n", form);
kprintf("\n", form);
}

View file

@ -16,11 +16,9 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/stdio/stdio.h"
#include "libc/calls/calls.h"
#include "libc/testlib/testlib.h"
void __testlib_ezbenchwarn(const char *msg) {
fputs("warning: failed to accurately benchmark", stderr);
fputs(msg, stderr);
fputc('\n', stderr);
tinyprint(2, "warning: failed to accurately benchmark", msg, "\n", NULL);
}

View file

@ -17,7 +17,7 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/runtime/internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/prot.h"
#include "libc/testlib/testlib.h"
@ -37,8 +37,9 @@ void testlib_runfixtures(const testfn_t *test_start, const testfn_t *test_end,
unsigned i, count;
count = testlib_countfixtures(fixture_start, fixture_end);
for (i = 0; i < count && !g_testlib_failed; ++i) {
(snprintf)(g_fixturename, sizeof(g_fixturename), "%s_%s",
fixture_start[i].group, fixture_start[i].name);
strlcpy(g_fixturename, fixture_start[i].group, sizeof(g_fixturename));
strlcat(g_fixturename, "_", sizeof(g_fixturename));
strlcat(g_fixturename, fixture_start[i].name, sizeof(g_fixturename));
fixture_start[i].fn();
testlib_runtestcases(test_start, test_end, NULL);
}

View file

@ -16,23 +16,48 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/intrin/bits.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "libc/testlib/testlib.h"
#include "libc/atomic.h"
#include "libc/fmt/itoa.h"
#include "libc/fmt/magnumstrs.internal.h"
#include "libc/intrin/atomic.h"
#include "libc/str/str.h"
static size_t sbufi_;
static char sbufs_[2][256];
#define STRS 4
#define BYTES 128
static atomic_uint bufi;
static char bufs[STRS][BYTES];
char *testlib_formatint(intptr_t x) {
char *str = sbufi_ < ARRAYLEN(sbufs_) ? sbufs_[sbufi_++] : malloc(256);
char *p = str;
p += sprintf(p, "%ld\t(or %#lx", x, x);
if (0 <= x && x < 256) {
p += sprintf(p, " or %#`c", (unsigned char)x);
int i = atomic_fetch_add(&bufi, 1) % STRS;
char *p = bufs[i];
p = FormatInt64(p, x);
p = stpcpy(p, " (or ");
p = FormatHex64(p, x, 1);
if (0 <= x && x <= 255) {
p = stpcpy(p, " or '");
if (!isascii(x) || iscntrl(x)) {
*p++ = '\\';
if (x > 7) {
if (x > 070) {
*p++ = '0' + ((x & 0700) >> 6);
}
*p++ = '0' + ((x & 070) >> 3);
}
*p++ = '0' + (x & 7);
} else if (x == '\\' || x == '\'') {
*p++ = '\\';
*p++ = x;
} else {
*p++ = x;
}
*p++ = '\'';
}
if (_strerrno(x)) {
p = stpcpy(p, " or ");
p = stpcpy(p, _strerrno(x));
}
*p++ = ')';
*p++ = '\0';
return strdup(str);
return bufs[i];
}

View file

@ -16,31 +16,98 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/bits.h"
#include "libc/str/str.h"
#include "libc/str/utf16.h"
#include "libc/testlib/testlib.h"
#include "libc/x/xasprintf.h"
#define STRS 4
#define BYTES 64
#define APPEND(c) \
do { \
if (j + 1 < BYTES) { \
bufs[i][j++] = c; \
} \
} while (0)
static atomic_uint bufi;
static char bufs[STRS][BYTES];
static int AppendWide(wint_t x, int i, int j) {
uint64_t w;
if (isascii(x) && iscntrl(x)) {
APPEND('\\');
APPEND('0' + ((x & 0700) >> 6));
APPEND('0' + ((x & 070) >> 3));
APPEND('0' + (x & 7));
} else if (x == '\\' || x == '\'') {
APPEND('\\');
APPEND(x);
} else {
w = tpenc(x);
while (w) {
APPEND(w);
w >>= 8;
}
}
return j;
}
/**
* Turns string into code.
*/
char *testlib_formatstr(size_t cw, const void *s, int n) {
if (s) {
switch (cw) {
case 1:
if (n == -1) n = s ? strlen(s) : 0;
return xasprintf("%`'.*s", n, s);
case 2:
if (n == -1) n = s ? strlen16(s) : 0;
return xasprintf("%`'.*hs", n, s);
case 4:
if (n == -1) n = s ? wcslen(s) : 0;
return xasprintf("%`'.*ls", n, s);
default:
abort();
char *testlib_formatstr(size_t cw, const void *p, int n) {
int i, j = 0;
if (!p) return "NULL";
i = atomic_fetch_add(&bufi, 1) % STRS;
switch (cw) {
case 1: {
const char *s = p;
if (n < 0) n = s ? strlen(s) : 0;
const char *se = s + n;
APPEND('"');
while (s < se) {
j = AppendWide(*s++ & 255, i, j);
}
break;
}
} else {
return strdup("NULL");
case 2: {
const char16_t *s = p;
if (n < 0) n = s ? strlen16(s) : 0;
const char16_t *se = s + n;
APPEND('u');
APPEND('"');
while (s < se) {
wint_t x = *s++ & 0xffff;
if (IsUtf16Cont(x)) continue;
if (!IsUcs2(x) && s < se) {
wint_t y = *s++ & 0xffff;
x = MergeUtf16(x, y);
}
j = AppendWide(x, i, j);
}
break;
}
case 4: {
const wchar_t *s = p;
if (n < 0) n = s ? wcslen(s) : 0;
const wchar_t *se = s + n;
APPEND('L');
APPEND('"');
while (s < se) {
j = AppendWide(*s++, i, j);
}
break;
}
default:
notpossible;
}
APPEND('"');
bufs[i][j] = 0;
if (j == BYTES - 1) {
WRITE32LE(bufs[i] + j - 4, READ32LE("...\""));
}
return bufs[i];
}

View file

@ -1,109 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/errno.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/bsr.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/backtrace.internal.h"
#include "libc/log/internal.h"
#include "libc/log/libfatal.internal.h"
#include "libc/log/log.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/sig.h"
#include "libc/testlib/testlib.h"
#include "third_party/dlmalloc/dlmalloc.h"
static dontasan dontubsan relegated uint64_t CountMappedBytes(void) {
size_t i;
uint64_t x, y;
for (x = i = 0; i < _mmi.i; ++i) {
y = _mmi.p[i].y - _mmi.p[i].x;
x += (y + 1) << 16;
}
return x;
}
static relegated void DieBecauseOfQuota(int rc, const char *message) {
char hostname[32];
stpcpy(hostname, "unknown");
gethostname(hostname, sizeof(hostname));
kprintf("%s on %s pid %d\n", message, hostname, (long)getpid());
PrintBacktraceUsingSymbols(2, 0, GetSymbolTable());
_Exit(rc);
}
static relegated void OnXcpu(int sig) {
__restore_tty();
DieBecauseOfQuota(23, "\n\nSIGXCPU: ran out of cpu");
}
static relegated void OnXfsz(int sig) {
__restore_tty();
DieBecauseOfQuota(25, "\n\nSIGXFSZ: exceeded maximum file size");
}
static unsigned long roundup2pow(unsigned long x) {
return x > 1 ? 2ul << _bsrl(x - 1) : x ? 1 : 0;
}
relegated void __oom_hook(size_t request) {
int e;
uint64_t toto, newlim;
__restore_tty();
e = errno;
toto = CountMappedBytes();
kprintf("\n\nWE REQUIRE MORE VESPENE GAS");
if (e != ENOMEM) kprintf(" (%s)", strerror(e));
if (IsRunningUnderMake()) {
newlim = toto + request;
newlim += newlim >> 1;
newlim = roundup2pow(newlim);
kprintf("FIX CODE OR TUNE QUOTA += -M%dm\n", newlim / (1024 * 1024));
}
kprintf("\n");
__print_maps();
kprintf("\nTHE STRAW THAT BROKE THE CAMEL'S BACK\n");
PrintBacktraceUsingSymbols(2, 0, GetSymbolTable());
PrintSystemMappings(2);
_Exit(42);
}
static textstartup void InstallQuotaHandlers(void) {
int e;
struct sigaction sa;
e = errno;
sa.sa_flags = 0;
sa.sa_handler = OnXcpu;
sigemptyset(&sa.sa_mask);
sigaction(SIGXCPU, &sa, 0);
sa.sa_handler = OnXfsz;
sigaction(SIGXFSZ, &sa, 0);
GetSymbolTable(); /* for effect in case we oom */
errno = e;
}
const void *const testlib_quota_handlers[] initarray = {
InstallQuotaHandlers,
};

View file

@ -30,14 +30,9 @@
*/
void testlib_runalltests(void) {
if ((intptr_t)__testcase_end > (intptr_t)__testcase_start) {
if (testlib_countfixtures(__combo_start, __combo_end)) {
testlib_runcombos(__testcase_start, __testcase_end, __combo_start,
__combo_end);
} else {
testlib_runtestcases(__testcase_start, __testcase_end, NULL);
testlib_runfixtures(__testcase_start, __testcase_end, __fixture_start,
__fixture_end);
testlib_finish();
}
testlib_runtestcases(__testcase_start, __testcase_end, NULL);
testlib_runfixtures(__testcase_start, __testcase_end, __fixture_start,
__fixture_end);
testlib_finish();
}
}

View file

@ -16,17 +16,21 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "ape/sections.internal.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/log/color.internal.h"
#include "libc/log/internal.h"
#include "libc/log/libfatal.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
@ -36,24 +40,33 @@ const char *testlib_showerror_func;
const char *testlib_showerror_macro;
const char *testlib_showerror_symbol;
// TODO(jart): Pay off tech debt re duplication
static void Free(void *p) {
if (_weaken(free) && (long)p >= (long)_end) {
_weaken(free)(p);
}
}
void testlib_showerror(const char *file, int line, const char *func,
const char *method, const char *symbol, const char *code,
char *v1, char *v2) {
char hostname[128];
__stpcpy(hostname, "unknown");
char hostname[128], linestr[12], pidstr[12], tidstr[12];
stpcpy(hostname, "unknown");
gethostname(hostname, sizeof(hostname));
kprintf("%serror%s%s:%s:%d%s: %s() in %s(%s) on %s pid %d tid %d\n"
"\t%s\n"
"\t\tneed %s %s\n"
"\t\t got %s\n"
"\t%s%s\n"
"\t%s%s\n",
RED2, UNBOLD, BLUE1, file, line, RESET, method, func, g_fixturename,
hostname, getpid(), gettid(), code, v1, symbol, v2, SUBTLE,
strerror(errno), GetProgramExecutableName(), RESET);
free(v1);
free(v2);
FormatInt32(linestr, line);
FormatInt32(pidstr, getpid());
FormatInt32(tidstr, gettid());
tinyprint(2, RED2, "error", UNBOLD, ":", BLUE1, //
file, ":", linestr, RESET, ": ", //
method, "() in ", func, "(", g_fixturename, ") ", //
"on ", hostname, " pid ", pidstr, " tid ", tidstr, "\n", //
"\t", code, "\n", //
"\t\tneed ", v1, " ", symbol, "\n", //
"\t\t got ", v2, "\n", //
"\t", SUBTLE, strerror(errno), "\n", //
"\t", __argv[0], RESET, "\n", //
NULL);
Free(v1);
Free(v2);
}
static void testlib_showerror_(int line, //
@ -63,36 +76,41 @@ static void testlib_showerror_(int line, //
char *FREED_got, //
const char *fmt, //
va_list va) {
int e;
char hostname[128];
e = errno;
if (gethostname(hostname, sizeof(hostname))) {
__stpcpy(hostname, "unknown");
}
kprintf("%serror%s:%s%s:%d%s: %s(%s) on %s pid %d tid %d\n"
"\t%s(%s, %s)\n",
RED2, UNBOLD, BLUE1, testlib_showerror_file, line, RESET,
testlib_showerror_func, g_fixturename, hostname, getpid(), gettid(),
testlib_showerror_macro, wantcode, gotcode);
int e = errno;
char hostname[128], linestr[12], pidstr[12], tidstr[12];
stpcpy(hostname, "unknown");
gethostname(hostname, sizeof(hostname));
FormatInt32(linestr, line);
FormatInt32(pidstr, getpid());
FormatInt32(tidstr, gettid());
tinyprint( //
2, RED2, "error", UNBOLD, BLUE1, ":", //
testlib_showerror_file, ":", linestr, RESET, ": ", //
testlib_showerror_func, "(", g_fixturename, ") ", //
"on ", hostname, " pid ", pidstr, " tid ", tidstr, "\n", //
"\t", testlib_showerror_macro, "(", wantcode, ", ", gotcode, ")\n", //
NULL);
if (wantcode) {
kprintf("\t\tneed %s %s\n"
"\t\t got %s\n",
FREED_want, testlib_showerror_symbol, FREED_got);
tinyprint(2, "\t\tneed ", FREED_want, " ", testlib_showerror_symbol, "\n",
"\t\t got ", FREED_got, "\n", NULL);
} else {
kprintf("\t\t→ %s%s\n", testlib_showerror_symbol, FREED_want);
tinyprint(2, "\t\t", testlib_showerror_symbol, FREED_want, "\n", NULL);
}
if (!isempty(fmt)) {
kprintf("\t");
kvprintf(fmt, va);
kprintf("\n");
if (_weaken(kvprintf)) {
tinyprint(2, "\t");
_weaken(kvprintf)(fmt, va);
tinyprint(2, "\n");
} else {
tinyprint(2, "\t[missing kvprintf]\n");
}
}
kprintf("\t%s%s%s\n"
"\t%s%s @ %s%s\n",
SUBTLE, strerror(e), RESET, SUBTLE,
firstnonnull(program_invocation_name, "unknown"), hostname, RESET);
/* free(FREED_want); */
/* free(FREED_got); */
tinyprint(2, "\t", SUBTLE, strerror(e), RESET, "\n\t", SUBTLE,
firstnonnull(program_invocation_name, "unknown"), " @ ", hostname,
RESET, "\n", NULL);
++g_testlib_failed;
Free(FREED_want);
Free(FREED_got);
}
void testlib_showerror_assert_eq(int line, //

View file

@ -29,17 +29,6 @@ COSMOPOLITAN_C_START_
__static_yoink("__fixture_start"); \
__FIXTURE("fixture", SUITE, NAME)
/**
* Registers explosive fixture with linker.
*
* All tests will run an additional time for each set of entries in the
* Cartesian product of groups. That makes this similar to fixture, but
* more appropriate for testing pure code (i.e. no syscalls) like math.
*/
#define COMBO(GROUP, ENTRY) \
__static_yoink("__combo_start"); \
__FIXTURE("combo", GROUP, ENTRY)
/**
* Declares benchmark function.
*
@ -104,13 +93,10 @@ COSMOPOLITAN_C_START_
/**
* Enables setup and teardown of test directories.
*
* If the linker says this symbol exists then, regardless of its value,
* a unique test directory will be created at the start of each test,
* the test will be run with that directory as its working directory,
* and if the test succeeds it'll be removed along with any contents.
* These should be called from SetUpOnce().
*/
extern char testlib_enable_tmp_setup_teardown;
extern char testlib_enable_tmp_setup_teardown_once;
void testlib_enable_tmp_setup_teardown(void);
void testlib_enable_tmp_setup_teardown_once(void);
/**
* User-defined test setup function.
@ -357,7 +343,6 @@ extern const char *testlib_showerror_func; /* set by macros */
extern const testfn_t __bench_start[], __bench_end[];
extern const testfn_t __testcase_start[], __testcase_end[];
extern const struct TestFixture __fixture_start[], __fixture_end[];
extern const struct TestFixture __combo_start[], __combo_end[];
void testlib_showerror_assert_eq(int, const char *, const char *, char *,
char *, const char *, ...) wontreturn;
@ -389,8 +374,6 @@ const char *testlib_strerror(void);
void testlib_runallbenchmarks(void);
bool testlib_memoryexists(const void *);
void testlib_runtestcases(const testfn_t *, const testfn_t *, testfn_t);
void testlib_runcombos(const testfn_t *, const testfn_t *,
const struct TestFixture *, const struct TestFixture *);
void testlib_runfixtures(const testfn_t *, const testfn_t *,
const struct TestFixture *,
const struct TestFixture *);

View file

@ -19,6 +19,7 @@ LIBC_TESTLIB_A_ASSETS = \
libc/testlib/moby.txt
LIBC_TESTLIB_A_HDRS = \
libc/testlib/aspect.internal.h \
libc/testlib/bench.h \
libc/testlib/blocktronics.h \
libc/testlib/ezbench.h \
@ -32,7 +33,6 @@ LIBC_TESTLIB_A_HDRS = \
LIBC_TESTLIB_A_SRCS_S = \
libc/testlib/bench.S \
libc/testlib/blocktronics.S \
libc/testlib/combo.S \
libc/testlib/fixture.S \
libc/testlib/hyperion.S \
libc/testlib/moby.S \
@ -45,7 +45,6 @@ LIBC_TESTLIB_A_SRCS_C = \
libc/testlib/benchrunner.c \
libc/testlib/binequals.c \
libc/testlib/clearxmmregisters.c \
libc/testlib/comborunner.c \
libc/testlib/contains.c \
libc/testlib/endswith.c \
libc/testlib/extract.c \
@ -67,7 +66,6 @@ LIBC_TESTLIB_A_SRCS_C = \
libc/testlib/hexequals.c \
libc/testlib/incrementfailed.c \
libc/testlib/memoryexists.c \
libc/testlib/quota.c \
libc/testlib/seterrno.c \
libc/testlib/shoulddebugbreak.c \
libc/testlib/showerror.c \
@ -77,6 +75,7 @@ LIBC_TESTLIB_A_SRCS_C = \
libc/testlib/strerror.c \
libc/testlib/testrunner.c \
libc/testlib/thunks.c \
libc/testlib/tmptest.c \
libc/testlib/waitforexit.c \
libc/testlib/waitforterm.c \
libc/testlib/yield.c
@ -98,6 +97,7 @@ LIBC_TESTLIB_A_DIRECTDEPS = \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_NT_KERNEL32 \
LIBC_PROC \
LIBC_RUNTIME \
LIBC_STDIO \
LIBC_STR \
@ -133,8 +133,6 @@ o/$(MODE)/libc/testlib/bench.o: libc/testlib/bench.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/testlib/blocktronics.o: libc/testlib/blocktronics.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/testlib/combo.o: libc/testlib/combo.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/testlib/fixture.o: libc/testlib/fixture.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/testlib/hyperion.o: libc/testlib/hyperion.S

View file

@ -16,47 +16,34 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "ape/sections.internal.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/dll.h"
#include "libc/intrin/getenv.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/log/check.h"
#include "libc/log/color.internal.h"
#include "libc/log/libfatal.internal.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/vendor.internal.h"
#include "libc/nexgen32e/x86feature.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.internal.h"
#include "libc/runtime/sysconf.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/sig.h"
#include "libc/testlib/aspect.internal.h"
#include "libc/testlib/testlib.h"
#include "third_party/dlmalloc/dlmalloc.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/tls.h"
#include "third_party/getopt/getopt.internal.h"
#define USAGE \
@ -68,20 +55,15 @@ Flags:\n\
-h show this information\n\
\n"
__static_yoink("__die");
__static_yoink("GetSymbolByAddr");
__static_yoink("testlib_quota_handlers");
static bool runbenchmarks_;
void PrintUsage(int rc, FILE *f) {
fputs("Usage: ", f);
fputs(firstnonnull(program_invocation_name, "unknown"), f);
fputs(USAGE, f);
static void PrintUsage(int rc, int fd) {
tinyprint(fd, "Usage: ", firstnonnull(program_invocation_name, "unknown"),
USAGE, NULL);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
static void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "?hbv")) != -1) {
switch (opt) {
@ -93,69 +75,9 @@ void GetOpts(int argc, char *argv[]) {
break;
case '?':
case 'h':
PrintUsage(EXIT_SUCCESS, stdout);
PrintUsage(0, 1);
default:
PrintUsage(EX_USAGE, stderr);
}
}
}
static void EmptySignalMask(void) {
sigset_t ss;
sigemptyset(&ss);
sigprocmask(SIG_SETMASK, &ss, 0);
}
static void FixIrregularFds(void) {
int e, i, fd, maxfds;
struct rlimit rlim;
struct pollfd *pfds;
for (i = 0; i < 3; ++i) {
if (fcntl(i, F_GETFL) == -1) {
errno = 0;
fd = open("/dev/null", O_RDWR);
CHECK_NE(-1, fd);
if (fd != i) {
close(fd);
}
}
}
// TODO(jart): delete this stuff
if (1) return;
e = errno;
if (!closefrom(3)) return;
errno = e;
if (IsWindows()) {
maxfds = 64;
} else {
maxfds = 256;
if (!getrlimit(RLIMIT_NOFILE, &rlim)) {
maxfds = MIN(maxfds, (uint64_t)rlim.rlim_cur);
}
}
pfds = malloc(maxfds * sizeof(struct pollfd));
for (i = 0; i < maxfds; ++i) {
pfds[i].fd = i + 3;
pfds[i].events = POLLIN;
}
if (poll(pfds, maxfds, 0) != -1) {
for (i = 0; i < maxfds; ++i) {
if (pfds[i].revents & POLLNVAL) continue;
CHECK_EQ(0, close(pfds[i].fd));
}
}
free(pfds);
}
static void SetLimit(int resource, uint64_t soft, uint64_t hard) {
struct rlimit old;
struct rlimit lim = {soft, hard};
if (resource == 127) return;
if (setrlimit(resource, &lim) == -1) {
if (!getrlimit(resource, &old)) {
lim.rlim_max = MIN(hard, old.rlim_max);
lim.rlim_cur = MIN(soft, lim.rlim_max);
setrlimit(resource, &lim);
PrintUsage(1, 2);
}
}
}
@ -166,34 +88,82 @@ static void SetLimit(int resource, uint64_t soft, uint64_t hard) {
* Generic test program main function.
*/
dontasan int main(int argc, char *argv[]) {
int fd;
struct Dll *e;
struct TestAspect *a;
__log_level = kLogInfo;
GetOpts(argc, argv);
for (fd = 3; fd < 10; ++fd) {
close(fd);
}
#ifndef TINY
setenv("GDB", "", true);
GetSymbolTable();
// normalize this process
FixIrregularFds();
EmptySignalMask();
#endif
ShowCrashReports();
// now get down to business
g_testlib_shoulddebugbreak = IsDebuggerPresent(false);
if (!IsWindows()) sys_getpid(); // make strace easier to read
// global setup
errno = 0;
STRACE("");
STRACE("# setting up once");
if (!IsWindows()) sys_getpid();
testlib_clearxmmregisters();
if (_weaken(SetUpOnce)) {
_weaken(SetUpOnce)();
}
for (e = dll_first(testlib_aspects); e; e = dll_next(testlib_aspects, e)) {
a = TESTASPECT_CONTAINER(e);
if (a->once && a->setup) {
a->setup(0);
}
}
// run tests
testlib_runalltests();
// run benchmarks
if (!g_testlib_failed && runbenchmarks_ &&
_weaken(testlib_runallbenchmarks)) {
_weaken(testlib_runallbenchmarks)();
if (IsAsan() && !g_testlib_failed) {
CheckForMemoryLeaks();
}
// global teardown
STRACE("");
STRACE("# tearing down once");
for (e = dll_last(testlib_aspects); e; e = dll_prev(testlib_aspects, e)) {
a = TESTASPECT_CONTAINER(e);
if (a->once && a->teardown) {
a->teardown(0);
}
if (!g_testlib_failed && IsRunningUnderMake()) {
return 254; // compile.com considers this 0 and propagates output
}
} else if (IsAsan() && !g_testlib_failed) {
}
if (_weaken(TearDownOnce)) {
_weaken(TearDownOnce)();
}
// make sure threads are in a good state
if (_weaken(_pthread_decimate)) {
_weaken(_pthread_decimate)();
}
if (_weaken(pthread_orphan_np) && !_weaken(pthread_orphan_np)()) {
tinyprint(2, "error: tests ended with threads still active\n", NULL);
_Exit(1);
}
// check for memory leaks
if (IsAsan() && !g_testlib_failed) {
CheckForMemoryLeaks();
}
// we're done!
exit(min(255, g_testlib_failed));
int status = MIN(255, g_testlib_failed);
if (!status && IsRunningUnderMake()) {
return 254; // compile.com considers this 0 and propagates output
} else if (!status && _weaken(pthread_exit)) {
_weaken(pthread_exit)(0);
} else {
return status;
}
}

View file

@ -21,7 +21,8 @@
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/dll.h"
#include "libc/intrin/getenv.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/limits.h"
@ -31,17 +32,20 @@
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/testlib/aspect.internal.h"
#include "libc/testlib/testlib.h"
#include "libc/thread/thread.h"
#include "libc/x/x.h"
static char g_olddir[PATH_MAX];
static char g_tmpdir[PATH_MAX];
struct Dll *testlib_aspects;
static pthread_mutex_t testlib_error_lock;
void testlib_finish(void) {
char b1[12], b2[12];
if (g_testlib_failed) {
kprintf("%u / %u %s\n", g_testlib_failed, g_testlib_ran, "tests failed");
FormatInt32(b1, g_testlib_failed);
FormatInt32(b2, g_testlib_ran);
tinyprint(2, b1, " / ", b2, " tests failed\n", NULL);
}
}
@ -69,37 +73,6 @@ wontreturn void testlib_abort(void) {
_Exit(MAX(1, MIN(255, g_testlib_failed)));
}
static void SetupTmpDir(void) {
char number[21];
FormatInt64(number, _rand64() & INT64_MAX);
g_tmpdir[0] = 0;
if (*kTmpPath != '/') {
strlcat(g_tmpdir, g_olddir, sizeof(g_tmpdir));
strlcat(g_tmpdir, "/", sizeof(g_tmpdir));
}
strlcat(g_tmpdir, kTmpPath, sizeof(g_tmpdir));
strlcat(g_tmpdir, program_invocation_short_name, sizeof(g_tmpdir));
strlcat(g_tmpdir, ".", sizeof(g_tmpdir));
strlcat(g_tmpdir, number, sizeof(g_tmpdir));
if (makedirs(g_tmpdir, 0755) || chdir(g_tmpdir)) {
perror(g_tmpdir);
tinyprint(2, "testlib failed to setup tmpdir\n", NULL);
exit(1);
}
}
static void TearDownTmpDir(void) {
if (chdir(g_olddir)) {
perror(g_olddir);
exit(1);
}
if (rmrf(g_tmpdir)) {
perror(g_tmpdir);
tinyprint(2, "testlib failed to tear down tmpdir\n", NULL);
exit(1);
}
}
/**
* Runs all test case functions in sorted order.
*/
@ -116,45 +89,41 @@ void testlib_runtestcases(const testfn_t *start, const testfn_t *end,
// Test cases are iterable via a decentralized section. Your TEST()
// macro inserts .testcase.SUITENAME sections into the binary which
// the linker sorts into an array.
//
// @see ape/ape.lds
char host[64];
struct Dll *e;
const testfn_t *fn;
if (_weaken(testlib_enable_tmp_setup_teardown) ||
_weaken(testlib_enable_tmp_setup_teardown_once)) {
if (!getcwd(g_olddir, sizeof(g_olddir))) {
perror("getcwd");
exit(1);
}
}
if (_weaken(testlib_enable_tmp_setup_teardown_once)) {
SetupTmpDir();
}
if (_weaken(SetUpOnce)) _weaken(SetUpOnce)();
struct TestAspect *a;
strcpy(host, "unknown");
gethostname(host, sizeof(host)), errno = 0;
for (fn = start; fn != end; ++fn) {
STRACE("");
STRACE("# setting up %t", fn);
if (_weaken(testlib_enable_tmp_setup_teardown)) SetupTmpDir();
for (e = dll_first(testlib_aspects); e; e = dll_next(testlib_aspects, e)) {
a = TESTASPECT_CONTAINER(e);
if (!a->once && a->setup) {
a->setup(fn);
}
}
if (_weaken(SetUp)) _weaken(SetUp)();
errno = 0;
if (IsWindows()) {
SetLastError(0);
}
if (IsWindows()) SetLastError(0);
if (!IsWindows()) sys_getpid();
if (warmup) warmup();
testlib_clearxmmregisters();
STRACE("");
STRACE("# running test %t", fn);
STRACE("# running test %t on %s@%s", fn, __getenv(environ, "USER").s, host);
(*fn)();
STRACE("");
STRACE("# tearing down %t", fn);
if (!IsWindows()) sys_getpid();
if (_weaken(TearDown)) _weaken(TearDown)();
if (_weaken(testlib_enable_tmp_setup_teardown)) TearDownTmpDir();
}
if (_weaken(TearDownOnce)) {
_weaken(TearDownOnce)();
}
if (_weaken(testlib_enable_tmp_setup_teardown_once)) {
TearDownTmpDir();
if (_weaken(TearDown)) {
_weaken(TearDown)();
}
for (e = dll_last(testlib_aspects); e; e = dll_prev(testlib_aspects, e)) {
a = TESTASPECT_CONTAINER(e);
if (!a->once && a->teardown) {
a->teardown(fn);
}
}
}
}

93
libc/testlib/tmptest.c Normal file
View file

@ -0,0 +1,93 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2023 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/dll.h"
#include "libc/limits.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/testlib/aspect.internal.h"
#include "libc/testlib/testlib.h"
#include "libc/x/x.h"
static struct {
bool is_aspected;
struct TestAspect aspect;
char olddir[PATH_MAX];
char tmpdir[PATH_MAX];
} g_tmptest;
static void SetupTmpDir(const testfn_t *fn) {
char number[21];
FormatInt64(number, _rand64() & INT64_MAX);
g_tmptest.tmpdir[0] = 0;
if (*__get_tmpdir() != '/') {
strlcat(g_tmptest.tmpdir, g_tmptest.olddir, sizeof(g_tmptest.tmpdir));
strlcat(g_tmptest.tmpdir, "/", sizeof(g_tmptest.tmpdir));
}
strlcat(g_tmptest.tmpdir, __get_tmpdir(), sizeof(g_tmptest.tmpdir));
strlcat(g_tmptest.tmpdir, program_invocation_short_name,
sizeof(g_tmptest.tmpdir));
strlcat(g_tmptest.tmpdir, ".", sizeof(g_tmptest.tmpdir));
strlcat(g_tmptest.tmpdir, number, sizeof(g_tmptest.tmpdir));
if (makedirs(g_tmptest.tmpdir, 0755) || chdir(g_tmptest.tmpdir)) {
perror(g_tmptest.tmpdir);
tinyprint(2, "testlib failed to setup tmpdir\n", NULL);
exit(1);
}
}
static void TearDownTmpDir(const testfn_t *fn) {
if (chdir(g_tmptest.olddir)) {
perror(g_tmptest.olddir);
exit(1);
}
if (rmrf(g_tmptest.tmpdir)) {
perror(g_tmptest.tmpdir);
tinyprint(2, "testlib failed to tear down tmpdir\n", NULL);
exit(1);
}
}
static void InstallAspect(void) {
unassert(!g_tmptest.is_aspected);
g_tmptest.is_aspected = true;
g_tmptest.aspect.teardown = TearDownTmpDir;
dll_init(&g_tmptest.aspect.elem);
dll_make_last(&testlib_aspects, &g_tmptest.aspect.elem);
if (!getcwd(g_tmptest.olddir, sizeof(g_tmptest.olddir))) {
perror("getcwd");
exit(1);
}
}
void testlib_enable_tmp_setup_teardown(void) {
g_tmptest.aspect.setup = SetupTmpDir;
InstallAspect();
}
void testlib_enable_tmp_setup_teardown_once(void) {
g_tmptest.aspect.once = true;
InstallAspect();
SetupTmpDir(0);
}

View file

@ -18,7 +18,8 @@
*/
#include "libc/calls/calls.h"
#include "libc/testlib/ezbench.h"
#include "libc/thread/thread.h"
void __testlib_yield(void) {
sched_yield();
pthread_yield();
}