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/calls/syscall_support-nt.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_SYSCALL_SUPPORT_NT_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_SYSCALL_SUPPORT_NT_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ bool isdirectory_nt(const char *) _Hide; bool isregularfile_nt(const char *) _Hide; bool issymlink_nt(const char *) _Hide; bool32 ntsetprivilege(int64_t, const char16_t *, uint32_t) _Hide; char16_t *CreatePipeName(char16_t *) _Hide; int __mkntpath(const char *, char16_t[hasatleast PATH_MAX]) _Hide; int __mkntpath2(const char *, char16_t[hasatleast PATH_MAX], int) _Hide; int __mkntpathat(int, const char *, int, char16_t[hasatleast PATH_MAX]) _Hide; int __sample_pids(int[hasatleast 64], int64_t[hasatleast 64], bool) _Hide; int ntaccesscheck(const char16_t *, uint32_t) paramsnonnull() _Hide; int sys_pause_nt(void) _Hide; int64_t __fix_enotdir(int64_t, char16_t *) _Hide; int64_t __fix_enotdir3(int64_t, char16_t *, char16_t *) _Hide; int64_t __winerr(void) nocallback privileged; int64_t ntreturn(uint32_t); void *GetProcAddressModule(const char *, const char *) _Hide; void WinMainForked(void) _Hide; void _check_sigalrm(void) _Hide; void _check_sigchld(void) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_SYSCALL_SUPPORT_NT_INTERNAL_H_ */
1,296
29
jart/cosmopolitan
false
cosmopolitan/libc/calls/mknod.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/dce.h" #include "libc/errno.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" /** * Creates filesystem inode. * * @param mode is octal mode, e.g. 0600; needs to be or'd with one of: * S_IFDIR: directory * S_IFIFO: named pipe * S_IFREG: regular file * S_IFSOCK: named socket * S_IFBLK: block device (root has authorization) * S_IFCHR: character device (root has authorization) * @param dev it's complicated * @return 0 on success, or -1 w/ errno * @asyncsignalsafe */ int mknod(const char *path, uint32_t mode, uint64_t dev) { int e, rc; if (IsAsan() && !__asan_is_valid_str(path)) return efault(); if (mode & S_IFREG) return creat(path, mode & ~S_IFREG); if (mode & S_IFDIR) return mkdir(path, mode & ~S_IFDIR); if (mode & S_IFIFO) return mkfifo(path, mode & ~S_IFIFO); if (!IsWindows()) { /* TODO(jart): Whys there code out there w/ S_xxx passed via dev? */ e = errno; rc = sys_mknod(path, mode, dev); if (rc == -1 && rc == ENOSYS) { errno = e; rc = sys_mknodat(AT_FDCWD, path, mode, dev); } } else { rc = enosys(); } STRACE("mknod(%#s, %#o, %#lx) → %d% m", path, mode, dev, rc); return rc; }
3,245
63
jart/cosmopolitan
false
cosmopolitan/libc/calls/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 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" /** * Opens file. * * This is equivalent to saying: * * int fd = openat(AT_FDCWD, file, flags, ...); * * @param file specifies filesystem path to open * @return file descriptor, or -1 w/ errno * @see openat() for further documentation * @cancellationpoint * @asyncsignalsafe * @restartable * @threadsafe * @vforksafe */ int open(const char *file, int flags, ...) { va_list va; unsigned mode; va_start(va, flags); mode = va_arg(va, unsigned); va_end(va); return openat(AT_FDCWD, file, flags, mode); }
2,431
46
jart/cosmopolitan
false
cosmopolitan/libc/calls/nanosleep.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/timespec.h" #include "libc/errno.h" #include "libc/sysv/consts/clock.h" /** * Sleeps for relative amount of time. * * @param req is the duration of time we should sleep * @param rem if non-null will be updated with the remainder of unslept * time when -1 w/ `EINTR` is returned otherwise `rem` is undefined * @return 0 on success, or -1 w/ errno * @raise EINVAL if `req->tv_nsec ∉ [0,1000000000)` * @raise ECANCELED if thread was cancelled in masked mode * @raise EINTR if a signal was delivered and `rem` is updated * @raise EFAULT if `req` is NULL or `req` / `rem` is a bad pointer * @raise ENOSYS on bare metal * @see clock_nanosleep() * @cancellationpoint * @norestart */ int nanosleep(const struct timespec *req, struct timespec *rem) { int rc; if (!(rc = clock_nanosleep(CLOCK_REALTIME, 0, req, rem))) { return 0; } else { errno = rc; return -1; } }
2,762
48
jart/cosmopolitan
false
cosmopolitan/libc/calls/ntcontext2linux.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/ucontext.h" #include "libc/log/libfatal.internal.h" #include "libc/nt/struct/context.h" #include "libc/str/str.h" #ifdef __x86_64__ // TODO(jart): uc_sigmask support privileged void _ntcontext2linux(ucontext_t *ctx, const struct NtContext *cr) { if (!cr) return; ctx->uc_mcontext.eflags = cr->EFlags; ctx->uc_mcontext.rax = cr->Rax; ctx->uc_mcontext.rbx = cr->Rbx; ctx->uc_mcontext.rcx = cr->Rcx; ctx->uc_mcontext.rdx = cr->Rdx; ctx->uc_mcontext.rdi = cr->Rdi; ctx->uc_mcontext.rsi = cr->Rsi; ctx->uc_mcontext.rbp = cr->Rbp; ctx->uc_mcontext.rsp = cr->Rsp; ctx->uc_mcontext.rip = cr->Rip; ctx->uc_mcontext.r8 = cr->R8; ctx->uc_mcontext.r9 = cr->R9; ctx->uc_mcontext.r10 = cr->R10; ctx->uc_mcontext.r11 = cr->R11; ctx->uc_mcontext.r12 = cr->R12; ctx->uc_mcontext.r13 = cr->R13; ctx->uc_mcontext.r14 = cr->R14; ctx->uc_mcontext.r15 = cr->R15; ctx->uc_mcontext.cs = cr->SegCs; ctx->uc_mcontext.gs = cr->SegGs; ctx->uc_mcontext.fs = cr->SegFs; ctx->uc_mcontext.fpregs = &ctx->__fpustate; __repmovsb(&ctx->__fpustate, &cr->FltSave, sizeof(ctx->__fpustate)); } privileged void _ntlinux2context(struct NtContext *cr, const ucontext_t *ctx) { if (!cr) return; cr->EFlags = ctx->uc_mcontext.eflags; cr->Rax = ctx->uc_mcontext.rax; cr->Rbx = ctx->uc_mcontext.rbx; cr->Rcx = ctx->uc_mcontext.rcx; cr->Rdx = ctx->uc_mcontext.rdx; cr->Rdi = ctx->uc_mcontext.rdi; cr->Rsi = ctx->uc_mcontext.rsi; cr->Rbp = ctx->uc_mcontext.rbp; cr->Rsp = ctx->uc_mcontext.rsp; cr->Rip = ctx->uc_mcontext.rip; cr->R8 = ctx->uc_mcontext.r8; cr->R9 = ctx->uc_mcontext.r9; cr->R10 = ctx->uc_mcontext.r10; cr->R11 = ctx->uc_mcontext.r11; cr->R12 = ctx->uc_mcontext.r12; cr->R13 = ctx->uc_mcontext.r13; cr->R14 = ctx->uc_mcontext.r14; cr->R15 = ctx->uc_mcontext.r15; cr->SegCs = ctx->uc_mcontext.cs; cr->SegGs = ctx->uc_mcontext.gs; cr->SegFs = ctx->uc_mcontext.fs; __repmovsb(&cr->FltSave, &ctx->__fpustate, sizeof(ctx->__fpustate)); } #endif /* __x86_64__ */
3,880
82
jart/cosmopolitan
false
cosmopolitan/libc/calls/chdir-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/syscall_support-nt.internal.h" #include "libc/errno.h" #include "libc/macros.internal.h" #include "libc/nt/errors.h" #include "libc/nt/files.h" #include "libc/nt/process.h" #include "libc/nt/runtime.h" #include "libc/nt/synchronization.h" #include "libc/sysv/errfuns.h" textwindows int sys_chdir_nt_impl(char16_t path[hasatleast PATH_MAX], uint32_t len) { uint32_t n; int e, ms, err; char16_t var[4]; if (len && path[len - 1] != u'\\') { if (len + 2 > PATH_MAX) return enametoolong(); path[len + 0] = u'\\'; path[len + 1] = u'\0'; } /* * chdir() seems flaky on windows 7 * in a similar way to rmdir() sigh */ for (err = errno, ms = 1;; ms *= 2) { if (SetCurrentDirectory(path)) { /* * Now we need to set a magic environment variable. */ if ((n = GetCurrentDirectory(PATH_MAX, path))) { if (n < PATH_MAX) { if (!((path[0] == '/' && path[1] == '/') || (path[0] == '\\' && path[1] == '\\'))) { var[0] = '='; var[1] = path[0]; var[2] = ':'; var[3] = 0; if (!SetEnvironmentVariable(var, path)) { return __winerr(); } } return 0; } else { return enametoolong(); } } else { return __winerr(); } } else { e = GetLastError(); if (ms <= 512 && (e == kNtErrorFileNotFound || e == kNtErrorAccessDenied)) { Sleep(ms); errno = err; continue; } else { break; } } } return __fix_enotdir(-1, path); } textwindows int sys_chdir_nt(const char *path) { int len; char16_t path16[PATH_MAX]; if ((len = __mkntpath(path, path16)) == -1) return -1; if (!len) return enoent(); return sys_chdir_nt_impl(path16, len); }
3,726
91
jart/cosmopolitan
false
cosmopolitan/libc/calls/ipc.h
#ifndef COSMOPOLITAN_LIBC_CALLS_IPC_H_ #define COSMOPOLITAN_LIBC_CALLS_IPC_H_ #define IPC_PRIVATE 0 #define IPC_RMID 0 #define IPC_SET 1 #define IPC_STAT 2 #define IPC_INFO 3 #define IPC_CREAT 01000 #define IPC_EXCL 02000 #define IPC_NOWAIT 04000 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int ftok(const char *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_IPC_H_ */
470
21
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcflow.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/internal.h" #include "libc/calls/struct/termios.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/termios.h" #include "libc/dce.h" #include "libc/fmt/itoa.h" #include "libc/intrin/strace.internal.h" #include "libc/mem/alloca.h" #include "libc/nt/comms.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/errfuns.h" #define kNtPurgeTxabort 1 #define kNtPurgeRxabort 2 static const char *DescribeFlow(char buf[12], int action) { if (action == TCOOFF) return "TCOOFF"; if (action == TCOON) return "TCOON"; if (action == TCIOFF) return "TCIOFF"; if (action == TCION) return "TCION"; FormatInt32(buf, action); return buf; } static int sys_tcflow_bsd(int fd, int action) { int rc; uint8_t c; struct termios t; if (action == TCOOFF) return sys_ioctl(fd, TIOCSTOP, 0); if (action == TCOON) return sys_ioctl(fd, TIOCSTART, 0); if (action != TCIOFF && action != TCION) return einval(); if (sys_ioctl(fd, TCGETS, &t) == -1) return -1; c = t.c_cc[action == TCIOFF ? VSTOP : VSTART]; if (c == 255) return 0; // code is disabled if (sys_write(fd, &c, 1) == -1) return -1; return 0; } static dontinline textwindows int sys_tcflow_nt(int fd, int action) { bool32 ok; int64_t h; if (!__isfdopen(fd)) return ebadf(); h = g_fds.p[fd].handle; if (action == TCOOFF) { ok = PurgeComm(h, kNtPurgeTxabort); } else if (action == TCIOFF) { ok = PurgeComm(h, kNtPurgeRxabort); } else if (action == TCOON || action == TCION) { ok = ClearCommBreak(h); } else { return einval(); } return ok ? 0 : __winerr(); } /** * Changes flow of teletypewriter data. * * @param fd is file descriptor of tty * @param action may be one of: * - `TCOOFF` to suspend output * - `TCOON` to resume output * - `TCIOFF` to transmit a `STOP` character * - `TCION` to transmit a `START` character * @return 0 on success, or -1 w/ errno * @raise EINVAL if `action` is invalid * @raise ENOSYS on Windows and Bare Metal * @raise EBADF if `fd` isn't an open file descriptor * @raise ENOTTY if `fd` is open but not a teletypewriter * @raise EIO if process group of writer is orphoned, calling thread is * not blocking `SIGTTOU`, and process isn't ignoring `SIGTTOU` * @asyncsignalsafe */ int tcflow(int fd, int action) { int rc; if (IsMetal()) { rc = enosys(); } else if (IsBsd()) { rc = sys_ioctl(fd, TCXONC, action); } else if (!IsWindows()) { rc = sys_ioctl(fd, TCXONC, action); } else { rc = sys_tcflow_nt(fd, action); } STRACE("tcflow(%d, %s) → %d% m", fd, DescribeFlow(alloca(12), action), rc); return rc; }
4,540
107
jart/cosmopolitan
false
cosmopolitan/libc/calls/munmap-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/intrin/directmap.internal.h" #include "libc/runtime/pc.internal.h" #ifdef __x86_64__ noasan int sys_munmap_metal(void *addr, size_t size) { size_t i; uint64_t *e, paddr; struct mman *mm; uint64_t *pml4t = __get_pml4t(); mm = (struct mman *)(BANE + 0x0500); for (i = 0; i < size; i += 4096) { e = __get_virtual(mm, pml4t, (uint64_t)addr + i, false); if (e) { paddr = *e & PAGE_TA; *e &= ~(PAGE_V | PAGE_RSRV); invlpg((uint64_t)addr + i); __unref_page(mm, pml4t, paddr); } } return 0; } #endif
2,397
42
jart/cosmopolitan
false
cosmopolitan/libc/calls/timeval_sub.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" /** * Subtracts two nanosecond timestamps. */ struct timeval timeval_sub(struct timeval a, struct timeval b) { a.tv_sec -= b.tv_sec; if (a.tv_usec < b.tv_usec) { a.tv_usec += 1000000; a.tv_sec--; } a.tv_usec -= b.tv_usec; return a; }
2,130
33
jart/cosmopolitan
false
cosmopolitan/libc/calls/poll-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/internal.h" #include "libc/intrin/safemacros.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/uart.internal.h" #include "libc/runtime/pc.internal.h" #include "libc/sock/internal.h" #include "libc/sock/struct/pollfd.h" #include "libc/sysv/consts/poll.h" #ifdef __x86_64__ int sys_poll_metal(struct pollfd *fds, size_t nfds, unsigned timeout_ms) { int rc; size_t i; bool blocking; uint64_t start, timeout; if (!timeout_ms) { start = 0; timeout = 0; blocking = false; } else { start = rdtsc(); timeout = timeout_ms; timeout *= 3; /* approx. cycles to nanoseconds */ timeout *= 1000000; blocking = true; } for (rc = 0;;) { for (i = 0; i < nfds; ++i) { fds[i].revents = 0; if (fds[i].fd >= 0) { if (__isfdopen(fds[i].fd)) { switch (g_fds.p[fds[i].fd].kind) { case kFdSerial: if ((fds[i].events & POLLIN) && (inb(g_fds.p[fds[i].fd].handle + UART_LSR) & UART_TTYDA)) { fds[i].revents |= POLLIN; } if ((fds[i].events & POLLOUT) && (inb(g_fds.p[fds[i].fd].handle + UART_LSR) & UART_TTYTXR)) { fds[i].revents |= POLLOUT; } break; case kFdFile: if (fds[i].events & (POLLIN | POLLOUT)) { fds[i].revents |= fds[i].events & (POLLIN | POLLOUT); } break; default: fds[i].revents = POLLNVAL; break; } } else { fds[i].revents = POLLNVAL; } } if (fds[i].revents) ++rc; } if (rc || !blocking || unsignedsubtract(rdtsc(), start) >= timeout) { break; } else { __builtin_ia32_pause(); } } return rc; } #endif
3,689
86
jart/cosmopolitan
false
cosmopolitan/libc/calls/isptmaster.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/dce.h" #include "libc/errno.h" #include "libc/sysv/consts/termios.h" int _isptmaster(int fd) { if (IsFreebsd()) { if (!sys_ioctl(fd, TIOCPTMASTER)) { return 0; } else { if (errno != EBADF) { errno = EINVAL; } return -1; } } else { return 0; } }
2,227
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/open-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/internal.h" #include "libc/calls/ntmagicpaths.internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/nt/createfile.h" #include "libc/nt/enum/filetype.h" #include "libc/nt/files.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/o.h" static textwindows int sys_open_nt_impl(int dirfd, const char *path, uint32_t flags, int32_t mode) { char16_t path16[PATH_MAX]; uint32_t perm, share, disp, attr; if (__mkntpathat(dirfd, path, flags, path16) == -1) return -1; if (GetNtOpenFlags(flags, mode, &perm, &share, &disp, &attr) == -1) return -1; return __fix_enotdir( CreateFile(path16, perm, share, &kNtIsInheritable, disp, attr, 0), path16); } static textwindows int sys_open_nt_console(int dirfd, const struct NtMagicPaths *mp, uint32_t flags, int32_t mode, size_t fd) { if (GetFileType(g_fds.p[STDIN_FILENO].handle) == kNtFileTypeChar && GetFileType(g_fds.p[STDOUT_FILENO].handle) == kNtFileTypeChar) { g_fds.p[fd].handle = g_fds.p[STDIN_FILENO].handle; g_fds.p[fd].extra = g_fds.p[STDOUT_FILENO].handle; } else if ((g_fds.p[fd].handle = sys_open_nt_impl( dirfd, mp->conin, (flags & ~O_ACCMODE) | O_RDONLY, mode)) != -1) { g_fds.p[fd].extra = sys_open_nt_impl(dirfd, mp->conout, (flags & ~O_ACCMODE) | O_WRONLY, mode); _npassert(g_fds.p[fd].extra != -1); } else { return -1; } g_fds.p[fd].kind = kFdConsole; g_fds.p[fd].flags = flags; g_fds.p[fd].mode = mode; return fd; } static textwindows int sys_open_nt_file(int dirfd, const char *file, uint32_t flags, int32_t mode, size_t fd) { if ((g_fds.p[fd].handle = sys_open_nt_impl(dirfd, file, flags, mode)) != -1) { g_fds.p[fd].kind = kFdFile; g_fds.p[fd].flags = flags; g_fds.p[fd].mode = mode; return fd; } else { return -1; } } textwindows int sys_open_nt(int dirfd, const char *file, uint32_t flags, int32_t mode) { int fd; ssize_t rc; __fds_lock(); if ((rc = fd = __reservefd_unlocked(-1)) != -1) { if ((flags & O_ACCMODE) == O_RDWR && !strcmp(file, kNtMagicPaths.devtty)) { rc = sys_open_nt_console(dirfd, &kNtMagicPaths, flags, mode, fd); } else { rc = sys_open_nt_file(dirfd, file, flags, mode, fd); } if (rc == -1) { __releasefd(fd); } __fds_unlock(); } return rc; }
4,647
97
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigblockall.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/str/str.h" sigset_t _sigblockall(void) { sigset_t ss; memset(&ss, -1, sizeof(ss)); return _sigsetmask(ss); }
2,005
27
jart/cosmopolitan
false
cosmopolitan/libc/calls/sleep.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/struct/timespec.h" #include "libc/errno.h" #include "libc/limits.h" #include "libc/sysv/consts/clock.h" #include "libc/time/time.h" /** * Sleeps for particular number of seconds. * * @return 0 if the full time elapsed, otherwise we assume an interrupt * was delivered, in which case the errno condition is ignored, and * this function shall return the number of unslept seconds rounded * using the ceiling function, and finally `-1u` may be returned if * thread was cancelled with `PTHREAD_CANCEL_MASKED` in play * @see clock_nanosleep() * @cancellationpoint * @asyncsignalsafe * @norestart */ unsigned sleep(unsigned seconds) { errno_t rc; unsigned unslept; struct timespec tv = {seconds}; if (!(rc = clock_nanosleep(CLOCK_REALTIME, 0, &tv, &tv))) return 0; if (rc == ECANCELED) return -1u; _npassert(rc == EINTR); unslept = tv.tv_sec; if (tv.tv_nsec && unslept < UINT_MAX) { ++unslept; } return unslept; }
2,843
52
jart/cosmopolitan
false
cosmopolitan/libc/calls/clock_gettime-mono.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/x86feature.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" static struct { pthread_once_t once; struct timespec base_wall; uint64_t base_tick; } g_mono; static void sys_clock_gettime_mono_init(void) { g_mono.base_wall = timespec_real(); g_mono.base_tick = rdtsc(); } int sys_clock_gettime_mono(struct timespec *time) { uint64_t nanos; uint64_t cycles; struct timespec res; if (X86_HAVE(INVTSC)) { pthread_once(&g_mono.once, sys_clock_gettime_mono_init); cycles = rdtsc() - g_mono.base_tick; nanos = cycles / 3; *time = timespec_add(g_mono.base_wall, timespec_fromnanos(nanos)); return 0; } else { return einval(); } }
2,656
51
jart/cosmopolitan
false
cosmopolitan/libc/calls/fstatfs.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/cp.internal.h" #include "libc/calls/internal.h" #include "libc/calls/struct/statfs-meta.internal.h" #include "libc/calls/struct/statfs.internal.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/runtime/stack.h" #include "libc/sysv/errfuns.h" /** * Returns information about filesystem. * @return 0 on success, or -1 w/ errno * @cancellationpoint */ int fstatfs(int fd, struct statfs *sf) { int rc; union statfs_meta m; BEGIN_CANCELLATION_POINT; CheckLargeStackAllocation(&m, sizeof(m)); if (!IsWindows()) { if ((rc = sys_fstatfs(fd, &m)) != -1) { statfs2cosmo(sf, &m); } } else if (__isfdopen(fd)) { rc = sys_fstatfs_nt(g_fds.p[fd].handle, sf); } else { rc = ebadf(); } END_CANCELLATION_POINT; STRACE("fstatfs(%d, [%s]) → %d% m", fd, DescribeStatfs(rc, sf)); return rc; }
2,743
54
jart/cosmopolitan
false
cosmopolitan/libc/calls/fstat-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/internal.h" #include "libc/calls/struct/stat.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" int sys_fstat_metal(int fd, struct stat *st) { if (fd < 0) return einval(); if (fd < g_fds.n && g_fds.p[fd].kind == kFdSerial) { bzero(st, sizeof(*st)); st->st_dev = g_fds.p[fd].handle; st->st_rdev = g_fds.p[fd].handle; st->st_nlink = 1; st->st_mode = S_IFCHR | 0600; st->st_blksize = 1; return 0; } else { return ebadf(); } }
2,362
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/makedev.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/makedev.h" #include "libc/dce.h" uint64_t(makedev)(uint32_t x, uint32_t y) { if (IsXnu()) { return x << 24 | y; } else if (IsNetbsd()) { return ((x << 8) & 0x000fff00) | ((y << 12) & 0xfff00000) | (y & 0x000000ff); } else if (IsOpenbsd()) { return (x & 0xff) << 8 | (y & 0xff) | (y & 0xffff00) << 8; } else if (IsFreebsd()) { return (uint64_t)(x & 0xffffff00) << 32 | (x & 0x000000ff) << 8 | (y & 0x0000ff00) << 24 | (y & 0xffff00ff); } else { return (uint64_t)(x & 0xfffff000) << 32 | (x & 0x00000fff) << 8 | (y & 0xffffff00) << 12 | (y & 0x000000ff); } }
2,480
38
jart/cosmopolitan
false
cosmopolitan/libc/calls/wincrash.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_WINCRASH_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_WINCRASH_INTERNAL_H_ #include "libc/nt/struct/ntexceptionpointers.h" #include "libc/nt/struct/overlapped.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ unsigned __wincrash_nt(struct NtExceptionPointers *); struct NtOverlapped *_offset2overlap(int64_t, int64_t, struct NtOverlapped *) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_WINCRASH_INTERNAL_H_ */
556
15
jart/cosmopolitan
false
cosmopolitan/libc/calls/gettimeofday.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/state.internal.h" #include "libc/calls/struct/itimerval.internal.h" #include "libc/calls/struct/timeval.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/sysv/errfuns.h" #include "libc/thread/tls.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. * * int64_t t; * char p[30]; * struct tm tm; * struct timeval tv; * gettimeofday(&tv, 0); * t = tv.tv_sec; * gmtime_r(&t, &tm); * FormatHttpDateTime(p, &tm); * printf("%s\n", p); * * @param tv points to timeval that receives result if non-NULL * @param tz receives UTC timezone if non-NULL * @error EFAULT if `tv` or `tz` isn't valid memory * @see clock_gettime() for nanosecond precision * @see strftime() for string formatting */ int gettimeofday(struct timeval *tv, struct timezone *tz) { int rc; axdx_t ad; if (IsAsan() && ((tv && !__asan_is_valid(tv, sizeof(*tv))) || (tz && !__asan_is_valid(tz, sizeof(*tz))))) { rc = efault(); } else { rc = __gettimeofday(tv, tz, 0).ax; } #if SYSDEBUG if (__tls_enabled && !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) { STRACE("gettimeofday([%s], %p) → %d% m", DescribeTimeval(rc, tv), tz, rc); } #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 { isfast = false; res = sys_gettimeofday; } if (opt_out_isfast) { *opt_out_isfast = isfast; } 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); }
4,579
114
jart/cosmopolitan
false
cosmopolitan/libc/calls/kntsystemdirectory.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/dce.h" #include "libc/macros.internal.h" #define BYTES 64 // RII constant holding 'C:/WINDOWS/SYSTEM32' directory. // // @note guarantees trailing slash if non-empty .initbss 300,_init_kNtSystemDirectory kNtSystemDirectory: .zero BYTES .endobj kNtSystemDirectory,globl .previous .init.start 300,_init_kNtSystemDirectory #if SupportsWindows() pushpop BYTES,%rdx mov __imp_GetSystemDirectoryA(%rip),%rax call __getntsyspath #else add $BYTES,%rdi #endif .init.end 300,_init_kNtSystemDirectory
2,354
42
jart/cosmopolitan
false
cosmopolitan/libc/calls/metalfile.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_METALFILE_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_METALFILE_INTERNAL_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct MetalFile { char *base; size_t size; size_t pos; }; extern void *__ape_com_base; extern size_t __ape_com_size; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #define APE_COM_NAME "/proc/self/exe" #endif /* COSMOPOLITAN_LIBC_CALLS_METALFILE_INTERNAL_H_ */
461
21
jart/cosmopolitan
false
cosmopolitan/libc/calls/getcwd-xnu.greg.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/metastat.internal.h" #include "libc/calls/struct/stat.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" #define XNU_F_GETPATH 50 #define XNU_MAXPATHLEN 1024 static inline bool CopyString(char *d, const char *s, size_t n) { size_t i; for (i = 0; i < n; ++i) { if (!(d[i] = s[i])) { return true; } } return false; } char *sys_getcwd_xnu(char *res, size_t size) { int fd; union metastat st[2]; char buf[XNU_MAXPATHLEN], *ret = NULL; if ((fd = __sys_openat_nc(AT_FDCWD, ".", O_RDONLY | O_DIRECTORY, 0)) != -1) { if (__sys_fstat(fd, &st[0]) != -1) { if (st[0].xnu.st_dev && st[0].xnu.st_ino) { if (__sys_fcntl(fd, XNU_F_GETPATH, (uintptr_t)buf) != -1) { if (__sys_fstatat(AT_FDCWD, buf, &st[1], 0) != -1) { if (st[0].xnu.st_dev == st[1].xnu.st_dev && st[0].xnu.st_ino == st[1].xnu.st_ino) { if (CopyString(res, buf, size)) { ret = res; } else { erange(); } } else { einval(); } } } } else { einval(); } } close(fd); } return ret; }
3,194
70
jart/cosmopolitan
false
cosmopolitan/libc/calls/weirdtypes.h
#ifndef COSMOPOLITAN_LIBC_CALLS_WEIRDTYPES_H_ #define COSMOPOLITAN_LIBC_CALLS_WEIRDTYPES_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) /** * @fileoverview Types we'd prefer hadn't been invented. */ #define blkcnt_t int64_t #define cc_t uint8_t #define clock_t int64_t /* uint64_t on xnu */ #define dev_t uint64_t /* int32_t on xnu */ #define fsblkcnt_t uint64_t #define fsfilcnt_t int64_t /* uint32_t on xnu */ #define gid_t uint32_t #define id_t uint32_t /* int32_t on linux/freebsd/etc. */ #define in_addr_t uint32_t #define in_addr_t uint32_t #define in_port_t uint16_t #define ino_t uint64_t #define key_t int32_t #define loff_t int64_t #define mode_t uint32_t /* uint16_t on xnu */ #define nfds_t uint64_t #define off_t int64_t #define pid_t int32_t #define register_t int64_t #define sa_family_t uint16_t /* bsd:uint8_t */ #define socklen_t uint32_t #define speed_t uint32_t #define suseconds_t int64_t /* int32_t on xnu */ #define useconds_t uint64_t /* uint32_t on xnu */ #define syscall_arg_t int64_t /* uint64_t on xnu */ #define tcflag_t uint32_t #define time_t int64_t #define timer_t void* #define uid_t uint32_t #define rlim_t uint64_t /* int64_t on bsd */ #define clockid_t int32_t #ifdef __x86_64__ #define blksize_t int64_t /* int32_t on xnu */ #define nlink_t uint64_t #elif defined(__aarch64__) #define blksize_t int32_t #define nlink_t uint32_t /* uint16_t on xnu */ #endif #define TIME_T_MAX __INT64_MAX__ #define TIME_T_MIN (-TIME_T_MAX - 1) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_WEIRDTYPES_H_ */
1,744
54
jart/cosmopolitan
false
cosmopolitan/libc/calls/execve-sysv.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_EXECVE_SYSV_H_ #define COSMOPOLITAN_LIBC_CALLS_EXECVE_SYSV_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ bool IsAPEMagic(char[8]) _Hide; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_EXECVE_SYSV_H_ */
307
11
jart/cosmopolitan
false
cosmopolitan/libc/calls/termios2host.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/termios.internal.h" #include "libc/dce.h" void *__termios2host(union metatermios *mt, const struct termios *lt) { if (!IsXnu() && !IsFreebsd() && !IsOpenbsd() && !IsNetbsd()) { return (/*unconst*/ void *)lt; } else if (IsXnu()) { COPY_TERMIOS(&mt->xnu, lt); return &mt->xnu; } else { COPY_TERMIOS(&mt->bsd, lt); return &mt->bsd; } }
2,219
33
jart/cosmopolitan
false
cosmopolitan/libc/calls/unlinkat.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/stat.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/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Deletes inode and maybe the file too. * * This may be used to delete files and directories and symlinks. * * @param dirfd is normally AT_FDCWD but if it's an open directory and * path is relative, then path becomes relative to dirfd * @param path is the thing to delete * @param flags can have AT_REMOVEDIR * @return 0 on success, or -1 w/ errno */ int unlinkat(int dirfd, const char *path, int flags) { int rc; if (IsAsan() && !__asan_is_valid_str(path)) { rc = efault(); } else if (_weaken(__zipos_notat) && (rc = __zipos_notat(dirfd, path)) == -1) { STRACE("zipos unlinkat not supported yet"); } else if (!IsWindows()) { rc = sys_unlinkat(dirfd, path, flags); } else { rc = sys_unlinkat_nt(dirfd, path, flags); } // POSIX.1 says unlink(directory) raises EPERM but on Linux // it always raises EISDIR, which is so much less ambiguous if (!IsLinux() && rc == -1 && !flags && errno == EPERM) { struct stat st; if (!fstatat(dirfd, path, &st, 0) && S_ISDIR(st.st_mode)) { errno = EISDIR; } else { errno = EPERM; } } STRACE("unlinkat(%s, %#s, %#b) → %d% m", DescribeDirfd(dirfd), path, flags, rc); return rc; }
3,524
73
jart/cosmopolitan
false
cosmopolitan/libc/calls/link.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/errfuns.h" /** * Creates hard filesystem link. * * This allows two names to point to the same file data on disk. They * can only be differentiated by examining the inode number. * * @return 0 on success, or -1 w/ errno * @asyncsignalsafe */ int link(const char *existingpath, const char *newpath) { return linkat(AT_FDCWD, existingpath, AT_FDCWD, newpath, 0); }
2,314
36
jart/cosmopolitan
false
cosmopolitan/libc/calls/setitimer-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/sig.internal.h" #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/siginfo.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/intrin/strace.internal.h" #include "libc/log/check.h" #include "libc/math.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/nexgen32e/nt2sysv.h" #include "libc/nt/files.h" #include "libc/nt/runtime.h" #include "libc/nt/synchronization.h" #include "libc/nt/thread.h" #include "libc/str/str.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" #include "libc/time/time.h" #ifdef __x86_64__ /** * @fileoverview Heartbreaking polyfill for SIGALRM on NT. * * Threads are used to trigger the SIGALRM handler, which should * hopefully be an unfancy function like this: * * void OnAlarm(int sig, struct siginfo *si, struct ucontext *uc) { * g_alarmed = true; * } * * This is needed because WIN32 provides no obvious solutions for * interrupting i/o operations on the standard input handle. */ static bool __hastimer; static bool __singleshot; static long double __lastalrm; static long double __interval; textwindows void _check_sigalrm(void) { // TODO(jart): use a different timing source // TODO(jart): synchronize across intervals? long double now, elapsed; if (!__hastimer) return; now = nowl(); elapsed = now - __lastalrm; if (elapsed > __interval) { __sig_add(0, SIGALRM, SI_TIMER); if (__singleshot) { __hastimer = false; } else { __lastalrm = now; } } } textwindows int sys_setitimer_nt(int which, const struct itimerval *newvalue, struct itimerval *out_opt_oldvalue) { long double elapsed, untilnext; if (which != ITIMER_REAL || (newvalue && (!(0 <= newvalue->it_value.tv_usec && newvalue->it_value.tv_usec < 1000000) || !(0 <= newvalue->it_interval.tv_usec && newvalue->it_interval.tv_usec < 1000000)))) { return einval(); } if (out_opt_oldvalue) { if (__hastimer) { elapsed = nowl() - __lastalrm; if (elapsed > __interval) { untilnext = 0; } else { untilnext = __interval - elapsed; } out_opt_oldvalue->it_interval.tv_sec = __interval; out_opt_oldvalue->it_interval.tv_usec = 1 / 1e6 * fmodl(__interval, 1); out_opt_oldvalue->it_value.tv_sec = untilnext; out_opt_oldvalue->it_value.tv_usec = 1 / 1e6 * fmodl(untilnext, 1); } else { out_opt_oldvalue->it_interval.tv_sec = 0; out_opt_oldvalue->it_interval.tv_usec = 0; out_opt_oldvalue->it_value.tv_sec = 0; out_opt_oldvalue->it_value.tv_usec = 0; } } if (newvalue) { if (newvalue->it_interval.tv_sec || newvalue->it_interval.tv_usec || newvalue->it_value.tv_sec || newvalue->it_value.tv_usec) { __hastimer = true; if (newvalue->it_interval.tv_sec || newvalue->it_interval.tv_usec) { __singleshot = false; __interval = newvalue->it_interval.tv_sec + 1 / 1e6 * newvalue->it_interval.tv_usec; } else { __singleshot = true; __interval = newvalue->it_value.tv_sec + 1 / 1e6 * newvalue->it_value.tv_usec; } __lastalrm = nowl(); } else { __hastimer = false; } } return 0; } #endif /* __x86_64__ */
5,382
137
jart/cosmopolitan
false
cosmopolitan/libc/calls/memfd_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/calls/calls.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/intrin/strace.internal.h" /** * Creates anonymous file. * * @param name is used for the `/proc/self/fd/FD` symlink * @param flags can have `MFD_CLOEXEC`, `MFD_ALLOW_SEALING` * @raise ENOSYS if not RHEL8+ */ int memfd_create(const char *name, unsigned int flags) { int rc; rc = sys_memfd_create(name, flags); STRACE("memfd_create(%#s, %#x) → %d% m", name, flags, rc); return rc; }
2,324
36
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigenter-netbsd.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 "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-meta.internal.h" #include "libc/calls/struct/siginfo-netbsd.internal.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/ucontext-netbsd.internal.h" #include "libc/calls/ucontext.h" #include "libc/log/libfatal.internal.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #ifdef __x86_64__ privileged void __sigenter_netbsd(int sig, struct siginfo_netbsd *si, struct ucontext_netbsd *ctx) { int rva, flags; ucontext_t uc; struct siginfo si2; rva = __sighandrvas[sig & (NSIG - 1)]; if (rva >= kSigactionMinRva) { flags = __sighandflags[sig & (NSIG - 1)]; if (~flags & SA_SIGINFO) { ((sigaction_f)(__executable_start + rva))(sig, 0, 0); } else { __repstosb(&uc, 0, sizeof(uc)); __siginfo2cosmo(&si2, (void *)si); uc.uc_mcontext.fpregs = &uc.__fpustate; uc.uc_stack.ss_sp = ctx->uc_stack.ss_sp; uc.uc_stack.ss_size = ctx->uc_stack.ss_size; uc.uc_stack.ss_flags = ctx->uc_stack.ss_flags; __repmovsb(&uc.uc_sigmask, &ctx->uc_sigmask, MIN(sizeof(uc.uc_sigmask), sizeof(ctx->uc_sigmask))); uc.uc_mcontext.rdi = ctx->uc_mcontext.rdi; uc.uc_mcontext.rsi = ctx->uc_mcontext.rsi; uc.uc_mcontext.rdx = ctx->uc_mcontext.rdx; uc.uc_mcontext.rcx = ctx->uc_mcontext.rcx; uc.uc_mcontext.r8 = ctx->uc_mcontext.r8; uc.uc_mcontext.r9 = ctx->uc_mcontext.r9; uc.uc_mcontext.rax = ctx->uc_mcontext.rax; uc.uc_mcontext.rbx = ctx->uc_mcontext.rbx; uc.uc_mcontext.rbp = ctx->uc_mcontext.rbp; uc.uc_mcontext.r10 = ctx->uc_mcontext.r10; uc.uc_mcontext.r11 = ctx->uc_mcontext.r11; uc.uc_mcontext.r12 = ctx->uc_mcontext.r12; uc.uc_mcontext.r13 = ctx->uc_mcontext.r13; uc.uc_mcontext.r14 = ctx->uc_mcontext.r14; uc.uc_mcontext.r15 = ctx->uc_mcontext.r15; uc.uc_mcontext.trapno = ctx->uc_mcontext.trapno; uc.uc_mcontext.fs = ctx->uc_mcontext.fs; uc.uc_mcontext.gs = ctx->uc_mcontext.gs; uc.uc_mcontext.err = ctx->uc_mcontext.err; uc.uc_mcontext.rip = ctx->uc_mcontext.rip; uc.uc_mcontext.rsp = ctx->uc_mcontext.rsp; *uc.uc_mcontext.fpregs = ctx->uc_mcontext.__fpregs; ((sigaction_f)(__executable_start + rva))(sig, &si2, &uc); ctx->uc_stack.ss_sp = uc.uc_stack.ss_sp; ctx->uc_stack.ss_size = uc.uc_stack.ss_size; ctx->uc_stack.ss_flags = uc.uc_stack.ss_flags; __repmovsb(&ctx->uc_sigmask, &uc.uc_sigmask, MIN(sizeof(uc.uc_sigmask), sizeof(ctx->uc_sigmask))); ctx->uc_mcontext.rdi = uc.uc_mcontext.rdi; ctx->uc_mcontext.rsi = uc.uc_mcontext.rsi; ctx->uc_mcontext.rdx = uc.uc_mcontext.rdx; ctx->uc_mcontext.rcx = uc.uc_mcontext.rcx; ctx->uc_mcontext.r8 = uc.uc_mcontext.r8; ctx->uc_mcontext.r9 = uc.uc_mcontext.r9; ctx->uc_mcontext.rax = uc.uc_mcontext.rax; ctx->uc_mcontext.rbx = uc.uc_mcontext.rbx; ctx->uc_mcontext.rbp = uc.uc_mcontext.rbp; ctx->uc_mcontext.r10 = uc.uc_mcontext.r10; ctx->uc_mcontext.r11 = uc.uc_mcontext.r11; ctx->uc_mcontext.r12 = uc.uc_mcontext.r12; ctx->uc_mcontext.r13 = uc.uc_mcontext.r13; ctx->uc_mcontext.r14 = uc.uc_mcontext.r14; ctx->uc_mcontext.r15 = uc.uc_mcontext.r15; ctx->uc_mcontext.trapno = uc.uc_mcontext.trapno; ctx->uc_mcontext.fs = uc.uc_mcontext.fs; ctx->uc_mcontext.gs = uc.uc_mcontext.gs; ctx->uc_mcontext.err = uc.uc_mcontext.err; ctx->uc_mcontext.rip = uc.uc_mcontext.rip; ctx->uc_mcontext.rsp = uc.uc_mcontext.rsp; ctx->uc_mcontext.__fpregs = *uc.uc_mcontext.fpregs; } } /* * When the NetBSD kernel invokes this signal handler it pushes a * trampoline on the stack which does two things: 1) it calls this * function, and 2) calls sys_sigreturn() once this returns. */ } #endif /* __x86_64__ */
6,007
116
jart/cosmopolitan
false
cosmopolitan/libc/calls/setsid.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" /** * Creates session and sets the process group id. * @return new session id, or -1 w/ errno */ int setsid(void) { int rc; rc = sys_setsid(); STRACE("setsid() → %d% m", rc); return rc; }
2,155
33
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigpending.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/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/sysv/errfuns.h" /** * Determines the blocked pending signals * * @param pending is where the bitset of pending signals is returned, * which may not be null * @return 0 on success, or -1 w/ errno * @raise EFAULT if `pending` points to invalid memory * @asyncsignalsafe */ int sigpending(sigset_t *pending) { int rc; if (!pending || (IsAsan() && !__asan_is_valid(pending, sizeof(*pending)))) { rc = efault(); } else if (IsLinux() || IsNetbsd() || IsOpenbsd() || IsFreebsd() || IsXnu()) { // 128 signals on NetBSD and FreeBSD, 64 on Linux, 32 on OpenBSD and XNU rc = sys_sigpending(pending, 8); // OpenBSD passes signal sets in words rather than pointers if (IsOpenbsd()) { pending->__bits[0] = (unsigned)rc; rc = 0; } // only modify memory on success if (!rc) { // clear unsupported bits if (IsXnu()) { pending->__bits[0] &= 0xFFFFFFFF; } if (IsLinux() || IsOpenbsd() || IsXnu()) { pending->__bits[1] = 0; } } } else if (IsWindows()) { sigemptyset(pending); __sig_pending(pending); rc = 0; } else { rc = enosys(); } STRACE("sigpending([%s]) → %d% m", DescribeSigset(rc, pending), rc); return rc; }
3,360
69
jart/cosmopolitan
false
cosmopolitan/libc/calls/isdirectory-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 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_support-nt.internal.h" #include "libc/errno.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/files.h" /** * Returns true if file exists and is a directory on Windows NT. */ bool isdirectory_nt(const char *path) { int e; uint32_t x; char16_t path16[PATH_MAX]; e = errno; if (__mkntpath(path, path16) == -1) return -1; if ((x = GetFileAttributes(path16)) != -1u) { return !!(x & kNtFileAttributeDirectory); } else { errno = e; return false; } }
2,389
41
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigsetmask.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/sig.internal.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/dce.h" #include "libc/sysv/consts/sig.h" sigset_t _sigsetmask(sigset_t neu) { sigset_t res; if (IsMetal() || IsWindows()) { __sig_mask(SIG_SETMASK, &neu, &res); } else { _npassert(!sys_sigprocmask(SIG_SETMASK, &neu, &res)); } return res; }
2,249
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/grantpt.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/calls/termios.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" extern const unsigned TIOCPTYGRANT; /** * Grants access to subordinate pseudoteletypewriter. * * @return 0 on success, or -1 w/ errno * @raise EBADF if fd isn't open * @raise EINVAL if fd is valid but not associated with pty * @raise EACCES if pseudoterminal couldn't be accessed */ int grantpt(int fd) { int rc; if (IsXnu()) { rc = sys_ioctl(fd, TIOCPTYGRANT); } else { rc = _isptmaster(fd); } STRACE("grantpt(%d) → %d% m", fd, rc); return rc; }
2,509
45
jart/cosmopolitan
false
cosmopolitan/libc/calls/createpipename.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/nt/process.h" static textwindows char16_t *UintToChar16Array(char16_t p[21], uint64_t x) { char t; size_t a, b, i = 0; do { p[i++] = x % 10 + '0'; x = x / 10; } while (x > 0); if (i) { for (a = 0, b = i - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } } return p + i; } textwindows char16_t *CreatePipeName(char16_t *a) { static long x; char16_t *p = a; const char *q = "\\\\?\\pipe\\cosmo\\"; while (*q) *p++ = *q++; p = UintToChar16Array(p, GetCurrentProcessId()); *p++ = '-'; p = UintToChar16Array(p, (x += 1)); *p = 0; return a; }
2,494
50
jart/cosmopolitan
false
cosmopolitan/libc/calls/fchdir-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_support-nt.internal.h" #include "libc/dce.h" #include "libc/nt/files.h" #include "libc/sysv/errfuns.h" int sys_chdir_nt_impl(char16_t[hasatleast PATH_MAX], uint32_t); textwindows int sys_fchdir_nt(int dirfd) { char16_t dir[PATH_MAX]; if (!__isfdkind(dirfd, kFdFile)) return ebadf(); return sys_chdir_nt_impl( dir, GetFinalPathNameByHandle(g_fds.p[dirfd].handle, dir, ARRAYLEN(dir), kNtFileNameNormalized | kNtVolumeNameDos)); }
2,406
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/futimens.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/internal.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/errfuns.h" /** * Changes access/modified time on open file, the modern way. * * XNU only has microsecond (1e-6) accuracy. Windows only has * hectonanosecond (1e-7) accuracy. RHEL5 (Linux c. 2007) doesn't * support this system call. * * @param fd is file descriptor of file whose timestamps will change * @param ts is {access, modified} timestamps, or null for current time * @return 0 on success, or -1 w/ errno * @raise ENOTSUP if `fd` is on the zip filesystem * @raise EINVAL if `flags` had an unrecognized value * @raise EPERM if pledge() is in play without `fattr` promise * @raise EINVAL if `ts` specifies a nanosecond value that's out of range * @raise EBADF if `fd` isn't an open file descriptor * @raise EFAULT if `ts` memory was invalid * @raise ENOSYS on RHEL5 or bare metal * @asyncsignalsafe * @threadsafe */ int futimens(int fd, const struct timespec ts[2]) { int rc; rc = __utimens(fd, 0, ts, 0); STRACE("futimens(%d, {%s, %s}) → %d% m", fd, DescribeTimespec(0, ts), DescribeTimespec(0, ts ? ts + 1 : 0), rc); return rc; }
3,095
52
jart/cosmopolitan
false
cosmopolitan/libc/calls/readv-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 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/iovec.internal.h" #include "libc/intrin/weaken.h" #include "libc/sock/internal.h" #include "libc/sock/syscall_fd.internal.h" #include "libc/sysv/errfuns.h" textwindows ssize_t sys_readv_nt(struct Fd *fd, const struct iovec *iov, int iovlen) { switch (fd->kind) { case kFdFile: case kFdConsole: return sys_read_nt(fd, iov, iovlen, -1); case kFdSocket: return _weaken(sys_recv_nt)(fd, iov, iovlen, 0); default: return ebadf(); } }
2,365
37
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigaction.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/sigaction.h" #include "ape/sections.internal.h" #include "libc/assert.h" #include "libc/calls/blocksigs.internal.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/sig.internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/sigaction.internal.h" #include "libc/calls/struct/siginfo.internal.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/bits.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/limits.h" #include "libc/log/backtrace.internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/limits.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" #undef sigaction #ifdef SYSDEBUG STATIC_YOINK("strsignal"); // for kprintf() #endif #define SA_RESTORER 0x04000000 static void sigaction_cosmo2native(union metasigaction *sa) { void *handler; uint64_t flags; void *restorer; uint32_t mask[4]; if (!sa) return; flags = sa->cosmo.sa_flags; handler = sa->cosmo.sa_handler; restorer = sa->cosmo.sa_restorer; mask[0] = sa->cosmo.sa_mask.__bits[0]; mask[1] = sa->cosmo.sa_mask.__bits[0] >> 32; mask[2] = sa->cosmo.sa_mask.__bits[1]; mask[3] = sa->cosmo.sa_mask.__bits[1] >> 32; if (IsLinux()) { sa->linux.sa_flags = flags; sa->linux.sa_handler = handler; sa->linux.sa_restorer = restorer; sa->linux.sa_mask[0] = mask[0]; sa->linux.sa_mask[1] = mask[1]; } else if (IsXnu()) { sa->xnu_in.sa_flags = flags; sa->xnu_in.sa_handler = handler; sa->xnu_in.sa_restorer = restorer; sa->xnu_in.sa_mask[0] = mask[0]; } else if (IsFreebsd()) { sa->freebsd.sa_flags = flags; sa->freebsd.sa_handler = handler; sa->freebsd.sa_mask[0] = mask[0]; sa->freebsd.sa_mask[1] = mask[1]; sa->freebsd.sa_mask[2] = mask[2]; sa->freebsd.sa_mask[3] = mask[3]; } else if (IsOpenbsd()) { sa->openbsd.sa_flags = flags; sa->openbsd.sa_handler = handler; sa->openbsd.sa_mask[0] = mask[0]; } else if (IsNetbsd()) { sa->netbsd.sa_flags = flags; sa->netbsd.sa_handler = handler; sa->netbsd.sa_mask[0] = mask[0]; sa->netbsd.sa_mask[1] = mask[1]; sa->netbsd.sa_mask[2] = mask[2]; sa->netbsd.sa_mask[3] = mask[3]; } } static void sigaction_native2cosmo(union metasigaction *sa) { void *handler; uint64_t flags; void *restorer = 0; uint32_t mask[4] = {0}; if (!sa) return; if (IsLinux()) { flags = sa->linux.sa_flags; handler = sa->linux.sa_handler; restorer = sa->linux.sa_restorer; mask[0] = sa->linux.sa_mask[0]; mask[1] = sa->linux.sa_mask[1]; } else if (IsXnu()) { flags = sa->xnu_out.sa_flags; handler = sa->xnu_out.sa_handler; mask[0] = sa->xnu_out.sa_mask[0]; } else if (IsFreebsd()) { flags = sa->freebsd.sa_flags; handler = sa->freebsd.sa_handler; mask[0] = sa->freebsd.sa_mask[0]; mask[1] = sa->freebsd.sa_mask[1]; mask[2] = sa->freebsd.sa_mask[2]; mask[3] = sa->freebsd.sa_mask[3]; } else if (IsOpenbsd()) { flags = sa->openbsd.sa_flags; handler = sa->openbsd.sa_handler; mask[0] = sa->openbsd.sa_mask[0]; } else if (IsNetbsd()) { flags = sa->netbsd.sa_flags; handler = sa->netbsd.sa_handler; mask[0] = sa->netbsd.sa_mask[0]; mask[1] = sa->netbsd.sa_mask[1]; mask[2] = sa->netbsd.sa_mask[2]; mask[3] = sa->netbsd.sa_mask[3]; } else { return; } sa->cosmo.sa_flags = flags; sa->cosmo.sa_handler = handler; sa->cosmo.sa_restorer = restorer; sa->cosmo.sa_mask.__bits[0] = mask[0] | (uint64_t)mask[1] << 32; sa->cosmo.sa_mask.__bits[1] = mask[2] | (uint64_t)mask[3] << 32; } static int __sigaction(int sig, const struct sigaction *act, struct sigaction *oldact) { _Static_assert( (sizeof(struct sigaction) >= sizeof(struct sigaction_linux) && sizeof(struct sigaction) >= sizeof(struct sigaction_xnu_in) && sizeof(struct sigaction) >= sizeof(struct sigaction_xnu_out) && sizeof(struct sigaction) >= sizeof(struct sigaction_freebsd) && sizeof(struct sigaction) >= sizeof(struct sigaction_openbsd) && sizeof(struct sigaction) >= sizeof(struct sigaction_netbsd)), "sigaction cosmo abi needs tuning"); int64_t arg4, arg5; int rc, rva, oldrva; sigaction_f sigenter; struct sigaction *ap, copy; if (IsMetal()) return enosys(); /* TODO: Signals on Metal */ if (!(1 <= sig && sig <= _NSIG)) return einval(); if (sig == SIGKILL || sig == SIGSTOP) return einval(); if (IsAsan() && ((act && !__asan_is_valid(act, sizeof(*act))) || (oldact && !__asan_is_valid(oldact, sizeof(*oldact))))) { return efault(); } if (!act) { rva = (int32_t)(intptr_t)SIG_DFL; } else if ((intptr_t)act->sa_handler < kSigactionMinRva) { rva = (int)(intptr_t)act->sa_handler; } else if ((intptr_t)act->sa_handler >= (intptr_t)&__executable_start + kSigactionMinRva && (intptr_t)act->sa_handler < (intptr_t)&__executable_start + INT_MAX) { rva = (int)((uintptr_t)act->sa_handler - (uintptr_t)&__executable_start); } else { return efault(); } if (__vforked && rva != (intptr_t)SIG_DFL && rva != (intptr_t)SIG_IGN) { return einval(); } if (!IsWindows()) { if (act) { memcpy(&copy, act, sizeof(copy)); ap = &copy; if (IsLinux()) { if (!(ap->sa_flags & SA_RESTORER)) { ap->sa_flags |= SA_RESTORER; ap->sa_restorer = &__restore_rt; } if (IsWsl1()) { sigenter = __sigenter_wsl; } else { sigenter = ap->sa_sigaction; } } else if (IsXnu()) { ap->sa_restorer = (void *)&__sigenter_xnu; sigenter = __sigenter_xnu; // mitigate Rosetta signal handling strangeness // https://github.com/jart/cosmopolitan/issues/455 ap->sa_flags |= SA_SIGINFO; } else if (IsNetbsd()) { sigenter = __sigenter_netbsd; } else if (IsFreebsd()) { sigenter = __sigenter_freebsd; } else if (IsOpenbsd()) { sigenter = __sigenter_openbsd; } else { return enosys(); } if (rva < kSigactionMinRva) { ap->sa_sigaction = (void *)(intptr_t)rva; } else { ap->sa_sigaction = sigenter; } sigaction_cosmo2native((union metasigaction *)ap); } else { ap = NULL; } if (IsXnu()) { arg4 = (int64_t)(intptr_t)oldact; /* from go code */ arg5 = 0; } else if (IsNetbsd()) { /* int __sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); */ if (ap) { arg4 = (int64_t)(intptr_t)&__restore_rt_netbsd; arg5 = 2; /* netbsd/lib/libc/arch/x86_64/sys/__sigtramp2.S */ } else { arg4 = 0; arg5 = 0; /* netbsd/lib/libc/arch/x86_64/sys/__sigtramp2.S */ } } else { arg4 = 8; /* or linux whines */ arg5 = 0; } if ((rc = sys_sigaction(sig, ap, oldact, arg4, arg5)) != -1) { sigaction_native2cosmo((union metasigaction *)oldact); } } else { if (oldact) { bzero(oldact, sizeof(*oldact)); } rc = 0; } if (rc != -1 && !__vforked) { if (oldact) { oldrva = __sighandrvas[sig]; oldact->sa_sigaction = (sigaction_f)(oldrva < kSigactionMinRva ? oldrva : (intptr_t)&__executable_start + oldrva); } if (act) { __sighandrvas[sig] = rva; __sighandflags[sig] = act->sa_flags; if (IsWindows()) { __sig_check_ignore(sig, rva); } } } return rc; } /** * Installs handler for kernel interrupt to thread, e.g.: * * void GotCtrlC(int sig, siginfo_t *si, void *ctx); * struct sigaction sa = {.sa_sigaction = GotCtrlC, * .sa_flags = SA_RESETHAND|SA_RESTART|SA_SIGINFO}; * CHECK_NE(-1, sigaction(SIGINT, &sa, NULL)); * * The following flags are supported across platforms: * * - `SA_SIGINFO`: Causes the `siginfo_t` and `ucontext_t` parameters to * be passed. `void *ctx` actually refers to `struct ucontext *`. * This not only gives you more information about the signal, but also * allows your signal handler to change the CPU registers. That's * useful for recovering from crashes. If you don't use this attribute, * then signal delivery will go a little faster. * * - `SA_RESTART`: Enables BSD signal handling semantics. Normally i/o * entrypoints check for pending signals to deliver. If one gets * delivered during an i/o call, the normal behavior is to cancel the * i/o operation and return -1 with EINTR in errno. If you use the * `SA_RESTART` flag then that behavior changes, so that any function * that's been annotated with @restartable will not return `EINTR` and * will instead resume the i/o operation. This makes coding easier but * it can be an anti-pattern if not used carefully, since poor usage * can easily result in latency issues. It also requires one to do * more work in signal handlers, so special care needs to be given to * which C library functions are @asyncsignalsafe. * * - `SA_RESETHAND`: Causes signal handler to be single-shot. This means * that, upon entry of delivery to a signal handler, it's reset to the * `SIG_DFL` handler automatically. You may use the alias `SA_ONESHOT` * for this flag, which means the same thing. * * - `SA_NODEFER`: Disables the reentrancy safety check on your signal * handler. Normally that's a good thing, since for instance if your * `SIGSEGV` signal handler happens to segfault, you're going to want * your process to just crash rather than looping endlessly. But in * some cases it's desirable to use `SA_NODEFER` instead, such as at * times when you wish to `longjmp()` out of your signal handler and * back into your program. This is only safe to do across platforms * for non-crashing signals such as `SIGCHLD` and `SIGINT`. Crash * handlers should use Xed instead to recover execution, because on * Windows a `SIGSEGV` or `SIGTRAP` crash handler might happen on a * separate stack and/or a separate thread. You may use the alias * `SA_NOMASK` for this flag, which means the same thing. * * - `SA_NOCLDWAIT`: Changes `SIGCHLD` so the zombie is gone and you * can't call `wait()` anymore; similar but may * still deliver the SIGCHLD. * * - `SA_NOCLDSTOP`: Lets you set `SIGCHLD` handler that's only notified * on exit/termination and not notified on `SIGSTOP`, `SIGTSTP`, * `SIGTTIN`, `SIGTTOU`, or `SIGCONT`. * * Here's an example of the most professional way to handle signals in * an i/o event loop. It's generally a best practice to have signal * handlers do the fewest number of things possible. The trick is to * have your signals work hand-in-glove with the EINTR errno. This * obfuscates the need for having to worry about @asyncsignalsafe. * * static volatile bool gotctrlc; * * void OnCtrlC(int sig) { * gotctrlc = true; * } * * int main() { * size_t got; * ssize_t rc; * char buf[1]; * struct sigaction oldint; * struct sigaction saint = {.sa_handler = GotCtrlC}; * if (sigaction(SIGINT, &saint, &oldint) == -1) { * perror("sigaction"); * exit(1); * } * for (;;) { * rc = read(0, buf, sizeof(buf)); * if (rc == -1) { * if (errno == EINTR) { * if (gotctrlc) { * break; * } * } else { * perror("read"); * exit(2); * } * } * if (!(got = rc)) { * break; * } * for (;;) { * rc = write(1, buf, got); * if (rc != -1) { * assert(rc == 1); * break; * } else if (errno != EINTR) { * perror("write"); * exit(3); * } * } * } * sigaction(SIGINT, &oldint, 0); * } * * Please note that you can't do the above if you use SA_RESTART. Since * the purpose of SA_RESTART is to restart i/o operations whose docs say * that they're @restartable and read() is one such function. Here's * some even better news: if you don't install any signal handlers at * all, then your i/o calls will never be interrupted! * * Here's an example of the most professional way to recover from * `SIGSEGV`, `SIGFPE`, and `SIGILL`. * * void ContinueOnCrash(void); * * void SkipOverFaultingInstruction(struct ucontext *ctx) { * struct XedDecodedInst xedd; * xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); * xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15); * ctx->uc_mcontext.rip += xedd.length; * } * * void OnCrash(int sig, struct siginfo *si, void *vctx) { * struct ucontext *ctx = vctx; * SkipOverFaultingInstruction(ctx); * ContinueOnCrash(); // reinstall here in case *rip faults * } * * void ContinueOnCrash(void) { * struct sigaction sa = {.sa_handler = OnSigSegv, * .sa_flags = SA_SIGINFO | SA_RESETHAND}; * sigaction(SIGSEGV, &sa, 0); * sigaction(SIGFPE, &sa, 0); * sigaction(SIGILL, &sa, 0); * } * * int main() { * ContinueOnCrash(); * // ... * } * * You may also edit any other CPU registers during the handler. For * example, you can use the above technique so that division by zero * becomes defined to a specific value of your choosing! * * Please note that Xed isn't needed to recover from `SIGTRAP` which can * be raised at any time by embedding `DebugBreak()` or `asm("int3")` in * your program code. Your signal handler will automatically skip over * the interrupt instruction, assuming your signal handler returns. * * The important signals supported across all platforms are: * * - `SIGINT`: When you press Ctrl-C this signal gets broadcasted to * your process session group. This is the normal way to terminate * console applications. * * - `SIGQUIT`: When you press CTRL-\ this signal gets broadcasted to * your process session group. This is the irregular way to kill an * application in cases where maybe your `SIGINT` handler is broken * although, Cosmopolitan Libc ShowCrashReports() should program it * such as to attach a debugger to the process if possible, or else * show a crash report. Also note that in New Technology you should * press CTRL+BREAK rather than CTRL+\ to get this signal. * * - `SIGHUP`: This gets sent to your non-daemon processes when you * close your terminal session. * * - `SIGTERM` is what the `kill` command sends by default. It's the * choice signal for terminating daemons. * * - `SIGUSR1` and `SIGUSR2` can be anything you want. Their default * action is to kill the process. By convention `SIGUSR1` is usually * used by daemons to reload the config file. * * - `SIGCHLD` is sent when a process terminates and it takes a certain * degree of UNIX mastery to address sanely. * * - `SIGALRM` is invoked by `setitimer()` and `alarm()`. It can be * useful for interrupting i/o operations like `connect()`. * * - `SIGTRAP`: This happens when an INT3 instruction is encountered. * * - `SIGILL` happens on illegal instructions, e.g. `UD2`. * * - `SIGABRT` happens when you call `abort()`. * * - `SIGFPE` happens when you divide ints by zero, among other things. * * - `SIGSEGV` and `SIGBUS` indicate memory access errors and they have * inconsistent semantics across platforms like FreeBSD. * * - `SIGWINCH` is sent when your terminal window is resized. * * - `SIGXCPU` and `SIGXFSZ` may be raised if you run out of resources, * which can happen if your process, or the parent process that * spawned your process, happened to call `setrlimit()`. Doing this is * a wonderful idea. * * @return 0 on success or -1 w/ errno * @see xsigaction() for a much better api * @asyncsignalsafe * @vforksafe */ int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact) { int rc; if (sig == SIGKILL || sig == SIGSTOP) { rc = einval(); } else { rc = __sigaction(sig, act, oldact); } STRACE("sigaction(%G, %s, [%s]) → %d% m", sig, DescribeSigaction(0, act), DescribeSigaction(rc, oldact), rc); return rc; }
18,886
486
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigwinch-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 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/sig.internal.h" #include "libc/calls/struct/fd.internal.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/struct/winsize.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/nt/struct/consolescreenbufferinfoex.h" #include "libc/str/str.h" #include "libc/sysv/consts/sicode.h" #include "libc/sysv/consts/sig.h" #include "libc/thread/tls.h" #ifdef __x86_64__ static struct winsize __ws; textwindows void _check_sigwinch(struct Fd *fd) { int e; siginfo_t si; struct winsize ws, old; struct NtConsoleScreenBufferInfoEx sbinfo; if (__tls_enabled && __threaded != gettid()) return; old = __ws; e = errno; if (old.ws_row != 0xffff) { if (ioctl_tiocgwinsz_nt(fd, &ws) != -1) { if (old.ws_col != ws.ws_col || old.ws_row != ws.ws_row) { __ws = ws; if (old.ws_col | old.ws_row) { __sig_add(0, SIGWINCH, SI_KERNEL); } } } else { if (!old.ws_row && !old.ws_col) { __ws.ws_row = 0xffff; } } } errno = e; } #endif /* __x86_64__ */
3,045
65
jart/cosmopolitan
false
cosmopolitan/libc/calls/timeval_tomicros.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" #include "libc/limits.h" /** * Converts timeval to scalar. * * This returns the absolute number of microseconds in a timeval. If * overflow happens, then `INT64_MAX` or `INT64_MIN` is returned. The * `errno` variable isn't changed. * * @return 64-bit integer holding microseconds since epoch */ int64_t timeval_tomicros(struct timeval x) { int64_t ns; if (!__builtin_mul_overflow(x.tv_sec, 1000000ul, &ns) && !__builtin_add_overflow(ns, x.tv_usec, &ns)) { return ns; } else if (x.tv_sec < 0) { return INT64_MIN; } else { return INT64_MAX; } }
2,455
42
jart/cosmopolitan
false
cosmopolitan/libc/calls/clock_nanosleep-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 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/internal.h" #include "libc/calls/sig.internal.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/macros.internal.h" #include "libc/nt/synchronization.h" #include "libc/sysv/consts/timer.h" #include "libc/sysv/errfuns.h" textwindows int sys_clock_nanosleep_nt(int clock, int flags, const struct timespec *req, struct timespec *rem) { struct timespec now, abs; if (flags & TIMER_ABSTIME) { abs = *req; for (;;) { if (sys_clock_gettime_nt(clock, &now)) return -1; if (timespec_cmp(now, abs) >= 0) return 0; if (_check_interrupts(false, g_fds.p)) return -1; SleepEx(MIN(__SIG_POLLING_INTERVAL_MS, timespec_tomillis(timespec_sub(abs, now))), false); } } else { if (sys_clock_gettime_nt(clock, &now)) return -1; abs = timespec_add(now, *req); for (;;) { sys_clock_gettime_nt(clock, &now); if (timespec_cmp(now, abs) >= 0) return 0; if (_check_interrupts(false, g_fds.p)) { if (rem) *rem = timespec_sub(abs, now); return -1; } SleepEx(MIN(__SIG_POLLING_INTERVAL_MS, timespec_tomillis(timespec_sub(abs, now))), false); } } }
3,179
58
jart/cosmopolitan
false
cosmopolitan/libc/calls/gethostname-bsd.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_support-sysv.internal.h" #include "libc/errno.h" #define CTL_KERN 1 int gethostname_bsd(char *name, size_t len, int kind) { int cmd[2] = {CTL_KERN, kind}; if (sys_sysctl(cmd, 2, name, &len, 0, 0) != -1) { return 0; } else { if (errno == ENOMEM) { errno = ENAMETOOLONG; } return -1; } }
2,213
36
jart/cosmopolitan
false
cosmopolitan/libc/calls/siglock.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/state.internal.h" #include "libc/str/str.h" #include "libc/thread/thread.h" void(__sig_lock)(void) { pthread_mutex_lock(&__sig_lock_obj); } void(__sig_unlock)(void) { pthread_mutex_unlock(&__sig_lock_obj); } void __sig_funlock(void) { bzero(&__sig_lock_obj, sizeof(__sig_lock_obj)); __sig_lock_obj._type = PTHREAD_MUTEX_RECURSIVE; } __attribute__((__constructor__)) static void __sig_init(void) { pthread_atfork(__sig_lock, __sig_unlock, __sig_funlock); }
2,327
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/ftruncate64.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│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ This is free and unencumbered software released into the public domain. │ │ │ │ Anyone is free to copy, modify, publish, use, compile, sell, or │ │ distribute this software, either in source code form or as a compiled │ │ binary, for any purpose, commercial or non-commercial, and by any │ │ means. │ │ │ │ In jurisdictions that recognize copyright laws, the author or authors │ │ of this software dedicate any and all copyright interest in the │ │ software to the public domain. We make this dedication for the benefit │ │ of the public at large and to the detriment of our heirs and │ │ successors. We intend this dedication to be an overt act of │ │ relinquishment in perpetuity of all present and future rights to this │ │ software under copyright law. │ │ │ │ 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 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/macros.internal.h" ftruncate64: jmp ftruncate .endfn ftruncate64,globl
2,605
32
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_get.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" #include "libc/sysv/consts/clock.h" #include "libc/time/time.h" /** * Returns high-precision timestamp, the C11 way. * * @param ts receives `CLOCK_REALTIME` timestamp * @param base must be `TIME_UTC` * @return `base` on success, or `0` on failure * @see timespec_real() */ int timespec_get(struct timespec *ts, int base) { if (base == TIME_UTC && !clock_gettime(CLOCK_REALTIME, ts)) { return base; } else { return 0; } }
2,319
38
jart/cosmopolitan
false
cosmopolitan/libc/calls/killpg.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/sysv/errfuns.h" /** * Sends signal to process group. */ int killpg(int pgrp, int sig) { if (!(0 < sig && sig < NSIG)) return einval(); if (pgrp == 1 || pgrp < 0) return esrch(); return kill(IsWindows() ? pgrp : -pgrp, sig); }
2,138
31
jart/cosmopolitan
false
cosmopolitan/libc/calls/truncate-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/syscall-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/nt/createfile.h" #include "libc/nt/enum/accessmask.h" #include "libc/nt/enum/creationdisposition.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/enum/filesharemode.h" #include "libc/nt/runtime.h" textwindows int sys_truncate_nt(const char *path, uint64_t length) { int rc; int64_t fh; uint16_t path16[PATH_MAX]; if (__mkntpath(path, path16) == -1) return -1; if ((fh = CreateFile(path16, kNtGenericWrite, kNtFileShareRead, NULL, kNtOpenExisting, kNtFileAttributeNormal, 0)) != -1) { rc = sys_ftruncate_nt(fh, length); CloseHandle(fh); } else { rc = -1; } return __fix_enotdir(rc, path16); }
2,611
42
jart/cosmopolitan
false
cosmopolitan/libc/calls/gethostname.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_support-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/strace.internal.h" #include "libc/nt/enum/computernameformat.h" #include "libc/sysv/errfuns.h" #define KERN_HOSTNAME 10 /** * Returns name of current host. * * For example, if the fully-qualified hostname is "host.domain.example" * then this SHOULD return "host" however that might not be the case; it * depends on how the host machine is configured. It's fair to say if it * has a dot, it's a FQDN, otherwise it's a node. * * The nul / mutation semantics are tricky. Here is some safe copypasta: * * char host[254]; * if (gethostname(host, sizeof(host))) { * strcpy(host, "localhost"); * } * * On Linux this is the same as `/proc/sys/kernel/hostname`. * * @param name receives output name, which is guaranteed to be complete * and have a nul-terminator if this function return zero * @param len is size of `name` consider using `DNS_NAME_MAX + 1` (254) * @raise EINVAL if `len` is negative * @raise EFAULT if `name` is an invalid address * @raise ENAMETOOLONG if the underlying system call succeeded, but the * returned hostname had a length equal to or greater than `len` in * which case this error is raised and the buffer is modified, with * as many bytes of hostname as possible excluding a nul-terminator * @return 0 on success, or -1 w/ errno */ int gethostname(char *name, size_t len) { int rc; if (len < 0) { rc = einval(); } else if (!len) { rc = 0; } else if (!name) { rc = efault(); } else if (IsLinux()) { rc = gethostname_linux(name, len); } else if (IsBsd()) { rc = gethostname_bsd(name, len, KERN_HOSTNAME); } else if (IsWindows()) { rc = gethostname_nt(name, len, kNtComputerNamePhysicalDnsHostname); } else { rc = enosys(); } STRACE("gethostname([%#.*s], %'zu) → %d% m", len, name, len, rc); return rc; }
3,835
77
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_tomillis.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" #include "libc/limits.h" /** * Reduces `ts` from 1e-9 to 1e-3 granularity w/ ceil rounding. * * This function uses ceiling rounding. For example, if `ts` is one * nanosecond, then one millisecond will be returned. Ceil rounding * is needed by many interfaces, e.g. setitimer(), because the zero * timestamp has a special meaning. * * This function also detects overflow in which case `INT64_MAX` or * `INT64_MIN` may be returned. The `errno` variable isn't changed. * * @return 64-bit scalar milliseconds since epoch */ int64_t timespec_tomillis(struct timespec ts) { int64_t ms; // reduce precision from nanos to millis if (ts.tv_nsec <= 999000000) { ts.tv_nsec = (ts.tv_nsec + 999999) / 1000000; } else { ts.tv_nsec = 0; if (ts.tv_sec < INT64_MAX) { ts.tv_sec += 1; } } // convert to scalar result if (!__builtin_mul_overflow(ts.tv_sec, 1000ul, &ms) && !__builtin_add_overflow(ms, ts.tv_nsec, &ms)) { return ms; } else if (ts.tv_sec < 0) { return INT64_MIN; } else { return INT64_MAX; } }
2,940
56
jart/cosmopolitan
false
cosmopolitan/libc/calls/fstatat-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/struct/stat.h" #include "libc/calls/struct/stat.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/nt/createfile.h" #include "libc/nt/enum/accessmask.h" #include "libc/nt/enum/creationdisposition.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/enum/filesharemode.h" #include "libc/nt/runtime.h" #include "libc/sysv/consts/at.h" textwindows int sys_fstatat_nt(int dirfd, const char *path, struct stat *st, int flags) { int rc; int64_t fh; uint16_t path16[PATH_MAX]; if (__mkntpathat(dirfd, path, 0, path16) == -1) return -1; if ((fh = CreateFile( path16, kNtFileReadAttributes, 0, 0, kNtOpenExisting, kNtFileAttributeNormal | kNtFileFlagBackupSemantics | ((flags & AT_SYMLINK_NOFOLLOW) ? kNtFileFlagOpenReparsePoint : 0), 0)) != -1) { rc = st ? sys_fstat_nt(fh, st) : 0; CloseHandle(fh); } else { rc = __winerr(); } return __fix_enotdir(rc, path16); }
2,911
49
jart/cosmopolitan
false
cosmopolitan/libc/calls/dprintf.h
#ifndef COSMOPOLITAN_LIBC_CALLS_DPRINTF_H_ #define COSMOPOLITAN_LIBC_CALLS_DPRINTF_H_ #include "libc/fmt/pflink.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int dprintf(int, const char *, ...) printfesque(2) paramsnonnull((2)); int vdprintf(int, const char *, va_list) paramsnonnull(); #if defined(__GNUC__) && !defined(__STRICT_ANSI__) #define dprintf(FD, FMT, ...) (dprintf)(FD, PFLINK(FMT), ##__VA_ARGS__) #define vdprintf(FD, FMT, VA) (vdprintf)(FD, PFLINK(FMT), VA) #endif /* GNU && !ANSI */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_DPRINTF_H_ */
634
19
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_fromnanos.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" /** * Converts timespec interval from nanoseconds. */ struct timespec timespec_fromnanos(int64_t x) { struct timespec ts; ts.tv_sec = x / 1000000000; ts.tv_nsec = x % 1000000000; return ts; }
2,079
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcdrain.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/cp.internal.h" #include "libc/calls/internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/calls/termios.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/nt/files.h" #include "libc/sysv/errfuns.h" static textwindows int sys_tcdrain_nt(int fd) { if (!__isfdopen(fd)) return ebadf(); if (_check_interrupts(false, g_fds.p)) return -1; if (!FlushFileBuffers(g_fds.p[fd].handle)) return __winerr(); return 0; } /** * Waits until all written output is transmitted. * * @param fd is file descriptor of tty * @raise EBADF if `fd` isn't an open file descriptor * @raise ENOTTY if `fd` is open but not a teletypewriter * @raise EIO if process group of writer is orphoned, calling thread is * not blocking `SIGTTOU`, and process isn't ignoring `SIGTTOU` * @raise ECANCELED if thread was cancelled in masked mode * @raise EINTR if signal was delivered * @raise ENOSYS on bare metal * @cancellationpoint * @asyncsignalsafe */ int tcdrain(int fd) { int rc; BEGIN_CANCELLATION_POINT; if (IsMetal()) { rc = enosys(); } else if (!IsWindows()) { rc = sys_ioctl_cp(fd, TCSBRK, (void *)(intptr_t)1); } else { rc = sys_tcdrain_nt(fd); } END_CANCELLATION_POINT; STRACE("tcdrain(%d) → %d% m", fd, rc); return rc; }
3,210
64
jart/cosmopolitan
false
cosmopolitan/libc/calls/wincrash_init.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/dce.h" #include "libc/macros.internal.h" .init.start 300,_init_wincrash #if !IsTiny() mov __wincrashearly(%rip),%rcx ntcall __imp_RemoveVectoredExceptionHandler #endif pushpop 1,%rcx ezlea __wincrash_nt,dx ntcall __imp_AddVectoredExceptionHandler .init.end 300,_init_wincrash,globl,hidden
2,148
31
jart/cosmopolitan
false
cosmopolitan/libc/calls/sync.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/strace.internal.h" /** * Flushes file system changes to disk by any means necessary. * @see __nosync to secretly disable */ void sync(void) { if (__nosync != 0x5453455454534146) { if (!IsWindows()) { sys_sync(); } else { sys_sync_nt(); } STRACE("sync()% m"); } else { STRACE("sync() → disabled% m"); } }
2,348
41
jart/cosmopolitan
false
cosmopolitan/libc/calls/open64.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 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/macros.internal.h" open64: jmp open .endfn open64,globl
1,909
23
jart/cosmopolitan
false
cosmopolitan/libc/calls/tcsetpgrp.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/calls/termios.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/errfuns.h" /** * Sets foreground process group id. * * @return 0 on success, or -1 w/ errno * @raise EINVAL if `pgrp` is invalid * @raise ENOSYS on Windows and Bare Metal * @raise EBADF if `fd` isn't an open file descriptor * @raise EPERM if `pgrp` didn't match process in our group * @raise ENOTTY if `fd` is isn't controlling teletypewriter * @raise EIO if process group of writer is orphoned, calling thread is * not blocking `SIGTTOU`, and process isn't ignoring `SIGTTOU` * @asyncsignalsafe */ int tcsetpgrp(int fd, int pgrp) { int rc; if (IsWindows() || IsMetal()) { rc = enosys(); } else { rc = sys_ioctl(fd, TIOCSPGRP, &pgrp); } STRACE("tcsetpgrp(%d, %d) → %d% m", fd, pgrp, rc); return rc; }
2,805
50
jart/cosmopolitan
false
cosmopolitan/libc/calls/internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_INTERNAL_H_ #include "libc/calls/struct/fd.internal.h" #include "libc/calls/struct/sigval.h" #include "libc/dce.h" #include "libc/macros.internal.h" #define kSigactionMinRva 8 /* >SIG_{ERR,DFL,IGN,...} */ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define kIoMotion ((const int8_t[3]){1, 0, 0}) _Hide extern struct Fds g_fds; _Hide extern const struct Fd kEmptyFd; int __reservefd(int) _Hide; int __reservefd_unlocked(int) _Hide; void __releasefd(int) _Hide; int __ensurefds(int) _Hide; int __ensurefds_unlocked(int) _Hide; void __printfds(void) _Hide; forceinline int64_t __getfdhandleactual(int fd) { return g_fds.p[fd].handle; } forceinline bool __isfdopen(int fd) { return 0 <= fd && fd < g_fds.n && g_fds.p[fd].kind != kFdEmpty; } forceinline bool __isfdkind(int fd, int kind) { return 0 <= fd && fd < g_fds.n && g_fds.p[fd].kind == kind; } forceinline size_t _clampio(size_t size) { if (!IsTrustworthy()) { return MIN(size, 0x7ffff000); } else { return size; } } int sys_close_nt(struct Fd *, int) _Hide; int _check_interrupts(bool, struct Fd *) _Hide; int sys_openat_metal(int, const char *, int, unsigned); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_INTERNAL_H_ */
1,355
52
jart/cosmopolitan
false
cosmopolitan/libc/calls/sigtimedwait.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/sigtimedwait.h" #include "libc/calls/asan.internal.h" #include "libc/calls/cp.internal.h" #include "libc/calls/sigtimedwait.internal.h" #include "libc/calls/struct/siginfo.internal.h" #include "libc/calls/struct/sigset.internal.h" #include "libc/calls/struct/timespec.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" /** * Waits for signal synchronously, w/ timeout. * * @param set is signals for which we'll be waiting * @param info if not null shall receive info about signal * @param timeout is relative deadline and null means wait forever * @return signal number on success, or -1 w/ errno * @raise EINTR if an asynchronous signal was delivered instead * @raise ECANCELED if thread was cancelled in masked mode * @raise EINVAL if nanoseconds parameter was out of range * @raise EAGAIN if deadline expired * @raise ENOSYS on Windows, XNU, OpenBSD, Metal * @raise EFAULT if invalid memory was supplied * @cancellationpoint */ int sigtimedwait(const sigset_t *set, siginfo_t *info, const struct timespec *timeout) { int rc; char strsig[15]; struct timespec ts; union siginfo_meta si = {0}; BEGIN_CANCELLATION_POINT; if (IsAsan() && (!__asan_is_valid(set, sizeof(*set)) || (info && !__asan_is_valid(info, sizeof(*info))) || (timeout && !__asan_is_valid_timespec(timeout)))) { rc = efault(); } else if (IsLinux() || IsFreebsd() || IsNetbsd()) { if (timeout) { // 1. Linux needs its size parameter // 2. NetBSD modifies timeout argument ts = *timeout; rc = sys_sigtimedwait(set, &si, &ts, 8); } else { rc = sys_sigtimedwait(set, &si, 0, 8); } if (rc != -1 && info) { __siginfo2cosmo(info, &si); } } else { rc = enosys(); } END_CANCELLATION_POINT; STRACE("sigtimedwait(%s, [%s], %s) → %s% m", DescribeSigset(0, set), DescribeSiginfo(rc, info), DescribeTimespec(0, timeout), strsignal_r(rc, strsig)); return rc; }
3,970
81
jart/cosmopolitan
false
cosmopolitan/libc/calls/isdirectory.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 directory. * * This function is equivalent to: * * struct stat st; * return fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && * S_ISDIR(st.st_mode); * * Except faster, with fewer dependencies, and less errno clobbering. * * @see isregularfile(), issymlink(), ischardev() */ bool isdirectory(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) { if (_weaken(__zipos_stat)(&zipname, &st.cosmo) != -1) { res = S_ISDIR(st.cosmo.st_mode); } else { res = false; } } else if (IsMetal()) { res = false; } else if (!IsWindows()) { if (__sys_fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1) { res = S_ISDIR(METASTAT(st, st_mode)); } else { res = false; } } else { res = isdirectory_nt(path); } STRACE("%s(%#s) → %hhhd% m", "isdirectory", path, res); if (!res && (errno == ENOENT || errno == ENOTDIR)) { errno = e; } return res; }
3,588
81
jart/cosmopolitan
false
cosmopolitan/libc/calls/now.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/clock_gettime.internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/x86feature.h" #include "libc/str/str.h" #include "libc/sysv/consts/clock.h" #include "libc/thread/tls.h" #include "libc/time/time.h" static clock_gettime_f *__gettime; static struct Now { uint64_t k0; long double r0, cpn; } g_now; static long double GetTimeSample(void) { uint64_t tick1, tick2; long double time1, time2; sched_yield(); time1 = dtime(CLOCK_REALTIME_PRECISE); tick1 = rdtsc(); nanosleep(&(struct timespec){0, 1000000}, NULL); time2 = dtime(CLOCK_REALTIME_PRECISE); tick2 = rdtsc(); return (time2 - time1) * 1e9 / MAX(1, tick2 - tick1); } static long double MeasureNanosPerCycle(void) { int i, n; long double avg, samp; if (__tls_enabled) __get_tls()->tib_flags |= TIB_FLAG_TIME_CRITICAL; if (IsWindows()) { n = 10; } else { n = 5; } for (avg = 1.0L, i = 1; i < n; ++i) { samp = GetTimeSample(); avg += (samp - avg) / i; } if (__tls_enabled) __get_tls()->tib_flags &= ~TIB_FLAG_TIME_CRITICAL; STRACE("MeasureNanosPerCycle cpn*1000=%d", (long)(avg * 1000)); return avg; } void RefreshTime(void) { struct Now now; now.cpn = MeasureNanosPerCycle(); now.r0 = dtime(CLOCK_REALTIME_PRECISE); now.k0 = rdtsc(); memcpy(&g_now, &now, sizeof(now)); } static long double nowl_sys(void) { return dtime(CLOCK_REALTIME_PRECISE); } static long double nowl_art(void) { uint64_t ticks = rdtsc() - g_now.k0; return g_now.r0 + (1 / 1e9L * (ticks * g_now.cpn)); } static long double nowl_vdso(void) { long double secs; struct timespec tv; _unassert(__gettime); __gettime(CLOCK_REALTIME_PRECISE, &tv); secs = tv.tv_nsec; secs *= 1 / 1e9L; secs += tv.tv_sec; return secs; } long double nowl_setup(void) { bool isfast; uint64_t ticks; __gettime = __clock_gettime_get(&isfast); if (isfast) { nowl = nowl_vdso; } else if (X86_HAVE(INVTSC)) { RefreshTime(); nowl = nowl_art; } else { nowl = nowl_sys; } return nowl(); } long double (*nowl)(void) = nowl_setup;
4,244
117
jart/cosmopolitan
false
cosmopolitan/libc/calls/offset2overlap.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/nt/struct/overlapped.h" #include "libc/str/str.h" textwindows struct NtOverlapped *_offset2overlap(int64_t handle, int64_t opt_offset, struct NtOverlapped *mem) { if (opt_offset == -1) return NULL; bzero(mem, sizeof(struct NtOverlapped)); mem->Pointer = (void *)(uintptr_t)opt_offset; return mem; }
2,257
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/setcontext.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 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/macros.internal.h" // Sets machine state. // // @see getcontext() setcontext: mov 224(%rdi),%rax test %rax,%rax je 1f movaps 160(%rax),%xmm0 movaps 176(%rax),%xmm1 movaps 192(%rax),%xmm2 movaps 208(%rax),%xmm3 movaps 224(%rax),%xmm4 movaps 240(%rax),%xmm5 movaps 256(%rax),%xmm6 movaps 272(%rax),%xmm7 movaps 288(%rax),%xmm8 movaps 304(%rax),%xmm9 movaps 320(%rax),%xmm10 movaps 336(%rax),%xmm11 movaps 352(%rax),%xmm12 movaps 368(%rax),%xmm13 movaps 384(%rax),%xmm14 movaps 400(%rax),%xmm15 1: push 176(%rdi) popf mov 40(%rdi),%r8 mov 48(%rdi),%r9 mov 56(%rdi),%r10 mov 64(%rdi),%r11 mov 72(%rdi),%r12 mov 80(%rdi),%r13 mov 88(%rdi),%r14 mov 96(%rdi),%r15 mov 112(%rdi),%rsi mov 120(%rdi),%rbp mov 128(%rdi),%rbx mov 136(%rdi),%rdx mov 144(%rdi),%rax mov 152(%rdi),%rcx mov 160(%rdi),%rsp xor %rax,%rax push 168(%rdi) mov 104(%rdi),%rdi ret .endfn setcontext,globl .end //////////////////////////////////////////////////////////////////////////////// noasan noubsan int setcontext(const ucontext_t *uc) { if (uc->uc_mcontext.fpregs) { asm volatile("movaps\t%0,%%xmm0" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[0])); asm volatile("movaps\t%0,%%xmm1" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[1])); asm volatile("movaps\t%0,%%xmm2" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[2])); asm volatile("movaps\t%0,%%xmm3" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[3])); asm volatile("movaps\t%0,%%xmm4" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[4])); asm volatile("movaps\t%0,%%xmm5" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[5])); asm volatile("movaps\t%0,%%xmm6" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[6])); asm volatile("movaps\t%0,%%xmm7" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[7])); asm volatile("movaps\t%0,%%xmm8" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[8])); asm volatile("movaps\t%0,%%xmm9" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[9])); asm volatile("movaps\t%0,%%xmm10" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[10])); asm volatile("movaps\t%0,%%xmm11" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[11])); asm volatile("movaps\t%0,%%xmm12" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[12])); asm volatile("movaps\t%0,%%xmm13" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[13])); asm volatile("movaps\t%0,%%xmm14" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[14])); asm volatile("movaps\t%0,%%xmm15" : /* no outputs */ : "m"(uc->uc_mcontext.fpregs->xmm[15])); } asm volatile("mov\t%0,%%r8" : /* no outputs */ : "m"(uc->uc_mcontext.r8)); asm volatile("mov\t%0,%%r9" : /* no outputs */ : "m"(uc->uc_mcontext.r9)); asm volatile("mov\t%0,%%r10" : /* no outputs */ : "m"(uc->uc_mcontext.r10)); asm volatile("mov\t%0,%%r11" : /* no outputs */ : "m"(uc->uc_mcontext.r11)); asm volatile("mov\t%0,%%r12" : /* no outputs */ : "m"(uc->uc_mcontext.r12)); asm volatile("mov\t%0,%%r13" : /* no outputs */ : "m"(uc->uc_mcontext.r13)); asm volatile("mov\t%0,%%r14" : /* no outputs */ : "m"(uc->uc_mcontext.r14)); asm volatile("mov\t%0,%%r15" : /* no outputs */ : "m"(uc->uc_mcontext.r15)); asm volatile("mov\t%0,%%rsi" : /* no outputs */ : "m"(uc->uc_mcontext.rsi)); asm volatile("mov\t%0,%%rbp" : /* no outputs */ : "m"(uc->uc_mcontext.rbp)); asm volatile("mov\t%0,%%rbx" : /* no outputs */ : "m"(uc->uc_mcontext.rbx)); asm volatile("mov\t%0,%%rdx" : /* no outputs */ : "m"(uc->uc_mcontext.rdx)); asm volatile("mov\t%0,%%rax" : /* no outputs */ : "m"(uc->uc_mcontext.rax)); asm volatile("mov\t%0,%%rcx" : /* no outputs */ : "m"(uc->uc_mcontext.rcx)); asm volatile("mov\t%0,%%rsp" : /* no outputs */ : "m"(uc->uc_mcontext.rsp)); asm volatile("xor\t%%rax,%%rax\n\t" "push\t%0\n\t" "mov\t%1,%%rdi\n\t" "ret" : /* no outputs */ : "m"(uc->uc_mcontext.rip), "m"(uc->uc_mcontext.rdi)); unreachable; }
5,910
111
jart/cosmopolitan
false
cosmopolitan/libc/calls/openat-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 "ape/relocations.h" #include "ape/sections.internal.h" #include "libc/assert.h" #include "libc/calls/internal.h" #include "libc/calls/metalfile.internal.h" #include "libc/intrin/directmap.internal.h" #include "libc/intrin/weaken.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/pc.internal.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/zipos/zipos.internal.h" #ifdef __x86_64__ int sys_openat_metal(int dirfd, const char *file, int flags, unsigned mode) { int fd; struct MetalFile *state; if (dirfd != AT_FDCWD || strcmp(file, APE_COM_NAME)) return enoent(); if (flags != O_RDONLY) return eacces(); if (!_weaken(__ape_com_base) || !_weaken(__ape_com_size)) return eopnotsupp(); if ((fd = __reservefd(-1)) == -1) return -1; if (!_weaken(calloc) || !_weaken(free)) { struct DirectMap dm; dm = sys_mmap_metal(NULL, ROUNDUP(sizeof(struct MetalFile), 4096), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); state = dm.addr; if (state == (void *)-1) return -1; } else { state = _weaken(calloc)(1, sizeof(struct MetalFile)); if (!state) return -1; } state->base = (char *)__ape_com_base; state->size = __ape_com_size; g_fds.p[fd].kind = kFdFile; g_fds.p[fd].flags = flags; g_fds.p[fd].mode = mode; g_fds.p[fd].handle = (intptr_t)state; return fd; } #endif /* __x86_64__ */
3,463
68
jart/cosmopolitan
false
cosmopolitan/libc/calls/metalfile.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│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ This is free and unencumbered software released into the public domain. │ │ │ │ Anyone is free to copy, modify, publish, use, compile, sell, or │ │ distribute this software, either in source code form or as a compiled │ │ binary, for any purpose, commercial or non-commercial, and by any │ │ means. │ │ │ │ In jurisdictions that recognize copyright laws, the author or authors │ │ of this software dedicate any and all copyright interest in the │ │ software to the public domain. We make this dedication for the benefit │ │ of the public at large and to the detriment of our heirs and │ │ successors. We intend this dedication to be an overt act of │ │ relinquishment in perpetuity of all present and future rights to this │ │ software under copyright law. │ │ │ │ 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 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 "ape/relocations.h" #include "ape/sections.internal.h" #include "libc/assert.h" #include "libc/calls/internal.h" #include "libc/calls/metalfile.internal.h" #include "libc/intrin/directmap.internal.h" #include "libc/intrin/weaken.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/pc.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/errfuns.h" #ifdef __x86_64__ #define MAP_ANONYMOUS_linux 0x00000020 #define MAP_FIXED_linux 0x00000010 #define MAP_SHARED_linux 0x00000001 STATIC_YOINK("_init_metalfile"); void *__ape_com_base; size_t __ape_com_size = 0; textstartup noasan void InitializeMetalFile(void) { if (IsMetal()) { /* * Copy out a pristine image of the program — before the program might * decide to modify its own .data section. * * This code is included if a symbol "file:/proc/self/exe" is defined * (see libc/calls/metalfile.internal.h & libc/calls/metalfile_init.S). * The zipos code will automatically arrange to do this. Alternatively, * user code can STATIC_YOINK this symbol. */ size_t size = ROUNDUP(_ezip - __executable_start, 4096); void *copied_base; struct DirectMap dm; dm = sys_mmap_metal(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED_linux | MAP_ANONYMOUS_linux, -1, 0); copied_base = dm.addr; _npassert(copied_base != (void *)-1); memcpy(copied_base, (void *)(BANE + IMAGE_BASE_PHYSICAL), size); __ape_com_base = copied_base; __ape_com_size = size; } } #endif /* __x86_64__ */
4,230
80
jart/cosmopolitan
false
cosmopolitan/libc/calls/siginfo2cosmo.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/siginfo-meta.internal.h" #include "libc/calls/struct/siginfo.h" #include "libc/dce.h" #include "libc/sysv/consts/sig.h" privileged void __siginfo2cosmo(struct siginfo *si, const union siginfo_meta *m) { void *si_addr; int32_t si_signo; int32_t si_errno; int32_t si_code; int32_t si_pid; int32_t si_uid; int32_t si_status; int32_t si_timerid; int32_t si_overrun; union sigval si_value; if (IsLinux()) { *si = m->linux; return; } else if (IsFreebsd()) { si_signo = m->freebsd.si_signo; si_errno = m->freebsd.si_errno; si_code = m->freebsd.si_code; si_pid = m->freebsd.si_pid; si_uid = m->freebsd.si_uid; si_status = m->freebsd.si_status; si_timerid = m->freebsd.si_timerid; si_overrun = m->freebsd.si_overrun; si_addr = m->freebsd.si_addr; si_value = m->freebsd.si_value; } else if (IsXnu()) { si_signo = m->xnu.si_signo; si_errno = m->xnu.si_errno; si_code = m->xnu.si_code; si_pid = m->xnu.si_pid; si_uid = m->xnu.si_uid; si_status = m->xnu.si_status; si_timerid = 0; si_overrun = 0; si_addr = m->xnu.si_addr; si_value = m->xnu.si_value; } else if (IsOpenbsd()) { si_signo = m->openbsd.si_signo; si_errno = m->openbsd.si_errno; si_code = m->openbsd.si_code; si_pid = m->openbsd.si_pid; si_uid = m->openbsd.si_uid; si_status = m->openbsd.si_status; si_timerid = 0; si_overrun = 0; si_addr = m->openbsd.si_addr; si_value = m->openbsd.si_value; } else if (IsNetbsd()) { si_signo = m->netbsd.si_signo; si_errno = m->netbsd.si_errno; si_code = m->netbsd.si_code; si_pid = m->netbsd.si_pid; si_uid = m->netbsd.si_uid; si_status = m->netbsd.si_status; si_timerid = 0; si_overrun = 0; si_addr = m->netbsd.si_addr; si_value = m->netbsd.si_value; } else { notpossible; } *si = (struct siginfo){0}; si->si_signo = si_signo; si->si_errno = si_errno; si->si_code = si_code; si->si_value = si_value; if (si_signo == SIGILL || // si_signo == SIGFPE || // si_signo == SIGSEGV || // si_signo == SIGBUS || // si_signo == SIGTRAP) { si->si_addr = si_addr; } else if (si_signo == SIGALRM) { si->si_timerid = si_timerid; si->si_overrun = si_overrun; } else { si->si_pid = si_pid; si->si_uid = si_uid; } }
4,258
107
jart/cosmopolitan
false
cosmopolitan/libc/calls/wait3.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/rusage.h" #include "libc/sysv/errfuns.h" /** * Waits for status to change on any child process. * * @param opt_out_wstatus optionally returns status code, and *wstatus * may be inspected using WEEXITSTATUS(), etc. * @param options can have WNOHANG, WUNTRACED, WCONTINUED, etc. * @param opt_out_rusage optionally returns accounting data * @return process id of terminated child or -1 w/ errno * @cancellationpoint * @asyncsignalsafe * @restartable */ int wait3(int *opt_out_wstatus, int options, struct rusage *opt_out_rusage) { return wait4(-1, opt_out_wstatus, options, opt_out_rusage); }
2,472
37
jart/cosmopolitan
false
cosmopolitan/libc/calls/flock-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/internal.h" #include "libc/calls/struct/fd.internal.h" #include "libc/calls/syscall-nt.internal.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/nt/enum/filelockflags.h" #include "libc/nt/files.h" #include "libc/nt/struct/byhandlefileinformation.h" #include "libc/nt/struct/overlapped.h" #include "libc/sysv/errfuns.h" #define _LOCK_SH 0 #define _LOCK_EX kNtLockfileExclusiveLock #define _LOCK_NB kNtLockfileFailImmediately #define _LOCK_UN 8 textwindows int sys_flock_nt(int fd, int op) { int64_t h; struct NtByHandleFileInformation info; if (!__isfdkind(fd, kFdFile)) return ebadf(); h = g_fds.p[fd].handle; struct NtOverlapped ov = {.hEvent = h}; if (!GetFileInformationByHandle(h, &info)) { return __winerr(); } if (op & _LOCK_UN) { if (op & ~_LOCK_UN) { return einval(); } if (UnlockFileEx(h, 0, info.nFileSizeLow, info.nFileSizeHigh, &ov)) { return 0; } else { return -1; } } if (op & ~(_LOCK_SH | _LOCK_EX | _LOCK_NB)) { return einval(); } if (LockFileEx(h, op, 0, info.nFileSizeLow, info.nFileSizeHigh, &ov)) { return 0; } else { return -1; } }
3,019
66
jart/cosmopolitan
false
cosmopolitan/libc/calls/close-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/struct/fd.internal.h" #include "libc/errno.h" #include "libc/intrin/weaken.h" #include "libc/nt/enum/filetype.h" #include "libc/nt/files.h" #include "libc/nt/runtime.h" #include "libc/sysv/consts/o.h" void sys_fcntl_nt_lock_cleanup(int) _Hide; textwindows int sys_close_nt(struct Fd *fd, int fildes) { int e; bool ok = true; if (_weaken(sys_fcntl_nt_lock_cleanup)) { _weaken(sys_fcntl_nt_lock_cleanup)(fildes); } if (fd->kind == kFdFile && ((fd->flags & O_ACCMODE) != O_RDONLY && GetFileType(fd->handle) == kNtFileTypeDisk)) { // Like Linux, closing a file on Windows doesn't guarantee it's // immediately synced to disk. But unlike Linux, this could cause // subsequent operations, e.g. unlink() to break w/ access error. e = errno; FlushFileBuffers(fd->handle); errno = e; } // if this file descriptor is wrapped in a named pipe worker thread // then we need to close our copy of the worker thread handle. it's // also required that whatever install a worker use malloc, so free if (!CloseHandle(fd->handle)) ok = false; if (fd->kind == kFdConsole && fd->extra && fd->extra != -1) { if (!CloseHandle(fd->extra)) ok = false; } return ok ? 0 : -1; }
3,101
57
jart/cosmopolitan
false
cosmopolitan/libc/calls/fadvise.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/syscall-nt.internal.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" int sys_fadvise_netbsd(int, int, int64_t, int64_t, int) asm("sys_fadvise"); /** * Drops hints to O/S about intended I/O behavior. * * It makes a huge difference. For example, when copying a large file, * it can stop the system from persisting GBs of useless memory content. * * @param len 0 means until end of file * @param advice can be MADV_SEQUENTIAL, MADV_RANDOM, etc. * @return 0 on success, or -1 w/ errno * @raise EBADF if `fd` isn't a valid file descriptor * @raise ESPIPE if `fd` refers to a pipe * @raise EINVAL if `advice` was invalid * @raise ENOSYS on XNU and OpenBSD */ int fadvise(int fd, uint64_t offset, uint64_t len, int advice) { int rc, e = errno; if (IsLinux()) { rc = sys_fadvise(fd, offset, len, advice); } else if (IsFreebsd() || IsNetbsd()) { if (IsFreebsd()) { rc = sys_fadvise(fd, offset, len, advice); } else { rc = sys_fadvise_netbsd(fd, offset, offset, len, advice); } _npassert(rc >= 0); if (rc) { errno = rc; rc = -1; } } else if (IsWindows()) { rc = sys_fadvise_nt(fd, offset, len, advice); } else { rc = enosys(); } STRACE("fadvise(%d, %'lu, %'lu, %d) → %d% m", fd, offset, len, advice, rc); return rc; }
3,357
68
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_frommillis.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" /** * Converts timespec interval from milliseconds. */ struct timespec timespec_frommillis(int64_t x) { struct timespec ts; ts.tv_sec = x / 1000; ts.tv_nsec = x % 1000 * 1000000; return ts; }
2,079
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/clock_gettime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=8 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/clock_gettime.internal.h" #include "libc/calls/state.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/dce.h" #include "libc/fmt/conv.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/strace.internal.h" #include "libc/mem/alloca.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. * * nowl l: 45𝑐 15𝑛𝑠 * 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) { int rc; if (clock == 127) { rc = einval(); // 127 is used by consts.sh to mean unsupported } else if (!ts || (IsAsan() && !__asan_is_valid_timespec(ts))) { rc = efault(); } else { rc = __clock_gettime(clock, ts); } #if SYSDEBUG if (__tls_enabled && !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) { STRACE("clock_gettime(%s, [%s]) → %d% m", DescribeClockName(clock), DescribeTimespec(rc, ts), rc); } #endif return rc; } #ifdef __aarch64__ #define CGT_VDSO __vdsosym("LINUX_2.6.39", "__kernel_clock_gettime") #else #define CGT_VDSO __vdsosym("LINUX_2.6", "__vdso_clock_gettime") #endif /** * Returns pointer to fastest clock_gettime(). */ clock_gettime_f *__clock_gettime_get(bool *opt_out_isfast) { bool isfast; clock_gettime_f *res; if (IsLinux() && (res = CGT_VDSO)) { isfast = true; } 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()) { isfast = true; res = sys_clock_gettime_nt; } else { isfast = false; res = sys_clock_gettime; } if (opt_out_isfast) { *opt_out_isfast = isfast; } return res; } _Hide int __clock_gettime_init(int clockid, struct timespec *ts) { clock_gettime_f *gettime; __clock_gettime = gettime = __clock_gettime_get(0); return gettime(clockid, ts); }
5,922
140
jart/cosmopolitan
false
cosmopolitan/libc/calls/ntmagicpaths.inc
TAB(devtty, "/dev/tty") TAB(devnull, "/dev/null") TAB(devstdin, "/dev/stdin") TAB(devstdout, "/dev/stdout") TAB(nul, "NUL") TAB(conin, "CONIN$") TAB(conout, "CONOUT$")
168
8
jart/cosmopolitan
false
cosmopolitan/libc/calls/fcntl.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/struct/flock.h" #include "libc/calls/struct/flock.internal.h" #include "libc/calls/syscall-nt.internal.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/intrin/weaken.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Does things with file descriptor, e.g. * * CHECK_NE(-1, fcntl(fd, F_SETFD, FD_CLOEXEC)); * * This function lets you duplicate file descriptors without running * into an edge case where they take over stdio handles: * * CHECK_GE((newfd = fcntl(oldfd, F_DUPFD, 3)), 3); * CHECK_GE((newfd = fcntl(oldfd, F_DUPFD_CLOEXEC, 3)), 3); * * This function implements file record locking, which lets independent * processes (and on Linux 3.15+, threads too!) lock arbitrary ranges * associated with a file. See `test/libc/calls/lock_test.c` and other * locking related tests in that folder. * * On Windows, the Cosmopolitan Libc polyfill for POSIX advisory locks * only implements enough of its nuances to support SQLite's needs. Some * possibilities, e.g. punching holes in lock, will raise `ENOTSUP`. * * @param fd is the file descriptor * @param cmd can be one of: * - `F_GETFD` gets `FD_CLOEXEC` status of `fd * - `F_SETFD` sets `FD_CLOEXEC` status of `arg` file descriptor * - `F_GETFL` returns file descriptor status flags * - `F_SETFL` sets file descriptor status flags * - `F_DUPFD` is like dup() but `arg` is a minimum result, e.g. 3 * - `F_DUPFD_CLOEXEC` ditto but sets `O_CLOEXEC` on returned fd * - `F_SETLK` for record locking where `arg` is `struct flock *` * - `F_SETLKW` ditto but waits for lock (SQLite avoids this) * - `F_GETLK` to retrieve information about a record lock * - `F_OFD_SETLK` for better non-blocking lock (Linux 3.15+ only) * - `F_OFD_SETLKW` for better blocking lock (Linux 3.15+ only) * - `F_OFD_GETLK` for better lock querying (Linux 3.15+ only) * - `F_FULLFSYNC` on MacOS for fsync() with release barrier * - `F_BARRIERFSYNC` on MacOS for fsync() with even more barriers * - `F_SETNOSIGPIPE` on MacOS and NetBSD to control `SIGPIPE` * - `F_GETNOSIGPIPE` on MacOS and NetBSD to control `SIGPIPE` * - `F_GETPATH` on MacOS and NetBSD where arg is `char[PATH_MAX]` * - `F_MAXFD` on NetBSD to get max open file descriptor * - `F_NOCACHE` on MacOS to toggle data caching * - `F_GETPIPE_SZ` on Linux to get pipe size * - `F_SETPIPE_SZ` on Linux to set pipe size * - `F_NOTIFY` raise `SIGIO` upon `fd` events in `arg` (Linux only) * - `DN_ACCESS` for file access * - `DN_MODIFY` for file modifications * - `DN_CREATE` for file creations * - `DN_DELETE` for file deletions * - `DN_RENAME` for file renames * - `DN_ATTRIB` for file attribute changes * - `DN_MULTISHOT` bitwise or for realtime signals (non-coalesced) * @param arg can be FD_CLOEXEC, etc. depending * @return 0 on success, or -1 w/ errno * @raise EBADF if `fd` isn't a valid open file descriptor * @raise EINVAL if `cmd` is unknown or unsupported by os * @raise EINVAL if `cmd` is invalid or unsupported by os * @raise EPERM if pledge() is in play w/o `stdio` or `flock` promise * @raise ENOLCK if `F_SETLKW` would have exceeded `RLIMIT_LOCKS` * @raise EPERM if `cmd` is `F_SETOWN` and we weren't authorized * @raise ESRCH if `cmd` is `F_SETOWN` and process group not found * @raise ENOTSUP on Windows if locking operation isn't supported yet * @raise EDEADLK if `cmd` was `F_SETLKW` and waiting would deadlock * @raise EMFILE if `cmd` is `F_DUPFD` or `F_DUPFD_CLOEXEC` and * `RLIMIT_NOFILE` would be exceeded * @cancellationpoint when `cmd` is `F_SETLKW` or `F_OFD_SETLKW` * @asyncsignalsafe * @restartable */ int fcntl(int fd, int cmd, ...) { int rc; va_list va; uintptr_t arg; va_start(va, cmd); arg = va_arg(va, uintptr_t); va_end(va); if (fd >= 0) { if (cmd >= 0) { if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) { rc = _weaken(__zipos_fcntl)(fd, cmd, arg); } else if (!IsWindows()) { if (cmd == F_SETLKW || cmd == F_OFD_SETLKW) { BEGIN_CANCELLATION_POINT; rc = sys_fcntl(fd, cmd, arg, __sys_fcntl_cp); END_CANCELLATION_POINT; } else { rc = sys_fcntl(fd, cmd, arg, __sys_fcntl); } } else { rc = sys_fcntl_nt(fd, cmd, arg); } } else { rc = einval(); } } else { rc = ebadf(); } #ifdef SYSDEBUG if (cmd == F_GETFD || // cmd == F_GETOWN || // cmd == F_FULLFSYNC || // cmd == F_BARRIERFSYNC || // cmd == F_MAXFD) { STRACE("fcntl(%d, %s) → %d% m", fd, DescribeFcntlCmd(cmd), rc); } else if (cmd == F_GETFL) { STRACE("fcntl(%d, %s) → %s% m", fd, DescribeFcntlCmd(cmd), DescribeOpenFlags(rc)); } else if (cmd == F_SETLK || // cmd == F_SETLKW || // cmd == F_GETLK || // ((SupportsLinux() || SupportsXnu()) && // cmd != -1 && // (cmd == F_OFD_SETLK || // cmd == F_OFD_SETLKW || // cmd == F_OFD_GETLK))) { STRACE("fcntl(%d, %s, %s) → %d% m", fd, DescribeFcntlCmd(cmd), DescribeFlock(cmd, (struct flock *)arg), rc); } else if ((SupportsNetbsd() || SupportsXnu()) && cmd != -1 && cmd == F_GETPATH) { STRACE("fcntl(%d, %s, [%s]) → %d% m", fd, DescribeFcntlCmd(cmd), !rc ? (const char *)arg : "n/a", rc); } else if (SupportsLinux() && cmd != -1 && cmd == F_NOTIFY) { STRACE("fcntl(%d, %s, %s) → %d% m", fd, DescribeFcntlCmd(cmd), DescribeDnotifyFlags(arg), rc); } else { STRACE("fcntl(%d, %s, %ld) → %#x% m", fd, DescribeFcntlCmd(cmd), arg, rc); } #endif return rc; }
8,041
167
jart/cosmopolitan
false
cosmopolitan/libc/calls/openpty.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/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/metatermios.internal.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/calls/termios.h" #include "libc/calls/termios.internal.h" #include "libc/dce.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/kprintf.h" #include "libc/log/rop.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/pty.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/errfuns.h" struct IoctlPtmGet { int m; int s; char mname[16]; char sname[16]; }; static int openpty_impl(int *mfd, int *sfd, char *name, const struct termios *tio, // const struct winsize *wsz) { int m, s, p; union metatermios mt; struct IoctlPtmGet t; RETURN_ON_ERROR((m = posix_openpt(O_RDWR | O_NOCTTY))); if (!IsOpenbsd()) { RETURN_ON_ERROR(grantpt(m)); RETURN_ON_ERROR(unlockpt(m)); RETURN_ON_ERROR(_ptsname(m, t.sname, sizeof(t.sname))); RETURN_ON_ERROR((s = sys_openat(AT_FDCWD, t.sname, O_RDWR, 0))); } else { RETURN_ON_ERROR(sys_ioctl(m, PTMGET, &t)); close(m); m = t.m; s = t.s; } *mfd = m; *sfd = s; if (name) strcpy(name, t.sname); if (tio) _npassert(!sys_ioctl(s, TCSETSF, __termios2host(&mt, tio))); if (wsz) _npassert(!sys_ioctl(s, TIOCGWINSZ, wsz)); return 0; OnError: if (m != -1) sys_close(m); return -1; } /** * Opens new pseudo teletypewriter. * * @param mfd receives controlling tty rw fd on success * @param sfd receives subordinate tty rw fd on success * @param tio may be passed to tune a century of legacy behaviors * @param wsz may be passed to set terminal display dimensions * @params flags is usually O_RDWR|O_NOCTTY * @return 0 on success, or -1 w/ errno */ int openpty(int *mfd, int *sfd, char *name, // const struct termios *tio, // const struct winsize *wsz) { int rc; if (IsWindows() || IsMetal()) { return enosys(); } if (IsAsan() && (!__asan_is_valid(mfd, sizeof(int)) || !__asan_is_valid(sfd, sizeof(int)) || (name && !__asan_is_valid(name, 16)) || (tio && !__asan_is_valid(tio, sizeof(*tio))) || (wsz && !__asan_is_valid(wsz, sizeof(*wsz))))) { return efault(); } BLOCK_CANCELLATIONS; rc = openpty(mfd, sfd, name, tio, wsz); ALLOW_CANCELLATIONS; return rc; }
4,533
106
jart/cosmopolitan
false
cosmopolitan/libc/calls/getpgrp.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-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" /** * Returns process group id of calling process. * * This function is equivalent to `getpgid(0)`. */ int getpgrp(void) { int rc; if (!IsWindows()) { rc = sys_getpgid(0); } else { rc = getpid(); } STRACE("%s() → %d% m", "getpgrp", rc); return rc; }
2,252
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/interrupts-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 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/sig.internal.h" #include "libc/calls/state.internal.h" #include "libc/calls/struct/fd.internal.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/syscall_support-nt.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" textwindows int _check_interrupts(bool restartable, struct Fd *fd) { int rc; if (_weaken(pthread_testcancel_np) && (rc = _weaken(pthread_testcancel_np)())) { errno = rc; return -1; } if (_weaken(_check_sigalrm)) _weaken(_check_sigalrm)(); if (!__tls_enabled || !(__get_tls()->tib_flags & TIB_FLAG_TIME_CRITICAL)) { if (_weaken(_check_sigchld)) _weaken(_check_sigchld)(); if (fd && _weaken(_check_sigwinch)) _weaken(_check_sigwinch)(fd); } if (_weaken(__sig_check) && _weaken(__sig_check)(restartable)) return eintr(); return 0; }
2,916
50
jart/cosmopolitan
false
cosmopolitan/libc/calls/kntwindowsdirectory.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/dce.h" #include "libc/macros.internal.h" #define BYTES 64 // RII constant holding 'C:/WINDOWS' directory. // // @note guarantees trailing slash if non-empty .initbss 300,_init_kNtWindowsDirectory kNtWindowsDirectory: .zero BYTES .endobj kNtWindowsDirectory,globl .previous .init.start 300,_init_kNtWindowsDirectory #if SupportsWindows() pushpop BYTES,%rdx mov __imp_GetWindowsDirectoryA(%rip),%rax call __getntsyspath #else add $BYTES,%rdi #endif .init.end 300,_init_kNtWindowsDirectory
2,351
42
jart/cosmopolitan
false
cosmopolitan/libc/calls/prctl.internal.h
#ifndef COSMOPOLITAN_LIBC_CALLS_PRCTL_INTERNAL_H_ #define COSMOPOLITAN_LIBC_CALLS_PRCTL_INTERNAL_H_ #include "libc/dce.h" #include "libc/sysv/consts/nrlinux.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline int sys_prctl(int op, long a, long b, long c, long d) { int rc; #ifdef __x86_64__ register long r10 asm("r10") = c; register long r8 asm("r8") = d; asm volatile("syscall" : "=a"(rc) : "0"(__NR_linux_prctl), "D"(op), "S"(a), "d"(b), "r"(r10), "r"(r8) : "rcx", "r11", "memory"); #elif defined(__aarch64__) register long r0 asm("x0") = op; register long r1 asm("x1") = a; register long r2 asm("x2") = b; register long r3 asm("x3") = c; register long r4 asm("x4") = d; register long res_x0 asm("x0"); asm volatile("mov\tx8,%1\n\t" "svc\t0" : "=r"(res_x0) : "i"(__NR_linux_prctl), "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4) : "x8", "memory"); rc = res_x0; #endif return rc; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_CALLS_PRCTL_INTERNAL_H_ */
1,193
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/timeval_frommicros.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" /** * Converts timeval interval from microseconds. */ struct timeval timeval_frommicros(int64_t x) { struct timeval tv; tv.tv_sec = x / 1000000; tv.tv_usec = x % 1000000; return tv; }
2,070
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/openat.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/cp.internal.h" #include "libc/calls/internal.h" #include "libc/calls/state.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/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/log.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/errfuns.h" #include "libc/zipos/zipos.internal.h" /** * Opens file. * * Here's an example of how a file can be created: * * int fd = openat(AT_FDCWD, "hi.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644); * write(fd, "hello\n", 6); * close(fd); * * Here's an example of how that file could read back into memory: * * char data[513] = {0}; * int fd = openat(AT_FDCWD, "hi.txt", O_RDONLY); * read(fd, data, 512); * close(fd); * assert(!strcmp(data, "hello\n")); * * If your main() source file has this statement: * * STATIC_YOINK("zip_uri_support"); * * Then you can read zip assets by adding a `"/zip/..."` prefix to `file`, e.g. * * // run `zip program.com hi.txt` beforehand * openat(AT_FDCWD, "/zip/hi.txt", O_RDONLY); * * @param dirfd is normally `AT_FDCWD` but if it's an open directory and * `file` names a relative path then it's opened relative to `dirfd` * @param file is a UTF-8 string naming filesystem entity, e.g. `foo/bar.txt`, * which on Windows is bludgeoned into a WIN32 path automatically, e.g. * - `foo/bar.txt` becomes `foo\bar.txt` * - `/tmp/...` becomes whatever GetTempPath() is * - `\\...` or `//...` is passed through to WIN32 unchanged * - `/c/foo` or `\c\foo` becomes `\\?\c:\foo` * - `c:/foo` or `c:\foo` becomes `\\?\c:\foo` * - `/D` becomes `\\?\D:\` * @param flags must have one of the following under the `O_ACCMODE` bits: * - `O_RDONLY` to open `file` for reading only * - `O_WRONLY` to open `file` for writing * - `O_RDWR` to open `file` for reading and writing * The following may optionally be bitwise or'd into `flags`: * - `O_CREAT` create file if it doesn't exist * - `O_TRUNC` automatic `ftruncate(fd,0)` if exists * - `O_CLOEXEC` automatic close() upon execve() * - `O_EXCL` exclusive access (see below) * - `O_APPEND` open file for appending only * - `O_EXEC` open file for execution only; see fexecve() * - `O_NOCTTY` prevents `file` possibly becoming controlling terminal * - `O_NONBLOCK` asks read/write to fail with `EAGAIN` rather than block * - `O_DIRECT` it's complicated (not supported on Apple and OpenBSD) * - `O_DIRECTORY` useful for stat'ing (hint on UNIX but required on NT) * - `O_NOFOLLOW` fail if it's a symlink (zero on Windows) * - `O_DSYNC` it's complicated (zero on non-Linux/Apple) * - `O_RSYNC` it's complicated (zero on non-Linux/Apple) * - `O_VERIFY` it's complicated (zero on non-FreeBSD) * - `O_SHLOCK` it's complicated (zero on non-BSD) * - `O_EXLOCK` it's complicated (zero on non-BSD) * - `O_PATH` open only for metadata (Linux 2.6.39+ otherwise zero) * - `O_NOATIME` don't record access time (zero on non-Linux) * - `O_RANDOM` hint random access intent (zero on non-Windows) * - `O_SEQUENTIAL` hint sequential access intent (zero on non-Windows) * - `O_COMPRESSED` ask fs to abstract compression (zero on non-Windows) * - `O_INDEXED` turns on that slow performance (zero on non-Windows) * - `O_TMPFILE` should not be used; use tmpfd() or tmpfile() instead * There are three regular combinations for the above flags: * - `O_RDONLY`: Opens existing file for reading. If it doesn't * exist then nil is returned and errno will be `ENOENT` (or in * some other cases `ENOTDIR`). * - `O_WRONLY|O_CREAT|O_TRUNC`: Creates file. If it already * exists, then the existing copy is destroyed and the opened * file will start off with a length of zero. This is the * behavior of the traditional creat() system call. * - `O_WRONLY|O_CREAT|O_EXCL`: Create file only if doesn't exist * already. If it does exist then `nil` is returned along with * `errno` set to `EEXIST`. * @param mode is an octal user/group/other permission signifier that's * ignored if `O_CREAT` isn't passed in `flags`; when creating files * you'll usually want `mode` to be `0644` which enables global read * and only permits the owner to write; or when creating executables * you'll usually want `mode` to be `0755` which is the same, except * the executable bit is set thrice too * @return file descriptor (which needs to be close()'d), or -1 w/ errno * @raise EPERM if pledge() is in play w/o appropriate rpath/wpath/cpath * @raise EACCES if unveil() is in play and didn't unveil your `file` path * @raise EACCES if we don't have permission to search a component of `file` * @raise EACCES if file exists but requested `flags & O_ACCMODE` was denied * @raise EACCES if file doesn't exist and parent dir lacks write permissions * @raise EACCES if `O_TRUNC` was specified in `flags` but writing was denied * @raise ENOTSUP if `file` is on zip file system and `dirfd` isn't `AT_FDCWD` * @raise ENOTDIR if a directory component in `file` exists as non-directory * @raise ENOTDIR if `file` is relative and `dirfd` isn't an open directory * @raise EROFS when writing is requested w/ `file` on read-only filesystem * @raise ENAMETOOLONG if symlink-resolved `file` length exceeds `PATH_MAX` * @raise ENAMETOOLONG if component in `file` exists longer than `NAME_MAX` * @raise ENOTSUP if `file` is on zip file system and process is vfork()'d * @raise ENOSPC if file system is full when `file` would be `O_CREAT`ed * @raise EINTR if we needed to block and a signal was delivered instead * @raise ECANCELED if thread was cancelled in masked mode * @raise ENOENT if `file` doesn't exist when `O_CREAT` isn't in `flags` * @raise ENOENT if `file` points to a string that's empty * @raise ENOMEM if insufficient memory was available * @raise EMFILE if process `RLIMIT_NOFILE` has been reached * @raise ENFILE if system-wide file limit has been reached * @raise EOPNOTSUPP if `file` names a named socket * @raise EFAULT if `file` points to invalid memory * @raise ETXTBSY if writing is requested on `file` that's being executed * @raise ELOOP if `flags` had `O_NOFOLLOW` and `file` is a symbolic link * @raise ELOOP if a loop was detected resolving components of `file` * @raise EISDIR if writing is requested and `file` names a directory * @cancellationpoint * @asyncsignalsafe * @restartable * @threadsafe * @vforksafe */ int openat(int dirfd, const char *file, int flags, ...) { int rc; va_list va; unsigned mode; struct ZiposUri zipname; va_start(va, flags); mode = va_arg(va, unsigned); va_end(va); BEGIN_CANCELLATION_POINT; if (file && (!IsAsan() || __asan_is_valid_str(file))) { if (!__isfdkind(dirfd, kFdZip)) { if (_weaken(__zipos_open) && _weaken(__zipos_parseuri)(file, &zipname) != -1) { if (!__vforked && dirfd == AT_FDCWD) { rc = _weaken(__zipos_open)(&zipname, flags, mode); } else { rc = enotsup(); /* TODO */ } } else if (!IsWindows() && !IsMetal()) { rc = sys_openat(dirfd, file, flags, mode); } else if (IsMetal()) { rc = sys_openat_metal(dirfd, file, flags, mode); } else { rc = sys_open_nt(dirfd, file, flags, mode); } } else { rc = enotsup(); /* TODO */ } } else { rc = efault(); } END_CANCELLATION_POINT; STRACE("openat(%s, %#s, %s, %#o) → %d% m", DescribeDirfd(dirfd), file, DescribeOpenFlags(flags), (flags & (O_CREAT | O_TMPFILE)) ? mode : 0, rc); return rc; }
9,953
192
jart/cosmopolitan
false
cosmopolitan/libc/calls/timespec_frommicros.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/struct/timespec.h" /** * Converts timespec interval from microseconds. */ struct timespec timespec_frommicros(int64_t x) { struct timespec ts; ts.tv_sec = x / 1000000; ts.tv_nsec = x % 1000000 * 1000; return ts; }
2,082
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/unlockpt.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/calls/syscall_support-sysv.internal.h" #include "libc/calls/termios.h" #include "libc/dce.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/pty.h" #include "libc/sysv/errfuns.h" extern const uint32_t TIOCPTYUNLK; /** * Unlocks pseudoteletypewriter pair. * * @return 0 on success, or -1 w/ errno * @raise EBADF if fd isn't open * @raise EINVAL if fd is valid but not associated with pty */ int unlockpt(int fd) { int rc, unlock = 0; if (IsFreebsd() || IsOpenbsd() || IsNetbsd()) { rc = _isptmaster(fd); } else if (IsXnu()) { rc = sys_ioctl(fd, TIOCPTYUNLK); } else if (IsLinux()) { rc = sys_ioctl(fd, TIOCSPTLCK, &unlock); } else { rc = enosys(); } STRACE("unlockpt(%d) → %d% m", fd, rc); return rc; }
2,691
51
jart/cosmopolitan
false
cosmopolitan/libc/calls/setfsuid.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/dce.h" #include "libc/intrin/strace.internal.h" /** * Sets user id of current process for file system ops. * @return previous filesystem uid */ int setfsuid(unsigned uid) { int rc; if (IsLinux()) { rc = sys_setfsuid(uid); } else { rc = geteuid(); seteuid(uid); }; STRACE("setfsuid(%d) → %d% m", uid, rc); return rc; }
2,275
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/sched_getscheduler.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/sched-sysv.internal.h" #include "libc/calls/struct/sched_param.h" #include "libc/dce.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" /** * Gets scheduler policy for `pid`. * * @param pid is the id of the process whose scheduling policy should be * queried. Setting `pid` to zero means the same thing as getpid(). * This applies to all threads associated with the process. Linux is * special; the kernel treats this as a thread id (noting that * `getpid() == gettid()` is always the case on Linux for the main * thread) and will only take effect for the specified tid. * Therefore this function is POSIX-compliant iif `!__threaded`. * @return scheduler policy, or -1 w/ errno * @error ESRCH if `pid` not found * @error EPERM if not permitted * @error EINVAL if `pid` is negative on Linux */ int sched_getscheduler(int pid) { int rc; if (IsNetbsd()) { struct sched_param p; rc = sys_sched_getscheduler_netbsd(pid, &p); } else { rc = sys_sched_getscheduler(pid); } STRACE("sched_getscheduler(%d) → %s% m", pid, DescribeSchedPolicy(rc)); return rc; }
3,013
51
jart/cosmopolitan
false
cosmopolitan/libc/calls/execvp.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/runtime/runtime.h" /** * Replaces process, with path search, using default environment. * @asyncsignalsafe * @vforksafe */ int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); }
2,101
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/winsockerr.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/errno.h" #include "libc/nt/winsock.h" #include "libc/sock/internal.h" /** * Error return path for winsock wrappers. */ textwindows int64_t __winsockerr(void) { errno = __dos2errno(WSAGetLastError()); return -1; }
2,071
30
jart/cosmopolitan
false
cosmopolitan/libc/calls/copy_file_range.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/cp.internal.h" #include "libc/calls/internal.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/sigset.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/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" static struct CopyFileRange { pthread_once_t once; bool ok; } g_copy_file_range; static bool HasCopyFileRange(void) { bool ok; int e, rc; e = errno; BLOCK_CANCELLATIONS; if (IsLinux()) { // We modernize our detection by a few years for simplicity. // This system call is chosen since it's listed by pledge(). // https://www.cygwin.com/bugzilla/show_bug.cgi?id=26338 ok = sys_close_range(-1, -2, 0) == -1 && errno == EINVAL; } else if (IsFreebsd()) { ok = sys_copy_file_range(-1, 0, -1, 0, 0, 0) == -1 && errno == EBADF; } else { ok = false; } ALLOW_CANCELLATIONS; errno = e; return ok; } static void copy_file_range_init(void) { g_copy_file_range.ok = HasCopyFileRange(); } /** * Transfers data between files. * * If this system call is available (Linux c. 2018 or FreeBSD c. 2021) * and the file system supports it (e.g. ext4) and the source and dest * files are on the same file system, then this system call shall make * copies go about 2x faster. * * This implementation requires Linux 5.9+ even though the system call * was introduced in Linux 4.5. That's to ensure ENOSYS works reliably * due to a faulty backport, that happened in RHEL7. FreeBSD detection * on the other hand will work fine. * * @param infd is source file, which should be on same file system * @param opt_in_out_inoffset may be specified for pread() behavior * @param outfd should be a writable file, but not `O_APPEND` * @param opt_in_out_outoffset may be specified for pwrite() behavior * @param uptobytes is maximum number of bytes to transfer * @param flags is reserved for future use and must be zero * @return number of bytes transferred, or -1 w/ errno * @raise EXDEV if source and destination are on different filesystems * @raise EBADF if `infd` or `outfd` aren't open files or append-only * @raise EPERM if `fdout` refers to an immutable file on Linux * @raise ENOTSUP if `infd` or `outfd` is a zip file descriptor * @raise ECANCELED if thread was cancelled in masked mode * @raise EINVAL if ranges overlap or `flags` is non-zero * @raise EFBIG if `setrlimit(RLIMIT_FSIZE)` is exceeded * @raise EFAULT if one of the pointers memory is bad * @raise ERANGE if overflow happens computing ranges * @raise ENOSPC if file system has run out of space * @raise ETXTBSY if source or dest is a swap file * @raise EINTR if a signal was delivered instead * @raise EISDIR if source or dest is a directory * @raise ENOSYS if not Linux 5.9+ or FreeBSD 13+ * @raise EIO if a low-level i/o error happens * @see sendfile() for seekable → socket * @see splice() for fd ↔ pipe * @cancellationpoint */ ssize_t copy_file_range(int infd, int64_t *opt_in_out_inoffset, int outfd, int64_t *opt_in_out_outoffset, size_t uptobytes, uint32_t flags) { ssize_t rc; pthread_once(&g_copy_file_range.once, copy_file_range_init); BEGIN_CANCELLATION_POINT; if (!g_copy_file_range.ok) { rc = enosys(); } else if (IsAsan() && ((opt_in_out_inoffset && !__asan_is_valid(opt_in_out_inoffset, 8)) || (opt_in_out_outoffset && !__asan_is_valid(opt_in_out_outoffset, 8)))) { rc = efault(); } else if (__isfdkind(infd, kFdZip) || __isfdkind(outfd, kFdZip)) { rc = enotsup(); } else { rc = sys_copy_file_range(infd, opt_in_out_inoffset, outfd, opt_in_out_outoffset, uptobytes, flags); } END_CANCELLATION_POINT; STRACE("copy_file_range(%d, %s, %d, %s, %'zu, %#x) → %'ld% m", infd, DescribeInOutInt64(rc, opt_in_out_inoffset), outfd, DescribeInOutInt64(rc, opt_in_out_outoffset), uptobytes, flags); return rc; }
6,146
130
jart/cosmopolitan
false
cosmopolitan/libc/calls/writev-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 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/internal.h" #include "libc/calls/struct/iovec.internal.h" #include "libc/intrin/weaken.h" #include "libc/sock/internal.h" #include "libc/sysv/errfuns.h" textwindows ssize_t sys_writev_nt(int fd, const struct iovec *iov, int iovlen) { switch (g_fds.p[fd].kind) { case kFdFile: case kFdConsole: return sys_write_nt(fd, iov, iovlen, -1); case kFdSocket: return _weaken(sys_send_nt)(fd, iov, iovlen, 0); default: return ebadf(); } }
2,325
36
jart/cosmopolitan
false
cosmopolitan/libc/calls/setreuid.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" /** * Sets real and/or effective user ids. * * @param ruid is real user id or -1 to leave it unchanged * @param euid is effective user id or -1 to leave it unchanged * @return 0 on success or -1 w/ errno */ int setreuid(uint32_t ruid, uint32_t euid) { int rc; rc = sys_setreuid(ruid, euid); STRACE("setreuid(%d, %d) → %d% m", ruid, euid, rc); return rc; }
2,326
36
jart/cosmopolitan
false
cosmopolitan/libc/calls/siginterrupt.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/sysv/consts/sa.h" /** * Tunes whether signal can interrupt restartable system calls. */ int siginterrupt(int sig, int flag) { struct sigaction sa; if (sigaction(sig, 0, &sa) != -1) { if (flag) { sa.sa_flags &= ~SA_RESTART; } else { sa.sa_flags |= SA_RESTART; } return sigaction(sig, &sa, 0); } else { return -1; } }
2,281
39
jart/cosmopolitan
false
cosmopolitan/libc/calls/symlinkat-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/syscall_support-nt.internal.h" #include "libc/errno.h" #include "libc/nt/enum/accessmask.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/nt/enum/symboliclink.h" #include "libc/nt/enum/tokeninformationclass.h" #include "libc/nt/errors.h" #include "libc/nt/files.h" #include "libc/nt/privilege.h" #include "libc/nt/runtime.h" #include "libc/nt/struct/luid.h" #include "libc/nt/struct/tokenprivileges.h" #include "libc/nt/thunk/msabi.h" #include "libc/sysv/errfuns.h" #include "libc/thread/thread.h" __msabi extern typeof(GetFileAttributes) *const __imp_GetFileAttributesW; static _Bool g_winlink_allowed; static pthread_once_t g_winlink_once; static textwindows void InitializeWinlink(void) { int64_t tok; struct NtLuid id; struct NtTokenPrivileges tp; if (!OpenProcessToken(GetCurrentProcess(), kNtTokenAllAccess, &tok)) return; if (!LookupPrivilegeValue(0, u"SeCreateSymbolicLinkPrivilege", &id)) return; tp.PrivilegeCount = 1; tp.Privileges[0].Luid = id; tp.Privileges[0].Attributes = kNtSePrivilegeEnabled; if (!AdjustTokenPrivileges(tok, 0, &tp, sizeof(tp), 0, 0)) return; g_winlink_allowed = GetLastError() != kNtErrorNotAllAssigned; } textwindows int sys_symlinkat_nt(const char *target, int newdirfd, const char *linkpath) { int targetlen; uint32_t attrs, flags; char16_t target16[PATH_MAX]; char16_t linkpath16[PATH_MAX]; // convert the paths if (__mkntpathat(newdirfd, linkpath, 0, linkpath16) == -1) return -1; if ((targetlen = __mkntpath(target, target16)) == -1) return -1; // determine if we need directory flag if ((attrs = __imp_GetFileAttributesW(target16)) != -1u) { if (attrs & kNtFileAttributeDirectory) { flags = kNtSymbolicLinkFlagDirectory; } else { flags = 0; } } else { // win32 needs to know if it's a directory of a file symlink, but // that's hard to determine if we're creating a broken symlink so // we'll fall back to checking for trailing slash if (targetlen && target16[targetlen - 1] == '\\') { flags = kNtSymbolicLinkFlagDirectory; } else { flags = 0; } } // windows only lets administrators do this // even then we're required to ask for permission pthread_once(&g_winlink_once, InitializeWinlink); if (!g_winlink_allowed) { return eperm(); } // we can now proceed if (CreateSymbolicLink(linkpath16, target16, flags)) { return 0; } else { return __fix_enotdir(-1, linkpath16); } }
4,393
97
jart/cosmopolitan
false
cosmopolitan/libc/calls/lseek.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-sysv.internal.h" #include "libc/dce.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/strace.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/backtrace.internal.h" #include "libc/zipos/zipos.internal.h" /** * Changes current position of file descriptor, e.g. * * int fd = open("hello.bin", O_RDONLY); * lseek(fd, 100, SEEK_SET); // set position to 100th byte * read(fd, buf, 8); // read bytes 100 through 107 * * This function may be used to inspect the current position: * * int64_t pos = lseek(fd, 0, SEEK_CUR); * * You may seek past the end of file. If a write happens afterwards * then the gap leading up to it will be filled with zeroes. Please * note that lseek() by itself will not extend the physical medium. * * If dup() is used then the current position will be shared across * multiple file descriptors. If you seek in one it will implicitly * seek the other too. * * The current position of a file descriptor is shared between both * processes and threads. For example, if an fd is inherited across * fork(), and both the child and parent want to read from it, then * changes made by one are observable to the other. * * The pread() and pwrite() functions obfuscate the need for having * global shared file position state. Consider using them, since it * helps avoid the gotchas of this interface described above. * * This function is supported by all OSes within our support vector * and our unit tests demonstrate the behaviors described above are * consistent across platforms. * * @param fd is a number returned by open() * @param offset is 0-indexed byte count w.r.t. `whence` * @param whence can be one of: * - `SEEK_SET`: Sets the file position to `offset` [default] * - `SEEK_CUR`: Sets the file position to `position + offset` * - `SEEK_END`: Sets the file position to `filesize + offset` * @return new position relative to beginning, or -1 w/ errno * @raise ESPIPE if `fd` is a pipe, socket, or fifo * @raise EBADF if `fd` isn't an open file descriptor * @raise EINVAL if resulting offset would be negative * @raise EINVAL if `whence` isn't valid * @asyncsignalsafe * @threadsafe * @vforksafe */ int64_t lseek(int fd, int64_t offset, int whence) { int64_t rc; if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) { rc = _weaken(__zipos_lseek)( (struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle, offset, whence); } else if (!IsWindows() && !IsOpenbsd() && !IsNetbsd()) { rc = sys_lseek(fd, offset, whence, 0); } else if (IsOpenbsd() || IsNetbsd()) { rc = sys_lseek(fd, offset, offset, whence); } else { rc = sys_lseek_nt(fd, offset, whence); } STRACE("lseek(%d, %'ld, %s) → %'ld% m", fd, offset, DescribeWhence(whence), rc); return rc; }
4,800
93
jart/cosmopolitan
false
cosmopolitan/libc/calls/lchown.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" /** * Changes owner and/or group 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 lchown(const char *pathname, uint32_t uid, uint32_t gid) { return fchownat(AT_FDCWD, pathname, uid, gid, AT_SYMLINK_NOFOLLOW); }
2,368
35
jart/cosmopolitan
false
cosmopolitan/libc/calls/ftok.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/calls/weirdtypes.h" #include "libc/str/str.h" /** * Convert pathname and a project ID to System V IPC key. */ int ftok(const char *path, int id) { struct stat st; if (stat(path, &st) == -1) return -1; return (uint32_t)id << 24 | (st.st_dev & 0xff) << 16 | (st.st_ino & 0xffff); }
2,206
32
jart/cosmopolitan
false
cosmopolitan/libc/calls/fchdir.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" /** * Sets current directory based on file descriptor. * * This does *not* update the `PWD` environment variable. * * @see open(path, O_DIRECTORY) * @asyncsignalsafe */ int fchdir(int dirfd) { if (!IsWindows()) { return sys_fchdir(dirfd); } else { return sys_fchdir_nt(dirfd); } }
2,281
39
jart/cosmopolitan
false