Make improvements

- This change fixes a bug that allowed unbuffered printf() output (to
  streams like stderr) to be truncated. This regression was introduced
  some time between now and the last release.

- POSIX specifies all functions as thread safe by default. This change
  works towards cleaning up our use of the @threadsafe / @threadunsafe
  documentation annotations to reflect that. The goal is (1) to use
  @threadunsafe to document functions which POSIX say needn't be thread
  safe, and (2) use @threadsafe to document functions that we chose to
  implement as thread safe even though POSIX didn't mandate it.

- Tidy up the clock_gettime() implementation. We're now trying out a
  cleaner approach to system call support that aims to maintain the
  Linux errno convention as long as possible. This also fixes bugs that
  existed previously, where the vDSO errno wasn't being translated
  properly. The gettimeofday() system call is now a wrapper for
  clock_gettime(), which reduces bloat in apps that use both.

- The recently-introduced improvements to the execute bit on Windows has
  had bugs fixed. access(X_OK) on a directory on Windows now succeeds.
  fstat() will now perform the MZ/#! ReadFile() operation correctly.

- Windows.h is no longer included in libc/isystem/, because it confused
  PCRE's build system into thinking Cosmopolitan is a WIN32 platform.
  Cosmo's Windows.h polyfill was never even really that good, since it
  only defines a subset of the subset of WIN32 APIs that Cosmo defines.

- The setlongerjmp() / longerjmp() APIs are removed. While they're nice
  APIs that are superior to the standardized setjmp / longjmp functions,
  they weren't superior enough to not be dead code in the monorepo. If
  you use these APIs, please file an issue and they'll be restored.

- The .com appending magic has now been removed from APE Loader.
This commit is contained in:
Justine Tunney 2023-10-02 19:25:19 -07:00
parent b99512ac58
commit ff77f2a6af
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
226 changed files with 708 additions and 2657 deletions

View file

