path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/test/libc/thread/spawn_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/intrin/atomic.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "libc/runtime/internal.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" atomic_int itworked; _Thread_local int var; void SetUpOnce(void) { __enable_threads(); ASSERT_SYS(0, 0, pledge("stdio", 0)); } int Worker(void *arg, int tid) { int i = (long)arg; ASSERT_EQ(0, var++); ASSERT_EQ(gettid(), tid); ASSERT_EQ(1, var++); ASSERT_EQ(sys_gettid(), tid); ASSERT_EQ(2, var++); itworked++; return 0; } TEST(_spawn, test) { long i, n = 128; struct spawn *t = gc(malloc(sizeof(struct spawn) * n)); for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, _spawn(Worker, (void *)i, t + i)); for (i = 0; i < n; ++i) EXPECT_SYS(0, 0, _join(t + i)); for (i = 0; i < n; ++i) EXPECT_SYS(0, 0, _join(t + i)); EXPECT_EQ(n, itworked); }
2,854
58
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_detach_test.c
/*-*- 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 2022 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/strace.internal.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "third_party/nsync/dll.h" void OnUsr1(int sig, struct siginfo *si, void *vctx) { struct ucontext *ctx = vctx; } void SetUp(void) { struct sigaction sig = {.sa_sigaction = OnUsr1, .sa_flags = SA_SIGINFO}; sigaction(SIGUSR1, &sig, 0); } void TriggerSignal(void) { sched_yield(); raise(SIGUSR1); sched_yield(); } static void *Increment(void *arg) { ASSERT_EQ(gettid(), pthread_getthreadid_np()); TriggerSignal(); return (void *)((uintptr_t)arg + 1); } TEST(pthread_detach, testCreateReturn) { pthread_t id; ASSERT_EQ(0, pthread_create(&id, 0, Increment, 0)); ASSERT_EQ(0, pthread_detach(id)); while (!pthread_orphan_np()) { pthread_decimate_np(); } } TEST(pthread_detach, testDetachUponCreation) { pthread_t th; pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); ASSERT_EQ(0, pthread_create(&th, &attr, Increment, 0)); ASSERT_EQ(0, pthread_attr_destroy(&attr)); while (!pthread_orphan_np()) { pthread_decimate_np(); } }
3,220
71
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_cancel_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/calls/blocksigs.internal.h" #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/runtime/runtime.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "libc/thread/thread2.h" #ifdef __x86_64__ int pfds[2]; pthread_cond_t cv; pthread_mutex_t mu; atomic_int gotcleanup; char testlib_enable_tmp_setup_teardown; void SetUp(void) { gotcleanup = false; } void OnCleanup(void *arg) { gotcleanup = true; } void *CancelSelfWorkerDeferred(void *arg) { char buf[8]; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0); pthread_cleanup_push(OnCleanup, 0); pthread_cancel(pthread_self()); read(pfds[0], buf, sizeof(buf)); pthread_cleanup_pop(0); return 0; } TEST(pthread_cancel, self_deferred_waitsForCancellationPoint) { void *rc; pthread_t th; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, CancelSelfWorkerDeferred, 0)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_TRUE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } void *Worker(void *arg) { int n; char buf[8]; pthread_cleanup_push(OnCleanup, 0); read(pfds[0], buf, sizeof(buf)); pthread_cleanup_pop(0); return 0; } TEST(pthread_cancel, synchronous) { void *rc; pthread_t th; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, Worker, 0)); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_TRUE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } TEST(pthread_cancel, synchronous_delayed) { void *rc; pthread_t th; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, Worker, 0)); usleep(10); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_TRUE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } void *DisabledWorker(void *arg) { char buf[8]; pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0); pthread_cleanup_push(OnCleanup, 0); ASSERT_SYS(ECANCELED, -1, read(pfds[0], buf, sizeof(buf))); pthread_cleanup_pop(0); return 0; } TEST(pthread_cancel, masked) { void *rc; pthread_t th; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, DisabledWorker, 0)); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(0, rc); ASSERT_FALSE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } TEST(pthread_cancel, masked_delayed) { void *rc; pthread_t th; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, DisabledWorker, 0)); usleep(10); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(0, rc); ASSERT_FALSE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } void *CondWaitMaskedWorker(void *arg) { pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0); ASSERT_EQ(0, pthread_mutex_lock(&mu)); ASSERT_EQ(ECANCELED, pthread_cond_timedwait(&cv, &mu, 0)); ASSERT_EQ(0, pthread_mutex_unlock(&mu)); return 0; } TEST(pthread_cancel, condMaskedWait) { void *rc; pthread_t th; ASSERT_EQ(0, pthread_create(&th, 0, CondWaitMaskedWorker, 0)); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(0, rc); } TEST(pthread_cancel, condWaitMaskedDelayed) { void *rc; pthread_t th; ASSERT_EQ(0, pthread_create(&th, 0, CondWaitMaskedWorker, 0)); usleep(10); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(0, rc); } void *CondWaitDeferredWorker(void *arg) { pthread_setcancelstate(PTHREAD_CANCEL_DEFERRED, 0); ASSERT_EQ(0, pthread_mutex_lock(&mu)); ASSERT_EQ(ECANCELED, pthread_cond_timedwait(&cv, &mu, 0)); ASSERT_EQ(0, pthread_mutex_unlock(&mu)); return 0; } TEST(pthread_cancel, condDeferredWait) { void *rc; pthread_t th; ASSERT_EQ(0, pthread_create(&th, 0, CondWaitDeferredWorker, 0)); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_EQ(0, pthread_mutex_trylock(&mu)); ASSERT_EQ(0, pthread_mutex_unlock(&mu)); } TEST(pthread_cancel, condDeferredWaitDelayed) { void *rc; pthread_t th; ASSERT_EQ(0, pthread_create(&th, 0, CondWaitDeferredWorker, 0)); usleep(10); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_EQ(0, pthread_mutex_trylock(&mu)); ASSERT_EQ(0, pthread_mutex_unlock(&mu)); } char *wouldleak; pthread_key_t key; bool key_destructor_was_run; atomic_int is_in_infinite_loop; void KeyDestructor(void *arg) { CheckStackIsAligned(); ASSERT_EQ(31337, (intptr_t)arg); key_destructor_was_run = true; } #ifdef __x86_64__ void TortureStack(void) { asm("sub\t$4,%rsp\n\t" "pause\n\t" "sub\t$2,%rsp\n\t" "pause\n\t" "add\t$6,%rsp"); } #endif void *CpuBoundWorker(void *arg) { char *volatile wontleak1; char *volatile wontleak2; CheckStackIsAligned(); wouldleak = malloc(123); wontleak1 = malloc(123); pthread_cleanup_push(free, wontleak1); wontleak2 = _gc(malloc(123)); ASSERT_EQ(0, pthread_setspecific(key, (void *)31337)); ASSERT_EQ(0, pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0)); #ifdef __x86_64__ for (;;) { TortureStack(); is_in_infinite_loop = true; } #endif pthread_cleanup_pop(1); free(wouldleak); return 0; } TEST(pthread_cancel, async) { void *rc; pthread_t th; ASSERT_EQ(0, pthread_key_create(&key, KeyDestructor)); if (IsWindows()) { // asynchronous cancellations aren't possible on windows yet ASSERT_EQ(ENOTSUP, pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0)); return; } wouldleak = NULL; is_in_infinite_loop = false; key_destructor_was_run = false; ASSERT_EQ(0, pthread_create(&th, 0, CpuBoundWorker, 0)); while (!is_in_infinite_loop) pthread_yield(); ASSERT_EQ(0, pthread_cancel(th)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_TRUE(key_destructor_was_run); ASSERT_EQ(0, pthread_key_delete(key)); free(wouldleak); } void *CancelSelfWorkerAsync(void *arg) { char buf[8]; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_cleanup_push(OnCleanup, 0); pthread_cancel(pthread_self()); pthread_cleanup_pop(0); return 0; } TEST(pthread_cancel, self_asynchronous_takesImmediateEffect) { void *rc; pthread_t th; if (IsWindows()) return; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_EQ(0, pthread_create(&th, 0, CancelSelfWorkerAsync, 0)); ASSERT_EQ(0, pthread_join(th, &rc)); ASSERT_EQ(PTHREAD_CANCELED, rc); ASSERT_TRUE(gotcleanup); ASSERT_SYS(0, 0, close(pfds[1])); ASSERT_SYS(0, 0, close(pfds[0])); } #endif /* __x86_64__ */
8,863
286
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_rwlock_rdlock_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #define ITERATIONS 50000 #define READERS 8 #define WRITERS 2 atomic_int reads; atomic_int writes; pthread_rwlock_t lock; pthread_barrier_t barrier; int Reader(void *arg, int tid) { pthread_barrier_wait(&barrier); for (int i = 0; i < ITERATIONS; ++i) { ASSERT_EQ(0, pthread_rwlock_rdlock(&lock)); ++reads; ASSERT_EQ(0, pthread_rwlock_unlock(&lock)); } return 0; } int Writer(void *arg, int tid) { pthread_barrier_wait(&barrier); for (int i = 0; i < ITERATIONS; ++i) { ASSERT_EQ(0, pthread_rwlock_wrlock(&lock)); ++writes; ASSERT_EQ(0, pthread_rwlock_unlock(&lock)); } return 0; } TEST(pthread_rwlock_rdlock, test) { int i; struct spawn *t = _gc(malloc(sizeof(struct spawn) * (READERS + WRITERS))); ASSERT_EQ(0, pthread_barrier_init(&barrier, 0, READERS + WRITERS)); for (i = 0; i < READERS + WRITERS; ++i) { ASSERT_SYS(0, 0, _spawn(i < READERS ? Reader : Writer, 0, t + i)); } for (i = 0; i < READERS + WRITERS; ++i) { EXPECT_SYS(0, 0, _join(t + i)); } EXPECT_EQ(READERS * ITERATIONS, reads); EXPECT_EQ(WRITERS * ITERATIONS, writes); ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); }
3,172
69
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_barrier_wait_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/errno.h" #include "libc/intrin/atomic.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" int i, n; atomic_int p, w; pthread_barrier_t barrier; int Worker(void *arg, int tid) { int rc; rc = pthread_barrier_wait(&barrier); atomic_fetch_add(&w, 1); ASSERT_GE(rc, 0); if (rc == PTHREAD_BARRIER_SERIAL_THREAD) { atomic_fetch_add(&p, 1); } return 0; } TEST(pthread_barrier_init, test0_isInvalid) { __assert_disable = true; ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, 0, 0)); __assert_disable = false; } TEST(pthread_barrier_wait, test1) { struct spawn t; p = 0; w = 0; n = 1; ASSERT_EQ(0, pthread_barrier_init(&barrier, 0, n)); ASSERT_SYS(0, 0, _spawn(Worker, 0, &t)); EXPECT_SYS(0, 0, _join(&t)); ASSERT_EQ(1, p); ASSERT_EQ(n, w); ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); } TEST(pthread_barrier_wait, test32) { struct spawn *t; p = 0; w = 0; n = 32; t = gc(malloc(sizeof(struct spawn) * n)); ASSERT_EQ(0, pthread_barrier_init(&barrier, 0, n)); for (i = 0; i < n; ++i) { ASSERT_EQ(0, w); ASSERT_SYS(0, 0, _spawn(Worker, 0, t + i)); } for (i = 0; i < n; ++i) { EXPECT_SYS(0, 0, _join(t + i)); } ASSERT_EQ(1, p); ASSERT_EQ(n, w); ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); }
3,283
81
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_kill_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" int fds[2]; _Thread_local sig_atomic_t gotsig; void SetUp(void) { if (IsXnuSilicon()) { fprintf(stderr, "TODO(jart): Get pthread_kill() working on XNU silicon\n"); exit(0); } } void OnSig(int sig) { gotsig = 1; } void *ReadWorker(void *arg) { char buf[8]; ASSERT_SYS(EINTR, -1, read(fds[0], buf, 8)); ASSERT_TRUE(gotsig); return 0; } TEST(pthread_kill, canCancelReadOperation) { pthread_t t; struct sigaction oldsa; struct sigaction sa = {.sa_handler = OnSig}; ASSERT_SYS(0, 0, sigaction(SIGUSR1, &sa, &oldsa)); ASSERT_SYS(0, 0, pipe(fds)); ASSERT_EQ(0, pthread_create(&t, 0, ReadWorker, 0)); ASSERT_SYS(0, 0, usleep(100000)); // potentially flaky ASSERT_EQ(0, pthread_kill(t, SIGUSR1)); ASSERT_EQ(0, pthread_join(t, 0)); ASSERT_FALSE(gotsig); ASSERT_SYS(0, 0, close(fds[0])); ASSERT_SYS(0, 0, close(fds[1])); ASSERT_SYS(0, 0, sigaction(SIGUSR1, &oldsa, 0)); }
3,032
65
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/sem_timedwait_test.c
/*-*- 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 2022 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/timespec.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/semaphore.h" #include "libc/thread/thread.h" void IgnoreStderr(void) { close(2); open("/dev/null", O_WRONLY); } TEST(sem_init, einval) { sem_t sem; ASSERT_SYS(EINVAL, -1, sem_init(&sem, 0, -1)); } TEST(sem_post, afterDestroyed_isUndefinedBehavior) { if (!IsModeDbg()) return; int val; sem_t sem; SPAWN(fork); ASSERT_SYS(0, 0, sem_init(&sem, 0, 0)); ASSERT_SYS(0, 0, sem_destroy(&sem)); IgnoreStderr(); sem_post(&sem); EXITS(77); } TEST(sem_trywait, afterDestroyed_isUndefinedBehavior) { if (!IsModeDbg()) return; int val; sem_t sem; SPAWN(fork); ASSERT_SYS(0, 0, sem_init(&sem, 0, 0)); ASSERT_SYS(0, 0, sem_destroy(&sem)); IgnoreStderr(); sem_trywait(&sem); EXITS(77); } TEST(sem_wait, afterDestroyed_isUndefinedBehavior) { if (!IsModeDbg()) return; int val; sem_t sem; SPAWN(fork); ASSERT_SYS(0, 0, sem_init(&sem, 0, 0)); ASSERT_SYS(0, 0, sem_destroy(&sem)); IgnoreStderr(); sem_wait(&sem); EXITS(77); } TEST(sem_timedwait, afterDestroyed_isUndefinedBehavior) { if (!IsModeDbg()) return; int val; sem_t sem; SPAWN(fork); ASSERT_SYS(0, 0, sem_init(&sem, 0, 0)); ASSERT_SYS(0, 0, sem_destroy(&sem)); IgnoreStderr(); sem_timedwait(&sem, 0); EXITS(77); } void *Worker(void *arg) { int rc; sem_t **s = arg; struct timespec ts; ASSERT_SYS(0, 0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; ASSERT_SYS(0, 0, sem_post(s[0])); ASSERT_SYS(0, 0, sem_timedwait(s[1], &ts)); return 0; } TEST(sem_timedwait, threads) { int i, r, n = 4; sem_t sm[2], *s[2] = {sm, sm + 1}; pthread_t *t = _gc(malloc(sizeof(pthread_t) * n)); ASSERT_SYS(0, 0, sem_init(s[0], 0, 0)); ASSERT_SYS(0, 0, sem_init(s[1], 0, 0)); for (i = 0; i < n; ++i) ASSERT_EQ(0, pthread_create(t + i, 0, Worker, s)); for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, sem_wait(s[0])); ASSERT_SYS(0, 0, sem_getvalue(s[0], &r)); ASSERT_EQ(0, r); for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, sem_post(s[1])); for (i = 0; i < n; ++i) ASSERT_EQ(0, pthread_join(t[i], 0)); ASSERT_SYS(0, 0, sem_getvalue(s[1], &r)); ASSERT_EQ(0, r); ASSERT_SYS(0, 0, sem_destroy(s[1])); ASSERT_SYS(0, 0, sem_destroy(s[0])); } TEST(sem_timedwait, processes) { int i, r, rc, n = 4, pshared = 1; sem_t *sm = _mapshared(FRAMESIZE), *s[2] = {sm, sm + 1}; ASSERT_SYS(0, 0, sem_init(s[0], pshared, 0)); ASSERT_SYS(0, 0, sem_init(s[1], pshared, 0)); for (i = 0; i < n; ++i) { ASSERT_NE(-1, (rc = fork())); if (!rc) Worker(s), _Exit(0); } for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, sem_wait(s[0])); ASSERT_SYS(0, 0, sem_getvalue(s[0], &r)); ASSERT_EQ(0, r); for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, sem_post(s[1])); for (;;) { int ws, pid, e = errno; if ((pid = waitpid(0, &ws, 0)) != -1) { if (WIFSIGNALED(ws)) { kprintf("process %d terminated with %G\n", pid, WTERMSIG(ws)); testlib_incrementfailed(); } else if (WEXITSTATUS(ws)) { kprintf("process %d exited with %d\n", pid, WEXITSTATUS(ws)); testlib_incrementfailed(); } } else { ASSERT_EQ(ECHILD, errno); errno = e; break; } } ASSERT_SYS(0, 0, sem_getvalue(s[1], &r)); ASSERT_EQ(0, r); ASSERT_SYS(0, 0, sem_destroy(s[1])); ASSERT_SYS(0, 0, sem_destroy(s[0])); ASSERT_SYS(0, 0, munmap(sm, FRAMESIZE)); }
5,590
157
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/test.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += TEST_LIBC_THREAD TEST_LIBC_THREAD_SRCS := $(wildcard test/libc/thread/*.c) TEST_LIBC_THREAD_SRCS_TEST = $(filter %_test.c,$(TEST_LIBC_THREAD_SRCS)) TEST_LIBC_THREAD_OBJS = \ $(TEST_LIBC_THREAD_SRCS:%.c=o/$(MODE)/%.o) TEST_LIBC_THREAD_COMS = \ $(TEST_LIBC_THREAD_SRCS:%.c=o/$(MODE)/%.com) TEST_LIBC_THREAD_BINS = \ $(TEST_LIBC_THREAD_COMS) \ $(TEST_LIBC_THREAD_COMS:%=%.dbg) TEST_LIBC_THREAD_TESTS = \ $(TEST_LIBC_THREAD_SRCS_TEST:%.c=o/$(MODE)/%.com.ok) TEST_LIBC_THREAD_CHECKS = \ $(TEST_LIBC_THREAD_SRCS_TEST:%.c=o/$(MODE)/%.com.runs) TEST_LIBC_THREAD_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_TESTLIB \ LIBC_THREAD \ LIBC_TIME \ THIRD_PARTY_NSYNC \ THIRD_PARTY_NSYNC_MEM TEST_LIBC_THREAD_DEPS := \ $(call uniq,$(foreach x,$(TEST_LIBC_THREAD_DIRECTDEPS),$($(x)))) o/$(MODE)/test/libc/thread/thread.pkg: \ $(TEST_LIBC_THREAD_OBJS) \ $(foreach x,$(TEST_LIBC_THREAD_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/test/libc/thread/%.com.dbg: \ $(TEST_LIBC_THREAD_DEPS) \ o/$(MODE)/test/libc/thread/%.o \ o/$(MODE)/test/libc/thread/thread.pkg \ $(LIBC_TESTMAIN) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/test/libc/thread/pthread_create_test.o: \ private OVERRIDE_CPPFLAGS += \ -DSTACK_FRAME_UNLIMITED .PHONY: o/$(MODE)/test/libc/thread o/$(MODE)/test/libc/thread: \ $(TEST_LIBC_THREAD_BINS) \ $(TEST_LIBC_THREAD_CHECKS)
1,796
66
jart/cosmopolitan
false
cosmopolitan/test/libc/thread/pthread_exit_test.c
/*-*- 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 2022 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/runtime/runtime.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #define MAIN 150 #define CHILD 170 pthread_t main_thread; _Thread_local static int exit_code; void OnExit(void) { _Exit(exit_code); } void *Worker(void *arg) { ASSERT_EQ(0, pthread_join(main_thread, 0)); exit_code = CHILD; pthread_exit(0); } TEST(pthread_exit, joinableOrphanedChild_runsAtexitHandlers) { pthread_t th; pthread_attr_t attr; SPAWN(fork); atexit(OnExit); exit_code = MAIN; main_thread = pthread_self(); ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); ASSERT_EQ(0, pthread_create(&th, &attr, Worker, 0)); ASSERT_EQ(0, pthread_attr_destroy(&attr)); pthread_exit(0); EXITS(CHILD); } TEST(pthread_exit, detachedOrphanedChild_runsAtexitHandlers) { pthread_t th; pthread_attr_t attr; SPAWN(fork); atexit(OnExit); exit_code = MAIN; main_thread = pthread_self(); ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); ASSERT_EQ(0, pthread_create(&th, &attr, Worker, 0)); ASSERT_EQ(0, pthread_attr_destroy(&attr)); pthread_exit(0); EXITS(CHILD); }
3,116
69
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/access_test.c
/*-*- 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/calls/calls.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/mem/alloca.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/ok.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(access, efault) { ASSERT_SYS(EFAULT, -1, access(0, F_OK)); if (IsWindows() || !IsAsan()) return; // not possible ASSERT_SYS(EFAULT, -1, access((void *)77, F_OK)); } TEST(access, enoent) { ASSERT_SYS(ENOENT, -1, access("", F_OK)); ASSERT_SYS(ENOENT, -1, access("doesnotexist", F_OK)); ASSERT_SYS(ENOENT, -1, access("o/doesnotexist", F_OK)); } TEST(access, enotdir) { ASSERT_SYS(0, 0, touch("o", 0644)); ASSERT_SYS(ENOTDIR, -1, access("o/doesnotexist", F_OK)); } TEST(access, test) { ASSERT_SYS(0, 0, close(creat("file", 0644))); ASSERT_SYS(0, 0, access("file", F_OK)); ASSERT_SYS(ENOENT, -1, access("dir", F_OK)); ASSERT_SYS(ENOTDIR, -1, access("file/dir", F_OK)); ASSERT_SYS(0, 0, mkdir("dir", 0755)); ASSERT_SYS(0, 0, access("dir", F_OK)); ASSERT_SYS(0, 0, access("dir", W_OK)); ASSERT_SYS(0, 0, access("file", W_OK)); } TEST(access, testRequestWriteOnReadOnly_returnsEaccess) { return; /* TODO(jart): maybe we need root to help? */ int fd; ASSERT_SYS(ENOENT, -1, access("file", F_OK)); ASSERT_SYS(0, 0, close(creat("file", 0444))); ASSERT_SYS(0, 0, access("file", F_OK)); ASSERT_SYS(0, 0, access("file", F_OK)); ASSERT_SYS(EACCES, -1, access("file", W_OK)); ASSERT_SYS(EACCES, -1, access("file", W_OK | R_OK)); ASSERT_SYS(0, 0, mkdir("dir", 0555)); ASSERT_SYS(0, 0, access("dir", F_OK)); ASSERT_SYS(EACCES, -1, access("dir", W_OK)); } TEST(access, runThisExecutable) { ASSERT_SYS(0, 0, access(GetProgramExecutableName(), R_OK | X_OK)); }
3,798
82
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/raise_test.c
/*-*- 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 2022 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/calls/struct/siginfo.h" #include "libc/dce.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" //////////////////////////////////////////////////////////////////////////////// // SIGTRAP TEST(raise, trap_sysv) { if (IsWindows()) return; signal(SIGTRAP, SIG_DFL); SPAWN(fork); raise(SIGTRAP); TERMS(SIGTRAP); } TEST(raise, trap_windows) { if (!IsWindows()) return; signal(SIGTRAP, SIG_DFL); SPAWN(fork); raise(SIGTRAP); EXITS(128 + SIGTRAP); } //////////////////////////////////////////////////////////////////////////////// // SIGFPE TEST(raise, fpe_sysv) { if (IsWindows()) return; signal(SIGFPE, SIG_DFL); SPAWN(fork); raise(SIGFPE); TERMS(SIGFPE); } TEST(raise, fpe_windows) { if (!IsWindows()) return; signal(SIGFPE, SIG_DFL); SPAWN(fork); raise(SIGFPE); EXITS(128 + SIGFPE); } //////////////////////////////////////////////////////////////////////////////// // SIGUSR1 TEST(raise, usr1_sysv) { if (IsWindows()) return; SPAWN(fork); raise(SIGUSR1); TERMS(SIGUSR1); } TEST(raise, usr1_windows) { if (!IsWindows()) return; SPAWN(fork); raise(SIGUSR1); EXITS(128 + SIGUSR1); } //////////////////////////////////////////////////////////////////////////////// // THREADS int threadid; void WorkerQuit(int sig, siginfo_t *si, void *ctx) { ASSERT_EQ(SIGILL, sig); if (!IsXnu() && !IsOpenbsd()) { ASSERT_EQ(SI_TKILL, si->si_code); } ASSERT_EQ(threadid, gettid()); } int Worker(void *arg, int tid) { struct sigaction sa = {.sa_sigaction = WorkerQuit, .sa_flags = SA_SIGINFO}; ASSERT_EQ(0, sigaction(SIGILL, &sa, 0)); threadid = tid; ASSERT_EQ(0, raise(SIGILL)); return 0; } TEST(raise, threaded) { signal(SIGILL, SIG_DFL); struct spawn worker; ASSERT_SYS(0, 0, _spawn(Worker, 0, &worker)); ASSERT_SYS(0, 0, _join(&worker)); }
3,934
113
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/writev_test.c
/*-*- 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/iovec.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/limits.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/iov.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(writev, negativeFd_ebadf) { ASSERT_SYS(EBADF, -1, writev(-1, 0, 0)); } TEST(writev, negativeCount_einval) { ASSERT_SYS(EINVAL, -1, writev(1, 0, -1)); } TEST(writev, negative_einvalOrEfault) { struct iovec v[] = {{"", -1}}; ASSERT_EQ(-1, writev(1, v, 1)); ASSERT_TRUE(errno == EINVAL || errno == EFAULT); errno = 0; } TEST(writev, exceedsIovMax_einval) { if (IsWindows()) return; // it's complicated int i, n = IOV_MAX + 1; struct iovec *v = _gc(malloc(sizeof(struct iovec) * n)); for (i = 0; i < n; ++i) { v[i].iov_base = "x"; v[i].iov_len = 1; } ASSERT_SYS(EINVAL, -1, writev(1, v, n)); } TEST(writev, test) { int fd; char ba[1] = "a"; char bb[1] = "b"; char bc[2] = "cd"; struct iovec iov[] = {{"", 0}, {ba, 1}, {NULL, 0}, {bb, 1}, {bc, 2}}; ASSERT_NE(-1, (fd = open("file", O_RDWR | O_CREAT | O_TRUNC, 0644))); EXPECT_EQ(4, writev(fd, iov, ARRAYLEN(iov))); EXPECT_EQ(1, lseek(fd, 1, SEEK_SET)); EXPECT_EQ(3, readv(fd, iov, ARRAYLEN(iov))); EXPECT_EQ('b', ba[0]); EXPECT_EQ('c', bb[0]); EXPECT_EQ('d', bc[0]); EXPECT_NE(-1, close(fd)); } TEST(writev, big_fullCompletion) { int fd; char *ba = gc(malloc(1024 * 1024)); char *bb = gc(malloc(1024 * 1024)); char *bc = gc(malloc(1024 * 1024)); struct iovec iov[] = { {"", 0}, // {ba, 1024 * 1024}, // {NULL, 0}, // {bb, 1024 * 1024}, // {bc, 1024 * 1024}, // }; ASSERT_NE(-1, (fd = open("file", O_RDWR | O_CREAT | O_TRUNC, 0644))); EXPECT_EQ(3 * 1024 * 1024, writev(fd, iov, ARRAYLEN(iov))); EXPECT_NE(-1, close(fd)); } TEST(writev, asanError_efaults) { if (!IsAsan()) return; void *malloc_(size_t) asm("malloc"); void free_(void *) asm("free"); void *p; int fd; p = malloc_(32); EXPECT_NE(-1, (fd = open("asan", O_RDWR | O_CREAT | O_TRUNC, 0644))); EXPECT_EQ(32, write(fd, p, 32)); EXPECT_NE(-1, lseek(fd, 0, SEEK_SET)); EXPECT_EQ(32, read(fd, p, 32)); EXPECT_EQ(-1, write(fd, p, 33)); EXPECT_EQ(EFAULT, errno); EXPECT_EQ(-1, write(fd, p, -1)); EXPECT_EQ(EFAULT, errno); free_(p); EXPECT_EQ(-1, write(fd, p, 32)); EXPECT_EQ(EFAULT, errno); EXPECT_EQ(-1, read(fd, p, 32)); EXPECT_EQ(EFAULT, errno); close(fd); } TEST(writev, empty_stillPerformsIoOperation) { int fd; struct iovec iov[] = {{"", 0}, {NULL, 0}}; ASSERT_NE(-1, touch("file", 0644)); ASSERT_NE(-1, (fd = open("file", O_RDONLY))); errno = 0; EXPECT_SYS(EBADF, -1, writev(fd, iov, ARRAYLEN(iov))); #ifndef __aarch64__ // Can't test this due to qemu-aarch64 bug EXPECT_EQ(-1, writev(fd, NULL, 0)); #endif EXPECT_NE(-1, close(fd)); }
5,061
136
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/ftruncate_test.c
/*-*- 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/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/stat.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/safemacros.internal.h" #include "libc/limits.h" #include "libc/mem/gc.internal.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" struct stat st; char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath", 0)); } TEST(ftruncate, ebadf) { ASSERT_SYS(EBADF, -1, ftruncate(-1, 0)); ASSERT_SYS(EBADF, -1, ftruncate(+3, 0)); } TEST(ftruncate, negativeLength_einval) { ASSERT_SYS(0, 3, creat("foo", 0755)); ASSERT_SYS(EINVAL, -1, ftruncate(3, -1)); ASSERT_SYS(0, 0, close(3)); } TEST(ftruncate, doesntHaveWritePermission_einval) { ASSERT_SYS(0, 3, creat("foo", 0755)); ASSERT_SYS(0, 5, write(3, "hello", 5)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("foo", O_RDONLY)); ASSERT_SYS(EINVAL, -1, ftruncate(3, 0)); ASSERT_SYS(0, 0, close(3)); } TEST(ftruncate, pipeFd_einval) { int fds[2]; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(EINVAL, -1, ftruncate(3, 0)); EXPECT_SYS(0, 0, close(4)); EXPECT_SYS(0, 0, close(3)); } TEST(ftruncate, efbig) { // FreeBSD and RHEL7 return 0 (why??) if (IsLinux() || IsFreebsd()) return; sighandler_t old = signal(SIGXFSZ, SIG_IGN); ASSERT_SYS(0, 3, creat("foo", 0755)); ASSERT_SYS(IsWindows() ? EINVAL : EFBIG, -1, ftruncate(3, INT64_MAX)); ASSERT_SYS(0, 0, close(3)); signal(SIGXFSZ, old); } TEST(ftruncate, test) { char got[512], want[512] = "helloworld"; // tests zero-extending ASSERT_SYS(0, 3, open("foo", O_CREAT | O_TRUNC | O_RDWR, 0755)); ASSERT_SYS(0, 5, write(3, "hello", 5)); ASSERT_SYS(0, 0, ftruncate(3, 8192)); ASSERT_SYS(0, 5, lseek(3, 0, SEEK_CUR)); // doesn't change position ASSERT_SYS(0, 5, write(3, "world", 5)); ASSERT_SYS(0, 0, fstat(3, &st)); ASSERT_EQ(8192, st.st_size); #if 0 if (!IsGenuineBlink()) { if (IsWindows() || IsNetbsd() || IsOpenbsd()) { // ASSERT_EQ(8192 / 512, st.st_blocks); // 8192 is physical size } else if (IsFreebsd()) { // ASSERT_EQ(512 / 512, st.st_blocks); // 512 is physical size } else if (IsLinux() || IsXnu()) { // ASSERT_EQ(4096 / 512, st.st_blocks); // 4096 is physical size } else { notpossible; } } #endif ASSERT_SYS(0, 512, pread(3, got, 512, 0)); ASSERT_EQ(0, memcmp(want, got, 512)); ASSERT_SYS(0, 0, ftruncate(3, 0)); // shrink file to be empty ASSERT_SYS(0, 0, pread(3, got, 512, 0)); ASSERT_SYS(0, 0, read(3, got, 512)); ASSERT_SYS(0, 10, lseek(3, 0, SEEK_CUR)); // position stays past eof ASSERT_SYS(0, 0, close(3)); }
4,792
112
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/closefrom_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/f.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" void SetUp(void) { if (closefrom(3) == -1) { if (IsOpenbsd()) { ASSERT_EQ(EBADF, errno); } else { ASSERT_EQ(ENOSYS, errno); exit(0); } } } TEST(closefrom, ebadf) { ASSERT_SYS(EBADF, -1, closefrom(-2)); } TEST(closefrom, test) { ASSERT_SYS(0, 3, dup(2)); ASSERT_SYS(0, 4, dup(2)); ASSERT_SYS(0, 5, dup(2)); ASSERT_SYS(0, 6, dup(2)); EXPECT_SYS(0, 0, closefrom(3)); ASSERT_SYS(0, 0, fcntl(2, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(3, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(4, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(5, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(6, F_GETFD)); } TEST(close_range, test) { if (IsLinux() || IsFreebsd()) { ASSERT_SYS(0, 3, dup(2)); ASSERT_SYS(0, 4, dup(2)); ASSERT_SYS(0, 5, dup(2)); ASSERT_SYS(0, 6, dup(2)); EXPECT_SYS(0, 0, close_range(3, -1, 0)); ASSERT_SYS(0, 0, fcntl(2, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(3, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(4, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(5, F_GETFD)); ASSERT_SYS(EBADF, -1, fcntl(6, F_GETFD)); } else { EXPECT_SYS(ENOSYS, -1, close_range(3, -1, 0)); } } TEST(close_range, ignoresNonexistantRanges) { if (!IsLinux() && !IsFreebsd()) return; EXPECT_SYS(0, 0, close_range(-2, -1, 0)); }
3,333
76
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/getitimer_test.c
/*-*- 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/itimerval.h" #include "libc/errno.h" #include "libc/sysv/consts/itimer.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" TEST(getitimer, testBadParam_returnsEinval) { struct itimerval it; EXPECT_SYS(EINVAL, -1, getitimer(31337, &it)); } TEST(getitimer, noTimer_returnsZeroes) { struct itimerval it; EXPECT_SYS(0, 0, getitimer(ITIMER_REAL, &it)); EXPECT_EQ(0, it.it_interval.tv_sec); EXPECT_EQ(0, it.it_interval.tv_usec); EXPECT_EQ(0, it.it_value.tv_sec); EXPECT_EQ(0, it.it_value.tv_usec); }
2,419
39
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/vfork_test.c
/*-*- 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/internal.h" #include "libc/calls/state.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; TEST(vfork, test) { int fd; char buf[8] = {0}; ASSERT_NE(-1, (fd = open("vfork_test", O_RDWR | O_CREAT, 0644))); ASSERT_EQ(5, write(fd, "hello", 5)); ASSERT_NE(-1, lseek(fd, 0, SEEK_SET)); if (!vfork()) { EXPECT_EQ(5, pread(fd, buf, 5, 0)); ASSERT_NE(-1, lseek(fd, 0, SEEK_SET)); EXPECT_STREQ("hello", buf); EXPECT_NE(-1, close(fd)); _exit(0); } EXPECT_EQ(0, __vforked); EXPECT_NE(-1, wait(0)); EXPECT_EQ(5, read(fd, buf, 5)); EXPECT_STREQ("hello", buf); EXPECT_NE(-1, close(fd)); }
2,607
47
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sched_setscheduler_test.c
/*-*- 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 2022 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/sched_param.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/midpoint.h" #include "libc/limits.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/sched.h" #include "libc/testlib/testlib.h" #define DEFAULT_POLICY SCHED_OTHER void SetUp(void) { if (IsFreebsd() && getuid() != 0) { exit(0); } if (IsXnu() || IsWindows() || IsOpenbsd() || IsWindows()) { exit(0); } int oldpolicy = sched_getscheduler(0); struct sched_param p = {sched_get_priority_min(DEFAULT_POLICY)}; EXPECT_SYS(0, oldpolicy, sched_setscheduler(0, DEFAULT_POLICY, &p)); } bool CanTuneRealtimeSchedulers(void) { int e = errno; int policy = SCHED_FIFO; struct sched_param p = {sched_get_priority_min(policy)}; if (sched_setscheduler(0, policy, &p) != -1) { struct sched_param p = {sched_get_priority_min(DEFAULT_POLICY)}; EXPECT_SYS(0, policy, sched_setscheduler(0, DEFAULT_POLICY, &p)); return true; } else if (errno == EPERM) { errno = e; return false; } else { abort(); } } TEST(sched_getscheduler, einval) { ASSERT_SYS(IsLinux() ? EINVAL : ESRCH, -1, sched_getscheduler(INT_MIN)); } TEST(sched_setscheduler, test) { struct sched_param p = {sched_get_priority_min(SCHED_OTHER)}; EXPECT_SYS(0, DEFAULT_POLICY, sched_setscheduler(0, SCHED_OTHER, &p)); } TEST(sched_setscheduler, testMidpoint) { if (!CanTuneRealtimeSchedulers()) return; struct sched_param p = {_midpoint(sched_get_priority_min(SCHED_FIFO), sched_get_priority_max(SCHED_FIFO))}; EXPECT_SYS(0, DEFAULT_POLICY, sched_setscheduler(0, SCHED_FIFO, &p)); }
3,523
74
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sigpending_test.c
/*-*- 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 2022 Gavin Arthur Hayes │ │ │ │ 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/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/errno.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" static unsigned OnSignalCnt = 0; void OnSignal(int sig, siginfo_t *si, void *ctx) { OnSignalCnt++; EXPECT_EQ(SIGUSR1, sig); } TEST(sigpending, efault) { ASSERT_SYS(EFAULT, -1, sigpending(0)); } TEST(sigpending, test) { sigset_t pending; sigfillset(&pending); EXPECT_EQ(0, sigpending(&pending)); EXPECT_EQ(0, sigcountset(&pending)); struct sigaction sa = {.sa_sigaction = OnSignal, .sa_flags = SA_SIGINFO}; ASSERT_EQ(0, sigaction(SIGUSR1, &sa, NULL)); sigset_t blocked; sigemptyset(&blocked); sigaddset(&blocked, SIGUSR1); ASSERT_EQ(0, sigprocmask(SIG_SETMASK, &blocked, NULL)); ASSERT_EQ(0, raise(SIGUSR1)); sigfillset(&pending); EXPECT_EQ(0, sigpending(&pending)); EXPECT_EQ(1, sigcountset(&pending)); EXPECT_EQ(1, sigismember(&pending, SIGUSR1)); ASSERT_NE(SIG_ERR, signal(SIGUSR1, SIG_IGN)); sigemptyset(&pending); EXPECT_EQ(0, sigpending(&pending)); EXPECT_EQ(0, sigcountset(&pending)); ASSERT_EQ(0, sigaction(SIGUSR1, &sa, NULL)); ASSERT_EQ(0, raise(SIGUSR1)); EXPECT_EQ(0, sigpending(&pending)); EXPECT_EQ(1, sigcountset(&pending)); EXPECT_EQ(1, sigismember(&pending, SIGUSR1)); sigemptyset(&blocked); ASSERT_EQ(0, sigprocmask(SIG_SETMASK, &blocked, NULL)); EXPECT_EQ(0, sigpending(&pending)); EXPECT_EQ(0, sigcountset(&pending)); EXPECT_EQ(1, OnSignalCnt); }
3,447
74
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/zipread.c
/*-*- 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 Gavin Arthur Hayes │ │ │ │ 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/str/str.h" #include "libc/sysv/consts/o.h" STATIC_YOINK("zip_uri_support"); int main(int argc, char *argv[]) { int fd = open("/zip/life.elf", O_RDONLY); if (fd != -1) { uint8_t buf[4] = {0}; ssize_t readres = read(fd, buf, sizeof(buf)); if (readres == sizeof(buf)) { if (memcmp(buf, "\x7F" "ELF", sizeof(buf)) == 0) { return 42; } } close(fd); } return 1; }
2,340
42
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/getpriority_test.c
/*-*- 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 2022 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/sigset.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/prio.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" void SetUp(void) { if (getpriority(PRIO_PROCESS, getpid()) != 0) { kprintf("getpriority_test.com must be launched at priority zero\n"); exit(0); } } TEST(getpriority, badWhich_einval) { ASSERT_SYS(EINVAL, -1, getpriority(-1, 0)); ASSERT_SYS(EINVAL, -1, setpriority(-1, 0, 0)); } TEST(getpriority, lowerPriorityOfSelf) { SPAWN(fork); ASSERT_SYS(0, 0, getpriority(PRIO_PROCESS, 0)); ASSERT_SYS(0, 0, getpriority(PRIO_PROCESS, getpid())); ASSERT_SYS(0, 0, setpriority(PRIO_PROCESS, getpid(), 5)); ASSERT_SYS(0, 5, getpriority(PRIO_PROCESS, getpid())); ASSERT_SYS(0, 5, getpriority(PRIO_PROCESS, 0)); EXITS(0); } TEST(getpriority, higherPriorityOfSelf) { if (IsWindows() || getuid() == 0) { SPAWN(fork); ASSERT_SYS(0, 0, setpriority(PRIO_PROCESS, 0, -5)); ASSERT_SYS(0, -5, getpriority(PRIO_PROCESS, 0)); ASSERT_SYS(0, 0, setpriority(PRIO_PROCESS, 0, 0)); EXITS(0); } } TEST(getpriority, lowerAndRaiseItAgain_notAllowed) { return; // this behavior seems limited to modern linux SPAWN(fork); ASSERT_SYS(0, 0, setpriority(PRIO_PROCESS, 0, 5)); ASSERT_SYS(EACCES, -1, setpriority(PRIO_PROCESS, 0, 4)); EXITS(0); } TEST(getpriority, lowerPriorityOfSubprocess) { int pid, ws; sigset_t ss, oldss; sigemptyset(&ss); sigaddset(&ss, SIGUSR1); ASSERT_SYS(0, 0, sigprocmask(SIG_BLOCK, &ss, &oldss)); ASSERT_NE(-1, (pid = fork())); if (!pid) { sigemptyset(&ss); ASSERT_SYS(EINTR, -1, sigsuspend(&ss)); _Exit(0); } ASSERT_SYS(0, 0, getpriority(PRIO_PROCESS, pid)); ASSERT_SYS(0, 0, setpriority(PRIO_PROCESS, pid, 5)); ASSERT_SYS(0, 5, getpriority(PRIO_PROCESS, pid)); ASSERT_SYS(0, 0, kill(pid, SIGUSR1)); ASSERT_SYS(0, pid, wait(&ws)); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &oldss, 0)); }
3,945
89
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/copy_file_range_test.c
/*-*- 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 2022 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/stat.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/posix.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" char testlib_enable_tmp_setup_teardown; void Make(const char *path, int mode) { int fd, n = lemur64() & 0xfffff; char *data = _gc(malloc(n)); rngset(data, n, lemur64, -1); ASSERT_NE(-1, (fd = creat(path, mode))); ASSERT_SYS(0, n, write(fd, data, n)); ASSERT_SYS(0, 0, close(fd)); } void Copy(const char *from, const char *to) { ssize_t rc; char buf[512]; struct stat st; int fdin, fdout, e = errno; ASSERT_NE(-1, (fdin = open(from, O_RDONLY))); ASSERT_SYS(0, 0, fstat(fdin, &st)); ASSERT_NE(-1, (fdout = creat(to, st.st_mode | 0400))); if (!(IsXnu() || IsOpenbsd())) { ASSERT_SYS(0, 0, posix_fadvise(fdin, 0, st.st_size, POSIX_FADV_SEQUENTIAL)); } ASSERT_SYS(0, 0, ftruncate(fdout, st.st_size)); while ((rc = copy_file_range(fdin, 0, fdout, 0, -1u, 0))) { if (rc == -1) { ASSERT_EQ(ENOSYS, errno); errno = e; while ((rc = read(fdin, buf, sizeof(buf)))) { ASSERT_NE(-1, rc); ASSERT_EQ(rc, write(fdout, buf, rc)); } break; } } ASSERT_SYS(0, 0, close(fdin)); ASSERT_SYS(0, 0, close(fdout)); } TEST(copy_file_range, test) { char *p, *q; size_t n, m; Make("foo", 0644); Copy("foo", "bar"); p = _gc(xslurp("foo", &n)); q = _gc(xslurp("bar", &m)); ASSERT_EQ(n, m); ASSERT_EQ(0, memcmp(p, q, n)); } bool HasCopyFileRange(void) { bool ok; int rc, e; e = errno; rc = copy_file_range(-1, 0, -1, 0, 0, 0); ok = rc == -1 && errno == EBADF; errno = e; return ok; } TEST(copy_file_range, badFd) { if (!HasCopyFileRange()) return; ASSERT_SYS(EBADF, -1, copy_file_range(-1, 0, -1, 0, -1u, 0)); } TEST(copy_file_range, badFlags) { if (!HasCopyFileRange()) return; ASSERT_SYS(EINVAL, -1, copy_file_range(0, 0, 1, 0, -1u, -1)); } TEST(copy_file_range, differentFileSystems) { return; // TODO(jart): Why does this flake on GitHub Actions? if (!IsLinux()) return; if (!HasCopyFileRange()) return; ASSERT_SYS(0, 3, open("/proc/stat", 0)); ASSERT_SYS(0, 4, creat("foo", 0644)); ASSERT_SYS(EXDEV, -1, copy_file_range(3, 0, 4, 0, -1u, 0)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(copy_file_range, twoDifferentFiles) { char buf[16] = {0}; int64_t i = 1, o = 0; if (!HasCopyFileRange()) return; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 4, open("bar", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, pwrite(3, "hello", 5, 0)); ASSERT_SYS(0, 4, copy_file_range(3, &i, 4, &o, 4, 0)); ASSERT_SYS(0, 0, copy_file_range(3, &i, 4, &o, 0, 0)); ASSERT_EQ(5, i); ASSERT_EQ(4, o); ASSERT_SYS(0, 4, read(4, buf, 16)); ASSERT_STREQ("ello", buf); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(copy_file_range, sameFile_doesntChangeFilePointer) { char buf[16] = {0}; int64_t i = 1, o = 5; if (!HasCopyFileRange()) return; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, pwrite(3, "hello", 5, 0)); ASSERT_SYS(0, 4, copy_file_range(3, &i, 3, &o, 4, 0)); ASSERT_EQ(5, i); ASSERT_EQ(9, o); ASSERT_SYS(0, 9, read(3, buf, 16)); ASSERT_STREQ("helloello", buf); ASSERT_SYS(0, 0, close(3)); } TEST(copy_file_range, overlappingRange) { int rc; int64_t i = 1, o = 2; if (!HasCopyFileRange()) return; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, pwrite(3, "hello", 5, 0)); rc = copy_file_range(3, &i, 3, &o, 4, 0); ASSERT_EQ(-1, rc); if (IsLinux()) { // [wut] rhel7 returns enosys here ASSERT_TRUE(errno == EINVAL || errno == ENOSYS); } else { ASSERT_TRUE(errno == EINVAL); } errno = 0; ASSERT_SYS(0, 0, close(3)); }
5,954
163
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/stat_test.c
/*-*- 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/calls/struct/stat.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/metastat.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/mem/gc.internal.h" #include "libc/nt/files.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/nr.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" STATIC_YOINK("zip_uri_support"); char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(stat_010, testEmptyFile_sizeIsZero) { struct stat st; memset(&st, -1, sizeof(st)); ASSERT_SYS(0, 0, close(creat("hi", 0644))); EXPECT_SYS(0, 0, stat("hi", &st)); EXPECT_EQ(0, st.st_size); } TEST(stat, enoent) { ASSERT_SYS(ENOENT, -1, stat("hi", 0)); ASSERT_SYS(ENOENT, -1, stat("o/doesnotexist", 0)); } TEST(stat, enotdir) { ASSERT_SYS(0, 0, close(creat("yo", 0644))); ASSERT_SYS(ENOTDIR, -1, stat("yo/there", 0)); } TEST(stat, zipos) { struct stat st; EXPECT_SYS(0, 0, stat("/zip/.python/test/" "tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", &st)); EXPECT_SYS(0, 0, stat("/zip", &st)); EXPECT_SYS(0, 0, stat("/zip/", &st)); EXPECT_SYS(0, 0, stat("/zip/.python", &st)); EXPECT_SYS(0, 0, stat("/zip/.python/", &st)); } static long Fstatat(const char *path, struct stat *st) { #ifdef __x86_64__ long ax, di, si, dx; register long r10 asm("r10") = 0; asm volatile("syscall" : "=a"(ax), "=D"(di), "=S"(si), "=d"(dx), "+r"(r10) : "0"(__NR_fstatat), "1"(AT_FDCWD), "2"(path), "3"(st) : "rcx", "r8", "r9", "r11", "memory", "cc"); return ax; #elif defined(__aarch64__) register long r0 asm("x0") = (long)AT_FDCWD; register long r1 asm("x1") = (long)path; register long r2 asm("x2") = (long)st; register long r3 asm("x3") = (long)0; register long r8 asm("x8") = (long)__NR_fstatat; register long res_x0 asm("x0"); asm volatile("svc\t0" : "=r"(res_x0) : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r8) : "memory"); return res_x0; #else #error "unsupported architecture" #endif } BENCH(stat, bench) { struct stat st; union metastat ms; EXPECT_SYS(0, 0, makedirs(".python/test", 0755)); EZBENCH2("__stat2cosmo", donothing, __stat2cosmo(&st, &ms)); EXPECT_SYS(0, 0, touch(".python/test/" "tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", 0644)); if (!IsWindows() && !IsFreebsd()) { EZBENCH2("fstatat syscall", donothing, Fstatat(".python/test/" "tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", &st)); } EZBENCH2("stat() fs", donothing, stat(".python/test/" "tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", &st)); EZBENCH2("stat() zipos", donothing, stat("/zip/.python/test/" "tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", &st)); }
5,117
125
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sigsuspend_test.c
/*-*- 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 2022 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/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/x/xspawn.h" volatile bool gotsig1; volatile bool gotsig2; volatile bool finished; void OnSigQueuing(int sig, siginfo_t *si, void *ctx) { if (!finished) { EXPECT_EQ(SIGUSR2, sig); EXPECT_EQ(SIGUSR2, si->si_signo); gotsig2 = true; } else { EXPECT_EQ(SIGUSR1, sig); EXPECT_EQ(SIGUSR1, si->si_signo); gotsig1 = true; } } TEST(sigsuspend, testSignalQueuingSelf) { sigset_t neu, old, bits; struct sigaction oldusr1, oldusr2; struct sigaction sa = {.sa_sigaction = OnSigQueuing, .sa_flags = SA_SIGINFO}; gotsig1 = false; gotsig2 = false; finished = false; sigemptyset(&neu); sigaddset(&neu, SIGUSR1); sigaddset(&neu, SIGUSR2); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &neu, &old)); ASSERT_EQ(0, sigaction(SIGUSR1, &sa, &oldusr1)); ASSERT_EQ(0, sigaction(SIGUSR2, &sa, &oldusr2)); raise(SIGUSR1); raise(SIGUSR2); sigdelset(&neu, SIGUSR2); EXPECT_EQ(false, gotsig2); memcpy(&bits, &neu, sizeof(bits)); ASSERT_EQ(-1, sigsuspend(&neu)); // raises SIGUSR2 EXPECT_EQ(0, memcmp(&bits, &neu, sizeof(bits))); // constness respected EXPECT_EQ(EINTR, errno); EXPECT_EQ(true, gotsig2); EXPECT_EQ(false, gotsig1); finished = true; EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &old, NULL)); // raises SIGUSR1 EXPECT_EQ(true, gotsig1); EXPECT_EQ(0, sigaction(SIGUSR1, &oldusr1, 0)); EXPECT_EQ(0, sigaction(SIGUSR2, &oldusr2, 0)); } TEST(sigsuspend, testSignalQueuingIpc) { if (IsWindows()) { // xxx: probably need a signal server to do this kind of signalling return; } int pid, ws; sigset_t neu, old, bits; struct sigaction oldusr1, oldusr2; struct sigaction sa = {.sa_sigaction = OnSigQueuing, .sa_flags = SA_SIGINFO}; gotsig1 = false; gotsig2 = false; finished = false; sigemptyset(&neu); sigaddset(&neu, SIGUSR1); sigaddset(&neu, SIGUSR2); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &neu, &old)); ASSERT_EQ(0, sigaction(SIGUSR1, &sa, &oldusr1)); ASSERT_EQ(0, sigaction(SIGUSR2, &sa, &oldusr2)); pid = getpid(); ASSERT_NE(-1, (ws = xspawn(0))); if (ws == -2) { kill(pid, SIGUSR1); kill(pid, SIGUSR2); _exit(0); } sigdelset(&neu, SIGUSR2); EXPECT_EQ(false, gotsig2); memcpy(&bits, &neu, sizeof(bits)); ASSERT_EQ(-1, sigsuspend(&neu)); // raises SIGUSR2 EXPECT_EQ(0, memcmp(&bits, &neu, sizeof(bits))); // constness respected EXPECT_EQ(EINTR, errno); EXPECT_EQ(true, gotsig2); EXPECT_EQ(false, gotsig1); finished = true; EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &old, NULL)); // raises SIGUSR1 EXPECT_EQ(true, gotsig1); EXPECT_EQ(0, sigaction(SIGUSR1, &oldusr1, 0)); EXPECT_EQ(0, sigaction(SIGUSR2, &oldusr2, 0)); }
4,889
117
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/mkntcmdline_test.c
/*-*- 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/calls/ntspawn.h" #include "libc/errno.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" char16_t cmdline[ARG_MAX / 2]; TEST(mkntcmdline, emptyArgvList_cantBeEmptyOnWindows) { char *argv[] = {"foo", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"foo", cmdline); } TEST(mkntcmdline, emptyArgvListWithProg_isEmpty) { char *argv[] = {NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"", cmdline); } TEST(mkntcmdline, emptyArg_getsQuoted) { char *argv[] = {"", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"\"\"", cmdline); } TEST(mkntcmdline, ignoranceIsBliss) { char *argv[] = {"echo", "hello", "world", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"echo hello world", cmdline); } TEST(mkntcmdline, spaceInArgument_getQuotesWrappedAround) { char *argv[] = {"echo", "hello there", "world", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"echo \"hello there\" world", cmdline); } TEST(mkntcmdline, justSlash) { char *argv[] = {"\\", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"\\", cmdline); } TEST(mkntcmdline, testUnicode) { char *argv1[] = { gc(strdup("(╯°□°)╯")), gc(strdup("要依法治国是赞美那些谁是公义的和惩罚恶人。 - 韩非")), NULL, }; EXPECT_NE(-1, mkntcmdline(cmdline, argv1)); EXPECT_STREQ(u"(╯°□°)╯ \"要依法治国是赞美那些谁是公义的和惩罚恶人。 - 韩非\"", cmdline); } TEST(mkntcmdline, fixAsBestAsWeCanForNow1) { char *argv1[] = { "/C/WINDOWS/system32/cmd.exe", "/C", "more <\"/C/Users/jart/AppData/Local/Temp/tmplquaa_d6\"", NULL, }; EXPECT_NE(-1, mkntcmdline(cmdline, argv1)); EXPECT_STREQ(u"C:\\WINDOWS\\system32\\cmd.exe /C \"more <" u"\"\"\"C:/Users/jart/AppData/Local/Temp/tmplquaa_d6\"\"\"\"", cmdline); } TEST(mkntcmdline, fixAsBestAsWeCanForNow2) { char *argv1[] = { "/C/WINDOWS/system32/cmd.exe", "/C", "less /C/Users/jart/AppData/Local/Temp/tmplquaa_d6", NULL, }; EXPECT_NE(-1, mkntcmdline(cmdline, argv1)); EXPECT_STREQ(u"C:\\WINDOWS\\system32\\cmd.exe /C \"less " u"C:/Users/jart/AppData/Local/Temp/tmplquaa_d6\"", cmdline); } TEST(mkntcmdline, testWut) { char *argv[] = {"C:\\Users\\jart\\𝑟𝑒𝑑𝑏𝑒𝑎𝑛.com", "--strace", NULL}; EXPECT_NE(-1, mkntcmdline(cmdline, argv)); EXPECT_STREQ(u"C:\\Users\\jart\\𝑟𝑒𝑑𝑏𝑒𝑎𝑛.com --strace", cmdline); }
4,505
106
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/pwrite_test.c
/*-*- 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 2022 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/stat.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char buf[8]; struct stat st; char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(pwrite, testWritePastEof_extendsFile) { EXPECT_SYS(0, 3, creat("foo", 0644)); EXPECT_SYS(0, 8, pwrite(3, buf, 8, 100)); EXPECT_SYS(0, 0, fstat(3, &st)); EXPECT_EQ(108, st.st_size); EXPECT_SYS(0, 0, close(3)); }
2,355
39
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/posix_fadvise_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/limits.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/posix.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUp(void) { if (IsOpenbsd() || IsXnu()) exit(0); } TEST(fadvise, ebadf) { ASSERT_SYS(EBADF, -1, fadvise(-1, 0, 0, MADV_SEQUENTIAL)); } TEST(posix_fadvise, ebadf) { ASSERT_SYS(0, EBADF, posix_fadvise(-1, 0, 0, POSIX_FADV_SEQUENTIAL)); } TEST(fadvise, test) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(0, 0, fadvise(3, 0, 0, MADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(3)); } TEST(posix_fadvise, test) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(0, 0, posix_fadvise(3, 0, 0, POSIX_FADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(3)); } TEST(fadvise, testBadAdvice) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(EINVAL, -1, fadvise(3, 0, 0, 127)); ASSERT_SYS(0, 0, close(3)); } TEST(posix_fadvise, testBadAdvice) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(0, EINVAL, posix_fadvise(3, 0, 0, 127)); ASSERT_SYS(0, 0, close(3)); } TEST(fadvise, testPastEof_isFine) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(0, 0, fadvise(3, 100, 100, MADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(3)); } TEST(fadvise, testNegativeLen_isInvalid) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(EINVAL, -1, fadvise(3, 0, INT64_MIN, MADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(3)); } TEST(posix_fadvise, testNegativeLen_isInvalid) { ASSERT_SYS(0, 0, xbarf("foo", "hello", -1)); ASSERT_SYS(0, 3, open("foo", 0)); ASSERT_SYS(0, EINVAL, posix_fadvise(3, 0, INT64_MIN, POSIX_FADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(3)); } TEST(fadvise, espipe) { int fds[2]; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(ESPIPE, -1, fadvise(3, 0, 0, MADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(posix_fadvise, espipe) { int fds[2]; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, ESPIPE, posix_fadvise(3, 0, 0, POSIX_FADV_SEQUENTIAL)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); }
4,285
107
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/utimensat_test.c
/*-*- 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 2022 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/stat.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timeval.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/utime.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(utimes, test) { struct stat st; struct timeval tv[2] = { {1655455857, 1}, // atim: Fri Jun 17 2022 08:50:57 GMT+0000 {827727928, 2}, // mtim: Mon Mar 25 1996 04:25:28 GMT+0000 }; EXPECT_SYS(0, 0, touch("boop", 0644)); EXPECT_SYS(0, 0, utimes("boop", tv)); EXPECT_SYS(0, 0, stat("boop", &st)); EXPECT_EQ(1655455857, st.st_atim.tv_sec); EXPECT_EQ(827727928, st.st_mtim.tv_sec); if (IsLinux() && !__is_linux_2_6_23()) { // rhel5 only seems to have second granularity EXPECT_EQ(0, st.st_atim.tv_nsec); EXPECT_EQ(0, st.st_mtim.tv_nsec); } else { EXPECT_EQ(1000, st.st_atim.tv_nsec); EXPECT_EQ(2000, st.st_mtim.tv_nsec); } } TEST(futimes, test) { if (IsLinux() && !__is_linux_2_6_23()) return; struct stat st; struct timeval tv[2] = {{1655455857, 1}, {827727928, 2}}; EXPECT_SYS(0, 3, creat("boop", 0644)); EXPECT_SYS(0, 0, futimes(3, tv)); EXPECT_SYS(0, 0, fstat(3, &st)); EXPECT_EQ(1655455857, st.st_atim.tv_sec); EXPECT_EQ(827727928, st.st_mtim.tv_sec); EXPECT_EQ(1000, st.st_atim.tv_nsec); EXPECT_EQ(2000, st.st_mtim.tv_nsec); EXPECT_SYS(0, 0, close(3)); } TEST(futimes, rhel5_enosys) { if (IsLinux() && !__is_linux_2_6_23()) { struct timeval tv[2] = {{1655455857}, {827727928}}; EXPECT_SYS(0, 3, creat("boop", 0644)); EXPECT_SYS(ENOSYS, -1, futimes(3, tv)); EXPECT_SYS(0, 0, close(3)); } } TEST(utimensat, test) { struct stat st; struct timespec ts[2] = { {1655455857}, // atim: Fri Jun 17 2022 08:50:57 GMT+0000 {827727928}, // mtim: Mon Mar 25 1996 04:25:28 GMT+0000 }; EXPECT_SYS(0, 0, touch("boop", 0644)); EXPECT_SYS(0, 0, utimensat(AT_FDCWD, "boop", ts, 0)); EXPECT_SYS(0, 0, stat("boop", &st)); EXPECT_EQ(1655455857, st.st_atim.tv_sec); EXPECT_EQ(827727928, st.st_mtim.tv_sec); } TEST(futimens, test) { if (IsLinux() && !__is_linux_2_6_23()) { // TODO(jart): How does RHEL5 do futimes()? return; } struct stat st; struct timespec ts[2] = { {1655455857}, // atim: Fri Jun 17 2022 08:50:57 GMT+0000 {827727928}, // mtim: Mon Mar 25 1996 04:25:28 GMT+0000 }; EXPECT_SYS(0, 0, touch("boop", 0644)); EXPECT_SYS(0, 3, open("boop", O_RDWR)); EXPECT_SYS(0, 0, futimens(3, ts)); EXPECT_SYS(0, 0, fstat(3, &st)); EXPECT_SYS(0, 0, close(3)); EXPECT_EQ(1655455857, st.st_atim.tv_sec); EXPECT_EQ(827727928, st.st_mtim.tv_sec); } TEST(utimensat, testOmit) { if (IsLinux() && !__is_linux_2_6_23()) { // TODO(jart): Ugh. return; } struct stat st; struct timespec ts[2] = { {123, UTIME_OMIT}, {123, UTIME_OMIT}, }; EXPECT_SYS(0, 0, touch("boop", 0644)); EXPECT_SYS(0, 0, utimensat(AT_FDCWD, "boop", ts, 0)); EXPECT_SYS(0, 0, stat("boop", &st)); EXPECT_NE(123, st.st_atim.tv_sec); EXPECT_NE(123, st.st_mtim.tv_sec); }
5,209
130
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/lseek_test.c
/*-*- 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/internal.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr proc", 0)); } TEST(lseek, ebadf) { ASSERT_SYS(EBADF, -1, lseek(-1, 0, SEEK_SET)); ASSERT_SYS(EBADF, -1, lseek(+3, 0, SEEK_SET)); } TEST(lseek, badWhence_einval) { ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_SYS(EINVAL, -1, lseek(3, 0, -1)); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, negativeComputedOffset_einval) { ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_SYS(EINVAL, -1, lseek(3, -1, SEEK_SET)); ASSERT_SYS(EINVAL, -1, lseek(3, -1, SEEK_CUR)); ASSERT_SYS(EINVAL, -1, lseek(3, -1, SEEK_END)); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, 64bit) { ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_SYS(0, 0x100000001, lseek(3, 0x100000001, SEEK_SET)); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, nonSeekableFd_espipe) { int fds[2]; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(ESPIPE, -1, lseek(3, 0, SEEK_SET)); EXPECT_SYS(0, 0, close(4)); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, filePositionChanges_areObservableAcrossDup) { ASSERT_SYS(0, 3, creat("wut", 0644)); ASSERT_SYS(0, 4, dup(3)); ASSERT_SYS(0, 0, lseek(3, 0, SEEK_CUR)); ASSERT_SYS(0, 1, lseek(4, 1, SEEK_SET)); ASSERT_SYS(0, 1, lseek(3, 0, SEEK_CUR)); EXPECT_SYS(0, 0, close(4)); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, filePositionChanges_areObservableAcrossProcesses) { char buf[8] = {0}; ASSERT_SYS(0, 3, open("wut", O_RDWR | O_CREAT, 0644)); ASSERT_SYS(0, 3, write(3, "wut", 3)); ASSERT_SYS(0, 0, lseek(3, 0, SEEK_SET)); SPAWN(fork); ASSERT_SYS(0, 1, lseek(3, 1, SEEK_SET)); EXITS(0); EXPECT_SYS(0, 1, read(3, buf, 1)); EXPECT_EQ('u', buf[0]); EXPECT_SYS(0, 0, close(3)); } TEST(lseek, beyondEndOfFile_isZeroExtendedUponSubsequentWrite) { char buf[8] = {1, 1}; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 2, lseek(3, 2, SEEK_SET)); ASSERT_SYS(0, 2, lseek(3, 0, SEEK_CUR)); ASSERT_SYS(0, 0, pread(3, buf, 8, 0)); // lseek() alone doesn't extend ASSERT_SYS(0, 2, write(3, buf, 2)); // does extend once i/o happens ASSERT_SYS(0, 4, pread(3, buf, 8, 0)); ASSERT_EQ(0, buf[0]); ASSERT_EQ(0, buf[1]); ASSERT_EQ(1, buf[2]); ASSERT_EQ(1, buf[3]); ASSERT_SYS(0, 0, close(3)); }
4,454
107
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/unlinkat_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/sysv/consts/at.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(unlink, efault) { ASSERT_SYS(EFAULT, -1, unlink(0)); if (IsWindows() || !IsAsan()) return; // not possible ASSERT_SYS(EFAULT, -1, unlink((void *)77)); } TEST(unlink, enoent) { ASSERT_SYS(ENOENT, -1, unlink("")); ASSERT_SYS(ENOENT, -1, unlink("doesnotexist")); ASSERT_SYS(ENOENT, -1, unlink("o/doesnotexist")); } TEST(unlink, enotdir) { ASSERT_SYS(0, 0, touch("o", 0644)); ASSERT_SYS(ENOTDIR, -1, unlink("o/doesnotexist")); } TEST(unlinkat, test) { int i, fd; EXPECT_EQ(0, touch("mytmp", 0644)); EXPECT_EQ(0, unlinkat(AT_FDCWD, "mytmp", 0)); for (i = 0; i < 8; ++i) { EXPECT_NE(-1, (fd = creat("mytmp", 0644))); EXPECT_EQ(0, close(fd)); EXPECT_EQ(0, unlinkat(AT_FDCWD, "mytmp", 0)); } }
2,844
58
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/read_test.c
/*-*- 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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/iovec.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/sock/internal.h" #include "libc/sysv/consts/nr.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; TEST(read, eof) { char b[8] = "hello"; ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_SYS(0, 4, open("foo", O_RDONLY)); ASSERT_SYS(0, 0, read(4, b, 8)); ASSERT_SYS(0, 8, write(3, b, 8)); ASSERT_SYS(0, 8, read(4, b, 8)); ASSERT_SYS(0, 0, read(4, b, 8)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } //////////////////////////////////////////////////////////////////////////////// BENCH(read, bench) { char buf[16]; ASSERT_SYS(0, 3, open("/dev/zero", O_RDONLY)); EZBENCH2("read", donothing, read(3, buf, 5)); EZBENCH2("pread", donothing, pread(3, buf, 5, 0)); EZBENCH2("readv₁", donothing, readv(3, &(struct iovec){buf, 5}, 1)); EZBENCH2("readv₂", donothing, readv(3, (struct iovec[]){{buf, 1}, {buf + 1, 4}}, 2)); EZBENCH2("preadv₁", donothing, preadv(3, &(struct iovec){buf, 5}, 1, 0)); EZBENCH2("preadv₂", donothing, preadv(3, (struct iovec[]){{buf, 1}, {buf + 1, 4}}, 2, 0)); EZBENCH2("sys_read", donothing, sys_read(3, buf, 5)); EZBENCH2("sys_readv", donothing, sys_readv(3, &(struct iovec){buf, 5}, 1)); ASSERT_SYS(0, 0, close(3)); }
3,403
63
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/lock_ofd_test.c
/*-*- 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 2022 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/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/struct/flock.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" /** * @fileoverview Better Advisory Locks Test */ #define PROCESSES 8 #define THREADS 8 // <-- THIS #define RATIO 3 #define ITERATIONS 10 char testlib_enable_tmp_setup_teardown; _Thread_local const char *kind; bool SupportsOfdLocks(void) { int e; bool r; if (!IsLinux()) return false; // F_OFD_* was introduced in linux 3.15 // getrandom() was introduced in linux 3.17 // testing for getrandom() should be a sure thing w/o creating an fd e = errno; BLOCK_CANCELLATIONS; r = !sys_getrandom(0, 0, 0); ALLOW_CANCELLATIONS; errno = e; return r; } void SetUp(void) { if (!SupportsOfdLocks()) { kprintf("ofd locks not supported on this system\n"); exit(0); } } void Log(const char *fmt, ...) { #if 0 va_list va; char b[512]; int i, n = sizeof(b); va_start(va, fmt); i = ksnprintf(b, n, "%s pid=%d tid=%d ", kind, getpid(), gettid()); i += kvsnprintf(b + i, MAX(0, n - i), fmt, va); i += ksnprintf(b + i, MAX(0, n - i), "\n"); write(2, b, MIN(i, n)); va_end(va); #endif } void Lock(int fd, int type, long start, long len) { int e; struct flock lock = { .l_type = type, .l_whence = SEEK_SET, .l_start = start, .l_len = len, }; e = errno; while (fcntl(fd, F_OFD_SETLK, &lock)) { ASSERT_TRUE(errno == EAGAIN || errno == EACCES); errno = e; Log("flock spinning on %d", fd); } } void WriteLock(int fd, long start, long len) { Lock(fd, F_WRLCK, start, len); Log("acquired write lock on %d", fd); } void ReadLock(int fd, long start, long len) { Lock(fd, F_RDLCK, start, len); Log("acquired read lock on %d", fd); } void Unlock(int fd, long start, long len) { Lock(fd, F_UNLCK, start, len); Log("released lock on %d", fd); } void *Reader(void *arg) { int i, j, fd; char buf[10]; kind = arg; ASSERT_NE(-1, (fd = open("db", O_RDONLY))); for (j = 0; j < ITERATIONS; ++j) { ReadLock(fd, 10, 10); for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pread(fd, buf + i, 1, 10 + i)); ASSERT_EQ(buf[0], buf[i]); } Unlock(fd, 10, 10); sched_yield(); } ASSERT_SYS(0, 0, close(fd)); return 0; } void *Writer(void *arg) { int i, j, fd; char buf[10]; kind = arg; ASSERT_NE(-1, (fd = open("db", O_RDWR))); for (j = 0; j < ITERATIONS; ++j) { WriteLock(fd, 10, 10); for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pread(fd, buf + i, 1, 10 + i)); ASSERT_EQ(buf[0], buf[i]); } for (i = 0; i < 10; ++i) { buf[i]++; } for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pwrite(fd, buf + i, 1, 10 + i)); } Unlock(fd, 10, 10); sched_yield(); } ASSERT_SYS(0, 0, close(fd)); return 0; } TEST(posixAdvisoryLocks, threadsAndProcessesFightingForLock) { int i, rc, pid, fd, ws; pthread_t th[THREADS + 1]; ASSERT_SYS(0, 3, creat("db", 0644)); ASSERT_SYS(0, 0, ftruncate(3, 30)); ASSERT_SYS(0, 0, close(3)); for (i = 0; i < THREADS; ++i) { if (i % RATIO == 0) { ASSERT_EQ(0, pthread_create(th + i, 0, Reader, "reader thread")); } else { ASSERT_EQ(0, pthread_create(th + i, 0, Writer, "writer thread")); } } for (i = 0; i < PROCESSES; ++i) { ASSERT_NE(-1, (rc = fork())); if (!rc) { if (i % RATIO == 0) { Writer("writer process"); } else { Reader("reader process"); } _Exit(0); } } ASSERT_NE(-1, (fd = open("db", O_RDWR))); Lock(fd, F_WRLCK, 0, 10); Lock(fd, F_WRLCK, 20, 10); for (i = 0; i < THREADS; ++i) { ASSERT_EQ(0, pthread_join(th[i], 0)); } kind = "main process"; for (;;) { int e = errno; if ((pid = waitpid(0, &ws, 0)) != -1) { if (WIFSIGNALED(ws)) { Log("process %d terminated with %G", pid, WTERMSIG(ws)); testlib_incrementfailed(); } else if (WEXITSTATUS(ws)) { Log("process %d exited with %d", pid, WEXITSTATUS(ws)); testlib_incrementfailed(); } } else { ASSERT_EQ(ECHILD, errno); errno = e; break; } } ASSERT_SYS(0, 0, close(fd)); }
6,323
211
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/fileexists_test.c
/*-*- 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/stat.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(fileexists, test) { EXPECT_SYS(0, 0, fileexists("doge")); EXPECT_SYS(0, 0, isdirectory("doge")); EXPECT_SYS(0, 0, close(creat("doge", 0644))); EXPECT_SYS(0, 1, fileexists("doge")); EXPECT_SYS(0, 0, isdirectory("doge")); } BENCH(fileexists, bench) { struct stat st; EZBENCH2("!stat", donothing, stat("doge", &st)); EZBENCH2("!fileexists", donothing, fileexists("doge")); EXPECT_SYS(0, 0, close(creat("doge", 0644))); EZBENCH2("stat", donothing, stat("doge", &st)); EZBENCH2("fileexists", donothing, fileexists("doge")); }
2,651
46
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/tkill_test.c
/*-*- 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 2022 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/calls/struct/sigset.h" #include "libc/errno.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" _Thread_local intptr_t gotsig; void OnSig(int sig) { gotsig = sig; } void *Worker(void *arg) { sigset_t ss; sigemptyset(&ss); ASSERT_SYS(EINTR, -1, sigsuspend(&ss)); return (void *)gotsig; } TEST(tkill, test) { if (IsWindows()) return; // TODO(jart): fix me void *res; int i, tid; pthread_t t; sigset_t ss, oldss; sighandler_t oldsig; sigemptyset(&ss); sigaddset(&ss, SIGUSR1); oldsig = signal(SIGUSR1, OnSig); ASSERT_SYS(0, 0, sigprocmask(SIG_BLOCK, &ss, &oldss)); ASSERT_EQ(0, pthread_create(&t, 0, Worker, 0)); ASSERT_EQ(0, pthread_getunique_np(t, &tid)); ASSERT_SYS(0, 0, tkill(tid, SIGUSR1)); ASSERT_EQ(0, pthread_join(t, &res)); ASSERT_EQ(SIGUSR1, (intptr_t)res); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &oldss, 0)); signal(SIGUSR1, oldsig); }
2,870
59
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/getgroups_test.c
/*-*- 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 2022 Gavin Arthur Hayes │ │ │ │ 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/dce.h" #include "libc/macros.internal.h" #include "libc/testlib/testlib.h" TEST(getgroups, test) { int n; if (IsWindows()) return; uint32_t G[500]; EXPECT_GT((n = getgroups(ARRAYLEN(G), G)), 0); if (getuid()) return; // this needs root EXPECT_SYS(0, 0, setgroups(n, G)); }
2,168
32
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/chdir_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(chdir, efault) { ASSERT_SYS(EFAULT, -1, chdir(0)); if (IsWindows() || !IsAsan()) return; // not possible ASSERT_SYS(EFAULT, -1, chdir((void *)77)); } TEST(chdir, enoent) { ASSERT_SYS(ENOENT, -1, chdir("")); ASSERT_SYS(ENOENT, -1, chdir("doesnotexist")); ASSERT_SYS(ENOENT, -1, chdir("o/doesnotexist")); } TEST(chdir, enotdir) { ASSERT_SYS(0, 0, touch("o", 0644)); ASSERT_SYS(ENOTDIR, -1, chdir("o/doesnotexist")); } TEST(chdir, test) { ASSERT_SYS(0, 0, mkdir("o", 0755)); ASSERT_SYS(0, 0, touch("o/file", 0644)); ASSERT_SYS(0, 3, open("o/file", O_RDONLY)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, chdir("o")); ASSERT_SYS(0, 3, open("file", O_RDONLY)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(ENOENT, -1, open("o/file", O_RDONLY)); }
2,888
58
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/_timespec_test.c
/*-*- 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 2022 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/struct/timespec.h" #include "libc/intrin/kprintf.h" #include "libc/limits.h" #include "libc/stdio/rand.h" #include "libc/testlib/testlib.h" #include "third_party/nsync/time.h" TEST(timespec_sub, test) { EXPECT_TRUE( !timespec_cmp((struct timespec){-1}, timespec_sub((struct timespec){1}, (struct timespec){2}))); EXPECT_TRUE( !timespec_cmp((struct timespec){1}, timespec_sub((struct timespec){2}, (struct timespec){1}))); EXPECT_TRUE(!timespec_cmp( (struct timespec){1, 1}, timespec_sub((struct timespec){2, 2}, (struct timespec){1, 1}))); EXPECT_TRUE(!timespec_cmp( (struct timespec){0, 999999999}, timespec_sub((struct timespec){2, 1}, (struct timespec){1, 2}))); } TEST(timespec_frommillis, test) { EXPECT_TRUE( !timespec_cmp((struct timespec){0, 1000000}, timespec_frommillis(1))); EXPECT_TRUE( !timespec_cmp((struct timespec){0, 2000000}, timespec_frommillis(2))); EXPECT_TRUE(!timespec_cmp((struct timespec){1}, timespec_frommillis(1000))); } TEST(timespec_frommicros, test) { EXPECT_TRUE( !timespec_cmp((struct timespec){0, 1000}, timespec_frommicros(1))); EXPECT_TRUE( !timespec_cmp((struct timespec){0, 2000}, timespec_frommicros(2))); EXPECT_TRUE( !timespec_cmp((struct timespec){1}, timespec_frommicros(1000000))); EXPECT_TRUE(!timespec_cmp((struct timespec){2, 123000}, timespec_frommicros(2000123))); } TEST(timespec_tomillis, test) { EXPECT_EQ(0, timespec_tomillis((struct timespec){0, 0})); EXPECT_EQ(1, timespec_tomillis((struct timespec){0, 1})); EXPECT_EQ(1, timespec_tomillis((struct timespec){0, 999999})); EXPECT_EQ(1, timespec_tomillis((struct timespec){0, 1000000})); EXPECT_EQ(1000, timespec_tomillis((struct timespec){0, 999999999})); EXPECT_EQ(2123, timespec_tomillis((struct timespec){2, 123000000})); EXPECT_EQ(INT64_MAX, timespec_tomillis((struct timespec){INT64_MAX, 0})); EXPECT_EQ(INT64_MIN, timespec_tomillis((struct timespec){INT64_MIN, 0})); EXPECT_EQ(INT64_MAX, timespec_tomillis( (struct timespec){0x7fffffffffffffff, 999999999})); } TEST(timespec_tomicros, test) { EXPECT_EQ(0, timespec_tomicros((struct timespec){0, 0})); EXPECT_EQ(1, timespec_tomicros((struct timespec){0, 1})); EXPECT_EQ(2000123, timespec_tomicros((struct timespec){2, 123000})); EXPECT_EQ(INT64_MAX, timespec_tomicros((struct timespec){INT64_MAX, 0})); EXPECT_EQ(INT64_MIN, timespec_tomicros((struct timespec){INT64_MIN, 0})); } TEST(timespec_tonanos, test) { EXPECT_EQ(2000123000, timespec_tonanos((struct timespec){2, 123000})); EXPECT_EQ(INT64_MAX, timespec_tonanos((struct timespec){INT64_MAX, 0})); EXPECT_EQ(INT64_MIN, timespec_tonanos((struct timespec){INT64_MIN, 0})); } static long mod(long x, long y) { if (y == -1) return 0; return x - y * (x / y - (x % y && (x ^ y) < 0)); } TEST(timespec_sub, math) { for (int i = 0; i < 1000; ++i) { struct timespec x = {mod(lemur64(), 10), mod(lemur64(), 10)}; struct timespec y = {mod(lemur64(), 10), mod(lemur64(), 10)}; struct timespec z = timespec_add(timespec_sub(x, y), y); EXPECT_TRUE(!timespec_cmp(x, timespec_add(timespec_sub(x, y), y))); } }
5,115
100
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/ioctl_siocgifconf_test.c
/*-*- 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/intrin/bits.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/ioctl.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "libc/sock/sock.h" #include "libc/sock/struct/ifconf.h" #include "libc/sock/struct/ifreq.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sio.h" #include "libc/sysv/consts/sock.h" #include "libc/testlib/testlib.h" TEST(ioctl_siocgifconf, test) { size_t n; char *data; int socketfd; struct ifreq *ifr; struct ifconf conf; char addrbuf[1024]; uint32_t ip, netmask; bool foundloopback = false; data = gc(malloc((n = 4096))); ASSERT_NE(-1, (socketfd = socket(AF_INET, SOCK_DGRAM, 0))); conf.ifc_buf = data; conf.ifc_len = n; ASSERT_NE(-1, ioctl(socketfd, SIOCGIFCONF, &conf)); for (ifr = (struct ifreq *)data; (char *)ifr < data + conf.ifc_len; ++ifr) { if (ifr->ifr_addr.sa_family != AF_INET) continue; ip = ntohl(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr); EXPECT_NE(-1, ioctl(socketfd, SIOCGIFNETMASK, ifr)); netmask = ntohl(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr); #if 0 fprintf(stderr, "%s %x %d\n" " ip %hhu.%hhu.%hhu.%hhu\n" " netmask %hhu.%hhu.%hhu.%hhu\n" "\n", ifr->ifr_name, ip, ifr->ifr_addr.sa_family, ip >> 24, ip >> 16, ip >> 8, ip, netmask >> 24, netmask >> 16, netmask >> 8, netmask); #endif if (ip == 0x7f000001) { foundloopback = true; EXPECT_EQ(0xFF000000, netmask); } } EXPECT_TRUE(foundloopback); ASSERT_NE(-1, close(socketfd)); }
3,598
73
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/setrlimit_test.c
/*-*- 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 "dsp/core/core.h" #include "libc/calls/calls.h" #include "libc/calls/struct/rlimit.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/intrin/directmap.internal.h" #include "libc/intrin/safemacros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" #include "libc/x/xsigaction.h" #include "libc/x/xspawn.h" #ifdef __x86_64__ #define MEM (64 * 1024 * 1024) static char tmpname[PATH_MAX]; void OnSigxcpu(int sig) { ASSERT_EQ(SIGXCPU, sig); _Exit(0); } void OnSigxfsz(int sig) { unlink(tmpname); ASSERT_EQ(SIGXFSZ, sig); _Exit(0); } TEST(setrlimit, testCpuLimit) { char *p; int i, wstatus; long double start; struct rlimit rlim; double matrices[3][3][3]; if (IsWindows()) return; /* of course it doesn't work on windows */ if (IsOpenbsd()) return; /* TODO(jart): fix flake */ ASSERT_NE(-1, (wstatus = xspawn(0))); if (wstatus == -2) { ASSERT_EQ(0, xsigaction(SIGXCPU, OnSigxcpu, 0, 0, 0)); ASSERT_EQ(0, getrlimit(RLIMIT_CPU, &rlim)); rlim.rlim_cur = 1; /* set soft limit to one second */ ASSERT_EQ(0, setrlimit(RLIMIT_CPU, &rlim)); start = nowl(); do { matmul3(matrices[0], matrices[1], matrices[2]); matmul3(matrices[0], matrices[1], matrices[2]); matmul3(matrices[0], matrices[1], matrices[2]); matmul3(matrices[0], matrices[1], matrices[2]); } while ((nowl() - start) < 5); _Exit(1); } EXPECT_TRUE(WIFEXITED(wstatus)); EXPECT_FALSE(WIFSIGNALED(wstatus)); EXPECT_EQ(0, WEXITSTATUS(wstatus)); EXPECT_EQ(0, WTERMSIG(wstatus)); } TEST(setrlimit, testFileSizeLimit) { char *p; char junkdata[512]; int i, fd, wstatus; struct rlimit rlim; if (IsWindows()) return; /* of course it doesn't work on windows */ ASSERT_NE(-1, (wstatus = xspawn(0))); if (wstatus == -2) { ASSERT_EQ(0, xsigaction(SIGXFSZ, OnSigxfsz, 0, 0, 0)); ASSERT_EQ(0, getrlimit(RLIMIT_FSIZE, &rlim)); rlim.rlim_cur = 1024 * 1024; /* set soft limit to one megabyte */ ASSERT_EQ(0, setrlimit(RLIMIT_FSIZE, &rlim)); snprintf(tmpname, sizeof(tmpname), "%s/%s.%d", firstnonnull(getenv("TMPDIR"), "/tmp"), firstnonnull(program_invocation_short_name, "unknown"), getpid()); ASSERT_NE(-1, (fd = open(tmpname, O_RDWR | O_CREAT | O_TRUNC, 0644))); rngset(junkdata, 512, _rand64, -1); for (i = 0; i < 5 * 1024 * 1024 / 512; ++i) { ASSERT_EQ(512, write(fd, junkdata, 512)); } close(fd); unlink(tmpname); _Exit(1); } EXPECT_TRUE(WIFEXITED(wstatus)); EXPECT_FALSE(WIFSIGNALED(wstatus)); EXPECT_EQ(0, WEXITSTATUS(wstatus)); EXPECT_EQ(0, WTERMSIG(wstatus)); } int SetKernelEnforcedMemoryLimit(size_t n) { struct rlimit rlim; getrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = n; return setrlimit(RLIMIT_AS, &rlim); } TEST(setrlimit, testMemoryLimit) { char *p; bool gotsome; int i, wstatus; if (IsXnu()) return; if (IsAsan()) return; /* b/c we use sys_mmap */ ASSERT_NE(-1, (wstatus = xspawn(0))); if (wstatus == -2) { ASSERT_EQ(0, SetKernelEnforcedMemoryLimit(MEM)); for (gotsome = i = 0; i < (MEM * 2) / GUARDSIZE; ++i) { p = mmap(0, GUARDSIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0); if (p != MAP_FAILED) { gotsome = true; } else { if (!IsNetbsd()) { // TODO(jart): what's going on with NetBSD? ASSERT_TRUE(gotsome); } ASSERT_EQ(ENOMEM, errno); _Exit(0); } rngset(p, GUARDSIZE, _rand64, -1); } _Exit(1); } EXPECT_TRUE(WIFEXITED(wstatus)); EXPECT_FALSE(WIFSIGNALED(wstatus)); EXPECT_EQ(0, WEXITSTATUS(wstatus)); EXPECT_EQ(0, WTERMSIG(wstatus)); } TEST(setrlimit, testVirtualMemoryLimit) { char *p; int i, wstatus; if (IsAsan()) return; if (IsXnu()) return; /* doesn't work on darwin */ if (IsOpenbsd()) return; /* unavailable on openbsd */ if (IsWindows()) return; /* of course it doesn't work on windows */ ASSERT_NE(-1, (wstatus = xspawn(0))); if (wstatus == -2) { ASSERT_EQ(0, setrlimit(RLIMIT_AS, &(struct rlimit){MEM, MEM})); for (i = 0; i < (MEM * 2) / GUARDSIZE; ++i) { p = sys_mmap(0, GUARDSIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0) .addr; if (p == MAP_FAILED) { ASSERT_EQ(ENOMEM, errno); _Exit(0); } rngset(p, GUARDSIZE, _rand64, -1); } _Exit(1); } EXPECT_TRUE(WIFEXITED(wstatus)); EXPECT_FALSE(WIFSIGNALED(wstatus)); EXPECT_EQ(0, WEXITSTATUS(wstatus)); EXPECT_EQ(0, WTERMSIG(wstatus)); } TEST(setrlimit, testDataMemoryLimit) { char *p; int i, wstatus; if (IsAsan()) return; if (IsXnu()) return; /* doesn't work on darwin */ if (IsNetbsd()) return; /* doesn't work on netbsd */ if (IsFreebsd()) return; /* doesn't work on freebsd */ if (IsLinux()) return; /* doesn't work on gnu/systemd */ if (IsWindows()) return; /* of course it doesn't work on windows */ ASSERT_NE(-1, (wstatus = xspawn(0))); if (wstatus == -2) { ASSERT_EQ(0, setrlimit(RLIMIT_DATA, &(struct rlimit){MEM, MEM})); for (i = 0; i < (MEM * 2) / GUARDSIZE; ++i) { p = sys_mmap(0, GUARDSIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0) .addr; if (p == MAP_FAILED) { ASSERT_EQ(ENOMEM, errno); _Exit(0); } rngset(p, GUARDSIZE, _rand64, -1); } _Exit(1); } EXPECT_TRUE(WIFEXITED(wstatus)); EXPECT_FALSE(WIFSIGNALED(wstatus)); EXPECT_EQ(0, WEXITSTATUS(wstatus)); EXPECT_EQ(0, WTERMSIG(wstatus)); } TEST(setrlimit, testPhysicalMemoryLimit) { /* RLIMIT_RSS doesn't work on gnu/systemd */ /* RLIMIT_RSS doesn't work on darwin */ /* RLIMIT_RSS doesn't work on freebsd */ /* RLIMIT_RSS doesn't work on netbsd */ /* RLIMIT_RSS doesn't work on openbsd */ /* of course it doesn't work on windows */ } wontreturn void OnVfork(void *ctx) { struct rlimit *rlim; rlim = ctx; rlim->rlim_cur -= 1; ASSERT_EQ(0, getrlimit(RLIMIT_CPU, rlim)); _Exit(0); } TEST(setrlimit, isVforkSafe) { int pid, ws; struct rlimit rlim[2]; if (IsWindows()) return; /* of course it doesn't work on windows */ ASSERT_EQ(0, getrlimit(RLIMIT_CPU, rlim)); ASSERT_NE(-1, (ws = xvspawn(OnVfork, rlim, 0))); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_FALSE(WIFSIGNALED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); EXPECT_EQ(0, WTERMSIG(ws)); ASSERT_EQ(0, getrlimit(RLIMIT_CPU, rlim + 1)); EXPECT_EQ(rlim[0].rlim_cur, rlim[1].rlim_cur); EXPECT_EQ(rlim[0].rlim_max, rlim[1].rlim_max); } #endif /* __x86_64__ */
8,760
245
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/write_test.c
/*-*- 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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/iovec.internal.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/sock/internal.h" #include "libc/sysv/consts/nr.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; TEST(write, notOpen_ebadf) { ASSERT_SYS(EBADF, -1, write(-1, 0, 0)); ASSERT_SYS(EBADF, -1, write(+3, 0, 0)); } TEST(write, readOnlyFd_ebadf) { ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_SYS(0, 3, open("foo", O_RDONLY)); ASSERT_SYS(EBADF, -1, write(3, "x", 1)); ASSERT_SYS(0, 0, close(3)); } TEST(write, badMemory_efault) { ASSERT_SYS(EFAULT, -1, write(1, 0, 1)); if (!IsAsan()) return; ASSERT_SYS(EFAULT, -1, write(1, (void *)1, 1)); } TEST(write, brokenPipe_sigpipeIgnored_returnsEpipe) { int fds[2]; SPAWN(fork); signal(SIGPIPE, SIG_IGN); ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, 1, write(4, "x", 1)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(EPIPE, -1, write(4, "x", 1)); ASSERT_SYS(0, 0, close(4)); EXITS(0); } TEST(write, brokenPipe_sigpipeBlocked_returnsEpipe) { int fds[2]; sigset_t mask; SPAWN(fork); signal(SIGPIPE, SIG_DFL); sigemptyset(&mask); sigaddset(&mask, SIGPIPE); sigprocmask(SIG_BLOCK, &mask, 0); ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(EPIPE, -1, write(4, "x", 1)); ASSERT_SYS(0, 0, close(4)); EXITS(0); } TEST(write, rlimitFsizeExceeded_raisesEfbig) { if (IsWindows()) return; // not supported struct rlimit rl = {1, 10}; SPAWN(fork); signal(SIGXFSZ, SIG_IGN); ASSERT_SYS(0, 0, setrlimit(RLIMIT_FSIZE, &rl)); ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_SYS(0, 1, write(3, "x", 1)); ASSERT_SYS(EFBIG, -1, write(3, "x", 1)); ASSERT_SYS(0, 0, close(3)); EXITS(0); } BENCH(write, bench) { ASSERT_SYS(0, 3, open("/dev/null", O_WRONLY)); EZBENCH2("write", donothing, write(3, "hello", 5)); EZBENCH2("writev", donothing, writev(3, &(struct iovec){"hello", 5}, 1)); EZBENCH2("sys_write", donothing, sys_write(3, "hello", 5)); EZBENCH2("sys_writev", donothing, sys_writev(3, &(struct iovec){"hello", 5}, 1)); ASSERT_SYS(0, 0, close(3)); }
4,423
108
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/preadv_test.c
/*-*- 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 2022 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/calls/internal.h" #include "libc/calls/struct/iovec.h" #include "libc/errno.h" #include "libc/nt/files.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; TEST(preadv, ebadf) { EXPECT_SYS(EBADF, -1, preadv(-1, 0, 0, 0)); EXPECT_SYS(EBADF, -1, pwritev(-1, 0, 0, 0)); } TEST(preadv, testOneIovecWorks_itDelegatesToPread) { char b1[2] = "hi"; struct iovec v[1] = {{b1, 2}}; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); EXPECT_SYS(0, 2, pwritev(3, v, 1, 0)); b1[0] = 0; b1[1] = 0; EXPECT_SYS(0, 0, preadv(3, 0, 0, 0)); EXPECT_SYS(0, 0, pwritev(3, 0, 0, 0)); EXPECT_SYS(0, 2, preadv(3, v, 1, 0)); ASSERT_EQ('h', b1[0]); ASSERT_EQ('i', b1[1]); b1[0] = 0; b1[1] = 0x55; EXPECT_SYS(0, 1, preadv(3, v, 1, 1)); ASSERT_EQ('i', b1[0]); ASSERT_EQ(0x55, b1[1]); ASSERT_SYS(0, 0, close(3)); } TEST(preadv, testTwoIovecWorks_itMustDoItsThing) { char b1[1] = "h"; char b2[1] = "i"; struct iovec v[2] = {{b1, 1}, {b2, 1}}; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); EXPECT_SYS(0, 2, pwritev(3, v, 2, 0)); b1[0] = 0; b2[0] = 0; EXPECT_SYS(0, 2, preadv(3, v, 2, 0)); ASSERT_EQ('h', b1[0]); ASSERT_EQ('i', b2[0]); b1[0] = 0; b2[0] = 0x55; EXPECT_SYS(0, 1, preadv(3, v, 2, 1)); ASSERT_EQ('i', b1[0]); ASSERT_EQ(0x55, b2[0]); ASSERT_SYS(0, 0, close(3)); } TEST(pwritev, writePastEof_zeroExtendsFile_alsoDoesntChangeFilePointer) { char b[6] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55}; char s[2] = "hi"; struct iovec v[1] = {{s, 2}}; ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(EINVAL, -1, pwritev(3, v, 1, -999)); ASSERT_SYS(0, 2, pwritev(3, v, 1, 0)); ASSERT_SYS(0, 2, pwritev(3, v, 1, 4)); ASSERT_SYS(0, 2, preadv(3, v, 1, 0)); ASSERT_SYS(0, 6, read(3, b, 6)); ASSERT_EQ('h', b[0]); ASSERT_EQ('i', b[1]); ASSERT_EQ(0, b[2]); ASSERT_EQ(0, b[3]); ASSERT_EQ('h', b[4]); ASSERT_EQ('i', b[5]); ASSERT_SYS(0, 0, close(3)); }
3,937
92
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/statfs_test.c
/*-*- 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 2022 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/statfs.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; struct statfs f; TEST(statfs, testFile) { EXPECT_SYS(0, 0, touch("foo", 0644)); EXPECT_SYS(0, 0, statfs("foo", &f)); } TEST(statfs, testDirectory) { EXPECT_SYS(0, 0, statfs(".", &f)); } TEST(statfs, testFdDirectory) { EXPECT_SYS(0, 3, open(".", O_RDONLY | O_DIRECTORY)); EXPECT_SYS(0, 0, fstatfs(3, &f)); EXPECT_SYS(0, 0, close(3)); } TEST(statfs, testFdFile) { EXPECT_SYS(0, 0, touch("foo", 0644)); EXPECT_SYS(0, 3, open("foo", O_RDONLY)); EXPECT_SYS(0, 0, fstatfs(3, &f)); EXPECT_SYS(0, 0, close(3)); }
2,540
48
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/poll_test.c
/*-*- 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/sysv/consts/poll.h" #include "libc/calls/calls.h" #include "libc/calls/pledge.h" #include "libc/calls/struct/sigaction.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/log/libfatal.internal.h" #include "libc/mem/gc.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/rdtscp.h" #include "libc/nt/synchronization.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/sock/struct/sockaddr.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/inaddr.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/sock.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "tool/decode/lib/flagger.h" bool gotsig; void SetUpOnce(void) { __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS | PLEDGE_STDERR_LOGGING; ASSERT_SYS(0, 0, pledge("stdio proc inet", 0)); } void SetUp(void) { gotsig = false; } void OnSig(int sig) { gotsig = true; } dontdiscard char *FormatPollFd(struct pollfd p[2]) { return xasprintf("fd:%d revents:%s\n" "fd:%d revents:%s\n", p[0].fd, "<TODO:kPollNames>", p[1].fd, "<TODO:kPollNames>"); } TEST(poll, allZero_doesNothingPrettyMuch) { EXPECT_SYS(0, 0, poll(0, 0, 0)); } TEST(ppoll, weCanProveItChecksForSignals) { if (IsXnu()) return; if (IsNetbsd()) return; int pipefds[2]; sigset_t set, old; struct sigaction oldss; struct sigaction sa = {.sa_handler = OnSig}; EXPECT_SYS(0, 0, pipe(pipefds)); struct pollfd fds[] = {{pipefds[0], POLLIN}}; ASSERT_SYS(0, 0, sigaction(SIGUSR1, &sa, &oldss)); ASSERT_SYS(0, 0, sigfillset(&set)); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &set, &old)); EXPECT_SYS(0, 0, kill(getpid(), SIGUSR1)); EXPECT_FALSE(gotsig); EXPECT_SYS(EINTR, -1, ppoll(fds, 1, 0, &old)); EXPECT_TRUE(gotsig); EXPECT_SYS(0, 0, sigprocmask(SIG_SETMASK, &old, 0)); EXPECT_SYS(0, 0, sigaction(SIGUSR1, &oldss, 0)); EXPECT_SYS(0, 0, close(pipefds[0])); EXPECT_SYS(0, 0, close(pipefds[1])); } TEST(poll, testNegativeOneFd_isIgnored) { ASSERT_SYS(0, 3, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); struct sockaddr_in addr = {AF_INET, 0, {htonl(INADDR_LOOPBACK)}}; ASSERT_SYS(0, 0, bind(3, (struct sockaddr *)&addr, sizeof(addr))); ASSERT_SYS(0, 0, listen(3, 10)); struct pollfd fds[] = {{-1}, {3}}; EXPECT_SYS(0, 0, poll(fds, ARRAYLEN(fds), 1)); EXPECT_STREQ("fd:-1 revents:<TODO:kPollNames>\n" "fd:3 revents:<TODO:kPollNames>\n", _gc(FormatPollFd(&fds[0]))); ASSERT_SYS(0, 0, close(3)); } TEST(poll, pipe_noInput) { // we can't test stdin here since // we can't assume it isn't /dev/null // since nil is always pollin as eof int pipefds[2]; EXPECT_SYS(0, 0, pipe(pipefds)); struct pollfd fds[] = {{pipefds[0], POLLIN}}; EXPECT_SYS(0, 0, poll(fds, 1, 0)); EXPECT_EQ(0, fds[0].revents); EXPECT_SYS(0, 0, close(pipefds[0])); EXPECT_SYS(0, 0, close(pipefds[1])); } TEST(poll, pipe_hasInputFromSameProcess) { char buf[2]; int pipefds[2]; EXPECT_SYS(0, 0, pipe(pipefds)); struct pollfd fds[] = {{pipefds[0], POLLIN}}; EXPECT_SYS(0, 2, write(pipefds[1], "hi", 2)); EXPECT_SYS(0, 1, poll(fds, 1, 1000)); // flake nt! EXPECT_EQ(POLLIN, fds[0].revents); EXPECT_SYS(0, 2, read(pipefds[0], buf, 2)); EXPECT_SYS(0, 0, poll(fds, 1, 0)); EXPECT_SYS(0, 0, close(pipefds[0])); EXPECT_SYS(0, 0, close(pipefds[1])); } TEST(poll, pipe_hasInput) { char buf[2]; sigset_t chldmask, savemask; int ws, pid, sync[2], pipefds[2]; EXPECT_EQ(0, sigemptyset(&chldmask)); EXPECT_EQ(0, sigaddset(&chldmask, SIGCHLD)); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &chldmask, &savemask)); EXPECT_SYS(0, 0, pipe(pipefds)); EXPECT_NE(-1, (pid = fork())); if (!pid) { EXPECT_SYS(0, 0, close(pipefds[0])); EXPECT_SYS(0, 2, write(pipefds[1], "hi", 2)); EXPECT_SYS(0, 2, write(pipefds[1], "hi", 2)); EXPECT_SYS(0, 0, close(pipefds[1])); _Exit(0); } EXPECT_SYS(0, 0, close(pipefds[1])); EXPECT_SYS(0, 2, read(pipefds[0], buf, 2)); struct pollfd fds[] = {{pipefds[0], POLLIN}}; EXPECT_SYS(0, 1, poll(fds, 1, -1)); EXPECT_EQ(POLLIN, fds[0].revents & POLLIN); EXPECT_SYS(0, 2, read(pipefds[0], buf, 2)); EXPECT_SYS(0, 0, close(pipefds[0])); ASSERT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &savemask, 0)); } #if 0 TEST(poll, emptyFds_becomesSleep) { // timing tests w/o mocks are always the hardest int64_t a, b, c, p, i = 0; do { if (++i == 5) { kprintf("too much cpu churn%n"); return; } p = TSC_AUX_CORE(rdpid()); a = rdtsc(); EXPECT_SYS(0, 0, poll(0, 0, 5)); b = rdtsc(); EXPECT_SYS(0, 0, poll(0, 0, 50)); c = rdtsc(); } while (TSC_AUX_CORE(rdpid()) != p); EXPECT_LT((b - a) * 2, c - b); } #endif
6,739
178
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/getcwd_test.c
/*-*- 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/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath cpath fattr", 0)); } TEST(getcwd, test) { char buf[PATH_MAX]; EXPECT_SYS(0, 0, mkdir("subdir", 0755)); EXPECT_SYS(0, 0, chdir("subdir")); EXPECT_STREQ("subdir", basename(getcwd(buf, ARRAYLEN(buf)))); } TEST(getcwd, testNullBuf_allocatesResult) { EXPECT_SYS(0, 0, mkdir("subdir", 0755)); EXPECT_SYS(0, 0, chdir("subdir")); EXPECT_STREQ("subdir", basename(gc(getcwd(0, 0)))); } TEST(getcwd, testWindows_addsFunnyPrefix) { if (!IsWindows()) return; char path[PATH_MAX]; ASSERT_NE(0, getcwd(path, sizeof(path))); EXPECT_STARTSWITH("/C/", path); }
2,743
53
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/seccomp_test.c
/*-*- 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 2022 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/internal.h" #include "libc/calls/struct/bpf.h" #include "libc/calls/struct/filter.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/seccomp.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sysv/consts/audit.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "tool/net/sandbox.h" void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio proc", 0)); } // It's been reported that Chromebooks return EINVAL here. bool CanUseSeccomp(void) { int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { if (seccomp(SECCOMP_SET_MODE_STRICT, 0, 0) != -1) { _Exit1(0); } else { _Exit1(1); } } EXPECT_NE(-1, wait(&ws)); return WIFEXITED(ws) && !WEXITSTATUS(ws); } void SetUp(void) { if (!__is_linux_2_6_23() || !CanUseSeccomp()) { exit(0); } } TEST(seccompStrictMode, evilProcess_getsKill9d) { int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { EXPECT_EQ(0, seccomp(SECCOMP_SET_MODE_STRICT, 0, 0)); open("/etc/passwd", O_RDWR); _Exit1(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFSIGNALED(ws)); EXPECT_EQ(SIGKILL, WTERMSIG(ws)); } TEST(seccompStrictMode, goodProcess_isAuthorized) { int ws, pid; int pfds[2]; char buf[3] = {0}; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_NE(-1, (pid = fork())); if (!pid) { EXPECT_EQ(0, seccomp(SECCOMP_SET_MODE_STRICT, 0, 0)); write(pfds[1], "hi", 3); _Exit1(0); } EXPECT_SYS(0, 0, close(pfds[1])); EXPECT_SYS(0, 3, read(pfds[0], buf, 3)); EXPECT_SYS(0, 0, close(pfds[0])); EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); EXPECT_STREQ("hi", buf); } TEST(seccompFilter, isSoMuchBetter) { char buf[3] = {0}; int ws, pid, pfds[2]; ASSERT_SYS(0, 0, pipe(pfds)); ASSERT_NE(-1, (pid = fork())); if (!pid) { struct sock_filter filter[] = { _SECCOMP_MACHINE(AUDIT_ARCH_X86_64), // _SECCOMP_LOAD_SYSCALL_NR(), // _SECCOMP_ALLOW_SYSCALL(0x0013), // readv _SECCOMP_ALLOW_SYSCALL(0x0014), // writev _SECCOMP_ALLOW_SYSCALL(0x0000), // read _SECCOMP_ALLOW_SYSCALL(0x0001), // write _SECCOMP_ALLOW_SYSCALL(0x0003), // close _SECCOMP_ALLOW_SYSCALL(0x000f), // rt_sigreturn _SECCOMP_ALLOW_SYSCALL(0x00e7), // exit_group _SECCOMP_ALLOW_SYSCALL(0x0009), // mmap _SECCOMP_ALLOW_SYSCALL(0x0106), // newfstatat _SECCOMP_ALLOW_SYSCALL(0x0008), // lseek _SECCOMP_ALLOW_SYSCALL(0x000b), // munmap _SECCOMP_ALLOW_SYSCALL(0x00e4), // clock_gettime _SECCOMP_ALLOW_SYSCALL(0x003f), // uname _SECCOMP_LOG_AND_RETURN_ERRNO(1), // EPERM }; struct sock_fprog prog = { .len = ARRAYLEN(filter), .filter = filter, }; ASSERT_EQ(0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)); ASSERT_EQ(0, prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)); ASSERT_SYS(0, 3, write(pfds[1], "hi", 3)); ASSERT_SYS(EPERM, -1, open("/etc/passwd", O_RDONLY)); _Exit(0); } EXPECT_SYS(0, 0, close(pfds[1])); EXPECT_SYS(0, 3, read(pfds[0], buf, 3)); EXPECT_SYS(0, 0, close(pfds[0])); EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); EXPECT_STREQ("hi", buf); }
5,411
136
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/lock2_test.c
/*-*- 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 2022 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/flock.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/errno.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; TEST(lock, wholeFile) { char buf[512]; ASSERT_SYS(0, 3, open("db", O_RDWR | O_CREAT | O_EXCL, 0644)); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){.l_type = F_RDLCK})); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){.l_type = F_UNLCK})); ASSERT_SYS(0, 0, close(3)); } TEST(lock, testUpgradeFromReadToWriteLock) { char buf[512]; ASSERT_SYS(0, 3, open("db", O_RDWR | O_CREAT | O_EXCL, 0644)); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){ .l_type = F_RDLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, close(3)); } TEST(lock, testUpgradeWriteToWriteLock) { char buf[512]; ASSERT_SYS(0, 3, open("db", O_RDWR | O_CREAT | O_EXCL, 0644)); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, close(3)); } TEST(lock, unlockEverything_unlocksSmallerRanges) { int fd, pi[2]; char buf[8] = {0}; ASSERT_SYS(0, 3, creat("db", 0644)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, pipe(pi)); SPAWN(fork); ASSERT_SYS(0, 5, open("db", O_RDWR)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 8, read(3, buf, 8)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, fcntl(5, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, fcntl(5, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000005, .l_len = 1, })); ASSERT_SYS(0, 0, close(5)); PARENT(); ASSERT_SYS(0, 0, close(3)); ASSERT_NE(-1, (fd = open("db", O_RDWR))); ASSERT_SYS(0, 0, fcntl(fd, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, fcntl(fd, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000005, .l_len = 1, })); ASSERT_SYS(0, 0, fcntl(fd, F_SETLK, &(struct flock){ .l_type = F_UNLCK, })); ASSERT_SYS(0, 8, write(4, buf, 8)); ASSERT_SYS(0, 0, close(4)); WAIT(exit, 0); ASSERT_SYS(0, 0, close(fd)); } TEST(lock, close_releasesLocks) { int fd, pi[2]; char buf[8] = {0}; ASSERT_SYS(0, 3, creat("db", 0644)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, pipe(pi)); SPAWN(fork); ASSERT_SYS(0, 5, open("db", O_RDWR)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 8, read(3, buf, 8)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, fcntl(5, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, close(5)); PARENT(); ASSERT_SYS(0, 0, close(3)); ASSERT_NE(-1, (fd = open("db", O_RDWR))); ASSERT_SYS(0, 0, fcntl(fd, F_SETLK, &(struct flock){ .l_type = F_WRLCK, .l_start = 0x40000000, .l_len = 1, })); ASSERT_SYS(0, 0, close(fd)); ASSERT_SYS(0, 8, write(4, buf, 8)); ASSERT_SYS(0, 0, close(4)); WAIT(exit, 0); }
6,475
169
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/reservefd_test.c
/*-*- 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 2022 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/internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/sigaction.h" #include "libc/errno.h" #include "libc/macros.internal.h" #include "libc/runtime/internal.h" #include "libc/runtime/stack.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/hyperion.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/tls.h" #include "libc/thread/wait0.internal.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" STATIC_YOINK("zip_uri_support"); STATIC_YOINK("libc/testlib/hyperion.txt"); #define THREADS 8 void SetUpOnce(void) { __enable_threads(); ASSERT_SYS(0, 0, pledge("stdio rpath", 0)); } void PullSomeZipFilesIntoLinkage(void) { gmtime(0); } TEST(reservefd, testGrowthOfFdsDataStructure) { int i, n; struct rlimit rlim; n = 1700; // pe '2**16/40' → 1638 (likely value of g_fds.n) if (!getrlimit(RLIMIT_NOFILE, &rlim)) n = MIN(n, rlim.rlim_cur - 3); for (i = 0; i < n; ++i) { EXPECT_SYS(0, i + 3, open("/zip/usr/share/zoneinfo/UTC", O_RDONLY)); } ASSERT_GT(g_fds.n, OPEN_MAX); for (i = 0; i < n; ++i) { EXPECT_SYS(0, 0, close(i + 3)); } } void OnSigAlrm(int sig, siginfo_t *si, void *ctx) { int rc, fd; char buf[64]; ASSERT_NE(-1, (fd = open("/zip/libc/testlib/hyperion.txt", O_RDONLY))); for (;;) { rc = read(fd, buf, 64); if (rc != -1) { ASSERT_EQ(64, rc); break; } else { ASSERT_EQ(EINTR, errno); errno = 0; } } ASSERT_EQ(0, memcmp(kHyperion, buf, 64)); close(fd); // can eintr which doesn't matter } int Worker(void *p, int tid) { char buf[64]; int i, rc, fd; for (i = 0; i < 64; ++i) { ASSERT_NE(-1, (fd = open("/zip/libc/testlib/hyperion.txt", O_RDONLY))); usleep(_rand64() % 100); for (;;) { rc = read(fd, buf, 64); if (rc != -1) { ASSERT_EQ(64, rc); break; } else { ASSERT_EQ(EINTR, errno); errno = 0; } } ASSERT_EQ(0, memcmp(kHyperion, buf, 64)); close(fd); } return 0; } TEST(reservefd, tortureTest) { int i; struct spawn th[THREADS]; struct sigaction oldsa; struct itimerval oldit; struct itimerval it = {{0, 10000}, {0, 100}}; struct sigaction sa = {.sa_sigaction = OnSigAlrm, .sa_flags = 0 /* SA_NODEFER */}; // ASSERT_SYS(0, 0, sigaction(SIGALRM, &sa, &oldsa)); // ASSERT_SYS(0, 0, setitimer(ITIMER_REAL, &it, &oldit)); for (i = 0; i < THREADS; ++i) _spawn(Worker, 0, th + i); for (i = 0; i < THREADS; ++i) _join(th + i); // EXPECT_SYS(0, 0, sigaction(SIGALRM, &oldsa, 0)); // EXPECT_SYS(0, 0, setitimer(ITIMER_REAL, &oldit, 0)); }
4,923
130
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/clock_getres_test.c
/*-*- 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 2022 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/timespec.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/clock.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" struct timespec ts; TEST(clock_getres, realtimeHasMillisecondPrecisionOrBetter) { ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 1000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, realtimeFastHasMillisecondPrecisionOrBetter) { ASSERT_EQ(0, clock_getres(CLOCK_REALTIME_FAST, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 1000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, realtimeCoarseHasMillisecondPrecisionOrBetter) { if (clock_getres(CLOCK_REALTIME_COARSE, &ts)) return; EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 100000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, realtimePreciseHasMillisecondPrecisionOrBetter) { if (clock_getres(CLOCK_REALTIME_PRECISE, &ts)) return; EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 100000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, monotonicHasMillisecondPrecisionOrBetter) { ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 1000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, monotonicFastHasMillisecondPrecisionOrBetter) { ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC_FAST, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 1000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, monotonicCoarseHasMillisecondPrecisionOrBetter) { if (clock_getres(CLOCK_MONOTONIC_COARSE, &ts)) return; EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 100000000); EXPECT_GT(ts.tv_nsec, 0); } TEST(clock_getres, monotonicPreciseHasMillisecondPrecisionOrBetter) { if (clock_getres(CLOCK_MONOTONIC_PRECISE, &ts)) return; EXPECT_EQ(0, ts.tv_sec); EXPECT_LT(ts.tv_nsec, 100000000); EXPECT_GT(ts.tv_nsec, 0); }
3,781
83
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/readansi_test.c
/*-*- 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/runtime/runtime.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" #include "libc/x/x.h" TEST(readansi, test) { char b[16]; const char *s; int ws, pid, fds[2]; ASSERT_NE(-1, pipe(fds)); ASSERT_NE(-1, (pid = fork())); if (!pid) { s = "a\eM\e[A→\e[123;456R\e[>c\eOz\xc2\x9bM"; write(fds[1], s, strlen(s)); _exit(0); } close(fds[1]); EXPECT_EQ(1, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("a", b); EXPECT_EQ(2, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\eM", b); EXPECT_EQ(3, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\e[A", b); EXPECT_EQ(3, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("→", b); EXPECT_EQ(10, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\e[123;456R", b); EXPECT_EQ(4, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\e[>c", b); EXPECT_EQ(3, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\eOz", b); EXPECT_EQ(3, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("\xc2\x9bM", b); EXPECT_EQ(0, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("", b); close(fds[0]); ASSERT_NE(-1, wait(&ws)); ASSERT_TRUE(WIFEXITED(ws)); ASSERT_EQ(0, WEXITSTATUS(ws)); } TEST(readansi, testOperatingSystemCommand) { char b[32]; const char *s; int ws, pid, fds[2]; s = "\e]rm -rf /\e\\"; ASSERT_NE(-1, pipe(fds)); ASSERT_NE(-1, (pid = fork())); if (!pid) { write(fds[1], s, strlen(s)); _exit(0); } close(fds[1]); EXPECT_EQ(strlen(s), readansi(fds[0], b, sizeof(b))); EXPECT_STREQ(s, b); EXPECT_EQ(0, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("", b); close(fds[0]); ASSERT_NE(-1, wait(&ws)); ASSERT_TRUE(WIFEXITED(ws)); ASSERT_EQ(0, WEXITSTATUS(ws)); } TEST(readansi, testSqueeze) { int fds[2]; char b[32]; const char *s = "\e\\"; ASSERT_NE(-1, pipe(fds)); write(fds[1], s, strlen(s)); close(fds[1]); EXPECT_EQ(strlen(s), readansi(fds[0], b, sizeof(b))); EXPECT_STREQ(s, b); EXPECT_EQ(0, readansi(fds[0], b, sizeof(b))); EXPECT_STREQ("", b); close(fds[0]); }
3,929
97
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/pipe_test.c
/*-*- 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 2022 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/rlimit.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/rlimit.h" #include "libc/testlib/testlib.h" int ws, pid, f[2]; char buf[6] = {0}; struct rlimit rlim = {0, 10}; TEST(pipe, efault) { EXPECT_SYS(EFAULT, -1, pipe(VEIL("r", (void *)0))); } TEST(pipe, einval) { EXPECT_SYS(EINVAL, -1, pipe2(f, -1)); } TEST(pipe, ebadf) { if (IsFreebsd()) return; // somehow succeeds if (IsOpenbsd()) return; // somehow succeeds EXPECT_SYS(0, 0, pipe(f)); EXPECT_SYS(EBADF, -1, write(f[0], "h", 1)); EXPECT_SYS(EBADF, -1, read(f[1], buf, 1)); EXPECT_SYS(0, 0, close(f[0])); EXPECT_SYS(0, 0, close(f[1])); } TEST(pipe, emfile) { if (IsWindows()) return; // TODO if (IsCygwin()) return; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_EQ(0, setrlimit(RLIMIT_NOFILE, &rlim)); ASSERT_SYS(EMFILE, -1, pipe(f)); _exit(0); } EXPECT_NE(-1, waitpid(pid, &ws, 0)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pipe, usesLowestFileNumbers) { EXPECT_SYS(0, 0, pipe(f)); EXPECT_SYS(0, 3, f[0]); EXPECT_SYS(0, 4, f[1]); EXPECT_SYS(0, 0, close(f[0])); EXPECT_SYS(0, 0, close(f[1])); } TEST(pipe, doesBuffering) { EXPECT_SYS(0, 0, pipe(f)); EXPECT_SYS(0, 5, write(f[1], "hello", 5)); EXPECT_SYS(0, 5, read(f[0], buf, 5)); EXPECT_STREQ("hello", buf); EXPECT_SYS(0, 0, close(f[0])); EXPECT_SYS(0, 0, close(f[1])); }
3,383
80
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/symlinkat_test.c
/*-*- 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 2022 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/stat.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/stdio/rand.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/s.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; char p[2][PATH_MAX]; struct stat st; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(symlink, enoent) { ASSERT_SYS(ENOENT, -1, symlink("o/foo", "")); ASSERT_SYS(ENOENT, -1, symlink("o/foo", "o/bar")); } TEST(symlinkat, enotdir) { ASSERT_SYS(0, 0, close(creat("yo", 0644))); ASSERT_SYS(ENOTDIR, -1, symlink("hrcue", "yo/there")); } TEST(symlinkat, test) { sprintf(p[0], "%s.%d", program_invocation_short_name, rand()); sprintf(p[1], "%s.%d", program_invocation_short_name, rand()); EXPECT_EQ(0, touch(p[0], 0644)); EXPECT_EQ(0, symlink(p[0], p[1])); // check the normal file EXPECT_FALSE(issymlink(p[0])); EXPECT_EQ(0, lstat(p[0], &st)); EXPECT_FALSE(S_ISLNK(st.st_mode)); // check the symlink file EXPECT_TRUE(issymlink(p[1])); EXPECT_EQ(0, lstat(p[1], &st)); EXPECT_TRUE(S_ISLNK(st.st_mode)); // symlink isn't a symlink if we use it normally EXPECT_EQ(0, stat(p[1], &st)); EXPECT_FALSE(S_ISLNK(st.st_mode)); }
3,185
69
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/clock_gettime_test.c
/*-*- 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 2022 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/clock_gettime.internal.h" #include "libc/calls/internal.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/calls/struct/timeval.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/clock.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" TEST(clock_gettime, fault) { ASSERT_SYS(EFAULT, -1, clock_gettime(0, 0)); } TEST(clock_gettime, test) { bool isfast; struct timespec ts = {0}; ASSERT_EQ(0, clock_gettime(0, &ts)); ASSERT_NE(0, ts.tv_sec); ASSERT_NE(0, ts.tv_nsec); #ifndef __aarch64__ // we support vdso on aarch64 but qemu-aarch64 won't let us test it if (__is_linux_2_6_23()) { ASSERT_GT((intptr_t)__clock_gettime_get(&isfast), getauxval(AT_SYSINFO_EHDR)); ASSERT_TRUE(isfast); } #endif } BENCH(clock_gettime, bench) { struct timeval tv; struct timespec ts; gettimeofday(&tv, 0); // trigger init clock_gettime(0, &ts); // trigger init EZBENCH2("nowl", donothing, nowl()); EZBENCH2("rdtsc", donothing, rdtsc()); EZBENCH2("gettimeofday", donothing, gettimeofday(&tv, 0)); EZBENCH2("timespec_real", donothing, timespec_real()); EZBENCH2("clock_gettime 0", donothing, clock_gettime(CLOCK_REALTIME_FAST, &ts)); EZBENCH2("clock_gettime 1", donothing, clock_gettime(CLOCK_MONOTONIC_FAST, &ts)); EZBENCH2("__clock_gettime 0", donothing, __clock_gettime(CLOCK_REALTIME_FAST, &ts)); EZBENCH2("__clock_gettime 1", donothing, __clock_gettime(CLOCK_MONOTONIC_FAST, &ts)); if (IsWindows()) { EZBENCH2("sys_clock_gettime 0", donothing, sys_clock_gettime_nt(CLOCK_REALTIME_FAST, &ts)); EZBENCH2("sys_clock_gettime 1", donothing, sys_clock_gettime_nt(CLOCK_MONOTONIC_FAST, &ts)); } else { EZBENCH2("sys_clock_gettime 0", donothing, sys_clock_gettime(CLOCK_REALTIME_FAST, &ts)); EZBENCH2("sys_clock_gettime 1", donothing, sys_clock_gettime(CLOCK_MONOTONIC_FAST, &ts)); } }
4,090
84
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/readlinkat_test.c
/*-*- 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/stat.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/mem/gc.internal.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/s.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(readlink, enoent) { char buf[32]; ASSERT_SYS(ENOENT, -1, readlink("doesnotexist", buf, 32)); ASSERT_SYS(ENOENT, -1, readlink("o/doesnotexist", buf, 32)); } TEST(readlink, enotdir) { char buf[32]; ASSERT_SYS(0, 0, touch("o", 0644)); ASSERT_SYS(ENOTDIR, -1, readlink("o/doesnotexist", buf, 32)); } TEST(readlinkat, test) { char buf[128], *p, *q; memset(buf, -1, sizeof(buf)); ASSERT_NE(-1, xbarf("hello→", "hi", -1)); ASSERT_STREQ("hi", gc(xslurp("hello→", 0))); ASSERT_NE(-1, symlink("hello→", "there→")); ASSERT_TRUE(isregularfile("hello→")); ASSERT_TRUE(issymlink("there→")); ASSERT_FALSE(isregularfile("there→")); ASSERT_SYS(0, 8, readlink("there→", buf, sizeof(buf))); EXPECT_EQ(255, buf[8] & 255); buf[8] = 0; EXPECT_STREQ("hello→", buf); p = gc(xjoinpaths(g_testlib_tmpdir, "hello→")); q = gc(realpath("there→", 0)); EXPECT_EQ(0, strcmp(p, q), "%`'s\n\t%`'s", p, q); } TEST(readlinkat, efault) { char buf[128]; ASSERT_SYS(EFAULT, -1, readlink(0, buf, sizeof(buf))); } TEST(readlinkat, notexist) { char buf[128]; ASSERT_SYS(ENOENT, -1, readlink("hi", buf, sizeof(buf))); } TEST(readlinkat, notalink) { char buf[128]; ASSERT_SYS(0, 0, close(creat("hi", 0644))); ASSERT_SYS(EINVAL, -1, readlink("hi", buf, sizeof(buf))); } TEST(readlinkat, frootloop) { int fd; char buf[128]; ASSERT_SYS(0, 0, symlink("froot", "froot")); ASSERT_SYS(ELOOP, -1, readlink("froot/loop", buf, sizeof(buf))); if (O_NOFOLLOW) { ASSERT_SYS(IsFreebsd() ? EMLINK : IsNetbsd() ? EFTYPE : ELOOP, -1, open("froot", O_RDONLY | O_NOFOLLOW)); if (0 && O_PATH) { /* need rhel5 test */ ASSERT_NE(-1, (fd = open("froot", O_RDONLY | O_NOFOLLOW | O_PATH))); ASSERT_NE(-1, close(fd)); } } } TEST(readlinkat, statReadsNameLength) { struct stat st; ASSERT_SYS(0, 0, symlink("froot", "froot")); ASSERT_SYS(0, 0, fstatat(AT_FDCWD, "froot", &st, AT_SYMLINK_NOFOLLOW)); EXPECT_TRUE(S_ISLNK(st.st_mode)); EXPECT_EQ(5, st.st_size); } TEST(readlinkat, realpathReturnsLongPath) { struct stat st; char buf[PATH_MAX]; if (!IsWindows()) return; if (!_startswith(getcwd(buf, PATH_MAX), "/c/")) return; ASSERT_SYS(0, 0, touch("froot", 0644)); ASSERT_STARTSWITH("/c/", realpath("froot", buf)); }
4,738
119
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/commandv_test.c
/*-*- 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/calls/calls.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/stat.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/check.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/dt.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" uint64_t i; char *oldpath; char tmp[PATH_MAX]; char pathbuf[PATH_MAX]; char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } void SetUp(void) { static int x; mkdir("bin", 0755); mkdir("home", 0755); oldpath = strdup(nulltoempty(getenv("PATH"))); CHECK_NE(-1, setenv("PATH", "bin", true)); } void TearDown(void) { CHECK_NE(-1, setenv("PATH", oldpath, true)); free(oldpath); } TEST(commandv, testPathSearch) { EXPECT_NE(-1, touch("bin/sh", 0755)); if (IsWindows()) { EXPECT_EQ(NULL, commandv("sh", pathbuf, sizeof(pathbuf))); EXPECT_EQ(errno, ENOENT); } else { EXPECT_STREQ("bin/sh", commandv("sh", pathbuf, sizeof(pathbuf))); } } TEST(commandv, testPathSearch_appendsComExtension) { EXPECT_NE(-1, touch("bin/sh.com", 0755)); EXPECT_STREQ("bin/sh.com", commandv("sh", pathbuf, sizeof(pathbuf))); } TEST(commandv, testSlashes_wontSearchPath_butChecksAccess) { EXPECT_NE(-1, touch("home/sh.com", 0755)); i = __syscount; EXPECT_STREQ("home/sh.com", commandv("home/sh.com", pathbuf, sizeof(pathbuf))); #ifdef __x86_64__ if (!IsWindows()) EXPECT_EQ(i + 2, __syscount); #endif } TEST(commandv, testSlashes_wontSearchPath_butStillAppendsComExtension) { EXPECT_NE(-1, touch("home/sh.com", 0755)); i = __syscount; EXPECT_STREQ("home/sh.com", commandv("home/sh", pathbuf, sizeof(pathbuf))); #ifdef __x86_64__ if (!IsWindows()) EXPECT_EQ(i + 3, __syscount); #endif } TEST(commandv, testSameDir_doesntHappenByDefaultUnlessItsWindows) { EXPECT_NE(-1, touch("bog.com", 0755)); if (IsWindows()) { EXPECT_STREQ("./bog.com", commandv("bog.com", pathbuf, sizeof(pathbuf))); } else { EXPECT_EQ(NULL, commandv("bog.com", pathbuf, sizeof(pathbuf))); EXPECT_EQ(errno, ENOENT); } } TEST(commandv, testSameDir_willHappenWithColonBlank) { CHECK_NE(-1, setenv("PATH", "bin:", true)); EXPECT_NE(-1, touch("bog.com", 0755)); if (IsWindows()) { EXPECT_STREQ("./bog.com", commandv("bog.com", pathbuf, sizeof(pathbuf))); } else { EXPECT_STREQ("bog.com", commandv("bog.com", pathbuf, sizeof(pathbuf))); } } TEST(commandv, testSameDir_willHappenWithColonBlank2) { CHECK_NE(-1, setenv("PATH", ":bin", true)); EXPECT_NE(-1, touch("bog.com", 0755)); if (IsWindows()) { EXPECT_STREQ("./bog.com", commandv("bog.com", pathbuf, sizeof(pathbuf))); } else { EXPECT_STREQ("bog.com", commandv("bog.com", pathbuf, sizeof(pathbuf))); } } TEST(commandv, test_DirPaths_wontConsiderDirectoriesExecutable) { CHECK_NE(-1, setenv("PATH", ":bin", true)); EXPECT_NE(-1, mkdir("Cursors", 0755)); EXPECT_EQ(NULL, commandv("Cursors", pathbuf, sizeof(pathbuf))); if (IsWindows()) { EXPECT_EQ(errno, ENOENT); } else { EXPECT_EQ(errno, EACCES); } } TEST(commandv, test_DirPaths_wontConsiderDirectoriesExecutable2) { CHECK_NE(-1, setenv("PATH", ":bin", true)); EXPECT_NE(-1, mkdir("this_is_a_directory.com", 0755)); EXPECT_EQ(NULL, commandv("this_is_a_directory.com", pathbuf, sizeof(pathbuf))); EXPECT_EQ(errno, EACCES); }
5,473
142
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/fexecve_test.c
/*-*- 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 2022 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/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/mfd.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" // clang-format off #ifdef __x86_64__ STATIC_YOINK("zip_uri_support"); int fds[2]; char buf[8]; char testlib_enable_tmp_setup_teardown; void SetUp(void) { if (IsFreebsd()) exit(0); // TODO: fixme on freebsd if (!__is_linux_2_6_23()) exit(0); // TODO: fixme on old linux } TEST(execve, elfIsUnreadable_mayBeExecuted) { if (IsWindows() || IsXnu()) return; testlib_extract("/zip/echo", "echo", 0111); ASSERT_SYS(0, 0, pipe2(fds, O_CLOEXEC)); SPAWN(vfork); ASSERT_SYS(0, 1, dup2(4, 1)); ASSERT_SYS( 0, 0, execve("echo", (char *const[]){"echo", "hi", 0}, (char *const[]){0})); notpossible; EXITS(0); bzero(buf, 8); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 3, read(3, buf, 7)); ASSERT_SYS(0, 0, close(3)); ASSERT_STREQ("hi\n", buf); } TEST(fexecve, elfIsUnreadable_mayBeExecuted) { if (!IsLinux() && !IsFreebsd()) return; testlib_extract("/zip/echo", "echo", 0111); ASSERT_SYS(0, 0, pipe2(fds, O_CLOEXEC)); SPAWN(vfork); ASSERT_SYS(0, 1, dup2(4, 1)); ASSERT_SYS(0, 5, open("echo", O_EXEC | O_CLOEXEC)); if (IsFreebsd()) ASSERT_SYS(0, 1, lseek(5, 1, SEEK_SET)); ASSERT_SYS(0, 0, fexecve(5, (char *const[]){"echo", "hi", 0}, (char *const[]){0})); notpossible; EXITS(0); bzero(buf, 8); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 3, read(3, buf, 7)); ASSERT_SYS(0, 0, close(3)); ASSERT_STREQ("hi\n", buf); } TEST(fexecve, memfd_create) { if (!IsLinux()) return; SPAWN(vfork); #define TINY_ELF_PROGRAM "\ \177\105\114\106\002\001\001\000\000\000\000\000\000\000\000\000\ \002\000\076\000\001\000\000\000\170\000\100\000\000\000\000\000\ \100\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\100\000\070\000\001\000\000\000\000\000\000\000\ \001\000\000\000\005\000\000\000\000\000\000\000\000\000\000\000\ \000\000\100\000\000\000\000\000\000\000\100\000\000\000\000\000\ \200\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\ \000\020\000\000\000\000\000\000\152\052\137\152\074\130\017\005" int fd = memfd_create("foo", MFD_CLOEXEC); if (fd == -1 && errno == ENOSYS) _Exit(42); write(fd, TINY_ELF_PROGRAM, sizeof(TINY_ELF_PROGRAM) - 1); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); } TEST(fexecve, APE) { if (!IsLinux() && !IsFreebsd()) return; testlib_extract("/zip/life-nomod.com", "life-nomod.com", 0555); SPAWN(fork); int fd = open("life-nomod.com", O_RDONLY); ASSERT_NE(-1, fd); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); } TEST(fexecve, APE_cloexec) { if (!IsLinux() && !IsFreebsd()) return; testlib_extract("/zip/life-nomod.com", "life-nomod.com", 0555); SPAWN(fork); int fd = open("life-nomod.com", O_RDONLY | O_CLOEXEC); ASSERT_NE(-1, fd); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); } TEST(fexecve, zipos) { if (!IsLinux() && !IsFreebsd()) return; int fd = open("/zip/life.elf", O_RDONLY); ASSERT_NE(-1, fd); SPAWN(fork); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); close(fd); } TEST(fexecve, ziposAPE) { if (!IsLinux() && !IsFreebsd()) return; int fd = open("/zip/life-nomod.com", O_RDONLY); ASSERT_NE(-1, fd); SPAWN(fork); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); close(fd); } TEST(fexecve, ziposAPEHasZipos) { if (!IsLinux() && !IsFreebsd()) return; int fd = open("/zip/zipread.com", O_RDONLY); SPAWN(fork); ASSERT_NE(-1, fd); if (fd == -1 && errno == ENOSYS) _Exit(42); fexecve(fd, (char *const[]){0}, (char *const[]){0}); EXITS(42); close(fd); } #endif /* __x86_64__ */
5,777
152
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/fcntl_test.c
/*-*- 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/flock.h" #include "libc/calls/struct/sigaction.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "libc/x/x.h" int Lock(int fd, int type, long start, long len) { int e; struct flock lock = { .l_type = type, .l_whence = SEEK_SET, .l_start = start, .l_len = len, }; e = errno; while (fcntl(fd, F_SETLK, &lock)) { if (errno == EAGAIN || errno == EACCES) { errno = e; continue; } else { return -1; } } return 0; } char testlib_enable_tmp_setup_teardown; TEST(fcntl_getfl, testRemembersAccessMode) { int fd; ASSERT_NE(-1, (fd = open("foo", O_CREAT | O_RDWR, 0644))); EXPECT_EQ(O_RDWR, fcntl(fd, F_GETFL) & O_ACCMODE); EXPECT_NE(-1, close(fd)); ASSERT_NE(-1, (fd = open("foo", O_WRONLY, 0644))); EXPECT_EQ(O_WRONLY, fcntl(fd, F_GETFL) & O_ACCMODE); EXPECT_NE(-1, close(fd)); } TEST(fcntl_setfl, testChangeAppendStatus) { if (IsWindows()) return; // Can't ReOpenFile() w/ O_APPEND char buf[8] = {0}; ASSERT_SYS(0, 3, open("foo", O_CREAT | O_WRONLY, 0644)); EXPECT_SYS(0, 3, write(3, "foo", 3)); EXPECT_SYS(0, 0, lseek(3, 0, SEEK_SET)); EXPECT_SYS(0, 0, fcntl(3, F_SETFL, O_APPEND)); EXPECT_SYS(0, 3, write(3, "bar", 3)); EXPECT_SYS(0, 0, lseek(3, 0, SEEK_SET)); EXPECT_SYS(0, 0, fcntl(3, F_SETFL, 0)); EXPECT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("foo", 0)); EXPECT_SYS(0, 6, read(3, buf, 6)); EXPECT_STREQ("foobar", buf); EXPECT_SYS(0, 0, close(3)); } TEST(fcntl, getfd) { ASSERT_SYS(0, 3, open("/dev/null", O_RDWR)); ASSERT_SYS(0, 0, fcntl(3, F_GETFD)); ASSERT_SYS(0, 4, open("/dev/null", O_RDWR | O_CLOEXEC)); ASSERT_SYS(0, FD_CLOEXEC, fcntl(4, F_GETFD)); ASSERT_SYS(0, 0, fcntl(4, F_SETFD, FD_CLOEXEC)); ASSERT_SYS(0, FD_CLOEXEC, fcntl(4, F_GETFD)); ASSERT_SYS(0, 0, fcntl(4, F_SETFD, 0)); ASSERT_SYS(0, 0, fcntl(4, F_GETFD)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(fcntl, F_DUPFD_CLOEXEC) { ASSERT_SYS(0, 3, open("/dev/null", O_RDWR)); ASSERT_SYS(0, 5, fcntl(3, F_DUPFD_CLOEXEC, 5)); ASSERT_SYS(0, FD_CLOEXEC, fcntl(5, F_GETFD)); ASSERT_SYS(0, 0, close(5)); ASSERT_SYS(0, 0, close(3)); } void OnSig(int sig) { } TEST(posixAdvisoryLocks, twoProcesses) { if (IsWindows()) return; // due to signals if (IsNetbsd()) return; // TODO: why does sigusr1 kill runitd? int ws, pid; struct flock lock; sigset_t ss, oldss; struct sigaction oldsa; struct sigaction sa = {.sa_handler = OnSig}; ASSERT_SYS(0, 0, sigemptyset(&ss)); ASSERT_SYS(0, 0, sigaddset(&ss, SIGUSR1)); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &ss, &oldss)); ASSERT_SYS(0, 0, sigdelset(&ss, SIGUSR1)); ASSERT_SYS(0, 0, sigaction(SIGUSR1, &sa, &oldsa)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 3, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, write(3, "hello", 5)); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 1; lock.l_len = 3; lock.l_pid = -2; ASSERT_SYS(0, 0, fcntl(3, F_SETLK, &lock)); EXPECT_EQ(F_WRLCK, lock.l_type); EXPECT_EQ(SEEK_SET, lock.l_whence); EXPECT_EQ(1, lock.l_start); EXPECT_EQ(3, lock.l_len); EXPECT_EQ(-2, lock.l_pid); ASSERT_SYS(0, 0, kill(getppid(), SIGUSR1)); ASSERT_SYS(EINTR, -1, sigsuspend(&ss)); _Exit(0); } ASSERT_SYS(EINTR, -1, sigsuspend(&ss)); ASSERT_SYS(0, 3, open("foo", O_RDWR)); // try lock lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = -1; ASSERT_SYS(EAGAIN, -1, fcntl(3, F_SETLK, &lock)); // get lock information lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = -1; ASSERT_SYS(0, 0, fcntl(3, F_GETLK, &lock)); EXPECT_EQ(F_WRLCK, lock.l_type); EXPECT_EQ(SEEK_SET, lock.l_whence); EXPECT_EQ(1, lock.l_start); EXPECT_EQ(3, lock.l_len); EXPECT_EQ(pid, lock.l_pid); // get lock information lock.l_type = F_RDLCK; lock.l_whence = SEEK_END; lock.l_start = -3; lock.l_len = 0; lock.l_pid = -1; ASSERT_SYS(0, 0, fcntl(3, F_GETLK, &lock)); EXPECT_EQ(F_WRLCK, lock.l_type); EXPECT_EQ(SEEK_SET, lock.l_whence); EXPECT_EQ(1, lock.l_start); EXPECT_EQ(3, lock.l_len); EXPECT_EQ(pid, lock.l_pid); // get lock information lock.l_type = F_RDLCK; lock.l_whence = SEEK_END; lock.l_start = -1; lock.l_len = 0; lock.l_pid = -1; ASSERT_SYS(0, 0, fcntl(3, F_GETLK, &lock)); EXPECT_EQ(F_UNLCK, lock.l_type); EXPECT_EQ(SEEK_END, lock.l_whence); EXPECT_EQ(-1, lock.l_start); EXPECT_EQ(0, lock.l_len); EXPECT_EQ(-1, lock.l_pid); ASSERT_SYS(0, 0, kill(pid, SIGUSR1)); EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, sigaction(SIGUSR1, &oldsa, 0)); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &oldss, 0)); }
7,108
200
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/diagnose_syscall_test.c
/*-*- 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 2022 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/ucontext.h" #include "libc/dce.h" #include "libc/intrin/kprintf.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/stdio/append.h" #include "libc/str/str.h" #include "libc/sysv/consts/nr.h" #include "libc/testlib/testlib.h" #ifdef __x86_64__ #define Z 0x5555555555555555 #define FLAGS_cf 0 #define FLAGS_pf 2 #define FLAGS_sf 7 #define FLAGS_of 11 intptr_t diagnose_syscall(intptr_t nr, // intptr_t arg1, // intptr_t arg2, // intptr_t arg3, // intptr_t arg4, // intptr_t arg5, // intptr_t arg6, // intptr_t arg7, // ucontext_t *before, // ucontext_t *after); // #define GREG(FIELD) \ do { \ uint64_t f1 = x->uc_mcontext.FIELD; \ uint64_t f2 = y->uc_mcontext.FIELD; \ if (f1 != f2) { \ if (b) appendw(&b, ' '); \ appends(&b, #FIELD); \ kprintf("%3s %016lx → %016lx\n", #FIELD, f1, f2); \ } \ } while (0) #define FLAG(FLAG) \ if ((x->uc_mcontext.eflags & (1ul << FLAGS_##FLAG)) ^ \ (y->uc_mcontext.eflags & (1ul << FLAGS_##FLAG))) { \ if (b) appendw(&b, ' '); \ appends(&b, #FLAG); \ } char *DiffContexts(ucontext_t *x, ucontext_t *y) { char *b = 0; GREG(rax); GREG(rdx); GREG(rdi); GREG(rsi); GREG(rcx); GREG(r8); GREG(r9); GREG(r10); GREG(r11); GREG(r12); GREG(r13); GREG(r14); GREG(r15); GREG(rbx); GREG(rbp); FLAG(cf); FLAG(sf); FLAG(of); FLAG(pf); return b; } void SetUp(void) { if (IsWindows()) { exit(0); } } TEST(diagnose_syscall, getpid) { ucontext_t x, y; diagnose_syscall(__NR_getpid, Z, Z, Z, Z, Z, Z, Z, &x, &y); if (IsFreebsd()) { ASSERT_STREQ("rax rcx r8 r9 r10 r11", _gc(DiffContexts(&x, &y))); } else if (IsNetbsd() || IsXnu()) { // netbsd puts parent pid in edx // xnu seems to just clobber it! ASSERT_STREQ("rax rdx rcx r11", _gc(DiffContexts(&x, &y))); } else if (IsWsl1()) { // XXX: WSL1 must be emulating SYSCALL instructions. ASSERT_STREQ("rax rcx", _gc(DiffContexts(&x, &y))); } else { ASSERT_STREQ("rax rcx r11", _gc(DiffContexts(&x, &y))); } } TEST(diagnose_syscall, testWriteSuccess) { ucontext_t x, y; diagnose_syscall(__NR_write, 2, Z, 0, Z, Z, Z, Z, &x, &y); if (IsFreebsd()) { ASSERT_STREQ("rax rcx r8 r9 r10 r11", _gc(DiffContexts(&x, &y))); } else if (IsWsl1()) { // XXX: WSL1 must be emulating SYSCALL instructions. ASSERT_STREQ("rax rcx", _gc(DiffContexts(&x, &y))); } else { ASSERT_STREQ("rax rcx r11", _gc(DiffContexts(&x, &y))); } } TEST(diagnose_syscall, testWriteFailed) { ucontext_t x, y; diagnose_syscall(__NR_write, -1, Z, Z, Z, Z, Z, Z, &x, &y); if (IsFreebsd()) { ASSERT_STREQ("rax rcx r8 r9 r10 r11 cf", _gc(DiffContexts(&x, &y))); } else if (IsBsd()) { ASSERT_STREQ("rax rcx r11 cf", _gc(DiffContexts(&x, &y))); } else if (IsWsl1()) { // XXX: WSL1 must be emulating SYSCALL instructions. ASSERT_STREQ("rax rcx", _gc(DiffContexts(&x, &y))); } else { ASSERT_STREQ("rax rcx r11", _gc(DiffContexts(&x, &y))); } } #endif /* __x86_64__ */
5,558
144
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/life.c
/*-*- 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 2022 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ int main(int argc, char *argv[]) { return 42; }
1,887
23
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/lock_test.c
/*-*- 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 2022 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/flock.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" /** * @fileoverview POSIX Advisory Locks Test */ #define PROCESSES 8 #define THREADS 0 // <-- consider F_OFD_* locks #define RATIO 3 #define ITERATIONS 10 char testlib_enable_tmp_setup_teardown; _Thread_local const char *kind; void Log(const char *fmt, ...) { #if 0 va_list va; char b[512]; int i, n = sizeof(b); va_start(va, fmt); i = ksnprintf(b, n, "%s pid=%d tid=%d ", kind, getpid(), gettid()); i += kvsnprintf(b + i, MAX(0, n - i), fmt, va); i += ksnprintf(b + i, MAX(0, n - i), "\n"); write(2, b, MIN(i, n)); va_end(va); #endif } void Lock(int fd, int type, long start, long len) { int e; struct flock lock = { .l_type = type, .l_whence = SEEK_SET, .l_start = start, .l_len = len, }; e = errno; while (fcntl(fd, F_SETLK, &lock)) { ASSERT_TRUE(errno == EAGAIN || errno == EACCES); errno = e; Log("flock spinning on %d", fd); } } void WriteLock(int fd, long start, long len) { Lock(fd, F_WRLCK, start, len); Log("acquired write lock on %d", fd); } void ReadLock(int fd, long start, long len) { Lock(fd, F_RDLCK, start, len); Log("acquired read lock on %d", fd); } void Unlock(int fd, long start, long len) { Lock(fd, F_UNLCK, start, len); Log("released lock on %d", fd); } void *Reader(void *arg) { int i, j, fd; char buf[10]; kind = arg; ASSERT_NE(-1, (fd = open("db", O_RDONLY))); for (j = 0; j < ITERATIONS; ++j) { ReadLock(fd, 10, 10); for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pread(fd, buf + i, 1, 10 + i)); ASSERT_EQ(buf[0], buf[i]); } Unlock(fd, 10, 10); sched_yield(); } ASSERT_SYS(0, 0, close(fd)); return 0; } void *Writer(void *arg) { int i, j, fd; char buf[10]; kind = arg; ASSERT_NE(-1, (fd = open("db", O_RDWR))); for (j = 0; j < ITERATIONS; ++j) { WriteLock(fd, 10, 10); for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pread(fd, buf + i, 1, 10 + i)); ASSERT_EQ(buf[0], buf[i]); } for (i = 0; i < 10; ++i) { buf[i]++; } for (i = 0; i < 10; ++i) { ASSERT_SYS(0, 1, pwrite(fd, buf + i, 1, 10 + i)); } Unlock(fd, 10, 10); sched_yield(); } ASSERT_SYS(0, 0, close(fd)); return 0; } TEST(posixAdvisoryLocks, threadsAndProcessesFightingForLock) { int i, rc, pid, fd, ws; pthread_t th[THREADS + 1]; ASSERT_SYS(0, 3, creat("db", 0644)); ASSERT_SYS(0, 0, ftruncate(3, 30)); ASSERT_SYS(0, 0, close(3)); for (i = 0; i < THREADS; ++i) { if (i % RATIO == 0) { ASSERT_EQ(0, pthread_create(th + i, 0, Reader, "reader thread")); } else { ASSERT_EQ(0, pthread_create(th + i, 0, Writer, "writer thread")); } } for (i = 0; i < PROCESSES; ++i) { ASSERT_NE(-1, (rc = fork())); if (!rc) { if (i % RATIO == 0) { Writer("writer process"); } else { Reader("reader process"); } _Exit(0); } } ASSERT_NE(-1, (fd = open("db", O_RDWR))); Lock(fd, F_WRLCK, 0, 10); Lock(fd, F_WRLCK, 20, 10); for (i = 0; i < THREADS; ++i) { ASSERT_EQ(0, pthread_join(th[i], 0)); } kind = "main process"; for (;;) { int e = errno; if ((pid = waitpid(0, &ws, 0)) != -1) { if (WIFSIGNALED(ws)) { Log("process %d terminated with %G", pid, WTERMSIG(ws)); testlib_incrementfailed(); } else if (WEXITSTATUS(ws)) { Log("process %d exited with %d", pid, WEXITSTATUS(ws)); testlib_incrementfailed(); } } else { ASSERT_EQ(ECHILD, errno); errno = e; break; } } ASSERT_SYS(0, 0, close(fd)); }
5,762
187
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/openbsd_test.c
/*-*- 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 2022 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/pledge.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/kprintf.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void CheckPlatform(void) { if (IsOpenbsd()) return; if (__is_linux_2_6_23()) return; kprintf("skipping openbsd_test\n"); exit(0); } void SetUp(void) { CheckPlatform(); } TEST(pledge, promisedSyscallsCanBeCalled_ieEnosysIsIgnored) { SPAWN(fork); EXPECT_SYS(0, 0, pledge("stdio", 0)); EXPECT_SYS(0, 0, read(0, 0, 0)); EXITS(0); } TEST(unveil, pathBecomeVisible_ieEnosysIsIgnored) { SPAWN(fork); EXPECT_SYS(0, 0, touch("foo", 0644)); EXPECT_SYS(0, 0, unveil("foo", "r")); EXPECT_SYS(0, 0, unveil(0, 0)); EXPECT_SYS(0, 3, open("foo", O_RDONLY)); EXITS(0); }
2,738
56
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/pread_test.c
/*-*- 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 2022 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/sysv/consts/o.h" #include "libc/testlib/testlib.h" int fd; char buf[8]; char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(pread, testReadPastEof_returnsZero) { EXPECT_NE(-1, (fd = open("a", O_RDWR | O_CREAT | O_TRUNC, 0644))); EXPECT_EQ(0, pread(fd, buf, 8, 0)); EXPECT_EQ(0, close(fd)); } TEST(pread, testReadOverlapsEof_returnsShortNumber) { EXPECT_NE(-1, (fd = open("b", O_RDWR | O_CREAT | O_TRUNC, 0644))); EXPECT_EQ(4, pwrite(fd, buf, 4, 0)); EXPECT_EQ(4, pread(fd, buf, 8, 0)); EXPECT_EQ(0, close(fd)); }
2,494
43
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/execve_test.c
/*-*- 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 2022 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/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/intrin/kprintf.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #ifdef __x86_64__ #define N 16 char *GenBuf(char buf[8], int x) { int i; bzero(buf, 8); for (i = 0; i < 7; ++i) { buf[i] = x & 127; // nt doesn't respect invalid unicode? x >>= 1; } return buf; } __attribute__((__constructor__)) static void init(void) { char buf[8]; if (__argc == 4 && !strcmp(__argv[1], "-")) { ASSERT_STREQ(GenBuf(buf, atoi(__argv[2])), __argv[3]); exit(0); } } TEST(execve, testArgPassing) { int i; char ibuf[12], buf[8]; for (i = 0; i < N; ++i) { FormatInt32(ibuf, i); GenBuf(buf, i); SPAWN(vfork); execve(GetProgramExecutableName(), (char *const[]){GetProgramExecutableName(), "-", ibuf, buf, 0}, (char *const[]){0}); kprintf("execve failed: %m\n"); EXITS(0); } } TEST(execve, ziposELF) { if (IsFreebsd()) return; // TODO: fixme on freebsd if (!__is_linux_2_6_23()) return; // TODO: fixme on old linux if (!IsLinux() && !IsFreebsd()) { EXPECT_SYS(ENOSYS, -1, execve("/zip/life.elf", (char *const[]){0}, (char *const[]){0})); return; } SPAWN(fork); execve("/zip/life.elf", (char *const[]){0}, (char *const[]){0}); kprintf("execve failed: %m\n"); EXITS(42); } TEST(execve, ziposAPE) { if (IsFreebsd()) return; // TODO: fixme on freebsd if (!__is_linux_2_6_23()) return; // TODO: fixme on old linux if (!IsLinux() && !IsFreebsd()) { EXPECT_EQ(-1, execve("/zip/life-nomod.com", (char *const[]){0}, (char *const[]){0})); return; } SPAWN(fork); execve("/zip/life-nomod.com", (char *const[]){0}, (char *const[]){0}); kprintf("execve failed: %m\n"); EXITS(42); } #endif
3,873
97
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/setitimer_test.c
/*-*- 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 2022 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/itimerval.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/ucontext.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" bool gotsig; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio", 0)); } void OnSigAlrm(int sig, siginfo_t *si, void *ctx) { EXPECT_EQ(SIGALRM, sig); EXPECT_EQ(SIGALRM, si->si_signo); gotsig = true; } TEST(setitimer, testSingleShot) { sigset_t block, oldmask; struct sigaction oldalrm; struct itimerval it = {{0, 0}, {0, 10000}}; struct sigaction sa = {.sa_sigaction = OnSigAlrm, .sa_flags = SA_RESETHAND | SA_SIGINFO}; gotsig = false; sigemptyset(&block); sigaddset(&block, SIGALRM); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &block, &oldmask)); ASSERT_EQ(0, sigaction(SIGALRM, &sa, &oldalrm)); ASSERT_EQ(0, setitimer(ITIMER_REAL, &it, 0)); sigdelset(&block, SIGALRM); EXPECT_EQ(-1, sigsuspend(&block)); EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &oldmask, 0)); EXPECT_EQ(0, sigaction(SIGUSR1, &oldalrm, 0)); EXPECT_EQ(true, gotsig); }
3,157
62
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/renameat_test.c
/*-*- 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/errno.h" #include "libc/sysv/consts/at.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(rename, enoent) { EXPECT_SYS(ENOENT, -1, rename("foo", "")); EXPECT_SYS(ENOENT, -1, rename("", "foo")); EXPECT_SYS(ENOENT, -1, rename("foo", "o/bar")); EXPECT_SYS(ENOENT, -1, rename("o/bar", "foo")); } TEST(renameat, enotdir) { EXPECT_SYS(0, 0, close(creat("yo", 0644))); EXPECT_SYS(ENOTDIR, -1, rename("yo/there", "hrcue")); // this test makes platforms crazy // EXPECT_SYS(ENOTDIR, -1, rename("zoo", "yo/there")); } TEST(renameat, testNull_returnsEfault) { ASSERT_SYS(0, 0, close(creat("hello", 0644))); EXPECT_SYS(EFAULT, -1, renameat(AT_FDCWD, 0, AT_FDCWD, 0)); EXPECT_SYS(EFAULT, -1, renameat(AT_FDCWD, 0, AT_FDCWD, "hello")); EXPECT_SYS(EFAULT, -1, renameat(AT_FDCWD, "hello", AT_FDCWD, 0)); } TEST(renameat, test) { ASSERT_SYS(0, 0, close(creat("first", 0644))); EXPECT_TRUE(fileexists("first")); EXPECT_TRUE(!fileexists("second")); EXPECT_SYS(0, 0, renameat(AT_FDCWD, "first", AT_FDCWD, "second")); EXPECT_TRUE(!fileexists("first")); EXPECT_TRUE(fileexists("second")); }
3,134
60
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/mkntenvblock_test.c
/*-*- 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/calls/ntspawn.h" #include "libc/mem/gc.internal.h" #include "libc/testlib/testlib.h" char tmp[ARG_MAX]; char16_t envvars[ARG_MAX / 2]; TEST(mkntenvblock, emptyList_onlyOutputsDoubleNulStringTerminator) { char *envp[] = {NULL}; ASSERT_NE(-1, mkntenvblock(envvars, envp, NULL, tmp)); ASSERT_BINEQ(u"  ", envvars); } TEST(mkntenvblock, envp_becomesSortedDoubleNulTerminatedUtf16String) { char *envp[] = {"u=b", "c=d", "韩=非", "uh=d", "hduc=d", NULL}; ASSERT_NE(-1, mkntenvblock(envvars, envp, NULL, tmp)); ASSERT_BINEQ(u"C = d   " u"H D U C = d   " u"U = b   " u"U H = d   " u"Θù= ^ù  " u"  ", envvars); } TEST(mkntenvblock, extraVar_getsAdded) { char *envp[] = {"u=b", "c=d", "韩=非", "uh=d", "hduc=d", NULL}; ASSERT_NE(-1, mkntenvblock(envvars, envp, "a=a", tmp)); ASSERT_BINEQ(u"A = a   " u"C = d   " u"H D U C = d   " u"U = b   " u"U H = d   " u"Θù= ^ù  " u"  ", envvars); } TEST(mkntenvblock, pathvars_getUpdated) { char *envp[] = {"PATH=/c/foo:/d/bar", NULL}; ASSERT_NE(-1, mkntenvblock(envvars, envp, 0, tmp)); ASSERT_BINEQ(u"P A T H = c : \\ f o o ; d : \\ b a r   " u"  ", envvars); }
3,294
64
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/clock_nanosleep_test.c
/*-*- 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 2022 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/itimerval.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/timespec.h" #include "libc/errno.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/time/time.h" void OnAlrm(int sig) { // do nothing STRACE("OnAlrm()"); } TEST(nanosleep, testFault) { EXPECT_SYS(EFAULT, -1, nanosleep(0, 0)); } TEST(nanosleep, testInvalid) { struct timespec ts = {0, -1}; EXPECT_SYS(EINVAL, -1, nanosleep(&ts, 0)); } TEST(nanosleep, testNoSignalIsDelivered) { struct timespec ts = {0, 1}; ASSERT_SYS(0, 0, nanosleep(&ts, &ts)); ASSERT_SYS(0, 0, nanosleep(&ts, 0)); } TEST(nanosleep, testInterrupt_remIsUpdated) { struct sigaction sa = { .sa_handler = OnAlrm, .sa_flags = SA_RESETHAND, }; ASSERT_SYS(0, 0, sigaction(SIGALRM, &sa, 0)); struct itimerval it = {{0, 0}, {0, 100000}}; // 100ms singleshot ASSERT_SYS(0, 0, setitimer(ITIMER_REAL, &it, 0)); struct timespec ts = {500, 0}; ASSERT_SYS(EINTR, -1, nanosleep(&ts, &ts)); ASSERT_LT(ts.tv_sec, 500); ASSERT_GT(ts.tv_sec, 400); ASSERT_NE(0, ts.tv_nsec); } TEST(clock_nanosleep, testNoSignalIsDelivered) { struct timespec ts = {0, 1}; ASSERT_EQ(0, clock_nanosleep(CLOCK_REALTIME, 0, &ts, &ts)); ASSERT_EQ(0, clock_nanosleep(CLOCK_REALTIME, 0, &ts, 0)); } TEST(clock_nanosleep, testInterrupt_remIsUpdated) { struct sigaction sa = { .sa_handler = OnAlrm, .sa_flags = SA_RESETHAND, }; ASSERT_SYS(0, 0, sigaction(SIGALRM, &sa, 0)); struct itimerval it = {{0, 0}, {0, 100000}}; // 100ms singleshot ASSERT_SYS(0, 0, setitimer(ITIMER_REAL, &it, 0)); struct timespec ts = {500, 0}; ASSERT_EQ(EINTR, clock_nanosleep(CLOCK_REALTIME, 0, &ts, &ts)); ASSERT_LT(ts.tv_sec, 500); ASSERT_GT(ts.tv_sec, 400); ASSERT_NE(0, ts.tv_nsec); }
3,887
88
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/mkntpath_test.c
/*-*- 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/calls/internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/mem/gc.internal.h" #include "libc/testlib/testlib.h" char16_t p[PATH_MAX]; TEST(mkntpath, testEmpty) { EXPECT_EQ(0, __mkntpath("", p)); EXPECT_STREQ(u"", p); } TEST(mkntpath, testSlashes) { /* * The Windows command prompt works fine with all reasonable * unix-style paths. There only seems to be one exception, and that's * all it takes to make the feature entirely useless to us, similar to * the law of noncontradiction. We address the issue as follows: */ EXPECT_EQ(9, __mkntpath("o/foo.com", p)); EXPECT_STREQ(u"o\\foo.com", p); } TEST(mkntpath, testUnicode) { EXPECT_EQ(20, __mkntpath("C:\\𐌰𐌱𐌲𐌳\\𐌴𐌵𐌶𐌷", p)); EXPECT_STREQ(u"C:\\𐌰𐌱𐌲𐌳\\𐌴𐌵𐌶𐌷", p); } TEST(mkntpath, testRemoveDoubleSlash) { EXPECT_EQ(21, __mkntpath("C:\\Users\\jart\\\\.config", p)); EXPECT_STREQ(u"C:\\Users\\jart\\.config", p); }
2,821
51
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/open_test.c
/*-*- 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/calls/calls.h" #include "libc/calls/internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } TEST(open, efault) { ASSERT_SYS(EFAULT, -1, open(0, O_RDONLY)); if (IsWindows() || !IsAsan()) return; // not possible ASSERT_SYS(EFAULT, -1, open((void *)77, O_RDONLY)); } TEST(open, enoent) { ASSERT_SYS(ENOENT, -1, open("", O_RDONLY)); ASSERT_SYS(ENOENT, -1, open("doesnotexist", O_RDONLY)); ASSERT_SYS(ENOENT, -1, open("o/doesnotexist", O_RDONLY)); } TEST(open, enotdir) { ASSERT_SYS(0, 0, touch("o", 0644)); ASSERT_SYS(ENOTDIR, -1, open("o/doesnotexist", O_RDONLY)); } TEST(open, eexist) { ASSERT_SYS(0, 0, touch("exists", 0644)); ASSERT_SYS(EEXIST, -1, open("exists", O_WRONLY | O_CREAT | O_EXCL, 0644)); } TEST(open, doubleSlash_worksAndGetsNormalizedOnWindows) { ASSERT_SYS(0, 0, mkdir("o", 0755)); ASSERT_SYS(0, 3, open(gc(xjoinpaths(gc(getcwd(0, 0)), "o//deleteme")), O_WRONLY | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 0, close(3)); } TEST(open, enametoolong) { size_t n = 260; char *s = gc(xcalloc(1, n + 1)); memset(s, 'J', n); ASSERT_SYS(ENAMETOOLONG, -1, creat(s, 0644)); } TEST(open, testSpaceInFilename) { char buf[8] = {0}; ASSERT_SYS(0, 0, xbarf("hello txt", "hello", -1)); ASSERT_SYS(0, 3, open("hello txt", O_WRONLY)); EXPECT_SYS(0, 1, write(3, "H", 1)); EXPECT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("hello txt", O_RDONLY)); EXPECT_SYS(0, 5, read(3, buf, 7)); EXPECT_STREQ("Hello", buf); EXPECT_SYS(0, 0, close(3)); } TEST(open, testOpenExistingForWriteOnly_seeksToStart) { char buf[8] = {0}; ASSERT_SYS(0, 0, xbarf("hello.txt", "hello", -1)); ASSERT_SYS(0, 3, open("hello.txt", O_WRONLY)); EXPECT_SYS(0, 1, write(3, "H", 1)); EXPECT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("hello.txt", O_RDONLY)); EXPECT_SYS(0, 5, read(3, buf, 7)); EXPECT_STREQ("Hello", buf); EXPECT_SYS(0, 0, close(3)); } TEST(open, testOpenExistingForReadWrite_seeksToStart) { char buf[8] = {0}; ASSERT_SYS(0, 0, xbarf("hello.txt", "hello", -1)); ASSERT_SYS(0, 3, open("hello.txt", O_RDWR)); EXPECT_SYS(0, 1, write(3, "H", 1)); EXPECT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("hello.txt", O_RDONLY)); EXPECT_SYS(0, 5, read(3, buf, 7)); EXPECT_STREQ("Hello", buf); EXPECT_SYS(0, 0, close(3)); } TEST(open, testOpenExistingForAppendWriteOnly_seeksToEnd) { char buf[16] = {0}; ASSERT_SYS(0, 0, xbarf("hello.txt", "hell", -1)); ASSERT_SYS(0, 3, open("hello.txt", O_WRONLY | O_APPEND)); EXPECT_SYS(0, 1, write(3, "o", 1)); EXPECT_SYS(0, 0, lseek(3, 0, SEEK_SET)); EXPECT_SYS(0, 1, write(3, "!", 1)); EXPECT_SYS(0, 0, close(3)); ASSERT_SYS(0, 3, open("hello.txt", O_RDONLY)); EXPECT_SYS(0, 6, read(3, buf, 8)); EXPECT_STREQ("hello!", buf); EXPECT_SYS(0, 0, close(3)); } TEST(open, testRelativePath_opensRelativeToDirFd) { ASSERT_SYS(0, 0, mkdir("foo", 0755)); ASSERT_SYS(0, 3, open("foo", O_RDONLY | O_DIRECTORY)); EXPECT_SYS(0, 4, openat(3, "bar", O_WRONLY | O_TRUNC | O_CREAT, 0755)); EXPECT_TRUE(fileexists("foo/bar")); EXPECT_SYS(0, 0, close(4)); EXPECT_SYS(0, 0, close(3)); } int CountFds(void) { int i, count; for (count = i = 0; i < g_fds.n; ++i) { if (g_fds.p[i].kind) { ++count; } } return count; } TEST(open, lotsOfFds) { if (!IsWindows()) return; int i, n = 200; ASSERT_SYS(0, 0, xbarf("hello.txt", "hello", -1)); for (i = 3; i < n; ++i) { EXPECT_EQ(i, CountFds()); EXPECT_SYS(0, i, open("hello.txt", O_RDONLY)); } for (i = 3; i < n; ++i) { EXPECT_SYS(0, 0, close(i)); } }
5,751
154
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/makedirs_test.c
/*-*- 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 2022 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/errno.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "libc/x/x.h" TEST(makedirs, empty) { ASSERT_SYS(ENOENT, -1, makedirs("", 0755)); } TEST(makedirs, isfile) { ASSERT_SYS(0, 0, xbarf("f", "hi", -1)); ASSERT_SYS(EEXIST, -1, makedirs("f", 0755)); } TEST(makedirs, isdir) { ASSERT_SYS(0, 0, mkdir("d", 0755)); ASSERT_SYS(0, 0, makedirs("d", 0755)); } TEST(makedirs, enotdir) { ASSERT_SYS(0, 0, xbarf("f", "hi", -1)); ASSERT_SYS(ENOTDIR, -1, makedirs("f/d", 0755)); } TEST(makedirs, basic) { ASSERT_SYS(0, 0, makedirs("a/b/c", 0755)); ASSERT_TRUE(isdirectory("a/b/c")); ASSERT_SYS(0, 0, makedirs("a/b/c/d/e/", 0755)); ASSERT_SYS(0, 0, makedirs("a/b/c/d/e/", 0755)); ASSERT_TRUE(isdirectory("a/b/c/d/e")); } #define DIR \ "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/A/B/C/D/E/F/G/H/I/J/K/" \ "L/M/N/O/P/Q/R/S/T/U/V/W/X/Y/Z" pthread_barrier_t barrier; char testlib_enable_tmp_setup_teardown; int Worker(void *arg, int tid) { pthread_barrier_wait(&barrier); ASSERT_EQ(0, makedirs(DIR, 0755)); return 0; } TEST(makedirs, test) { int i, n = 8; struct spawn *t = gc(malloc(sizeof(struct spawn) * n)); ASSERT_EQ(0, pthread_barrier_init(&barrier, 0, n)); for (i = 0; i < n; ++i) ASSERT_SYS(0, 0, _spawn(Worker, 0, t + i)); for (i = 0; i < n; ++i) EXPECT_SYS(0, 0, _join(t + i)); ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); }
3,453
76
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sigprocmask_test.c
/*-*- 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 2022 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/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" volatile int n; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio proc", 0)); } void OnSig(int sig, siginfo_t *si, void *ctx) { ++n; } TEST(sigprocmask, testMultipleBlockedDeliveries) { int pid, ws; sigset_t neu, old; struct sigaction oldusr1, oldusr2; struct sigaction sa = {.sa_sigaction = OnSig, .sa_flags = SA_SIGINFO}; n = 0; sigemptyset(&neu); sigaddset(&neu, SIGUSR1); sigaddset(&neu, SIGUSR2); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &neu, &old)); ASSERT_EQ(0, sigaction(SIGUSR1, &sa, &oldusr1)); ASSERT_EQ(0, sigaction(SIGUSR2, &sa, &oldusr2)); ASSERT_EQ(0, raise(SIGUSR1)); ASSERT_EQ(0, raise(SIGUSR2)); EXPECT_EQ(0, n); EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &old, NULL)); EXPECT_EQ(0, sigaction(SIGUSR1, &oldusr1, 0)); EXPECT_EQ(0, sigaction(SIGUSR2, &oldusr2, 0)); ASSERT_EQ(2, n); } TEST(sigprocmask, testMultipleBlockedDeliveriesOfSameSignal) { int pid, ws; sigset_t neu, old; struct sigaction oldusr2; struct sigaction sa = {.sa_sigaction = OnSig, .sa_flags = SA_SIGINFO}; n = 0; sigemptyset(&neu); sigaddset(&neu, SIGUSR2); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &neu, &old)); ASSERT_EQ(0, sigaction(SIGUSR2, &sa, &oldusr2)); ASSERT_EQ(0, raise(SIGUSR2)); ASSERT_EQ(0, raise(SIGUSR2)); EXPECT_EQ(0, n); EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &old, NULL)); EXPECT_EQ(0, sigaction(SIGUSR2, &oldusr2, 0)); if (IsFreebsd() || IsWindows()) { EXPECT_EQ(2, n); } else { EXPECT_EQ(1, n); } } TEST(sigprocmask, testBlockingSIGINT) { sigset_t neu, old; struct sigaction oldsigint; struct sigaction sa = {.sa_sigaction = OnSig, .sa_flags = SA_SIGINFO}; n = 0; sigemptyset(&neu); sigaddset(&neu, SIGINT); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &neu, &old)); ASSERT_EQ(0, sigaction(SIGINT, &sa, &oldsigint)); ASSERT_EQ(0, raise(SIGINT)); EXPECT_EQ(0, n); EXPECT_EQ(0, sigprocmask(SIG_SETMASK, &old, NULL)); EXPECT_EQ(0, sigaction(SIGINT, &oldsigint, 0)); }
4,105
96
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/unveil_test.c
/*-*- 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 2022 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/landlock.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/stat.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/mem/copyfd.internal.h" #include "libc/mem/gc.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/msync.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/sock.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #define EACCES_OR_ENOENT (IsOpenbsd() ? ENOENT : EACCES) char testlib_enable_tmp_setup_teardown; struct stat st; bool HasUnveilSupport(void) { return unveil("", 0) >= 0; } bool UnveilCanSecureTruncate(void) { int abi = unveil("", 0); return abi == 0 || abi >= 3; } void SetUpOnce(void) { __enable_threads(); if (!HasUnveilSupport()) { fprintf(stderr, "warning: unveil() not supported on this system: %m\n"); exit(0); } } void SetUp(void) { // make sure zipos maps executable into memory early ASSERT_SYS(0, 0, stat("/zip/life.elf", &st)); } TEST(unveil, api_differences) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("foo", 0755)); ASSERT_SYS(0, 0, unveil("foo", "r")); if (IsOpenbsd()) { // openbsd imposes restrictions immediately ASSERT_SYS(ENOENT, -1, open("/", O_RDONLY | O_DIRECTORY)); } else { // restrictions on linux don't go into effect until unveil(0,0) ASSERT_SYS(0, 3, open(".", O_RDONLY | O_DIRECTORY)); ASSERT_SYS(0, 0, close(3)); } ASSERT_SYS(0, 0, unveil(0, 0)); // error numbers are inconsistent ASSERT_SYS(EACCES_OR_ENOENT, -1, open("/", O_RDONLY | O_DIRECTORY)); // wut if (IsLinux()) { ASSERT_SYS(0, 3, open("/", O_PATH)); // wut ASSERT_SYS(0, 0, stat("/", &st)); // wut } EXITS(0); } TEST(unveil, rx_readOnlyPreexistingExecutable_worksFine) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("folder", 0755)); testlib_extract("/zip/life.elf", "folder/life.elf", 0755); ASSERT_SYS(0, 0, unveil("folder", "rx")); ASSERT_SYS(0, 0, unveil(0, 0)); SPAWN(fork); execl("folder/life.elf", "folder/life.elf", 0); kprintf("execve failed! %s\n", strerror(errno)); _Exit(127); EXITS(42); EXITS(0); } TEST(unveil, r_noExecutePreexistingExecutable_raisesEacces) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("folder", 0755)); testlib_extract("/zip/life.elf", "folder/life.elf", 0755); ASSERT_SYS(0, 0, unveil("folder", "r")); ASSERT_SYS(0, 0, unveil(0, 0)); SPAWN(fork); ASSERT_SYS(EACCES, -1, execl("folder/life.elf", "folder/life.elf", 0)); EXITS(0); EXITS(0); } TEST(unveil, canBeUsedAgainAfterVfork) { ASSERT_SYS(0, 0, touch("bad", 0644)); ASSERT_SYS(0, 0, touch("good", 0644)); SPAWN(fork); SPAWN(vfork); ASSERT_SYS(0, 0, unveil("bad", "r")); ASSERT_SYS(0, 0, unveil("good", "r")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 3, open("bad", 0)); EXITS(0); ASSERT_SYS(0, 0, unveil("good", "r")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 3, open("good", 0)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open("bad", 0)); EXITS(0); } TEST(unveil, rwc_createExecutableFile_isAllowedButCantBeRun) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("folder", 0755)); ASSERT_SYS(0, 0, unveil("folder", "rwc")); ASSERT_SYS(0, 0, unveil(0, 0)); testlib_extract("/zip/life.elf", "folder/life.elf", 0755); SPAWN(fork); ASSERT_SYS(0, 0, stat("folder/life.elf", &st)); ASSERT_SYS(EACCES, -1, execl("folder/life.elf", "folder/life.elf", 0)); EXITS(0); EXITS(0); } TEST(unveil, rwcx_createExecutableFile_canAlsoBeRun) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("folder", 0755)); ASSERT_SYS(0, 0, unveil("folder", "rwcx")); ASSERT_SYS(0, 0, unveil(0, 0)); testlib_extract("/zip/life.elf", "folder/life.elf", 0755); SPAWN(fork); ASSERT_SYS(0, 0, stat("folder/life.elf", &st)); execl("folder/life.elf", "folder/life.elf", 0); kprintf("execve failed! %s\n", strerror(errno)); _Exit(127); EXITS(42); EXITS(0); } TEST(unveil, dirfdHacking_doesntWork) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, touch("garden/secret.txt", 0644)); ASSERT_SYS(0, 3, open("garden", O_RDONLY | O_DIRECTORY)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(EACCES_OR_ENOENT, -1, openat(3, "secret.txt", O_RDONLY)); EXITS(0); } TEST(unveil, mostRestrictivePolicy) { if (IsOpenbsd()) return; // openbsd behaves oddly; see docs SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, touch("garden/secret.txt", 0644)); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open("jail", O_RDONLY | O_DIRECTORY)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open("garden/secret.txt", O_RDONLY)); EXITS(0); } TEST(unveil, overlappingDirectories_inconsistentBehavior) { SPAWN(fork); ASSERT_SYS(0, 0, makedirs("f1/f2", 0755)); testlib_extract("/zip/life.elf", "f1/f2/life.elf", 0755); ASSERT_SYS(0, 0, unveil("f1", "x")); ASSERT_SYS(0, 0, unveil("f1/f2", "r")); ASSERT_SYS(0, 0, unveil(0, 0)); if (IsOpenbsd()) { // OpenBSD favors the most restrictive policy SPAWN(fork); ASSERT_SYS(0, 0, stat("f1/f2/life.elf", &st)); ASSERT_SYS(EACCES, -1, execl("f1/f2/life.elf", "f1/f2/life.elf", 0)); EXITS(0); } else { // Landlock (Linux) uses the union of policies // // TODO(jart): this test flakes on github actions. it reports an // exit code of 0! find out why this is happening... // so far it's happened to MODE=rel and MODE=tiny... // // SPAWN(fork); // ASSERT_SYS(0, 0, stat("f1/f2/life.elf", &st)); // execl("f1/f2/life.elf", "f1/f2/life.elf", 0); // kprintf("execve failed! %s\n", strerror(errno)); // _Exit(127); // EXITS(42); } EXITS(0); } TEST(unveil, usedTwice_allowedOnLinux) { if (IsOpenbsd()) return; SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, xbarf("jail/ok.txt", "hello", 5)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, mkdir("heaven", 0755)); ASSERT_SYS(0, 0, xbarf("heaven/verysecret.txt", "hello", 5)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil("garden", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 3, open("garden/secret.txt", O_RDONLY)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil("heaven", "rw")); // not allowed, superset of parent ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 4, open("jail/ok.txt", O_RDONLY)); ASSERT_SYS(EACCES, -1, open("garden/secret.txt", O_RDONLY)); ASSERT_SYS(EACCES, -1, open("heaven/verysecret.txt", O_RDONLY)); EXITS(0); } TEST(unveil, truncate_isForbiddenBySeccomp) { SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(!UnveilCanSecureTruncate() ? EPERM : EACCES_OR_ENOENT, -1, truncate("garden/secret.txt", 0)); if (IsLinux()) { ASSERT_SYS(0, 0, stat("garden/secret.txt", &st)); ASSERT_EQ(5, st.st_size); } EXITS(0); } TEST(unveil, ftruncate_isForbidden) { if (IsOpenbsd()) return; // b/c O_PATH is a Linux thing SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 3, open("garden/secret.txt", O_PATH)); ASSERT_SYS(EBADF, -1, ftruncate(3, 0)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(0, 0, stat("garden/secret.txt", &st)); ASSERT_EQ(5, st.st_size); EXITS(0); } TEST(unveil, procfs_isForbiddenByDefault) { if (IsOpenbsd()) return; SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(EACCES, -1, open("/proc/self/cmdline", O_RDONLY)); EXITS(0); } int Worker(void *arg, int tid) { ASSERT_SYS(EACCES_OR_ENOENT, -1, open("garden/secret.txt", O_RDONLY)); return 0; } TEST(unveil, isInheritedAcrossThreads) { struct spawn t; SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 0, _spawn(Worker, 0, &t)); EXPECT_SYS(0, 0, _join(&t)); EXITS(0); } int Worker2(void *arg, int tid) { ASSERT_SYS(0, 0, unveil("jail", "rw")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open("garden/secret.txt", O_RDONLY)); return 0; } TEST(unveil, isThreadSpecificOnLinux_isProcessWideOnOpenbsd) { struct spawn t; SPAWN(fork); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, _spawn(Worker2, 0, &t)); EXPECT_SYS(0, 0, _join(&t)); if (IsOpenbsd()) { ASSERT_SYS(ENOENT, -1, open("garden/secret.txt", O_RDONLY)); } else { ASSERT_SYS(0, 3, open("garden/secret.txt", O_RDONLY)); } EXITS(0); } TEST(unveil, usedTwice_forbidden_worksWithPledge) { int ws, pid; bool *gotsome; ASSERT_NE(-1, (gotsome = _mapshared(FRAMESIZE))); ASSERT_NE(-1, (pid = fork())); if (!pid) { // install our first seccomp filter ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath unveil", 0)); ASSERT_SYS(0, 0, mkdir("jail", 0755)); ASSERT_SYS(0, 0, mkdir("garden", 0755)); ASSERT_SYS(0, 0, xbarf("garden/secret.txt", "hello", 5)); ASSERT_SYS(0, 0, unveil("jail", "rw")); // committing and locking causes a new bpf filter to be installed ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open("garden/secret.txt", O_RDONLY)); // verify the second filter is working ASSERT_SYS(EACCES_OR_ENOENT, -1, open("garden/secret.txt", O_RDONLY)); // verify the first filter is still working *gotsome = true; socket(AF_UNIX, SOCK_STREAM, 0); _Exit(0); } ASSERT_NE(-1, wait(&ws)); ASSERT_TRUE(*gotsome); ASSERT_TRUE(WIFSIGNALED(ws)); ASSERT_EQ(IsOpenbsd() ? SIGABRT : SIGSYS, WTERMSIG(ws)); EXPECT_SYS(0, 0, munmap(gotsome, FRAMESIZE)); } TEST(unveil, lotsOfPaths) { int i, n; SPAWN(fork); n = 100; for (i = 0; i < n; ++i) { ASSERT_SYS(0, 0, touch(xasprintf("%d", i), 0644)); ASSERT_SYS(0, 0, touch(xasprintf("%d-", i), 0644)); } for (i = 0; i < n; ++i) { ASSERT_SYS(0, 0, unveil(xasprintf("%d", i), "rw")); } ASSERT_SYS(0, 0, unveil(0, 0)); for (i = 0; i < n; ++i) { ASSERT_SYS(0, 3, open(xasprintf("%d", i), O_RDONLY)); ASSERT_SYS(0, 0, close(3)); ASSERT_SYS(EACCES_OR_ENOENT, -1, open(xasprintf("%d-", i), O_RDONLY)); } EXITS(0); } TEST(unveil, reparent) { return; // need abi 2 :'( SPAWN(fork); ASSERT_SYS(0, 0, mkdir("x", 0755)); ASSERT_SYS(0, 0, unveil("x", "rwc")); ASSERT_SYS(0, 0, unveil(0, 0)); ASSERT_SYS(0, 0, mkdir("x/y", 0755)); ASSERT_SYS(0, 0, touch("x/y/z", 0644)); ASSERT_SYS(0, 0, rename("x/y/z", "x/z")); EXITS(0); }
13,544
389
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/dup_test.c
/*-*- 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/internal.h" #include "libc/calls/struct/stat.h" #include "libc/errno.h" #include "libc/log/check.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/x/xspawn.h" char testlib_enable_tmp_setup_teardown; static textstartup void TestInit(int argc, char **argv) { int fd; if (argc == 2 && !strcmp(argv[1], "boop")) { if ((fd = open("/dev/null", O_RDWR | O_CLOEXEC)) == 3) { _exit(72); } else { _exit(fd + 1); } } } const void *const TestCtor[] initarray = {TestInit}; TEST(dup, ebadf) { ASSERT_SYS(EBADF, -1, dup(-1)); ASSERT_SYS(EBADF, -1, dup2(-1, 0)); ASSERT_SYS(EBADF, -1, dup2(0, -1)); ASSERT_SYS(EBADF, -1, dup3(0, -1, 0)); ASSERT_SYS(EBADF, -1, dup3(10, 0, 0)); } TEST(dup, sameNumber) { ASSERT_SYS(0, 0, dup2(0, 0)); ASSERT_SYS(EINVAL, -1, dup3(0, 0, 0)); EXPECT_SYS(EBADF, -1, dup2(-1, -1)); EXPECT_SYS(EINVAL, -1, dup3(-1, -1, 0)); ASSERT_SYS(EBADF, -1, dup2(3, 3)); ASSERT_SYS(EBADF, -1, dup2(0, -1)); } TEST(dup, bigNumber) { ASSERT_SYS(0, 100, dup2(0, 100)); ASSERT_SYS(0, 0, close(100)); } #ifdef __x86_64__ TEST(dup, clearsCloexecFlag) { int ws; ASSERT_SYS(0, 0, close(creat("file", 0644))); ASSERT_SYS(0, 3, open("file", O_RDWR | O_CLOEXEC)); ASSERT_NE(-1, (ws = xspawn(0))); if (ws == -2) { dup2(3, 0); execv(GetProgramExecutableName(), (char *const[]){GetProgramExecutableName(), "boop", 0}); _exit(127); } ASSERT_EQ(72, WEXITSTATUS(ws)); ASSERT_SYS(0, 0, close(3)); } #endif
3,564
86
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/mkdir_test.c
/*-*- 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/dce.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath fattr", 0)); } void SetUp(void) { errno = 0; } TEST(mkdir, testNothingExists_ENOENT) { EXPECT_SYS(ENOENT, -1, mkdir("yo/yo/yo", 0755)); } TEST(mkdir, testDirectoryComponentIsFile_ENOTDIR) { EXPECT_SYS(0, 0, touch("yo", 0644)); EXPECT_SYS(ENOTDIR, -1, mkdir("yo/yo/yo", 0755)); } TEST(mkdir, testPathIsFile_EEXIST) { EXPECT_SYS(0, 0, mkdir("yo", 0755)); EXPECT_SYS(0, 0, mkdir("yo/yo", 0755)); EXPECT_SYS(0, 0, touch("yo/yo/yo", 0644)); EXPECT_SYS(EEXIST, -1, mkdir("yo/yo/yo", 0755)); } TEST(mkdir, testPathIsDirectory_EEXIST) { EXPECT_SYS(0, 0, mkdir("yo", 0755)); EXPECT_SYS(0, 0, mkdir("yo/yo", 0755)); EXPECT_SYS(0, 0, mkdir("yo/yo/yo", 0755)); EXPECT_SYS(EEXIST, -1, mkdir("yo/yo/yo", 0755)); } TEST(makedirs, pathExists_isSuccess) { EXPECT_SYS(0, 0, makedirs("foo/bar", 0755)); EXPECT_SYS(0, 0, makedirs("foo/bar", 0755)); } TEST(mkdir, enametoolong) { int i; size_t n = 2048; char *d, *s = gc(calloc(1, n)); for (i = 0; i < n - 1; ++i) s[i] = 'x'; s[i] = 0; EXPECT_SYS(ENAMETOOLONG, -1, mkdir(s, 0644)); } TEST(makedirs, testEmptyString_ENOENT) { EXPECT_SYS(ENOENT, -1, mkdir("", 0755)); } TEST(mkdirat, testRelativePath_opensRelativeToDirFd) { int dirfd; ASSERT_SYS(0, 0, mkdir("foo", 0755)); ASSERT_SYS(0, 3, (dirfd = open("foo", O_RDONLY | O_DIRECTORY))); EXPECT_SYS(0, 0, mkdirat(dirfd, "bar", 0755)); EXPECT_TRUE(isdirectory("foo/bar")); EXPECT_SYS(0, 0, close(dirfd)); } TEST(mkdir, longname) { int i; char *d, s[270] = {0}; for (i = 0; i < sizeof(s) - 1; ++i) s[i] = 'x'; s[i] = 0; ASSERT_NE(NULL, (d = gc(getcwd(0, 0)))); memcpy(s, d, strlen(d)); s[strlen(d)] = '/'; ASSERT_SYS(0, 0, mkdir(s, 0644)); }
4,018
103
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/pledge_test.c
/*-*- 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 2022 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/internal.h" #include "libc/calls/ioctl.h" #include "libc/calls/pledge.internal.h" #include "libc/calls/struct/bpf.h" #include "libc/calls/struct/filter.h" #include "libc/calls/struct/flock.h" #include "libc/calls/struct/seccomp.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/stat.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/macros.internal.h" #include "libc/mem/copyfd.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/sockaddr.h" #include "libc/stdio/lock.internal.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fio.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/nrlinux.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "libc/time/time.h" #include "libc/x/x.h" char testlib_enable_tmp_setup_teardown; void OnSig(int sig) { // do nothing } int sys_memfd_secret(unsigned int); // our ENOSYS threshold void SetUp(void) { __enable_threads(); if (pledge(0, 0) == -1) { fprintf(stderr, "warning: pledge() not supported on this system\n"); exit(0); } testlib_extract("/zip/life.elf", "life.elf", 0755); testlib_extract("/zip/sock.elf", "sock.elf", 0755); __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; } TEST(pledge, default_allowsExit) { int *job; int ws, pid; // create small shared memory region ASSERT_NE(-1, (job = mmap(0, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0))); job[0] = 2; // create workload job[1] = 2; ASSERT_NE(-1, (pid = fork())); // create enclaved worker if (!pid) { ASSERT_SYS(0, 0, pledge("", 0)); job[0] = job[0] + job[1]; // do work _Exit(0); } EXPECT_NE(-1, wait(&ws)); // wait for worker EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); EXPECT_EQ(4, job[0]); // check result EXPECT_SYS(0, 0, munmap(job, FRAMESIZE)); } TEST(pledge, execpromises_notok) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; ASSERT_SYS(0, 0, pledge("stdio rpath exec", "stdio")); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(129, WEXITSTATUS(ws)); } int Enclave(void *arg, int tid) { ASSERT_SYS(0, 0, pledge("", 0)); int *job = arg; // get job job[0] = job[0] + job[1]; // do work return 0; // exit } TEST(pledge, withThreadMemory) { if (IsOpenbsd()) return; // openbsd doesn't allow it, wisely struct spawn worker; int job[2] = {2, 2}; // create workload ASSERT_SYS(0, 0, _spawn(Enclave, job, &worker)); // create worker ASSERT_SYS(0, 0, _join(&worker)); // wait for exit EXPECT_EQ(4, job[0]); // check result } bool gotusr1; void OnUsr1(int sig) { gotusr1 = true; } int TgkillWorker(void *arg, int tid) { sigset_t mask; signal(SIGUSR1, OnUsr1); sigemptyset(&mask); ASSERT_SYS(EINTR, -1, sigsuspend(&mask)); ASSERT_TRUE(gotusr1); return 0; } TEST(pledge, tgkill) { // https://github.com/jart/cosmopolitan/issues/628 if (!IsLinux()) return; sigset_t mask; struct spawn worker; SPAWN(fork); sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, 0); ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(0, 0, _spawn(TgkillWorker, 0, &worker)); ASSERT_SYS(0, 0, tgkill(getpid(), worker.ptid, SIGUSR1)); ASSERT_SYS(0, 0, _join(&worker)); EXITS(0); } TEST(pledge, stdio_forbidsOpeningPasswd1) { if (!IsLinux()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(EPERM, -1, open("/etc/passwd", O_RDWR)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, stdio_forbidsOpeningPasswd2) { int ws, pid; __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(EPERM, -1, open("/etc/passwd", O_RDWR)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFSIGNALED(ws)); EXPECT_EQ(IsOpenbsd() ? SIGABRT : SIGSYS, WTERMSIG(ws)); } TEST(pledge, multipleCalls_canOnlyBecomeMoreRestrictive1) { if (IsOpenbsd()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(0, 0, pledge("stdio unix", 0)); ASSERT_SYS(0, 3, dup(2)); ASSERT_SYS(EPERM, -1, socket(AF_UNIX, SOCK_STREAM, 0)); ASSERT_SYS(0, 2, prctl(PR_GET_SECCOMP, 0, 0)); ASSERT_SYS(0, 0, prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)); ASSERT_SYS(EINVAL, -1, prctl(PR_SET_NO_NEW_PRIVS, 0, 0, 0, 0)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, multipleCalls_canOnlyBecomeMoreRestrictive2) { if (!IsOpenbsd()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", "stdio")); ASSERT_SYS(EPERM, -1, pledge("stdio unix", "stdio unix")); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, multipleCalls_canOnlyBecomeMoreRestrictive3) { if (!IsOpenbsd()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio unix", 0)); ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(0, 3, dup(2)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, stdio_fcntl_allowsSomeFirstArgs) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; struct flock lk; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio inet", 0)); ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_NE(-1, fcntl(0, F_GETFL)); ASSERT_SYS(0, 0, fcntl(0, F_GETFD)); ASSERT_SYS(0, 3, fcntl(2, F_DUPFD_CLOEXEC, 3)); ASSERT_SYS(0, 0, ioctl(0, FIOCLEX, 0)); ASSERT_SYS(EPERM, 0, isatty(0)); ASSERT_SYS(EPERM, -1, fcntl(0, 777)); ASSERT_SYS(EPERM, -1, fcntl(0, F_GETLK, &lk)); ASSERT_SYS(EPERM, -1, fcntl(0, F_NOTIFY)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, stdioTty_sendtoRestricted_requiresNullAddr) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid, sv[2]; ASSERT_SYS(0, 0, socketpair(AF_UNIX, SOCK_STREAM, 0, sv)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio tty", 0)); ASSERT_SYS(0, 5, send(sv[0], "hello", 5, 0)); ASSERT_SYS(0, 5, sendto(sv[0], "hello", 5, 0, 0, 0)); isatty(0); ASSERT_NE(EPERM, errno); errno = 0; // set lower 32-bit word of pointer to zero lool struct sockaddr_in *sin = mmap((void *)0x300000000000, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); sin->sin_family = AF_INET; ASSERT_SYS( EPERM, -1, sendto(sv[0], "hello", 5, 0, (struct sockaddr *)sin, sizeof(*sin))); _Exit(0); } close(sv[0]); close(sv[1]); EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, unix_forbidsInetSockets) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio unix", 0)); ASSERT_SYS(0, 3, socket(AF_UNIX, SOCK_STREAM, 0)); ASSERT_SYS(0, 4, socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); ASSERT_SYS(EPERM, -1, socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP)); ASSERT_SYS(EPERM, -1, socket(AF_UNIX, SOCK_RAW, 0)); ASSERT_SYS(EPERM, -1, socket(AF_UNIX, SOCK_STREAM, 1)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, wpath_doesNotImplyRpath) { int ws, pid; bool *gotsome; ASSERT_NE(-1, (gotsome = _mapshared(FRAMESIZE))); ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio wpath", 0)); ASSERT_SYS(0, 3, open("foo", O_WRONLY)); *gotsome = true; ASSERT_SYS(EPERM, -1, open("foo", O_RDONLY)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); ASSERT_TRUE(*gotsome); if (IsOpenbsd()) { ASSERT_TRUE(WIFSIGNALED(ws)); ASSERT_EQ(SIGABRT, WTERMSIG(ws)); } else { ASSERT_TRUE(WIFEXITED(ws)); ASSERT_EQ(0, WEXITSTATUS(ws)); } } TEST(pledge, inet_forbidsOtherSockets) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid, yes = 1; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio inet", 0)); ASSERT_SYS(0, 3, socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)); ASSERT_SYS(0, 4, socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)); ASSERT_SYS(0, 5, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); ASSERT_SYS(0, 6, socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)); ASSERT_SYS(0, 7, socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP)); ASSERT_SYS(0, 0, setsockopt(3, SOL_SOCKET, SO_BROADCAST, &yes, 4)); ASSERT_SYS(EPERM, -1, socket(AF_UNIX, SOCK_STREAM, 0)); ASSERT_SYS(EPERM, -1, socket(AF_BLUETOOTH, SOCK_DGRAM, IPPROTO_UDP)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_RAW, IPPROTO_UDP)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_DGRAM, IPPROTO_RAW)); ASSERT_SYS(EPERM, -1, setsockopt(3, SOL_SOCKET, SO_TIMESTAMP, &yes, 4)); struct sockaddr_in sin = {AF_INET, 0, {htonl(0x7f000001)}}; ASSERT_SYS(0, 0, bind(4, (struct sockaddr *)&sin, sizeof(sin))); uint32_t az = sizeof(sin); ASSERT_SYS(0, 0, getsockname(4, (struct sockaddr *)&sin, &az)); ASSERT_SYS(0, 5, sendto(3, "hello", 5, 0, (struct sockaddr *)&sin, sizeof(sin))); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, mmap) { if (IsOpenbsd()) return; // b/c testing linux bpf char *p; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_NE(MAP_FAILED, (p = mmap(0, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0))); ASSERT_SYS(0, 0, mprotect(p, FRAMESIZE, PROT_READ)); ASSERT_SYS(EPERM, MAP_FAILED, mprotect(p, FRAMESIZE, PROT_READ | PROT_EXEC)); ASSERT_SYS(EPERM, MAP_FAILED, mmap(0, FRAMESIZE, PROT_EXEC | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, mmapProtExec) { if (IsOpenbsd()) return; // b/c testing linux bpf char *p; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio prot_exec", 0)); ASSERT_NE(MAP_FAILED, (p = mmap(0, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0))); ASSERT_SYS(0, 0, mprotect(p, FRAMESIZE, PROT_READ)); ASSERT_SYS(0, 0, mprotect(p, FRAMESIZE, PROT_READ | PROT_EXEC)); ASSERT_NE(MAP_FAILED, mmap(0, FRAMESIZE, PROT_EXEC | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, chmod_ignoresDangerBits) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_SYS(0, 3, creat("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio rpath wpath", 0)); ASSERT_SYS(0, 0, fchmod(3, 00700)); ASSERT_SYS(0, 0, chmod("foo", 00700)); ASSERT_SYS(0, 0, fchmodat(AT_FDCWD, "foo", 00700, 0)); ASSERT_SYS(EPERM, -1, fchmod(3, 07700)); ASSERT_SYS(EPERM, -1, chmod("foo", 04700)); ASSERT_SYS(EPERM, -1, fchmodat(AT_FDCWD, "foo", 02700, 0)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); close(3); } TEST(pledge, open_rpath) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio rpath", 0)); ASSERT_SYS(0, 3, open("foo", O_RDONLY)); ASSERT_SYS(EPERM, -1, open("foo", O_RDONLY | O_TRUNC)); ASSERT_SYS(EPERM, -1, open("foo", O_RDONLY | O_TMPFILE)); ASSERT_SYS(EPERM, -1, open("foo", O_RDWR | O_TRUNC | O_CREAT, 0644)); ASSERT_SYS(EPERM, -1, open("foo", O_WRONLY | O_TRUNC | O_CREAT, 0644)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, open_wpath) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio wpath", 0)); ASSERT_SYS(EPERM, -1, open(".", O_RDWR | O_TMPFILE, 07644)); ASSERT_SYS(0, 3, open("foo", O_WRONLY | O_TRUNC)); ASSERT_SYS(0, 4, open("foo", O_RDWR)); ASSERT_SYS(EPERM, -1, open("foo", O_WRONLY | O_TRUNC | O_CREAT, 0644)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, open_cpath) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; struct stat st; ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio cpath", 0)); ASSERT_SYS(0, 3, open("foo", O_WRONLY | O_TRUNC | O_CREAT, 0644)); ASSERT_SYS(0, 0, fstat(3, &st)); ASSERT_EQ(0100644, st.st_mode); // make sure open() can't apply the setuid bit ASSERT_SYS(EPERM, -1, open("bar", O_WRONLY | O_TRUNC | O_CREAT, 04644)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws) && !WEXITSTATUS(ws)); } TEST(pledge, execpromises_ok) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio exec", "stdio")); execl("life.elf", "life.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(42, WEXITSTATUS(ws)); } TEST(pledge, execpromises_notok1) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio exec", "stdio")); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(128 + EPERM, WEXITSTATUS(ws)); } TEST(pledge, execpromises_reducesAtExecOnLinux) { if (IsOpenbsd()) return; // b/c testing linux bpf int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio inet tty exec", "stdio tty")); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(128 + EPERM, WEXITSTATUS(ws)); } TEST(pledge_openbsd, execpromisesIsNull_letsItDoAnything) { if (!IsOpenbsd()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio exec", 0)); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(3, WEXITSTATUS(ws)); } TEST(pledge_openbsd, execpromisesIsSuperset_letsItDoAnything) { if (!IsOpenbsd()) return; int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio rpath exec", "stdio rpath tty inet")); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(3, WEXITSTATUS(ws)); } TEST(pledge_linux, execpromisesIsSuperset_notPossible) { if (IsOpenbsd()) return; ASSERT_SYS(EINVAL, -1, pledge("stdio exec", "stdio inet exec")); } TEST(pledge_openbsd, execpromises_notok) { int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio exec", "stdio")); execl("sock.elf", "sock.elf", 0); _Exit(127); } EXPECT_NE(-1, wait(&ws)); if (IsOpenbsd()) { EXPECT_TRUE(WIFSIGNALED(ws)); EXPECT_EQ(SIGABRT, WTERMSIG(ws)); } else { // linux can't be consistent here since we pledged exec // so we return EPERM instead and sock.elf passes along EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(128 + EPERM, WEXITSTATUS(ws)); } } TEST(pledge_openbsd, bigSyscalls) { if (IsOpenbsd()) return; // testing lunix int ws, pid; ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(ENOSYS, -1, sys_memfd_secret(0)); ASSERT_SYS(ENOSYS, -1, sys_bogus()); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } int LockWorker(void *arg, int tid) { flockfile(stdout); ASSERT_EQ(gettid(), ((pthread_mutex_t *)stdout->lock)->_owner); funlockfile(stdout); return 0; } TEST(pledge, threadWithLocks_canCodeMorph) { struct spawn worker; int ws, pid; // not sure how this works on OpenBSD but it works! if (!fork()) { __enable_threads(); ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(0, 0, _spawn(LockWorker, 0, &worker)); ASSERT_SYS(0, 0, _join(&worker)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, everything) { int ws, pid; if (!fork()) { // contains 591 bpf instructions [2022-07-24] ASSERT_SYS(0, 0, pledge("stdio rpath wpath cpath dpath " "flock fattr inet unix dns tty " "recvfd sendfd proc exec id " "unveil settime prot_exec " "vminfo tmppath", "stdio rpath wpath cpath dpath " "flock fattr inet unix dns tty " "recvfd sendfd proc exec id " "unveil settime prot_exec " "vminfo tmppath")); _Exit(0); } EXPECT_NE(-1, wait(&ws)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } TEST(pledge, execWithoutRpath) { int ws, pid; ASSERT_SYS(0, 0, touch("foo", 0644)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, 0, pledge("stdio prot_exec exec", "stdio prot_exec exec")); ASSERT_SYS(EPERM, -1, open("foo", O_RDONLY)); _Exit(0); } EXPECT_NE(-1, wait(&ws)); if (IsOpenbsd()) { EXPECT_TRUE(WIFSIGNALED(ws)); EXPECT_EQ(SIGABRT, WTERMSIG(ws)); } else { EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(0, WEXITSTATUS(ws)); } } BENCH(pledge, bench) { int pid; if (!fork()) { ASSERT_SYS(0, 0, pledge("stdio", 0)); EZBENCH2("sched_yield", donothing, sched_yield()); _Exit(0); } wait(0); }
21,602
662
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sched_getaffinity_test.c
/*-*- 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 2022 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/cpuset.h" #include "libc/dce.h" #include "libc/fmt/conv.h" #include "libc/intrin/popcnt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/posix_spawn.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "libc/thread/thread2.h" void SetUp(void) { if (!IsLinux() && !IsFreebsd() && !IsWindows()) { exit(0); } if (IsFreebsd() && getuid() != 0) { exit(0); } } TEST(sched_getaffinity, firstOnly) { cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(0, &x); ASSERT_SYS(0, 0, sched_setaffinity(0, sizeof(x), &x)); ASSERT_SYS(0, 0, sched_getaffinity(0, sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_TRUE(CPU_ISSET(0, &y)); EXPECT_FALSE(CPU_ISSET(1, &y)); } TEST(sched_getaffinity, secondOnly) { if (_getcpucount() < 2) return; cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(1, &x); ASSERT_SYS(0, 0, sched_setaffinity(0, sizeof(x), &x)); ASSERT_SYS(0, 0, sched_getaffinity(0, sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_FALSE(CPU_ISSET(0, &y)); EXPECT_TRUE(CPU_ISSET(1, &y)); } TEST(sched_setaffinity, isInheritedAcrossFork) { cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(0, &x); ASSERT_SYS(0, 0, sched_setaffinity(0, sizeof(x), &x)); SPAWN(fork); ASSERT_SYS(0, 0, sched_getaffinity(0, sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_TRUE(CPU_ISSET(0, &y)); EXPECT_FALSE(CPU_ISSET(1, &y)); EXITS(0); } __attribute__((__constructor__)) static void init(void) { cpu_set_t y; switch (atoi(nulltoempty(getenv("THE_DOGE")))) { case 42: ASSERT_SYS(0, 0, sched_getaffinity(0, sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_TRUE(CPU_ISSET(0, &y)); EXPECT_FALSE(CPU_ISSET(1, &y)); exit(42); default: break; } } #ifdef __x86_64__ TEST(sched_setaffinity, isInheritedAcrossExecve) { cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(0, &x); ASSERT_SYS(0, 0, sched_setaffinity(0, sizeof(x), &x)); int rc, ws, pid; char *prog = GetProgramExecutableName(); char *args[] = {program_invocation_name, NULL}; char *envs[] = {"THE_DOGE=42", NULL}; EXPECT_EQ(0, posix_spawn(&pid, prog, NULL, NULL, args, envs)); EXPECT_NE(-1, waitpid(pid, &ws, 0)); EXPECT_TRUE(WIFEXITED(ws)); EXPECT_EQ(42, WEXITSTATUS(ws)); } #endif /* __x86_64__ */ TEST(sched_getaffinity, getpid) { cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(0, &x); ASSERT_SYS(0, 0, sched_setaffinity(getpid(), sizeof(x), &x)); ASSERT_SYS(0, 0, sched_getaffinity(getpid(), sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_TRUE(CPU_ISSET(0, &y)); EXPECT_FALSE(CPU_ISSET(1, &y)); } TEST(pthread_getaffinity, getpid) { cpu_set_t x, y; CPU_ZERO(&x); CPU_SET(0, &x); ASSERT_SYS(0, 0, pthread_setaffinity_np(pthread_self(), sizeof(x), &x)); if (IsWindows()) return; // win32 doesn't define GetThreadAffinityMask ;_; ASSERT_SYS(0, 0, pthread_getaffinity_np(pthread_self(), sizeof(y), &y)); EXPECT_EQ(1, CPU_COUNT(&y)); EXPECT_TRUE(CPU_ISSET(0, &y)); EXPECT_FALSE(CPU_ISSET(1, &y)); }
4,982
130
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/printargs_test.c
/*-*- 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 2022 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/runtime/internal.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath tty proc", 0)); } /** * @fileoverview platform arguments tool * * This is intended to integrate with the Emacs keystroke `C-c C-s` * which will remotely launch it on all the other operating systems and * print the output. This way we can audit stuff. */ TEST(printargs, test) { __printargs("%r"); }
2,361
40
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sigaction_test.c
/*-*- 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/struct/sigaction.h" #include "libc/calls/calls.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/uc.h" #include "libc/testlib/testlib.h" #include "third_party/xed/x86.h" struct sigaction oldsa; volatile bool gotsigint; void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath proc", 0)); } void OnSigInt(int sig) { CheckStackIsAligned(); gotsigint = true; } void SetUp(void) { gotsigint = false; } //////////////////////////////////////////////////////////////////////////////// // test raise() TEST(sigaction, raise) { struct sigaction saint = {.sa_handler = OnSigInt}; EXPECT_SYS(0, 0, sigaction(SIGINT, &saint, &oldsa)); ASSERT_FALSE(gotsigint); EXPECT_NE(-1, raise(SIGINT)); ASSERT_TRUE(gotsigint); EXPECT_SYS(0, 0, sigaction(SIGINT, &oldsa, NULL)); } //////////////////////////////////////////////////////////////////////////////// // test kill() TEST(sigaction, testPingPongParentChildWithSigint) { if (IsNetbsd()) return; // TODO: what's up with runitd on netbsd? int pid, status; sigset_t blockint, oldmask; struct sigaction oldint; struct sigaction ignoreint = {.sa_handler = SIG_IGN}; struct sigaction catchint = {.sa_handler = OnSigInt}; if (IsWindows()) { // this works if it's run by itself on the command prompt. but it // doesn't currently work if it's launched as a subprocess of some // kind of runner. todo(fixme!) return; } EXPECT_SYS(0, 0, sigemptyset(&blockint)); EXPECT_SYS(0, 0, sigaddset(&blockint, SIGINT)); EXPECT_SYS(0, 0, sigprocmask(SIG_BLOCK, &blockint, &oldmask)); EXPECT_SYS(0, 0, sigaction(SIGINT, &catchint, &oldint)); ASSERT_NE(-1, (pid = fork())); if (!pid) { // ping EXPECT_SYS(0, 0, kill(getppid(), SIGINT)); EXPECT_FALSE(gotsigint); // pong EXPECT_SYS(0, 0, sigaction(SIGINT, &catchint, 0)); EXPECT_SYS(EINTR, -1, sigsuspend(0)); EXPECT_TRUE(gotsigint); _exit(0); } // pong EXPECT_FALSE(gotsigint); EXPECT_SYS(0, 0, sigaction(SIGINT, &catchint, 0)); EXPECT_SYS(EINTR, -1, sigsuspend(0)); EXPECT_TRUE(gotsigint); // ping EXPECT_SYS(0, 0, sigaction(SIGINT, &ignoreint, 0)); EXPECT_SYS(0, 0, kill(pid, SIGINT)); // cleanup EXPECT_NE(-1, wait4(pid, &status, 0, 0)); EXPECT_EQ(1, WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); EXPECT_EQ(0, WTERMSIG(status)); EXPECT_SYS(0, 0, sigaction(SIGINT, &oldint, 0)); EXPECT_SYS(0, 0, sigprocmask(SIG_BLOCK, &oldmask, 0)); } #ifdef __x86_64__ //////////////////////////////////////////////////////////////////////////////// // test int3 crash // we expect this to be recoverable by default volatile int trapeax; void OnTrap(int sig, struct siginfo *si, void *vctx) { struct ucontext *ctx = vctx; CheckStackIsAligned(); trapeax = ctx->uc_mcontext.rax; } TEST(sigaction, debugBreak_handlerCanReadCpuState) { struct sigaction saint = {.sa_sigaction = OnTrap, .sa_flags = SA_SIGINFO}; EXPECT_NE(-1, sigaction(SIGTRAP, &saint, &oldsa)); asm("int3" : /* no outputs */ : "a"(0x31337)); EXPECT_EQ(0x31337, trapeax); EXPECT_SYS(0, 0, sigaction(SIGTRAP, &oldsa, NULL)); } //////////////////////////////////////////////////////////////////////////////// // test fpu crash (unrecoverable) // test signal handler can modify cpu registers (now it's recoverable!) void SkipOverFaultingInstruction(struct ucontext *ctx) { CheckStackIsAligned(); struct XedDecodedInst xedd; xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15); ctx->uc_mcontext.rip += xedd.length; } void OnFpe(int sig, struct siginfo *si, void *vctx) { struct ucontext *ctx = vctx; CheckStackIsAligned(); SkipOverFaultingInstruction(ctx); ctx->uc_mcontext.rax = 42; ctx->uc_mcontext.rdx = 0; } noubsan void ubsanTrumpsSystemsEngineering(void) { struct sigaction saint = {.sa_sigaction = OnFpe, .sa_flags = SA_SIGINFO}; EXPECT_SYS(0, 0, sigaction(SIGFPE, &saint, &oldsa)); volatile long x = 0; EXPECT_EQ(42, 666 / x); /* systems engineering trumps math */ EXPECT_SYS(0, 0, sigaction(SIGFPE, &oldsa, NULL)); } TEST(sigaction, sigFpe_handlerCanEditProcessStateAndRecoverExecution) { ubsanTrumpsSystemsEngineering(); } #endif /* __x86_64__ */ static unsigned OnSignalCnt = 0; void OnSignal(int sig, siginfo_t *si, void *ctx) { OnSignalCnt++; } TEST(sigaction, ignoringSignalDiscardsSignal) { struct sigaction sa = {.sa_sigaction = OnSignal, .sa_flags = SA_SIGINFO}; ASSERT_EQ(0, sigaction(SIGUSR1, &sa, NULL)); sigset_t blocked; sigemptyset(&blocked); sigaddset(&blocked, SIGUSR1); ASSERT_EQ(0, sigprocmask(SIG_SETMASK, &blocked, NULL)); ASSERT_EQ(0, raise(SIGUSR1)); ASSERT_NE(SIG_ERR, signal(SIGUSR1, SIG_IGN)); ASSERT_EQ(0, sigaction(SIGUSR1, &sa, NULL)); ASSERT_EQ(0, sigprocmask(SIG_UNBLOCK, &blocked, NULL)); EXPECT_EQ(0, OnSignalCnt); } TEST(sigaction, autoZombieSlayer) { if (IsWindows()) return; if (IsCygwin()) return; int pid; struct sigaction sa; // make sure we're starting in expected state ASSERT_SYS(0, 0, sigaction(SIGCHLD, 0, &sa)); ASSERT_EQ(SIG_DFL, sa.sa_handler); // verify child becomes zombie ASSERT_NE(-1, (pid = fork())); if (!pid) _Exit(0); ASSERT_SYS(0, pid, wait(0)); // enable automatic zombie slayer sa.sa_handler = SIG_IGN; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); ASSERT_SYS(0, 0, sigaction(SIGCHLD, &sa, &sa)); // verify it works ASSERT_NE(-1, (pid = fork())); if (!pid) _Exit(0); // XXX: WSL does the wrong thing here. if (IsWsl1()) usleep(10); ASSERT_SYS(ECHILD, -1, wait(0)); // clean up ASSERT_SYS(0, 0, sigaction(SIGCHLD, &sa, 0)); } TEST(sigaction, enosys_returnsErrnoRatherThanSigsysByDefault) { if (IsTiny()) return; // systemfive.S disables the fix w/ tiny if (IsOpenbsd()) return; // TODO: Why does OpenBSD raise SIGABRT? ASSERT_SYS(ENOSYS, -1, sys_bogus()); } sig_atomic_t gotusr1; void OnSigMask(int sig, struct siginfo *si, void *ctx) { ucontext_t *uc = ctx; sigaddset(&uc->uc_sigmask, sig); gotusr1 = true; } TEST(uc_sigmask, signalHandlerCanChangeSignalMaskOfTrappedThread) { if (IsWindows()) return; // TODO(jart): uc_sigmask support on windows sigset_t want, got; struct sigaction oldsa; struct sigaction sa = {.sa_sigaction = OnSigMask, .sa_flags = SA_SIGINFO}; sigemptyset(&want); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &want, &got)); ASSERT_FALSE(sigismember(&got, SIGUSR1)); ASSERT_SYS(0, 0, sigaction(SIGUSR1, &sa, &oldsa)); ASSERT_SYS(0, 0, raise(SIGUSR1)); ASSERT_TRUE(gotusr1); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, 0, &got)); ASSERT_TRUE(sigismember(&got, SIGUSR1)); sigaddset(&want, SIGUSR1); ASSERT_STREQ(DescribeSigset(0, &want), DescribeSigset(0, &got)); ASSERT_SYS(0, 0, sigaction(SIGUSR1, &oldsa, 0)); sigdelset(&want, SIGUSR1); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &want, 0)); }
9,278
251
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/test.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += TEST_LIBC_CALLS TEST_LIBC_CALLS_SRCS := \ $(wildcard test/libc/calls/*.c) TEST_LIBC_CALLS_SRCS_TEST = \ $(filter %_test.c,$(TEST_LIBC_CALLS_SRCS)) TEST_LIBC_CALLS_OBJS = \ $(TEST_LIBC_CALLS_SRCS:%.c=o/$(MODE)/%.o) TEST_LIBC_CALLS_COMS = \ $(TEST_LIBC_CALLS_SRCS_TEST:%.c=o/$(MODE)/%.com) TEST_LIBC_CALLS_BINS = \ $(TEST_LIBC_CALLS_COMS) \ $(TEST_LIBC_CALLS_COMS:%=%.dbg) \ o/$(MODE)/test/libc/calls/life-nomod.com \ o/$(MODE)/test/libc/calls/life-classic.com \ o/$(MODE)/test/libc/calls/zipread.com.dbg \ o/$(MODE)/test/libc/calls/zipread.com TEST_LIBC_CALLS_TESTS = \ $(TEST_LIBC_CALLS_SRCS_TEST:%.c=o/$(MODE)/%.com.ok) TEST_LIBC_CALLS_CHECKS = \ $(TEST_LIBC_CALLS_SRCS_TEST:%.c=o/$(MODE)/%.com.runs) TEST_LIBC_CALLS_DIRECTDEPS = \ DSP_CORE \ LIBC_CALLS \ LIBC_TINYMATH \ LIBC_SOCK \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_STDIO \ LIBC_NT_KERNEL32 \ LIBC_SYSV_CALLS \ LIBC_RUNTIME \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_THREAD \ LIBC_TIME \ LIBC_TESTLIB \ LIBC_X \ LIBC_ZIPOS \ TOOL_DECODE_LIB \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_XED TEST_LIBC_CALLS_DEPS := \ $(call uniq,$(foreach x,$(TEST_LIBC_CALLS_DIRECTDEPS),$($(x)))) o/$(MODE)/test/libc/calls/calls.pkg: \ $(TEST_LIBC_CALLS_OBJS) \ $(foreach x,$(TEST_LIBC_CALLS_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/test/libc/calls/%.com.dbg: \ $(TEST_LIBC_CALLS_DEPS) \ o/$(MODE)/test/libc/calls/%.o \ o/$(MODE)/test/libc/calls/life-nomod.com.zip.o \ o/$(MODE)/test/libc/calls/life-classic.com.zip.o \ o/$(MODE)/test/libc/calls/tiny64.elf.zip.o \ o/$(MODE)/test/libc/mem/prog/life.elf.zip.o \ o/$(MODE)/test/libc/mem/prog/sock.elf.zip.o \ o/$(MODE)/third_party/python/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt.zip.o \ o/$(MODE)/test/libc/calls/calls.pkg \ $(LIBC_TESTMAIN) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/test/libc/calls/life-classic.com.dbg: \ $(LIBC_RUNTIME) \ o/$(MODE)/test/libc/calls/life.o \ $(CRT) \ $(APE) @$(APELINK) o/$(MODE)/test/libc/calls/life-nomod.com.dbg: \ $(LIBC_RUNTIME) \ o/$(MODE)/test/libc/calls/life.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/test/libc/calls/fexecve_test.com.dbg: \ $(TEST_LIBC_CALLS_DEPS) \ o/$(MODE)/test/libc/calls/fexecve_test.o \ o/$(MODE)/test/libc/calls/calls.pkg \ o/$(MODE)/test/libc/mem/prog/life.elf.zip.o \ o/$(MODE)/tool/build/echo.zip.o \ o/$(MODE)/test/libc/calls/life-nomod.com.zip.o \ o/$(MODE)/test/libc/calls/zipread.com.zip.o \ $(LIBC_TESTMAIN) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/test/libc/calls/tiny64.elf.zip.o \ o/$(MODE)/test/libc/calls/life-nomod.com.zip.o \ o/$(MODE)/test/libc/calls/life-classic.com.zip.o \ o/$(MODE)/test/libc/calls/zipread.com.zip.o: private \ ZIPOBJ_FLAGS += \ -B # TODO(jart): Have pledge() support SIOCGIFCONF o/$(MODE)/test/libc/calls/ioctl_siocgifconf_test.com.runs: \ private .PLEDGE = o/$(MODE)/test/libc/calls/poll_test.com.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc inet o/$(MODE)/test/libc/calls/fcntl_test.com.runs \ o/$(MODE)/test/libc/calls/lock_test.com.runs \ o/$(MODE)/test/libc/calls/lock2_test.com.runs \ o/$(MODE)/test/libc/calls/lock_ofd_test.com.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc flock o/$(MODE)/test/libc/calls/unveil_test.com.runs \ o/$(MODE)/test/libc/calls/openbsd_test.com.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc unveil o/$(MODE)/test/libc/calls/fexecve_test.com.runs: \ private .UNSANDBOXED = 1 # for memfd_create() o/$(MODE)/test/libc/calls/execve_test.com.runs: \ private .UNSANDBOXED = 1 # for memfd_create() o/$(MODE)/test/libc/calls/read_test.com.runs: \ private .UNVEIL += /dev/zero # TODO(jart): Update nointernet() to allow AF_INET6 o/$(MODE)/test/libc/calls/pledge_test.com.runs: \ private .INTERNET = 1 o/$(MODE)/test/libc/calls/pledge_test.com.runs: \ private .PLEDGE = .PHONY: o/$(MODE)/test/libc/calls o/$(MODE)/test/libc/calls: \ $(TEST_LIBC_CALLS_BINS) \ $(TEST_LIBC_CALLS_CHECKS)
4,657
150
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/getcontext_test.c
/*-*- 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 2022 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/ucontext.h" #include "libc/runtime/runtime.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" #ifdef __x86_64__ int x; bool ok1; bool ok2; ucontext_t context; void func(void) { x++; setcontext(&context); abort(); } void test(void) { getcontext(&context); if (!x) { ok1 = true; func(); } else { ok2 = true; } } TEST(getcontext, test) { test(); ASSERT_TRUE(ok1); ASSERT_TRUE(ok2); } void SetGetContext(void) { static int a; a = 0; getcontext(&context); if (!a) { a = 1; setcontext(&context); } } BENCH(getcontext, bench) { EZBENCH2("get/setcontext", donothing, SetGetContext()); } #endif /* __x86_64__ */
2,570
69
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/splice_test.c
/*-*- 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 2022 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/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/o.h" #include "libc/testlib/testlib.h" char testlib_enable_tmp_setup_teardown; void SetUp(void) { int e = errno; if (splice(-1, 0, -1, 0, 0, 0) == -1 && errno == ENOSYS) { exit(0); } errno = e; } TEST(splice, einval) { ASSERT_SYS(0, 0, splice(0, 0, 1, 0, 0, -1)); } TEST(splice, espipe) { int64_t x; int fds[2]; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, 0, splice(0, 0, 4, &x, 0, 0)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(splice, noOffsets_usesFilePointer) { // this test fails on rhel5 and rhel7 int fds[2]; char buf[16] = {0}; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, 5, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, pwrite(5, "hello", 5, 0)); ASSERT_SYS(0, 5, splice(5, 0, 4, 0, 5, 0)); ASSERT_SYS(0, 5, splice(3, 0, 5, 0, 5, 0)); ASSERT_SYS(0, 10, pread(5, buf, sizeof(buf), 0)); ASSERT_STREQ("hellohello", buf); ASSERT_SYS(0, 0, close(5)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); } TEST(splice, offsets_doesntChangePointerAndIsReadOnly) { int fds[2]; int64_t x = 0; char buf[16] = {0}; ASSERT_SYS(0, 0, pipe(fds)); ASSERT_SYS(0, 5, open("foo", O_RDWR | O_CREAT | O_TRUNC, 0644)); ASSERT_SYS(0, 5, pwrite(5, "hello", 5, 0)); ASSERT_SYS(0, 5, splice(5, &x, 4, 0, 5, 0)); ASSERT_EQ(5, x); ASSERT_SYS(0, 5, splice(3, 0, 5, &x, 5, 0)); ASSERT_EQ(10, x); ASSERT_SYS(0, 10, read(5, buf, sizeof(buf))); ASSERT_STREQ("hellohello", buf); ASSERT_SYS(0, 0, close(5)); ASSERT_SYS(0, 0, close(4)); ASSERT_SYS(0, 0, close(3)); }
3,544
82
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/sigtimedwait_test.c
/*-*- 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 2022 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/sigtimedwait.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/siginfo.internal.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/timespec.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" void SetUp(void) { if (IsXnu()) exit(0); if (IsMetal()) exit(0); if (IsWindows()) exit(0); if (IsOpenbsd()) exit(0); } TEST(sigtimedwait, nullSet_efault) { ASSERT_SYS(EFAULT, -1, sigtimedwait(0, 0, 0)); } TEST(sigtimedwait, emptySet_timesOut) { sigset_t ss = {0}; struct timespec ts = {0, 0}; ASSERT_SYS(EAGAIN, -1, sigtimedwait(&ss, 0, &ts)); } TEST(sigtimedwait, badTimestamp_einval) { sigset_t ss = {0}; struct timespec ts = {0, -1}; ASSERT_SYS(EINVAL, -1, sigtimedwait(&ss, 0, &ts)); } TEST(sigtimedwait, test) { int pid, ws; siginfo_t info; sigset_t ss, oldss; struct timespec ts = {1, 0}; sigemptyset(&ss); sigaddset(&ss, SIGUSR1); ASSERT_SYS(0, 0, sigprocmask(SIG_BLOCK, &ss, &oldss)); ASSERT_NE(-1, (pid = fork())); if (!pid) { ASSERT_SYS(0, SIGUSR1, sigtimedwait(&ss, &info, &ts)); ASSERT_EQ(SIGUSR1, info.si_signo); ASSERT_EQ(SI_USER, info.si_code); ASSERT_EQ(getuid(), info.si_uid); _Exit(0); } ASSERT_SYS(0, 0, kill(pid, SIGUSR1)); ASSERT_SYS(0, pid, wait(&ws)); ASSERT_EQ(0, ws); ASSERT_SYS(0, 0, sigprocmask(SIG_SETMASK, &oldss, 0)); }
3,378
76
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/raise_race_test.c
/*-*- 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│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ │ │ libc-test │ │ Copyright © 2005-2013 libc-test AUTHORS │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/kprintf.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" // libc-test/src/regression/raise-race.c // commit: 370f78f2c80c64b7b0780a01e672494a26b5678e 2011-03-09 // commit: 0bed7e0acfd34e3fb63ca0e4d99b7592571355a9 2011-03-09 // raise should be robust against async fork in a signal handler // [jart] i can't believe fork() is async-signal-safe #define t_error(...) \ do { \ kprintf(__VA_ARGS__); \ ++t_status; \ } while (0) static atomic_int c0; static atomic_int c1; static atomic_int child; static atomic_int t_status; static void handler0(int sig) { c0++; } static void handler1(int sig) { c1++; switch (fork()) { case 0: child = 1; break; case -1: t_error("fork failed: %s\n", strerror(errno)); default: break; } } static void *start(void *arg) { int i, r, s; for (i = 0; i < 1000; i++) { r = raise(SIGRTMIN); if (r) t_error("raise failed: %s\n", strerror(errno)); } if (c0 != 1000) { t_error("lost signals: got %d, wanted 1000 (ischild %d forks %d)\n", c0, child, c1); } if (child) _exit(t_status); /* make sure we got all pthread_kills, then wait the forked children */ while (c1 < 100) donothing; for (i = 0; i < 100; i++) { r = wait(&s); if (r == -1) { t_error("wait failed: %s\n", strerror(errno)); } else if (!WIFEXITED(s) || WTERMSIG(s)) { t_error("child failed: pid:%d status:%d sig:%s\n", r, s, strsignal(WTERMSIG(s))); } } return 0; } TEST(raise, test) { if (IsNetbsd()) return; // why doesn't it work? if (IsOpenbsd()) return; // no support for realtime signals yet if (IsXnu()) return; // no support for realtime signals yet if (IsWindows()) return; // TODO(jart): why does it exit 128+SIGRTMIN? void *p; int r, i, s; pthread_t t; if (signal(SIGRTMIN, handler0) == SIG_ERR) t_error("registering signal handler failed: %s\n", strerror(errno)); if (signal(SIGRTMIN + 1, handler1) == SIG_ERR) t_error("registering signal handler failed: %s\n", strerror(errno)); r = pthread_create(&t, 0, start, 0); if (r) t_error("pthread_create failed: %s\n", strerror(r)); for (i = 0; i < 100; i++) { r = pthread_kill(t, SIGRTMIN + 1); if (r) t_error("phread_kill failed: %s\n", strerror(r)); } r = pthread_join(t, &p); if (r) t_error("pthread_join failed: %s\n", strerror(r)); ASSERT_EQ(0, t_status); }
5,069
118
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/signal_test.c
/*-*- 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/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/dce.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" void OnUsr1(int sig) { _exit(0); } void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio proc", 0)); } TEST(signal, test) { ASSERT_NE(SIG_ERR, signal(SIGUSR1, OnUsr1)); ASSERT_NE(-1, raise(SIGUSR1)); __die(); } //////////////////////////////////////////////////////////////////////////////// // signal round-trip delivery takes about 1µs void OnSigTrap(int sig, struct siginfo *si, void *ctx) { } void TrapBench(int n) { for (int i = 0; i < n; ++i) { __builtin_trap(); } } BENCH(signal, trapBench) { struct sigaction old; struct sigaction sabus = {.sa_sigaction = OnSigTrap}; ASSERT_SYS(0, 0, sigaction(SIGTRAP, &sabus, &old)); EZBENCH_N("signal trap", 16, TrapBench(16)); EZBENCH_N("signal trap", 256, TrapBench(256)); EZBENCH_N("signal trap", 1024, TrapBench(1024)); sigaction(SIGTRAP, &old, 0); } BENCH(signal, trapBenchSiginfo) { struct sigaction old; struct sigaction sabus = {.sa_sigaction = OnSigTrap, .sa_flags = SA_SIGINFO}; ASSERT_SYS(0, 0, sigaction(SIGTRAP, &sabus, &old)); EZBENCH_N("siginfo trap", 16, TrapBench(16)); EZBENCH_N("siginfo trap", 256, TrapBench(256)); EZBENCH_N("siginfo trap", 1024, TrapBench(1024)); sigaction(SIGTRAP, &old, 0); } #ifdef __x86_64__ void OnSigHlt(int sig, struct siginfo *si, void *vctx) { struct ucontext *ctx = vctx; ctx->uc_mcontext.rip += 1; } void HltBench(int n) { for (int i = 0; i < n; ++i) { asm("hlt"); } } BENCH(signal, hltBenchSiginfo) { struct sigaction old[2]; struct sigaction sabus = {.sa_sigaction = OnSigHlt, .sa_flags = SA_SIGINFO}; ASSERT_SYS(0, 0, sigaction(SIGSEGV, &sabus, old + 0)); ASSERT_SYS(0, 0, sigaction(SIGBUS, &sabus, old + 1)); EZBENCH_N("siginfo hlt", 16, HltBench(16)); EZBENCH_N("siginfo hlt", 256, HltBench(256)); EZBENCH_N("siginfo hlt", 1024, HltBench(1024)); sigaction(SIGSEGV, old + 0, 0); sigaction(SIGBUS, old + 1, 0); } #endif /* __x86_64__ */
4,076
102
jart/cosmopolitan
false
cosmopolitan/test/libc/calls/pledge2_test.c
/*-*- 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 2022 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/pledge.internal.h" #include "libc/calls/struct/seccomp.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/promises.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/sock.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" void SetUp(void) { if (pledge(0, 0) == -1) { fprintf(stderr, "warning: pledge() not supported on this system\n"); exit(0); } } TEST(pledge, testSoftError) { if (IsOpenbsd()) return; SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); _Exit(7); EXITS(7); } TEST(pledge, testKillThreadMode) { SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_KILL_THREAD | PLEDGE_STDERR_LOGGING; ASSERT_SYS(0, 0, pledge("stdio", 0)); socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TERMS(SIGABRT); } TEST(pledge, testKillProcessMode) { SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS | PLEDGE_STDERR_LOGGING; ASSERT_SYS(0, 0, pledge("stdio", 0)); socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TERMS(SIGABRT); } TEST(pledge, testLogMessage_inSoftyMode) { if (IsOpenbsd()) return; int fds[2]; char msg[256] = {0}; ASSERT_SYS(0, 0, pipe(fds)); SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM | PLEDGE_STDERR_LOGGING; ASSERT_SYS(0, 2, dup2(fds[1], 2)); ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(EPERM, -1, socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); EXITS(0); close(fds[1]); read(fds[0], msg, sizeof(msg)); close(fds[0]); if (IsLinux()) { ASSERT_STARTSWITH("error: protected syscall socket", msg); } } TEST(pledge, testLogMessage_onKillProcess) { int fds[2]; char msg[256] = {0}; ASSERT_SYS(0, 0, pipe(fds)); SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_KILL_THREAD | PLEDGE_STDERR_LOGGING; ASSERT_SYS(0, 2, dup2(fds[1], 2)); ASSERT_SYS(0, 0, pledge("stdio", 0)); socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TERMS(SIGABRT); close(fds[1]); read(fds[0], msg, sizeof(msg)); close(fds[0]); if (IsLinux()) { ASSERT_STARTSWITH("error: protected syscall socket", msg); } } TEST(pledge, testDoublePledge_isFine) { SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_KILL_THREAD; ASSERT_SYS(0, 0, pledge("stdio", 0)); ASSERT_SYS(0, 0, pledge("stdio", 0)); EXITS(0); } TEST(pledge, testEmptyPledge_doesntUseTrapping) { SPAWN(fork); __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS; ASSERT_SYS(0, 0, pledge("", 0)); socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TERMS(IsOpenbsd() ? SIGABRT : SIGSYS); }
4,704
121
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/rand64_test.c
/*-*- 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 2022 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/macros.internal.h" #include "libc/runtime/internal.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #define THREADS 8 #define ENTRIES 100 volatile uint64_t A[THREADS * ENTRIES]; pthread_barrier_t barrier; void SetUpOnce(void) { __enable_threads(); ASSERT_SYS(0, 0, pledge("stdio", 0)); } void OnChld(int sig) { // do nothing } dontinline void Generate(int i) { A[i] = _rand64(); } int Thrasher(void *arg, int tid) { int i, id = (intptr_t)arg; pthread_barrier_wait(&barrier); for (i = 0; i < ENTRIES; ++i) { Generate(id * ENTRIES + i); } return 0; } TEST(_rand64, testLcg_doesntProduceIdenticalValues) { int i, j; bzero(A, sizeof(A)); for (i = 0; i < ARRAYLEN(A); ++i) { A[i] = _rand64(); } for (i = 0; i < ARRAYLEN(A); ++i) { EXPECT_NE(0, A[i], "i=%d", i); for (j = 0; j < ARRAYLEN(A); ++j) { if (i == j) continue; EXPECT_NE(A[i], A[j], "i=%d j=%d", i, j); } } } TEST(_rand64, testThreadSafety_doesntProduceIdenticalValues) { int i, j, rc, ws; sigset_t ss, oldss; struct sigaction oldsa; struct spawn th[THREADS]; struct sigaction sa = {.sa_handler = OnChld, .sa_flags = SA_RESTART}; EXPECT_NE(-1, sigaction(SIGCHLD, &sa, &oldsa)); bzero(A, sizeof(A)); sigemptyset(&ss); sigaddset(&ss, SIGCHLD); EXPECT_EQ(0, sigprocmask(SIG_BLOCK, &ss, &oldss)); ASSERT_EQ(0, pthread_barrier_init(&barrier, 0, THREADS)); for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _spawn(Thrasher, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _join(th + i)); } sigaction(SIGCHLD, &oldsa, 0); sigprocmask(SIG_BLOCK, &oldss, 0); for (i = 0; i < ARRAYLEN(A); ++i) { EXPECT_NE(0, A[i], "i=%d", i); for (j = 0; j < ARRAYLEN(A); ++j) { if (i == j) continue; EXPECT_NE(A[i], A[j], "i=%d j=%d", i, j); } } ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); }
3,996
103
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/lockscale_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/struct/timespec.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "libc/time/time.h" /** * @fileoverview Lock Waiter Scalability Test * * This test can be run as follows: * * make o//test/libc/intrin/lockscale_test.com.runs V=5 TESTARGS=-b * * It's intended to demonstrate the importance of futexes. On systems * that don't have them, this test consumes orders of a magnitude more * cpu time, because there's a lot of waiters and they need to wait a * very long time. */ #define WAITERS 100 #define ITERATIONS 10000 atomic_int x; pthread_t t[WAITERS]; pthread_mutex_t lock; pthread_barrier_t barrier; void Worker(void) { pthread_mutex_lock(&lock); pthread_barrier_wait(&barrier); for (x = 0; x < ITERATIONS; ++x) { sched_yield(); } pthread_mutex_unlock(&lock); } void *Waiter(void *arg) { pthread_barrier_wait(&barrier); pthread_mutex_lock(&lock); ASSERT_EQ(ITERATIONS, x); pthread_mutex_unlock(&lock); return 0; } BENCH(lock, scalability) { int i; struct timespec t1, t2; t1 = timespec_real(); pthread_mutex_init(&lock, 0); pthread_barrier_init(&barrier, 0, WAITERS + 1); for (i = 0; i < WAITERS; ++i) { ASSERT_EQ(0, pthread_create(t + i, 0, Waiter, 0)); } Worker(); for (i = 0; i < WAITERS; ++i) { ASSERT_EQ(0, pthread_join(t[i], 0)); } pthread_barrier_destroy(&barrier); pthread_mutex_destroy(&lock); t2 = timespec_real(); printf("consumed %10g seconds real time and %10g seconds cpu time\n", timespec_tonanos(timespec_sub(t2, t1)) / 1e9, (double)clock() / CLOCKS_PER_SEC); }
3,602
87
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/strrchr_test.c
/*-*- 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/str/str.h" #include "libc/testlib/testlib.h" TEST(strrchr, test) { EXPECT_EQ(NULL, strrchr("hello", 'z')); EXPECT_STREQ("lo", strrchr("hello", 'l')); EXPECT_STREQ("llo", strchr("hello", 'l')); EXPECT_STREQ("hello", strrchr("hello", 'h')); EXPECT_STREQ("ello", strrchr("hello", 'e')); EXPECT_STREQ("o", strrchr("hello", 'o')); } TEST(strrchr, simdVectorStuffIsntBroken) { EXPECT_EQ(NULL, strrchr("--------------------------------", 'x')); EXPECT_STREQ("x", strrchr("-------------------------------x", 'x')); EXPECT_STREQ("x-------------------------------", strrchr("x-------------------------------", 'x')); EXPECT_STREQ("x" "z-------------------------------", strrchr("x" "z-------------------------------", 'x')); EXPECT_STREQ("x-------------------------------" "y-------------------------------", strrchr("x-------------------------------" "y-------------------------------", 'x')); EXPECT_STREQ("x" "z-------------------------------" "y-------------------------------", strrchr("x" "z-------------------------------" "y-------------------------------", 'x')); } TEST(strrchr16, test) { EXPECT_EQ(NULL, strrchr16(u"hello", 'z')); EXPECT_STREQ(u"lo", strrchr16(u"hello", 'l')); EXPECT_STREQ(u"llo", strchr16(u"hello", 'l')); EXPECT_STREQ(u"hello", strrchr16(u"hello", 'h')); EXPECT_STREQ(u"ello", strrchr16(u"hello", 'e')); EXPECT_STREQ(u"o", strrchr16(u"hello", 'o')); } TEST(strrchr16, simdVectorStuffIsntBroken) { EXPECT_EQ(NULL, strrchr16(u"--------------------------------", 'x')); EXPECT_STREQ(u"x", strrchr16(u"-------------------------------x", 'x')); EXPECT_STREQ(u"x-------------------------------", strrchr16(u"x-------------------------------", 'x')); EXPECT_STREQ(u"x" u"z-------------------------------", strrchr16(u"x" u"z-------------------------------", 'x')); EXPECT_STREQ(u"x-------------------------------" u"y-------------------------------", strrchr16(u"x-------------------------------" u"y-------------------------------", 'x')); EXPECT_STREQ(u"x" u"z-------------------------------" u"y-------------------------------", strrchr16(u"x" u"z-------------------------------" u"y-------------------------------", 'x')); } TEST(wcsrchr, test) { EXPECT_EQ(NULL, wcsrchr(L"hello", 'z')); EXPECT_STREQ(L"lo", wcsrchr(L"hello", 'l')); EXPECT_STREQ(L"llo", wcschr(L"hello", 'l')); EXPECT_STREQ(L"hello", wcsrchr(L"hello", 'h')); EXPECT_STREQ(L"ello", wcsrchr(L"hello", 'e')); EXPECT_STREQ(L"o", wcsrchr(L"hello", 'o')); } TEST(wcsrchr, simdVectorStuffIsntBroken) { EXPECT_EQ(NULL, wcsrchr(L"--------------------------------", 'x')); EXPECT_STREQ(L"x", wcsrchr(L"-------------------------------x", 'x')); EXPECT_STREQ(L"x-------------------------------", wcsrchr(L"x-------------------------------", 'x')); EXPECT_STREQ(L"x" L"z-------------------------------", wcsrchr(L"x" L"z-------------------------------", 'x')); EXPECT_STREQ(L"x-------------------------------" L"y-------------------------------", wcsrchr(L"x-------------------------------" L"y-------------------------------", 'x')); EXPECT_STREQ(L"x" L"z-------------------------------" L"y-------------------------------", wcsrchr(L"x" L"z-------------------------------" L"y-------------------------------", 'x')); }
5,979
120
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/describesigset_test.c
/*-*- 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 2022 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/struct/sigset.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/dce.h" #include "libc/intrin/describeflags.internal.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/testlib.h" TEST(DescribeSigset, full) { sigset_t ss; sigfillset(&ss); if (IsXnu()) { EXPECT_STREQ("~{ABRT,THR,KILL,STOP}", DescribeSigset(0, &ss)); } else if (IsOpenbsd()) { EXPECT_STREQ("~{ABRT,KILL,STOP,THR}", DescribeSigset(0, &ss)); } else { EXPECT_STREQ("~{ABRT,KILL,STOP,THR}", DescribeSigset(0, &ss)); } } TEST(DescribeSigset, present) { sigset_t ss; sigemptyset(&ss); sigaddset(&ss, SIGINT); sigaddset(&ss, SIGUSR1); EXPECT_STREQ("{INT,USR1}", DescribeSigset(0, &ss)); } TEST(DescribeSigset, absent) { sigset_t ss; sigfillset(&ss); sigdelset(&ss, SIGINT); sigdelset(&ss, SIGUSR1); if (IsXnu()) { EXPECT_STREQ("~{INT,ABRT,THR,KILL,STOP,USR1}", DescribeSigset(0, &ss)); } else if (IsBsd()) { EXPECT_STREQ("~{INT,ABRT,KILL,STOP,USR1,THR}", DescribeSigset(0, &ss)); } else { EXPECT_STREQ("~{INT,ABRT,KILL,USR1,STOP,THR}", DescribeSigset(0, &ss)); } }
2,968
59
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/pthread_mutex_lock_test.c
/*-*- 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 2022 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/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/state.internal.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlimit.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "libc/thread/wait0.internal.h" #include "third_party/nsync/mu.h" #define THREADS 8 #define ITERATIONS 512 int count; atomic_int started; atomic_int finished; pthread_mutex_t mylock; pthread_spinlock_t slock; struct spawn th[THREADS]; void SetUpOnce(void) { __enable_threads(); ASSERT_SYS(0, 0, pledge("stdio rpath", 0)); } TEST(pthread_mutex_lock, initializer) { struct sqlite3_mutex { pthread_mutex_t mutex; } mu[] = {{ PTHREAD_MUTEX_INITIALIZER, }}; } TEST(pthread_mutex_lock, normal) { pthread_mutex_t lock; pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); ASSERT_EQ(0, pthread_mutex_init(&lock, 0)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(EBUSY, pthread_mutex_trylock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_trylock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } TEST(pthread_mutex_lock, recursive) { pthread_mutex_t lock; pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(0, pthread_mutex_trylock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } TEST(pthread_mutex_lock, errorcheck) { pthread_mutex_t lock; pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); ASSERT_EQ(0, pthread_mutex_lock(&lock)); ASSERT_EQ(EDEADLK, pthread_mutex_lock(&lock)); ASSERT_EQ(EBUSY, pthread_mutex_trylock(&lock)); ASSERT_EQ(0, pthread_mutex_unlock(&lock)); ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } int MutexWorker(void *p, int tid) { int i; ++started; for (i = 0; i < ITERATIONS; ++i) { if (pthread_mutex_lock(&mylock)) { ASSERT_EQ(0, pthread_mutex_lock(&mylock)); } ++count; ASSERT_EQ(0, pthread_mutex_unlock(&mylock)); } ++finished; return 0; } TEST(pthread_mutex_lock, contention) { int i; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&mylock, &attr); pthread_mutexattr_destroy(&attr); count = 0; started = 0; finished = 0; for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _spawn(MutexWorker, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _join(th + i)); } EXPECT_EQ(THREADS, started); EXPECT_EQ(THREADS, finished); EXPECT_EQ(THREADS * ITERATIONS, count); EXPECT_EQ(0, pthread_mutex_destroy(&mylock)); } TEST(pthread_mutex_lock, rcontention) { int i; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mylock, &attr); pthread_mutexattr_destroy(&attr); count = 0; started = 0; finished = 0; for (i = 0; i < THREADS; ++i) { ASSERT_NE(-1, _spawn(MutexWorker, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { _join(th + i); } EXPECT_EQ(THREADS, started); EXPECT_EQ(THREADS, finished); EXPECT_EQ(THREADS * ITERATIONS, count); EXPECT_EQ(0, pthread_mutex_destroy(&mylock)); } TEST(pthread_mutex_lock, econtention) { int i; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mylock, &attr); pthread_mutexattr_destroy(&attr); count = 0; started = 0; finished = 0; for (i = 0; i < THREADS; ++i) { ASSERT_NE(-1, _spawn(MutexWorker, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { _join(th + i); } EXPECT_EQ(THREADS, started); EXPECT_EQ(THREADS, finished); EXPECT_EQ(THREADS * ITERATIONS, count); EXPECT_EQ(0, pthread_mutex_destroy(&mylock)); } int SpinlockWorker(void *p, int tid) { int i; ++started; for (i = 0; i < ITERATIONS; ++i) { pthread_spin_lock(&slock); ++count; pthread_spin_unlock(&slock); } ++finished; STRACE("SpinlockWorker Finished %d", tid); return 0; } TEST(pthread_spin_lock, test) { int i; count = 0; started = 0; finished = 0; EXPECT_EQ(0, pthread_spin_init(&slock, 0)); EXPECT_EQ(0, pthread_spin_trylock(&slock)); EXPECT_EQ(EBUSY, pthread_spin_trylock(&slock)); EXPECT_EQ(0, pthread_spin_unlock(&slock)); EXPECT_EQ(0, pthread_spin_lock(&slock)); EXPECT_EQ(EBUSY, pthread_spin_trylock(&slock)); EXPECT_EQ(0, pthread_spin_unlock(&slock)); for (i = 0; i < THREADS; ++i) { ASSERT_NE(-1, _spawn(SpinlockWorker, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { _join(th + i); } EXPECT_EQ(THREADS, started); EXPECT_EQ(THREADS, finished); EXPECT_EQ(THREADS * ITERATIONS, count); EXPECT_EQ(0, pthread_spin_destroy(&slock)); }
8,155
234
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/roundup2log_test.c
/*-*- 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/calls/calls.h" #include "libc/intrin/bits.h" #include "libc/testlib/testlib.h" void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio", 0)); } TEST(_roundup2log, test) { EXPECT_EQ(0, _roundup2log(0)); EXPECT_EQ(1, _roundup2log(1)); EXPECT_EQ(1, _roundup2log(2)); EXPECT_EQ(2, _roundup2log(3)); EXPECT_EQ(2, _roundup2log(4)); EXPECT_EQ(12, _roundup2log(PAGESIZE - 1)); EXPECT_EQ(12, _roundup2log(PAGESIZE)); EXPECT_EQ(13, _roundup2log(PAGESIZE + 1)); EXPECT_EQ(12, _roundup2log(PAGESIZE - 1)); EXPECT_EQ(12, _roundup2log(PAGESIZE)); EXPECT_EQ(13, _roundup2log(PAGESIZE + 1)); }
2,453
40
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/sched_yield_test.c
/*-*- 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 2022 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/testlib/testlib.h" TEST(sched_yield, test) { EXPECT_SYS(0, 0, sched_yield()); }
1,964
25
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/pthread_mutex_lock2_test.c
/*-*- 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 2022 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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define EZBENCH_COUNT 10000 #include "libc/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/struct/timespec.h" #include "libc/intrin/atomic.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "third_party/nsync/mu.h" int THREADS = 16; int ITERATIONS = 100; int count; atomic_int started; atomic_int finished; pthread_mutex_t lock; pthread_mutexattr_t attr; FIXTURE(pthread_mutex_lock, normal) { ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } FIXTURE(pthread_mutex_lock, recursive) { ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } FIXTURE(pthread_mutex_lock, errorcheck) { ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } //////////////////////////////////////////////////////////////////////////////// // TESTS int MutexWorker(void *p, int tid) { int i; ++started; for (i = 0; i < ITERATIONS; ++i) { pthread_mutex_lock(&lock); ++count; sched_yield(); pthread_mutex_unlock(&lock); } ++finished; return 0; } TEST(pthread_mutex_lock, contention) { int i; struct spawn *th = gc(malloc(sizeof(struct spawn) * THREADS)); pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&lock, &attr); pthread_mutexattr_destroy(&attr); count = 0; started = 0; finished = 0; for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _spawn(MutexWorker, (void *)(intptr_t)i, th + i)); } for (i = 0; i < THREADS; ++i) { ASSERT_SYS(0, 0, _join(th + i)); } EXPECT_EQ(THREADS, started); EXPECT_EQ(THREADS, finished); EXPECT_EQ(THREADS * ITERATIONS, count); EXPECT_EQ(0, pthread_mutex_destroy(&lock)); } //////////////////////////////////////////////////////////////////////////////// // BENCHMARKS void BenchSpinUnspin(pthread_spinlock_t *s) { pthread_spin_lock(s); pthread_spin_unlock(s); } void BenchLockUnlock(pthread_mutex_t *m) { pthread_mutex_lock(m); pthread_mutex_unlock(m); } void BenchLockUnlockNsync(nsync_mu *m) { nsync_mu_lock(m); nsync_mu_unlock(m); } BENCH(pthread_mutex_lock, bench_uncontended) { { pthread_spinlock_t s = {0}; EZBENCH2("spin 1x", donothing, BenchSpinUnspin(&s)); } { nsync_mu m = {0}; EZBENCH2("nsync 1x", donothing, BenchLockUnlockNsync(&m)); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&m, &attr); EZBENCH2("normal 1x", donothing, BenchLockUnlock(&m)); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&m, &attr); EZBENCH2("recursive 1x", donothing, BenchLockUnlock(&m)); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&m, &attr); EZBENCH2("errorcheck 1x", donothing, BenchLockUnlock(&m)); } } struct SpinContentionArgs { pthread_spinlock_t *spin; atomic_char done; atomic_char ready; }; int SpinContentionWorker(void *arg, int tid) { struct SpinContentionArgs *a = arg; while (!atomic_load_explicit(&a->done, memory_order_relaxed)) { pthread_spin_lock(a->spin); atomic_store_explicit(&a->ready, 1, memory_order_relaxed); pthread_spin_unlock(a->spin); } return 0; } struct MutexContentionArgs { pthread_mutex_t *mutex; atomic_char done; atomic_char ready; }; int MutexContentionWorker(void *arg, int tid) { struct MutexContentionArgs *a = arg; while (!atomic_load_explicit(&a->done, memory_order_relaxed)) { if (pthread_mutex_lock(a->mutex)) notpossible; atomic_store_explicit(&a->ready, 1, memory_order_relaxed); if (pthread_mutex_unlock(a->mutex)) notpossible; } return 0; } struct NsyncContentionArgs { nsync_mu *nsync; atomic_char done; atomic_char ready; }; int NsyncContentionWorker(void *arg, int tid) { struct NsyncContentionArgs *a = arg; while (!atomic_load_explicit(&a->done, memory_order_relaxed)) { nsync_mu_lock(a->nsync); atomic_store_explicit(&a->ready, 1, memory_order_relaxed); nsync_mu_unlock(a->nsync); } return 0; } BENCH(pthread_mutex_lock, bench_contended) { struct spawn t; { pthread_spinlock_t s = {0}; struct SpinContentionArgs a = {&s}; _spawn(SpinContentionWorker, &a, &t); while (!a.ready) sched_yield(); EZBENCH2("spin 2x", donothing, BenchSpinUnspin(&s)); a.done = true; _join(&t); } { nsync_mu m = {0}; struct NsyncContentionArgs a = {&m}; _spawn(NsyncContentionWorker, &a, &t); while (!a.ready) sched_yield(); EZBENCH2("nsync 2x", donothing, BenchLockUnlockNsync(&m)); a.done = true; _join(&t); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&m, &attr); struct MutexContentionArgs a = {&m}; _spawn(MutexContentionWorker, &a, &t); while (!a.ready) sched_yield(); EZBENCH2("normal 2x", donothing, BenchLockUnlock(&m)); a.done = true; _join(&t); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&m, &attr); struct MutexContentionArgs a = {&m}; _spawn(MutexContentionWorker, &a, &t); while (!a.ready) sched_yield(); EZBENCH2("recursive 2x", donothing, BenchLockUnlock(&m)); a.done = true; _join(&t); } { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&m, &attr); struct MutexContentionArgs a = {&m}; _spawn(MutexContentionWorker, &a, &t); while (!a.ready) sched_yield(); EZBENCH2("errorcheck 2x", donothing, BenchLockUnlock(&m)); a.done = true; _join(&t); } }
8,570
262
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/strlen_test.c
/*-*- 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/bits.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" char u8[] = "utf-8 ☻"; char16_t u16[] = u"utf16 ☻"; wchar_t u32[] = L"utf32 ☻"; size_t strlen_pure(const char *s) { size_t n = 0; while (*s++) ++n; return n; } TEST(strlen, usageExample_c11) { _Alignas(16) char ugh[] = "eeeeeeeeeeeeeee\017"; EXPECT_EQ(1, strlen_pure(ugh + 15)); EXPECT_EQ(6 + 3, strlen(u8)); EXPECT_EQ(7, strlen16(u16)); EXPECT_EQ(7, wcslen(u32)); } TEST(strlen, usageExample_c99) { EXPECT_EQ(6 + 3, strlen(u8)); EXPECT_EQ(7, strlen16(u16)); EXPECT_EQ(7, wcslen(u32)); } TEST(strlen, whatMemoryLooksLike) { EXPECT_BINEQ(u"utf-8 Γÿ╗ ", u8); /* ← thompson-pike encoded */ EXPECT_BINEQ(u"u t f 1 6   ;&  ", u16); EXPECT_BINEQ(u"u   t   f   3   2       ;&      ", u32); } TEST(strlen, test_const) { const char buf[] = "hellothere"; ASSERT_EQ(0, strlen("")); ASSERT_EQ(0, strnlen("e", 0)); ASSERT_EQ(10, strlen(buf)); } TEST(strlen, test_nonconst) { char buf[256]; unsigned i; for (i = 0; i < 255; ++i) buf[i] = i + 1; buf[i] = '\0'; ASSERT_EQ(255, strlen(buf)); } TEST(strnlen, testconst) { ASSERT_EQ(0, strnlen_s(NULL, 3)); ASSERT_EQ(0, strnlen("", 3)); ASSERT_EQ(0, strnlen("a", 0)); ASSERT_EQ(3, strnlen("123", 3)); ASSERT_EQ(2, strnlen("123", 2)); ASSERT_EQ(3, strnlen("123", 4)); } TEST(strlen, testnonconst) { /* this test case is a great example of why we need: "m"(*(char(*)[0x7fffffff])StR) rather than: "m"(*StR) */ char buf[256]; unsigned i; for (i = 0; i < 250; ++i) buf[i] = i + 1; buf[i] = '\0'; ASSERT_EQ(250, strlen(buf)); } TEST(strnlen_s, null_ReturnsZero) { ASSERT_EQ(0, strnlen_s(NULL, 3)); } TEST(wcsnlen_s, null_ReturnsZero) { ASSERT_EQ(0, wcsnlen_s(NULL, 3)); } TEST(strnlen, nulNotFound_ReturnsSize) { int sizes[] = {1, 2, 7, 8, 15, 16, 31, 32, 33}; for (unsigned i = 0; i < ARRAYLEN(sizes); ++i) { char *buf = malloc(sizes[i]); memset(buf, ' ', sizes[i]); ASSERT_EQ(sizes[i], strnlen(buf, sizes[i]), "%d", sizes[i]); free(buf); } } TEST(strnlen_s, nulNotFound) { char buf[3] = {1, 2, 3}; ASSERT_EQ(3, strnlen_s(buf, 3)); } TEST(wcsnlen_s, nulNotFound) { wchar_t buf[3] = {1, 2, 3}; ASSERT_EQ(3, wcsnlen_s(buf, 3)); } TEST(strlen, fuzz) { char *b; size_t n, n1, n2; for (n = 2; n < 1026; ++n) { b = rngset(calloc(1, n), n - 1, _rand64, -1); n1 = strlen(b); n2 = strlen_pure(b); ASSERT_EQ(n1, n2, "%#.*s", n, b); n1 = strlen(b + 1); n2 = strlen_pure(b + 1); ASSERT_EQ(n1, n2); free(b); } } BENCH(strlen, bench) { extern size_t strlen_(const char *) asm("strlen"); extern size_t strlen_pure_(const char *) asm("strlen_pure"); static char b[2048]; static char c[512]; static char d[256]; memset(b, -1, sizeof(b) - 1); memset(c, -1, sizeof(c) - 1); memset(d, -1, sizeof(d) - 1); EZBENCH2("strlen 1", donothing, strlen_("")); EZBENCH2("strlen_pure 1", donothing, strlen_pure_("")); EZBENCH2("strlen 2", donothing, strlen_("1")); EZBENCH2("strlen_pure 2", donothing, strlen_pure_("1")); EZBENCH2("strlen 3", donothing, strlen_("11")); EZBENCH2("strlen_pure 3", donothing, strlen_pure_("11")); EZBENCH2("strlen 4", donothing, strlen_("113")); EZBENCH2("strlen_pure 4", donothing, strlen_pure_("113")); EZBENCH2("strlen 7", donothing, strlen_("123456")); EZBENCH2("strlen_pure 7", donothing, strlen_pure_("123456")); EZBENCH2("strlen 8", donothing, strlen_("1234567")); EZBENCH2("strlen_pure 8", donothing, strlen_pure_("1234567")); EZBENCH2("strlen 9", donothing, strlen_("12345678")); EZBENCH2("strlen_pure 9", donothing, strlen_pure_("12345678")); EZBENCH2("strlen 11", donothing, strlen_("12345678aa")); EZBENCH2("strlen_pure 11", donothing, strlen_pure_("12345678aa")); EZBENCH2("strlen 13", donothing, strlen_("12345678aabb")); EZBENCH2("strlen_pure 13", donothing, strlen_pure_("12345678aabb")); EZBENCH2("strlen 16", donothing, strlen_("123456781234567")); EZBENCH2("strlen_pure 16", donothing, strlen_pure_("123456781234567")); EZBENCH2("strlen 17", donothing, strlen_("123456781234567e")); EZBENCH2("strlen_pure 17", donothing, strlen_pure_("123456781234567e")); EZBENCH2("strlen 34", donothing, strlen_("123456781234567e123456781234567ee")); EZBENCH2("strlen_pure 34", donothing, strlen_pure_("123456781234567e123456781234567ee")); EZBENCH2("strlen 68", donothing, strlen_("123456781234567e123456781234567ee123456781234567e1234567812" "34567eee")); EZBENCH2("strlen_pure 68", donothing, strlen_pure_("123456781234567e123456781234567ee123456781234567e12345" "6781234567eee")); EZBENCH2("strlen 256", donothing, strlen_(d)); EZBENCH2("strlen_pure 256", donothing, strlen_pure_(d)); EZBENCH2("strlen 512", donothing, strlen_(c)); EZBENCH2("strlen_pure 512", donothing, strlen_pure_(c)); EZBENCH2("strlen 2048", donothing, strlen_(b)); EZBENCH2("strlen_pure 2048", donothing, strlen_pure_(b)); }
7,182
185
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/popcnt_test.c
/*-*- 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/calls/calls.h" #include "libc/intrin/popcnt.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/hyperion.h" #include "libc/testlib/testlib.h" void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio rpath", 0)); } TEST(popcnt, test) { EXPECT_EQ(32, popcnt(0x5555555555555555)); EXPECT_EQ(32, popcnt(VEIL("r", 0x5555555555555555))); EXPECT_EQ(32, (popcnt)(VEIL("r", 0x5555555555555555))); } BENCH(popcnt, bench) { EZBENCH2("popcnt", donothing, EXPROPRIATE(popcnt(VEIL("r", 0x5555555555555555)))); EZBENCH2("(popcnt)", donothing, EXPROPRIATE((popcnt)(VEIL("r", 0x5555555555555555)))); EZBENCH_N("_countbits", kHyperionSize, _countbits(kHyperion, kHyperionSize)); }
2,558
42
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/pshuf_test.c
/*-*- 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/pshufd.h" #include "libc/intrin/pshufhw.h" #include "libc/intrin/pshuflw.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" #define T(f, m) \ f(a, x, m); \ (f)(b, x, m); \ EXPECT_EQ(0, memcmp(a, b, 16)) TEST(pshuflw, test) { int i, j; int16_t x[8], a[8], b[8]; for (i = 0; i < 10; ++i) { for (j = 0; j < 8; ++j) x[j] = rand(); T(pshuflw, 0b00000000); T(pshuflw, 0b00000001); T(pshuflw, 0b00000011); T(pshuflw, 0b00001100); T(pshuflw, 0b00001101); T(pshuflw, 0b00001111); T(pshuflw, 0b00110000); T(pshuflw, 0b00110001); T(pshuflw, 0b00110011); T(pshuflw, 0b00111100); T(pshuflw, 0b00111101); T(pshuflw, 0b00111111); T(pshuflw, 0b01000000); T(pshuflw, 0b01000001); T(pshuflw, 0b01000011); T(pshuflw, 0b01001100); T(pshuflw, 0b01001101); T(pshuflw, 0b01001111); T(pshuflw, 0b01110000); T(pshuflw, 0b01110001); T(pshuflw, 0b01110011); T(pshuflw, 0b01111100); T(pshuflw, 0b01111101); T(pshuflw, 0b01111111); T(pshuflw, 0b11000000); T(pshuflw, 0b11000001); T(pshuflw, 0b11000011); T(pshuflw, 0b11001100); T(pshuflw, 0b11001101); T(pshuflw, 0b11001111); T(pshuflw, 0b11110000); T(pshuflw, 0b11110001); T(pshuflw, 0b11110011); T(pshuflw, 0b11111100); T(pshuflw, 0b11111101); T(pshuflw, 0b11111111); } } TEST(pshufhw, test) { int i, j; int16_t x[8], a[8], b[8]; for (i = 0; i < 10; ++i) { for (j = 0; j < 8; ++j) x[j] = rand(); T(pshufhw, 0b00000000); T(pshufhw, 0b00000001); T(pshufhw, 0b00000011); T(pshufhw, 0b00001100); T(pshufhw, 0b00001101); T(pshufhw, 0b00001111); T(pshufhw, 0b00110000); T(pshufhw, 0b00110001); T(pshufhw, 0b00110011); T(pshufhw, 0b00111100); T(pshufhw, 0b00111101); T(pshufhw, 0b00111111); T(pshufhw, 0b01000000); T(pshufhw, 0b01000001); T(pshufhw, 0b01000011); T(pshufhw, 0b01001100); T(pshufhw, 0b01001101); T(pshufhw, 0b01001111); T(pshufhw, 0b01110000); T(pshufhw, 0b01110001); T(pshufhw, 0b01110011); T(pshufhw, 0b01111100); T(pshufhw, 0b01111101); T(pshufhw, 0b01111111); T(pshufhw, 0b11000000); T(pshufhw, 0b11000001); T(pshufhw, 0b11000011); T(pshufhw, 0b11001100); T(pshufhw, 0b11001101); T(pshufhw, 0b11001111); T(pshufhw, 0b11110000); T(pshufhw, 0b11110001); T(pshufhw, 0b11110011); T(pshufhw, 0b11111100); T(pshufhw, 0b11111101); T(pshufhw, 0b11111111); } } TEST(pshufd, test) { int i, j; int32_t x[4], a[4], b[4]; for (i = 0; i < 10; ++i) { for (j = 0; j < 4; ++j) x[j] = rand(); T(pshufd, 0b00000000); T(pshufd, 0b00000001); T(pshufd, 0b00000011); T(pshufd, 0b00001100); T(pshufd, 0b00001101); T(pshufd, 0b00001111); T(pshufd, 0b00110000); T(pshufd, 0b00110001); T(pshufd, 0b00110011); T(pshufd, 0b00111100); T(pshufd, 0b00111101); T(pshufd, 0b00111111); T(pshufd, 0b01000000); T(pshufd, 0b01000001); T(pshufd, 0b01000011); T(pshufd, 0b01001100); T(pshufd, 0b01001101); T(pshufd, 0b01001111); T(pshufd, 0b01110000); T(pshufd, 0b01110001); T(pshufd, 0b01110011); T(pshufd, 0b01111100); T(pshufd, 0b01111101); T(pshufd, 0b01111111); T(pshufd, 0b11000000); T(pshufd, 0b11000001); T(pshufd, 0b11000011); T(pshufd, 0b11001100); T(pshufd, 0b11001101); T(pshufd, 0b11001111); T(pshufd, 0b11110000); T(pshufd, 0b11110001); T(pshufd, 0b11110011); T(pshufd, 0b11111100); T(pshufd, 0b11111101); T(pshufd, 0b11111111); } }
5,521
162
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/dos2errno_test.c
/*-*- 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/dce.h" #include "libc/errno.h" #include "libc/intrin/dos2errno.internal.h" #include "libc/intrin/kprintf.h" #include "libc/nt/errors.h" #include "libc/sock/internal.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" TEST(__dos2errno, test) { #ifdef __x86__ EXPECT_EQ(0, __dos2errno(0)); EXPECT_EQ(EACCES, __dos2errno(kNtErrorSectorNotFound)); EXPECT_EQ(EADDRNOTAVAIL, __dos2errno(kNtErrorInvalidNetname)); EXPECT_EQ(EAGAIN, __dos2errno(33)); if (IsWindows()) { EXPECT_EQ(ENOLCK, __dos2errno(kNtErrorNotLocked)); } #endif }
2,403
39
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/describegidlist_test.c
/*-*- 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 2022 Gavin Arthur Hayes │ │ │ │ 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/groups.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/testlib/testlib.h" TEST(DescribeGidList, test) { uint32_t list[] = {8, 67, 530, 9}; uint32_t biglist[] = {8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9}; EXPECT_STREQ("n/a", DescribeGidList(-1, sizeof(list) / sizeof(list[0]), list)); EXPECT_STREQ("n/a", DescribeGidList(0, -1, list)); EXPECT_STREQ("{}", DescribeGidList(0, 0, list)); EXPECT_STREQ("NULL", DescribeGidList(0, 9001, NULL)); EXPECT_STREQ("{8, 67, 530, 9}", DescribeGidList(0, sizeof(list) / sizeof(list[0]), list)); EXPECT_STREQ("{8, 67, 530}", DescribeGidList(0, sizeof(list) / sizeof(list[0]) - 1, list)); EXPECT_STREQ( "{8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, " "530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, 67, 530, 9, 8, ...", DescribeGidList(0, sizeof(biglist) / sizeof(biglist[0]), biglist)); }
2,940
42
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/integralarithmetic_test.c
/*-*- 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/bits.h" #include "libc/calls/calls.h" #include "libc/limits.h" #include "libc/macros.internal.h" #include "libc/testlib/testlib.h" #define ROR(w, k) (CheckUnsigned(w) >> (k) | (w) << (sizeof(w) * 8 - (k))) #define ROL(w, k) ((w) << (k) | CheckUnsigned(w) >> (sizeof(w) * 8 - (k))) void SetUpOnce(void) { ASSERT_SYS(0, 0, pledge("stdio", 0)); } TEST(TwosComplementBane, LiteralsThatAreLiterallyTheSameNumber) { EXPECT_EQ(4, sizeof(INT_MIN)); EXPECT_EQ(8, sizeof(-2147483648)); EXPECT_TRUE(TYPE_SIGNED(-2147483648)); EXPECT_FALSE(TYPE_SIGNED(0x80000000)); EXPECT_FALSE(TYPE_SIGNED(-0x80000000)); } TEST(RotateRight, Test) { EXPECT_EQ(0x41122334u, ROR(0x11223344u, 4)); EXPECT_EQ(0x44112233u, ROR(0x11223344u, 8)); EXPECT_EQ(0x34411223u, ROR(0x11223344u, 12)); EXPECT_EQ(0x33441122u, ROR(0x11223344u, 16)); } TEST(RotateLeft, Test) { EXPECT_EQ(0x12233441u, ROL(0x11223344u, 4)); EXPECT_EQ(0x22334411u, ROL(0x11223344u, 8)); EXPECT_EQ(0x23344112u, ROL(0x11223344u, 12)); EXPECT_EQ(0x33441122u, ROL(0x11223344u, 16)); }
2,906
53
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/getenv_test.c
/*-*- 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/runtime/runtime.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" TEST(getenv, test) { putenv("X=y"); EXPECT_STREQ("y", getenv("X")); unsetenv("X"); EXPECT_EQ(NULL, getenv("X")); } BENCH(getenv, bench) { char *getenv_(const char *) asm("getenv"); EZBENCH2("getenv(TZ)", donothing, getenv_("TZ")); }
2,215
35
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/pthread_atfork_test.c
/*-*- 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 2022 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/dce.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/stdio/lock.internal.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "third_party/nsync/mu.h" int Ai; const char *A[16]; // clang-format off void prepare1(void) { A[Ai++] = "prepare1"; } void prepare2(void) { A[Ai++] = "prepare2"; } void parent1(void) { A[Ai++] = "parent1"; } void parent2(void) { A[Ai++] = "parent2"; } void child1(void) { A[Ai++] = "child1"; } void child2(void) { A[Ai++] = "child2"; } // clang-format on void *ForceThreadingMode(void *arg) { return 0; } TEST(pthread_atfork, test) { int pid; __enable_threads(); SPAWN(fork); ASSERT_EQ(0, pthread_atfork(prepare1, parent1, child1)); ASSERT_EQ(0, pthread_atfork(prepare2, parent2, child2)); flockfile(stdout); SPAWN(fork); flockfile(stdout); ASSERT_STREQ("prepare2", A[0]); ASSERT_STREQ("prepare1", A[1]); ASSERT_STREQ("child1", A[2]); ASSERT_STREQ("child2", A[3]); funlockfile(stdout); EXITS(0); funlockfile(stdout); ASSERT_STREQ("prepare2", A[0]); ASSERT_STREQ("prepare1", A[1]); ASSERT_STREQ("parent1", A[2]); ASSERT_STREQ("parent2", A[3]); EXITS(0); } pthread_mutex_t mu; void mu_lock(void) { pthread_mutex_lock(&mu); } void mu_unlock(void) { pthread_mutex_unlock(&mu); } void mu_funlock(void) { pthread_mutex_init(&mu, 0); } void *Worker(void *arg) { for (int i = 0; i < 20; ++i) { mu_lock(); usleep(20); mu_unlock(); SPAWN(fork); mu_lock(); usleep(1); mu_unlock(); mu_lock(); mu_unlock(); EXITS(0); mu_lock(); mu_unlock(); } return 0; } TEST(pthread_atfork, torture) { if (IsWindows()) return; // TODO(jart): why do we get EBADF? it worked before pthread_mutex_init(&mu, 0); pthread_atfork(mu_lock, mu_unlock, mu_funlock); int i, n = 4; pthread_t *t = _gc(malloc(sizeof(pthread_t) * n)); for (i = 0; i < n; ++i) { ASSERT_EQ(0, pthread_create(t + i, 0, Worker, 0)); } for (i = 0; i < n; ++i) { ASSERT_EQ(0, pthread_join(t[i], 0)); } }
4,002
114
jart/cosmopolitan
false
cosmopolitan/test/libc/intrin/pmulhrsw_test.c
/*-*- 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/pmulhrsw.h" #include "dsp/core/q.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" #include "tool/viz/lib/formatstringtable-testlib.h" #define ACCURACY powf(10, -4) #define FOR8(STMT) \ for (y = 0; y < 8; ++y) { \ STMT; \ } #define FOR88(STMT) \ for (y = 0; y < 8; ++y) { \ for (x = 0; x < 8; ++x) { \ STMT; \ } \ } FIXTURE(pmulhrsw, disableHardwareExtensions) { #ifdef __x86_64__ memset((/*unconst*/ void *)kCpuids, 0, sizeof(kCpuids)); #endif } TEST(pmulhrsw, testLimits) { int i; short A[8], B[8]; const short kPmulhrswTorture[][3] = { {SHRT_MIN, SHRT_MIN, SHRT_MIN}, {SHRT_MIN, -1, 1}, {SHRT_MIN, 0, 0}, {SHRT_MIN, 1, -1}, {-1, SHRT_MIN, 1}, {-1, -1, 0}, {-1, 0, 0}, {-1, 1, 0}, {-1, SHRT_MAX, -1}, {0, SHRT_MIN, 0}, {0, -1, 0}, {0, 0, 0}, {0, 1, 0}, {0, SHRT_MAX, 0}, {1, SHRT_MIN, -1}, {1, -1, 0}, {1, 0, 0}, {1, 1, 0}, {1, SHRT_MAX, 1}, {SHRT_MAX, -1, -1}, {SHRT_MAX, 0, 0}, {SHRT_MAX, 1, 1}, }; memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B)); for (i = 0; i < ARRAYLEN(kPmulhrswTorture); ++i) { A[0] = kPmulhrswTorture[i][0]; B[0] = kPmulhrswTorture[i][1]; pmulhrsw(A, A, B); EXPECT_EQ(kPmulhrswTorture[i][2], A[0], "pmulhrsw(%hd,%hd)→%hd", kPmulhrswTorture[i][0], kPmulhrswTorture[i][1], A[0]); } for (i = 0; i < ARRAYLEN(kPmulhrswTorture); ++i) { A[0] = kPmulhrswTorture[i][0]; B[0] = kPmulhrswTorture[i][1]; (pmulhrsw)(A, A, B); EXPECT_EQ(kPmulhrswTorture[i][2], A[0], "pmulhrsw(%hd,%hd)→%hd", kPmulhrswTorture[i][0], kPmulhrswTorture[i][1], A[0]); } } TEST(pmulhrsw, testFakeFloat) { int y, x; float R[8][8]; float Q[8][8]; short QQ[8][8]; short QD[8][8]; short QM[8][8]; float D[8][8] = /* clang-format off */ { {.929142, .147545, .17061, .765948, .874296, .925816, .073955, .10664}, {.986743, .311924, .550892, .789301, .873408, .743376, .434021, .143184}, {.405694, .080979, .894841, .625169, .465688, .877854, .97371, .264295}, {.781549, .20985, .599735, .943491, .059135, .045806, .770352, .081862}, {.584684, .701568, .022328, .177048, .412809, .185355, .992654, .252167}, {.327565, .693878, .722431, .84546, .060729, .383725, .589365, .435534}, {.942854, .62579, .177928, .809653, .143087, .624792, .851914, .072192}, {.750157, .968502, .270052, .087784, .406716, .510766, .959699, .416836}, }; float M[8][8] = { {.009407, .882863, .000511, .565419, .69844, .035758, .817049, .249922}, {.072144, .703228, .479622, .121608, .288279, .55492, .387912, .140278}, {.047205, .748263, .683692, .805669, .137764, .858753, .787804, .059591}, {.682286, .787778, .503573, .473795, .437378, .573171, .135995, .341236}, {.588849, .723929, .624155, .710336, .480396, .462433, .865392, .071378}, {.598636, .575209, .758356, .518674, .043861, .542574, .355843, .02014}, {.359636, .95607, .698256, .492859, .149454, .795121, .790219, .357014}, {.401603, .928426, .416429, .11747, .643411, .907285, .074102, .411959}, } /* clang-format on */; FOR88(QD[y][x] = F2Q(15, D[y][x])); FOR88(QM[y][x] = F2Q(15, M[y][x])); /* for (y = 0; y < 8; ++y) { */ /* for (x = 0; x < 8; ++x) { */ /* CHECK_NE(8, x); */ /* CHECK_NE(8, y); */ /* QM[y][x] = F2Q(15, M[y][x]); */ /* CHECK_NE(8, x); */ /* CHECK_NE(8, y); */ /* } */ /* } */ FOR8(pmulhrsw(QQ[y], QD[y], QM[y])); FOR88(Q[y][x] = Q2F(15, QQ[y][x])); FOR88(R[y][x] = D[y][x] * M[y][x]); FOR88(EXPECT_TRUE(ACCURACY > Q[y][x] - R[y][x])); }
5,694
135
jart/cosmopolitan
false