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/libc/thread/posixthread.internal.h
#ifndef COSMOPOLITAN_LIBC_THREAD_POSIXTHREAD_INTERNAL_H_ #define COSMOPOLITAN_LIBC_THREAD_POSIXTHREAD_INTERNAL_H_ #include "libc/calls/struct/sched_param.h" #include "libc/calls/struct/sigset.h" #include "libc/runtime/runtime.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/nsync/dll.h" #define PT_OWNSTACK 1 #define PT_STATIC 2 #define PT_ASYNC 4 #define PT_NOCANCEL 8 #define PT_MASKED 16 #define PT_INCANCEL 32 #define PT_OPENBSD_KLUDGE 64 #define PT_EXITING 128 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ // LEGAL TRANSITIONS ┌──> TERMINATED ─┐ // pthread_create ─┬─> JOINABLE ─┴┬─> DETACHED ───┴─> ZOMBIE // └──────────────┘ enum PosixThreadStatus { // this is a running thread that needs pthread_join() // // the following transitions are possible: // // - kPosixThreadJoinable -> kPosixThreadTerminated if start_routine() // returns, or is longjmp'd out of by pthread_exit(), and the thread // is waiting to be joined. // // - kPosixThreadJoinable -> kPosixThreadDetached if pthread_detach() // is called on this thread. kPosixThreadJoinable, // this is a managed thread that'll be cleaned up by the library. // // the following transitions are possible: // // - kPosixThreadDetached -> kPosixThreadZombie if start_routine() // returns, or is longjmp'd out of by pthread_exit(), and the thread // is waiting to be joined. kPosixThreadDetached, // this is a joinable thread that terminated. // // the following transitions are possible: // // - kPosixThreadTerminated -> _pthread_free() will happen when // pthread_join() is called by the user. // - kPosixThreadTerminated -> kPosixThreadZombie will happen when // pthread_detach() is called by the user. kPosixThreadTerminated, // this is a detached thread that terminated. // // the following transitions are possible: // // - kPosixThreadZombie -> _pthread_free() will happen whenever // convenient, e.g. pthread_create() entry or atexit handler. kPosixThreadZombie, }; struct PosixThread { int flags; // 0x00: see PT_* constants _Atomic(int) cancelled; // 0x04: thread has bad beliefs _Atomic(enum PosixThreadStatus) status; _Atomic(int) ptid; // transitions 0 → tid void *(*start)(void *); // creation callback void *arg; // start's parameter void *rc; // start's return value char *altstack; // thread sigaltstack char *tls; // bottom of tls allocation struct CosmoTib *tib; // middle of tls allocation nsync_dll_element_ list; // list of threads jmp_buf exiter; // for pthread_exit pthread_attr_t attr; struct _pthread_cleanup_buffer *cleanup; }; typedef void (*atfork_f)(void); extern nsync_dll_list_ _pthread_list; extern pthread_spinlock_t _pthread_lock; extern _Atomic(pthread_key_dtor) _pthread_key_dtor[PTHREAD_KEYS_MAX] _Hide; int _pthread_atfork(atfork_f, atfork_f, atfork_f) _Hide; int _pthread_reschedule(struct PosixThread *) _Hide; int _pthread_setschedparam_freebsd(int, int, const struct sched_param *) _Hide; void _pthread_zombify(struct PosixThread *) _Hide; void _pthread_free(struct PosixThread *) _Hide; void _pthread_onfork_prepare(void) _Hide; void _pthread_onfork_parent(void) _Hide; void _pthread_onfork_child(void) _Hide; void _pthread_ungarbage(void) _Hide; int _pthread_cancel_sys(void) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_THREAD_POSIXTHREAD_INTERNAL_H_ */
3,734
104
jart/cosmopolitan
false
cosmopolitan/libc/thread/sem_destroy.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/intrin/atomic.h" #include "libc/limits.h" #include "libc/sysv/errfuns.h" #include "libc/thread/semaphore.h" /** * Destroys unnamed semaphore. * * If `sem` was successfully initialized by sem_init() then * sem_destroy() may be called multiple times, before it may be * reinitialized again by calling sem_init(). * * Calling sem_destroy() on a semaphore created by sem_open() has * undefined behavior. Using `sem` after calling sem_destroy() is * undefined behavior that will cause semaphore APIs to either crash or * raise `EINVAL` until `sem` is passed to sem_init() again. * * @param sem was created by sem_init() * @return 0 on success, or -1 w/ errno * @raise EINVAL if `sem` wasn't valid * @raise EBUSY if `sem` has waiters */ int sem_destroy(sem_t *sem) { int waiters; _npassert(sem->sem_magic != SEM_MAGIC_NAMED); if (sem->sem_magic != SEM_MAGIC_UNNAMED) return einval(); waiters = atomic_load_explicit(&sem->sem_waiters, memory_order_relaxed); _unassert(waiters >= 0); if (waiters) return ebusy(); atomic_store_explicit(&sem->sem_value, INT_MIN, memory_order_relaxed); return 0; }
2,997
52
jart/cosmopolitan
false
cosmopolitan/libc/thread/wait0.internal.h
#ifndef COSMOPOLITAN_LIBC_INTRIN_WAIT0_H_ #define COSMOPOLITAN_LIBC_INTRIN_WAIT0_H_ #include "libc/atomic.h" #include "libc/calls/struct/timespec.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ errno_t _wait0(const atomic_int *, struct timespec *) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_INTRIN_WAIT0_H_ */
386
13
jart/cosmopolitan
false
cosmopolitan/libc/thread/thread2.h
#ifndef COSMOPOLITAN_LIBC_INTRIN_PTHREAD2_H_ #define COSMOPOLITAN_LIBC_INTRIN_PTHREAD2_H_ #include "libc/calls/struct/cpuset.h" #include "libc/calls/struct/sched_param.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/timespec.h" #include "libc/runtime/stack.h" #include "libc/thread/thread.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* clang-format off */ int pthread_attr_getschedparam(const pthread_attr_t *, struct sched_param *) paramsnonnull(); int pthread_attr_getsigmask_np(const pthread_attr_t *, sigset_t *) paramsnonnull((1)); int pthread_attr_setschedparam(pthread_attr_t *, const struct sched_param *) paramsnonnull(); int pthread_attr_setsigmask_np(pthread_attr_t *, const sigset_t *) paramsnonnull((1)); int pthread_cond_timedwait(pthread_cond_t *, pthread_mutex_t *, const struct timespec *) paramsnonnull((1, 2)); int pthread_getaffinity_np(pthread_t, size_t, cpu_set_t *) paramsnonnull(); int pthread_getschedparam(pthread_t, int *, struct sched_param *) paramsnonnull(); int pthread_setaffinity_np(pthread_t, size_t, const cpu_set_t *) paramsnonnull(); int pthread_setschedparam(pthread_t, int, const struct sched_param *) paramsnonnull(); int pthread_timedjoin_np(pthread_t, void **, struct timespec *); /* clang-format off */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_INTRIN_PTHREAD2_H_ */
1,405
28
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_condattr_destroy.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/str/str.h" #include "libc/thread/thread.h" /** * Destroys condition attributes. * * @return 0 on success, or error on failure */ errno_t pthread_condattr_destroy(pthread_condattr_t *attr) { memset(attr, -1, sizeof(*attr)); return 0; }
2,095
31
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_atfork.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/state.internal.h" #include "libc/errno.h" #include "libc/intrin/atomic.h" #include "libc/intrin/kmalloc.h" #include "libc/mem/mem.h" #include "libc/runtime/memtrack.internal.h" #include "libc/str/str.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" static struct AtForks { pthread_spinlock_t lock; struct AtFork { struct AtFork *p[2]; atfork_f f[3]; } * list; } _atforks; static void _pthread_purge(void) { nsync_dll_element_ *e; while ((e = nsync_dll_first_(_pthread_list))) { _pthread_list = nsync_dll_remove_(_pthread_list, e); _pthread_free(e->container); } } static void _pthread_onfork(int i) { struct AtFork *a; struct PosixThread *pt; _unassert(0 <= i && i <= 2); if (!i) pthread_spin_lock(&_atforks.lock); for (a = _atforks.list; a; a = a->p[!i]) { if (a->f[i]) a->f[i](); _atforks.list = a; } if (i) pthread_spin_unlock(&_atforks.lock); } void _pthread_onfork_prepare(void) { _pthread_onfork(0); pthread_spin_lock(&_pthread_lock); __fds_lock(); __mmi_lock(); __kmalloc_lock(); } void _pthread_onfork_parent(void) { __kmalloc_unlock(); __mmi_unlock(); __fds_unlock(); pthread_spin_unlock(&_pthread_lock); _pthread_onfork(1); } void _pthread_onfork_child(void) { struct CosmoTib *tib; struct PosixThread *pt; pthread_mutexattr_t attr; extern pthread_mutex_t __mmi_lock_obj; tib = __get_tls(); pt = (struct PosixThread *)tib->tib_pthread; // let's choose to let the new process live. // even though it's unclear what to do with this kind of race. atomic_store_explicit(&pt->cancelled, false, memory_order_relaxed); // wipe core runtime locks __kmalloc_unlock(); pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&__mmi_lock_obj, &attr); pthread_mutex_init(&__fds_lock_obj, &attr); pthread_spin_init(&_pthread_lock, 0); // call user-supplied forked child callbacks _pthread_onfork(2); // delete other threads that existed before forking // this must come after onfork, since it calls free _pthread_list = nsync_dll_remove_(_pthread_list, &pt->list); _pthread_purge(); _pthread_list = nsync_dll_make_first_in_list_(_pthread_list, &pt->list); } int _pthread_atfork(atfork_f prepare, atfork_f parent, atfork_f child) { int rc; struct AtFork *a; if (!(a = kmalloc(sizeof(struct AtFork)))) return ENOMEM; a->f[0] = prepare; a->f[1] = parent; a->f[2] = child; pthread_spin_lock(&_atforks.lock); a->p[0] = 0; a->p[1] = _atforks.list; if (_atforks.list) _atforks.list->p[0] = a; _atforks.list = a; pthread_spin_unlock(&_atforks.lock); rc = 0; return rc; }
4,611
121
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_barrierattr_destroy.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/str/str.h" #include "libc/thread/thread.h" /** * Destroys barrier attributes. * * @return 0 on success, or error on failure */ errno_t pthread_barrierattr_destroy(pthread_barrierattr_t *attr) { memset(attr, -1, sizeof(*attr)); return 0; }
2,099
31
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_decimate_np.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/intrin/atomic.h" #include "libc/runtime/runtime.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/nsync/dll.h" /** * Releases memory of detached threads that have terminated. */ void pthread_decimate_np(void) { nsync_dll_element_ *e; struct PosixThread *pt; enum PosixThreadStatus status; StartOver: pthread_spin_lock(&_pthread_lock); for (e = nsync_dll_first_(_pthread_list); e; e = nsync_dll_next_(_pthread_list, e)) { pt = (struct PosixThread *)e->container; if (pt->tib == __get_tls()) continue; status = atomic_load_explicit(&pt->status, memory_order_acquire); if (status != kPosixThreadZombie) break; if (!atomic_load_explicit(&pt->tib->tib_tid, memory_order_acquire)) { _pthread_list = nsync_dll_remove_(_pthread_list, e); pthread_spin_unlock(&_pthread_lock); _pthread_free(pt); goto StartOver; } } pthread_spin_unlock(&_pthread_lock); }
2,850
50
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_zombify.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/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "third_party/nsync/dll.h" void _pthread_zombify(struct PosixThread *pt) { pthread_spin_lock(&_pthread_lock); _pthread_list = nsync_dll_remove_(_pthread_list, &pt->list); _pthread_list = nsync_dll_make_first_in_list_(_pthread_list, &pt->list); pthread_spin_unlock(&_pthread_lock); }
2,214
29
jart/cosmopolitan
false
cosmopolitan/libc/thread/mktls.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 "ape/sections.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/asancodes.h" #include "libc/intrin/atomic.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/thread/spawn.h" #include "libc/thread/tls.h" #define I(x) ((uintptr_t)x) void Bzero(void *, size_t) asm("bzero"); // gcc bug static char *_mktls_finish(struct CosmoTib **out_tib, char *mem, struct CosmoTib *tib) { struct CosmoTib *old; old = __get_tls(); Bzero(tib, sizeof(*tib)); tib->tib_self = tib; tib->tib_self2 = tib; tib->tib_ftrace = old->tib_ftrace; tib->tib_strace = old->tib_strace; tib->tib_sigmask = old->tib_sigmask; atomic_store_explicit(&tib->tib_tid, -1, memory_order_relaxed); if (out_tib) { *out_tib = tib; } return mem; } static char *_mktls_below(struct CosmoTib **out_tib) { char *tls; struct CosmoTib *neu; // allocate memory for tdata, tbss, and tib tls = memalign(TLS_ALIGNMENT, I(_tls_size) + sizeof(struct CosmoTib)); if (!tls) return 0; // poison memory between tdata and tbss if (IsAsan()) { __asan_poison(tls + I(_tdata_size), I(_tbss_offset) - I(_tdata_size), kAsanProtected); } // initialize .tdata if (I(_tdata_size)) { memmove(tls, _tdata_start, I(_tdata_size)); } // clear .tbss Bzero(tls + I(_tbss_offset), I(_tbss_size)); // set up thread information block return _mktls_finish(out_tib, tls, (struct CosmoTib *)(tls + I(_tls_size))); } static char *_mktls_above(struct CosmoTib **out_tib) { size_t hiz, siz; char *mem, *dtv, *tls; struct CosmoTib *tib, *old; // allocate memory for tdata, tbss, and tib hiz = ROUNDUP(sizeof(*tib) + 2 * sizeof(void *), I(_tls_align)); siz = hiz + I(_tls_size); mem = memalign(TLS_ALIGNMENT, siz); if (!mem) return 0; // poison memory between tdata and tbss if (IsAsan()) { __asan_poison(mem + hiz + I(_tdata_size), I(_tbss_offset) - I(_tdata_size), kAsanProtected); } tib = (struct CosmoTib *)mem; dtv = mem + sizeof(*tib); tls = mem + hiz; // set dtv ((uintptr_t *)dtv)[0] = 1; ((void **)dtv)[1] = tls; // initialize .tdata if (I(_tdata_size)) { memmove(tls, _tdata_start, I(_tdata_size)); } // clear .tbss if (I(_tbss_size)) { Bzero(tls + I(_tbss_offset), I(_tbss_size)); } // set up thread information block return _mktls_finish(out_tib, mem, tib); } /** * Allocates thread-local storage memory for new thread. * @return buffer that must be released with free() */ char *_mktls(struct CosmoTib **out_tib) { __require_tls(); #ifdef __x86_64__ return _mktls_below(out_tib); #else return _mktls_above(out_tib); #endif }
4,678
130
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_mutexattr_setpshared.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/errno.h" #include "libc/thread/thread.h" /** * Sets mutex process sharing. * * @param pshared can be one of * - `PTHREAD_PROCESS_PRIVATE` (default) * - `PTHREAD_PROCESS_SHARED` * @return 0 on success, or error on failure * @raises EINVAL if `pshared` is invalid */ errno_t pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared) { switch (pshared) { case PTHREAD_PROCESS_SHARED: case PTHREAD_PROCESS_PRIVATE: attr->_pshared = pshared; return 0; default: return EINVAL; } }
2,388
41
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_tryjoin_np.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/thread/thread2.h" /** * Joins thread if it's already terminated. * * Multiple threads joining the same thread is undefined behavior. If a * deferred or masked cancellation happens to the calling thread either * before or during the waiting process then the target thread will not * be joined. Calling pthread_join() on a non-joinable thread, e.g. one * that's been detached, is undefined behavior. If a thread attempts to * join itself, then the behavior is undefined. * * @param value_ptr if non-null will receive pthread_exit() argument * if the thread called pthread_exit(), or `PTHREAD_CANCELED` if * pthread_cancel() destroyed the thread instead * @return 0 on success, or errno on error * @raise ECANCELED if calling thread was cancelled in masked mode * @cancellationpoint * @returnserrno * @threadsafe */ errno_t pthread_tryjoin_np(pthread_t thread, void **value_ptr) { return pthread_timedjoin_np(thread, value_ptr, &timespec_zero); }
2,824
43
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlock_init.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/thread/thread.h" /** * Initializes read-write lock. * * @param attr may be null * @return 0 on success, or error number on failure */ errno_t pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr) { *rwlock = (pthread_rwlock_t){0}; return 0; }
2,158
32
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_setsigmask_np.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/str/str.h" #include "libc/thread/thread2.h" /** * Sets signal mask on thread attributes object. * * For example, to spawn a thread that won't interfere with signals: * * pthread_t id; * sigset_t mask; * pthread_attr_t attr; * sigfillset(&mask); * pthread_attr_init(&attr); * pthread_attr_setsigmask_np(&attr, &mask); * pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); * pthread_create(&id, &attr, Worker, 0); * pthread_attr_destroy(&attr); * * @param attr is the thread attributes object * @param sigmask will be copied into attributes, or if it's null, then * the existing signal mask presence on the object will be cleared * @return 0 on success, or errno on error */ errno_t pthread_attr_setsigmask_np(pthread_attr_t *attr, const sigset_t *sigmask) { _Static_assert(sizeof(attr->__sigmask) == sizeof(*sigmask), ""); if (sigmask) { attr->__havesigmask = true; memcpy(attr->__sigmask, sigmask, sizeof(*sigmask)); } else { attr->__havesigmask = false; } return 0; }
2,946
53
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlockattr_destroy.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/str/str.h" #include "libc/thread/thread.h" /** * Destroys read-write lock attributes. * * @return 0 on success, or error on failure */ errno_t pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr) { memset(attr, -1, sizeof(*attr)); return 0; }
2,105
31
jart/cosmopolitan
false
cosmopolitan/libc/thread/sem_wait.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/thread/semaphore.h" /** * Locks semaphore. * * @return 0 on success, or -1 w/ errno * @raise ECANCELED if calling thread was cancelled in masked mode * @raise EINTR if signal was delivered instead * @raise EDEADLK if deadlock was detected * @raise EINVAL if `sem` is invalid * @cancellationpoint */ int sem_wait(sem_t *sem) { return sem_timedwait(sem, 0); }
2,221
34
jart/cosmopolitan
false
cosmopolitan/libc/thread/README.md
# Cosmpolitan POSIX Threads Library Cosmopolitan Libc implements threading as it is written in The Open Group Base Specifications Issue 7, 2018 edition IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008) in addition to GNU extensions.
240
6
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_destroy.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/str/str.h" #include "libc/thread/thread.h" /** * Destroys pthread attributes. * * @return 0 on success, or errno on error */ errno_t pthread_attr_destroy(pthread_attr_t *attr) { memset(attr, -1, sizeof(*attr)); return 0; }
2,083
31
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_kill.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/errno.h" #include "libc/intrin/atomic.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" /** * Sends signal to thread. * * @return 0 on success, or errno on error * @raise ESRCH if `tid` was valid but no such thread existed * @raise EAGAIN if `RLIMIT_SIGPENDING` was exceeded * @raise EINVAL if `tid` or `sig` was invalid * @raise EPERM if permission was denied * @asyncsignalsafe */ errno_t pthread_kill(pthread_t thread, int sig) { int e, rc, tid; struct PosixThread *p; if (!(rc = pthread_getunique_np(thread, &tid))) { e = errno; p = (struct PosixThread *)thread; if (!__tkill(tid, sig, p->tib)) { rc = 0; } else { rc = errno; errno = e; } } return rc; }
2,682
51
jart/cosmopolitan
false
cosmopolitan/libc/thread/openbsd.internal.h
#ifndef COSMOPOLITAN_LIBC_THREAD_OPENBSD_INTERNAL_H_ #define COSMOPOLITAN_LIBC_THREAD_OPENBSD_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct __tfork { void *tf_tcb; int32_t *tf_tid; void *tf_stack; }; int __tfork_thread(struct __tfork *, size_t, void (*)(void *), void *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_THREAD_OPENBSD_INTERNAL_H_ */
439
17
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_setstack.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/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/thread/thread.h" /** * Configures custom allocated stack for thread, e.g. * * pthread_t id; * pthread_attr_t attr; * char *stk = _mapstack(); * pthread_attr_init(&attr); * pthread_attr_setstack(&attr, stk, GetStackSize()); * pthread_create(&id, &attr, func, 0); * pthread_attr_destroy(&attr); * pthread_join(id, 0); * _freestack(stk); * * Your stack must have at least `PTHREAD_STACK_MIN` bytes, which * Cosmpolitan Libc defines as `GetStackSize()`. It's a link-time * constant used by Actually Portable Executable that's 128 kb by * default. See libc/runtime/stack.h for docs on your stack limit * since the APE ELF phdrs are the one true source of truth here. * * Cosmpolitan Libc runtime magic (e.g. ftrace) and memory safety * (e.g. kprintf) assumes that stack sizes are two-powers and are * aligned to that two-power. Conformance isn't required since we * say caveat emptor to those who don't maintain these invariants * please consider using _mapstack() which always does it perfect * or use `mmap(0, GetStackSize() << 1, ...)` for a bigger stack. * * Unlike pthread_attr_setstacksize(), this function permits just * about any parameters and will change the values and allocation * as needed to conform to the mandatory requirements of the host * operating system even if it doesn't meet the stricter needs of * Cosmopolitan Libc userspace libraries. For example with malloc * allocations, things like page size alignment, shall be handled * automatically for compatibility with existing codebases. * * @param stackaddr is address of stack allocated by caller, and * may be NULL in which case default behavior is restored * @param stacksize is size of caller allocated stack * @return 0 on success, or errno on error * @raise EINVAL if parameters were unacceptable * @see pthread_attr_setstacksize() */ errno_t pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize) { if (!stackaddr) { attr->__stackaddr = 0; attr->__stacksize = 0; return 0; } if (stacksize < PTHREAD_STACK_MIN || (IsAsan() && !__asan_is_valid(stackaddr, stacksize))) { return EINVAL; } attr->__stackaddr = stackaddr; attr->__stacksize = stacksize; return 0; }
4,241
80
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_getinheritsched.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/thread/thread.h" /** * Returns thread inherit schedule attribute. */ errno_t pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched) { *inheritsched = attr->__inheritsched; return 0; }
2,100
29
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_getschedparam.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/thread/posixthread.internal.h" #include "libc/thread/thread2.h" /** * Gets most recently set scheduling of thread. */ errno_t pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param) { struct PosixThread *pt = (struct PosixThread *)thread; *policy = pt->attr.__schedpolicy; *param = (struct sched_param){pt->attr.__schedparam}; return 0; }
2,255
32
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_getattr_np.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/intrin/atomic.h" #include "libc/str/str.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" /** * Gets thread attributes. * * These attributes are copied from the ones supplied when * pthread_create() was called. However this function supplies * additional runtime information too: * * 1. The detached state. You can use pthread_attr_getdetachstate() on * the `attr` result to see, for example, if a thread detached itself * or some other thread detached it, after it was spawned. * * 2. The thread's stack. You can use pthread_attr_getstack() to see the * address and size of the stack that was allocated by cosmo for your * thread. This is useful for knowing where the stack is. It can also * be useful If you explicitly configured a stack too, since we might * have needed to slightly tune the address and size to meet platform * requirements. This function returns information that reflects that * * 3. You can view changes pthread_create() may have made to the stack * guard size by calling pthread_attr_getguardsize() on `attr` * * @param attr is output argument that receives attributes, which should * find its way to pthread_attr_destroy() when it's done being used * @return 0 on success, or errno on error * @raise ENOMEM is listed as a possible result by LSB 5.0 */ errno_t pthread_getattr_np(pthread_t thread, pthread_attr_t *attr) { struct PosixThread *pt = (struct PosixThread *)thread; memcpy(attr, &pt->attr, sizeof(pt->attr)); switch (atomic_load_explicit(&pt->status, memory_order_relaxed)) { case kPosixThreadJoinable: case kPosixThreadTerminated: attr->__detachstate = PTHREAD_CREATE_JOINABLE; break; case kPosixThreadDetached: case kPosixThreadZombie: attr->__detachstate = PTHREAD_CREATE_DETACHED; break; default: unreachable; } return 0; }
3,758
67
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlockattr_setpshared.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/errno.h" #include "libc/thread/thread.h" /** * Sets read-write lock process sharing. * * @param pshared can be one of * - `PTHREAD_PROCESS_PRIVATE` (default) * - `PTHREAD_PROCESS_SHARED` (unsupported) * @return 0 on success, or error on failure * @raises EINVAL if `pshared` is invalid */ errno_t pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr, int pshared) { switch (pshared) { case PTHREAD_PROCESS_PRIVATE: *attr = pshared; return 0; default: return EINVAL; } }
2,372
40
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_setname_np.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/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/asmflag.h" #include "libc/intrin/atomic.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/pr.h" #include "libc/thread/posixthread.internal.h" static errno_t pthread_setname_impl(pthread_t thread, const char *name) { char path[128], *p; int e, fd, rc, tid, len; if ((rc = pthread_getunique_np(thread, &tid))) return rc; len = strlen(name); if (IsLinux()) { e = errno; if (tid == gettid()) { if (prctl(PR_SET_NAME, name) == -1) { rc = errno; errno = e; return rc; } } else { p = path; p = stpcpy(p, "/proc/self/task/"); p = FormatUint32(p, tid); p = stpcpy(p, "/comm"); if ((fd = sys_openat(AT_FDCWD, path, O_WRONLY | O_CLOEXEC, 0)) == -1) { rc = errno; errno = e; return rc; } rc = sys_write(fd, name, len); rc |= sys_close(fd); if (rc == -1) { rc = errno; errno = e; return rc; } } if (len > 15) { // linux is documented as truncating here. we still set the name // since the limit might be raised in the future checking return // value of this function is a bummer. Grep it for TASK_COMM_LEN return ERANGE; } return 0; } else if (IsFreebsd()) { char cf; int ax, dx; asm volatile(CFLAG_ASM("syscall") : CFLAG_CONSTRAINT(cf), "=a"(ax), "=d"(dx) : "1"(323 /* thr_set_name */), "D"(tid), "S"(name) : "rcx", "r8", "r9", "r10", "r11", "memory"); return !cf ? 0 : ax; } else if (IsNetbsd()) { char cf; int ax, dx; asm volatile(CFLAG_ASM("syscall") : CFLAG_CONSTRAINT(cf), "=a"(ax), "=d"(dx) : "1"(323 /* _lwp_setname */), "D"(tid), "S"(name) : "rcx", "r8", "r9", "r10", "r11", "memory"); return !cf ? 0 : ax; } else { return ENOSYS; } } /** * Registers custom name of thread with system, e.g. * * void *worker(void *arg) { * pthread_setname_np(pthread_self(), "justine"); * pause(); * return 0; * } * * int main(int argc, char *argv[]) { * pthread_t id; * pthread_create(&id, 0, worker, 0); * pthread_join(id, 0); * } * * ProTip: The `htop` software is good at displaying thread names. * * @return 0 on success, or errno on error * @raise ERANGE if length of `name` exceeded system limit, in which * case the name may have still been set with os using truncation * @raise ENOSYS on MacOS, Windows, and OpenBSD * @see pthread_getname_np() */ errno_t pthread_setname_np(pthread_t thread, const char *name) { errno_t rc; BLOCK_CANCELLATIONS; rc = pthread_setname_impl(thread, name); ALLOW_CANCELLATIONS; return rc; }
4,916
128
jart/cosmopolitan
false
cosmopolitan/libc/thread/tls.h
#ifndef COSMOPOLITAN_LIBC_THREAD_TLS_H_ #define COSMOPOLITAN_LIBC_THREAD_TLS_H_ #define TLS_ALIGNMENT 64 #define TIB_FLAG_TIME_CRITICAL 1 #define TIB_FLAG_VFORKED 2 #define TIB_FLAG_WINCRASHING 4 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct CosmoFtrace { /* 16 */ bool ft_once; /* 0 */ bool ft_noreentry; /* 1 */ int ft_skew; /* 4 */ int64_t ft_lastaddr; /* 8 */ }; struct CosmoTib { struct CosmoTib *tib_self; /* 0x00 */ struct CosmoFtrace tib_ftracer; /* 0x08 */ void *tib_garbages; /* 0x18 */ intptr_t tib_locale; /* 0x20 */ intptr_t tib_pthread; /* 0x28 */ struct CosmoTib *tib_self2; /* 0x30 */ _Atomic(int32_t) tib_tid; /* 0x38 transitions -1 → tid → 0 */ int32_t tib_errno; /* 0x3c */ uint64_t tib_flags; /* 0x40 */ void *tib_nsync; int tib_ftrace; /* inherited */ int tib_strace; /* inherited */ uint64_t tib_sigmask; /* inherited */ void *tib_reserved4; void *tib_reserved5; void *tib_reserved6; void *tib_reserved7; void *tib_keys[128]; }; extern int __threaded; extern unsigned __tls_index; #ifdef __x86_64__ extern bool __tls_enabled; #define __tls_enabled_set(x) __tls_enabled = x #else #define __tls_enabled true #define __tls_enabled_set(x) (void)0 #endif void __require_tls(void); void __set_tls(struct CosmoTib *); #ifdef __x86_64__ /** * Returns location of thread information block. * * This can't be used in privileged functions. */ #define __get_tls() \ ({ \ struct CosmoTib *_t; \ asm("mov\t%%fs:0,%0" : "=r"(_t) : /* no inputs */ : "memory"); \ _t; \ }) #define __adj_tls(tib) (tib) #elif defined(__aarch64__) #define __get_tls() \ ({ \ register struct CosmoTib *_t asm("x28"); \ _t - 1; \ }) #define __adj_tls(tib) ((struct CosmoTib *)(tib) + 1) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_THREAD_TLS_H_ */
2,332
80
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_getdetachstate.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/thread/thread.h" /** * Gets thread detachable attribute. * * @param detachstate is set to one of the following * - `PTHREAD_CREATE_JOINABLE` (default) * - `PTHREAD_CREATE_DETACHED` * @return 0 on success, or error on failure */ errno_t pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate) { *detachstate = attr->__detachstate; return 0; }
2,267
34
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_condattr_getpshared.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/thread/thread.h" /** * Gets condition process sharing. * * @param pshared is set to one of the following * - `PTHREAD_PROCESS_PRIVATE` (default) * - `PTHREAD_PROCESS_SHARED` * @return 0 on success, or error on failure */ errno_t pthread_condattr_getpshared(const pthread_condattr_t *attr, int *pshared) { *pshared = *attr; return 0; }
2,242
34
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_barrier_init.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/errno.h" #include "libc/thread/thread.h" #include "third_party/nsync/counter.h" /** * Initializes barrier. * * @param attr may be null * @param count is how many threads need to call pthread_barrier_wait() * before the barrier is released, which must be greater than zero * @return 0 on success, or error number on failure * @raise EINVAL if `count` isn't greater than zero * @raise ENOMEM if insufficient memory exists */ errno_t pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned count) { nsync_counter c; if (!count) return EINVAL; if (!(c = nsync_counter_new(count))) return ENOMEM; *barrier = (pthread_barrier_t){._nsync = c}; return 0; }
2,619
42
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_detach.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/errno.h" #include "libc/intrin/atomic.h" #include "libc/intrin/strace.internal.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "third_party/nsync/dll.h" /** * Asks POSIX thread to free itself automatically upon termination. * * If this function is used, then it's important to use pthread_exit() * rather than exit() since otherwise your program isn't guaranteed to * gracefully terminate. * * Detaching a non-joinable thread is undefined behavior. For example, * pthread_detach() can't be called twice on the same thread. * * @return 0 on success, or errno with error * @returnserrno * @threadsafe */ errno_t pthread_detach(pthread_t thread) { struct PosixThread *pt; enum PosixThreadStatus status, transition; for (pt = (struct PosixThread *)thread;;) { status = atomic_load_explicit(&pt->status, memory_order_acquire); if (status == kPosixThreadJoinable) { transition = kPosixThreadDetached; } else if (status == kPosixThreadTerminated) { transition = kPosixThreadZombie; } else { unreachable; } if (atomic_compare_exchange_weak_explicit(&pt->status, &status, transition, memory_order_release, memory_order_relaxed)) { break; } } if (transition == kPosixThreadZombie) { _pthread_zombify(pt); } pthread_decimate_np(); return 0; }
3,419
68
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_getscope.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/thread/thread.h" /** * Gets contention scope attribute. * * @return 0 on success, or errno on error */ errno_t pthread_attr_getscope(const pthread_attr_t *attr, int *contentionscope) { *contentionscope = attr->__contentionscope; return 0; }
2,131
31
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlockattr_getpshared.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/thread/thread.h" /** * Gets read-write lock process sharing. * * @param pshared is set to one of the following * - `PTHREAD_PROCESS_PRIVATE` (default) * - `PTHREAD_PROCESS_SHARED` (unsupported) * @return 0 on success, or error on failure */ errno_t pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *attr, int *pshared) { *pshared = *attr; return 0; }
2,268
34
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_init.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/stack.h" #include "libc/thread/thread.h" /** * Initializes pthread attributes. * * @return 0 on success, or errno on error */ errno_t pthread_attr_init(pthread_attr_t *attr) { *attr = (pthread_attr_t){ .__stacksize = GetStackSize(), .__guardsize = GUARDSIZE, }; return 0; }
2,156
34
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_setscope.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/dce.h" #include "libc/errno.h" #include "libc/thread/thread.h" /** * Sets contention scope attribute. * * @param contentionscope may be one of: * - `PTHREAD_SCOPE_SYSTEM` to fight the system for resources * - `PTHREAD_SCOPE_PROCESS` to fight familiar threads for resources * @return 0 on success, or errno on error * @raise ENOTSUP if `contentionscope` isn't supported on host OS * @raise EINVAL if `contentionscope` was invalid */ errno_t pthread_attr_setscope(pthread_attr_t *attr, int contentionscope) { switch (contentionscope) { case PTHREAD_SCOPE_SYSTEM: attr->__contentionscope = contentionscope; return 0; case PTHREAD_SCOPE_PROCESS: // Linux almost certainly doesn't support thread scoping // FreeBSD has THR_SYSTEM_SCOPE but it's not implemented // OpenBSD pthreads claims support but really ignores it // NetBSD pthreads claims support, but really ignores it // XNU sources appear to make no mention of thread scope // WIN32 documentation says nothing about thread scoping return ENOTSUP; default: return EINVAL; } }
2,973
50
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlock_wrlock.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/thread/thread.h" #include "third_party/nsync/mu.h" /** * Acquires write lock on read-write lock. * * @return 0 on success, or errno on error */ errno_t pthread_rwlock_wrlock(pthread_rwlock_t *rwlock) { nsync_mu_lock((nsync_mu *)rwlock); rwlock->_iswrite = 1; return 0; }
2,133
32
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_condattr_init.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/thread/thread.h" /** * Initializes condition attributes. * * @return 0 on success, or error on failure */ errno_t pthread_condattr_init(pthread_condattr_t *attr) { *attr = 0; return 0; }
2,047
30
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_getstack.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/stack.h" #include "libc/thread/thread.h" /** * Returns configuration for thread stack. * * This is a getter for a configuration attribute. By default, zeros are * returned. If pthread_attr_setstack() was called earlier, then this'll * return those earlier supplied values. * * @param stackaddr will be set to stack address in bytes * @return 0 on success, or errno on error * @see pthread_attr_setstacksize() */ errno_t pthread_attr_getstack(const pthread_attr_t *attr, void **stackaddr, size_t *stacksize) { *stackaddr = attr->__stackaddr; *stacksize = attr->__stacksize; return 0; }
2,491
39
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlock_unlock.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/thread/thread.h" #include "third_party/nsync/mu.h" /** * Unlocks read-write lock. * * @return 0 on success, or errno on error * @raise EINVAL if lock is in a bad state */ errno_t pthread_rwlock_unlock(pthread_rwlock_t *rwlock) { if (rwlock->_iswrite) { rwlock->_iswrite = 0; nsync_mu_unlock((nsync_mu *)rwlock); } else { nsync_mu_runlock((nsync_mu *)rwlock); } return 0; }
2,250
37
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_sigmask.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/errno.h" /** * Examines and/or changes blocked signals on current thread. * * @return 0 on success, or errno on error * @asyncsignalsafe */ errno_t pthread_sigmask(int how, const sigset_t *set, sigset_t *old) { int rc, e = errno; if (!sigprocmask(how, set, old)) { rc = 0; } else { rc = errno; errno = e; } return rc; }
2,237
38
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_timedjoin_np.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/struct/timespec.h" #include "libc/errno.h" #include "libc/intrin/atomic.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread2.h" #include "libc/thread/tls.h" #include "libc/thread/wait0.internal.h" /** * Waits for thread to terminate. * * Multiple threads joining the same thread is undefined behavior. If a * deferred or masked cancellation happens to the calling thread either * before or during the waiting process then the target thread will not * be joined. Calling pthread_join() on a non-joinable thread, e.g. one * that's been detached, is undefined behavior. If a thread attempts to * join itself, then the behavior is undefined. * * @param value_ptr if non-null will receive pthread_exit() argument * if the thread called pthread_exit(), or `PTHREAD_CANCELED` if * pthread_cancel() destroyed the thread instead * @param abstime specifies an absolute deadline or the timestamp of * when we'll stop waiting; if this is null we will wait forever * @return 0 on success, or errno on error * @raise ECANCELED if calling thread was cancelled in masked mode * @raise EBUSY if `abstime` deadline elapsed * @cancellationpoint * @returnserrno * @threadsafe */ errno_t pthread_timedjoin_np(pthread_t thread, void **value_ptr, struct timespec *abstime) { errno_t rc; struct PosixThread *pt; enum PosixThreadStatus status; pt = (struct PosixThread *)thread; status = atomic_load_explicit(&pt->status, memory_order_acquire); // "The behavior is undefined if the value specified by the thread // argument to pthread_join() does not refer to a joinable thread." // ──Quoth POSIX.1-2017 _unassert(status == kPosixThreadJoinable || status == kPosixThreadTerminated); if (!(rc = _wait0(&pt->tib->tib_tid, abstime))) { pthread_spin_lock(&_pthread_lock); _pthread_list = nsync_dll_remove_(_pthread_list, &pt->list); pthread_spin_unlock(&_pthread_lock); if (value_ptr) { *value_ptr = pt->rc; } _pthread_free(pt); pthread_decimate_np(); } return 0; }
4,004
73
jart/cosmopolitan
false
cosmopolitan/libc/thread/sem_open.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/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/atomic.h" #include "libc/intrin/nopl.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/limits.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/errfuns.h" #include "libc/thread/semaphore.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" static struct Semaphores { pthread_once_t once; pthread_mutex_t lock; struct Semaphore { struct Semaphore *next; sem_t *sem; char *path; bool dead; int refs; } * list; } g_semaphores; static void sem_open_lock(void) { pthread_mutex_lock(&g_semaphores.lock); } static void sem_open_unlock(void) { pthread_mutex_unlock(&g_semaphores.lock); } static void sem_open_funlock(void) { pthread_mutex_init(&g_semaphores.lock, 0); } static void sem_open_setup(void) { sem_open_funlock(); pthread_atfork(sem_open_lock, sem_open_unlock, sem_open_funlock); } static void sem_open_init(void) { pthread_once(&g_semaphores.once, sem_open_setup); } #ifdef _NOPL0 #define sem_open_lock() _NOPL0("__threadcalls", sem_open_lock) #define sem_open_unlock() _NOPL0("__threadcalls", sem_open_unlock) #endif static sem_t *sem_open_impl(const char *path, int oflag, unsigned mode, unsigned value) { int fd; sem_t *sem; struct stat st; oflag |= O_RDWR | O_CLOEXEC; if ((fd = openat(AT_FDCWD, path, oflag, mode)) == -1) { return SEM_FAILED; } _npassert(!fstat(fd, &st)); if (st.st_size < PAGESIZE && ftruncate(fd, PAGESIZE) == -1) { _npassert(!close(fd)); return SEM_FAILED; } sem = mmap(0, PAGESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (sem != MAP_FAILED) { atomic_store_explicit(&sem->sem_value, value, memory_order_relaxed); sem->sem_magic = SEM_MAGIC_NAMED; sem->sem_dev = st.st_dev; sem->sem_ino = st.st_ino; sem->sem_pshared = true; } else { sem = SEM_FAILED; } _npassert(!close(fd)); return sem; } static struct Semaphore *sem_open_find(const char *path) { struct Semaphore *s; for (s = g_semaphores.list; s; s = s->next) { if (!strcmp(path, s->path)) { return s; } } return 0; } static struct Semaphore *sem_open_reopen(const char *path) { int e = errno; struct stat st; struct Semaphore *s; for (s = g_semaphores.list; s; s = s->next) { if (!s->dead && // !strcmp(path, s->path)) { if (!fstatat(AT_FDCWD, path, &st, 0) && // st.st_dev == s->sem->sem_dev && // st.st_ino == s->sem->sem_ino) { return s; } else { errno = e; s->dead = true; } } } return 0; } static struct Semaphore *sem_open_get(const sem_t *sem, struct Semaphore ***out_prev) { struct Semaphore *s, *t, **p; for (p = &g_semaphores.list, s = *p; s; p = &s->next, s = s->next) { if (s && sem == s->sem) { *out_prev = p; return s; } } return 0; } /** * Initializes and opens named semaphore. * * This function tracks open semaphore objects within a process. When a * process calls sem_open() multiple times with the same name, then the * same shared memory address will be returned, unless it was unlinked. * * @param name is arbitrary string that begins with a slash character * @param oflag can have any of: * - `O_CREAT` to create the named semaphore if it doesn't exist, * in which case two additional arguments must be supplied * - `O_EXCL` to raise `EEXIST` if semaphore already exists * @param mode is octal mode bits, required if `oflag & O_CREAT` * @param value is initial of semaphore, required if `oflag & O_CREAT` * @return semaphore object which needs sem_close(), or SEM_FAILED w/ errno * @raise ENOSPC if file system is full when `name` would be `O_CREAT`ed * @raise EINVAL if `oflag` has bits other than `O_CREAT | O_EXCL` * @raise EINVAL if `value` is negative or exceeds `SEM_VALUE_MAX` * @raise EEXIST if `O_CREAT|O_EXCL` is used and semaphore exists * @raise EACCES if we didn't have permission to create semaphore * @raise EACCES if recreating open semaphore pending an unlink * @raise EMFILE if process `RLIMIT_NOFILE` has been reached * @raise ENFILE if system-wide file limit has been reached * @raise ENOMEM if we require more vespene gas * @raise EINTR if signal handler was called * @threadsafe */ sem_t *sem_open(const char *name, int oflag, ...) { sem_t *sem; va_list va; struct Semaphore *s; unsigned mode = 0, value = 0; char *path, pathbuf[PATH_MAX]; if (oflag & ~(O_CREAT | O_EXCL)) { einval(); return SEM_FAILED; } if (oflag & O_CREAT) { va_start(va, oflag); mode = va_arg(va, unsigned); value = va_arg(va, unsigned); va_end(va); if (value > SEM_VALUE_MAX) { einval(); return SEM_FAILED; } } if (!(path = sem_path_np(name, pathbuf, sizeof(pathbuf)))) { return SEM_FAILED; } BLOCK_CANCELLATIONS; sem_open_init(); sem_open_lock(); if ((s = sem_open_reopen(path))) { if (s->sem->sem_lazydelete) { if (oflag & O_CREAT) { eacces(); } else { enoent(); } sem = SEM_FAILED; } else if (~oflag & O_EXCL) { sem = s->sem; atomic_fetch_add_explicit(&sem->sem_prefs, 1, memory_order_acq_rel); ++s->refs; } else { eexist(); sem = SEM_FAILED; } } else if ((s = calloc(1, sizeof(struct Semaphore)))) { if ((s->path = strdup(path))) { if ((sem = sem_open_impl(path, oflag, mode, value)) != SEM_FAILED) { atomic_fetch_add_explicit(&sem->sem_prefs, 1, memory_order_acq_rel); s->next = g_semaphores.list; s->sem = sem; s->refs = 1; g_semaphores.list = s; } else { free(s->path); free(s); } } else { free(s); sem = SEM_FAILED; } } else { sem = SEM_FAILED; } sem_open_unlock(); ALLOW_CANCELLATIONS; return sem; } /** * Closes named semaphore. * * Calling sem_close() on a semaphore not created by sem_open() has * undefined behavior. Using `sem` after calling sem_close() from either * the current process or forked processes sharing the same address is * also undefined behavior. If any threads in this process or forked * children are currently blocked on `sem` then calling sem_close() has * undefined behavior. * * @param sem was created with sem_open() * @return 0 on success, or -1 w/ errno */ int sem_close(sem_t *sem) { int rc, prefs; bool unmap, delete; struct Semaphore *s, **p; _npassert(sem->sem_magic == SEM_MAGIC_NAMED); sem_open_init(); sem_open_lock(); _npassert((s = sem_open_get(sem, &p))); prefs = atomic_fetch_add_explicit(&sem->sem_prefs, -1, memory_order_acq_rel); _npassert(s->refs > 0); if ((unmap = !--s->refs)) { _npassert(prefs > 0); delete = sem->sem_lazydelete && prefs == 1; *p = s->next; } else { _npassert(prefs > 1); delete = false; } sem_open_unlock(); if (unmap) { _npassert(!munmap(sem, PAGESIZE)); } if (delete) { rc = unlink(s->path); } if (unmap) { free(s->path); free(s); } return 0; } /** * Removes named semaphore. * * This causes the file resource to be deleted. If processes have this * semaphore currently opened, then on platforms like Windows deletion * may be postponed until the last process calls sem_close(). * * @param name can be absolute path or should be component w/o slashes * @return 0 on success, or -1 w/ errno * @raise ACCESS if Windows is being fussy about deleting open files * @raise EPERM if pledge() is in play w/o `cpath` promise * @raise ENOENT if named semaphore doesn't exist * @raise EACCES if permission is denied * @raise ENAMETOOLONG if too long */ int sem_unlink(const char *name) { int rc, e = errno; struct Semaphore *s; char *path, pathbuf[PATH_MAX]; if (!(path = sem_path_np(name, pathbuf, sizeof(pathbuf)))) return -1; if ((rc = unlink(path)) == -1 && IsWindows() && errno == EACCES) { sem_open_init(); sem_open_lock(); if ((s = sem_open_find(path))) { s->sem->sem_lazydelete = true; errno = e; rc = 0; } sem_open_unlock(); } return rc; }
10,393
319
jart/cosmopolitan
false
cosmopolitan/libc/thread/thread.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 += LIBC_THREAD LIBC_THREAD_ARTIFACTS += LIBC_THREAD_A LIBC_THREAD = $(LIBC_THREAD_A_DEPS) $(LIBC_THREAD_A) LIBC_THREAD_A = o/$(MODE)/libc/thread/thread.a LIBC_THREAD_A_FILES := $(wildcard libc/thread/*) LIBC_THREAD_A_HDRS = $(filter %.h,$(LIBC_THREAD_A_FILES)) LIBC_THREAD_A_SRCS_C = $(filter %.c,$(LIBC_THREAD_A_FILES)) LIBC_THREAD_A_SRCS_S = $(filter %.S,$(LIBC_THREAD_A_FILES)) LIBC_THREAD_A_SRCS = \ $(LIBC_THREAD_A_SRCS_S) \ $(LIBC_THREAD_A_SRCS_C) LIBC_THREAD_A_OBJS = \ $(LIBC_THREAD_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(LIBC_THREAD_A_SRCS_C:%.c=o/$(MODE)/%.o) LIBC_THREAD_A_CHECKS = \ $(LIBC_THREAD_A).pkg \ $(LIBC_THREAD_A_HDRS:%=o/$(MODE)/%.ok) LIBC_THREAD_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_INTRIN \ LIBC_MEM \ LIBC_NT_KERNEL32 \ LIBC_NT_SYNCHRONIZATION \ LIBC_RUNTIME \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_NEXGEN32E \ THIRD_PARTY_NSYNC \ THIRD_PARTY_NSYNC_MEM LIBC_THREAD_A_DEPS := \ $(call uniq,$(foreach x,$(LIBC_THREAD_A_DIRECTDEPS),$($(x)))) $(LIBC_THREAD_A): \ libc/thread/ \ $(LIBC_THREAD_A).pkg \ $(LIBC_THREAD_A_OBJS) $(LIBC_THREAD_A).pkg: \ $(LIBC_THREAD_A_OBJS) \ $(foreach x,$(LIBC_THREAD_A_DIRECTDEPS),$($(x)_A).pkg) LIBC_THREAD_LIBS = $(foreach x,$(LIBC_THREAD_ARTIFACTS),$($(x))) LIBC_THREAD_SRCS = $(foreach x,$(LIBC_THREAD_ARTIFACTS),$($(x)_SRCS)) LIBC_THREAD_HDRS = $(foreach x,$(LIBC_THREAD_ARTIFACTS),$($(x)_HDRS)) LIBC_THREAD_CHECKS = $(foreach x,$(LIBC_THREAD_ARTIFACTS),$($(x)_CHECKS)) LIBC_THREAD_OBJS = $(foreach x,$(LIBC_THREAD_ARTIFACTS),$($(x)_OBJS)) $(LIBC_THREAD_OBJS): $(BUILD_FILES) libc/thread/thread.mk .PHONY: o/$(MODE)/libc/thread o/$(MODE)/libc/thread: $(LIBC_THREAD_CHECKS)
1,972
62
jart/cosmopolitan
false
cosmopolitan/libc/thread/spawn.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/thread/spawn.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/clone.internal.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/stdalign.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/errfuns.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/tls.h" #include "libc/thread/wait0.internal.h" /** * @fileoverview Simple threading API * * This API is supported on all six operating systems. We have this * because the POSIX threads API is positively enormous. We currently * only implement a small subset of POSIX threads, e.g. mutexes. So * until we can implement all of POSIX threads, this API is great. If we * consider that the classic forking concurrency library consists of a * single function, it's a shame POSIX didn't define threads in the past * to just be this. Since create/join/atomics is really all we need. * * Your spawn library abstracts clone() which also works on all * platforms; however our implementation of clone() is significantly * complicated so we strongly recommend always favoring this API. */ #define _TLSZ ((intptr_t)_tls_size) #define _TLDZ ((intptr_t)_tdata_size) #define _TIBZ sizeof(struct CosmoTib) #define _MEMZ ROUNDUP(_TLSZ + _TIBZ, alignof(struct CosmoTib)) struct spawner { int (*fun)(void *, int); void *arg; }; static int Spawner(void *arg, int tid) { int rc; struct spawner *spawner = arg; rc = spawner->fun(spawner->arg, tid); _pthread_ungarbage(); free(spawner); return 0; } /** * Spawns thread, e.g. * * int worker(void *arg, int tid) { * const char *s = arg; * printf("%s\n", s); * return 0; * } * * int main() { * struct spawn th; * _spawn(worker, "hi", &th); * _join(&th); * } * * @param fun is thread worker callback, which receives `arg` and `ctid` * @param arg shall be passed to `fun` * @param opt_out_thread needn't be initialiized and is always clobbered * except when it isn't specified, in which case, the thread is kind * of detached and will (currently) just leak the stack / tls memory * @return 0 on success, or -1 w/ errno */ int _spawn(int fun(void *, int), void *arg, struct spawn *opt_out_thread) { errno_t rc; struct spawn *th, ths; struct spawner *spawner; __require_tls(); if (!fun) return einval(); // we need to to clobber the output memory before calling clone, since // there's no guarantee clone() won't suspend the parent, and focus on // running the child instead; in that case child might want to read it if (opt_out_thread) { th = opt_out_thread; } else { th = &ths; } // allocate enough TLS memory for all the GNU Linuker (_tls_size) // organized _Thread_local data, as well as Cosmpolitan Libc (64) if (!(th->tls = _mktls(&th->tib))) { return -1; } // we must use _mapstack() to allocate the stack because OpenBSD has // very strict requirements for what's allowed to be used for stacks if (!(th->stk = _mapstack())) { free(th->tls); return -1; } spawner = malloc(sizeof(struct spawner)); spawner->fun = fun; spawner->arg = arg; rc = clone(Spawner, th->stk, GetStackSize() - 16 /* openbsd:stackbound */, CLONE_VM | CLONE_THREAD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID, spawner, &th->ptid, __adj_tls(th->tib), &th->tib->tib_tid); if (rc) { errno = rc; _freestack(th->stk); free(th->tls); return -1; } return 0; } /** * Waits for thread created by _spawn() to terminate. * * This will free your thread's stack and tls memory too. */ int _join(struct spawn *th) { int rc; if (th->tib) { // wait for ctid to become zero _npassert(!_wait0(&th->tib->tib_tid, 0)); // free thread memory free(th->tls); rc = munmap(th->stk, GetStackSize()); rc = 0; } else { rc = 0; } bzero(th, sizeof(*th)); return rc; }
6,156
163
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_rwlockattr_init.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/thread/thread.h" /** * Initializes read-write lock attributes. * * @return 0 on success, or error on failure */ errno_t pthread_rwlockattr_init(pthread_rwlockattr_t *attr) { *attr = 0; return 0; }
2,057
30
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_cond_timedwait.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/errno.h" #include "libc/thread/thread.h" #include "libc/thread/thread2.h" #include "third_party/nsync/common.internal.h" #include "third_party/nsync/cv.h" #include "third_party/nsync/time.h" /** * Waits for condition with optional time limit, e.g. * * struct timespec ts; // one second timeout * ts = timespec_add(timespec_real(), timespec_frommillis(1000)); * if (pthread_cond_timedwait(cond, mutex, &ts) == ETIMEDOUT) { * // handle timeout... * } * * @param mutex needs to be held by thread when calling this function * @param abstime may be null to wait indefinitely and should contain * some arbitrary interval added to a `CLOCK_REALTIME` timestamp * @return 0 on success, or errno on error * @raise ETIMEDOUT if `abstime` was specified and the current time * exceeded its value * @raise EPERM if `mutex` is `PTHREAD_MUTEX_ERRORCHECK` and the lock * isn't owned by the current thread * @raise EINVAL if `0 ≤ abstime->tv_nsec < 1000000000` wasn't the case * @raise ECANCELED if calling thread was cancelled in masked mode * @see pthread_cond_broadcast() * @see pthread_cond_signal() * @cancellationpoint */ errno_t pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { if (abstime && !(0 <= abstime->tv_nsec && abstime->tv_nsec < 1000000000)) { return EINVAL; } if (mutex->_type != PTHREAD_MUTEX_NORMAL) { nsync_panic_("pthread cond needs normal mutex\n"); } return nsync_cv_wait_with_deadline( (nsync_cv *)cond, (nsync_mu *)mutex, abstime ? *abstime : nsync_time_no_deadline, 0); }
3,507
61
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_attr_getschedparam.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/thread/thread2.h" /** * Gets thread scheduler parameter attribute. */ errno_t pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param) { *param = (struct sched_param){attr->__schedparam}; return 0; }
2,118
29
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_create.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/blocksigs.internal.h" #include "libc/calls/calls.h" #include "libc/calls/struct/sigaltstack.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/atomic.h" #include "libc/intrin/bits.h" #include "libc/log/internal.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/clone.internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/str/str.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/ss.h" #include "libc/thread/posixthread.internal.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/dll.h" STATIC_YOINK("nsync_mu_lock"); STATIC_YOINK("nsync_mu_unlock"); STATIC_YOINK("_pthread_atfork"); #define MAP_ANON_OPENBSD 0x1000 #define MAP_STACK_OPENBSD 0x4000 void _pthread_free(struct PosixThread *pt) { if (pt->flags & PT_STATIC) return; free(pt->tls); if ((pt->flags & PT_OWNSTACK) && // pt->attr.__stackaddr && // pt->attr.__stackaddr != MAP_FAILED) { _npassert(!munmap(pt->attr.__stackaddr, pt->attr.__stacksize)); } if (pt->altstack) { free(pt->altstack); } free(pt); } static int PosixThread(void *arg, int tid) { void *rc; struct sigaltstack ss; struct PosixThread *pt = arg; enum PosixThreadStatus status; _unassert(__get_tls()->tib_tid > 0); if (pt->altstack) { ss.ss_flags = 0; ss.ss_size = SIGSTKSZ; ss.ss_sp = pt->altstack; if (sigaltstack(&ss, 0)) { notpossible; } } if (pt->attr.__inheritsched == PTHREAD_EXPLICIT_SCHED) { _pthread_reschedule(pt); } // set long jump handler so pthread_exit can bring control back here if (!setjmp(pt->exiter)) { __get_tls()->tib_pthread = (pthread_t)pt; _npassert(!sigprocmask(SIG_SETMASK, (sigset_t *)pt->attr.__sigmask, 0)); rc = pt->start(pt->arg); // ensure pthread_cleanup_pop(), and pthread_exit() popped cleanup _npassert(!pt->cleanup); // calling pthread_exit() will either jump back here, or call exit pthread_exit(rc); } // return to clone polyfill which clears tid, wakes futex, and exits return 0; } static int FixupCustomStackOnOpenbsd(pthread_attr_t *attr) { // OpenBSD: Only permits RSP to occupy memory that's been explicitly // defined as stack memory. We need to squeeze the provided interval // in order to successfully call mmap(), which will return EINVAL if // these calculations should overflow. size_t n; int e, rc; uintptr_t x, y; n = attr->__stacksize; x = (uintptr_t)attr->__stackaddr; y = ROUNDUP(x, PAGESIZE); n -= y - x; n = ROUNDDOWN(n, PAGESIZE); e = errno; if (__sys_mmap((void *)y, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON_OPENBSD | MAP_STACK_OPENBSD, -1, 0, 0) == (void *)y) { attr->__stackaddr = (void *)y; attr->__stacksize = n; return 0; } else { rc = errno; errno = e; if (rc == EOVERFLOW) { rc = EINVAL; } return rc; } } static errno_t pthread_create_impl(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg, sigset_t oldsigs) { int rc, e = errno; struct PosixThread *pt; // create posix thread object if (!(pt = calloc(1, sizeof(struct PosixThread)))) { errno = e; return EAGAIN; } pt->start = start_routine; pt->arg = arg; // create thread local storage memory if (!(pt->tls = _mktls(&pt->tib))) { free(pt); errno = e; return EAGAIN; } // setup attributes if (attr) { pt->attr = *attr; attr = 0; } else { pthread_attr_init(&pt->attr); } // setup stack if (pt->attr.__stackaddr) { // caller supplied their own stack // assume they know what they're doing as much as possible if (IsOpenbsd()) { if ((rc = FixupCustomStackOnOpenbsd(&pt->attr))) { _pthread_free(pt); return rc; } } } else { // cosmo is managing the stack // 1. in mono repo optimize for tiniest stack possible // 2. in public world optimize to *work* regardless of memory pt->flags = PT_OWNSTACK; pt->attr.__stacksize = MAX(pt->attr.__stacksize, GetStackSize()); pt->attr.__stacksize = _roundup2pow(pt->attr.__stacksize); pt->attr.__guardsize = ROUNDUP(pt->attr.__guardsize, GUARDSIZE); if (pt->attr.__guardsize + GUARDSIZE >= pt->attr.__stacksize) { _pthread_free(pt); return EINVAL; } if (pt->attr.__guardsize == GUARDSIZE) { // user is wisely using smaller stacks with default guard size pt->attr.__stackaddr = mmap(0, pt->attr.__stacksize, PROT_READ | PROT_WRITE, MAP_STACK | MAP_ANONYMOUS, -1, 0); } else { // user is tuning things, performance may suffer pt->attr.__stackaddr = mmap(0, pt->attr.__stacksize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (pt->attr.__stackaddr != MAP_FAILED) { if (IsOpenbsd() && __sys_mmap( pt->attr.__stackaddr, pt->attr.__stacksize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON_OPENBSD | MAP_STACK_OPENBSD, -1, 0, 0) != pt->attr.__stackaddr) { notpossible; } if (pt->attr.__guardsize && !IsWindows() && mprotect(pt->attr.__stackaddr, pt->attr.__guardsize, PROT_NONE)) { notpossible; } } } if (pt->attr.__stackaddr == MAP_FAILED) { rc = errno; _pthread_free(pt); errno = e; if (rc == EINVAL || rc == EOVERFLOW) { return EINVAL; } else { return EAGAIN; } } if (IsAsan() && pt->attr.__guardsize) { __asan_poison(pt->attr.__stackaddr, pt->attr.__guardsize, kAsanStackOverflow); } } // setup signal handler stack if (_wantcrashreports && !IsWindows()) { pt->altstack = malloc(SIGSTKSZ); } // set initial status if (!pt->attr.__havesigmask) { pt->attr.__havesigmask = true; memcpy(pt->attr.__sigmask, &oldsigs, sizeof(oldsigs)); } switch (pt->attr.__detachstate) { case PTHREAD_CREATE_JOINABLE: atomic_store_explicit(&pt->status, kPosixThreadJoinable, memory_order_relaxed); break; case PTHREAD_CREATE_DETACHED: atomic_store_explicit(&pt->status, kPosixThreadDetached, memory_order_relaxed); break; default: _pthread_free(pt); return EINVAL; } // add thread to global list // we add it to the end since zombies go at the beginning nsync_dll_init_(&pt->list, pt); pthread_spin_lock(&_pthread_lock); _pthread_list = nsync_dll_make_last_in_list_(_pthread_list, &pt->list); pthread_spin_unlock(&_pthread_lock); // launch PosixThread(pt) in new thread if ((rc = clone(PosixThread, pt->attr.__stackaddr, pt->attr.__stacksize - (IsOpenbsd() ? 16 : 0), CLONE_VM | CLONE_THREAD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID, pt, &pt->ptid, __adj_tls(pt->tib), &pt->tib->tib_tid))) { pthread_spin_lock(&_pthread_lock); _pthread_list = nsync_dll_remove_(_pthread_list, &pt->list); pthread_spin_unlock(&_pthread_lock); _pthread_free(pt); return rc; } *thread = (pthread_t)pt; return 0; } /** * Creates thread, e.g. * * void *worker(void *arg) { * fputs(arg, stdout); * return "there\n"; * } * * int main() { * void *result; * pthread_t id; * pthread_create(&id, 0, worker, "hi "); * pthread_join(id, &result); * fputs(result, stdout); * } * * Here's the OSI model of threads in Cosmopolitan: * * ┌──────────────────┐ * │ pthread_create() │ - Standard * └─────────┬────────┘ Abstraction * ┌─────────┴────────┐ * │ clone() │ - Polyfill * └─────────┬────────┘ * ┌────────┬──┴┬─┬─┬─────────┐ - Kernel * ┌─────┴─────┐ │ │ │┌┴──────┐ │ Interfaces * │ sys_clone │ │ │ ││ tfork │ ┌┴─────────────┐ * └───────────┘ │ │ │└───────┘ │ CreateThread │ * ┌───────────────┴──┐│┌┴────────┐ └──────────────┘ * │ bsdthread_create │││ thr_new │ * └──────────────────┘│└─────────┘ * ┌───────┴──────┐ * │ _lwp_create │ * └──────────────┘ * * @param thread if non-null is used to output the thread id * upon successful completion * @param attr points to launch configuration, or may be null * to use sensible defaults; it must be initialized using * pthread_attr_init() * @param start_routine is your thread's callback function * @param arg is an arbitrary value passed to `start_routine` * @return 0 on success, or errno on error * @raise EAGAIN if resources to create thread weren't available * @raise EINVAL if `attr` was supplied and had unnaceptable data * @raise EPERM if scheduling policy was requested and user account * isn't authorized to use it * @returnserrno * @threadsafe */ errno_t pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { errno_t rc; __require_tls(); pthread_decimate_np(); BLOCK_SIGNALS; rc = pthread_create_impl(thread, attr, start_routine, arg, _SigMask); ALLOW_SIGNALS; return rc; }
12,504
333
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_mutex_destroy.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/str/str.h" #include "libc/thread/thread.h" /** * Destroys mutex. * * @return 0 on success, or error number on failure * @raise EINVAL if mutex is locked in our implementation */ errno_t pthread_mutex_destroy(pthread_mutex_t *mutex) { memset(mutex, -1, sizeof(*mutex)); return 0; }
2,142
32
jart/cosmopolitan
false
cosmopolitan/libc/thread/pthread_exit.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/dce.h" #include "libc/intrin/atomic.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/limits.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/thread/posixthread.internal.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "third_party/nsync/dll.h" #include "third_party/nsync/futex.internal.h" static void CleanupThread(struct PosixThread *pt) { struct _pthread_cleanup_buffer *cb; while ((cb = pt->cleanup)) { pt->cleanup = cb->__prev; cb->__routine(cb->__arg); } } static void DestroyTlsKeys(struct CosmoTib *tib) { int i, j, gotsome; void *val, **keys; pthread_key_dtor dtor; keys = tib->tib_keys; for (j = 0; j < PTHREAD_DESTRUCTOR_ITERATIONS; ++j) { for (gotsome = i = 0; i < PTHREAD_KEYS_MAX; ++i) { if ((val = keys[i]) && (dtor = atomic_load_explicit(_pthread_key_dtor + i, memory_order_relaxed)) && dtor != (pthread_key_dtor)-1) { gotsome = 1; keys[i] = 0; dtor(val); } } if (!gotsome) { break; } } } /** * Terminates current POSIX thread. * * For example, a thread could terminate early as follows: * * pthread_exit((void *)123); * * The result value could then be obtained when joining the thread: * * void *rc; * pthread_join(id, &rc); * assert((intptr_t)rc == 123); * * Under normal circumstances a thread can exit by simply returning from * the callback function that was supplied to pthread_create(). This may * be used if the thread wishes to exit at any other point in the thread * lifecycle, in which case this function is responsible for ensuring we * invoke _gc(), _defer(), and pthread_cleanup_push() callbacks, as well * as pthread_key_create() destructors. * * If the current thread is an orphaned thread, or is the main thread * when no other threads were created, then this will terminated your * process with an exit code of zero. It's not possible to supply a * non-zero exit status to wait4() via this function. * * Once a thread has exited, access to its stack memory is undefined. * The behavior of calling pthread_exit() from cleanup handlers and key * destructors is also undefined. * * @param rc is reported later to pthread_join() * @threadsafe * @noreturn */ wontreturn void pthread_exit(void *rc) { struct CosmoTib *tib; struct PosixThread *pt; enum PosixThreadStatus status, transition; STRACE("pthread_exit(%p)", rc); tib = __get_tls(); pt = (struct PosixThread *)tib->tib_pthread; _unassert(~pt->flags & PT_EXITING); pt->flags |= PT_EXITING; pt->rc = rc; // free resources CleanupThread(pt); DestroyTlsKeys(tib); _pthread_ungarbage(); pthread_decimate_np(); // transition the thread to a terminated state status = atomic_load_explicit(&pt->status, memory_order_acquire); do { switch (status) { case kPosixThreadJoinable: transition = kPosixThreadTerminated; break; case kPosixThreadDetached: transition = kPosixThreadZombie; break; default: unreachable; } } while (!atomic_compare_exchange_weak_explicit( &pt->status, &status, transition, memory_order_release, memory_order_relaxed)); // make this thread a zombie if it was detached if (transition == kPosixThreadZombie) { _pthread_zombify(pt); } // check if this is the main thread or an orphaned thread if (pthread_orphan_np()) { exit(0); } // check if the main thread has died whilst children live // note that the main thread is joinable by child threads if (pt->flags & PT_STATIC) { atomic_store_explicit(&tib->tib_tid, 0, memory_order_release); nsync_futex_wake_(&tib->tib_tid, INT_MAX, !IsWindows()); _Exit1(0); } // this is a child thread longjmp(pt->exiter, 1); }
5,845
155
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcgetpgrp.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/syscall-sysv.internal.h" #include "libc/calls/termios.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/errfuns.h" /** * Returns which process group controls terminal. * * @return process group id on success, or -1 w/ errno * @raise ENOTTY if `fd` is isn't controlling teletypewriter * @raise EBADF if `fd` isn't an open file descriptor * @raise ENOSYS on Windows and Bare Metal * @asyncsignalsafe */ int tcgetpgrp(int fd) { int rc, pgrp; if (IsWindows() || IsMetal()) { rc = enosys(); } else { rc = sys_ioctl(fd, TIOCGPGRP, &pgrp); } STRACE("tcgetpgrp(%d) → %d% m", fd, rc == -1 ? rc : pgrp); return rc == -1 ? rc : pgrp; }
2,587
45
jart/cosmopolitan
false
cosmopolitan/libc/calls/ucontext.h
#ifndef COSMOPOLITAN_LIBC_CALLS_UCONTEXT_H_ #define COSMOPOLITAN_LIBC_CALLS_UCONTEXT_H_ #include "libc/calls/struct/sigaltstack.h" #include "libc/calls/struct/sigset.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #ifdef __x86_64__ struct XmmRegister { uint64_t u64[2]; }; struct FpuStackEntry { uint16_t significand[4]; uint16_t exponent; uint16_t padding[3]; }; struct thatispacked FpuState { uint16_t cwd; uint16_t swd; uint16_t ftw; uint16_t fop; uint64_t rip; uint64_t rdp; uint32_t mxcsr; uint32_t mxcr_mask; struct FpuStackEntry st[8]; struct XmmRegister xmm[16]; uint32_t __padding[24]; }; typedef uint64_t greg_t; typedef greg_t gregset_t[23]; typedef struct FpuState *fpregset_t; #endif /* __x86_64__ */ struct sigcontext { #ifdef __x86_64__ union { struct { uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rdi; uint64_t rsi; uint64_t rbp; uint64_t rbx; uint64_t rdx; uint64_t rax; uint64_t rcx; uint64_t rsp; uint64_t rip; uint64_t eflags; uint16_t cs; uint16_t gs; uint16_t fs; uint16_t __pad0; uint64_t err; uint64_t trapno; uint64_t oldmask; uint64_t cr2; }; gregset_t gregs; }; struct FpuState *fpregs; /* zero when no fpu context */ uint64_t __pad1[8]; #elif defined(__aarch64__) uint64_t fault_address; uint64_t regs[31]; uint64_t sp; uint64_t pc; uint64_t pstate; uint8_t __reserved[4096] __attribute__((__aligned__(16))); #endif /* __x86_64__ */ }; typedef struct sigcontext mcontext_t; struct ucontext { uint64_t uc_flags; /* don't use this */ struct ucontext *uc_link; stack_t uc_stack; #ifdef __x86_64__ struct sigcontext uc_mcontext; sigset_t uc_sigmask; uint64_t __pad; struct FpuState __fpustate; /* for cosmo on non-linux */ #elif defined(__aarch64__) sigset_t uc_sigmask; uint8_t __unused[1024 / 8 - sizeof(sigset_t)]; struct sigcontext uc_mcontext; #endif }; typedef struct ucontext ucontext_t; int getcontext(ucontext_t *); int setcontext(const ucontext_t *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_UCONTEXT_H_ */
2,341
111
jart/cosmopolitan
false
cosmopolitan/libc/calls/blockcancel.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_BLOCKCANCEL_H_ #define COSMOPOLITAN_LIBC_CALLS_BLOCKCANCEL_H_ #include "libc/thread/thread.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define BLOCK_CANCELLATIONS \ do { \ int _CancelState; \ _CancelState = _pthread_block_cancellations() #define ALLOW_CANCELLATIONS \ _pthread_allow_cancellations(_CancelState); \ } \ while (0) int _pthread_block_cancellations(void); void _pthread_allow_cancellations(int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_BLOCKCANCEL_H_ */
683
23
jart/cosmopolitan
false
cosmopolitan/libc/calls/fcntl-nt.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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/fd.internal.h" #include "libc/calls/struct/flock.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/wincrash.internal.h" #include "libc/errno.h" #include "libc/intrin/kmalloc.h" #include "libc/intrin/weaken.h" #include "libc/limits.h" #include "libc/log/backtrace.internal.h" #include "libc/macros.internal.h" #include "libc/nt/enum/filelockflags.h" #include "libc/nt/errors.h" #include "libc/nt/files.h" #include "libc/nt/runtime.h" #include "libc/nt/struct/byhandlefileinformation.h" #include "libc/nt/struct/overlapped.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/sysv/errfuns.h" #include "libc/thread/thread.h" struct FileLock { struct FileLock *next; int64_t off; int64_t len; int fd; bool exc; }; struct FileLocks { pthread_mutex_t mu; struct FileLock *list; struct FileLock *free; }; static struct FileLocks g_locks; static textwindows struct FileLock *NewFileLock(void) { struct FileLock *fl; if (g_locks.free) { fl = g_locks.free; g_locks.free = fl->next; } else { fl = kmalloc(sizeof(*fl)); } bzero(fl, sizeof(*fl)); fl->next = g_locks.list; g_locks.list = fl; return fl; } static textwindows void FreeFileLock(struct FileLock *fl) { fl->next = g_locks.free; g_locks.free = fl; } static textwindows bool OverlapsFileLock(struct FileLock *fl, int64_t off, int64_t len) { uint64_t BegA, EndA, BegB, EndB; BegA = off; EndA = off + (len - 1); BegB = fl->off; EndB = fl->off + (fl->len - 1); return MAX(BegA, BegB) < MIN(EndA, EndB); } static textwindows bool EncompassesFileLock(struct FileLock *fl, int64_t off, int64_t len) { return off <= fl->off && fl->off + fl->len <= off + len; } static textwindows bool EqualsFileLock(struct FileLock *fl, int64_t off, int64_t len) { return fl->off == off && off + len == fl->off + fl->len; } _Hide textwindows void sys_fcntl_nt_lock_cleanup(int fd) { struct FileLock *fl, *ft, **flp; pthread_mutex_lock(&g_locks.mu); for (flp = &g_locks.list, fl = *flp; fl;) { if (fl->fd == fd) { *flp = fl->next; ft = fl->next; FreeFileLock(fl); fl = ft; } else { flp = &fl->next; fl = *flp; } } pthread_mutex_unlock(&g_locks.mu); } static textwindows int sys_fcntl_nt_lock(struct Fd *f, int fd, int cmd, uintptr_t arg) { int e; struct flock *l; uint32_t flags, err; struct FileLock *fl, *ft, **flp; int64_t pos, off, len, end, size; l = (struct flock *)arg; len = l->l_len; off = l->l_start; switch (l->l_whence) { case SEEK_SET: break; case SEEK_CUR: pos = 0; if (SetFilePointerEx(f->handle, 0, &pos, SEEK_CUR)) { off = pos + off; } else { return __winerr(); } break; case SEEK_END: off = INT64_MAX - off; break; default: return einval(); } if (!len) { len = INT64_MAX - off; } if (off < 0 || len < 0 || __builtin_add_overflow(off, len, &end)) { return einval(); } bool32 ok; struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = (void *)(uintptr_t)off}; if (l->l_type == F_RDLCK || l->l_type == F_WRLCK) { if (cmd == F_SETLK || cmd == F_SETLKW) { // make it possible to transition read locks to write locks for (flp = &g_locks.list, fl = *flp; fl;) { if (fl->fd == fd) { if (EqualsFileLock(fl, off, len)) { if (fl->exc == l->l_type == F_WRLCK) { // we already have this lock return 0; } else { // unlock our read lock and acquire write lock below if (UnlockFileEx(f->handle, 0, len, len >> 32, &ov)) { *flp = fl->next; ft = fl->next; FreeFileLock(fl); fl = ft; continue; } else { return -1; } } break; } else if (OverlapsFileLock(fl, off, len)) { return enotsup(); } } flp = &fl->next; fl = *flp; } } // return better information on conflicting locks if possible if (cmd == F_GETLK) { for (fl = g_locks.list; fl; fl = fl->next) { if (fl->fd == fd && // OverlapsFileLock(fl, off, len) && (l->l_type == F_WRLCK || !fl->exc)) { l->l_whence = SEEK_SET; l->l_start = fl->off; l->l_len = fl->len; l->l_type == fl->exc ? F_WRLCK : F_RDLCK; l->l_pid = getpid(); return 0; } } } flags = 0; if (cmd != F_SETLKW) { // TODO(jart): we should use expo backoff in wrapper function // should not matter since sqlite doesn't need it flags |= kNtLockfileFailImmediately; } if (l->l_type == F_WRLCK) { flags |= kNtLockfileExclusiveLock; } ok = LockFileEx(f->handle, flags, 0, len, len >> 32, &ov); if (cmd == F_GETLK) { if (ok) { l->l_type = F_UNLCK; if (!UnlockFileEx(f->handle, 0, len, len >> 32, &ov)) { return -1; } } else { l->l_pid = -1; ok = true; } } else if (ok) { fl = NewFileLock(); fl->off = off; fl->len = len; fl->exc = l->l_type == F_WRLCK; fl->fd = fd; } return ok ? 0 : -1; } if (l->l_type == F_UNLCK) { if (cmd == F_GETLK) return einval(); // allow a big range to unlock many small ranges for (flp = &g_locks.list, fl = *flp; fl;) { if (fl->fd == fd && EncompassesFileLock(fl, off, len)) { struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = (void *)(uintptr_t)fl->off}; if (UnlockFileEx(f->handle, 0, fl->len, fl->len >> 32, &ov)) { *flp = fl->next; ft = fl->next; FreeFileLock(fl); fl = ft; } else { return -1; } } else { flp = &fl->next; fl = *flp; } } // win32 won't let us carve up existing locks int overlap_count = 0; for (fl = g_locks.list; fl; fl = fl->next) { if (fl->fd == fd && // OverlapsFileLock(fl, off, len)) { ++overlap_count; } } // try to handle the carving cases needed by sqlite if (overlap_count == 1) { for (fl = g_locks.list; fl; fl = fl->next) { if (fl->fd == fd && // off <= fl->off && // off + len >= fl->off && // off + len < fl->off + fl->len) { // cleave left side of lock struct NtOverlapped ov = {.hEvent = f->handle, .Pointer = (void *)(uintptr_t)fl->off}; if (!UnlockFileEx(f->handle, 0, fl->len, fl->len >> 32, &ov)) { return -1; } fl->len = (fl->off + fl->len) - (off + len); fl->off = off + len; ov.Pointer = (void *)(uintptr_t)fl->off; if (!LockFileEx(f->handle, kNtLockfileExclusiveLock, 0, fl->len, fl->len >> 32, &ov)) { return -1; } return 0; } } } if (overlap_count) { return enotsup(); } return 0; } return einval(); } static textwindows int sys_fcntl_nt_dupfd(int fd, int cmd, int start) { if (start < 0) return einval(); return sys_dup_nt(fd, -1, (cmd == F_DUPFD_CLOEXEC ? O_CLOEXEC : 0), start); } textwindows int sys_fcntl_nt(int fd, int cmd, uintptr_t arg) { int rc; uint32_t flags; if (__isfdkind(fd, kFdFile) || __isfdkind(fd, kFdSocket)) { if (cmd == F_GETFL) { rc = g_fds.p[fd].flags & (O_ACCMODE | O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NONBLOCK | O_RANDOM | O_SEQUENTIAL); } else if (cmd == F_SETFL) { // O_APPEND doesn't appear to be tunable at cursory glance // O_NONBLOCK might require we start doing all i/o in threads // O_DSYNC / O_RSYNC / O_SYNC maybe if we fsync() everything // O_DIRECT | O_RANDOM | O_SEQUENTIAL | O_NDELAY possible but // not worth it. rc = enosys(); } else if (cmd == F_GETFD) { if (g_fds.p[fd].flags & O_CLOEXEC) { rc = FD_CLOEXEC; } else { rc = 0; } } else if (cmd == F_SETFD) { if (arg & FD_CLOEXEC) { g_fds.p[fd].flags |= O_CLOEXEC; } else { g_fds.p[fd].flags &= ~O_CLOEXEC; } rc = 0; } else if (cmd == F_SETLK || cmd == F_SETLKW || cmd == F_GETLK) { pthread_mutex_lock(&g_locks.mu); rc = sys_fcntl_nt_lock(g_fds.p + fd, fd, cmd, arg); pthread_mutex_unlock(&g_locks.mu); } else if (cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC) { rc = sys_fcntl_nt_dupfd(fd, cmd, arg); } else { rc = einval(); } } else { rc = ebadf(); } return rc; }
11,122
351
jart/cosmopolitan
false
cosmopolitan/libc/calls/setpriority-nt.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/calls/syscall-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/nt/enum/processaccess.h" #include "libc/nt/enum/processcreationflags.h" #include "libc/nt/process.h" #include "libc/nt/runtime.h" #include "libc/sysv/consts/prio.h" #include "libc/sysv/errfuns.h" textwindows int sys_setpriority_nt(int which, unsigned pid, int nice) { int rc; uint32_t tier; int64_t h, closeme = -1; if (which != PRIO_PROCESS) { return einval(); } if (!pid || pid == getpid()) { h = GetCurrentProcess(); } else if (__isfdkind(pid, kFdProcess)) { h = g_fds.p[pid].handle; } else { h = OpenProcess(kNtProcessSetInformation | kNtProcessQueryInformation, false, pid); if (!h) return __winerr(); closeme = h; } if (nice <= -15) { tier = kNtRealtimePriorityClass; } else if (nice <= -9) { tier = kNtHighPriorityClass; } else if (nice <= -3) { tier = kNtAboveNormalPriorityClass; } else if (nice <= 3) { tier = kNtNormalPriorityClass; } else if (nice <= 12) { tier = kNtBelowNormalPriorityClass; } else { tier = kNtIdlePriorityClass; } if (SetPriorityClass(h, tier)) { rc = 0; } else { rc = __winerr(); } if (closeme != -1) { CloseHandle(closeme); } return rc; }
3,213
76
jart/cosmopolitan
false
cosmopolitan/libc/calls/getcpucount.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/sched-sysv.internal.h" #include "libc/calls/struct/cpuset.h" #include "libc/calls/weirdtypes.h" #include "libc/dce.h" #include "libc/macros.internal.h" #include "libc/nt/accounting.h" #include "libc/nt/dll.h" #include "libc/nt/struct/systeminfo.h" #include "libc/nt/systeminfo.h" #include "libc/runtime/runtime.h" #define CTL_HW 6 #define HW_NCPU 3 #define HW_NCPUONLINE_OPENBSD 25 #define HW_NCPUONLINE_NETBSD 16 #define ALL_PROCESSOR_GROUPS 0xffff static unsigned _getcpucount_linux(void) { cpu_set_t s = {0}; if (sys_sched_getaffinity(0, sizeof(s), &s) != -1) { return CPU_COUNT(&s); } else { return 0; } } static unsigned _getcpucount_bsd(void) { size_t n; int c, cmd[2]; n = sizeof(c); cmd[0] = CTL_HW; if (IsOpenbsd()) { cmd[1] = HW_NCPUONLINE_OPENBSD; } else if (IsNetbsd()) { cmd[1] = HW_NCPUONLINE_NETBSD; } else { cmd[1] = HW_NCPU; } if (!sys_sysctl(cmd, 2, &c, &n, 0, 0)) { return c; } else { return 0; } } static unsigned _getcpucount_impl(void) { if (!IsWindows()) { if (!IsBsd()) { return _getcpucount_linux(); } else { return _getcpucount_bsd(); } } else { return GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS); } } static int g_cpucount; // precompute because process affinity on linux may change later __attribute__((__constructor__)) static void _getcpucount_init(void) { g_cpucount = _getcpucount_impl(); } /** * Returns number of CPUs in system. * * This is the same as the standard interface: * * sysconf(_SC_NPROCESSORS_ONLN); * * Except this function isn't a bloated diamond dependency. * * On Intel systems with HyperThreading this will return the number of * cores multiplied by two. * * @return cpu count or 0 if it couldn't be determined */ int _getcpucount(void) { return g_cpucount; }
3,752
101
jart/cosmopolitan
false
cosmopolitan/libc/calls/gettimeofday-metal.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/timeval.internal.h" #include "libc/time/struct/timezone.h" axdx_t sys_gettimeofday_metal(struct timeval *tv, struct timezone *tz, void *wut) { return (axdx_t){-1, 0}; }
2,066
26
jart/cosmopolitan
false
cosmopolitan/libc/calls/signal.c
/*-*- mode:c; indent-tabs-mode:nil; tab-width:2; 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/sysv/consts/sa.h" /** * Installs kernel interrupt handler, e.g. * * void GotCtrlC(int sig) { ... } * CHECK_NE(SIG_ERR, signal(SIGINT, GotCtrlC)); * * @return old signal handler on success or SIG_ERR w/ errno * @note this function has BSD semantics, i.e. SA_RESTART * @see sigaction() which has more features and docs */ sighandler_t(signal)(int sig, sighandler_t func) { struct sigaction old, sa = {.sa_handler = func, .sa_flags = SA_RESTART}; if ((sigaction)(sig, &sa, &old) != -1) { return old.sa_handler; } else { return SIG_ERR; } }
2,493
41
jart/cosmopolitan
false
cosmopolitan/libc/calls/tkill.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/sig.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/sicode.h" // OpenBSD has an optional `tib` parameter for extra safety int __tkill(int tid, int sig, void *tib) { int rc; if (!IsWindows() && !IsMetal()) { rc = sys_tkill(tid, sig, tib); } else { rc = __sig_add(tid, sig, SI_TKILL); } STRACE("tkill(%d, %G) → %d% m", tid, sig, rc); return rc; } /** * Kills thread. * * @param tid is thread id * @param sig does nothing on xnu * @return 0 on success, or -1 w/ errno * @raise EAGAIN if `RLIMIT_SIGPENDING` was exceeded * @raise EINVAL if `tid` or `sig` were invalid * @raise ESRCH if no such `tid` existed * @raise EPERM if permission was denied * @asyncsignalsafe */ int tkill(int tid, int sig) { return __tkill(tid, sig, 0); }
2,805
54
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigsuspend.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/cp.internal.h" #include "libc/calls/internal.h" #include "libc/calls/sig.internal.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/log/backtrace.internal.h" #include "libc/nt/errors.h" #include "libc/nt/synchronization.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" /** * Blocks until SIG ∉ MASK is delivered to thread. * * This temporarily replaces the signal mask until a signal that it * doesn't contain is delivered. * * @param ignore is a bitset of signals to block temporarily, which if * NULL is equivalent to passing an empty signal set * @return -1 w/ EINTR (or possibly EFAULT) * @cancellationpoint * @asyncsignalsafe * @norestart */ int sigsuspend(const sigset_t *ignore) { int rc; long ms, totoms; sigset_t save, *arg, mask = {0}; STRACE("sigsuspend(%s) → ...", DescribeSigset(0, ignore)); BEGIN_CANCELLATION_POINT; if (IsAsan() && ignore && !__asan_is_valid(ignore, sizeof(*ignore))) { rc = efault(); } else if (IsXnu() || IsOpenbsd()) { // openbsd and xnu only support 32 signals // they use a register calling convention for sigsuspend if (ignore) { arg = (sigset_t *)(uintptr_t)(*(uint32_t *)ignore); } else { arg = 0; } rc = sys_sigsuspend(arg, 8); } else if (IsLinux() || IsFreebsd() || IsNetbsd() || IsWindows()) { if (ignore) { arg = ignore; } else { arg = &mask; } if (!IsWindows()) { rc = sys_sigsuspend(arg, 8); } else { __sig_mask(SIG_SETMASK, arg, &save); ms = 0; totoms = 0; do { if ((rc = _check_interrupts(false, g_fds.p))) { break; } if (SleepEx(__SIG_POLLING_INTERVAL_MS, true) == kNtWaitIoCompletion) { POLLTRACE("IOCP EINTR"); continue; } #if defined(SYSDEBUG) && defined(_POLLTRACE) ms += __SIG_POLLING_INTERVAL_MS; if (ms >= __SIG_LOGGING_INTERVAL_MS) { totoms += ms, ms = 0; POLLTRACE("... sigsuspending for %'lums...", totoms); } #endif } while (1); __sig_mask(SIG_SETMASK, &save, 0); } } else { // TODO(jart): sigsuspend metal support rc = enosys(); } END_CANCELLATION_POINT; STRACE("...sigsuspend → %d% m", rc); return rc; }
4,358
105
jart/cosmopolitan
false
cosmopolitan/libc/calls/truncate.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/cp.internal.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Changes size of file. * * If the file size is increased, the extended area shall appear as if * it were zero-filled. If your file size is decreased, the extra data * shall be lost. * * Some operating systems implement an optimization, where `length` is * treated as a logical size and the requested physical space won't be * allocated until non-zero values get written into it. Our tests show * this happens on Linux (usually with 4096 byte granularity), FreeBSD * (which favors 512-byte granularity), and MacOS (prefers 4096 bytes) * however Windows, OpenBSD, and NetBSD always reserve physical space. * This may be inspected using stat() then consulting stat::st_blocks. * * @param path is name of file that shall be resized * @return 0 on success, or -1 w/ errno * @raise EINVAL if `length` is negative * @raise EINTR if signal was delivered instead * @raise ECANCELED if thread was cancelled in masked mode * @raise EFBIG or EINVAL if `length` is too huge * @raise EFAULT if `path` points to invalid memory * @raise ENOTSUP if `path` is a zip filesystem path * @raise EACCES if we don't have permission to search a component of `path` * @raise ENOTDIR if a directory component in `path` exists as non-directory * @raise ENAMETOOLONG if symlink-resolved `path` length exceeds `PATH_MAX` * @raise ENAMETOOLONG if component in `path` exists longer than `NAME_MAX` * @raise ELOOP if a loop was detected resolving components of `path` * @raise ENOENT if `path` doesn't exist or is an empty string * @raise ETXTBSY if `path` is an executable being executed * @raise EROFS if `path` is on a read-only filesystem * @raise ENOSYS on bare metal * @cancellationpoint * @see ftruncate() * @threadsafe */ int truncate(const char *path, int64_t length) { int rc; struct ZiposUri zipname; BEGIN_CANCELLATION_POINT; if (IsMetal()) { rc = enosys(); } else if (!path || (IsAsan() && !__asan_is_valid_str(path))) { rc = efault(); } else if (_weaken(__zipos_parseuri) && _weaken(__zipos_parseuri)(path, &zipname) != -1) { rc = enotsup(); } else if (!IsWindows()) { rc = sys_truncate(path, length, length); if (IsNetbsd() && rc == -1 && errno == ENOSPC) { errno = EFBIG; // POSIX doesn't specify ENOSPC for truncate() } } else { rc = sys_truncate_nt(path, length); } END_CANCELLATION_POINT; STRACE("truncate(%#s, %'ld) → %d% m", path, length, rc); return rc; }
4,682
92
jart/cosmopolitan
false
cosmopolitan/libc/calls/issymlink.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/metastat.internal.h" #include "libc/calls/struct/stat.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/nt/files.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Returns true if file exists and is a symbolic link. * * This function is equivalent to: * * struct stat st; * return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && * S_ISLNK(st.st_mode); * * Except faster and with fewer dependencies. * * @see isregularfile(), isdirectory(), fileexists(), ischardev() */ bool issymlink(const char *path) { int e; bool res; union metastat st; struct ZiposUri zipname; e = errno; if (IsAsan() && !__asan_is_valid_str(path)) { efault(); res = false; } else if (_weaken(__zipos_open) && _weaken(__zipos_parseuri)(path, &zipname) != -1) { res = false; } else if (IsMetal()) { res = false; } else if (!IsWindows()) { if (__sys_fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1) { res = S_ISLNK(METASTAT(st, st_mode)); } else { res = false; } } else { res = issymlink_nt(path); } STRACE("%s(%#s) → %hhhd% m", "issymlink", path, res); if (!res && (errno == ENOENT || errno == ENOTDIR)) { errno = e; } return res; }
3,458
77
jart/cosmopolitan
false
cosmopolitan/libc/calls/execve.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/pledge.h" #include "libc/calls/pledge.internal.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/likely.h" #include "libc/intrin/promises.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/libfatal.internal.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Replaces current process with program. * * On Windows, `argv` and `envp` can't contain binary strings. They need * to be valid UTF-8 in order to round-trip the WIN32 API, without being * corrupted. * * @param program will not be PATH searched, see commandv() * @param argv[0] is the name of the program to run * @param argv[1,n-2] optionally specify program arguments * @param argv[n-1] is NULL * @param envp[0,n-2] specifies "foo=bar" environment variables * @param envp[n-1] is NULL * @return doesn't return, or -1 w/ errno * @asyncsignalsafe * @vforksafe */ int execve(const char *prog, char *const argv[], char *const envp[]) { struct ZiposUri uri; int rc; size_t i; if (!prog || !argv || !envp || (IsAsan() && (!__asan_is_valid_str(prog) || // !__asan_is_valid_strlist(argv) || // !__asan_is_valid_strlist(envp)))) { rc = efault(); } else { STRACE("execve(%#s, %s, %s) → ...", prog, DescribeStringList(argv), DescribeStringList(envp)); rc = 0; if (IsLinux() && __execpromises && _weaken(sys_pledge_linux)) { rc = _weaken(sys_pledge_linux)(__execpromises, __pledge_mode); } if (!rc) { if (_weaken(__zipos_parseuri) && (_weaken(__zipos_parseuri)(prog, &uri) != -1)) { rc = _weaken(__zipos_open)(&uri, O_RDONLY | O_CLOEXEC, 0); if (rc != -1) { const int zipFD = rc; strace_enabled(-1); rc = fexecve(zipFD, argv, envp); close(zipFD); strace_enabled(+1); } } else if (!IsWindows()) { rc = sys_execve(prog, argv, envp); } else { rc = sys_execve_nt(prog, argv, envp); } } } STRACE("execve(%#s) failed %d% m", prog, rc); return rc; }
4,219
90
jart/cosmopolitan
false
cosmopolitan/libc/calls/islinux.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/dce.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/pr.h" privileged bool __is_linux_2_6_23(void) { #ifdef __x86_64__ int rc; if (!IsLinux()) return false; if (IsGenuineBlink()) return true; asm volatile("syscall" : "=a"(rc) : "0"(157), "D"(PR_GET_SECCOMP) : "rcx", "r11", "memory"); return rc != -EINVAL; #else return true; #endif }
2,283
38
jart/cosmopolitan
false
cosmopolitan/libc/calls/ptsname.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/syscall_support-sysv.internal.h" #include "libc/calls/termios.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" static char g_ptsname[16]; /** * Gets name subordinate pseudoteletypewriter. * * @return static string path on success, or NULL w/ errno */ char *ptsname(int fd) { char *res; if (!_ptsname(fd, g_ptsname, sizeof(g_ptsname))) { res = g_ptsname; } else { res = 0; } STRACE("ptsname(%d) → %#s% m", fd, res); return res; }
2,333
41
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigenter-linux.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 "ape/sections.internal.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/ucontext.h" #include "libc/intrin/likely.h" #include "libc/math.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #ifdef __x86_64__ privileged void __sigenter_wsl(int sig, struct siginfo *info, ucontext_t *ctx) { int i, rva, flags; rva = __sighandrvas[sig & (NSIG - 1)]; if (rva >= kSigactionMinRva) { flags = __sighandflags[sig & (NSIG - 1)]; // WSL1 doesn't set the fpregs field. // https://github.com/microsoft/WSL/issues/2555 if ((flags & SA_SIGINFO) && UNLIKELY(!ctx->uc_mcontext.fpregs)) { ctx->uc_mcontext.fpregs = &ctx->__fpustate; for (i = 0; i < 8; ++i) { long double nan = NAN; memcpy(ctx->__fpustate.st + i, &nan, 16); } } ((sigaction_f)(__executable_start + rva))(sig, info, ctx); } } #endif /* __x86_64__ */
2,877
52
jart/cosmopolitan
false
cosmopolitan/libc/calls/rename.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/sysv/consts/at.h" /** * Moves file the Unix way. * * This is generally an atomic operation with the file system, since all * it's doing is changing a name associated with an inode. However, that * means rename() doesn't permit your `oldpathname` and `newpathname` to * be on separate file systems, in which case this returns EXDEV. That's * also the case on Windows. * * @return 0 on success or -1 w/ errno * @asyncsignalsafe */ int rename(const char *oldpathname, const char *newpathname) { return renameat(AT_FDCWD, oldpathname, AT_FDCWD, newpathname); }
2,452
37
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_totimeval.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/timeval.h" /** * Reduces `ts` from 1e-9 to 1e-6 granularity w/ ceil rounding. * * This function uses ceiling rounding. For example, if `ts` is one * nanosecond, then one microsecond will be returned. Ceil rounding * is needed by many interfaces, e.g. setitimer(), because the zero * timestamp has a special meaning. * * @return microseconds since epoch * @see timespec_tomicros() */ struct timeval timespec_totimeval(struct timespec ts) { if (ts.tv_nsec < 1000000000 - 999) { return (struct timeval){ts.tv_sec, (ts.tv_nsec + 999) / 1000}; } else { return (struct timeval){ts.tv_sec + 1, 0}; } }
2,484
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/ptrace.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/sysv/consts/ptrace.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/errfuns.h" /** * Traces process. * * This API is terrible. Consider using sys_ptrace(). * * @param request can be PTRACE_xxx * @note de facto linux only atm * @vforksafe */ long ptrace(int request, ...) { // TODO(jart): FreeBSD addr and data args are different int pid; va_list va; bool ispeek; long rc, peek, addr, *data; va_start(va, request); pid = va_arg(va, int); addr = va_arg(va, long); data = va_arg(va, long *); va_end(va); if (request == -1) { rc = einval(); /* see consts.sh */ } else { ispeek = IsLinux() && request - 1u < 3; if (ispeek) data = &peek; rc = __sys_ptrace(request, pid, addr, data); if (rc != -1 && ispeek) rc = peek; } STRACE("ptrace(%s, %d, %p, %p) → %p% m", DescribePtrace(request), pid, addr, data, rc); return rc; }
2,867
58
jart/cosmopolitan
false
cosmopolitan/libc/calls/fchown.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/syscall-sysv.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/at.h" /** * Changes owner and/or group of file, via open()'d descriptor. * * @param uid is user id, or -1u to not change * @param gid is group id, or -1u to not change * @return 0 on success, or -1 w/ errno * @see /etc/passwd for user ids * @see /etc/group for group ids * @raises ENOSYS on Windows */ int fchown(int fd, uint32_t uid, uint32_t gid) { int rc; rc = sys_fchown(fd, uid, gid); STRACE("fchown(%d, %d, %d) → %d% m", fd, uid, gid, rc); return rc; }
2,459
40
jart/cosmopolitan
false
cosmopolitan/libc/calls/flock.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/cp.internal.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" /** * Acquires lock on file. * * Please note multiple file descriptors means multiple locks. * * @param op can have LOCK_{SH,EX,NB,UN} for shared, exclusive, * non-blocking, and unlocking * @return 0 on success, or -1 w/ errno * @cancellationpoint * @restartable */ int flock(int fd, int op) { int rc; BEGIN_CANCELLATION_POINT; if (!IsWindows()) { rc = sys_flock(fd, op); } else { rc = sys_flock_nt(fd, op); } END_CANCELLATION_POINT; STRACE("flock(%d, %d) → %d% m", fd, op, rc); return rc; }
2,590
51
jart/cosmopolitan
false
cosmopolitan/libc/calls/time.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/time/time.h" #include "libc/calls/struct/timeval.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/sysv/errfuns.h" /** * Returns time as seconds from UNIX epoch. * * @param opt_out_ret can receive return value on success * @return seconds since epoch, or -1 w/ errno * @asyncsignalsafe */ int64_t time(int64_t *opt_out_ret) { int64_t secs; struct timeval tv; if (IsAsan() && opt_out_ret && !__asan_is_valid(opt_out_ret, sizeof(*opt_out_ret))) { secs = efault(); } else if (gettimeofday(&tv, 0) != -1) { secs = tv.tv_sec; if (opt_out_ret) { *opt_out_ret = secs; } } else { secs = -1; } return secs; }
2,533
48
jart/cosmopolitan
false
cosmopolitan/libc/calls/pipe.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/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/errfuns.h" /** * Creates file-less file descriptors for interprocess communication. * * @param fd is (reader, writer) * @return 0 on success or -1 w/ errno * @raise EFAULT if pipefd is NULL or an invalid address * @raise EMFILE if RLIMIT_NOFILE is exceedde * @asyncsignalsafe * @see pipe2() */ int pipe(int pipefd[hasatleast 2]) { int rc; if (!pipefd || (IsAsan() && !__asan_is_valid(pipefd, sizeof(int) * 2))) { // needed for windows which is polyfilled // needed for xnu and netbsd which don't take an argument rc = efault(); } else if (!IsWindows()) { rc = sys_pipe(pipefd); } else { rc = sys_pipe_nt(pipefd, 0); } if (!rc) { STRACE("pipe([{%d, %d}]) → %d% m", pipefd[0], pipefd[1], rc); } else { STRACE("pipe(%p) → %d% m", pipefd, rc); } return rc; }
2,893
55
jart/cosmopolitan
false
cosmopolitan/libc/calls/fchmodat.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/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Changes permissions on file, e.g.: * * CHECK_NE(-1, fchmodat(AT_FDCWD, "foo/bar.txt", 0644)); * CHECK_NE(-1, fchmodat(AT_FDCWD, "o/default/program.com", 0755)); * CHECK_NE(-1, fchmodat(AT_FDCWD, "privatefolder/", 0700)); * * @param path must exist * @param mode contains octal flags (base 8) * @param flags can have `AT_SYMLINK_NOFOLLOW` * @raise ENOTSUP if `dirfd` or `path` use zip file system * @errors ENOENT, ENOTDIR, ENOSYS * @asyncsignalsafe * @see fchmod() */ int fchmodat(int dirfd, const char *path, uint32_t mode, int flags) { int rc; if (IsAsan() && !__asan_is_valid_str(path)) { rc = efault(); } else if (_weaken(__zipos_notat) && (rc = __zipos_notat(dirfd, path)) == -1) { rc = enotsup(); } else if (!IsWindows()) { rc = sys_fchmodat(dirfd, path, mode, flags); } else { rc = sys_fchmodat_nt(dirfd, path, mode, flags); } STRACE("fchmodat(%s, %#s, %#o, %d) → %d% m", DescribeDirfd(dirfd), path, mode, flags, rc); return rc; }
3,235
61
jart/cosmopolitan
false
cosmopolitan/libc/calls/setresgid.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/syscall-sysv.internal.h" #include "libc/intrin/strace.internal.h" /** * Sets real, effective, and "saved" group ids. * * @param real sets real group id or -1 to do nothing * @param effective sets effective group id or -1 to do nothing * @param saved sets saved group id or -1 to do nothing * @see setresuid(), getauxval(AT_SECURE) * @raise ENOSYS on Windows NT */ int setresgid(uint32_t real, uint32_t effective, uint32_t saved) { int rc; if (saved != -1) { rc = sys_setresgid(real, effective, saved); } else { // polyfill xnu and netbsd rc = sys_setregid(real, effective); } STRACE("setresgid(%d, %d, %d) → %d% m", real, effective, saved, rc); return rc; }
2,580
43
jart/cosmopolitan
false
cosmopolitan/libc/calls/realpath.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ 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 above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ 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/assert.h" #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/limits.h" #include "libc/log/backtrace.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" #define SYMLOOP_MAX 40 asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); /* clang-format off */ static inline bool IsSlash(char c) { return c == '/' || c == '\\'; } static size_t GetSlashLen(const char *s) { const char *s0 = s; while (IsSlash(*s)) s++; return s-s0; } static char *ResolvePath(char *d, const char *s, size_t n) { if (d || (_weaken(malloc) && (d = _weaken(malloc)(n+1)))) { return memmove(d, s, n+1); } else { enomem(); return 0; } } /** * Returns absolute pathname. * * This function removes `/./` and `/../` components. IF the path is a * symbolic link then it's resolved. * * @param resolved needs PATH_MAX bytes or NULL to use malloc() * @return resolved or NULL w/ errno */ char *realpath(const char *filename, char *resolved) { ssize_t rc; int e, up, check_dir=0; size_t k, p, q, l, l0, cnt=0, nup=0; char output[PATH_MAX], stack[PATH_MAX+1], *z; /* STRACE("realpath(%#s, %#s)", filename, resolved); */ if (!filename) { einval(); return 0; } l = strnlen(filename, sizeof stack); if (!l) { enoent(); return 0; } if (l >= PATH_MAX) goto toolong; if (l >= 4 && READ32LE(filename) == READ32LE("/zip") && (!filename[4] || filename[4] == '/')) { return ResolvePath(resolved, filename, l); } p = sizeof stack - l - 1; q = 0; memcpy(stack+p, filename, l+1); /* Main loop. Each iteration pops the next part from stack of * remaining path components and consumes any slashes that follow. * If not a link, it's moved to output; if a link, contents are * pushed to the stack. */ restart: for (; ; p+=GetSlashLen(stack+p)) { /* If stack starts with /, the whole component is / or // * and the output state must be reset. */ if (IsSlash(stack[p])) { check_dir=0; nup=0; q=0; output[q++] = '/'; p++; /* Initial // is special. */ if (IsSlash(stack[p]) && !IsSlash(stack[p+1])) output[q++] = '/'; continue; } z = (char *)min((intptr_t)strchrnul(stack+p, '/'), (intptr_t)strchrnul(stack+p, '\\')); l0 = l = z-(stack+p); if (!l && !check_dir) break; /* Skip any . component but preserve check_dir status. */ if (l==1 && stack[p]=='.') { p += l; continue; } /* Copy next component onto output at least temporarily, to * call readlink, but wait to advance output position until * determining it's not a link. */ if (q && !IsSlash(output[q-1])) { if (!p) goto toolong; stack[--p] = '/'; l++; } if (q+l >= PATH_MAX) goto toolong; memcpy(output+q, stack+p, l); output[q+l] = 0; p += l; up = 0; if (l0==2 && stack[p-2]=='.' && stack[p-1]=='.') { up = 1; /* Any non-.. path components we could cancel start * after nup repetitions of the 3-byte string "../"; * if there are none, accumulate .. components to * later apply to cwd, if needed. */ if (q <= 3*nup) { nup++; q += l; continue; } /* When previous components are already known to be * directories, processing .. can skip readlink. */ if (!check_dir) goto skip_readlink; } e = errno; if ((rc = readlink(output, stack, p)) == -1) { if (errno != EINVAL) return 0; errno = e; /* [jart] undirty errno if not a symlink */ skip_readlink: check_dir = 0; if (up) { while(q && !IsSlash(output[q-1])) q--; if (q>1 && (q>2 || !IsSlash(output[0]))) q--; continue; } if (l0) q += l; check_dir = stack[p]; continue; } k = rc; _npassert(k <= p); if (k==p) goto toolong; if (!k) { errno = ENOENT; return 0; } if (++cnt == SYMLOOP_MAX) { errno = ELOOP; return 0; } /* If link contents end in /, strip any slashes already on * stack to avoid /->// or //->/// or spurious toolong. */ if (IsSlash(stack[k-1])) { while (IsSlash(stack[p])) p++; } p -= k; memmove(stack+p, stack, k); /* Skip the stack advancement in case we have a new * absolute base path. */ goto restart; } output[q] = 0; if (!IsSlash(output[0])) { if (!getcwd(stack, sizeof(stack))) return 0; l = strlen(stack); /* Cancel any initial .. components. */ p = 0; while (nup--) { while(l>1 && !IsSlash(stack[l-1])) l--; if (l>1) l--; p += 2; if (p<q) p++; } if (q-p && !IsSlash(stack[l-1])) stack[l++] = '/'; if (l + (q-p) + 1 >= PATH_MAX) goto toolong; memmove(output + l, output + p, q - p + 1); memcpy(output, stack, l); q = l + q-p; } return ResolvePath(resolved, output, q); toolong: enametoolong(); return 0; }
7,538
236
jart/cosmopolitan
false
cosmopolitan/libc/calls/pipe2-sysv.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/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" int32_t sys_pipe2(int pipefd[hasatleast 2], unsigned flags) { int e, rc; if (!flags) goto OldSkool; e = errno; rc = __sys_pipe2(pipefd, flags); if (rc == -1 && errno == ENOSYS) { errno = e; OldSkool: if ((rc = sys_pipe(pipefd)) != -1) { if (flags) { __fixupnewfd(pipefd[0], flags); __fixupnewfd(pipefd[1], flags); } } } return rc; }
2,435
43
jart/cosmopolitan
false
cosmopolitan/libc/calls/ioctl.h
#ifndef COSMOPOLITAN_LIBC_CALLS_IOCTL_H_ #define COSMOPOLITAN_LIBC_CALLS_IOCTL_H_ #include "libc/sysv/consts/fio.h" #include "libc/sysv/consts/sio.h" #include "libc/sysv/consts/termios.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § system calls » ioctl ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ int ioctl(int, uint64_t, ...); #if defined(__GNUC__) && !defined(__STRICT_ANSI__) /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § system calls » ioctl » undiamonding ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ #define ioctl(FD, REQUEST, ...) \ __IOCTL_DISPATCH(__EQUIVALENT, ioctl_default(FD, REQUEST, ##__VA_ARGS__), \ FD, REQUEST, ##__VA_ARGS__) #define __EQUIVALENT(X, Y) (__builtin_constant_p((X) == (Y)) && ((X) == (Y))) #define __IOCTL_DISPATCH(CMP, DEFAULT, FD, REQUEST, ...) \ ({ \ int ReZ; \ if (CMP(REQUEST, TIOCGWINSZ)) { \ ReZ = ioctl_tiocgwinsz(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, TIOCSWINSZ)) { \ ReZ = ioctl_tiocswinsz(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, TCGETS)) { \ ReZ = ioctl_tcgets(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, TCSETS)) { \ ReZ = ioctl_tcsets(FD, REQUEST, ##__VA_ARGS__); \ } else if (CMP(REQUEST, TCSETSW)) { \ ReZ = ioctl_tcsets(FD, REQUEST, ##__VA_ARGS__); \ } else if (CMP(REQUEST, TCSETSF)) { \ ReZ = ioctl_tcsets(FD, REQUEST, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFCONF)) { \ ReZ = ioctl_siocgifconf(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFADDR)) { \ ReZ = ioctl_siocgifaddr(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFNETMASK)) { \ ReZ = ioctl_siocgifnetmask(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFBRDADDR)) { \ ReZ = ioctl_siocgifbrdaddr(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFDSTADDR)) { \ ReZ = ioctl_siocgifdstaddr(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, SIOCGIFFLAGS)) { \ ReZ = ioctl_siocgifflags(FD, ##__VA_ARGS__); \ } else if (CMP(REQUEST, FIONBIO)) { \ ReZ = ioctl_default(FD, REQUEST, ##__VA_ARGS__); \ } else if (CMP(REQUEST, FIOCLEX)) { \ ReZ = ioctl_fioclex(FD, REQUEST); \ } else if (CMP(REQUEST, FIONCLEX)) { \ ReZ = ioctl_fioclex(FD, REQUEST); \ } else { \ ReZ = DEFAULT; \ } \ ReZ; \ }) int ioctl_default(int, uint64_t, ...); int ioctl_fioclex(int, int); int ioctl_siocgifaddr(int, ...); int ioctl_siocgifbrdaddr(int, ...); int ioctl_siocgifconf(int, ...); int ioctl_siocgifdstaddr(int, ...); int ioctl_siocgifflags(int, ...); int ioctl_siocgifnetmask(int, ...); int ioctl_tcgets(int, ...); int ioctl_tcsets(int, uint64_t, ...); int ioctl_tiocgwinsz(int, ...); int ioctl_tiocswinsz(int, ...); #endif /* GNUC && !ANSI */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_IOCTL_H_ */
4,492
82
jart/cosmopolitan
false
cosmopolitan/libc/calls/rusage_add.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/rusage.h" #include "libc/macros.internal.h" /** * Accumulates resource statistics in `y` to `x`. */ void rusage_add(struct rusage *x, const struct rusage *y) { x->ru_utime = timeval_add(x->ru_utime, y->ru_utime); x->ru_stime = timeval_add(x->ru_stime, y->ru_stime); x->ru_maxrss = MAX(x->ru_maxrss, y->ru_maxrss); x->ru_ixrss += y->ru_ixrss; x->ru_idrss += y->ru_idrss; x->ru_isrss += y->ru_isrss; x->ru_minflt += y->ru_minflt; x->ru_majflt += y->ru_majflt; x->ru_nswap += y->ru_nswap; x->ru_inblock += y->ru_inblock; x->ru_oublock += y->ru_oublock; x->ru_msgsnd += y->ru_msgsnd; x->ru_msgrcv += y->ru_msgrcv; x->ru_nsignals += y->ru_nsignals; x->ru_nvcsw += y->ru_nvcsw; x->ru_nivcsw += y->ru_nivcsw; }
2,603
43
jart/cosmopolitan
false
cosmopolitan/libc/calls/lchmod.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/at.h" /** * Changes mode of pathname, w/o dereferencing symlinks. * * @param uid is user id, or -1u to not change * @param gid is group id, or -1u to not change * @return 0 on success, or -1 w/ errno * @see chown() which dereferences symbolic links * @see /etc/passwd for user ids * @see /etc/group for group ids */ int lchmod(const char *pathname, uint32_t mode) { return fchmodat(AT_FDCWD, pathname, mode, AT_SYMLINK_NOFOLLOW); }
2,337
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/xattr.h
#ifndef COSMOPOLITAN_LIBC_CALLS_XATTR_H_ #define COSMOPOLITAN_LIBC_CALLS_XATTR_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ ssize_t flistxattr(int, char *, size_t); ssize_t fgetxattr(int, const char *, void *, size_t); int fsetxattr(int, const char *, const void *, size_t, int); int fremovexattr(int, const char *); ssize_t listxattr(const char *, char *, size_t); ssize_t getxattr(const char *, const char *, void *, size_t); int setxattr(const char *, const char *, const void *, size_t, int); int removexattr(const char *, const char *); ssize_t llistxattr(const char *, char *, size_t); ssize_t lgetxattr(const char *, const char *, void *, size_t); int lsetxattr(const char *, const char *, const void *, size_t, int); int lremovexattr(const char *, const char *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_XATTR_H_ */
904
22
jart/cosmopolitan
false
cosmopolitan/libc/calls/getdomainname-linux.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/utsname-linux.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" int getdomainname_linux(char *name, size_t len) { struct utsname_linux uts; if (!sys_uname_linux(&uts)) { if (memccpy(name, uts.domainname, '\0', len)) { return 0; } else { return enametoolong(); } } return -1; }
2,193
34
jart/cosmopolitan
false
cosmopolitan/libc/calls/rusage2linux.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/rusage.h" #include "libc/calls/struct/rusage.internal.h" #include "libc/dce.h" void __rusage2linux(struct rusage *ru) { if (IsXnu()) { ru->ru_maxrss /= 1024; } }
2,035
28
jart/cosmopolitan
false
cosmopolitan/libc/calls/mount.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/mount.h" #include "libc/dce.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" int32_t sys_mount_linux(const char *source, const char *target, const char *filesystemtype, uint64_t mountflags, const void *data) asm("sys_mount"); int32_t sys_mount_bsd(const char *type, const char *dir, int32_t flags, void *data) asm("sys_mount"); /** * Mounts file system. * * The following flags may be specified: * * - `MS_RDONLY` (mount read-only) * - `MS_NOSUID` (don't honor S_ISUID bit) * - `MS_NODEV` (disallow special files) * - `MS_NOEXEC` (disallow program execution) * - `MS_SYNCHRONOUS` (writes are synced at once) * - `MS_NOATIME` (do not update access times) * - `MS_REMOUNT` (tune existing mounting) * * The following flags may also be used, but could be set to zero at * runtime if the underlying kernel doesn't support them. * * - `MNT_ASYNC` (xnu, freebsd, openbsd, netbsd) * - `MNT_RELOAD` (xnu, freebsd, openbsd, netbsd) * - `MS_STRICTATIME` (linux, xnu) * - `MS_RELATIME` (linux, netbsd) * - `MNT_SNAPSHOT` (xnu, freebsd) * - `MS_MANDLOCK` (linux) * - `MS_DIRSYNC` (linux) * - `MS_NODIRATIME` (linux) * - `MS_BIND` (linux) * - `MS_MOVE` (linux) * - `MS_REC` (linux) * - `MS_SILENT` (linux) * - `MS_POSIXACL` (linux) * - `MS_UNBINDABLE` (linux) * - `MS_PRIVATE` (linux) * - `MS_SLAVE` (linux) * - `MS_SHARED` (linux) * - `MS_KERNMOUNT` (linux) * - `MS_I_VERSION` (linux) * - `MS_LAZYTIME` (linux) * - `MS_ACTIVE` (linux) * - `MS_NOUSER` (linux) * - `MS_RMT`_MASK (linux) * - `MNT_SUIDDIR` (freebsd) * - `MNT_NOCLUSTERR` (freebsd) * - `MNT_NOCLUSTERW` (freebsd) * * Some example values for the `type` parameter: * * - `"nfs"` * - `"vfat"` * - `"tmpfs"` * - `"iso8601"` * */ int mount(const char *source, const char *target, const char *type, unsigned long flags, const void *data) { if (!IsWindows()) { if (!IsBsd()) { return sys_mount_linux(source, target, type, flags, data); } else { if (!strcmp(type, "iso9660")) type = "cd9660"; if (!strcmp(type, "vfat")) { if (IsOpenbsd() || IsNetbsd()) { type = "msdos"; } else { type = "msdosfs"; } } return sys_mount_bsd(type, target, flags, data); } } else { return enosys(); } }
4,220
101
jart/cosmopolitan
false
cosmopolitan/libc/calls/mkntpath.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/ntmagicpaths.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/macros.internal.h" #include "libc/nt/systeminfo.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" static inline bool IsSlash(char c) { return c == '/' || c == '\\'; } static inline int IsAlpha(int c) { return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'); } textwindows static const char *FixNtMagicPath(const char *path, unsigned flags) { const struct NtMagicPaths *mp = &kNtMagicPaths; asm("" : "+r"(mp)); if (!IsSlash(path[0])) return path; if (strcmp(path, mp->devtty) == 0) { if ((flags & O_ACCMODE) == O_RDONLY) { return mp->conin; } else if ((flags & O_ACCMODE) == O_WRONLY) { return mp->conout; } } if (strcmp(path, mp->devnull) == 0) return mp->nul; if (strcmp(path, mp->devstdin) == 0) return mp->conin; if (strcmp(path, mp->devstdout) == 0) return mp->conout; return path; } textwindows int __mkntpath(const char *path, char16_t path16[hasatleast PATH_MAX]) { return __mkntpath2(path, path16, -1); } /** * Copies path for Windows NT. * * This function does the following chores: * * 1. Converting UTF-8 to UTF-16 * 2. Replacing forward-slashes with backslashes * 3. Fixing drive letter paths, e.g. `/c/` → `c:\` * 4. Add `\\?\` prefix for paths exceeding 260 chars * 5. Remapping well-known paths, e.g. `/dev/null` → `NUL` * * @param flags is used by open() * @param path16 is shortened so caller can prefix, e.g. \\.\pipe\, and * due to a plethora of special-cases throughout the Win32 API * @return short count excluding NUL on success, or -1 w/ errno * @error ENAMETOOLONG */ textwindows int __mkntpath2(const char *path, char16_t path16[hasatleast PATH_MAX], int flags) { /* * 1. Need +1 for NUL-terminator * 2. Need +1 for UTF-16 overflow * 3. Need ≥2 for SetCurrentDirectory trailing slash requirement * 4. Need ≥13 for mkdir() i.e. 1+8+3+1, e.g. "\\ffffffff.xxx\0" * which is an "8.3 filename" from the DOS days */ const char *q; bool isdospath; char16_t c, *p; size_t i, j, n, m, x, z; if (!path) return efault(); path = FixNtMagicPath(path, flags); p = path16; q = path; if (IsSlash(q[0]) && IsAlpha(q[1]) && IsSlash(q[2])) { z = MIN(32767, PATH_MAX); // turn "\c\foo" into "\\?\c:\foo" p[0] = '\\'; p[1] = '\\'; p[2] = '?'; p[3] = '\\'; p[4] = q[1]; p[5] = ':'; p[6] = '\\'; p += 7; q += 3; z -= 7; x = 7; } else if (IsSlash(q[0]) && IsAlpha(q[1]) && !q[2]) { z = MIN(32767, PATH_MAX); // turn "\c" into "\\?\c:\" p[0] = '\\'; p[1] = '\\'; p[2] = '?'; p[3] = '\\'; p[4] = q[1]; p[5] = ':'; p[6] = '\\'; p += 7; q += 2; z -= 7; x = 7; } else if (IsAlpha(q[0]) && q[1] == ':' && IsSlash(q[2])) { z = MIN(32767, PATH_MAX); // turn "c:\foo" into "\\?\c:\foo" p[0] = '\\'; p[1] = '\\'; p[2] = '?'; p[3] = '\\'; p[4] = q[0]; p[5] = ':'; p[6] = '\\'; p += 7; q += 3; z -= 7; x = 7; } else if (IsSlash(q[0]) && IsSlash(q[1]) && q[2] == '?' && IsSlash(q[3])) { z = MIN(32767, PATH_MAX); x = 0; } else { z = MIN(260, PATH_MAX); x = 0; } // turn /tmp into GetTempPath() if (!x && IsSlash(q[0]) && q[1] == 't' && q[2] == 'm' && q[3] == 'p' && (IsSlash(q[4]) || !q[4])) { m = GetTempPath(z, p); if (!q[4]) return m; q += 5; p += m; z -= m; } else { m = 0; } // turn utf-8 into utf-16 n = tprecode8to16(p, z, q).ax; if (n >= z - 1) { STRACE("path too long for windows: %#s", path); return enametoolong(); } // 1. turn `/` into `\` // 2. turn `\\` into `\` if not at beginning for (j = i = 0; i < n; ++i) { c = p[i]; if (c == '/') { c = '\\'; } if (j > 1 && c == '\\' && p[j - 1] == '\\') { continue; } p[j++] = c; } p[j] = 0; n = j; // our path is now stored at `path16` with length `n` n = x + m + n; // To avoid toil like this: // // CMD.EXE was started with the above path as the current directory. // UNC paths are not supported. Defaulting to Windows directory. // Access is denied. // // Remove \\?\ prefix if we're within 260 character limit. if (n > 4 && n < 260 && // path16[0] == '\\' && // path16[1] == '\\' && // path16[2] == '?' && // path16[3] == '\\') { memmove(path16, path16 + 4, (n - 4 + 1) * sizeof(char16_t)); n -= 4; } return n; }
6,583
199
jart/cosmopolitan
false
cosmopolitan/libc/calls/gethostname-linux.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/utsname-linux.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" int gethostname_linux(char *name, size_t len) { struct utsname_linux uts; if (!sys_uname_linux(&uts)) { if (memccpy(name, uts.nodename, '\0', len)) { return 0; } else { return enametoolong(); } } return -1; }
2,243
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigaltstack.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/sigaltstack.h" #include "libc/calls/struct/metasigaltstack.h" #include "libc/calls/struct/sigaltstack.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/ss.h" #include "libc/sysv/errfuns.h" static void sigaltstack2bsd(struct sigaltstack_bsd *bsd, const struct sigaltstack *linux) { void *sp; int flags; size_t size; sp = linux->ss_sp; flags = linux->ss_flags; size = linux->ss_size; bsd->ss_sp = sp; bsd->ss_flags = flags; bsd->ss_size = size; } static void sigaltstack2linux(struct sigaltstack *linux, const struct sigaltstack_bsd *bsd) { void *sp; int flags; size_t size; sp = bsd->ss_sp; flags = bsd->ss_flags; size = bsd->ss_size; linux->ss_sp = sp; linux->ss_flags = flags; linux->ss_size = size; } /** * Sets and/or gets alternate signal stack, e.g. * * struct sigaction sa; * struct sigaltstack ss; * ss.ss_flags = 0; * ss.ss_size = GetStackSize(); * ss.ss_sp = mmap(0, GetStackSize(), PROT_READ | PROT_WRITE, * MAP_STACK | MAP_ANONYMOUS, -1, 0); * sa.sa_flags = SA_ONSTACK; * sa.sa_handler = OnStackOverflow; * __cxa_atexit(free, ss[0].ss_sp, 0); * sigemptyset(&sa.ss_mask); * sigaltstack(&ss, 0); * sigaction(SIGSEGV, &sa, 0); * * It's strongly recommended that you allocate a stack with the same * size as GetStackSize() and that it have GetStackSize() alignment. * Otherwise some of your runtime support code (e.g. ftrace stack use * logging, kprintf() memory safety) won't be able to work as well. * * @param neu if non-null will install new signal alt stack * @param old if non-null will receive current signal alt stack * @return 0 on success, or -1 w/ errno * @raise EFAULT if bad memory was supplied * @raise ENOMEM if `neu->ss_size` is less than `MINSIGSTKSZ` */ int sigaltstack(const struct sigaltstack *neu, struct sigaltstack *old) { int rc; void *b; const void *a; struct sigaltstack_bsd bsd; if (IsAsan() && ((old && __asan_check(old, sizeof(*old)).kind) || (neu && (__asan_check(neu, sizeof(*neu)).kind || __asan_check(neu->ss_sp, neu->ss_size).kind)))) { rc = efault(); } else if (neu && neu->ss_size < MINSIGSTKSZ) { rc = enomem(); } else if (IsLinux() || IsBsd()) { if (IsLinux()) { a = neu; b = old; } else { if (neu) { sigaltstack2bsd(&bsd, neu); a = &bsd; } else { a = 0; } if (old) { b = &bsd; } else { b = 0; } } if ((rc = sys_sigaltstack(a, b)) != -1) { if (IsBsd() && old) { sigaltstack2linux(old, &bsd); } rc = 0; } else { rc = -1; } } else { rc = enosys(); } STRACE("sigaltstack(%s, [%s]) → %d% m", DescribeSigaltstk(0, neu), DescribeSigaltstk(0, old), rc); return rc; }
4,977
126
jart/cosmopolitan
false
cosmopolitan/libc/calls/readv-metal.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/metalfile.internal.h" #include "libc/calls/struct/fd.internal.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/iovec.internal.h" #include "libc/intrin/weaken.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" #include "libc/vga/vga.internal.h" #ifdef __x86_64__ ssize_t sys_readv_metal(struct Fd *fd, const struct iovec *iov, int iovlen) { int i; size_t got, toto; struct MetalFile *file; switch (fd->kind) { case kFdConsole: /* * The VGA teletypewriter code may wish to send out "status report" * escape sequences, in response to requests sent to it via write(). * Read & return these if they are available. */ if (_weaken(sys_readv_vga)) { ssize_t res = _weaken(sys_readv_vga)(fd, iov, iovlen); if (res > 0) return res; } /* fall through */ case kFdSerial: return sys_readv_serial(fd, iov, iovlen); case kFdFile: file = (struct MetalFile *)fd->handle; for (toto = i = 0; i < iovlen && file->pos < file->size; ++i) { got = MIN(iov[i].iov_len, file->size - file->pos); memcpy(iov[i].iov_base, file->base, got); toto += got; } return toto; default: return ebadf(); } } #endif /* __x86_64__ */
3,168
63
jart/cosmopolitan
false
cosmopolitan/libc/calls/cp.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_CP_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_CP_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int begin_cancellation_point(void); void end_cancellation_point(int); #ifndef MODE_DBG #define BEGIN_CANCELLATION_POINT (void)0 #define END_CANCELLATION_POINT (void)0 #else #define BEGIN_CANCELLATION_POINT \ do { \ int _Cp; \ _Cp = begin_cancellation_point() #define END_CANCELLATION_POINT \ end_cancellation_point(_Cp); \ } \ while (0) #endif COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_CP_INTERNAL_H_ */
709
26
jart/cosmopolitan
false
cosmopolitan/libc/calls/onwincrash.S
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" .text.windows __wincrash_nt: ezlea __wincrash,ax jmp __nt2sysv .endfn __wincrash_nt,globl,hidden
1,971
26
jart/cosmopolitan
false
cosmopolitan/libc/calls/program_invocation_short_name.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 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/str/str.h" char *program_invocation_short_name; __attribute__((__constructor__)) static void // program_invocation_short_name_init(void) { char *p, *r; if (!__argc) return; if ((p = strrchr(__argv[0], '/'))) { r = p + 1; } else { r = __argv[0]; } program_invocation_short_name = r; }
2,192
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcgetattr.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/ioctl.h" #include "libc/calls/termios.h" #include "libc/sysv/consts/termios.h" /** * Obtains the termios struct. * * Here are the general defaults you can expect across platforms: * * c_iflag = ICRNL IXON * c_oflag = OPOST ONLCR NL0 CR0 TAB0 BS0 VT0 FF0 * c_cflag = ISIG CREAD CS8 * c_lflag = ISIG ICANON ECHO ECHOE ECHOK IEXTEN ECHOCTL ECHOKE * c_ispeed = 38400 * c_ospeed = 38400 * c_cc[VINTR] = CTRL-C * c_cc[VQUIT] = CTRL-\ # ignore this comment * c_cc[VERASE] = CTRL-? * c_cc[VKILL] = CTRL-U * c_cc[VEOF] = CTRL-D * c_cc[VTIME] = CTRL-@ * c_cc[VMIN] = CTRL-A * c_cc[VSTART] = CTRL-Q * c_cc[VSTOP] = CTRL-S * c_cc[VSUSP] = CTRL-Z * c_cc[VEOL] = CTRL-@ * c_cc[VSWTC] = CTRL-@ * c_cc[VREPRINT] = CTRL-R * c_cc[VDISCARD] = CTRL-O * c_cc[VWERASE] = CTRL-W * c_cc[VLNEXT] = CTRL-V * c_cc[VEOL2] = CTRL-@ * * @param fd open file descriptor that isatty() * @param tio is where result is stored * @return 0 on success, or -1 w/ errno * @asyncsignalsafe */ int(tcgetattr)(int fd, struct termios *tio) { return ioctl(fd, TCGETS, tio); }
3,101
60
jart/cosmopolitan
false
cosmopolitan/libc/calls/CPU_EQUAL.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/cpuset.h" #include "libc/str/str.h" int CPU_EQUAL(cpu_set_t *x, cpu_set_t *y) { return !memcmp(x, y, sizeof(*x)); }
1,983
25
jart/cosmopolitan
false
cosmopolitan/libc/calls/chdir.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/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/errfuns.h" /** * Sets current directory. * * This does *not* update the `PWD` environment variable. * * @return 0 on success, or -1 w/ errno * @asyncsignalsafe * @see fchdir() */ int chdir(const char *path) { int rc; GetProgramExecutableName(); // XXX: ugly workaround if (!path || (IsAsan() && !__asan_is_valid_str(path))) { rc = efault(); } else if (!IsWindows()) { rc = sys_chdir(path); } else { rc = sys_chdir_nt(path); } STRACE("%s(%#s) → %d% m", "chdir", path, rc); return rc; }
2,607
49
jart/cosmopolitan
false
cosmopolitan/libc/calls/pipe2.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/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" /** * Creates file-less file descriptors for interprocess communication. * * @raise EMFILE if process `RLIMIT_NOFILE` has been reached * @raise ENFILE if system-wide file limit has been reached * @param pipefd is used to return (reader, writer) file descriptors * @param flags can have O_CLOEXEC or O_DIRECT or O_NONBLOCK * @return 0 on success, or -1 w/ errno and pipefd isn't modified */ int pipe2(int pipefd[hasatleast 2], int flags) { int rc; if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT)) { return einval(); } else if (!pipefd || (IsAsan() && !__asan_is_valid(pipefd, sizeof(int) * 2))) { rc = efault(); } else if (!IsWindows()) { rc = sys_pipe2(pipefd, flags); } else { rc = sys_pipe_nt(pipefd, flags); } if (!rc) { STRACE("pipe2([{%d, %d}], %#o) → %d% m", pipefd[0], pipefd[1], flags, rc); } else { STRACE("pipe2(%p, %#o) → %d% m", pipefd, flags, rc); } return rc; }
3,038
55
jart/cosmopolitan
false
cosmopolitan/libc/calls/pivot_root.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-sysv.internal.h" #include "libc/intrin/strace.internal.h" /** * Changes root mount. * * @raise ENOSYS on non-Linux */ int pivot_root(const char *new_root, const char *put_old) { int rc; rc = sys_pivot_root(new_root, put_old); STRACE("pivot_root(%#s, %#s) → %d% m", new_root, put_old, rc); return rc; }
2,212
34
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcgetwinsize.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 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/ioctl.h" #include "libc/calls/struct/winsize.h" /** * Gets terminal window size. */ int tcgetwinsize(int fd, struct winsize *ws) { return ioctl_tiocgwinsz(fd, ws); }
2,058
29
jart/cosmopolitan
false
cosmopolitan/libc/calls/utimens.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/assert.h" #include "libc/calls/asan.internal.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/calls/struct/timeval.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" int __utimens(int fd, const char *path, const struct timespec ts[2], int flags) { int rc; struct ZiposUri zipname; if (IsMetal()) { rc = enosys(); } else if (IsAsan() && ((fd == AT_FDCWD && !__asan_is_valid_str(path)) || (ts && (!__asan_is_valid_timespec(ts + 0) || !__asan_is_valid_timespec(ts + 1))))) { rc = efault(); // bad memory } else if ((flags & ~AT_SYMLINK_NOFOLLOW)) { rc = einval(); // unsupported flag } else if (__isfdkind(fd, kFdZip) || (path && (_weaken(__zipos_parseuri) && _weaken(__zipos_parseuri)(path, &zipname) != -1))) { rc = enotsup(); } else if (IsLinux() && !__is_linux_2_6_23() && fd == AT_FDCWD && !flags) { rc = sys_utimes(path, (void *)ts); // rhel5 truncates to seconds } else if (!IsWindows()) { rc = sys_utimensat(fd, path, ts, flags); } else { rc = sys_utimensat_nt(fd, path, ts, flags); } return rc; }
3,399
60
jart/cosmopolitan
false
cosmopolitan/libc/calls/winerr.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_WINERR_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_WINERR_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_WINERR_INTERNAL_H_ */
286
9
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_real.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/struct/timespec.h" #include "libc/sysv/consts/clock.h" /** * Returns current time. * * This function uses a `CLOCK_REALTIME` clock and never fails. Unlike * clock_gettime() or timespec_real() this interface avoids the use of * pointers which lets time handling code become more elegant. * * @see timespec_mono() */ struct timespec timespec_real(void) { struct timespec ts; _npassert(!clock_gettime(CLOCK_REALTIME, &ts)); return ts; }
2,331
37
jart/cosmopolitan
false