@ -76,7 +76,8 @@ struct Syslib {
long (*write)(int, const void *, size_t); long (*write)(int, const void *, size_t);
long (*read)(int, void *, size_t); long (*read)(int, void *, size_t);
long (*sigaction)(int, const struct sigaction *, struct sigaction *); long (*sigaction)(int, const struct sigaction *, struct sigaction *);
long (*pselect)(int, fd_set *, fd_set *, fd_set *, const struct timespec *, const sigset_t *); long (*pselect)(int, fd_set *, fd_set *, fd_set *, const struct timespec *,
const sigset_t *);
long (*mprotect)(void *, size_t, int); long (*mprotect)(void *, size_t, int);
}; };
@ -187,10 +188,6 @@ struct ApeLoader {
char rando[16]; char rando[16];
}; };
static int ToLower(int c) {
return 'A' <= c && c <= 'Z' ? c + ('a' - 'A') : c;
}
static unsigned long StrLen(const char *s) { static unsigned long StrLen(const char *s) {
unsigned long n = 0; unsigned long n = 0;
while (*s++) ++n; while (*s++) ++n;
@ -349,38 +346,14 @@ __attribute__((__noreturn__)) static void Pexit(const char *c, int failed,
_exit(127); _exit(127);
} }
static char EndsWithIgnoreCase(const char *p, unsigned long n, const char *s) { static char AccessCommand(struct PathSearcher *ps, unsigned long pathlen) {
unsigned long i, m; if (pathlen + 1 + ps->namelen + 1 > sizeof(ps->path)) return 0;
if (n >= (m = StrLen(s))) {
for (i = n - m; i < n; ++i) {
if (ToLower(p[i]) != *s++) {
return 0;
}
}
return 1;
} else {
return 0;
}
}
static char IsComPath(struct PathSearcher *ps) {
return EndsWithIgnoreCase(ps->name, ps->namelen, ".com") ||
EndsWithIgnoreCase(ps->name, ps->namelen, ".exe") ||
EndsWithIgnoreCase(ps->name, ps->namelen, ".com.dbg");
}
static char AccessCommand(struct PathSearcher *ps, const char *suffix,
unsigned long pathlen) {
unsigned long suffixlen;
suffixlen = StrLen(suffix);
if (pathlen + 1 + ps->namelen + suffixlen + 1 > sizeof(ps->path)) return 0;
if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/'; if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/';
MemMove(ps->path + pathlen, ps->name, ps->namelen); MemMove(ps->path + pathlen, ps->name, ps->namelen);
MemMove(ps->path + pathlen + ps->namelen, suffix, suffixlen + 1);
return !access(ps->path, X_OK); return !access(ps->path, X_OK);
} }
static char SearchPath(struct PathSearcher *ps, const char *suffix) { static char SearchPath(struct PathSearcher *ps) {
const char *p; const char *p;
unsigned long i; unsigned long i;
for (p = ps->syspath;;) { for (p = ps->syspath;;) {
@ -389,7 +362,7 @@ static char SearchPath(struct PathSearcher *ps, const char *suffix) {
ps->path[i] = p[i]; ps->path[i] = p[i];
} }
} }
if (AccessCommand(ps, suffix, i)) { if (AccessCommand(ps, i)) {
return 1; return 1;
} else if (p[i] == ':') { } else if (p[i] == ':') {
p += i + 1; p += i + 1;
@ -399,13 +372,13 @@ static char SearchPath(struct PathSearcher *ps, const char *suffix) {
} }
} }
static char FindCommand(struct PathSearcher *ps, const char *suffix) { static char FindCommand(struct PathSearcher *ps) {
ps->path[0] = 0; ps->path[0] = 0;
/* paths are always 100% taken literally when a slash exists /* paths are always 100% taken literally when a slash exists
$ ape foo/bar.com arg1 arg2 */ $ ape foo/bar.com arg1 arg2 */
if (MemChr(ps->name, '/', ps->namelen)) { if (MemChr(ps->name, '/', ps->namelen)) {
return AccessCommand(ps, suffix, 0); return AccessCommand(ps, 0);
} }
/* we don't run files in the current directory /* we don't run files in the current directory
@ -416,12 +389,12 @@ static char FindCommand(struct PathSearcher *ps, const char *suffix) {
however we will execute this however we will execute this
$ ape - foo.com foo.com arg1 arg2 $ ape - foo.com foo.com arg1 arg2
because cosmo's execve needs it */ because cosmo's execve needs it */
if (ps->literally && AccessCommand(ps, suffix, 0)) { if (ps->literally && AccessCommand(ps, 0)) {
return 1; return 1;
} }
/* otherwise search for name on $PATH */ /* otherwise search for name on $PATH */
return SearchPath(ps, suffix); return SearchPath(ps);
} }
static char *Commandv(struct PathSearcher *ps, const char *name, static char *Commandv(struct PathSearcher *ps, const char *name,
@ -429,7 +402,7 @@ static char *Commandv(struct PathSearcher *ps, const char *name,
ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin"; ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin";
if (!(ps->namelen = StrLen((ps->name = name)))) return 0; if (!(ps->namelen = StrLen((ps->name = name)))) return 0;
if (ps->namelen + 1 > sizeof(ps->path)) return 0; if (ps->namelen + 1 > sizeof(ps->path)) return 0;
if (FindCommand(ps, "") || (!IsComPath(ps) && FindCommand(ps, ".com"))) { if (FindCommand(ps)) {
return ps->path; return ps->path;
} else { } else {
return 0; return 0;
@ -843,12 +816,14 @@ static long sys_mmap(void *addr, size_t size, int prot, int flags, int fd,
return sysret((long)mmap(addr, size, prot, flags, fd, off)); return sysret((long)mmap(addr, size, prot, flags, fd, off));
} }
static long sys_sigaction(int sig, const struct sigaction *act, struct sigaction *oact) { static long sys_sigaction(int sig, const struct sigaction *act,
struct sigaction *oact) {
return sysret(sigaction(sig, act, oact)); return sysret(sigaction(sig, act, oact));
} }
static long sys_pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, static long sys_pselect(int nfds, fd_set *readfds, fd_set *writefds,
const struct timespec *timeout, const sigset_t *sigmask) { fd_set *errorfds, const struct timespec *timeout,
const sigset_t *sigmask) {
return sysret(pselect(nfds, readfds, writefds, errorfds, timeout, sigmask)); return sysret(pselect(nfds, readfds, writefds, errorfds, timeout, sigmask));
} }

View file

@ -227,10 +227,6 @@ EXTERN_C void Launch(void *, long, void *, int) __attribute__((__noreturn__));
extern char __executable_start[]; extern char __executable_start[];
extern char _end[]; extern char _end[];
static int ToLower(int c) {
return 'A' <= c && c <= 'Z' ? c + ('a' - 'A') : c;
}
static unsigned long StrLen(const char *s) { static unsigned long StrLen(const char *s) {
unsigned long n = 0; unsigned long n = 0;
while (*s++) ++n; while (*s++) ++n;
@ -538,38 +534,14 @@ __attribute__((__noreturn__)) static void Pexit(int os, const char *c, int rc,
Exit(127, os); Exit(127, os);
} }
static char EndsWithIgnoreCase(const char *p, unsigned long n, const char *s) { static char AccessCommand(struct PathSearcher *ps, unsigned long pathlen) {
unsigned long i, m; if (pathlen + 1 + ps->namelen + 1 > sizeof(ps->path)) return 0;
if (n >= (m = StrLen(s))) {
for (i = n - m; i < n; ++i) {
if (ToLower(p[i]) != *s++) {
return 0;
}
}
return 1;
} else {
return 0;
}
}
static char IsComPath(struct PathSearcher *ps) {
return EndsWithIgnoreCase(ps->name, ps->namelen, ".com") ||
EndsWithIgnoreCase(ps->name, ps->namelen, ".exe") ||
EndsWithIgnoreCase(ps->name, ps->namelen, ".com.dbg");
}
static char AccessCommand(struct PathSearcher *ps, const char *suffix,
unsigned long pathlen) {
unsigned long suffixlen;
suffixlen = StrLen(suffix);
if (pathlen + 1 + ps->namelen + suffixlen + 1 > sizeof(ps->path)) return 0;
if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/'; if (pathlen && ps->path[pathlen - 1] != '/') ps->path[pathlen++] = '/';
MemMove(ps->path + pathlen, ps->name, ps->namelen); MemMove(ps->path + pathlen, ps->name, ps->namelen);
MemMove(ps->path + pathlen + ps->namelen, suffix, suffixlen + 1);
return !Access(ps->path, X_OK, ps->os); return !Access(ps->path, X_OK, ps->os);
} }
static char SearchPath(struct PathSearcher *ps, const char *suffix) { static char SearchPath(struct PathSearcher *ps) {
const char *p; const char *p;
unsigned long i; unsigned long i;
for (p = ps->syspath;;) { for (p = ps->syspath;;) {
@ -578,7 +550,7 @@ static char SearchPath(struct PathSearcher *ps, const char *suffix) {
ps->path[i] = p[i]; ps->path[i] = p[i];
} }
} }
if (AccessCommand(ps, suffix, i)) { if (AccessCommand(ps, i)) {
return 1; return 1;
} else if (p[i] == ':') { } else if (p[i] == ':') {
p += i + 1; p += i + 1;
@ -588,13 +560,13 @@ static char SearchPath(struct PathSearcher *ps, const char *suffix) {
} }
} }
static char FindCommand(struct PathSearcher *ps, const char *suffix) { static char FindCommand(struct PathSearcher *ps) {
ps->path[0] = 0; ps->path[0] = 0;
/* paths are always 100% taken literally when a slash exists /* paths are always 100% taken literally when a slash exists
$ ape foo/bar.com arg1 arg2 */ $ ape foo/bar.com arg1 arg2 */
if (MemChr(ps->name, '/', ps->namelen)) { if (MemChr(ps->name, '/', ps->namelen)) {
return AccessCommand(ps, suffix, 0); return AccessCommand(ps, 0);
} }
/* we don't run files in the current directory /* we don't run files in the current directory
@ -605,12 +577,12 @@ static char FindCommand(struct PathSearcher *ps, const char *suffix) {
however we will execute this however we will execute this
$ ape - foo.com foo.com arg1 arg2 $ ape - foo.com foo.com arg1 arg2
because cosmo's execve needs it */ because cosmo's execve needs it */
if (ps->literally && AccessCommand(ps, suffix, 0)) { if (ps->literally && AccessCommand(ps, 0)) {
return 1; return 1;
} }
/* otherwise search for name on $PATH */ /* otherwise search for name on $PATH */
return SearchPath(ps, suffix); return SearchPath(ps);
} }
static char *Commandv(struct PathSearcher *ps, int os, const char *name, static char *Commandv(struct PathSearcher *ps, int os, const char *name,
@ -619,7 +591,7 @@ static char *Commandv(struct PathSearcher *ps, int os, const char *name,
ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin"; ps->syspath = syspath ? syspath : "/bin:/usr/local/bin:/usr/bin";
if (!(ps->namelen = StrLen((ps->name = name)))) return 0; if (!(ps->namelen = StrLen((ps->name = name)))) return 0;
if (ps->namelen + 1 > sizeof(ps->path)) return 0; if (ps->namelen + 1 > sizeof(ps->path)) return 0;
if (FindCommand(ps, "") || (!IsComPath(ps) && FindCommand(ps, ".com"))) { if (FindCommand(ps)) {
return ps->path; return ps->path;
} else { } else {
return 0; return 0;

View file

@ -32,6 +32,7 @@
#include "dsp/mpeg/idct.h" #include "dsp/mpeg/idct.h"
#include "dsp/mpeg/mpeg.h" #include "dsp/mpeg/mpeg.h"
#include "dsp/mpeg/video.h" #include "dsp/mpeg/video.h"
#include "libc/calls/struct/timespec.h"
#include "libc/fmt/conv.h" #include "libc/fmt/conv.h"
#include "libc/log/log.h" #include "libc/log/log.h"
#include "libc/macros.internal.h" #include "libc/macros.internal.h"

View file

@ -107,6 +107,8 @@ o//libc/calls/statfs2cosmo.o: private \
# we always want -O2 because: # we always want -O2 because:
# division is expensive if not optimized # division is expensive if not optimized
o/$(MODE)/libc/calls/clock.o \ o/$(MODE)/libc/calls/clock.o \
o/$(MODE)/libc/calls/gettimeofday.o \
o/$(MODE)/libc/calls/clock_gettime-mono.o \
o/$(MODE)/libc/calls/timespec_tomillis.o \ o/$(MODE)/libc/calls/timespec_tomillis.o \
o/$(MODE)/libc/calls/timespec_tomicros.o \ o/$(MODE)/libc/calls/timespec_tomicros.o \
o/$(MODE)/libc/calls/timespec_totimeval.o \ o/$(MODE)/libc/calls/timespec_totimeval.o \

View file

@ -52,7 +52,7 @@ int64_t clock(void) {
struct rusage ru; struct rusage ru;
struct timespec ts; struct timespec ts;
e = errno; e = errno;
if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == -1) { if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)) {
errno = e; errno = e;
if (getrusage(RUSAGE_SELF, &ru) != -1) { if (getrusage(RUSAGE_SELF, &ru) != -1) {
ts = timeval_totimespec(timeval_add(ru.ru_utime, ru.ru_stime)); ts = timeval_totimespec(timeval_add(ru.ru_utime, ru.ru_stime));

View file

@ -54,7 +54,6 @@ static int sys_clock_getres_xnu(int clock, struct timespec *ts) {
* @error EPERM if pledge() is in play without stdio promise * @error EPERM if pledge() is in play without stdio promise
* @error EINVAL if `clock` isn't supported on this system * @error EINVAL if `clock` isn't supported on this system
* @error EFAULT if `ts` points to bad memory * @error EFAULT if `ts` points to bad memory
* @threadsafe
*/ */
int clock_getres(int clock, struct timespec *ts) { int clock_getres(int clock, struct timespec *ts) {
int rc; int rc;

View file

@ -16,15 +16,19 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/atomic.h"
#include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.h"
#include "libc/cosmo.h" #include "libc/cosmo.h"
#include "libc/errno.h"
#include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/rdtsc.h"
#include "libc/nexgen32e/x86feature.h" #include "libc/nexgen32e/x86feature.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/errfuns.h" /**
* @fileoverview Fast Monotonic Clock Polyfill for XNU/NT.
*/
static struct { static struct {
_Atomic(uint32_t) once; atomic_uint once;
struct timespec base_wall; struct timespec base_wall;
uint64_t base_tick; uint64_t base_tick;
} g_mono; } g_mono;
@ -37,13 +41,18 @@ static void sys_clock_gettime_mono_init(void) {
int sys_clock_gettime_mono(struct timespec *time) { int sys_clock_gettime_mono(struct timespec *time) {
uint64_t nanos; uint64_t nanos;
uint64_t cycles; uint64_t cycles;
if (X86_HAVE(INVTSC)) { #ifdef __x86_64__
// intel architecture guarantees that a mapping exists between rdtsc &
// nanoseconds only if the cpu advertises invariant timestamps support
if (!X86_HAVE(INVTSC)) return -EINVAL;
#endif
cosmo_once(&g_mono.once, sys_clock_gettime_mono_init); cosmo_once(&g_mono.once, sys_clock_gettime_mono_init);
cycles = rdtsc() - g_mono.base_tick; cycles = rdtsc() - g_mono.base_tick;
// this is a crude approximation, that's worked reasonably well so far
// only the kernel knows the actual mapping between rdtsc and nanosecs
// which we could attempt to measure ourselves using clock_gettime but
// we'd need to impose 100 ms of startup latency for a guess this good
nanos = cycles / 3; nanos = cycles / 3;
*time = timespec_add(g_mono.base_wall, timespec_fromnanos(nanos)); *time = timespec_add(g_mono.base_wall, timespec_fromnanos(nanos));
return 0; return 0;
} else {
return einval();
}
} }

View file

@ -16,12 +16,12 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/clock_gettime.internal.h" #include "libc/calls/struct/timespec.internal.h"
#include "libc/fmt/conv.h" #include "libc/errno.h"
#include "libc/fmt/wintime.internal.h"
#include "libc/nt/struct/filetime.h" #include "libc/nt/struct/filetime.h"
#include "libc/nt/synchronization.h" #include "libc/nt/synchronization.h"
#include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/clock.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_clock_gettime_nt(int clock, struct timespec *ts) { textwindows int sys_clock_gettime_nt(int clock, struct timespec *ts) {
struct NtFileTime ft; struct NtFileTime ft;
@ -32,6 +32,6 @@ textwindows int sys_clock_gettime_nt(int clock, struct timespec *ts) {
} else if (clock == CLOCK_MONOTONIC) { } else if (clock == CLOCK_MONOTONIC) {
return sys_clock_gettime_mono(ts); return sys_clock_gettime_mono(ts);
} else { } else {
return einval(); return -EINVAL;
} }
} }

View file

@ -1,7 +1,7 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ /*-*- 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 vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney Copyright 2023 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the any purpose with or without fee is hereby granted, provided that the
@ -16,11 +16,10 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timespec.internal.h" #include "libc/calls/struct/timespec.internal.h"
#include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/runtime/syslib.internal.h" #include "libc/sysv/consts/nr.h"
int sys_clock_gettime_m1(int clock, struct timespec *ts) { int sys_clock_gettime(int clock, struct timespec *ts) {
return _sysret(__syslib->__clock_gettime(clock, ts)); return __syscall2i(clock, (long)ts, __NR_clock_gettime);
} }

View file

@ -16,28 +16,46 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/clock_gettime.internal.h" #include "libc/calls/struct/timespec.internal.h"
#include "libc/calls/struct/timeval.internal.h" #include "libc/calls/struct/timeval.internal.h"
#include "libc/errno.h"
#include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/clock.h"
#include "libc/sysv/errfuns.h" #ifdef __x86_64__
int sys_clock_gettime_xnu(int clock, struct timespec *ts) { int sys_clock_gettime_xnu(int clock, struct timespec *ts) {
axdx_t ad; long ax, dx;
if (clock == CLOCK_REALTIME) { if (clock == CLOCK_REALTIME) {
ad = sys_gettimeofday((struct timeval *)ts, 0, 0); // invoke the system call
if (ad.ax != -1) { //
if (ad.ax) { // int gettimeofday(struct timeval *tp,
ts->tv_sec = ad.ax; // struct timezone *tzp,
ts->tv_nsec = ad.dx; // uint64_t *mach_absolute_time);
//
// as follows
//
// ax, dx = gettimeofday(&ts, 0, 0);
//
// to support multiple calling conventions
//
// 1. new xnu returns *ts in memory via rdi
// 2. old xnu returns *ts in rax:rdx regs
//
// we assume this system call always succeeds
asm volatile("syscall"
: "=a"(ax), "=d"(dx)
: "0"(0x2000000 | 116), "D"(ts), "S"(0), "1"(0)
: "rcx", "r8", "r9", "r10", "r11", "memory");
if (ax) {
ts->tv_sec = ax;
ts->tv_nsec = dx;
} }
ts->tv_nsec *= 1000; ts->tv_nsec *= 1000;
return 0; return 0;
} else {
return -1;
}
} else if (clock == CLOCK_MONOTONIC) { } else if (clock == CLOCK_MONOTONIC) {
return sys_clock_gettime_mono(ts); return sys_clock_gettime_mono(ts);
} else { } else {
return einval(); return -EINVAL;
} }
} }
#endif /* __x86_64__ */

View file

@ -16,82 +16,14 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/assert.h" #include "libc/calls/struct/timespec.h"
#include "libc/calls/asan.internal.h"
#include "libc/calls/clock_gettime.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/timespec.internal.h" #include "libc/calls/struct/timespec.internal.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/syscall_support-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h" #include "libc/dce.h"
#include "libc/fmt/conv.h" #include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/asmflag.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/describeflags.internal.h" #include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h" #include "libc/intrin/strace.internal.h"
#include "libc/mem/alloca.h" #include "libc/runtime/syslib.internal.h"
#include "libc/nt/synchronization.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/tls.h"
/**
* Returns nanosecond time.
*
* This is a high-precision timer that supports multiple definitions of
* time. Among the more popular is CLOCK_MONOTONIC. This function has a
* zero syscall implementation of that on modern x86.
*
* rdtsc l: 13𝑐 4𝑛𝑠
* gettimeofday l: 44𝑐 14𝑛𝑠
* clock_gettime l: 40𝑐 13𝑛𝑠
* __clock_gettime l: 35𝑐 11𝑛𝑠
* sys_clock_gettime l: 220𝑐 71𝑛𝑠
*
* @param clock can be one of:
* - `CLOCK_REALTIME`: universally supported
* - `CLOCK_REALTIME_FAST`: ditto but faster on freebsd
* - `CLOCK_REALTIME_PRECISE`: ditto but better on freebsd
* - `CLOCK_REALTIME_COARSE`: : like `CLOCK_REALTIME_FAST` w/ Linux 2.6.32+
* - `CLOCK_MONOTONIC`: universally supported
* - `CLOCK_MONOTONIC_FAST`: ditto but faster on freebsd
* - `CLOCK_MONOTONIC_PRECISE`: ditto but better on freebsd
* - `CLOCK_MONOTONIC_COARSE`: : like `CLOCK_MONOTONIC_FAST` w/ Linux 2.6.32+
* - `CLOCK_MONOTONIC_RAW`: is actually monotonic but needs Linux 2.6.28+
* - `CLOCK_PROCESS_CPUTIME_ID`: linux and bsd
* - `CLOCK_THREAD_CPUTIME_ID`: linux and bsd
* - `CLOCK_MONOTONIC_COARSE`: linux, freebsd
* - `CLOCK_PROF`: linux and netbsd
* - `CLOCK_BOOTTIME`: linux and openbsd
* - `CLOCK_REALTIME_ALARM`: linux-only
* - `CLOCK_BOOTTIME_ALARM`: linux-only
* - `CLOCK_TAI`: linux-only
* @param ts is where the result is stored
* @return 0 on success, or -1 w/ errno
* @error EPERM if pledge() is in play without stdio promise
* @error EINVAL if `clock` isn't supported on this system
* @error EFAULT if `ts` points to bad memory
* @see strftime(), gettimeofday()
* @asyncsignalsafe
* @threadsafe
* @vforksafe
*/
int clock_gettime(int clock, struct timespec *ts) {
// threads on win32 stacks call this so we can't asan check *ts
int rc;
if (clock == 127) {
rc = einval(); // 127 is used by consts.sh to mean unsupported
} else {
rc = __clock_gettime(clock, ts);
}
#if SYSDEBUG
if (__tls_enabled && !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
POLLTRACE("clock_gettime(%s, [%s]) → %d% m", DescribeClockName(clock),
DescribeTimespec(rc, ts), rc);
}
#endif
return rc;
}
#ifdef __aarch64__ #ifdef __aarch64__
#define CGT_VDSO __vdsosym("LINUX_2.6.39", "__kernel_clock_gettime") #define CGT_VDSO __vdsosym("LINUX_2.6.39", "__kernel_clock_gettime")
@ -99,39 +31,72 @@ int clock_gettime(int clock, struct timespec *ts) {
#define CGT_VDSO __vdsosym("LINUX_2.6", "__vdso_clock_gettime") #define CGT_VDSO __vdsosym("LINUX_2.6", "__vdso_clock_gettime")
#endif #endif
/** typedef int clock_gettime_f(int, struct timespec *);
* Returns pointer to fastest clock_gettime().
*/ static clock_gettime_f *__clock_gettime_get(void) {
clock_gettime_f *__clock_gettime_get(bool *opt_out_isfast) { clock_gettime_f *cgt;
bool isfast; if (IsLinux() && (cgt = CGT_VDSO)) {
clock_gettime_f *res; return cgt;
if (IsLinux() && (res = CGT_VDSO)) { } else if (__syslib) {
isfast = true; return (void *)__syslib->__clock_gettime;
} else if (IsXnu()) {
#ifdef __x86_64__
res = sys_clock_gettime_xnu;
isfast = false;
#elif defined(__aarch64__)
res = sys_clock_gettime_m1;
isfast = true;
#else
#error "unsupported architecture"
#endif
} else if (IsWindows()) { } else if (IsWindows()) {
isfast = true; return sys_clock_gettime_nt;
res = sys_clock_gettime_nt; #ifdef __x86_64__
} else if (IsXnu()) {
return sys_clock_gettime_xnu;
#endif
} else { } else {
isfast = false; return sys_clock_gettime;
res = sys_clock_gettime;
} }
if (opt_out_isfast) {
*opt_out_isfast = isfast;
}
return res;
} }
int __clock_gettime_init(int clockid, struct timespec *ts) { static int __clock_gettime_init(int, struct timespec *);
clock_gettime_f *gettime; static clock_gettime_f *__clock_gettime = __clock_gettime_init;
__clock_gettime = gettime = __clock_gettime_get(0); static int __clock_gettime_init(int clockid, struct timespec *ts) {
return gettime(clockid, ts); clock_gettime_f *cgt;
__clock_gettime = cgt = __clock_gettime_get();
return cgt(clockid, ts);
}
/**
* Returns nanosecond time.
*
* @param clock can be one of:
* - `CLOCK_REALTIME`: universally supported
* - `CLOCK_REALTIME_FAST`: ditto but faster on freebsd
* - `CLOCK_REALTIME_PRECISE`: ditto but better on freebsd
* - `CLOCK_REALTIME_COARSE`: : like `CLOCK_REALTIME_FAST` w/ Linux 2.6.32+
* - `CLOCK_MONOTONIC`: universally supported (except on XNU/NT w/o INVTSC)
* - `CLOCK_MONOTONIC_FAST`: ditto but faster on freebsd
* - `CLOCK_MONOTONIC_PRECISE`: ditto but better on freebsd
* - `CLOCK_MONOTONIC_COARSE`: : like `CLOCK_MONOTONIC_FAST` w/ Linux 2.6.32+
* - `CLOCK_MONOTONIC_RAW`: is actually monotonic but needs Linux 2.6.28+
* - `CLOCK_PROCESS_CPUTIME_ID`: linux and bsd (NetBSD permits OR'd PID)
* - `CLOCK_THREAD_CPUTIME_ID`: linux and bsd (NetBSD permits OR'd TID)
* - `CLOCK_MONOTONIC_COARSE`: linux, freebsd
* - `CLOCK_PROF`: linux and netbsd
* - `CLOCK_BOOTTIME`: linux and openbsd
* - `CLOCK_REALTIME_ALARM`: linux-only
* - `CLOCK_BOOTTIME_ALARM`: linux-only
* - `CLOCK_TAI`: linux-only
* @param ts is where the result is stored (or null to do clock check)
* @return 0 on success, or -1 w/ errno
* @raise EFAULT if `ts` points to invalid memory
* @error EINVAL if `clock` isn't supported on this system
* @error EPERM if pledge() is in play without stdio promise
* @error ESRCH on NetBSD if PID/TID OR'd into `clock` wasn't found
* @see strftime(), gettimeofday()
* @asyncsignalsafe
* @vforksafe
*/
int clock_gettime(int clock, struct timespec *ts) {
// threads on win32 stacks call this so we can't asan check *ts
int rc = __clock_gettime(clock, ts);
if (rc) {
errno = -rc;
rc = -1;
}
TIMETRACE("clock_gettime(%s, [%s]) → %d% m", DescribeClockName(clock),
DescribeTimespec(rc, ts), rc);
return rc;
} }

View file

@ -1,16 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_
#define COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_
#include "libc/calls/struct/timespec.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef int clock_gettime_f(int, struct timespec *);
extern clock_gettime_f *__clock_gettime;
clock_gettime_f *__clock_gettime_get(bool *);
int __clock_gettime_init(int, struct timespec *);
int sys_clock_gettime_mono(struct timespec *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_ */

View file

@ -19,40 +19,40 @@
#include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timespec.internal.h" #include "libc/calls/struct/timespec.internal.h"
#include "libc/calls/struct/timeval.h" #include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/timeval.internal.h"
#include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall-sysv.internal.h"
#include "libc/errno.h" #include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h" #include "libc/intrin/weaken.h"
#include "libc/runtime/syslib.internal.h" #include "libc/runtime/syslib.internal.h"
#include "libc/sock/internal.h" #include "libc/sock/internal.h"
#include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/timer.h" #include "libc/sysv/consts/timer.h"
#include "libc/sysv/errfuns.h" #include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h" #include "libc/thread/thread.h"
#include "libc/thread/tls.h"
int sys_clock_nanosleep_xnu(int clock, int flags, const struct timespec *req, int sys_clock_nanosleep_xnu(int clock, int flags, const struct timespec *req,
struct timespec *rem) { struct timespec *rem) {
#ifdef __x86_64__ #ifdef __x86_64__
struct timeval abs, now, rel;
if (clock == CLOCK_REALTIME) {
if (flags & TIMER_ABSTIME) { if (flags & TIMER_ABSTIME) {
abs = timespec_totimeval(*req); struct timespec now;
sys_gettimeofday_xnu(&now, 0, 0); sys_clock_gettime_xnu(clock, &now);
if (timeval_cmp(abs, now) > 0) { if (timespec_cmp(*req, now) > 0) {
rel = timeval_sub(abs, now); struct timeval rel = timespec_totimeval(timespec_sub(*req, now));
return sys_select(0, 0, 0, 0, &rel); return sys_select(0, 0, 0, 0, &rel);
} else { } else {
return 0; return 0;
} }
} else { } else {
return sys_nanosleep_xnu(req, rem); int rc;
struct timespec beg;
if (rem) sys_clock_gettime_xnu(CLOCK_REALTIME, &beg);
struct timeval rel = timespec_totimeval(*req); // rounds up
rc = sys_select(0, 0, 0, 0, &rel);
if (rc == -1 && rem && errno == EINTR) {
struct timespec end;
sys_clock_gettime_xnu(CLOCK_REALTIME, &end);
*rem = timespec_subz(*req, timespec_sub(end, beg));
} }
} else { return rc;
return enotsup();
} }
#else #else
long res; long res;

View file

@ -21,7 +21,6 @@
#include "libc/calls/blockcancel.internal.h" #include "libc/calls/blockcancel.internal.h"
#include "libc/calls/blocksigs.internal.h" #include "libc/calls/blocksigs.internal.h"
#include "libc/calls/calls.h" #include "libc/calls/calls.h"
#include "libc/calls/clock_gettime.internal.h"
#include "libc/calls/cp.internal.h" #include "libc/calls/cp.internal.h"
#include "libc/calls/state.internal.h" #include "libc/calls/state.internal.h"
#include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.h"
@ -76,16 +75,15 @@ static errno_t sys_clock_nanosleep(int clock, int flags,
static struct timespec GetNanosleepLatency(void) { static struct timespec GetNanosleepLatency(void) {
errno_t rc; errno_t rc;
int64_t nanos; int64_t nanos;
clock_gettime_f *cgt;
struct timespec x, y, w = {0, 1}; struct timespec x, y, w = {0, 1};
if (!(nanos = g_nanosleep_latency)) { if (!(nanos = g_nanosleep_latency)) {
BLOCK_SIGNALS; BLOCK_SIGNALS;
for (cgt = __clock_gettime_get(0);;) { for (;;) {
npassert(!cgt(CLOCK_REALTIME_PRECISE, &x)); unassert(!clock_gettime(CLOCK_REALTIME_PRECISE, &x));
rc = sys_clock_nanosleep(CLOCK_REALTIME, 0, &w, 0); rc = sys_clock_nanosleep(CLOCK_REALTIME, 0, &w, 0);
npassert(!rc || rc == EINTR); unassert(!rc || rc == EINTR);
if (!rc) { if (!rc) {
npassert(!cgt(CLOCK_REALTIME_PRECISE, &y)); unassert(!clock_gettime(CLOCK_REALTIME_PRECISE, &y));
nanos = timespec_tonanos(timespec_sub(y, x)); nanos = timespec_tonanos(timespec_sub(y, x));
g_nanosleep_latency = nanos; g_nanosleep_latency = nanos;
break; break;
@ -107,7 +105,6 @@ static errno_t CheckCancel(void) {
static errno_t SpinNanosleep(int clock, int flags, const struct timespec *req, static errno_t SpinNanosleep(int clock, int flags, const struct timespec *req,
struct timespec *rem) { struct timespec *rem) {
errno_t rc; errno_t rc;
clock_gettime_f *cgt;
struct timespec now, start, elapsed; struct timespec now, start, elapsed;
if ((rc = CheckCancel())) { if ((rc = CheckCancel())) {
if (rc == EINTR && !flags && rem) { if (rc == EINTR && !flags && rem) {
@ -115,11 +112,10 @@ static errno_t SpinNanosleep(int clock, int flags, const struct timespec *req,
} }
return rc; return rc;
} }
cgt = __clock_gettime_get(0); unassert(!clock_gettime(CLOCK_REALTIME, &start));
npassert(!cgt(CLOCK_REALTIME, &start));
for (;;) { for (;;) {
pthread_yield(); pthread_yield();
npassert(!cgt(CLOCK_REALTIME, &now)); unassert(!clock_gettime(CLOCK_REALTIME, &now));
if (flags & TIMER_ABSTIME) { if (flags & TIMER_ABSTIME) {
if (timespec_cmp(now, *req) >= 0) { if (timespec_cmp(now, *req) >= 0) {
return 0; return 0;
@ -177,7 +173,7 @@ static bool ShouldUseSpinNanosleep(int clock, int flags,
return false; return false;
} }
e = errno; e = errno;
if (__clock_gettime_get(0)(clock, &now)) { if (clock_gettime(clock, &now)) {
// punt to the nanosleep system call // punt to the nanosleep system call
errno = e; errno = e;
return false; return false;
@ -258,12 +254,8 @@ errno_t clock_nanosleep(int clock, int flags, const struct timespec *req,
} else { } else {
rc = sys_clock_nanosleep(clock, flags, req, rem); rc = sys_clock_nanosleep(clock, flags, req, rem);
} }
#if SYSDEBUG TIMETRACE("clock_nanosleep(%s, %s, %s, [%s]) → %s", DescribeClockName(clock),
if (__tls_enabled && !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) {
STRACE("clock_nanosleep(%s, %s, %s, [%s]) → %s", DescribeClockName(clock),
DescribeSleepFlags(flags), DescribeTimespec(0, req), DescribeSleepFlags(flags), DescribeTimespec(0, req),
DescribeTimespec(rc, rem), DescribeErrno(rc)); DescribeTimespec(rc, rem), DescribeErrno(rc));
}
#endif
return rc; return rc;
} }

View file

@ -34,7 +34,6 @@
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @restartable * @restartable
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int creat(const char *file, uint32_t mode) { int creat(const char *file, uint32_t mode) {

View file

@ -21,7 +21,7 @@
#include "libc/calls/internal.h" #include "libc/calls/internal.h"
#include "libc/calls/struct/stat.h" #include "libc/calls/struct/stat.h"
#include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h"
#include "libc/fmt/conv.h" #include "libc/fmt/wintime.internal.h"
#include "libc/intrin/atomic.h" #include "libc/intrin/atomic.h"
#include "libc/intrin/bsr.h" #include "libc/intrin/bsr.h"
#include "libc/intrin/strace.internal.h" #include "libc/intrin/strace.internal.h"

View file

@ -35,3 +35,5 @@ int fstatvfs(int fd, struct statvfs *sv) {
return -1; return -1;
} }
} }
__weak_reference(fstatvfs, fstatvfs64);

View file

@ -60,7 +60,6 @@
* @raise ENOSYS on bare metal * @raise ENOSYS on bare metal
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int ftruncate(int fd, int64_t length) { int ftruncate(int fd, int64_t length) {
int rc; int rc;

View file

@ -40,7 +40,6 @@
* @raise EFAULT if `ts` memory was invalid * @raise EFAULT if `ts` memory was invalid
* @raise ENOSYS on RHEL5 or bare metal * @raise ENOSYS on RHEL5 or bare metal
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int futimens(int fd, const struct timespec ts[2]) { int futimens(int fd, const struct timespec ts[2]) {
int rc; int rc;

View file

@ -37,7 +37,6 @@
* @raise ENOSYS on RHEL5 or bare metal * @raise ENOSYS on RHEL5 or bare metal
* @see futimens() for modern version * @see futimens() for modern version
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int futimes(int fd, const struct timeval tv[2]) { int futimes(int fd, const struct timeval tv[2]) {
int rc; int rc;

View file

@ -30,7 +30,6 @@
// @see makecontext() // @see makecontext()
// @see swapcontext() // @see swapcontext()
// @see setcontext() // @see setcontext()
// @threadsafe
.ftrace1 .ftrace1
getcontext: getcontext:
.ftrace2 .ftrace2

View file

@ -28,7 +28,6 @@
* @return parent process id (always successful) * @return parent process id (always successful)
* @note slow on Windows; needs to iterate process tree * @note slow on Windows; needs to iterate process tree
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int getppid(void) { int getppid(void) {

View file

@ -19,7 +19,7 @@
#include "libc/calls/sig.internal.h" #include "libc/calls/sig.internal.h"
#include "libc/calls/struct/rusage.internal.h" #include "libc/calls/struct/rusage.internal.h"
#include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h"
#include "libc/fmt/conv.h" #include "libc/fmt/wintime.internal.h"
#include "libc/nt/accounting.h" #include "libc/nt/accounting.h"
#include "libc/nt/process.h" #include "libc/nt/process.h"
#include "libc/nt/runtime.h" #include "libc/nt/runtime.h"

View file

@ -1,35 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/timeval.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sysv/consts/clock.h"
axdx_t sys_gettimeofday_m1(struct timeval *tv, struct timezone *tz, void *wut) {
axdx_t ad;
struct timespec ts;
ad.ax = _sysret(__syslib->__clock_gettime(CLOCK_REALTIME, &ts));
ad.dx = 0;
if (!ad.ax && tv) {
*tv = timespec_totimeval(ts);
}
return ad;
}

View file

@ -1,25 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/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};
}

View file

@ -1,31 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/fmt/conv.h"
#include "libc/nt/struct/filetime.h"
#include "libc/nt/synchronization.h"
#include "libc/str/str.h"
textwindows axdx_t sys_gettimeofday_nt(struct timeval *tv, struct timezone *tz,
void *wut) {
struct NtFileTime ft;
GetSystemTimeAsFileTime(&ft);
if (tv) *tv = FileTimeToTimeVal(ft);
if (tz) bzero(tz, sizeof(*tz));
return (axdx_t){0, 0};
}

View file

@ -1,31 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/struct/timeval.internal.h"
axdx_t sys_gettimeofday_xnu(struct timeval *tv, struct timezone *tz,
void *wut) {
axdx_t ad;
ad = sys_gettimeofday(tv, tz, wut);
if (ad.ax > 0 && tv) {
tv->tv_sec = ad.ax;
tv->tv_usec = ad.dx;
ad.ax = 0;
}
return ad;
}

View file

@ -16,24 +16,11 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/assert.h" #include "libc/calls/struct/timespec.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/itimerval.internal.h"
#include "libc/calls/struct/timeval.h" #include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/timeval.internal.h" #include "libc/sysv/consts/clock.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/sysv/errfuns.h"
#include "libc/thread/tls.h"
#include "libc/time/struct/timezone.h" #include "libc/time/struct/timezone.h"
typedef axdx_t gettimeofday_f(struct timeval *, struct timezone *, void *);
static gettimeofday_f __gettimeofday_init;
static gettimeofday_f *__gettimeofday = __gettimeofday_init;
/** /**
* Returns system wall time in microseconds, e.g. * Returns system wall time in microseconds, e.g.
* *
@ -47,60 +34,26 @@ static gettimeofday_f *__gettimeofday = __gettimeofday_init;
* iso8601(p, &tm); * iso8601(p, &tm);
* printf("%s\n", p); * printf("%s\n", p);
* *
* @param tv points to timeval that receives result if non-NULL * @param tv points to timeval that receives result if non-null
* @param tz receives UTC timezone if non-NULL * @param tz is completely ignored
* @return 0 on success, or -1 w/ errno
* @raise EFAULT if `tv` points to invalid memory
* @see clock_gettime() for nanosecond precision * @see clock_gettime() for nanosecond precision
* @see strftime() for string formatting * @see strftime() for string formatting
* @asyncsignalsafe
* @vforksafe
*/ */
int gettimeofday(struct timeval *tv, struct timezone *tz) { int gettimeofday(struct timeval *tv, struct timezone *tz) {
int rc = __gettimeofday(tv, tz, 0).ax; if (tv) {
#if SYSDEBUG struct timespec ts;
if (__tls_enabled && !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) { if (clock_gettime(CLOCK_REALTIME, &ts) != -1) {
POLLTRACE("gettimeofday([%s], %p) → %d% m", DescribeTimeval(rc, tv), tz, tv->tv_sec = ts.tv_sec;
rc); tv->tv_usec = (ts.tv_nsec + 999) / 1000;
} return 0;
#endif
return rc;
}
/**
* Returns pointer to fastest gettimeofday().
*/
gettimeofday_f *__gettimeofday_get(bool *opt_out_isfast) {
bool isfast;
gettimeofday_f *res;
if (IsLinux() && (res = __vdsosym("LINUX_2.6", "__vdso_gettimeofday"))) {
isfast = true;
} else if (IsWindows()) {
isfast = true;
res = sys_gettimeofday_nt;
} else if (IsXnu()) {
#ifdef __x86_64__
res = sys_gettimeofday_xnu;
isfast = false;
#elif defined(__aarch64__)
res = sys_gettimeofday_m1;
isfast = true;
#else
#error "unsupported architecture"
#endif
} else if (IsMetal()) {
isfast = false;
res = sys_gettimeofday_metal;
} else { } else {
isfast = false; return -1;
res = sys_gettimeofday;
} }
if (opt_out_isfast) { } else {
*opt_out_isfast = isfast; return 0;
} }
return res;
}
static axdx_t __gettimeofday_init(struct timeval *tv, //
struct timezone *tz, //
void *arg) {
gettimeofday_f *gettime;
__gettimeofday = gettime = __gettimeofday_get(0);
return gettime(tv, tz, 0);
} }

View file

@ -37,7 +37,6 @@
* *
* @return user id (always successful) * @return user id (always successful)
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
uint32_t getuid(void) { uint32_t getuid(void) {
@ -62,7 +61,6 @@ uint32_t getuid(void) {
* *
* @return group id (always successful) * @return group id (always successful)
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
uint32_t getgid(void) { uint32_t getgid(void) {

View file

@ -72,7 +72,6 @@
* @raise EINVAL if resulting offset would be negative * @raise EINVAL if resulting offset would be negative
* @raise EINVAL if `whence` isn't valid * @raise EINVAL if `whence` isn't valid
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int64_t lseek(int fd, int64_t offset, int whence) { int64_t lseek(int fd, int64_t offset, int whence) {

View file

@ -44,7 +44,6 @@
* @raise ENOENT if `path` is an empty string * @raise ENOENT if `path` is an empty string
* @raise ELOOP if loop was detected resolving components of `path` * @raise ELOOP if loop was detected resolving components of `path`
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int makedirs(const char *path, unsigned mode) { int makedirs(const char *path, unsigned mode) {
int c, e, i, n; int c, e, i, n;

View file

@ -45,7 +45,6 @@
* @see makedirs() which is higher-level * @see makedirs() which is higher-level
* @see mkdirat() for modern call * @see mkdirat() for modern call
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int mkdir(const char *path, unsigned mode) { int mkdir(const char *path, unsigned mode) {
return mkdirat(AT_FDCWD, path, mode); return mkdirat(AT_FDCWD, path, mode);

View file

@ -29,7 +29,6 @@
* but it works on everything else including bare metal. * but it works on everything else including bare metal.
* *
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int sys_munmap(void *p, size_t n) { int sys_munmap(void *p, size_t n) {
int rc; int rc;

View file

@ -1,51 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timespec.internal.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/timeval.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/errno.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sock/internal.h"
// nanosleep() on xnu: a bloodbath of a polyfill
// consider using clock_nanosleep(TIMER_ABSTIME)
int sys_nanosleep_xnu(const struct timespec *req, struct timespec *rem) {
#ifdef __x86_64__
int rc;
struct timeval wt, t1, t2, td;
if (rem) sys_gettimeofday_xnu(&t1, 0, 0);
wt = timespec_totimeval(*req); // rounds up
rc = sys_select(0, 0, 0, 0, &wt);
if (rem && rc == -1 && errno == EINTR) {
sys_gettimeofday_xnu(&t2, 0, 0);
td = timeval_sub(t2, t1);
if (timeval_cmp(td, wt) >= 0) {
rem->tv_sec = 0;
rem->tv_nsec = 0;
} else {
*rem = timeval_totimespec(timeval_sub(wt, td));
}
}
return rc;
#else
return _sysret(__syslib->__nanosleep(req, rem));
#endif
}

View file

@ -37,11 +37,11 @@
* @norestart * @norestart
*/ */
int nanosleep(const struct timespec *req, struct timespec *rem) { int nanosleep(const struct timespec *req, struct timespec *rem) {
int rc; errno_t err;
if (!(rc = clock_nanosleep(CLOCK_REALTIME, 0, req, rem))) { if (!(err = clock_nanosleep(CLOCK_REALTIME, 0, req, rem))) {
return 0; return 0;
} else { } else {
errno = rc; errno = err;
return -1; return -1;
} }
} }

View file

@ -16,6 +16,7 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/assert.h"
#include "libc/calls/calls.h" #include "libc/calls/calls.h"
#include "libc/calls/internal.h" #include "libc/calls/internal.h"
#include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h"
@ -35,6 +36,7 @@
#include "libc/nt/errors.h" #include "libc/nt/errors.h"
#include "libc/nt/files.h" #include "libc/nt/files.h"
#include "libc/nt/runtime.h" #include "libc/nt/runtime.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/struct/genericmapping.h" #include "libc/nt/struct/genericmapping.h"
#include "libc/nt/struct/privilegeset.h" #include "libc/nt/struct/privilegeset.h"
#include "libc/nt/struct/securitydescriptor.h" #include "libc/nt/struct/securitydescriptor.h"
@ -62,6 +64,7 @@ textwindows int ntaccesscheck(const char16_t *pathname, uint32_t flags) {
struct NtGenericMapping mapping; struct NtGenericMapping mapping;
struct NtPrivilegeSet privileges; struct NtPrivilegeSet privileges;
uint32_t secsize, granted, privsize; uint32_t secsize, granted, privsize;
struct NtByHandleFileInformation wst;
int64_t hToken, hImpersonatedToken, hFile; int64_t hToken, hImpersonatedToken, hFile;
intptr_t buffer[1024 / sizeof(intptr_t)]; intptr_t buffer[1024 / sizeof(intptr_t)];
if (flags & X_OK) flags |= R_OK; if (flags & X_OK) flags |= R_OK;
@ -100,7 +103,9 @@ textwindows int ntaccesscheck(const char16_t *pathname, uint32_t flags) {
0, kNtOpenExisting, 0, kNtOpenExisting,
kNtFileAttributeNormal | kNtFileFlagBackupSemantics, kNtFileAttributeNormal | kNtFileFlagBackupSemantics,
0)) != -1) { 0)) != -1) {
if (IsWindowsExecutable(hFile)) { unassert(GetFileInformationByHandle(hFile, &wst));
if ((wst.dwFileAttributes & kNtFileAttributeDirectory) ||
IsWindowsExecutable(hFile)) {
rc = 0; rc = 0;
} else { } else {
rc = eacces(); rc = eacces();

View file

@ -32,7 +32,6 @@
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @restartable * @restartable
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int open(const char *file, int flags, ...) { int open(const char *file, int flags, ...) {

View file

@ -168,7 +168,6 @@
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @restartable * @restartable
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int openat(int dirfd, const char *path, int flags, ...) { int openat(int dirfd, const char *path, int flags, ...) {

View file

@ -2297,7 +2297,6 @@ static privileged void AppendPledge(struct Filter *f, //
* @param ipromises is inverted integer bitmask of pledge() promises * @param ipromises is inverted integer bitmask of pledge() promises
* @return 0 on success, or negative error number on error * @return 0 on success, or negative error number on error
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
privileged int sys_pledge_linux(unsigned long ipromises, int mode) { privileged int sys_pledge_linux(unsigned long ipromises, int mode) {

View file

@ -234,7 +234,6 @@
* @raise ENOSYS if `pledge(0, 0)` was used and security is not possible * @raise ENOSYS if `pledge(0, 0)` was used and security is not possible
* @raise EINVAL if `execpromises` on Linux isn't a subset of `promises` * @raise EINVAL if `execpromises` on Linux isn't a subset of `promises`
* @raise EINVAL if `promises` allows exec and `execpromises` is null * @raise EINVAL if `promises` allows exec and `execpromises` is null
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int pledge(const char *promises, const char *execpromises) { int pledge(const char *promises, const char *execpromises) {

View file

@ -62,7 +62,6 @@
* @raise EINTR if signal was delivered * @raise EINTR if signal was delivered
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @norestart * @norestart
*/ */
int poll(struct pollfd *fds, size_t nfds, int timeout_ms) { int poll(struct pollfd *fds, size_t nfds, int timeout_ms) {

View file

@ -46,7 +46,6 @@ int sys_fadvise_netbsd(int, int, int64_t, int64_t, int) asm("sys_fadvise");
* @raise ENOTSUP if `fd` is a /zip file * @raise ENOTSUP if `fd` is a /zip file
* @raise ENOSYS on XNU and OpenBSD * @raise ENOSYS on XNU and OpenBSD
* @returnserrno * @returnserrno
* @threadsafe
*/ */
errno_t posix_fadvise(int fd, int64_t offset, int64_t len, int advice) { errno_t posix_fadvise(int fd, int64_t offset, int64_t len, int advice) {
int rc, e = errno; int rc, e = errno;

View file

@ -24,7 +24,6 @@
* *
* @return 0 on success, or errno on error * @return 0 on success, or errno on error
* @returnserrno * @returnserrno
* @threadsafe
*/ */
errno_t posix_madvise(void *addr, uint64_t len, int advice) { errno_t posix_madvise(void *addr, uint64_t len, int advice) {
int rc, e = errno; int rc, e = errno;

View file

@ -57,7 +57,6 @@
* @raise EINTR if signal was delivered * @raise EINTR if signal was delivered
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @norestart * @norestart
*/ */
int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout, int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout,

View file

@ -52,7 +52,6 @@
* @see pwrite(), write() * @see pwrite(), write()
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
ssize_t pread(int fd, void *buf, size_t size, int64_t offset) { ssize_t pread(int fd, void *buf, size_t size, int64_t offset) {

View file

@ -46,7 +46,6 @@
* @see pread(), write() * @see pread(), write()
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
ssize_t pwrite(int fd, const void *buf, size_t size, int64_t offset) { ssize_t pwrite(int fd, const void *buf, size_t size, int64_t offset) {

View file

@ -53,8 +53,6 @@
#include "libc/thread/tls.h" #include "libc/thread/tls.h"
#ifdef __x86_64__ #ifdef __x86_64__
__msabi extern typeof(CloseHandle) *const __imp_CloseHandle;
static const struct { static const struct {
int vk; int vk;
int normal_str; int normal_str;
@ -578,7 +576,7 @@ textwindows ssize_t sys_read_nt_impl(int fd, void *data, size_t size,
goto BlockingOperation; goto BlockingOperation;
} }
} }
__imp_CloseHandle(overlap.hEvent); // __imp_ to avoid log noise CloseHandle(overlap.hEvent);
if (!pwriting && seekable) { if (!pwriting && seekable) {
if (ok) f->pointer = offset + got; if (ok) f->pointer = offset + got;

View file

@ -51,7 +51,6 @@ int __ensurefds_unlocked(int fd) {
/** /**
* Grows file descriptor array memory if needed. * Grows file descriptor array memory if needed.
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int __ensurefds(int fd) { int __ensurefds(int fd) {
__fds_lock(); __fds_lock();
@ -89,7 +88,6 @@ int __reservefd_unlocked(int start) {
/** /**
* Finds open file descriptor slot. * Finds open file descriptor slot.
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int __reservefd(int start) { int __reservefd(int start) {
int fd; int fd;

View file

@ -85,6 +85,14 @@ privileged void __siginfo2cosmo(struct siginfo *si,
notpossible; notpossible;
} }
// Turn BUS_OBJERR into BUS_ADRERR for consistency with Linux.
// See test/libc/calls/sigbus_test.c
if (IsFreebsd() || IsOpenbsd()) {
if (si_signo == 10 && si_code == 3) {
si_code = 2;
}
}
*si = (struct siginfo){0}; *si = (struct siginfo){0};
si->si_signo = si_signo; si->si_signo = si_signo;
si->si_errno = si_errno; si->si_errno = si_errno;

View file

@ -6,7 +6,6 @@
COSMOPOLITAN_C_START_ COSMOPOLITAN_C_START_
extern int __vforked; extern int __vforked;
extern bool __time_critical;
extern pthread_mutex_t __fds_lock_obj; extern pthread_mutex_t __fds_lock_obj;
extern unsigned __sighandrvas[NSIG + 1]; extern unsigned __sighandrvas[NSIG + 1];
extern unsigned __sighandflags[NSIG + 1]; extern unsigned __sighandflags[NSIG + 1];

View file

@ -35,3 +35,5 @@ int statvfs(const char *path, struct statvfs *sv) {
return -1; return -1;
} }
} }
__strong_reference(statvfs, statvfs64);

View file

@ -16,6 +16,12 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/clock_gettime.internal.h" #include "libc/calls/struct/timeval.h"
#include "libc/time/time.h"
clock_gettime_f *__clock_gettime = __clock_gettime_init; /**
* Changes time, the old fashioned way.
*/
int stime(const int64_t *t) {
return settimeofday(&(struct timeval){*t}, 0);
}

View file

@ -10,18 +10,18 @@ int __sys_clock_nanosleep(int, int, const struct timespec *, struct timespec *);
int __sys_utimensat(int, const char *, const struct timespec[2], int); int __sys_utimensat(int, const char *, const struct timespec[2], int);
int __utimens(int, const char *, const struct timespec[2], int); int __utimens(int, const char *, const struct timespec[2], int);
int sys_clock_getres(int, struct timespec *); int sys_clock_getres(int, struct timespec *);
int sys_clock_settime(int, const struct timespec *);
int sys_clock_gettime(int, struct timespec *); int sys_clock_gettime(int, struct timespec *);
int sys_clock_gettime_nt(int, struct timespec *);
int sys_clock_gettime_m1(int, struct timespec *); int sys_clock_gettime_m1(int, struct timespec *);
int sys_clock_gettime_mono(struct timespec *);
int sys_clock_gettime_nt(int, struct timespec *);
int sys_clock_gettime_xnu(int, struct timespec *); int sys_clock_gettime_xnu(int, struct timespec *);
int sys_clock_nanosleep_nt(int, int, const struct timespec *, struct timespec *); int sys_clock_nanosleep_nt(int, int, const struct timespec *, struct timespec *);
int sys_clock_nanosleep_openbsd(int, int, const struct timespec *, struct timespec *); int sys_clock_nanosleep_openbsd(int, int, const struct timespec *, struct timespec *);
int sys_clock_nanosleep_xnu(int, int, const struct timespec *, struct timespec *); int sys_clock_nanosleep_xnu(int, int, const struct timespec *, struct timespec *);
int sys_clock_settime(int, const struct timespec *);
int sys_futimens(int, const struct timespec[2]); int sys_futimens(int, const struct timespec[2]);
int sys_nanosleep(const struct timespec *, struct timespec *); int sys_nanosleep(const struct timespec *, struct timespec *);
int sys_nanosleep_nt(const struct timespec *, struct timespec *); int sys_nanosleep_nt(const struct timespec *, struct timespec *);
int sys_nanosleep_xnu(const struct timespec *, struct timespec *);
int sys_sem_timedwait(int64_t, const struct timespec *); int sys_sem_timedwait(int64_t, const struct timespec *);
int sys_utimensat(int, const char *, const struct timespec[2], int); int sys_utimensat(int, const char *, const struct timespec[2], int);
int sys_utimensat_nt(int, const char *, const struct timespec[2], int); int sys_utimensat_nt(int, const char *, const struct timespec[2], int);

View file

@ -6,16 +6,11 @@
#if !(__ASSEMBLER__ + __LINKER__ + 0) #if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_ COSMOPOLITAN_C_START_
axdx_t sys_gettimeofday(struct timeval *, struct timezone *, void *);
int sys_settimeofday(const struct timeval *, const struct timezone *); int sys_settimeofday(const struct timeval *, const struct timezone *);
int sys_futimes(int, const struct timeval *); int sys_futimes(int, const struct timeval *);
int sys_lutimes(const char *, const struct timeval *); int sys_lutimes(const char *, const struct timeval *);
int sys_utimes(const char *, const struct timeval *); int sys_utimes(const char *, const struct timeval *);
axdx_t sys_gettimeofday_m1(struct timeval *, struct timezone *, void *);
axdx_t sys_gettimeofday_xnu(struct timeval *, struct timezone *, void *);
axdx_t sys_gettimeofday_nt(struct timeval *, struct timezone *, void *);
int sys_utimes_nt(const char *, const struct timeval[2]); int sys_utimes_nt(const char *, const struct timeval[2]);
axdx_t sys_gettimeofday_metal(struct timeval *, struct timezone *, void *);
const char *DescribeTimeval(char[45], int, const struct timeval *); const char *DescribeTimeval(char[45], int, const struct timeval *);
#define DescribeTimeval(rc, ts) DescribeTimeval(alloca(45), rc, ts) #define DescribeTimeval(rc, ts) DescribeTimeval(alloca(45), rc, ts)

View file

@ -35,7 +35,6 @@
// //
// @return 0 on success, or -1 w/ errno // @return 0 on success, or -1 w/ errno
// @returnstwice // @returnstwice
// @threadsafe
.ftrace1 .ftrace1
swapcontext: swapcontext:
.ftrace2 .ftrace2

View file

@ -6,6 +6,11 @@ COSMOPOLITAN_C_START_
cosmopolitan § syscalls » system five » structless support cosmopolitan § syscalls » system five » structless support
*/ */
long __syscall2(long, long, int);
int __syscall2i(long, long, int) asm("__syscall2");
long __syscall3(long, long, long, int);
int __syscall3i(long, long, long, int) asm("__syscall3");
bool __is_linux_2_6_23(void); bool __is_linux_2_6_23(void);
bool32 sys_isatty_metal(int); bool32 sys_isatty_metal(int);
int __fixupnewfd(int, int); int __fixupnewfd(int, int);

View file

@ -31,6 +31,6 @@
*/ */
struct timespec timespec_real(void) { struct timespec timespec_real(void) {
struct timespec ts; struct timespec ts;
npassert(!clock_gettime(CLOCK_REALTIME, &ts)); unassert(!clock_gettime(CLOCK_REALTIME, &ts));
return ts; return ts;
} }

View file

@ -71,7 +71,6 @@ int _mkstemp(char *, int);
* @see tmpfile() for stdio version * @see tmpfile() for stdio version
* @cancellationpoint * @cancellationpoint
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int tmpfd(void) { int tmpfd(void) {

View file

@ -61,7 +61,6 @@
* @raise ENOSYS on bare metal * @raise ENOSYS on bare metal
* @cancellationpoint * @cancellationpoint
* @see ftruncate() * @see ftruncate()
* @threadsafe
*/ */
int truncate(const char *path, int64_t length) { int truncate(const char *path, int64_t length) {
int rc; int rc;

View file

@ -17,7 +17,7 @@
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/calls.h" #include "libc/calls/calls.h"
#include "libc/calls/sysparam.h" #include "libc/stdio/sysparam.h"
#include "libc/errno.h" #include "libc/errno.h"
#include "libc/log/log.h" #include "libc/log/log.h"
#include "libc/paths.h" #include "libc/paths.h"

View file

@ -85,7 +85,6 @@ static errno_t ttyname_linux(int fd, char *buf, size_t size) {
* @return 0 on success, or error number on error * @return 0 on success, or error number on error
* @raise ERANGE if `size` was too small * @raise ERANGE if `size` was too small
* @returnserrno * @returnserrno
* @threadsafe
*/ */
errno_t ttyname_r(int fd, char *buf, size_t size) { errno_t ttyname_r(int fd, char *buf, size_t size) {
errno_t e, res; errno_t e, res;

View file

@ -43,7 +43,6 @@ static int __contextmask(const sigset_t *opt_set, sigset_t *opt_out_oldset) {
* @see swapcontext() * @see swapcontext()
* @see makecontext() * @see makecontext()
* @see getcontext() * @see getcontext()
* @threadsafe
*/ */
int setcontext(const ucontext_t *uc) { int setcontext(const ucontext_t *uc) {
if (__contextmask(&uc->uc_sigmask, 0)) return -1; if (__contextmask(&uc->uc_sigmask, 0)) return -1;

View file

@ -460,7 +460,6 @@ int sys_unveil_linux(const char *path, const char *permissions) {
* @note on Linux this function requires Linux Kernel 5.13+ and version 6.2+ * @note on Linux this function requires Linux Kernel 5.13+ and version 6.2+
* to properly support truncation operations * to properly support truncation operations
* @see [1] https://docs.kernel.org/userspace-api/landlock.html * @see [1] https://docs.kernel.org/userspace-api/landlock.html
* @threadsafe
*/ */
int unveil(const char *path, const char *permissions) { int unveil(const char *path, const char *permissions) {
int e, rc; int e, rc;

View file

@ -26,7 +26,6 @@
* @return 0 on success, or -1 w/ errno * @return 0 on success, or -1 w/ errno
* @see utimensat() for modern version * @see utimensat() for modern version
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int utime(const char *path, const struct utimbuf *times) { int utime(const char *path, const struct utimbuf *times) {
struct timeval tv[2]; struct timeval tv[2];

View file

@ -17,8 +17,9 @@
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/internal.h" #include "libc/calls/internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h"
#include "libc/fmt/conv.h" #include "libc/fmt/wintime.internal.h"
#include "libc/nt/createfile.h" #include "libc/nt/createfile.h"
#include "libc/nt/enum/accessmask.h" #include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/creationdisposition.h" #include "libc/nt/enum/creationdisposition.h"

View file

@ -51,7 +51,6 @@
* @raise ENOTSUP on XNU or RHEL5 when `dirfd` isn't `AT_FDCWD` * @raise ENOTSUP on XNU or RHEL5 when `dirfd` isn't `AT_FDCWD`
* @raise ENOSYS on bare metal * @raise ENOSYS on bare metal
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int utimensat(int dirfd, const char *path, const struct timespec ts[2], int utimensat(int dirfd, const char *path, const struct timespec ts[2],
int flags) { int flags) {

View file

@ -32,7 +32,6 @@
* @note truncates to second precision on rhel5 * @note truncates to second precision on rhel5
* @see utimensat() for modern version * @see utimensat() for modern version
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
int utimes(const char *path, const struct timeval tv[2]) { int utimes(const char *path, const struct timeval tv[2]) {
int rc; int rc;

View file

@ -27,6 +27,7 @@
#include "libc/elf/struct/verdaux.h" #include "libc/elf/struct/verdaux.h"
#include "libc/elf/struct/verdef.h" #include "libc/elf/struct/verdef.h"
#include "libc/intrin/bits.h" #include "libc/intrin/bits.h"
#include "libc/intrin/getauxval.internal.h"
#include "libc/intrin/strace.internal.h" #include "libc/intrin/strace.internal.h"
#include "libc/runtime/runtime.h" #include "libc/runtime/runtime.h"
#include "libc/str/str.h" #include "libc/str/str.h"
@ -55,7 +56,7 @@ static inline int CheckDsoSymbolVersion(Elf64_Verdef *vd, int sym,
} }
/** /**
* Returns address of vDSO function. * Returns address of "Virtual Dynamic Shared Object" function on Linux.
*/ */
void *__vdsosym(const char *version, const char *name) { void *__vdsosym(const char *version, const char *name) {
void *p; void *p;
@ -64,23 +65,19 @@ void *__vdsosym(const char *version, const char *name) {
Elf64_Phdr *phdr; Elf64_Phdr *phdr;
char *strtab = 0; char *strtab = 0;
size_t *dyn, base; size_t *dyn, base;
unsigned long *ap;
Elf64_Sym *symtab = 0; Elf64_Sym *symtab = 0;
uint16_t *versym = 0; uint16_t *versym = 0;
Elf_Symndx *hashtab = 0; Elf_Symndx *hashtab = 0;
Elf64_Verdef *verdef = 0; Elf64_Verdef *verdef = 0;
struct AuxiliaryValue av;
for (ehdr = 0, ap = __auxv; ap[0]; ap += 2) { av = __getauxval(AT_SYSINFO_EHDR);
if (ap[0] == AT_SYSINFO_EHDR) { if (!av.isfound) {
ehdr = (void *)ap[1]; KERNTRACE("__vdsosym() → missing AT_SYSINFO_EHDR");
break;
}
}
if (!ehdr || READ32LE(ehdr->e_ident) != READ32LE("\177ELF")) {
KERNTRACE("__vdsosym() → AT_SYSINFO_EHDR ELF not found");
return 0; return 0;
} }
ehdr = (void *)av.value;
phdr = (void *)((char *)ehdr + ehdr->e_phoff); phdr = (void *)((char *)ehdr + ehdr->e_phoff);
for (base = -1, dyn = 0, i = 0; i < ehdr->e_phnum; for (base = -1, dyn = 0, i = 0; i < ehdr->e_phnum;
i++, phdr = (void *)((char *)phdr + ehdr->e_phentsize)) { i++, phdr = (void *)((char *)phdr + ehdr->e_phentsize)) {

View file

@ -64,6 +64,7 @@ typedef uint32_t nlink_t; /* uint16_t on xnu */
#define fstat64 fstat #define fstat64 fstat
#define fstatat64 fstatat #define fstatat64 fstatat
#define fstatfs64 fstatfs #define fstatfs64 fstatfs
#define fstatvfs64 fstatvfs
#define getrlimit64 getrlimit #define getrlimit64 getrlimit
#define ino64_t ino_t #define ino64_t ino_t
#define lockf64 lockf #define lockf64 lockf
@ -83,6 +84,7 @@ typedef uint32_t nlink_t; /* uint16_t on xnu */
#define setrlimit64 setrlimit #define setrlimit64 setrlimit
#define stat64 stat #define stat64 stat
#define statfs64 statfs #define statfs64 statfs
#define statvfs64 statvfs
#define versionsort64 versionsort #define versionsort64 versionsort
#endif #endif

View file

@ -17,12 +17,27 @@
PERFORMANCE OF THIS SOFTWARE. PERFORMANCE OF THIS SOFTWARE.
*/ */
#include "libc/calls/internal.h" #include "libc/calls/internal.h"
#include "libc/nt/errors.h"
#include "libc/nt/events.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h" #include "libc/nt/runtime.h"
#include "libc/nt/struct/overlapped.h"
// checks if file should be considered an executable on windows
textwindows int IsWindowsExecutable(int64_t handle) { textwindows int IsWindowsExecutable(int64_t handle) {
// read first two bytes of file
// access() and stat() aren't cancelation points
char buf[2]; char buf[2];
uint32_t got; uint32_t got;
return ReadFile(handle, buf, 2, &got, 0) && got == 2 && struct NtOverlapped overlap = {.hEvent = CreateEvent(0, 0, 0, 0)};
bool ok = (ReadFile(handle, buf, 2, 0, &overlap) ||
GetLastError() == kNtErrorIoPending) &&
GetOverlappedResult(handle, &overlap, &got, true);
CloseHandle(overlap.hEvent);
// it's an executable if it starts with `MZ` or `#!`
return ok && got == 2 && //
((buf[0] == 'M' && buf[1] == 'Z') || // ((buf[0] == 'M' && buf[1] == 'Z') || //
(buf[0] == '#' && buf[1] == '!')); (buf[0] == '#' && buf[1] == '!'));
} }

View file

@ -47,8 +47,6 @@
#include "libc/thread/thread.h" #include "libc/thread/thread.h"
#include "libc/thread/tls.h" #include "libc/thread/tls.h"
__msabi extern typeof(CloseHandle) *const __imp_CloseHandle;
static bool IsMouseModeCommand(int x) { static bool IsMouseModeCommand(int x) {
return x == 1000 || // SET_VT200_MOUSE return x == 1000 || // SET_VT200_MOUSE
x == 1002 || // SET_BTN_EVENT_MOUSE x == 1002 || // SET_BTN_EVENT_MOUSE
@ -202,7 +200,7 @@ static textwindows ssize_t sys_write_nt_impl(int fd, void *data, size_t size,
goto BlockingOperation; goto BlockingOperation;
} }
} }
__imp_CloseHandle(overlap.hEvent); // __imp_ to avoid log noise CloseHandle(overlap.hEvent);
if (seekable && !pwriting) { if (seekable && !pwriting) {
if (ok) f->pointer = offset + sent; if (ok) f->pointer = offset + sent;

View file

@ -21,7 +21,6 @@
/** /**
* Frees addresses returned by getaddrinfo(). * Frees addresses returned by getaddrinfo().
* @threadsafe
*/ */
void freeaddrinfo(struct addrinfo *ai) { void freeaddrinfo(struct addrinfo *ai) {
struct addrinfo *next; struct addrinfo *next;

View file

@ -41,7 +41,6 @@
* @param res receives a pointer that must be freed with freeaddrinfo(), * @param res receives a pointer that must be freed with freeaddrinfo(),
* and won't be modified if non-zero is returned * and won't be modified if non-zero is returned
* @return 0 on success or EAI_xxx value * @return 0 on success or EAI_xxx value
* @threadsafe
*/ */
int getaddrinfo(const char *name, const char *service, int getaddrinfo(const char *name, const char *service,
const struct addrinfo *hints, struct addrinfo **res) { const struct addrinfo *hints, struct addrinfo **res) {

View file

@ -51,7 +51,6 @@ static const char *GetHostsTxtPath(char *path, size_t size) {
* Returns hosts.txt map. * Returns hosts.txt map.
* *
* @note yoinking realloc() ensures there's no size limits * @note yoinking realloc() ensures there's no size limits
* @threadsafe
*/ */
const struct HostsTxt *GetHostsTxt(void) { const struct HostsTxt *GetHostsTxt(void) {
FILE *f; FILE *f;

View file

@ -37,7 +37,6 @@ static struct ResolvConfInitialStaticMemory {
/** /**
* Returns singleton with DNS server address. * Returns singleton with DNS server address.
* @threadsafe
*/ */
const struct ResolvConf *GetResolvConf(void) { const struct ResolvConf *GetResolvConf(void) {
int rc; int rc;

View file

@ -50,7 +50,6 @@
* @return -1 on error, or positive port number * @return -1 on error, or positive port number
* @note aliases are read from file for comparison, but not returned. * @note aliases are read from file for comparison, but not returned.
* @see LookupServicesByPort * @see LookupServicesByPort
* @threadsafe
*/ */
int LookupServicesByName(const char *servname, char *servproto, int LookupServicesByName(const char *servname, char *servproto,
size_t servprotolen, char *buf, size_t bufsize, size_t servprotolen, char *buf, size_t bufsize,

View file

@ -1,16 +1,5 @@
#ifndef COSMOPOLITAN_LIBC_FMT_CONV_H_ #ifndef COSMOPOLITAN_LIBC_FMT_CONV_H_
#define COSMOPOLITAN_LIBC_FMT_CONV_H_ #define COSMOPOLITAN_LIBC_FMT_CONV_H_
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/nt/struct/filetime.h"
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § conversion
*/
#define MODERNITYSECONDS 11644473600ull
#define HECTONANOSECONDS 10000000ull
#if !(__ASSEMBLER__ + __LINKER__ + 0) #if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_ COSMOPOLITAN_C_START_
@ -48,52 +37,10 @@ float wcstof(const wchar_t *, wchar_t **);
double wcstod(const wchar_t *, wchar_t **); double wcstod(const wchar_t *, wchar_t **);
long double wcstold(const wchar_t *, wchar_t **); long double wcstold(const wchar_t *, wchar_t **);
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § conversion » time
*/
int64_t DosDateTimeToUnix(unsigned, unsigned) libcesque nosideeffect;
struct timeval WindowsTimeToTimeVal(int64_t)
libcesque nosideeffect;
struct timespec WindowsTimeToTimeSpec(int64_t)
libcesque nosideeffect;
int64_t TimeSpecToWindowsTime(struct timespec) libcesque nosideeffect;
int64_t TimeValToWindowsTime(struct timeval) libcesque nosideeffect;
struct timeval WindowsDurationToTimeVal(int64_t)
libcesque nosideeffect;
struct timespec WindowsDurationToTimeSpec(int64_t)
libcesque nosideeffect;
#define MakeFileTime(x) \
({ \
int64_t __x = x; \
(struct NtFileTime){(uint32_t)__x, (uint32_t)(__x >> 32)}; \
})
#define ReadFileTime(t) \
({ \
struct NtFileTime __t = t; \
uint64_t x = __t.dwHighDateTime; \
(int64_t)(x << 32 | __t.dwLowDateTime); \
})
#define FileTimeToTimeSpec(x) WindowsTimeToTimeSpec(ReadFileTime(x))
#define FileTimeToTimeVal(x) WindowsTimeToTimeVal(ReadFileTime(x))
#define TimeSpecToFileTime(x) MakeFileTime(TimeSpecToWindowsTime(x))
#define TimeValToFileTime(x) MakeFileTime(TimeValToWindowsTime(x))
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § conversion » manipulation
*/
#ifdef _COSMO_SOURCE #ifdef _COSMO_SOURCE
char *stripext(char *); char *stripext(char *);
char *stripexts(char *); char *stripexts(char *);
#endif #endif /* _COSMO_SOURCE */
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § conversion » computation
*/
typedef struct { typedef struct {
int quot; int quot;
@ -120,10 +67,6 @@ ldiv_t ldiv(long, long) pureconst;
lldiv_t lldiv(long long, long long) pureconst; lldiv_t lldiv(long long, long long) pureconst;
imaxdiv_t imaxdiv(intmax_t, intmax_t) pureconst; imaxdiv_t imaxdiv(intmax_t, intmax_t) pureconst;
/*───────────────────────────────────────────────────────────────────────────│─╗
cosmopolitan § conversion » optimizations
*/
#if __STDC_VERSION__ + 0 >= 199901L #if __STDC_VERSION__ + 0 >= 199901L
#define div(num, den) ((div_t){(num) / (den), (num) % (den)}) #define div(num, den) ((div_t){(num) / (den), (num) % (den)})
#define ldiv(num, den) ((ldiv_t){(num) / (den), (num) % (den)}) #define ldiv(num, den) ((ldiv_t){(num) / (den), (num) % (den)})

View file

@ -0,0 +1,41 @@
#ifndef COSMOPOLITAN_LIBC_FMT_WINTIME_H_
#define COSMOPOLITAN_LIBC_FMT_WINTIME_H_
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/nt/struct/filetime.h"
#define MODERNITYSECONDS 11644473600ull
#define HECTONANOSECONDS 10000000ull
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int64_t DosDateTimeToUnix(uint32_t, uint32_t) pureconst;
int64_t TimeSpecToWindowsTime(struct timespec) pureconst;
int64_t TimeValToWindowsTime(struct timeval) pureconst;
struct timespec WindowsDurationToTimeSpec(int64_t) pureconst;
struct timespec WindowsTimeToTimeSpec(int64_t) pureconst;
struct timeval WindowsDurationToTimeVal(int64_t) pureconst;
struct timeval WindowsTimeToTimeVal(int64_t) pureconst;
#define MakeFileTime(x) \
({ \
int64_t __x = x; \
(struct NtFileTime){(uint32_t)__x, (uint32_t)(__x >> 32)}; \
})
#define ReadFileTime(t) \
({ \
struct NtFileTime __t = t; \
uint64_t x = __t.dwHighDateTime; \
(int64_t)(x << 32 | __t.dwLowDateTime); \
})
#define FileTimeToTimeSpec(x) WindowsTimeToTimeSpec(ReadFileTime(x))
#define FileTimeToTimeVal(x) WindowsTimeToTimeVal(ReadFileTime(x))
#define TimeSpecToFileTime(x) MakeFileTime(TimeSpecToWindowsTime(x))
#define TimeValToFileTime(x) MakeFileTime(TimeValToWindowsTime(x))
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_FMT_WINTIME_H_ */

View file

@ -1,68 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 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/intrin/kprintf.h"
#include "libc/intrin/weaken.h"
#include "libc/log/backtrace.internal.h"
#include "libc/runtime/symbols.internal.h"
static _Thread_local bool noreentry;
/**
* Shows backtrace if crash reporting facilities are linked.
*/
void _bt(const char *fmt, ...) {
int e;
va_list va;
if (!noreentry) {
noreentry = true;
} else {
return;
}
if (fmt) {
va_start(va, fmt);
kvprintf(fmt, va);
va_end(va);
}
if (_weaken(ShowBacktrace) && _weaken(GetSymbolTable)) {
e = errno;
_weaken(ShowBacktrace)(2, __builtin_frame_address(0));
errno = e;
} else {
kprintf("_bt() can't show backtrace because you need:\n"
"\t__static_yoink(\"ShowBacktrace\");\n"
"to be linked.\n");
if (_weaken(PrintBacktraceUsingSymbols) && _weaken(GetSymbolTable)) {
e = errno;
_weaken(PrintBacktraceUsingSymbols)(2, __builtin_frame_address(0),
_weaken(GetSymbolTable)());
errno = e;
} else {
kprintf("_bt() can't show backtrace because you need:\n"
"\t__static_yoink(\"PrintBacktraceUsingSymbols\");\n"
"\t__static_yoink(\"GetSymbolTable\");\n"
"to be linked.\n");
}
}
noreentry = false;
}

View file

@ -1,37 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 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/syscall_support-nt.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/log/log.h"
#include "libc/nt/runtime.h"
#include "libc/nt/thunk/msabi.h"
__msabi extern typeof(CloseHandle) *const __imp_CloseHandle;
/**
* Closes an open object handle.
* @note this wrapper takes care of ABI, STRACE(), and __winerr()
*/
textwindows bool32 CloseHandle(int64_t hObject) {
bool32 ok;
ok = __imp_CloseHandle(hObject);
if (!ok) __winerr();
NTTRACE("CloseHandle(%ld) → %hhhd% m", hObject, ok);
return ok;
}

View file

@ -51,9 +51,7 @@ void end_cancellation_point(int state) {
} }
void report_cancellation_point(void) { void report_cancellation_point(void) {
BLOCK_CANCELLATIONS; __builtin_trap();
_bt("error: need BEGIN/END_CANCELLATION_POINT\n");
ALLOW_CANCELLATIONS;
} }
#endif /* MODE_DBG */ #endif /* MODE_DBG */

View file

@ -33,7 +33,6 @@
* for passing the magic memory handle on Windows NT to CloseHandle(). * for passing the magic memory handle on Windows NT to CloseHandle().
* *
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
struct DirectMap sys_mmap(void *addr, size_t size, int prot, int flags, int fd, struct DirectMap sys_mmap(void *addr, size_t size, int prot, int flags, int fd,
int64_t off) { int64_t off) {

View file

@ -40,7 +40,6 @@
* by hosing the interrupt descriptors and triple faulting the system. * by hosing the interrupt descriptors and triple faulting the system.
* *
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
* @noreturn * @noreturn
*/ */

View file

@ -40,7 +40,6 @@ __msabi extern typeof(ExitThread) *const __imp_ExitThread;
* *
* @param rc only works on Linux and Windows * @param rc only works on Linux and Windows
* @see cthread_exit() * @see cthread_exit()
* @threadsafe
* @noreturn * @noreturn
*/ */
privileged wontreturn void _Exit1(int rc) { privileged wontreturn void _Exit1(int rc) {

View file

@ -28,6 +28,8 @@
#include "libc/sysv/consts/rlim.h" #include "libc/sysv/consts/rlim.h"
#include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/rlimit.h"
// Hack for guessing boundaries of _start()'s stack
//
// Every UNIX system in our support vector creates arg blocks like: // Every UNIX system in our support vector creates arg blocks like:
// //
// <HIGHEST-STACK-ADDRESS> // <HIGHEST-STACK-ADDRESS>
@ -53,6 +55,11 @@
// up to the microprocessor page size (this computes the top addr) // up to the microprocessor page size (this computes the top addr)
// and the bottom is computed by subtracting RLIMIT_STACK rlim_cur // and the bottom is computed by subtracting RLIMIT_STACK rlim_cur
// It's simple but gets tricky if we consider environ can be empty // It's simple but gets tricky if we consider environ can be empty
//
// This code always guesses correctly on Windows because WinMain()
// is written to allocate a stack ourself. Local testing on Linux,
// XNU, FreeBSD, OpenBSD, and NetBSD says that accuracy is ±1 page
// and that error rate applies to both beginning and end addresses
static char *__get_last(char **list) { static char *__get_last(char **list) {
char *res = 0; char *res = 0;

View file

@ -38,7 +38,6 @@
* *
* @return process id (always successful) * @return process id (always successful)
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int getpid(void) { int getpid(void) {

View file

@ -34,7 +34,6 @@
* *
* @return thread id greater than zero or -1 w/ errno * @return thread id greater than zero or -1 w/ errno
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
int gettid(void) { int gettid(void) {

View file

@ -43,7 +43,6 @@ static struct {
* @note this function is not intended for cryptography * @note this function is not intended for cryptography
* @note this function passes bigcrush and practrand * @note this function passes bigcrush and practrand
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
uint64_t _rand64(void) { uint64_t _rand64(void) {

View file

@ -3,12 +3,13 @@
#include "libc/intrin/likely.h" #include "libc/intrin/likely.h"
#include "libc/runtime/runtime.h" #include "libc/runtime/runtime.h"
#define _KERNTRACE 0 /* not configurable w/ flag yet */ #define _NTTRACE 1 /* not configurable w/ flag yet */
#define _POLLTRACE 0 /* not configurable w/ flag yet */ #define _POLLTRACE 0 /* not configurable w/ flag yet */
#define _DATATRACE 1 /* not configurable w/ flag yet */ #define _DATATRACE 1 /* not configurable w/ flag yet */
#define _STDIOTRACE 0 /* not configurable w/ flag yet */
#define _LOCKTRACE 0 /* not configurable w/ flag yet */ #define _LOCKTRACE 0 /* not configurable w/ flag yet */
#define _NTTRACE 0 /* not configurable w/ flag yet */ #define _STDIOTRACE 0 /* not configurable w/ flag yet */
#define _KERNTRACE 0 /* not configurable w/ flag yet */
#define _TIMETRACE 0 /* not configurable w/ flag yet */
#define STRACE_PROLOGUE "%rSYS %6P %'18T " #define STRACE_PROLOGUE "%rSYS %6P %'18T "
@ -63,6 +64,12 @@ COSMOPOLITAN_C_START_
#define LOCKTRACE(FMT, ...) (void)0 #define LOCKTRACE(FMT, ...) (void)0
#endif #endif
#if defined(SYSDEBUG) && _TIMETRACE
#define TIMETRACE(FMT, ...) STRACE(FMT, ##__VA_ARGS__)
#else
#define TIMETRACE(FMT, ...) (void)0
#endif
void __stracef(const char *, ...); void __stracef(const char *, ...);
COSMOPOLITAN_C_END_ COSMOPOLITAN_C_END_

View file

@ -33,8 +33,9 @@ static char g_strsignal[21];
* *
* @param sig is signal number which should be in range 1 through 128 * @param sig is signal number which should be in range 1 through 128
* @return string which is valid code describing signal * @return string which is valid code describing signal
* @see strsignal_r() for better thread safety * @see strsignal_r()
* @see sigaction() * @see sigaction()
* @threadunsafe
*/ */
char *strsignal(int sig) { char *strsignal(int sig) {
return strsignal_r(sig, g_strsignal); return strsignal_r(sig, g_strsignal);

View file

@ -34,7 +34,6 @@
* @return pointer to .rodata string, or to `buf` after mutating * @return pointer to .rodata string, or to `buf` after mutating
* @see sigaction() * @see sigaction()
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
privileged char *strsignal_r(int sig, char buf[21]) { privileged char *strsignal_r(int sig, char buf[21]) {
const char *s; const char *s;

View file

@ -19,6 +19,7 @@
#include "libc/dce.h" #include "libc/dce.h"
#include "libc/intrin/getenv.internal.h" #include "libc/intrin/getenv.internal.h"
#include "libc/runtime/runtime.h" #include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h" #include "libc/sysv/errfuns.h"
/** /**
@ -27,15 +28,12 @@
* @param s is non-empty environment key which can't contain `'='` * @param s is non-empty environment key which can't contain `'='`
* @return 0 on success, or -1 w/ errno and environment is unchanged * @return 0 on success, or -1 w/ errno and environment is unchanged
* @raise EINVAL if `s` is an empty string or has a `'='` character * @raise EINVAL if `s` is an empty string or has a `'='` character
* @threadunsafe
*/ */
int unsetenv(const char *s) { int unsetenv(const char *s) {
char **p; char **p;
struct Env e; struct Env e;
const char *t; if (!s || !*s || strchr(s, '=')) return einval();
if (!s || !*s) return einval();
for (t = s; *t; ++t) {
if (*t == '=') return einval();
}
if ((p = environ)) { if ((p = environ)) {
e = __getenv(p, s); e = __getenv(p, s);
while (p[e.i]) { while (p[e.i]) {

View file

@ -4,7 +4,7 @@
#include "libc/calls/calls.h" #include "libc/calls/calls.h"
#include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/rusage.h" #include "libc/calls/struct/rusage.h"
#include "libc/calls/sysparam.h" #include "libc/stdio/sysparam.h"
#include "libc/calls/weirdtypes.h" #include "libc/calls/weirdtypes.h"
#include "libc/limits.h" #include "libc/limits.h"
#include "libc/sysv/consts/endian.h" #include "libc/sysv/consts/endian.h"

File diff suppressed because it is too large Load diff

View file

@ -38,7 +38,6 @@
* *
* @see __minicrash() for signal handlers, e.g. handling abort() * @see __minicrash() for signal handlers, e.g. handling abort()
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
relegated wontreturn void __die(void) { relegated wontreturn void __die(void) {

View file

@ -49,7 +49,6 @@
* *
* @see __die() for crashing from normal code without aborting * @see __die() for crashing from normal code without aborting
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
* @vforksafe * @vforksafe
*/ */
relegated dontinstrument void __minicrash(int sig, siginfo_t *si, void *arg) { relegated dontinstrument void __minicrash(int sig, siginfo_t *si, void *arg) {

View file

@ -81,7 +81,6 @@ static void vflogf_onfail(FILE *f) {
* time that it took to connect. This is great in forking applications. * time that it took to connect. This is great in forking applications.
* *
* @asyncsignalsafe * @asyncsignalsafe
* @threadsafe
*/ */
void(vflogf)(unsigned level, const char *file, int line, FILE *f, void(vflogf)(unsigned level, const char *file, int line, FILE *f,
const char *fmt, va_list va) { const char *fmt, va_list va) {

View file

@ -10,6 +10,14 @@
* @fileoverview Common C preprocessor, assembler, and linker macros. * @fileoverview Common C preprocessor, assembler, and linker macros.
*/ */
#ifdef MAX
#undef MAX
#endif
#ifdef MIN
#undef MIN
#endif
#define TRUE 1 #define TRUE 1
#define FALSE 0 #define FALSE 0

View file

@ -27,7 +27,6 @@
* @return memory address, or NULL w/ errno * @return memory address, or NULL w/ errno
* @throw EINVAL if !IS2POW(a) * @throw EINVAL if !IS2POW(a)
* @see pvalloc() * @see pvalloc()
* @threadsafe
*/ */
void *aligned_alloc(size_t a, size_t n) { void *aligned_alloc(size_t a, size_t n) {
if (IS2POW(a)) { if (IS2POW(a)) {

View file

@ -30,7 +30,6 @@ void *(*hook_calloc)(size_t, size_t) = dlcalloc;
* @return rax is memory address, or NULL w/ errno * @return rax is memory address, or NULL w/ errno
* @note overreliance on memalign is a sure way to fragment space * @note overreliance on memalign is a sure way to fragment space
* @see dlcalloc() * @see dlcalloc()
* @threadsafe
*/ */
void *calloc(size_t n, size_t itemsize) { void *calloc(size_t n, size_t itemsize) {
return hook_calloc(n, itemsize); return hook_calloc(n, itemsize);

Some files were not shown because too many files have changed in this diff Show more