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/posix_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 POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, etc.
* @return 0 on success, or errno on error
* @raise EBADF if `fd` isn't a valid file descriptor
* @raise EINVAL if `advice` is invalid or `len` is huge
* @raise ESPIPE if `fd` refers to a pipe
* @raise ENOSYS on XNU and OpenBSD
* @returnserrno
* @threadsafe
*/
errno_t posix_fadvise(int fd, int64_t offset, int64_t len, int advice) {
int rc, e = errno;
if (IsLinux()) {
rc = sys_fadvise(fd, offset, len, advice);
} else if (IsFreebsd()) {
rc = sys_fadvise(fd, offset, len, advice);
_unassert(rc >= 0);
} else if (IsNetbsd()) {
rc = sys_fadvise_netbsd(fd, offset, offset, len, advice);
_unassert(rc >= 0);
} else if (IsWindows()) {
rc = sys_fadvise_nt(fd, offset, len, advice);
} else {
rc = enosys();
}
if (rc == -1) {
rc = errno;
errno = e;
}
STRACE("posix_fadvise(%d, %'lu, %'lu, %d) â %s", fd, offset, len, advice,
!rc ? "0" : _strerrno(rc));
return rc;
}
| 3,454 | 70 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sysinfo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/sysinfo.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/sysinfo.internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#define CTL_KERN 1
#define CTL_HW 6
#define KERN_BOOTTIME 21
#define HW_PHYSMEM (IsXnu() ? 24 : 5)
static int64_t GetUptime(void) {
if (IsNetbsd()) return 0; // TODO(jart): Why?
struct timeval x;
size_t n = sizeof(x);
int mib[] = {CTL_KERN, KERN_BOOTTIME};
if (sys_sysctl(mib, ARRAYLEN(mib), &x, &n, 0, 0) == -1) return 0;
return timespec_real().tv_sec - x.tv_sec;
}
static int64_t GetPhysmem(void) {
uint64_t x = 0;
size_t n = sizeof(x);
int mib[] = {CTL_HW, HW_PHYSMEM};
if (sys_sysctl(mib, ARRAYLEN(mib), &x, &n, 0, 0) == -1) return 0;
return x;
}
static int sys_sysinfo_bsd(struct sysinfo *info) {
info->uptime = GetUptime();
info->totalram = GetPhysmem();
return 0;
}
/**
* Returns amount of system ram, cores, etc.
*
* Only the `totalram` field is supported on all platforms right now.
* Support is best on Linux. Fields will be set to zero when they're not
* known.
*
* @return 0 on success or -1 w/ errno
* @error EFAULT
*/
int sysinfo(struct sysinfo *info) {
int rc;
struct sysinfo x = {0};
if (IsAsan() && info && !__asan_is_valid(info, sizeof(*info))) {
rc = efault();
} else if (!IsWindows()) {
if (IsLinux()) {
rc = sys_sysinfo(&x);
} else {
rc = sys_sysinfo_bsd(&x);
}
} else {
rc = sys_sysinfo_nt(&x);
}
if (rc != -1) {
memcpy(info, &x, sizeof(x));
}
STRACE("sysinfo(%p) â %d% m", info, rc);
return rc;
}
| 3,661 | 89 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/utime.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/timeval.h"
#include "libc/time/struct/utimbuf.h"
/**
* Changes last accessed/modified times on file.
*
* @param times if NULL means now
* @return 0 on success, or -1 w/ errno
* @see utimensat() for modern version
* @asyncsignalsafe
* @threadsafe
*/
int utime(const char *path, const struct utimbuf *times) {
struct timeval tv[2];
if (times) {
tv[0].tv_sec = times->actime;
tv[0].tv_usec = 0;
tv[1].tv_sec = times->modtime;
tv[1].tv_usec = 0;
return utimes(path, tv);
} else {
return utimes(path, NULL);
}
}
| 2,412 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ppoll.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/cp.internal.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/sigset.internal.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timespec.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/sock/struct/pollfd.internal.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
/**
* Waits for something to happen on multiple file descriptors at once.
*
* This function is the same as saying:
*
* sigset_t old;
* sigprocmask(SIG_SETMASK, sigmask, &old);
* poll(fds, nfds, timeout);
* sigprocmask(SIG_SETMASK, old, 0);
*
* Except it happens atomically when the kernel supports doing that. On
* kernel such as XNU and NetBSD which don't, this wrapper will fall
* back to using the example above. Consider using pselect() which is
* atomic on all supported platforms.
*
* The Linux Kernel modifies the timeout parameter. This wrapper gives
* it a local variable due to POSIX requiring that `timeout` be const.
* If you need that information from the Linux Kernel use sys_ppoll().
*
* @param timeout if null will block indefinitely
* @param sigmask may be null in which case no mask change happens
* @raise ECANCELED if thread was cancelled in masked mode
* @raise EINTR if signal was delivered
* @cancellationpoint
* @asyncsignalsafe
* @threadsafe
* @norestart
*/
int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout,
const sigset_t *sigmask) {
size_t n;
int e, rc;
uint64_t millis;
sigset_t oldmask;
struct timespec ts, *tsp;
BEGIN_CANCELLATION_POINT;
if (IsAsan() && (__builtin_mul_overflow(nfds, sizeof(struct pollfd), &n) ||
!__asan_is_valid(fds, n) ||
(timeout && !__asan_is_valid(timeout, sizeof(timeout))) ||
(sigmask && !__asan_is_valid(sigmask, sizeof(sigmask))))) {
rc = efault();
} else if (!IsWindows()) {
e = errno;
if (timeout) {
ts = *timeout;
tsp = &ts;
} else {
tsp = 0;
}
rc = sys_ppoll(fds, nfds, tsp, sigmask, 8);
if (rc == -1 && errno == ENOSYS) {
errno = e;
if (!timeout ||
__builtin_add_overflow(timeout->tv_sec, timeout->tv_nsec / 1000000,
&millis)) {
millis = -1;
}
if (sigmask) sys_sigprocmask(SIG_SETMASK, sigmask, &oldmask);
rc = poll(fds, nfds, millis);
if (sigmask) sys_sigprocmask(SIG_SETMASK, &oldmask, 0);
}
} else {
if (!timeout || __builtin_add_overflow(
timeout->tv_sec, timeout->tv_nsec / 1000000, &millis)) {
millis = -1;
}
rc = sys_poll_nt(fds, nfds, &millis, sigmask);
}
END_CANCELLATION_POINT;
STRACE("ppoll(%s, %'zu, %s, %s) â %d% lm", DescribePollFds(rc, fds, nfds),
nfds, DescribeTimespec(0, timeout), DescribeSigset(0, sigmask), rc);
return rc;
}
| 4,881 | 108 | 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=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2023 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/clock_gettime.internal.h"
clock_gettime_f *__clock_gettime = __clock_gettime_init;
| 1,941 | 22 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sched_get_priority_min.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/sched-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/sched.h"
#include "libc/sysv/errfuns.h"
static int sys_sched_get_priority_min_netbsd(int policy) {
if (policy == SCHED_OTHER) {
return -1;
} else if (policy == SCHED_RR || policy == SCHED_FIFO) {
return 0; // NetBSD Libc needs 19 system calls to compute this!
} else {
return einval();
}
}
/**
* Returns minimum `sched_param::sched_priority` for `policy`.
*
* @return priority, or -1 w/ errno
* @raise ENOSYS on XNU, Windows, OpenBSD
* @raise EINVAL if `policy` is invalid
*/
int sched_get_priority_min(int policy) {
int rc;
if (IsNetbsd()) {
rc = sys_sched_get_priority_min_netbsd(policy);
} else {
rc = sys_sched_get_priority_min(policy);
}
STRACE("sched_get_priority_min(%s) â %d% m", DescribeSchedPolicy(policy), rc);
return rc;
}
| 2,834 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/gethostname-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/macros.internal.h"
#include "libc/nt/enum/computernameformat.h"
#include "libc/nt/systeminfo.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
// Guarantees NUL-terminator, if zero is returned.
// Mutates on ENAMETOOLONG without nul-terminator.
textwindows int gethostname_nt(char *name, size_t len, int kind) {
uint32_t nSize;
char name8[256];
char16_t name16[256];
nSize = ARRAYLEN(name16);
if (GetComputerNameEx(kind, name16, &nSize)) {
tprecode16to8(name8, sizeof(name8), name16);
if (memccpy(name, name8, '\0', len)) {
return 0;
} else {
return enametoolong();
}
return 0;
} else {
return __winerr();
}
}
| 2,604 | 46 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/seteuid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/intrin/strace.internal.h"
/**
* Sets effective user ID.
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if euid not in legal range
* @raise EPERM if lack privileges
*/
int seteuid(uint32_t euid) {
return setregid(euid, -1);
}
| 2,125 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/setgroups.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/groups.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"
/**
* Sets list of supplementary group IDs.
*
* On recent versions of Linux only, it's possible to say:
*
* setgroups(0, NULL);
*
* Which will cause subsequent calls to `EPERM`.
*
* @param size number of items in list
* @param list input set of gid_t to set
* @return -1 w/ EFAULT
*/
int setgroups(size_t size, const uint32_t list[]) {
int rc;
size_t n;
if (IsAsan() && (__builtin_mul_overflow(size, sizeof(list[0]), &n) ||
!__asan_is_valid(list, n))) {
rc = efault();
} else if (IsLinux() || IsNetbsd() || IsOpenbsd() || IsFreebsd() || IsXnu()) {
rc = sys_setgroups(size, list);
} else {
rc = enosys();
}
STRACE("setgroups(%u, %s) â %d% m", size, DescribeGidList(rc, size, list),
rc);
return rc;
}
| 2,861 | 55 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fdatasync-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/nt/files.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_fdatasync_nt(int fd) {
// TODO(jart): what should we do with worker pipes?
if (!__isfdkind(fd, kFdFile)) return ebadf();
if (_check_interrupts(false, 0)) return -1;
return FlushFileBuffers(g_fds.p[fd].handle) ? 0 : -1;
}
| 2,177 | 29 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pledge.h | #ifndef COSMOPOLITAN_LIBC_CALLS_PLEDGE_H_
#define COSMOPOLITAN_LIBC_CALLS_PLEDGE_H_
#define PLEDGE_PENALTY_KILL_THREAD 0x0000
#define PLEDGE_PENALTY_KILL_PROCESS 0x0001
#define PLEDGE_PENALTY_RETURN_EPERM 0x0002
#define PLEDGE_PENALTY_MASK 0x000f
#define PLEDGE_STDERR_LOGGING 0x0010
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern int __pledge_mode;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_PLEDGE_H_ */
| 503 | 18 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/nosync.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Tunes sync system call availability.
*
* If this value is set to 0x5453455454534146, then the system calls
* sync(), fsync(), and fdatasync() system calls will do nothing and
* return success. This is intended to be used for things like making
* things like Python unit tests go faster because fsync is extremely
* slow and using tmpfs requires root privileges.
*/
uint64_t __nosync;
| 2,265 | 31 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fstatvfs.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/statfs.h"
#include "libc/calls/struct/statfs.internal.h"
#include "libc/calls/struct/statvfs.h"
/**
* Returns information about filesystem.
* @return 0 on success, or -1 w/ errno
* @note consider using fstatfs()
*/
int fstatvfs(int fd, struct statvfs *sv) {
struct statfs sf;
if (fstatfs(fd, &sf) != -1) {
statfs2statvfs(sv, &sf);
return 0;
} else {
return -1;
}
}
| 2,284 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/stat.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/calls/struct/stat.h"
#include "libc/sysv/consts/at.h"
/**
* Returns information about thing.
*
* @param st is where result is stored
* @see S_ISDIR(st.st_mode), S_ISREG(), etc.
* @raise EACCES if denied access to component in path prefix
* @raise EIO if i/o error occurred while reading from filesystem
* @raise ELOOP if a symbolic link loop exists in `path`
* @raise ENAMETOOLONG if a component in `path` exceeds `NAME_MAX`
* @raise ENOENT on empty string or if component in path doesn't exist
* @raise ENOTDIR if a parent component existed that wasn't a directory
* @raise EOVERFLOW shouldn't be possible on 64-bit systems
* @raise ELOOP may ahappen if `SYMLOOP_MAX` symlinks were dereferenced
* @raise ENAMETOOLONG may happen if `path` exceeded `PATH_MAX`
* @asyncsignalsafe
*/
int stat(const char *path, struct stat *st) {
return fstatat(AT_FDCWD, path, st, 0);
}
| 2,737 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pause.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/cp.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sock/internal.h"
/**
* Waits for signal.
*
* This suspends execution until an unmasked signal is delivered. If the
* signal delivery kills the process, this won't return. The signal mask
* of the current thread is used. If a signal handler exists, this shall
* return after it's been invoked.
*
* This function is equivalent to:
*
* select(0, 0, 0, 0, 0);
*
* However this has a tinier footprint and better logging.
*
* @return -1 w/ errno set to EINTR
* @cancellationpoint
* @see sigsuspend()
* @norestart
*/
int pause(void) {
int rc;
STRACE("pause() â [...]");
BEGIN_CANCELLATION_POINT;
if (!IsWindows()) {
// We'll polyfill pause() using select() with a null timeout, which
// should hopefully do the same thing, which means wait forever but
// the usual signal interrupt rules apply.
//
// "If the readfds, writefds, and errorfds arguments are all null
// pointers and the timeout argument is not a null pointer, the
// pselect() or select() function shall block for the time
// specified, or until interrupted by a signal. If the readfds,
// writefds, and errorfds arguments are all null pointers and the
// timeout argument is a null pointer, the pselect() or select()
// function shall block until interrupted by a signal." ââQuoth
// IEEE 1003.1-2017 §functions/select
//
#ifdef __aarch64__
rc = sys_pselect(0, 0, 0, 0, 0, 0);
#else
rc = sys_select(0, 0, 0, 0, 0);
#endif
} else {
rc = sys_pause_nt();
}
END_CANCELLATION_POINT;
STRACE("[...] pause â %d% m", rc);
return rc;
}
| 3,671 | 77 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/reservefd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/state.internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/cmpxchg.h"
#include "libc/intrin/extend.internal.h"
#include "libc/macros.internal.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/map.h"
// TODO(jart): make more of this code lockless
static volatile size_t mapsize;
/**
* Grows file descriptor array memory if needed.
*
* @see libc/runtime/memtrack64.txt
* @see libc/runtime/memtrack32.txt
* @asyncsignalsafe
*/
int __ensurefds_unlocked(int fd) {
bool relocate;
if (fd < g_fds.n) return fd;
g_fds.n = fd + 1;
g_fds.e = _extend(g_fds.p, g_fds.n * sizeof(*g_fds.p), g_fds.e, MAP_PRIVATE,
kMemtrackFdsStart + kMemtrackFdsSize);
return fd;
}
/**
* Grows file descriptor array memory if needed.
* @asyncsignalsafe
* @threadsafe
*/
int __ensurefds(int fd) {
__fds_lock();
fd = __ensurefds_unlocked(fd);
__fds_unlock();
return fd;
}
/**
* Finds open file descriptor slot.
* @asyncsignalsafe
*/
int __reservefd_unlocked(int start) {
int fd, f1, f2;
for (;;) {
f1 = atomic_load_explicit(&g_fds.f, memory_order_acquire);
for (fd = MAX(start, f1); fd < g_fds.n; ++fd) {
if (!g_fds.p[fd].kind) {
break;
}
}
fd = __ensurefds_unlocked(fd);
bzero(g_fds.p + fd, sizeof(*g_fds.p));
if (_cmpxchg(&g_fds.p[fd].kind, kFdEmpty, kFdReserved)) {
// g_fds.f isn't guarded by our mutex
do {
f2 = MAX(fd + 1, f1);
} while (!atomic_compare_exchange_weak_explicit(
&g_fds.f, &f1, f2, memory_order_release, memory_order_relaxed));
return fd;
}
}
}
/**
* Finds open file descriptor slot.
* @asyncsignalsafe
* @threadsafe
*/
int __reservefd(int start) {
int fd;
__fds_lock();
fd = __reservefd_unlocked(start);
__fds_unlock();
return fd;
}
| 3,783 | 100 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/setegid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/intrin/strace.internal.h"
/**
* Sets effective group ID.
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if euid not in legal range
* @raise EPERM if lack privileges
*/
int setegid(uint32_t egid) {
return setregid(-1, egid);
}
| 2,126 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/asan.internal.h | #ifndef COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
#define COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/asmflag.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
forceinline bool __asan_is_valid_timespec(const struct timespec *ts) {
#ifdef __x86_64__
bool zf;
asm(ZFLAG_ASM("cmpw\t$0,0x7fff8000(%1)")
: ZFLAG_CONSTRAINT(zf)
: "r"((intptr_t)ts >> 3)
: "memory");
return zf;
#else
return __asan_is_valid(ts, sizeof(*ts));
#endif
}
forceinline bool __asan_is_valid_timeval(const struct timeval *tv) {
return __asan_is_valid_timespec((const struct timespec *)tv);
}
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_ASAN_INTERNAL_H_ */
| 861 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/mkntenvblock.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/ntspawn.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/macros.internal.h"
#include "libc/mem/alloca.h"
#include "libc/mem/arraylist2.internal.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "libc/str/thompike.h"
#include "libc/str/utf16.h"
#include "libc/sysv/errfuns.h"
#define ToUpper(c) ((c) >= 'a' && (c) <= 'z' ? (c) - 'a' + 'A' : (c))
static inline int IsAlpha(int c) {
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
}
static inline char *StrChr(char *s, int c) {
for (;; ++s) {
if ((*s & 255) == (c & 255)) return s;
if (!*s) return 0;
}
}
static textwindows inline int CompareStrings(const char *l, const char *r) {
int a, b;
size_t i = 0;
while ((a = ToUpper(l[i] & 255)) == (b = ToUpper(r[i] & 255)) && r[i]) ++i;
return a - b;
}
static textwindows void FixPath(char *path) {
char *p;
size_t i;
// skip over variable name
while (*path++) {
if (path[-1] == '=') {
break;
}
}
// turn colon into semicolon
// unless it already looks like a dos path
for (p = path; *p; ++p) {
if (p[0] == ':' && p[1] != '\\') {
p[0] = ';';
}
}
// turn \c\... into c:\...
p = path;
if ((p[0] == '/' | p[0] == '\\') && IsAlpha(p[1]) &&
(p[2] == '/' || p[2] == '\\')) {
p[0] = p[1];
p[1] = ':';
}
for (; *p; ++p) {
if (p[0] == ';' && (p[1] == '/' || p[1] == '\\') && IsAlpha(p[2]) &&
(p[3] == '/' || p[3] == '\\')) {
p[1] = p[2];
p[2] = ':';
}
}
// turn slash into backslash
for (p = path; *p; ++p) {
if (*p == '/') {
*p = '\\';
}
}
}
static textwindows void InsertString(char **a, size_t i, char *s,
char buf[ARG_MAX], size_t *bufi) {
char *v;
size_t j, k;
// apply fixups to var=/c/...
if ((v = StrChr(s, '=')) && v[1] == '/' && IsAlpha(v[2]) && v[3] == '/') {
v = buf + *bufi;
for (k = 0; s[k]; ++k) {
if (*bufi + 1 < ARG_MAX) {
buf[(*bufi)++] = s[k];
}
}
if (*bufi < ARG_MAX) {
buf[(*bufi)++] = 0;
FixPath(v);
s = v;
}
}
// append to sorted list
for (j = i; j > 0 && CompareStrings(s, a[j - 1]) < 0; --j) {
a[j] = a[j - 1];
}
a[j] = s;
}
/**
* Copies sorted environment variable block for Windows.
*
* This is designed to meet the requirements of CreateProcess().
*
* @param envvars receives sorted double-NUL terminated string list
* @param envp is an a NULL-terminated array of UTF-8 strings
* @param extravar is a VAR=val string we consider part of envp or NULL
* @return 0 on success, or -1 w/ errno
* @error E2BIG if total number of shorts exceeded ARG_MAX/2 (32767)
*/
textwindows int mkntenvblock(char16_t envvars[ARG_MAX / 2], char *const envp[],
const char *extravar, char buf[ARG_MAX]) {
bool v;
char *t;
axdx_t rc;
uint64_t w;
char **vars;
wint_t x, y;
size_t i, j, k, n, m, bufi = 0;
for (n = 0; envp[n];) n++;
vars = alloca((n + 1) * sizeof(char *));
for (i = 0; i < n; ++i) InsertString(vars, i, envp[i], buf, &bufi);
if (extravar) InsertString(vars, n++, extravar, buf, &bufi);
for (k = i = 0; i < n; ++i) {
j = 0;
v = false;
do {
x = vars[i][j++] & 0xff;
if (x >= 0200) {
if (x < 0300) continue;
m = ThomPikeLen(x);
x = ThomPikeByte(x);
while (--m) {
if ((y = vars[i][j++] & 0xff)) {
x = ThomPikeMerge(x, y);
} else {
x = 0;
break;
}
}
}
if (!v) {
if (x != '=') {
x = ToUpper(x);
} else {
v = true;
}
}
w = EncodeUtf16(x);
do {
envvars[k++] = w & 0xffff;
if (k == ARG_MAX / 2) {
return e2big();
}
} while ((w >>= 16));
} while (x);
}
envvars[k] = u'\0';
return 0;
}
| 5,772 | 181 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/execve-nt.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 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. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define ShouldUseMsabiAttribute() 1
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/ntspawn.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/mem/alloca.h"
#include "libc/nt/accounting.h"
#include "libc/nt/console.h"
#include "libc/nt/enum/startf.h"
#include "libc/nt/enum/status.h"
#include "libc/nt/memory.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/processinformation.h"
#include "libc/nt/struct/startupinfo.h"
#include "libc/nt/synchronization.h"
#include "libc/nt/thunk/msabi.h"
#include "libc/runtime/memtrack.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/ok.h"
#include "libc/sysv/errfuns.h"
__msabi extern typeof(CloseHandle) *const __imp_CloseHandle;
__msabi extern typeof(WaitForSingleObject) *const __imp_WaitForSingleObject;
__msabi extern typeof(GetExitCodeProcess) *const __imp_GetExitCodeProcess;
__msabi extern typeof(UnmapViewOfFile) *const __imp_UnmapViewOfFile;
static noinstrument __msabi bool32
BlockExecveConsoleEvent(uint32_t dwCtrlType) {
// block SIGINT and SIGQUIT in execve() parent process
return true;
}
textwindows int sys_execve_nt(const char *program, char *const argv[],
char *const envp[]) {
int rc;
size_t i;
uint32_t dwExitCode;
char progbuf[PATH_MAX];
struct NtStartupInfo startinfo;
struct NtProcessInformation procinfo;
if (strlen(program) + 4 + 1 > PATH_MAX) {
return enametoolong();
}
// this is a non-recoverable operation, so do some manual validation
if (sys_faccessat_nt(AT_FDCWD, program, X_OK, 0) == -1) {
stpcpy(stpcpy(progbuf, program), ".com");
if (sys_faccessat_nt(AT_FDCWD, progbuf, X_OK, 0) != -1) {
program = progbuf;
} else {
stpcpy(stpcpy(progbuf, program), ".exe");
if (sys_faccessat_nt(AT_FDCWD, progbuf, X_OK, 0) != -1) {
program = progbuf;
} else {
return eacces();
}
}
}
//////////////////////////////////////////////////////////////////////////////
// execve operation is unrecoverable from this point
// close cloexec handles
for (i = 3; i < g_fds.n; ++i) {
if (g_fds.p[i].kind != kFdEmpty && (g_fds.p[i].flags & O_CLOEXEC)) {
__imp_CloseHandle(g_fds.p[i].handle);
}
}
bzero(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(struct NtStartupInfo);
startinfo.dwFlags = kNtStartfUsestdhandles;
startinfo.hStdInput = __getfdhandleactual(0);
startinfo.hStdOutput = __getfdhandleactual(1);
startinfo.hStdError = __getfdhandleactual(2);
// spawn the process
rc = ntspawn(program, argv, envp, 0, 0, 0, true, 0, 0, &startinfo, &procinfo);
if (rc == -1) {
STRACE("panic: unrecoverable ntspawn(%#s) error: %m", program);
__imp_ExitProcess(6543);
}
//////////////////////////////////////////////////////////////////////////////
// zombie shell process remains, to wait for child and propagate its exit
// code
__imp_CloseHandle(g_fds.p[0].handle);
__imp_CloseHandle(g_fds.p[1].handle);
__imp_CloseHandle(procinfo.hThread);
__imp_SetConsoleCtrlHandler((void *)BlockExecveConsoleEvent, 1);
do {
__imp_WaitForSingleObject(procinfo.hProcess, -1);
dwExitCode = kNtStillActive;
__imp_GetExitCodeProcess(procinfo.hProcess, &dwExitCode);
} while (dwExitCode == kNtStillActive);
__imp_CloseHandle(procinfo.hProcess);
__imp_ExitProcess(dwExitCode);
notpossible;
}
| 5,421 | 125 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/getdomainname.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/macros.internal.h"
#include "libc/nt/enum/computernameformat.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#define KERN_DOMAINNAME 22
/**
* Returns domain of current host.
*
* For example, if the fully-qualified hostname is "host.domain.example"
* then this SHOULD return "domain.example" however, it might not be the
* case; it depends on how the host machine is configured.
*
* The nul / mutation semantics are tricky. Here is some safe copypasta:
*
* char domain[254];
* if (getdomainname(domain, sizeof(domain))) {
* strcpy(domain, "(none)");
* }
*
* On Linux this is the same as `/proc/sys/kernel/domainname`. However,
* we turn the weird `"(none)"` string into empty string.
*
* @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 getdomainname(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 = getdomainname_linux(name, len);
} else if (IsBsd()) {
rc = gethostname_bsd(name, len, KERN_DOMAINNAME);
} else if (IsWindows()) {
rc = gethostname_nt(name, len, kNtComputerNamePhysicalDnsDomain);
} else {
rc = enosys();
}
if (!rc && len && !strcmp(name, "(none)")) {
name[0] = 0;
}
STRACE("getdomainname([%#.*s], %'zu) â %d% m", len, name, len, rc);
return rc;
}
| 3,985 | 82 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/dup3-sysv.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/thread.h"
#define F_DUP2FD 10
#define F_DUP2FD_CLOEXEC 18
static struct Dup3 {
pthread_once_t once;
bool demodernize;
} g_dup3;
static void sys_dup3_test(void) {
int e = errno;
__sys_dup3(-1, -1, 0);
if ((g_dup3.demodernize = errno == ENOSYS)) {
STRACE("demodernizing %s() due to %s", "dup3", "ENOSYS");
}
errno = e;
}
int32_t sys_dup3(int32_t oldfd, int32_t newfd, int flags) {
int how;
_unassert(oldfd >= 0);
_unassert(newfd >= 0);
_unassert(!(flags & ~O_CLOEXEC));
if (IsFreebsd()) {
if (flags & O_CLOEXEC) {
how = F_DUP2FD_CLOEXEC;
} else {
how = F_DUP2FD;
}
return __sys_fcntl(oldfd, how, newfd);
}
pthread_once(&g_dup3.once, sys_dup3_test);
if (!g_dup3.demodernize) {
return __sys_dup3(oldfd, newfd, flags);
} else {
return __fixupnewfd(sys_dup2(oldfd, newfd, 0), flags);
}
}
| 3,004 | 69 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/preadv.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/cp.internal.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/likely.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
static ssize_t Preadv(int fd, struct iovec *iov, int iovlen, int64_t off) {
int e, i;
size_t got;
ssize_t rc, toto;
if (fd < 0) {
return ebadf();
}
if (iovlen < 0) {
return einval();
}
if (IsAsan() && !__asan_is_valid_iov(iov, iovlen)) {
return efault();
}
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
return _weaken(__zipos_read)(
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle, iov, iovlen, off);
}
if (IsMetal()) {
return espipe(); // must be serial or console if not zipos
}
if (IsWindows()) {
if (fd < g_fds.n) {
return sys_read_nt(g_fds.p + fd, iov, iovlen, off);
} else {
return ebadf();
}
}
while (iovlen && !iov->iov_len) {
--iovlen;
++iov;
}
if (!iovlen) {
return sys_pread(fd, 0, 0, off, off);
}
if (iovlen == 1) {
return sys_pread(fd, iov->iov_base, iov->iov_len, off, off);
}
e = errno;
rc = sys_preadv(fd, iov, iovlen, off, off);
if (rc != -1 || errno != ENOSYS) return rc;
errno = e;
for (toto = i = 0; i < iovlen; ++i) {
rc = sys_pread(fd, iov[i].iov_base, iov[i].iov_len, off, off);
if (rc == -1) {
if (!toto) {
toto = -1;
} else if (errno != EINTR) {
notpossible;
}
break;
}
got = rc;
toto += got;
off += got;
if (got != iov[i].iov_len) {
break;
}
}
return toto;
}
/**
* Reads with maximum generality.
*
* @return number of bytes actually read, or -1 w/ errno
* @cancellationpoint
* @asyncsignalsafe
* @vforksafe
*/
ssize_t preadv(int fd, struct iovec *iov, int iovlen, int64_t off) {
ssize_t rc;
BEGIN_CANCELLATION_POINT;
rc = Preadv(fd, iov, iovlen, off);
END_CANCELLATION_POINT;
STRACE("preadv(%d, [%s], %d, %'ld) â %'ld% m", fd,
DescribeIovec(rc, iov, iovlen), iovlen, off, rc);
return rc;
}
| 4,251 | 125 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pledge-linux.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "ape/sections.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/pledge.internal.h"
#include "libc/calls/prctl.internal.h"
#include "libc/calls/struct/bpf.h"
#include "libc/calls/struct/filter.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/intrin/bsr.h"
#include "libc/intrin/likely.h"
#include "libc/intrin/promises.internal.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/prot.h"
/**
* @fileoverview OpenBSD pledge() Polyfill Payload for GNU/Systemd
*
* This file contains only the minimum amount of Linux-specific code
* that's necessary to get a pledge() policy installed. This file is
* designed to not use static or tls memory or libc depnedencies, so
* it can be transplanted into codebases and injected into programs.
*/
#define Eperm 1
#define Sigabrt 6
#define Einval 22
#define Sigsys 31
#define Enosys 38
#define Sig_Setmask 2
#define Sa_Siginfo 4
#define Sa_Restorer 0x04000000
#define Sa_Restart 0x10000000
#define SPECIAL 0xf000
#define SELF 0x8000
#define ADDRLESS 0x2000
#define INET 0x2000
#define LOCK 0x4000
#define NOEXEC 0x8000
#define EXEC 0x4000
#define READONLY 0x8000
#define WRITEONLY 0x4000
#define CREATONLY 0x2000
#define STDIO 0x8000
#define THREAD 0x8000
#define TTY 0x8000
#define UNIX 0x4000
#define NOBITS 0x8000
#define RESTRICT 0x1000
#define PLEDGE(pledge) pledge, ARRAYLEN(pledge)
#define OFF(f) offsetof(struct seccomp_data, f)
#ifdef __x86_64__
#define MCONTEXT_SYSCALL_RESULT_REGISTER rax
#define MCONTEXT_INSTRUCTION_POINTER rip
#define ARCHITECTURE AUDIT_ARCH_X86_64
#elif defined(__aarch64__)
#define MCONTEXT_SYSCALL_RESULT_REGISTER regs[0]
#define MCONTEXT_INSTRUCTION_POINTER pc
#define ARCHITECTURE AUDIT_ARCH_AARCH64
#else
#error "unsupported architecture"
#endif
struct Filter {
size_t n;
struct sock_filter p[700];
};
static const struct thatispacked SyscallName {
uint16_t n;
const char *const s;
} kSyscallName[] = {
{__NR_linux_exit, "exit"}, //
{__NR_linux_exit_group, "exit_group"}, //
{__NR_linux_read, "read"}, //
{__NR_linux_write, "write"}, //
{__NR_linux_open, "open"}, //
{__NR_linux_close, "close"}, //
{__NR_linux_stat, "stat"}, //
{__NR_linux_fstat, "fstat"}, //
#ifdef __NR_linux_lstat //
{__NR_linux_lstat, "lstat"}, //
#endif //
#ifdef __NR_linux_poll //
{__NR_linux_poll, "poll"}, //
#endif //
{__NR_linux_ppoll, "ppoll"}, //
#ifdef __NR_linux_brk //
{__NR_linux_brk, "brk"}, //
#endif //
{__NR_linux_sigreturn, "sigreturn"}, //
{__NR_linux_lseek, "lseek"}, //
{__NR_linux_mmap, "mmap"}, //
{__NR_linux_msync, "msync"}, //
{__NR_linux_mprotect, "mprotect"}, //
{__NR_linux_munmap, "munmap"}, //
{__NR_linux_sigaction, "sigaction"}, //
{__NR_linux_sigprocmask, "sigprocmask"}, //
{__NR_linux_ioctl, "ioctl"}, //
{__NR_linux_pread, "pread"}, //
{__NR_linux_pwrite, "pwrite"}, //
{__NR_linux_readv, "readv"}, //
{__NR_linux_writev, "writev"}, //
#ifdef __NR_linux_access //
{__NR_linux_access, "access"}, //
#endif //
#ifdef __NR_linux_pipe //
{__NR_linux_pipe, "pipe"}, //
#endif //
#ifdef __NR_linux_select //
{__NR_linux_select, "select"}, //
#endif //
{__NR_linux_pselect6, "pselect6"}, //
{__NR_linux_sched_yield, "sched_yield"}, //
{__NR_linux_mremap, "mremap"}, //
{__NR_linux_mincore, "mincore"}, //
{__NR_linux_madvise, "madvise"}, //
{__NR_linux_shmget, "shmget"}, //
{__NR_linux_shmat, "shmat"}, //
{__NR_linux_shmctl, "shmctl"}, //
{__NR_linux_dup, "dup"}, //
#ifdef __NR_linux_dup2 //
{__NR_linux_dup2, "dup2"}, //
#endif //
#ifdef __NR_linux_pause //
{__NR_linux_pause, "pause"}, //
#endif //
{__NR_linux_nanosleep, "nanosleep"}, //
{__NR_linux_getitimer, "getitimer"}, //
{__NR_linux_setitimer, "setitimer"}, //
#ifdef __NR_linux_alarm //
{__NR_linux_alarm, "alarm"}, //
#endif //
{__NR_linux_getpid, "getpid"}, //
{__NR_linux_sendfile, "sendfile"}, //
{__NR_linux_socket, "socket"}, //
{__NR_linux_connect, "connect"}, //
{__NR_linux_accept, "accept"}, //
{__NR_linux_sendto, "sendto"}, //
{__NR_linux_recvfrom, "recvfrom"}, //
{__NR_linux_sendmsg, "sendmsg"}, //
{__NR_linux_recvmsg, "recvmsg"}, //
{__NR_linux_shutdown, "shutdown"}, //
{__NR_linux_bind, "bind"}, //
{__NR_linux_listen, "listen"}, //
{__NR_linux_getsockname, "getsockname"}, //
{__NR_linux_getpeername, "getpeername"}, //
{__NR_linux_socketpair, "socketpair"}, //
{__NR_linux_setsockopt, "setsockopt"}, //
{__NR_linux_getsockopt, "getsockopt"}, //
#ifdef __NR_linux_fork //
{__NR_linux_fork, "fork"}, //
#endif //
#ifdef __NR_linux_vfork //
{__NR_linux_vfork, "vfork"}, //
#endif //
{__NR_linux_execve, "execve"}, //
{__NR_linux_wait4, "wait4"}, //
{__NR_linux_kill, "kill"}, //
{__NR_linux_clone, "clone"}, //
{__NR_linux_tkill, "tkill"}, //
{__NR_linux_futex, "futex"}, //
{__NR_linux_set_robust_list, "set_robust_list"}, //
{__NR_linux_get_robust_list, "get_robust_list"}, //
{__NR_linux_uname, "uname"}, //
{__NR_linux_semget, "semget"}, //
{__NR_linux_semop, "semop"}, //
{__NR_linux_semctl, "semctl"}, //
{__NR_linux_shmdt, "shmdt"}, //
{__NR_linux_msgget, "msgget"}, //
{__NR_linux_msgsnd, "msgsnd"}, //
{__NR_linux_msgrcv, "msgrcv"}, //
{__NR_linux_msgctl, "msgctl"}, //
{__NR_linux_fcntl, "fcntl"}, //
{__NR_linux_flock, "flock"}, //
{__NR_linux_fsync, "fsync"}, //
{__NR_linux_fdatasync, "fdatasync"}, //
{__NR_linux_truncate, "truncate"}, //
{__NR_linux_ftruncate, "ftruncate"}, //
{__NR_linux_getcwd, "getcwd"}, //
{__NR_linux_chdir, "chdir"}, //
{__NR_linux_fchdir, "fchdir"}, //
#ifdef __NR_linux_rename //
{__NR_linux_rename, "rename"}, //
#endif //
#ifdef __NR_linux_mkdir //
{__NR_linux_mkdir, "mkdir"}, //
#endif //
#ifdef __NR_linux_rmdir //
{__NR_linux_rmdir, "rmdir"}, //
#endif //
#ifdef __NR_linux_creat //
{__NR_linux_creat, "creat"}, //
#endif //
#ifdef __NR_linux_link //
{__NR_linux_link, "link"}, //
#endif //
{__NR_linux_unlink, "unlink"}, //
#ifdef __NR_linux_symlink //
{__NR_linux_symlink, "symlink"}, //
#endif //
#ifdef __NR_linux_readlink //
{__NR_linux_readlink, "readlink"}, //
#endif //
#ifdef __NR_linux_chmod //
{__NR_linux_chmod, "chmod"}, //
#endif //
{__NR_linux_fchmod, "fchmod"}, //
#ifdef __NR_linux_chown //
{__NR_linux_chown, "chown"}, //
#endif //
{__NR_linux_fchown, "fchown"}, //
#ifdef __NR_linux_lchown //
{__NR_linux_lchown, "lchown"}, //
#endif //
{__NR_linux_umask, "umask"}, //
{__NR_linux_gettimeofday, "gettimeofday"}, //
{__NR_linux_getrlimit, "getrlimit"}, //
{__NR_linux_getrusage, "getrusage"}, //
{__NR_linux_sysinfo, "sysinfo"}, //
{__NR_linux_times, "times"}, //
{__NR_linux_ptrace, "ptrace"}, //
{__NR_linux_syslog, "syslog"}, //
{__NR_linux_getuid, "getuid"}, //
{__NR_linux_getgid, "getgid"}, //
{__NR_linux_getppid, "getppid"}, //
#ifdef __NR_linux_getpgrp //
{__NR_linux_getpgrp, "getpgrp"}, //
#endif //
{__NR_linux_setsid, "setsid"}, //
{__NR_linux_getsid, "getsid"}, //
{__NR_linux_getpgid, "getpgid"}, //
{__NR_linux_setpgid, "setpgid"}, //
{__NR_linux_geteuid, "geteuid"}, //
{__NR_linux_getegid, "getegid"}, //
{__NR_linux_getgroups, "getgroups"}, //
{__NR_linux_setgroups, "setgroups"}, //
{__NR_linux_setreuid, "setreuid"}, //
{__NR_linux_setregid, "setregid"}, //
{__NR_linux_setuid, "setuid"}, //
{__NR_linux_setgid, "setgid"}, //
{__NR_linux_setresuid, "setresuid"}, //
{__NR_linux_setresgid, "setresgid"}, //
{__NR_linux_getresuid, "getresuid"}, //
{__NR_linux_getresgid, "getresgid"}, //
{__NR_linux_sigpending, "sigpending"}, //
{__NR_linux_sigsuspend, "sigsuspend"}, //
{__NR_linux_sigaltstack, "sigaltstack"}, //
#ifdef __NR_linux_mknod //
{__NR_linux_mknod, "mknod"}, //
#endif //
{__NR_linux_mknodat, "mknodat"}, //
{__NR_linux_statfs, "statfs"}, //
{__NR_linux_fstatfs, "fstatfs"}, //
{__NR_linux_getpriority, "getpriority"}, //
{__NR_linux_setpriority, "setpriority"}, //
{__NR_linux_mlock, "mlock"}, //
{__NR_linux_munlock, "munlock"}, //
{__NR_linux_mlockall, "mlockall"}, //
{__NR_linux_munlockall, "munlockall"}, //
{__NR_linux_setrlimit, "setrlimit"}, //
{__NR_linux_chroot, "chroot"}, //
{__NR_linux_sync, "sync"}, //
{__NR_linux_acct, "acct"}, //
{__NR_linux_settimeofday, "settimeofday"}, //
{__NR_linux_mount, "mount"}, //
{__NR_linux_reboot, "reboot"}, //
{__NR_linux_quotactl, "quotactl"}, //
{__NR_linux_setfsuid, "setfsuid"}, //
{__NR_linux_setfsgid, "setfsgid"}, //
{__NR_linux_capget, "capget"}, //
{__NR_linux_capset, "capset"}, //
{__NR_linux_sigtimedwait, "sigtimedwait"}, //
{__NR_linux_sigqueueinfo, "sigqueueinfo"}, //
{__NR_linux_personality, "personality"}, //
#ifdef __NR_linux_ustat //
{__NR_linux_ustat, "ustat"}, //
#endif //
#ifdef __NR_linux_sysfs //
{__NR_linux_sysfs, "sysfs"}, //
#endif //
{__NR_linux_sched_setparam, "sched_setparam"}, //
{__NR_linux_sched_getparam, "sched_getparam"}, //
{__NR_linux_sched_setscheduler, "sched_setscheduler"}, //
{__NR_linux_sched_getscheduler, "sched_getscheduler"}, //
{__NR_linux_sched_get_priority_max, "sched_get_priority_max"}, //
{__NR_linux_sched_get_priority_min, "sched_get_priority_min"}, //
{__NR_linux_sched_rr_get_interval, "sched_rr_get_interval"}, //
{__NR_linux_vhangup, "vhangup"}, //
#ifdef __NR_linux_modify_ldt //
{__NR_linux_modify_ldt, "modify_ldt"}, //
#endif //
{__NR_linux_pivot_root, "pivot_root"}, //
#ifdef __NR_linux__sysctl //
{__NR_linux__sysctl, "_sysctl"}, //
#endif //
{__NR_linux_prctl, "prctl"}, //
#ifdef __NR_linux_arch_prctl //
{__NR_linux_arch_prctl, "arch_prctl"}, //
#endif //
{__NR_linux_adjtimex, "adjtimex"}, //
{__NR_linux_umount2, "umount2"}, //
{__NR_linux_swapon, "swapon"}, //
{__NR_linux_swapoff, "swapoff"}, //
{__NR_linux_sethostname, "sethostname"}, //
{__NR_linux_setdomainname, "setdomainname"}, //
#ifdef __NR_linux_iopl //
{__NR_linux_iopl, "iopl"}, //
#endif //
#ifdef __NR_linux_ioperm //
{__NR_linux_ioperm, "ioperm"}, //
#endif //
{__NR_linux_init_module, "init_module"}, //
{__NR_linux_delete_module, "delete_module"}, //
{__NR_linux_gettid, "gettid"}, //
{__NR_linux_readahead, "readahead"}, //
{__NR_linux_setxattr, "setxattr"}, //
{__NR_linux_fsetxattr, "fsetxattr"}, //
{__NR_linux_getxattr, "getxattr"}, //
{__NR_linux_fgetxattr, "fgetxattr"}, //
{__NR_linux_listxattr, "listxattr"}, //
{__NR_linux_flistxattr, "flistxattr"}, //
{__NR_linux_removexattr, "removexattr"}, //
{__NR_linux_fremovexattr, "fremovexattr"}, //
{__NR_linux_lsetxattr, "lsetxattr"}, //
{__NR_linux_lgetxattr, "lgetxattr"}, //
{__NR_linux_llistxattr, "llistxattr"}, //
{__NR_linux_lremovexattr, "lremovexattr"}, //
{__NR_linux_sched_setaffinity, "sched_setaffinity"}, //
{__NR_linux_sched_getaffinity, "sched_getaffinity"}, //
{__NR_linux_io_setup, "io_setup"}, //
{__NR_linux_io_destroy, "io_destroy"}, //
{__NR_linux_io_getevents, "io_getevents"}, //
{__NR_linux_io_submit, "io_submit"}, //
{__NR_linux_io_cancel, "io_cancel"}, //
{__NR_linux_lookup_dcookie, "lookup_dcookie"}, //
#ifdef __NR_linux_epoll_create //
{__NR_linux_epoll_create, "epoll_create"}, //
#endif //
#ifdef __NR_linux_epoll_wait //
{__NR_linux_epoll_wait, "epoll_wait"}, //
#endif //
{__NR_linux_epoll_ctl, "epoll_ctl"}, //
{__NR_linux_getdents, "getdents"}, //
#ifdef __NR_linux_oldgetdents //
{__NR_linux_oldgetdents, "oldgetdents"}, //
#endif //
{__NR_linux_set_tid_address, "set_tid_address"}, //
{__NR_linux_restart_syscall, "restart_syscall"}, //
{__NR_linux_semtimedop, "semtimedop"}, //
{__NR_linux_fadvise, "fadvise"}, //
{__NR_linux_timer_create, "timer_create"}, //
{__NR_linux_timer_settime, "timer_settime"}, //
{__NR_linux_timer_gettime, "timer_gettime"}, //
{__NR_linux_timer_getoverrun, "timer_getoverrun"}, //
{__NR_linux_timer_delete, "timer_delete"}, //
{__NR_linux_clock_settime, "clock_settime"}, //
{__NR_linux_clock_gettime, "clock_gettime"}, //
{__NR_linux_clock_getres, "clock_getres"}, //
{__NR_linux_clock_nanosleep, "clock_nanosleep"}, //
{__NR_linux_tgkill, "tgkill"}, //
{__NR_linux_mbind, "mbind"}, //
{__NR_linux_set_mempolicy, "set_mempolicy"}, //
{__NR_linux_get_mempolicy, "get_mempolicy"}, //
{__NR_linux_mq_open, "mq_open"}, //
{__NR_linux_mq_unlink, "mq_unlink"}, //
{__NR_linux_mq_timedsend, "mq_timedsend"}, //
{__NR_linux_mq_timedreceive, "mq_timedreceive"}, //
{__NR_linux_mq_notify, "mq_notify"}, //
{__NR_linux_mq_getsetattr, "mq_getsetattr"}, //
{__NR_linux_kexec_load, "kexec_load"}, //
{__NR_linux_waitid, "waitid"}, //
{__NR_linux_add_key, "add_key"}, //
{__NR_linux_request_key, "request_key"}, //
{__NR_linux_keyctl, "keyctl"}, //
{__NR_linux_ioprio_set, "ioprio_set"}, //
{__NR_linux_ioprio_get, "ioprio_get"}, //
#ifdef __NR_linux_inotify_init //
{__NR_linux_inotify_init, "inotify_init"}, //
#endif //
#ifdef __NR_linux_inotify_add_watch //
{__NR_linux_inotify_add_watch, "inotify_add_watch"}, //
#endif //
#ifdef __NR_linux_inotify_rm_watch //
{__NR_linux_inotify_rm_watch, "inotify_rm_watch"}, //
#endif //
{__NR_linux_openat, "openat"}, //
{__NR_linux_mkdirat, "mkdirat"}, //
{__NR_linux_fchownat, "fchownat"}, //
{__NR_linux_utime, "utime"}, //
{__NR_linux_utimes, "utimes"}, //
#ifdef __NR_linux_futimesat //
{__NR_linux_futimesat, "futimesat"}, //
#endif //
{__NR_linux_fstatat, "fstatat"}, //
{__NR_linux_unlinkat, "unlinkat"}, //
{__NR_linux_renameat, "renameat"}, //
{__NR_linux_linkat, "linkat"}, //
{__NR_linux_symlinkat, "symlinkat"}, //
{__NR_linux_readlinkat, "readlinkat"}, //
{__NR_linux_fchmodat, "fchmodat"}, //
{__NR_linux_faccessat, "faccessat"}, //
{__NR_linux_unshare, "unshare"}, //
{__NR_linux_splice, "splice"}, //
{__NR_linux_tee, "tee"}, //
{__NR_linux_sync_file_range, "sync_file_range"}, //
{__NR_linux_vmsplice, "vmsplice"}, //
{__NR_linux_migrate_pages, "migrate_pages"}, //
{__NR_linux_move_pages, "move_pages"}, //
{__NR_linux_preadv, "preadv"}, //
{__NR_linux_pwritev, "pwritev"}, //
{__NR_linux_utimensat, "utimensat"}, //
{__NR_linux_fallocate, "fallocate"}, //
{__NR_linux_accept4, "accept4"}, //
{__NR_linux_dup3, "dup3"}, //
{__NR_linux_pipe2, "pipe2"}, //
{__NR_linux_epoll_pwait, "epoll_pwait"}, //
{__NR_linux_epoll_create1, "epoll_create1"}, //
{__NR_linux_perf_event_open, "perf_event_open"}, //
{__NR_linux_inotify_init1, "inotify_init1"}, //
{__NR_linux_tgsigqueueinfo, "tgsigqueueinfo"}, //
#ifdef __NR_linux_signalfd //
{__NR_linux_signalfd, "signalfd"}, //
#endif //
{__NR_linux_signalfd4, "signalfd4"}, //
#ifdef __NR_linux_eventfd //
{__NR_linux_eventfd, "eventfd"}, //
#endif //
{__NR_linux_eventfd2, "eventfd2"}, //
{__NR_linux_timerfd_create, "timerfd_create"}, //
{__NR_linux_timerfd_settime, "timerfd_settime"}, //
{__NR_linux_timerfd_gettime, "timerfd_gettime"}, //
{__NR_linux_recvmmsg, "recvmmsg"}, //
{__NR_linux_fanotify_init, "fanotify_init"}, //
{__NR_linux_fanotify_mark, "fanotify_mark"}, //
{__NR_linux_prlimit, "prlimit"}, //
{__NR_linux_name_to_handle_at, "name_to_handle_at"}, //
{__NR_linux_open_by_handle_at, "open_by_handle_at"}, //
{__NR_linux_clock_adjtime, "clock_adjtime"}, //
{__NR_linux_syncfs, "syncfs"}, //
{__NR_linux_sendmmsg, "sendmmsg"}, //
{__NR_linux_setns, "setns"}, //
{__NR_linux_getcpu, "getcpu"}, //
{__NR_linux_process_vm_readv, "process_vm_readv"}, //
{__NR_linux_process_vm_writev, "process_vm_writev"}, //
{__NR_linux_kcmp, "kcmp"}, //
{__NR_linux_finit_module, "finit_module"}, //
{__NR_linux_sched_setattr, "sched_setattr"}, //
{__NR_linux_sched_getattr, "sched_getattr"}, //
{__NR_linux_renameat2, "renameat2"}, //
{__NR_linux_seccomp, "seccomp"}, //
{__NR_linux_getrandom, "getrandom"}, //
{__NR_linux_memfd_create, "memfd_create"}, //
{__NR_linux_kexec_file_load, "kexec_file_load"}, //
{__NR_linux_bpf, "bpf"}, //
{__NR_linux_execveat, "execveat"}, //
{__NR_linux_userfaultfd, "userfaultfd"}, //
{__NR_linux_membarrier, "membarrier"}, //
{__NR_linux_mlock2, "mlock2"}, //
{__NR_linux_copy_file_range, "copy_file_range"}, //
{__NR_linux_preadv2, "preadv2"}, //
{__NR_linux_pwritev2, "pwritev2"}, //
{__NR_linux_pkey_mprotect, "pkey_mprotect"}, //
{__NR_linux_pkey_alloc, "pkey_alloc"}, //
{__NR_linux_pkey_free, "pkey_free"}, //
{__NR_linux_statx, "statx"}, //
{__NR_linux_io_pgetevents, "io_pgetevents"}, //
{__NR_linux_rseq, "rseq"}, //
{__NR_linux_pidfd_send_signal, "pidfd_send_signal"}, //
{__NR_linux_io_uring_setup, "io_uring_setup"}, //
{__NR_linux_io_uring_enter, "io_uring_enter"}, //
{__NR_linux_io_uring_register, "io_uring_register"}, //
{__NR_linux_open_tree, "open_tree"}, //
{__NR_linux_move_mount, "move_mount"}, //
{__NR_linux_fsopen, "fsopen"}, //
{__NR_linux_fsconfig, "fsconfig"}, //
{__NR_linux_fsmount, "fsmount"}, //
{__NR_linux_fspick, "fspick"}, //
{__NR_linux_pidfd_open, "pidfd_open"}, //
{__NR_linux_clone3, "clone3"}, //
{__NR_linux_close_range, "close_range"}, //
{__NR_linux_openat2, "openat2"}, //
{__NR_linux_pidfd_getfd, "pidfd_getfd"}, //
{__NR_linux_faccessat2, "faccessat2"}, //
{__NR_linux_process_madvise, "process_madvise"}, //
{__NR_linux_epoll_pwait2, "epoll_pwait2"}, //
{__NR_linux_mount_setattr, "mount_setattr"}, //
#ifdef __NR_linux_quotactl_fd //
{__NR_linux_quotactl_fd, "quotactl_fd"}, //
#endif //
{__NR_linux_landlock_create_ruleset, "landlock_create_ruleset"}, //
{__NR_linux_landlock_add_rule, "landlock_add_rule"}, //
{__NR_linux_landlock_restrict_self, "landlock_restrict_self"}, //
#ifdef __NR_linux_memfd_secret //
{__NR_linux_memfd_secret, "memfd_secret"}, //
#endif //
#ifdef __NR_linux_process_mrelease //
{__NR_linux_process_mrelease, "process_mrelease"}, //
#endif //
#ifdef __NR_linux_futex_waitv //
{__NR_linux_futex_waitv, "futex_waitv"}, //
#endif //
#ifdef __NR_linux_set_mempolicy_home_node //
{__NR_linux_set_mempolicy_home_node, "set_mempolicy_home_node"}, //
#endif //
};
static const uint16_t kPledgeDefault[] = {
__NR_linux_exit, // thread return / exit()
};
// stdio contains all the benign system calls. openbsd makes the
// assumption that preexisting file descriptors are trustworthy. we
// implement checking for these as a simple linear scan rather than
// binary search, since there doesn't appear to be any measurable
// difference in the latency of sched_yield() if it's at the start of
// the bpf script or the end.
static const uint16_t kPledgeStdio[] = {
__NR_linux_sigreturn, //
__NR_linux_restart_syscall, //
__NR_linux_exit_group, //
__NR_linux_sched_yield, //
__NR_linux_sched_getaffinity, //
__NR_linux_clock_getres, //
__NR_linux_clock_gettime, //
__NR_linux_clock_nanosleep, //
__NR_linux_close_range, //
__NR_linux_close, //
__NR_linux_write, //
__NR_linux_writev, //
__NR_linux_pwrite, //
__NR_linux_pwritev, //
__NR_linux_pwritev2, //
__NR_linux_read, //
__NR_linux_readv, //
__NR_linux_pread, //
__NR_linux_preadv, //
__NR_linux_preadv2, //
__NR_linux_dup, //
#ifdef __NR_linux_dup2 //
__NR_linux_dup2, //
#endif //
__NR_linux_dup3, //
__NR_linux_fchdir, //
__NR_linux_fcntl | STDIO, //
__NR_linux_fstat, //
__NR_linux_fsync, //
__NR_linux_sysinfo, //
__NR_linux_fdatasync, //
__NR_linux_ftruncate, //
__NR_linux_getrandom, //
__NR_linux_getgroups, //
__NR_linux_getpgid, //
#ifdef __NR_linux_getpgrp //
__NR_linux_getpgrp, //
#endif //
__NR_linux_getpid, //
__NR_linux_gettid, //
__NR_linux_getuid, //
__NR_linux_getgid, //
__NR_linux_getsid, //
__NR_linux_getppid, //
__NR_linux_geteuid, //
__NR_linux_getegid, //
__NR_linux_getrlimit, //
__NR_linux_getresgid, //
__NR_linux_getresuid, //
__NR_linux_getitimer, //
__NR_linux_setitimer, //
__NR_linux_timerfd_create, //
__NR_linux_timerfd_settime, //
__NR_linux_timerfd_gettime, //
__NR_linux_copy_file_range, //
__NR_linux_gettimeofday, //
__NR_linux_sendfile, //
__NR_linux_vmsplice, //
__NR_linux_splice, //
__NR_linux_lseek, //
__NR_linux_tee, //
#ifdef __NR_linux_brk //
__NR_linux_brk, //
#endif //
__NR_linux_msync, //
__NR_linux_mmap | NOEXEC, //
__NR_linux_mlock, //
__NR_linux_mremap, //
__NR_linux_munmap, //
__NR_linux_mincore, //
__NR_linux_madvise, //
__NR_linux_fadvise, //
__NR_linux_mprotect | NOEXEC, //
#ifdef __NR_linux_arch_prctl //
__NR_linux_arch_prctl, //
#endif //
__NR_linux_migrate_pages, //
__NR_linux_sync_file_range, //
__NR_linux_set_tid_address, //
__NR_linux_membarrier, //
__NR_linux_nanosleep, //
#ifdef __NR_linux_pipe //
__NR_linux_pipe, //
#endif //
__NR_linux_pipe2, //
#ifdef __NR_linux_poll //
__NR_linux_poll, //
#endif //
__NR_linux_ppoll, //
#ifdef __NR_linux_select //
__NR_linux_select, //
#endif //
__NR_linux_pselect6, //
#ifdef __NR_linux_epoll_create //
__NR_linux_epoll_create, //
#endif //
__NR_linux_epoll_create1, //
__NR_linux_epoll_ctl, //
#ifdef __NR_linux_epoll_wait //
__NR_linux_epoll_wait, //
#endif //
__NR_linux_epoll_pwait, //
__NR_linux_epoll_pwait2, //
__NR_linux_recvfrom, //
__NR_linux_sendto | ADDRLESS, //
__NR_linux_ioctl | RESTRICT, //
#ifdef __NR_linux_alarm //
__NR_linux_alarm, //
#endif //
#ifdef __NR_linux_pause //
__NR_linux_pause, //
#endif //
__NR_linux_shutdown, //
#ifdef __NR_linux_eventfd //
__NR_linux_eventfd, //
#endif //
__NR_linux_eventfd2, //
#ifdef __NR_linux_signalfd //
__NR_linux_signalfd, //
#endif //
__NR_linux_signalfd4, //
__NR_linux_sigaction, //
__NR_linux_sigaltstack, //
__NR_linux_sigprocmask, //
__NR_linux_sigsuspend, //
__NR_linux_sigpending, //
__NR_linux_kill | SELF, //
__NR_linux_tkill, //
__NR_linux_tgkill | SELF, //
__NR_linux_socketpair, //
__NR_linux_getrusage, //
__NR_linux_times, //
__NR_linux_umask, //
__NR_linux_wait4, //
__NR_linux_uname, //
__NR_linux_prctl | STDIO, //
__NR_linux_clone | THREAD, //
__NR_linux_futex, //
__NR_linux_set_robust_list, //
__NR_linux_get_robust_list, //
__NR_linux_prlimit | STDIO, //
__NR_linux_sched_getaffinity, //
__NR_linux_sched_setaffinity, //
__NR_linux_sigtimedwait, //
};
static const uint16_t kPledgeFlock[] = {
__NR_linux_flock, //
__NR_linux_fcntl | LOCK, //
};
static const uint16_t kPledgeRpath[] = {
__NR_linux_chdir, //
__NR_linux_getcwd, //
__NR_linux_open | READONLY, //
__NR_linux_openat | READONLY, //
__NR_linux_stat, //
#ifdef __NR_linux_lstat //
__NR_linux_lstat, //
#endif //
__NR_linux_fstat, //
__NR_linux_fstatat, //
#ifdef __NR_linux_access //
__NR_linux_access, //
#endif //
__NR_linux_faccessat, //
__NR_linux_faccessat2, //
#ifdef __NR_linux_readlink //
__NR_linux_readlink, //
#endif //
__NR_linux_readlinkat, //
__NR_linux_statfs, //
__NR_linux_fstatfs, //
__NR_linux_getdents, //
#ifdef __NR_linux_oldgetdents //
__NR_linux_oldgetdents, //
#endif //
};
static const uint16_t kPledgeWpath[] = {
__NR_linux_getcwd, //
__NR_linux_open | WRITEONLY, //
__NR_linux_openat | WRITEONLY, //
__NR_linux_stat, //
__NR_linux_fstat, //
#ifdef __NR_linux_lstat //
__NR_linux_lstat, //
#endif //
__NR_linux_fstatat, //
#ifdef __NR_linux_access //
__NR_linux_access, //
#endif //
__NR_linux_truncate, //
__NR_linux_faccessat, //
__NR_linux_faccessat2, //
__NR_linux_readlinkat, //
#ifdef __NR_linux_chmod //
__NR_linux_chmod | NOBITS, //
#endif //
__NR_linux_fchmod | NOBITS, //
__NR_linux_fchmodat | NOBITS, //
};
static const uint16_t kPledgeCpath[] = {
__NR_linux_open | CREATONLY, //
__NR_linux_openat | CREATONLY, //
#ifdef __NR_linux_creat //
__NR_linux_creat | RESTRICT, //
#endif //
#ifdef __NR_linux_rename //
__NR_linux_rename, //
#endif //
__NR_linux_renameat, //
__NR_linux_renameat2, //
#ifdef __NR_linux_link //
__NR_linux_link, //
#endif //
__NR_linux_linkat, //
#ifdef __NR_linux_symlink //
__NR_linux_symlink, //
#endif //
__NR_linux_symlinkat, //
#ifdef __NR_linux_rmdir //
__NR_linux_rmdir, //
#endif //
__NR_linux_unlink, //
__NR_linux_unlinkat, //
#ifdef __NR_linux_mkdir //
__NR_linux_mkdir, //
#endif //
__NR_linux_mkdirat, //
};
static const uint16_t kPledgeDpath[] = {
#ifdef __NR_linux_mknod //
__NR_linux_mknod, //
#endif //
__NR_linux_mknodat, //
};
static const uint16_t kPledgeFattr[] = {
#ifdef __NR_linux_chmod //
__NR_linux_chmod | NOBITS, //
#endif //
__NR_linux_fchmod | NOBITS, //
__NR_linux_fchmodat | NOBITS, //
__NR_linux_utime, //
__NR_linux_utimes, //
#ifdef __NR_linux_futimesat //
__NR_linux_futimesat, //
#endif //
__NR_linux_utimensat, //
};
static const uint16_t kPledgeInet[] = {
__NR_linux_socket | INET, //
__NR_linux_listen, //
__NR_linux_bind, //
__NR_linux_sendto, //
__NR_linux_connect, //
__NR_linux_accept, //
__NR_linux_accept4, //
__NR_linux_ioctl | INET, //
__NR_linux_getsockopt | RESTRICT, //
__NR_linux_setsockopt | RESTRICT, //
__NR_linux_getpeername, //
__NR_linux_getsockname, //
};
// anet is similar to init, but without connect;
// this allows to accept, but not initiate socket connections
static const uint16_t kPledgeAnet[] = {
__NR_linux_socket | INET, //
__NR_linux_listen, //
__NR_linux_bind, //
__NR_linux_sendto, //
__NR_linux_accept, //
__NR_linux_accept4, //
__NR_linux_ioctl | INET, //
__NR_linux_getsockopt | RESTRICT, //
__NR_linux_setsockopt | RESTRICT, //
__NR_linux_getpeername, //
__NR_linux_getsockname, //
};
static const uint16_t kPledgeUnix[] = {
__NR_linux_socket | UNIX, //
__NR_linux_listen, //
__NR_linux_bind, //
__NR_linux_connect, //
__NR_linux_sendto, //
__NR_linux_accept, //
__NR_linux_accept4, //
__NR_linux_getsockopt | RESTRICT, //
__NR_linux_setsockopt | RESTRICT, //
__NR_linux_getpeername, //
__NR_linux_getsockname, //
};
static const uint16_t kPledgeDns[] = {
__NR_linux_socket | INET, //
__NR_linux_bind, //
__NR_linux_sendto, //
__NR_linux_connect, //
__NR_linux_recvfrom, //
__NR_linux_setsockopt | RESTRICT, //
__NR_linux_fstatat, //
__NR_linux_openat | READONLY, //
__NR_linux_read, //
__NR_linux_close, //
};
static const uint16_t kPledgeTty[] = {
__NR_linux_ioctl | TTY, //
};
static const uint16_t kPledgeRecvfd[] = {
__NR_linux_recvmsg, //
__NR_linux_recvmmsg, //
};
static const uint16_t kPledgeSendfd[] = {
__NR_linux_sendmsg, //
__NR_linux_sendmmsg, //
};
static const uint16_t kPledgeProc[] = {
#ifdef __NR_linux_fork //
__NR_linux_fork, //
#endif //
#ifdef __NR_linux_vfork //
__NR_linux_vfork, //
#endif //
__NR_linux_clone | RESTRICT, //
__NR_linux_kill, //
__NR_linux_tgkill, //
__NR_linux_setsid, //
__NR_linux_setpgid, //
__NR_linux_prlimit, //
__NR_linux_setrlimit, //
__NR_linux_getpriority, //
__NR_linux_setpriority, //
__NR_linux_ioprio_get, //
__NR_linux_ioprio_set, //
__NR_linux_sched_getscheduler, //
__NR_linux_sched_setscheduler, //
__NR_linux_sched_get_priority_min, //
__NR_linux_sched_get_priority_max, //
__NR_linux_sched_getparam, //
__NR_linux_sched_setparam, //
};
static const uint16_t kPledgeId[] = {
__NR_linux_setuid, //
__NR_linux_setreuid, //
__NR_linux_setresuid, //
__NR_linux_setgid, //
__NR_linux_setregid, //
__NR_linux_setresgid, //
__NR_linux_setgroups, //
__NR_linux_prlimit, //
__NR_linux_setrlimit, //
__NR_linux_getpriority, //
__NR_linux_setpriority, //
__NR_linux_setfsuid, //
__NR_linux_setfsgid, //
};
static const uint16_t kPledgeChown[] = {
#ifdef __NR_linux_chown //
__NR_linux_chown, //
#endif //
__NR_linux_fchown, //
#ifdef __NR_linux_lchown //
__NR_linux_lchown, //
#endif //
__NR_linux_fchownat, //
};
static const uint16_t kPledgeSettime[] = {
__NR_linux_settimeofday, //
__NR_linux_clock_adjtime, //
};
static const uint16_t kPledgeProtExec[] = {
__NR_linux_mmap | EXEC, //
__NR_linux_mprotect, //
};
static const uint16_t kPledgeExec[] = {
__NR_linux_execve, //
__NR_linux_execveat, //
};
static const uint16_t kPledgeUnveil[] = {
__NR_linux_landlock_create_ruleset, //
__NR_linux_landlock_add_rule, //
__NR_linux_landlock_restrict_self, //
};
// placeholder group
//
// pledge.com checks this to do auto-unveiling
static const uint16_t kPledgeVminfo[] = {
__NR_linux_sched_yield, //
};
// placeholder group
//
// pledge.com uses this to auto-unveil /tmp and $TMPPATH with rwc
// permissions. pledge() alone (without unveil() too) offers very
// little security here. consider using them together.
static const uint16_t kPledgeTmppath[] = {
#ifdef __NR_linux_lstat //
__NR_linux_lstat, //
#endif //
__NR_linux_unlink, //
__NR_linux_unlinkat, //
};
const struct Pledges kPledge[PROMISE_LEN_] = {
[PROMISE_STDIO] = {"stdio", PLEDGE(kPledgeStdio)}, //
[PROMISE_RPATH] = {"rpath", PLEDGE(kPledgeRpath)}, //
[PROMISE_WPATH] = {"wpath", PLEDGE(kPledgeWpath)}, //
[PROMISE_CPATH] = {"cpath", PLEDGE(kPledgeCpath)}, //
[PROMISE_DPATH] = {"dpath", PLEDGE(kPledgeDpath)}, //
[PROMISE_FLOCK] = {"flock", PLEDGE(kPledgeFlock)}, //
[PROMISE_FATTR] = {"fattr", PLEDGE(kPledgeFattr)}, //
[PROMISE_INET] = {"inet", PLEDGE(kPledgeInet)}, //
[PROMISE_ANET] = {"anet", PLEDGE(kPledgeAnet)}, //
[PROMISE_UNIX] = {"unix", PLEDGE(kPledgeUnix)}, //
[PROMISE_DNS] = {"dns", PLEDGE(kPledgeDns)}, //
[PROMISE_TTY] = {"tty", PLEDGE(kPledgeTty)}, //
[PROMISE_RECVFD] = {"recvfd", PLEDGE(kPledgeRecvfd)}, //
[PROMISE_SENDFD] = {"sendfd", PLEDGE(kPledgeSendfd)}, //
[PROMISE_PROC] = {"proc", PLEDGE(kPledgeProc)}, //
[PROMISE_EXEC] = {"exec", PLEDGE(kPledgeExec)}, //
[PROMISE_ID] = {"id", PLEDGE(kPledgeId)}, //
[PROMISE_UNVEIL] = {"unveil", PLEDGE(kPledgeUnveil)}, //
[PROMISE_SETTIME] = {"settime", PLEDGE(kPledgeSettime)}, //
[PROMISE_PROT_EXEC] = {"prot_exec", PLEDGE(kPledgeProtExec)}, //
[PROMISE_VMINFO] = {"vminfo", PLEDGE(kPledgeVminfo)}, //
[PROMISE_TMPPATH] = {"tmppath", PLEDGE(kPledgeTmppath)}, //
[PROMISE_CHOWN] = {"chown", PLEDGE(kPledgeChown)}, //
};
static const struct sock_filter kPledgeStart[] = {
// make sure this isn't an i386 binary or something
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ARCHITECTURE, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
// each filter assumes ordinal is already loaded into accumulator
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
#ifdef __NR_linux_memfd_secret
// forbid some system calls with ENOSYS (rather than EPERM)
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_linux_memfd_secret, 5, 0),
#else
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_linux_landlock_restrict_self + 1,
5, 0),
#endif
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_rseq, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_memfd_create, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_openat2, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_clone3, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_statx, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (Enosys & SECCOMP_RET_DATA)),
};
static const struct sock_filter kFilterIgnoreExitGroup[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_exit_group, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (Eperm & SECCOMP_RET_DATA)),
};
static privileged unsigned long StrLen(const char *s) {
unsigned long n = 0;
while (*s++) ++n;
return n;
}
static privileged void *MemCpy(void *d, const void *s, unsigned long n) {
unsigned long i = 0;
for (; i < n; ++i) ((char *)d)[i] = ((char *)s)[i];
return (char *)d + n;
}
static privileged char *FixCpy(char p[17], uint64_t x, int k) {
while (k > 0) *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15];
*p = '\0';
return p;
}
static privileged char *HexCpy(char p[17], uint64_t x) {
return FixCpy(p, x, ROUNDUP(x ? _bsrl(x) + 1 : 1, 4));
}
static privileged int GetPid(void) {
int res;
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_getpid)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_getpid)
: "x8", "memory");
res = res_x0;
#endif
return res;
}
static privileged int GetTid(void) {
int res;
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_gettid)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_gettid)
: "x8", "memory");
res = res_x0;
#endif
return res;
}
static privileged void Log(const char *s, ...) {
int res;
va_list va;
va_start(va, s);
do {
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_write), "D"(2), "S"(s), "d"(StrLen(s))
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
register long r0 asm("x0") = 2;
register long r1 asm("x1") = (long)s;
register long r2 asm("x2") = StrLen(s);
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_write), "r"(r0), "r"(r1), "r"(r2)
: "x8", "memory");
#endif
} while ((s = va_arg(va, const char *)));
va_end(va);
}
static privileged int SigAction(int sig, struct sigaction *act,
struct sigaction *old) {
int res;
act->sa_flags |= Sa_Restorer;
act->sa_restorer = &__restore_rt;
#ifdef __x86_64__
asm volatile("mov\t%5,%%r10\n\t"
"syscall"
: "=a"(res)
: "0"(__NR_linux_sigaction), "D"(sig), "S"(act), "d"(old), "g"(8)
: "rcx", "r10", "r11", "memory");
#elif defined(__aarch64__)
register long r0 asm("x0") = (long)sig;
register long r1 asm("x1") = (long)act;
register long r2 asm("x2") = (long)old;
register long r3 asm("x3") = (long)8;
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_sigaction), "r"(r0), "r"(r1), "r"(r2), "r"(r3)
: "x8", "memory");
res = res_x0;
#endif
return res;
}
static privileged int SigProcMask(int how, int64_t set, int64_t *old) {
int res;
#ifdef __x86_64__
asm volatile("mov\t%5,%%r10\n\t"
"syscall"
: "=a"(res)
: "0"(__NR_linux_sigprocmask), "D"(how), "S"(&set), "d"(old),
"g"(8)
: "rcx", "r10", "r11", "memory");
#elif defined(__aarch64__)
register long r0 asm("x0") = (long)how;
register long r1 asm("x1") = (long)set;
register long r2 asm("x2") = (long)old;
register long r3 asm("x3") = (long)8;
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_sigprocmask), "r"(r0), "r"(r1), "r"(r2), "r"(r3)
: "x8", "memory");
res = res_x0;
#endif
return res;
}
static privileged void KillThisProcess(void) {
int res;
SigAction(Sigabrt, &(struct sigaction){0}, 0);
SigProcMask(Sig_Setmask, -1, 0);
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_kill), "D"(GetPid()), "S"(Sigabrt)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
{
register long r0 asm("x0") = (long)GetPid();
register long r1 asm("x1") = (long)Sigabrt;
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_kill), "r"(r0), "r"(r1)
: "x8", "memory");
}
#endif
SigProcMask(Sig_Setmask, 0, 0);
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_exit_group), "D"(128 + Sigabrt)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
{
register long r0 asm("x0") = (long)(128 + Sigabrt);
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_exit_group), "r"(r0)
: "x8", "memory");
}
#endif
}
static privileged void KillThisThread(void) {
int res;
SigAction(Sigabrt, &(struct sigaction){0}, 0);
SigProcMask(Sig_Setmask, -1, 0);
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(res)
: "0"(__NR_linux_tkill), "D"(GetTid()), "S"(Sigabrt)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
#endif
SigProcMask(Sig_Setmask, 0, 0);
#ifdef __x86_64__
asm volatile("syscall"
: /* no outputs */
: "a"(__NR_linux_exit), "D"(128 + Sigabrt)
: "rcx", "r11", "memory");
#elif defined(__aarch64__)
register long r0 asm("x0") = (long)(128 + Sigabrt);
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(__NR_linux_exit), "r"(r0)
: "x8", "memory");
#endif
}
static privileged const char *GetSyscallName(uint16_t n) {
int i;
for (i = 0; i < ARRAYLEN(kSyscallName); ++i) {
if (kSyscallName[i].n == n) {
return kSyscallName[i].s;
}
}
return "unknown";
}
static privileged int HasSyscall(struct Pledges *p, uint16_t n) {
int i;
for (i = 0; i < p->len; ++i) {
if (p->syscalls[i] == n) {
return 1;
}
if ((p->syscalls[i] & 0xfff) == n) {
return 2;
}
}
return 0;
}
static privileged void OnSigSys(int sig, siginfo_t *si, void *vctx) {
bool found;
char ord[17];
int i, ok, mode = si->si_errno;
ucontext_t *ctx = vctx;
ctx->uc_mcontext.MCONTEXT_SYSCALL_RESULT_REGISTER = -Eperm;
FixCpy(ord, si->si_syscall, 12);
for (found = i = 0; i < ARRAYLEN(kPledge); ++i) {
if (HasSyscall(kPledge + i, si->si_syscall)) {
Log("error: protected syscall ", GetSyscallName(si->si_syscall),
" (ord=", ord, "); pledge promise '", kPledge[i].name, "' to allow\n",
NULL);
found = true;
}
}
if (!found) {
Log("error: bad syscall ", GetSyscallName(si->si_syscall),
" (ord=", ord, ")\n", NULL);
}
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_PROCESS:
KillThisProcess();
// fallthrough
case PLEDGE_PENALTY_KILL_THREAD:
KillThisThread();
notpossible;
default:
break;
}
}
static privileged void MonitorSigSys(void) {
struct sigaction sa = {
.sa_sigaction = OnSigSys,
.sa_flags = Sa_Siginfo | Sa_Restart,
};
// we block changing sigsys once pledge is installed
// so we aren't terribly concerned if this will fail
if (SigAction(Sigsys, &sa, 0) == -1) {
notpossible;
}
}
static privileged void AppendFilter(struct Filter *f, struct sock_filter *p,
size_t n) {
if (UNLIKELY(f->n + n > ARRAYLEN(f->p))) notpossible;
MemCpy(f->p + f->n, p, n * sizeof(*f->p));
f->n += n;
}
// The first argument of kill() must be
//
// - getpid()
//
static privileged void AllowKillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_kill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, GetPid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of tgkill() must be
//
// - getpid()
//
static privileged void AllowTgkillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_tgkill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, GetPid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The following system calls are allowed:
//
// - write(2) to allow logging
// - kill(getpid(), SIGABRT) to abort process
// - tkill(gettid(), SIGABRT) to abort thread
// - sigaction(SIGABRT) to force default signal handler
// - sigreturn() to return from signal handler
// - sigprocmask() to force signal delivery
//
static privileged void AllowMonitor(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_write, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_kill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, GetPid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, Sigabrt, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_tkill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, GetTid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, Sigabrt, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_sigaction, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, Sigabrt, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_sigreturn, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_sigprocmask, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
}
// SYSCALL is only allowed in the .privileged section
// We assume program image is loaded in 32-bit spaces
static privileged void AppendOriginVerification(struct Filter *f) {
long x = (long)__privileged_start;
long y = (long)__privileged_end;
struct sock_filter fragment[] = {
/*L0*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(instruction_pointer) + 4),
/*L1*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 5 - 2),
/*L2*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(instruction_pointer)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, x, 0, 5 - 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, y, 0, 6 - 5),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static privileged void AllowCloneRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_clone, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x00822000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must have:
//
// - CLONE_VM (0x00000100)
// - CLONE_FS (0x00000200)
// - CLONE_FILES (0x00000400)
// - CLONE_THREAD (0x00010000)
// - CLONE_SIGHAND (0x00000800)
//
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static privileged void AllowCloneThread(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_clone, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x00010f00),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x00010f00, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x00822000),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - FIONREAD (0x541b)
// - FIONBIO (0x5421)
// - FIOCLEX (0x5451)
// - FIONCLEX (0x5450)
//
static privileged void AllowIoctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_ioctl, 0, 7),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x541b, 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5421, 2, 0),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5451, 1, 0),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5450, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - SIOCATMARK (0x8905)
//
static privileged void AllowIoctlInet(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_ioctl, 0, 4),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x8905, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - TCGETS (0x5401)
// - TCSETS (0x5402)
// - TCSETSW (0x5403)
// - TCSETSF (0x5404)
// - TIOCGWINSZ (0x5413)
// - TIOCSPGRP (0x5410)
// - TIOCGPGRP (0x540f)
// - TIOCSWINSZ (0x5414)
// - TCFLSH (0x540b)
// - TCXONC (0x540a)
// - TCSBRK (0x5409)
// - TIOCSBRK (0x5427)
//
static privileged void AllowIoctlTty(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_ioctl, 0, 15),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5401, 11, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5402, 10, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5403, 9, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5404, 8, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5413, 7, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5410, 6, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x540f, 5, 0),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5414, 4, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x540b, 3, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x540a, 2, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5409, 1, 0),
/*L13*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x5427, 0, 1),
/*L14*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L15*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L16*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The level argument of setsockopt() must be one of:
//
// - SOL_IP (0)
// - SOL_SOCKET (1)
// - SOL_TCP (6)
// - SOL_IPV6 (41)
//
// The optname argument of setsockopt() must be one of:
//
// - TCP_NODELAY (0x01)
// - TCP_CORK (0x03)
// - TCP_KEEPIDLE (0x04)
// - TCP_KEEPINTVL (0x05)
// - SO_TYPE (0x03)
// - SO_ERROR (0x04)
// - SO_DONTROUTE (0x05)
// - SO_BROADCAST (0x06)
// - SO_REUSEPORT (0x0f)
// - SO_REUSEADDR (0x02)
// - SO_KEEPALIVE (0x09)
// - SO_RCVTIMEO (0x14)
// - SO_SNDTIMEO (0x15)
// - IP_RECVTTL (0x0c)
// - IP_RECVERR (0x0b)
// - TCP_FASTOPEN (0x17)
// - TCP_FASTOPEN_CONNECT (0x1e)
// - IPV6_V6ONLY (0x1a)
// - TCP_QUICKACK (0x0c)
//
static privileged void AllowSetsockoptRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_setsockopt, 0, 25),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 41, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 6, 0, 19),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0c, 16, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x1a, 15, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x06, 14, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0f, 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x03, 12, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0c, 11, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x13, 10, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x02, 9, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x09, 8, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x14, 7, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x01, 6, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0b, 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x04, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x05, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x17, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x1e, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x15, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The level argument of getsockopt() must be one of:
//
// - SOL_SOCKET (1)
// - SOL_TCP (6)
//
// The optname argument of getsockopt() must be one of:
//
// - SO_TYPE (0x03)
// - SO_ERROR (0x04)
// - SO_REUSEPORT (0x0f)
// - SO_REUSEADDR (0x02)
// - SO_KEEPALIVE (0x09)
// - SO_RCVTIMEO (0x14)
// - SO_SNDTIMEO (0x15)
//
static privileged void AllowGetsockoptRestrict(struct Filter *f) {
static const int nr = __NR_linux_getsockopt;
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, nr, 0, 13),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 1, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 6, 0, 9),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x03, 6, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x04, 5, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0f, 4, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x02, 3, 0),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x09, 2, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x14, 1, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x15, 0, 1),
/*L12*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L13*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L14*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The flags parameter of mmap() must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_NONBLOCK (0x10000)
// - MAP_HUGETLB (0x40000)
//
static privileged void AllowMmapExec(struct Filter *f) {
long y = (long)__privileged_end;
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_mmap, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x52000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 5 - 4),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mmap() may only have:
//
// - PROT_NONE (0)
// - PROT_READ (1)
// - PROT_WRITE (2)
//
// The flags parameter must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_NONBLOCK (0x10000)
// - MAP_HUGETLB (0x40000)
//
static privileged void AllowMmapNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_mmap, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x5a000),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mprotect() may only have:
//
// - PROT_NONE (0)
// - PROT_READ (1)
// - PROT_WRITE (2)
//
static privileged void AllowMprotectNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_mprotect, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static privileged void AllowOpenReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_open, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020001100),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static privileged void AllowOpenatReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_openat, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020001100),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The open() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static privileged void AllowOpenWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_open, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020000100),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The openat() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static privileged void AllowOpenatWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_openat, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020000100),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// If the flags parameter of open() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowOpenCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_open, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 000000100),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 000000100, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// If the flags parameter of openat() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowOpenatCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_openat, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 000000100),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 000000100, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_linux_creat
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowCreatRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_creat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The second argument of fcntl() must be one of:
//
// - F_DUPFD (0)
// - F_DUPFD_CLOEXEC (1030)
// - F_GETFD (1)
// - F_SETFD (2)
// - F_GETFL (3)
// - F_SETFL (4)
//
static privileged void AllowFcntlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_fcntl, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1030, 4 - 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 5, 5 - 4, 0),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of fcntl() must be one of:
//
// - F_GETLK (0x05)
// - F_SETLK (0x06)
// - F_SETLKW (0x07)
// - F_OFD_GETLK (0x24)
// - F_OFD_SETLK (0x25)
// - F_OFD_SETLKW (0x26)
//
static privileged void AllowFcntlLock(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_fcntl, 0, 9),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x05, 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x06, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x07, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x24, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x25, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x26, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The addr parameter of sendto() must be
//
// - NULL
//
static privileged void AllowSendtoAddrless(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_sendto, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 0),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 5),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_INET (0x02)
// - AF_INET6 (0x0a)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (0x01)
// - SOCK_DGRAM (0x02)
//
// The protocol parameter of socket() must be one of:
//
// - 0
// - IPPROTO_ICMP (0x01)
// - IPPROTO_TCP (0x06)
// - IPPROTO_UDP (0x11)
//
static privileged void AllowSocketInet(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_socket, 0, 15 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x02, 1, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0a, 0, 14 - 4),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~0x80800),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x01, 1, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x02, 0, 14 - 8),
/* L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x00, 3, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x01, 2, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x06, 1, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x11, 0, 1),
/*L13*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L14*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L15*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_UNIX (1)
// - AF_LOCAL (1)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (1)
// - SOCK_DGRAM (2)
//
// The protocol parameter of socket() must be one of:
//
// - 0
//
static privileged void AllowSocketUnix(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_socket, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 0, 10 - 3),
/* L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~0x80800),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 1, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The first parameter of prctl() can be any of
//
// - PR_SET_NAME (15)
// - PR_GET_NAME (16)
// - PR_GET_SECCOMP (21)
// - PR_SET_SECCOMP (22)
// - PR_SET_NO_NEW_PRIVS (38)
// - PR_CAPBSET_READ (23)
// - PR_CAPBSET_DROP (24)
//
static privileged void AllowPrctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_prctl, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 15, 6, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 16, 5, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 21, 4, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 22, 3, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 23, 2, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 24, 1, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 38, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_linux_chmod
// The mode parameter of chmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowChmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_chmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The mode parameter of fchmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowFchmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_fchmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The mode parameter of fchmodat() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static privileged void AllowFchmodatNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_fchmodat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The new_limit parameter of prlimit() must be
//
// - NULL (0)
//
static privileged void AllowPrlimitStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_linux_prlimit, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
static privileged int CountUnspecial(const uint16_t *p, size_t len) {
int i, count;
for (count = i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) {
++count;
}
}
return count;
}
static privileged void AppendPledge(struct Filter *f, //
const uint16_t *p, //
size_t len) { //
int i, j, count;
// handle ordinals which allow syscalls regardless of args
// we put in extra effort here to reduce num of bpf instrs
if ((count = CountUnspecial(p, len))) {
if (count < 256) {
for (j = i = 0; i < len; ++i) {
if (p[i] & SPECIAL) continue;
// jump to ALLOW rule below if accumulator equals ordinal
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, // instruction
p[i], // operand
count - j - 1, // jump if true displacement
j == count - 1), // jump if false displacement
};
AppendFilter(f, PLEDGE(fragment));
++j;
}
struct sock_filter fragment[] = {
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
} else {
notpossible;
}
}
// handle "special" ordinals which use hand-crafted bpf
for (i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) continue;
switch (p[i]) {
case __NR_linux_mmap | EXEC:
AllowMmapExec(f);
break;
case __NR_linux_mmap | NOEXEC:
AllowMmapNoexec(f);
break;
case __NR_linux_mprotect | NOEXEC:
AllowMprotectNoexec(f);
break;
#ifdef __NR_linux_chmod
case __NR_linux_chmod | NOBITS:
AllowChmodNobits(f);
break;
#endif
case __NR_linux_fchmod | NOBITS:
AllowFchmodNobits(f);
break;
case __NR_linux_fchmodat | NOBITS:
AllowFchmodatNobits(f);
break;
case __NR_linux_prctl | STDIO:
AllowPrctlStdio(f);
break;
case __NR_linux_open | CREATONLY:
AllowOpenCreatonly(f);
break;
case __NR_linux_openat | CREATONLY:
AllowOpenatCreatonly(f);
break;
case __NR_linux_open | READONLY:
AllowOpenReadonly(f);
break;
case __NR_linux_openat | READONLY:
AllowOpenatReadonly(f);
break;
case __NR_linux_open | WRITEONLY:
AllowOpenWriteonly(f);
break;
case __NR_linux_openat | WRITEONLY:
AllowOpenatWriteonly(f);
break;
case __NR_linux_setsockopt | RESTRICT:
AllowSetsockoptRestrict(f);
break;
case __NR_linux_getsockopt | RESTRICT:
AllowGetsockoptRestrict(f);
break;
#ifdef __NR_linux_creat
case __NR_linux_creat | RESTRICT:
AllowCreatRestrict(f);
break;
#endif
case __NR_linux_fcntl | STDIO:
AllowFcntlStdio(f);
break;
case __NR_linux_fcntl | LOCK:
AllowFcntlLock(f);
break;
case __NR_linux_ioctl | RESTRICT:
AllowIoctlStdio(f);
break;
case __NR_linux_ioctl | TTY:
AllowIoctlTty(f);
break;
case __NR_linux_ioctl | INET:
AllowIoctlInet(f);
break;
case __NR_linux_socket | INET:
AllowSocketInet(f);
break;
case __NR_linux_socket | UNIX:
AllowSocketUnix(f);
break;
case __NR_linux_sendto | ADDRLESS:
AllowSendtoAddrless(f);
break;
case __NR_linux_clone | RESTRICT:
AllowCloneRestrict(f);
break;
case __NR_linux_clone | THREAD:
AllowCloneThread(f);
break;
case __NR_linux_prlimit | STDIO:
AllowPrlimitStdio(f);
break;
case __NR_linux_kill | SELF:
AllowKillSelf(f);
break;
case __NR_linux_tgkill | SELF:
AllowTgkillSelf(f);
break;
default:
notpossible;
}
}
}
/**
* Installs SECCOMP BPF filter on Linux thread.
*
* @param ipromises is inverted integer bitmask of pledge() promises
* @return 0 on success, or negative error number on error
* @asyncsignalsafe
* @threadsafe
* @vforksafe
*/
privileged int sys_pledge_linux(unsigned long ipromises, int mode) {
struct Filter f;
int i, e, rc = -1;
struct sock_filter sf[1] = {BPF_STMT(BPF_RET | BPF_K, 0)};
CheckLargeStackAllocation(&f, sizeof(f));
f.n = 0;
// set up the seccomp filter
AppendFilter(&f, PLEDGE(kPledgeStart));
if (ipromises == -1) {
// if we're pledging empty string, then avoid triggering a sigsys
// when _Exit() gets called since we need to fallback to _Exit1()
AppendFilter(&f, PLEDGE(kFilterIgnoreExitGroup));
}
AppendPledge(&f, PLEDGE(kPledgeDefault));
for (i = 0; i < ARRAYLEN(kPledge); ++i) {
if (~ipromises & (1ul << i)) {
if (kPledge[i].len) {
AppendPledge(&f, kPledge[i].syscalls, kPledge[i].len);
} else {
notpossible;
}
}
}
// now determine what we'll do on sandbox violations
if (mode & PLEDGE_STDERR_LOGGING) {
// trapping mode
//
// if we haven't pledged exec, then we can monitor SIGSYS
// and print a helpful error message when things do break
// to avoid tls / static memory, we embed mode within bpf
MonitorSigSys();
AllowMonitor(&f);
sf[0].k = SECCOMP_RET_TRAP | (mode & SECCOMP_RET_DATA);
AppendFilter(&f, PLEDGE(sf));
} else {
// non-trapping mode
//
// our sigsys error message handler can't be inherited across
// execve() boundaries so if you've pledged exec then that'll
// likely cause a SIGSYS in your child after the exec happens
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_THREAD:
sf[0].k = SECCOMP_RET_KILL_THREAD;
break;
case PLEDGE_PENALTY_KILL_PROCESS:
sf[0].k = SECCOMP_RET_KILL_PROCESS;
break;
case PLEDGE_PENALTY_RETURN_EPERM:
sf[0].k = SECCOMP_RET_ERRNO | Eperm;
break;
default:
return -Einval;
}
AppendFilter(&f, PLEDGE(sf));
}
// drop privileges
//
// PR_SET_SECCOMP (Linux 2.6.23+) will refuse to work if
// PR_SET_NO_NEW_PRIVS (Linux 3.5+) wasn't called so we punt the error
// detection to the seccomp system call below.
sys_prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
// register our seccomp filter with the kernel
struct sock_fprog sandbox = {.len = f.n, .filter = f.p};
rc = sys_prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, (long)&sandbox, 0, 0);
// the EINVAL error could mean a lot of things. it could mean the bpf
// code is broken. it could also mean we're running on RHEL5 which
// doesn't have SECCOMP support. since we don't consider lack of
// system support for security to be an error, we distinguish these
// two cases by running a simpler SECCOMP operation.
if (rc == -Einval && sys_prctl(PR_GET_SECCOMP, 0, 0, 0, 0) == -Einval) {
rc = 0; // -Enosys
}
return rc;
}
| 100,568 | 2,347 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/readv-serial.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/calls/struct/iovec.internal.h"
#include "libc/nexgen32e/uart.internal.h"
#include "libc/runtime/pc.internal.h"
#ifdef __x86_64__
static bool IsDataAvailable(struct Fd *fd) {
return inb(fd->handle + UART_LSR) & UART_TTYDA;
}
static int GetFirstIov(struct iovec *iov, int iovlen) {
int i;
for (i = 0; i < iovlen; ++i) {
if (iov[i].iov_len) {
return i;
}
}
return -1;
}
ssize_t sys_readv_serial(struct Fd *fd, const struct iovec *iov, int iovlen) {
size_t i;
if ((i = GetFirstIov(iov, iovlen)) != -1) {
while (!IsDataAvailable(fd)) {
__builtin_ia32_pause();
}
((char *)iov[i].iov_base)[0] = inb(fd->handle);
return 1;
} else {
return 0;
}
}
#endif
| 2,601 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timeval_totimespec.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Coerces `tv` from 1e-6 to 1e-9 granularity.
*/
struct timespec timeval_totimespec(struct timeval tv) {
return (struct timespec){tv.tv_sec, tv.tv_usec * 1000};
}
| 2,047 | 27 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/vdprintf.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/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/fmt/fmt.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/nt/files.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
struct VdprintfState {
int n, t, fd;
char b[1024];
};
static int vdprintf_putc(const char *s, struct VdprintfState *t, size_t n) {
struct iovec iov[2];
if (n) {
if (t->n + n < sizeof(t->b)) {
memcpy(t->b + t->n, s, n);
t->n += n;
} else {
iov[0].iov_base = t->b;
iov[0].iov_len = t->n;
iov[1].iov_base = s;
iov[1].iov_len = n;
if (WritevUninterruptible(t->fd, iov, 2) == -1) {
return -1;
}
t->t += t->n;
t->n = 0;
}
}
return 0;
}
/**
* Formats string directly to system i/o device.
* @asyncsignalsafe
* @vforksafe
*/
int(vdprintf)(int fd, const char *fmt, va_list va) {
struct iovec iov[1];
struct VdprintfState t;
t.n = 0;
t.t = 0;
t.fd = fd;
if (__fmt(vdprintf_putc, &t, fmt, va) == -1) return -1;
if (t.n) {
iov[0].iov_base = t.b;
iov[0].iov_len = t.n;
if (WritevUninterruptible(t.fd, iov, 1) == -1) {
return -1;
}
t.t += t.n;
}
return t.t;
}
| 3,127 | 78 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/clock_nanosleep-xnu.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/calls/struct/timespec.internal.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/timeval.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/fmt/conv.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sock/internal.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/timer.h"
#include "libc/sysv/errfuns.h"
int sys_clock_nanosleep_xnu(int clock, int flags, const struct timespec *req,
struct timespec *rem) {
#ifdef __x86_64__
struct timeval abs, now, rel;
if (clock == CLOCK_REALTIME) {
if (flags & TIMER_ABSTIME) {
abs = timespec_totimeval(*req);
sys_gettimeofday_xnu(&now, 0, 0);
if (timeval_cmp(abs, now) > 0) {
rel = timeval_sub(abs, now);
return sys_select(0, 0, 0, 0, &rel);
} else {
return 0;
}
} else {
return sys_nanosleep_xnu(req, rem);
}
} else {
return enotsup();
}
#else
long res;
struct timespec abs, now, rel;
if (flags & TIMER_ABSTIME) {
abs = *req;
if (!(res = __syslib->clock_gettime(clock, &now))) {
if (timespec_cmp(abs, now) > 0) {
rel = timespec_sub(abs, now);
res = __syslib->nanosleep(&rel, 0);
}
}
} else {
res = __syslib->nanosleep(req, rem);
}
return _sysret(res);
#endif
}
| 3,226 | 68 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timespec_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/timespec.h"
#include "libc/limits.h"
/**
* Reduces `ts` from 1e-9 to 1e-6 granularity w/ ceil rounding.
*
* This function uses ceiling rounding. For example, if `ts` is one
* nanosecond, then one microsecond will be returned. Ceil rounding
* is needed by many interfaces, e.g. setitimer(), because the zero
* timestamp has a special meaning.
*
* 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 holding microseconds since epoch
* @see timespec_totimeval()
*/
int64_t timespec_tomicros(struct timespec ts) {
int64_t us;
// reduce precision from nanos to micros
if (ts.tv_nsec <= 999999000) {
ts.tv_nsec = (ts.tv_nsec + 999) / 1000;
} 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, 1000000ul, &us) &&
!__builtin_add_overflow(us, ts.tv_nsec, &us)) {
return us;
} else if (ts.tv_sec < 0) {
return INT64_MIN;
} else {
return INT64_MAX;
}
}
| 2,974 | 57 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ntaccesscheck.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/mem/mem.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/securityimpersonationlevel.h"
#include "libc/nt/enum/securityinformation.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/genericmapping.h"
#include "libc/nt/struct/privilegeset.h"
#include "libc/nt/struct/securitydescriptor.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/errfuns.h"
/**
* Asks Microsoft if we're authorized to use a folder or file.
*
* Implementation Details: MSDN documentation imposes no limit on the
* internal size of SECURITY_DESCRIPTOR, which we are responsible for
* allocating. We've selected 1024 which shall hopefully be adequate.
*
* @param flags can have R_OK, W_OK, X_OK, etc.
* @return 0 if authorized, or -1 w/ errno
* @see https://blog.aaronballman.com/2011/08/how-to-check-access-rights/
* @see libc/sysv/consts.sh
*/
textwindows int ntaccesscheck(const char16_t *pathname, uint32_t flags) {
int rc, e;
void *freeme;
bool32 result;
struct NtSecurityDescriptor *s;
struct NtGenericMapping mapping;
struct NtPrivilegeSet privileges;
int64_t hToken, hImpersonatedToken;
uint32_t secsize, granted, privsize;
intptr_t buffer[1024 / sizeof(intptr_t)];
freeme = 0;
granted = 0;
result = false;
s = (void *)buffer;
secsize = sizeof(buffer);
privsize = sizeof(privileges);
bzero(&privileges, sizeof(privileges));
mapping.GenericRead = kNtFileGenericRead;
mapping.GenericWrite = kNtFileGenericWrite;
mapping.GenericExecute = kNtFileGenericExecute;
mapping.GenericAll = kNtFileAllAccess;
MapGenericMask(&flags, &mapping);
hImpersonatedToken = hToken = -1;
TryAgain:
if (GetFileSecurity(pathname,
kNtOwnerSecurityInformation |
kNtGroupSecurityInformation |
kNtDaclSecurityInformation,
s, secsize, &secsize)) {
if (OpenProcessToken(GetCurrentProcess(),
kNtTokenImpersonate | kNtTokenQuery |
kNtTokenDuplicate | kNtStandardRightsRead,
&hToken)) {
if (DuplicateToken(hToken, kNtSecurityImpersonation,
&hImpersonatedToken)) {
if (AccessCheck(s, hImpersonatedToken, flags, &mapping, &privileges,
&privsize, &granted, &result)) {
if (result || flags == F_OK) {
rc = 0;
} else {
STRACE("ntaccesscheck finale failed %d %d", result, flags);
rc = eacces();
}
} else {
rc = __winerr();
STRACE("%s(%#hs) failed: %m", "AccessCheck", pathname);
}
} else {
rc = __winerr();
STRACE("%s(%#hs) failed: %m", "DuplicateToken", pathname);
}
} else {
rc = __winerr();
STRACE("%s(%#hs) failed: %m", "OpenProcessToken", pathname);
}
} else {
e = GetLastError();
if (!IsTiny() && e == kNtErrorInsufficientBuffer) {
if (!freeme && _weaken(malloc) && (freeme = _weaken(malloc)(secsize))) {
s = freeme;
goto TryAgain;
} else {
rc = enomem();
STRACE("%s(%#hs) failed: %m", "GetFileSecurity", pathname);
}
} else {
errno = e;
STRACE("%s(%#hs) failed: %m", "GetFileSecurity", pathname);
rc = -1;
}
}
if (freeme && _weaken(free)) _weaken(free)(freeme);
if (hImpersonatedToken != -1) CloseHandle(hImpersonatedToken);
if (hToken != -1) CloseHandle(hToken);
return rc;
}
| 5,717 | 130 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/read.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Reads data from file descriptor.
*
* This function changes the current file position. For documentation
* on file position behaviors and gotchas, see the lseek() function.
* This function may be used on socket file descriptors, including on
* Windows.
*
* @param fd is something open()'d earlier
* @param buf is copied into, cf. copy_file_range(), sendfile(), etc.
* @param size in range [1..0x7ffff000] is reasonable
* @return [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with
* exception of size==0, in which case return zero means no error
* @raise EBADF if `fd` is negative or not an open file descriptor
* @raise EBADF if `fd` is open in `O_WRONLY` mode
* @raise EFAULT if `size` is nonzero and `buf` points to bad memory
* @raise EPERM if pledge() is in play without the stdio promise
* @raise EIO if low-level i/o error happened
* @raise EINTR if signal was delivered instead
* @raise ECANCELED if thread was cancelled in masked mode
* @raise ENOTCONN if `fd` is a socket and it isn't connected
* @raise ECONNRESET if socket peer forcibly closed connection
* @raise ETIMEDOUT if socket transmission timeout occurred
* @raise EAGAIN if `O_NONBLOCK` is in play and read needs to block,
* or `SO_RCVTIMEO` is in play and the time interval elapsed
* @raise ENOBUFS is specified by POSIX
* @raise ENXIO is specified by POSIX
* @cancellationpoint
* @asyncsignalsafe
* @restartable
* @vforksafe
*/
ssize_t read(int fd, void *buf, size_t size) {
ssize_t rc;
BEGIN_CANCELLATION_POINT;
if (fd >= 0) {
if ((!buf && size) || (IsAsan() && !__asan_is_valid(buf, size))) {
rc = efault();
} else if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
rc = _weaken(__zipos_read)(
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle,
&(struct iovec){buf, size}, 1, -1);
} else if (!IsWindows() && !IsMetal()) {
rc = sys_read(fd, buf, size);
} else if (fd >= g_fds.n) {
rc = ebadf();
} else if (IsMetal()) {
rc = sys_readv_metal(g_fds.p + fd, &(struct iovec){buf, size}, 1);
} else {
rc = sys_readv_nt(g_fds.p + fd, &(struct iovec){buf, size}, 1);
}
} else {
rc = ebadf();
}
END_CANCELLATION_POINT;
DATATRACE("read(%d, [%#.*hhs%s], %'zu) â %'zd% m", fd, MAX(0, MIN(40, rc)),
buf, rc > 40 ? "..." : "", size, rc);
return rc;
}
| 4,709 | 93 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/getitimer.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/itimerval.h"
#include "libc/calls/struct/itimerval.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Retrieves last setitimer() value, correcting for remaining time.
*
* @param which can be ITIMER_REAL, ITIMER_VIRTUAL, etc.
* @return 0 on success or -1 w/ errno
*/
int getitimer(int which, struct itimerval *curvalue) {
int rc;
if (IsAsan() && !__asan_is_valid(curvalue, sizeof(*curvalue))) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_getitimer(which, curvalue);
} else if (!curvalue) {
rc = efault();
} else {
rc = sys_setitimer_nt(which, 0, curvalue);
}
if (curvalue) {
STRACE("getitimer(%d, [{{%'ld, %'ld}, {%'ld, %'ld}}]) â %d% m", which,
curvalue->it_interval.tv_sec, curvalue->it_interval.tv_usec,
curvalue->it_value.tv_sec, curvalue->it_value.tv_usec, rc);
} else {
STRACE("getitimer(%d, 0) â %d% m", which, rc);
}
return rc;
}
| 2,915 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ioctl_tcgets.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/ioctl.h"
#include "libc/calls/struct/metatermios.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/termios.internal.h"
#include "libc/calls/ttydefaults.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/consts/termios.h"
#include "libc/sysv/errfuns.h"
int ioctl_tcgets_nt(int, struct termios *) _Hide;
static int ioctl_tcgets_metal(int fd, struct termios *tio) {
bzero(tio, sizeof(*tio));
tio->c_iflag = TTYDEF_IFLAG;
tio->c_oflag = TTYDEF_OFLAG;
tio->c_lflag = TTYDEF_LFLAG;
tio->c_cflag = TTYDEF_CFLAG;
return 0;
}
static int ioctl_tcgets_sysv(int fd, struct termios *tio) {
int rc;
union metatermios mt;
if (IsLinux()) {
if (IsAsan() && !__asan_is_valid(tio, sizeof(*tio))) return efault();
return sys_ioctl(fd, TCGETS, tio);
} else {
if ((rc = sys_ioctl(fd, TCGETS, &mt)) != -1) {
if (IsXnu()) {
COPY_TERMIOS(tio, &mt.xnu);
} else if (IsFreebsd() || IsOpenbsd() || IsNetbsd()) {
COPY_TERMIOS(tio, &mt.bsd);
} else {
unreachable;
}
}
return rc;
}
}
/**
* Returns information about terminal.
*
* @see tcgetattr(fd, tio) dispatches here
* @see ioctl(fd, TCGETS, tio) dispatches here
* @see ioctl(fd, TIOCGETA, tio) dispatches here
*/
int ioctl_tcgets(int fd, ...) {
int rc;
va_list va;
struct termios *tio;
va_start(va, fd);
tio = va_arg(va, struct termios *);
va_end(va);
if (fd >= 0) {
if (!tio || (IsAsan() && !__asan_is_valid(tio, sizeof(*tio)))) {
rc = efault();
} else if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
rc = enotty();
} else if (IsMetal()) {
rc = ioctl_tcgets_metal(fd, tio);
} else if (!IsWindows()) {
rc = ioctl_tcgets_sysv(fd, tio);
} else {
rc = ioctl_tcgets_nt(fd, tio);
}
} else {
rc = einval();
}
STRACE("ioctl_tcgets(%d, %p) â %d% m", fd, tio, rc);
return rc;
}
| 3,894 | 95 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/lstat64.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"
lstat64:
jmp lstat
.endfn lstat64,globl
| 2,593 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/copyfile.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/copyfile.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.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/files.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/filetime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/o.h"
#include "libc/time/time.h"
static textwindows int sys_copyfile_nt(const char *src, const char *dst,
int flags) {
int64_t fhsrc, fhdst;
struct NtFileTime accessed, modified;
char16_t src16[PATH_MAX], dst16[PATH_MAX];
if (__mkntpath(src, src16) == -1) return -1;
if (__mkntpath(dst, dst16) == -1) return -1;
if (CopyFile(src16, dst16, !!(flags & COPYFILE_NOCLOBBER))) {
if (flags & COPYFILE_PRESERVE_TIMESTAMPS) {
fhsrc = CreateFile(src16, kNtFileReadAttributes, kNtFileShareRead, NULL,
kNtOpenExisting, kNtFileAttributeNormal, 0);
fhdst = CreateFile(dst16, kNtFileWriteAttributes, kNtFileShareRead, NULL,
kNtOpenExisting, kNtFileAttributeNormal, 0);
if (fhsrc != -1 && fhdst != -1) {
GetFileTime(fhsrc, NULL, &accessed, &modified);
SetFileTime(fhdst, NULL, &accessed, &modified);
}
CloseHandle(fhsrc);
CloseHandle(fhdst);
}
return 0;
} else {
return __winerr();
}
}
static int sys_copyfile(const char *src, const char *dst, int flags) {
struct stat st;
size_t remaining;
ssize_t transferred;
struct timespec amtime[2];
int64_t inoffset, outoffset;
int rc, srcfd, dstfd, oflags, omode;
rc = -1;
if ((srcfd = openat(AT_FDCWD, src, O_RDONLY, 0)) != -1) {
if (fstat(srcfd, &st) != -1) {
omode = st.st_mode & 0777;
oflags = O_WRONLY | O_CREAT;
if (flags & COPYFILE_NOCLOBBER) oflags |= O_EXCL;
if ((dstfd = openat(AT_FDCWD, dst, oflags, omode)) != -1) {
remaining = st.st_size;
ftruncate(dstfd, remaining);
inoffset = 0;
outoffset = 0;
while (remaining &&
(transferred = copy_file_range(
srcfd, &inoffset, dstfd, &outoffset, remaining, 0)) != -1) {
remaining -= transferred;
}
if (!remaining) {
rc = 0;
if (flags & COPYFILE_PRESERVE_TIMESTAMPS) {
amtime[0] = st.st_atim;
amtime[1] = st.st_mtim;
utimensat(dstfd, NULL, amtime, 0);
}
}
rc |= close(dstfd);
}
}
rc |= close(srcfd);
}
return rc;
}
/**
* Copies file.
*
* This implementation goes 2x faster than the `cp` command that comes
* included with most systems since we use the newer copy_file_range()
* system call rather than sendfile().
*
* @param flags may have COPYFILE_PRESERVE_TIMESTAMPS, COPYFILE_NOCLOBBER
* @return 0 on success, or -1 w/ errno
*/
int _copyfile(const char *src, const char *dst, int flags) {
if (!IsWindows() || _startswith(src, "/zip/") || _startswith(dst, "/zip/")) {
return sys_copyfile(src, dst, flags);
} else {
return sys_copyfile_nt(src, dst, flags);
}
}
| 5,210 | 120 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/getsid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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.
*/
int getsid(int pid) {
int rc;
rc = sys_getsid(pid);
STRACE("%s(%d) â %d% m", "getsid", pid, rc);
return rc;
}
| 2,132 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/symlink.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Creates symbolic link.
*
* This is like link() but adds a tiny indirection to make the fact that
* the file is a link obvious. It also enables certain other features,
* like the ability to be broken.
*
* @param target can be relative and needn't exist
* @param linkpath is what gets created
* @return 0 on success, or -1 w/ errno
* @note Windows NT only lets admins do this
* @asyncsignalsafe
*/
int symlink(const char *target, const char *linkpath) {
return symlinkat(target, AT_FDCWD, linkpath);
}
| 2,420 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/syscall-sysv.internal.h | #ifndef COSMOPOLITAN_LIBC_CALLS_SYSCALL_SYSV_INTERNAL_H_
#define COSMOPOLITAN_LIBC_CALLS_SYSCALL_SYSV_INTERNAL_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define i32 int32_t
#define i64 int64_t
#define u32 uint32_t
#define u64 uint64_t
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § syscalls » system five » structless synthetic jump slots ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
axdx_t __sys_fork(void) _Hide;
axdx_t __sys_pipe(i32[hasatleast 2], i32) _Hide;
axdx_t sys_getpid(void) _Hide;
char *sys_getcwd(char *, u64) _Hide;
char *sys_getcwd_xnu(char *, u64) _Hide;
i32 __sys_dup3(i32, i32, i32) _Hide;
i32 __sys_execve(const char *, char *const[], char *const[]) _Hide;
i32 __sys_fcntl(i32, i32, ...) _Hide;
i32 __sys_fcntl_cp(i32, i32, ...) _Hide;
i32 __sys_fstat(i32, void *) _Hide;
i32 __sys_fstatat(i32, const char *, void *, i32) _Hide;
i32 __sys_gettid(i64 *) _Hide;
i32 __sys_munmap(void *, u64) _Hide;
i32 __sys_openat(i32, const char *, i32, u32) _Hide;
i32 __sys_openat_nc(i32, const char *, i32, u32) _Hide;
i32 __sys_pipe2(i32[hasatleast 2], u32) _Hide;
i32 sys_arch_prctl(i32, i64) _Hide;
i32 sys_chdir(const char *) _Hide;
i32 sys_chroot(const char *) _Hide;
i32 sys_close(i32) _Hide;
i32 sys_close_range(u32, u32, u32) _Hide;
i32 sys_closefrom(i32) _Hide;
i32 sys_dup(i32) _Hide;
i32 sys_dup2(i32, i32, i32) _Hide;
i32 sys_dup3(i32, i32, i32) _Hide;
i32 sys_execve(const char *, char *const[], char *const[]) _Hide;
i32 sys_execveat(i32, const char *, char *const[], char *const[], i32) _Hide;
i32 sys_faccessat(i32, const char *, i32, u32) _Hide;
i32 sys_faccessat2(i32, const char *, i32, u32) _Hide;
i32 sys_fadvise(i32, i64, i64, i32) _Hide;
i32 sys_fchdir(i32) _Hide;
i32 sys_fchmod(i32, u32) _Hide;
i32 sys_fchmodat(i32, const char *, u32, u32) _Hide;
i32 sys_fchown(i64, u32, u32) _Hide;
i32 sys_fchownat(i32, const char *, u32, u32, u32) _Hide;
i32 sys_fcntl(i32, i32, u64, i32 (*)(i32, i32, ...)) _Hide;
i32 sys_fdatasync(i32) _Hide;
i32 sys_fexecve(i32, char *const[], char *const[]) _Hide;
i32 sys_flock(i32, i32) _Hide;
i32 sys_fork(void) _Hide;
i32 sys_fsync(i32) _Hide;
i32 sys_ftruncate(i32, i64, i64) _Hide;
i32 sys_getcontext(void *) _Hide;
i32 sys_getpgid(i32) _Hide;
i32 sys_getppid(void) _Hide;
i32 sys_getpriority(i32, u32) _Hide;
i32 sys_getresgid(u32 *, u32 *, u32 *) _Hide;
i32 sys_getresuid(u32 *, u32 *, u32 *) _Hide;
i32 sys_getsid(i32) _Hide;
i32 sys_gettid(void) _Hide;
i32 sys_ioctl(i32, u64, ...) _Hide;
i32 sys_ioctl_cp(i32, u64, ...) _Hide;
i32 sys_issetugid(void) _Hide;
i32 sys_kill(i32, i32, i32) _Hide;
i32 sys_linkat(i32, const char *, i32, const char *, i32) _Hide;
i32 sys_madvise(void *, size_t, i32) _Hide;
i32 sys_memfd_create(const char *, u32) _Hide;
i32 sys_mincore(void *, u64, unsigned char *) _Hide;
i32 sys_mkdirat(i32, const char *, u32) _Hide;
i32 sys_mkfifo(const char *, u32) _Hide;
i32 sys_mknod(const char *, u32, u64) _Hide;
i32 sys_mknodat(i32, const char *, u32, u64) _Hide;
i32 sys_mprotect(void *, u64, i32) _Hide;
i32 sys_msync(void *, u64, i32) _Hide;
i32 sys_munmap(void *, u64) _Hide;
i32 sys_openat(i32, const char *, i32, u32) _Hide;
i32 sys_pause(void) _Hide;
i32 sys_pipe(i32[hasatleast 2]) _Hide;
i32 sys_pipe2(i32[hasatleast 2], u32) _Hide;
i32 sys_pivot_root(const char *, const char *) _Hide;
i32 sys_pledge(const char *, const char *) _Hide;
i32 sys_posix_openpt(i32) _Hide;
i32 sys_renameat(i32, const char *, i32, const char *) _Hide;
i32 sys_sem_close(i64) _Hide;
i32 sys_sem_destroy(i64) _Hide;
i32 sys_sem_getvalue(i64, u32 *) _Hide;
i32 sys_sem_init(u32, i64 *) _Hide;
i32 sys_sem_open(const char *, int, u32, i64 *) _Hide;
i32 sys_sem_post(i64) _Hide;
i32 sys_sem_trywait(i64) _Hide;
i32 sys_sem_unlink(const char *) _Hide;
i32 sys_sem_wait(i64) _Hide;
i32 sys_setfsgid(i32) _Hide;
i32 sys_setfsuid(i32) _Hide;
i32 sys_setgid(i32) _Hide;
i32 sys_setpgid(i32, i32) _Hide;
i32 sys_setpriority(i32, u32, i32) _Hide;
i32 sys_setregid(u32, u32) _Hide;
i32 sys_setresgid(u32, u32, u32) _Hide;
i32 sys_setresuid(u32, u32, u32) _Hide;
i32 sys_setreuid(u32, u32) _Hide;
i32 sys_setsid(void) _Hide;
i32 sys_setuid(i32) _Hide;
i32 sys_shm_open(const char *, i32, u32) _Hide;
i32 sys_sigaction(i32, const void *, void *, i64, i64) _Hide;
i32 sys_sigaltstack(const void *, void *) _Hide;
i32 sys_symlinkat(const char *, i32, const char *) _Hide;
i32 sys_sync(void) _Hide;
i32 sys_sync_file_range(i32, i64, i64, u32) _Hide;
i32 sys_syslog(i32, char *, i32) _Hide;
i32 sys_tgkill(i32, i32, i32) _Hide;
i32 sys_tkill(i32, i32, void *) _Hide;
i32 sys_truncate(const char *, u64, u64) _Hide;
i32 sys_uname(void *) _Hide;
i32 sys_unlink(const char *) _Hide;
i32 sys_unlinkat(i32, const char *, i32) _Hide;
i32 sys_unmount(const char *, i32) _Hide;
i32 sys_unveil(const char *, const char *) _Hide;
i64 __sys_ptrace(i32, i32, i64, long *) _Hide;
i64 sys_copy_file_range(i32, long *, i32, long *, u64, u32) _Hide;
i64 sys_getrandom(void *, u64, u32) _Hide;
i64 sys_lseek(i32, i64, i64, i64) _Hide;
i64 sys_pread(i32, void *, u64, i64, i64) _Hide;
i64 sys_pwrite(i32, const void *, u64, i64, i64) _Hide;
i64 sys_read(i32, void *, u64) _Hide;
i64 sys_readlinkat(i32, const char *, char *, u64) _Hide;
i64 sys_sendfile(i32, i32, i64 *, u64) _Hide;
i64 sys_splice(i32, i64 *, i32, i64 *, u64, u32) _Hide;
i64 sys_write(i32, const void *, u64) _Hide;
u32 sys_getegid(void) _Hide;
u32 sys_geteuid(void) _Hide;
u32 sys_getgid(void) _Hide;
u32 sys_getuid(void) _Hide;
u32 sys_umask(u32) _Hide;
unsigned long _sysret(unsigned long) _Hide;
void *__sys_mmap(void *, u64, u32, u32, i64, i64, i64) _Hide;
void *__sys_mremap(void *, u64, u64, i32, void *) _Hide;
void *sys_mremap(void *, u64, u64, i32, void *) _Hide;
void sys_exit(i32) _Hide;
#undef i32
#undef i64
#undef u32
#undef u64
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_SYSCALL_SYSV_INTERNAL_H_ */
| 6,330 | 150 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/getpriority.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/errno.h"
#include "libc/intrin/asmflag.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/limits.h"
/**
* Returns nice value of thing.
*
* Since -1 might be a valid return value for this API, it's necessary
* to clear `errno` beforehand and see if it changed, in order to truly
* determine if an error happened.
*
* On Windows, there's only six priority classes. We define them as -16
* (realtime), -10 (high), -5 (above), 0 (normal), 5 (below), 15 (idle)
* which are the only values that'll roundtrip getpriority/setpriority.
*
* @param which can be one of:
* - `PRIO_PROCESS` is supported universally
* - `PRIO_PGRP` is supported on unix
* - `PRIO_USER` is supported on unix
* @param who is the pid, pgid, or uid (0 means current)
* @return value â [-NZERO,NZERO) or -1 w/ errno
* @raise EINVAL if `which` was invalid or unsupported
* @raise EPERM if access to process was denied
* @raise ESRCH if no such process existed
* @see setpriority()
*/
privileged int getpriority(int which, unsigned who) {
int rc;
#ifdef __x86_64__
char cf;
if (IsLinux()) {
asm volatile("syscall"
: "=a"(rc)
: "0"(140), "D"(which), "S"(who)
: "rcx", "r11", "memory");
if (rc >= 0) {
rc = NZERO - rc;
} else {
errno = -rc;
rc = -1;
}
} else if (IsBsd()) {
asm volatile(CFLAG_ASM("syscall")
: CFLAG_CONSTRAINT(cf), "=a"(rc)
: "1"((IsXnu() ? 0x2000000 : 0) | 100), "D"(which), "S"(who)
: "rcx", "rdx", "r8", "r9", "r10", "r11", "memory");
if (cf) {
errno = rc;
rc = -1;
}
} else {
rc = sys_getpriority_nt(which, who);
}
#else
rc = sys_getpriority(which, who);
if (rc != -1) {
rc = NZERO - rc;
}
#endif
STRACE("getpriority(%s, %u) â %d% m", DescribeWhichPrio(which), who, rc);
return rc;
}
| 3,943 | 87 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/statfs2cosmo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/statfs-meta.internal.h"
#include "libc/dce.h"
#include "libc/str/str.h"
static const char *DescribeStatfsTypeLinux(int64_t x) {
switch (x) {
case 0xadf5:
return "adfs";
case 0xadff:
return "affs";
case 0x0187:
return "autofs";
case 0x1373:
return "devfs";
case 0x1cd1:
return "devpts";
case 0xf15f:
return "ecryptfs";
case 0x137d:
return "ext1";
case 0xef51:
return "ext2_old";
case 0xef53:
return "ext"; // ext2, ext3, ext4
case 0x4244:
return "hfs";
case 0x9660:
return "isofs";
case 0x72b6:
return "jffs2";
case 0x137f:
return "minix";
case 0x138f:
return "minix2";
case 0x2468:
return "minix2";
case 0x2478:
return "minix22";
case 0x4d5a:
return "minix3";
case 0x4d44:
return "msdos";
case 0x564c:
return "ncp";
case 0x6969:
return "nfs";
case 0x3434:
return "nilfs";
case 0x9fa1:
return "openprom";
case 0x9fa0:
return "proc";
case 0x002f:
return "qnx4";
case 0x7275:
return "romfs";
case 0x517b:
return "smb";
case 0x9fa2:
return "usbdevice";
case 0x27e0eb:
return "cgroup";
case 0xbad1dea:
return "futexfs";
case 0x5346414f:
return "afs";
case 0x09041934:
return "anon_inode_fs";
case 0x62646576:
return "bdevfs";
case 0x42465331:
return "befs";
case 0x1badface:
return "bfs";
case 0x42494e4d:
return "binfmtfs";
case 0xcafe4a11:
return "bpf_fs";
case 0x9123683e:
return "btrfs";
case 0x73727279:
return "btrfs_test";
case 0x63677270:
return "cgroup2";
case 0xff534d42:
return "cifs_number";
case 0x73757245:
return "coda";
case 0x012ff7b7:
return "coh";
case 0x28cd3d45:
return "cramfs";
case 0x64626720:
return "debugfs";
case 0xde5e81e4:
return "efivarfs";
case 0x00414a53:
return "efs";
case 0xf2f52010:
return "f2fs";
case 0x65735546:
return "fuse";
case 0x00c0ffee:
return "hostfs";
case 0xf995e849:
return "hpfs";
case 0x958458f6:
return "hugetlbfs";
case 0x3153464a:
return "jfs";
case 0x19800202:
return "mqueue";
case 0x11307854:
return "mtd_inode_fs";
case 0x6e736673:
return "nsfs";
case 0x5346544e:
return "ntfs_sb";
case 0x7461636f:
return "ocfs2";
case 0x794c7630:
return "overlayfs";
case 0x50495045:
return "pipefs";
case 0x6165676c:
return "pstorefs";
case 0x68191122:
return "qnx6";
case 0x858458f6:
return "ramfs";
case 0x52654973:
return "reiserfs";
case 0x73636673:
return "securityfs";
case 0xf97cff8c:
return "selinux";
case 0x43415d53:
return "smack";
case 0x534f434b:
return "sockfs";
case 0x73717368:
return "squashfs";
case 0x62656572:
return "sysfs";
case 0x012ff7b6:
return "sysv2";
case 0x012ff7b5:
return "sysv4";
case 0x01021994:
return "tmpfs";
case 0x74726163:
return "tracefs";
case 0x15013346:
return "udf";
case 0x00011954:
return "ufs";
case 0x01021997:
return "v9fs";
case 0xa501fcf5:
return "vxfs";
case 0xabba1974:
return "xenfs";
case 0x012ff7b4:
return "xenix";
case 0x58465342:
return "xfs";
case 0x012fd16d:
return "_xiafs";
case 0x2fc12fc1:
return "zfs";
case 0x4253584e:
return "apfs";
default:
return "unknown";
}
}
void statfs2cosmo(struct statfs *f, const union statfs_meta *m) {
int64_t f_type;
int64_t f_bsize;
int64_t f_blocks;
int64_t f_bfree;
int64_t f_bavail;
int64_t f_files;
int64_t f_ffree;
fsid_t f_fsid;
int64_t f_namelen;
int64_t f_frsize;
int64_t f_flags;
int32_t f_owner;
char f_fstypename[16];
if (IsLinux()) {
f_type = m->linux.f_type;
f_bsize = m->linux.f_bsize;
f_blocks = m->linux.f_blocks;
f_bfree = m->linux.f_bfree;
f_bavail = m->linux.f_bavail;
f_files = m->linux.f_files;
f_ffree = m->linux.f_ffree;
f_fsid = m->linux.f_fsid;
f_namelen = m->linux.f_namelen;
f_frsize = m->linux.f_frsize;
f_flags = m->linux.f_flags;
f_owner = 0;
bzero(f_fstypename, 16);
strcpy(f_fstypename, DescribeStatfsTypeLinux(m->linux.f_type));
} else if (IsFreebsd()) {
f_type = m->freebsd.f_type;
f_bsize = m->freebsd.f_iosize;
f_blocks = m->freebsd.f_blocks;
f_bfree = m->freebsd.f_bfree;
f_bavail = m->freebsd.f_bavail;
f_files = m->freebsd.f_files;
f_ffree = m->freebsd.f_ffree;
f_fsid = m->freebsd.f_fsid;
f_namelen = m->freebsd.f_namemax;
f_frsize = m->freebsd.f_bsize;
f_flags = m->freebsd.f_flags;
f_owner = m->freebsd.f_owner;
memcpy(f_fstypename, m->freebsd.f_fstypename, 16);
} else if (IsXnu()) {
f_type = m->xnu.f_type;
f_bsize = m->xnu.f_iosize;
f_blocks = m->xnu.f_blocks;
f_bfree = m->xnu.f_bfree;
f_bavail = m->xnu.f_bavail;
f_files = m->xnu.f_files;
f_ffree = m->xnu.f_ffree;
f_fsid = m->xnu.f_fsid;
f_namelen = 255;
f_frsize = m->xnu.f_bsize;
f_flags = m->xnu.f_flags;
f_owner = m->xnu.f_owner;
memcpy(f_fstypename, m->xnu.f_fstypename, 16);
} else if (IsOpenbsd()) {
f_type = f->f_type;
f_bsize = m->openbsd.f_iosize;
f_blocks = m->openbsd.f_blocks;
f_bfree = m->openbsd.f_bfree;
f_bavail = m->openbsd.f_bavail;
f_files = m->openbsd.f_files;
f_ffree = m->openbsd.f_ffree;
f_fsid = m->openbsd.f_fsid;
f_namelen = m->openbsd.f_namemax;
f_frsize = m->openbsd.f_bsize;
f_flags = m->openbsd.f_flags;
f_owner = m->openbsd.f_owner;
memcpy(f_fstypename, m->openbsd.f_fstypename, 16);
} else if (IsNetbsd()) {
f_type = m->netbsd.f_type;
f_bsize = m->netbsd.f_iosize;
f_blocks = m->netbsd.f_blocks;
f_bfree = m->netbsd.f_bfree;
f_bavail = m->netbsd.f_bavail;
f_files = m->netbsd.f_files;
f_ffree = m->netbsd.f_ffree;
f_fsid = m->netbsd.f_fsid;
f_namelen = f->f_namelen;
f_frsize = m->netbsd.f_bsize;
f_flags = m->netbsd.f_flags;
f_owner = m->netbsd.f_owner;
memcpy(f_fstypename, m->netbsd.f_fstypename, 16);
} else {
notpossible;
}
f->f_type = f_type;
f->f_bsize = f_bsize;
f->f_blocks = f_blocks;
f->f_bfree = f_bfree;
f->f_bavail = f_bavail;
f->f_files = f_files;
f->f_ffree = f_ffree;
f->f_fsid = f_fsid;
f->f_namelen = f_namelen;
f->f_frsize = f_frsize;
f->f_flags = f_flags;
memcpy(f->f_fstypename, f_fstypename, 16);
}
| 8,641 | 304 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/seccomp.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/seccomp.h"
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/errfuns.h"
/**
* Tunes Linux security policy.
*
* This system call was first introduced in Linux 3.17. We polyfill
* automatically features like SECCOMP_SET_MODE_STRICT, for kernels
* dating back to 2.6.23, whenever possible.
*
* @raise ENOSYS on non-Linux.
*/
privileged int seccomp(unsigned operation, unsigned flags, void *args) {
int rc;
if (IsLinux()) {
#ifdef __x86_64__
asm volatile("syscall"
: "=a"(rc)
: "0"(317), "D"(operation), "S"(flags), "d"(args)
: "rcx", "r11", "memory");
if (rc == -ENOSYS) {
if (operation == SECCOMP_SET_MODE_STRICT) {
asm volatile("syscall"
: "=a"(rc)
: "0"(157), "D"(PR_SET_SECCOMP), "S"(SECCOMP_MODE_STRICT)
: "rcx", "r11", "memory");
} else if (operation == SECCOMP_SET_MODE_FILTER && !flags) {
asm volatile("syscall"
: "=a"(rc)
: "0"(157), "D"(PR_SET_SECCOMP), "S"(SECCOMP_MODE_FILTER),
"d"(args)
: "rcx", "r11", "memory");
}
}
if (rc > -4096u) {
errno = -rc;
rc = -1;
}
#elif defined(__aarch64__)
register long r0 asm("x0") = (long)operation;
register long r1 asm("x1") = (long)flags;
register long r2 asm("x2") = (long)args;
register long res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(211), "r"(r0), "r"(r1), "r"(r2)
: "x8", "memory");
rc = _sysret(res_x0);
#else
#error "arch unsupported"
#endif
} else {
rc = enosys();
}
STRACE("seccomp(%s, %#x, %p) â %d% m", DescribeSeccompOperation(operation),
flags, args, rc);
return rc;
}
| 3,936 | 85 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timeval_add.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/timeval.h"
/**
* Adds two microsecond timestamps.
*/
struct timeval timeval_add(struct timeval x, struct timeval y) {
x.tv_sec += y.tv_sec;
x.tv_usec += y.tv_usec;
if (x.tv_usec >= 1000000) {
x.tv_usec -= 1000000;
x.tv_sec += 1;
}
return x;
}
| 2,128 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fadvise64.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"
fadvise64:
jmp fadvise
.endfn fadvise64,globl
| 1,919 | 24 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fstat-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/struct/stat.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bsr.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/tpenc.h"
#include "libc/macros.internal.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/fileinfobyhandleclass.h"
#include "libc/nt/enum/filetype.h"
#include "libc/nt/enum/fsctl.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/byhandlefileinformation.h"
#include "libc/nt/struct/filecompressioninfo.h"
#include "libc/nt/struct/reparsedatabuffer.h"
#include "libc/str/str.h"
#include "libc/str/utf16.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/errfuns.h"
static textwindows uint32_t GetSizeOfReparsePoint(int64_t fh) {
wint_t x, y;
const char16_t *p;
uint32_t mem, i, n, z = 0;
struct NtReparseDataBuffer *rdb;
long buf[(sizeof(*rdb) + PATH_MAX * sizeof(char16_t)) / sizeof(long)];
mem = sizeof(buf);
rdb = (struct NtReparseDataBuffer *)buf;
if (DeviceIoControl(fh, kNtFsctlGetReparsePoint, 0, 0, rdb, mem, &n, 0)) {
i = 0;
n = rdb->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(char16_t);
p = (char16_t *)((char *)rdb->SymbolicLinkReparseBuffer.PathBuffer +
rdb->SymbolicLinkReparseBuffer.PrintNameOffset);
while (i < n) {
x = p[i++] & 0xffff;
if (!IsUcs2(x)) {
if (i < n) {
y = p[i++] & 0xffff;
x = MergeUtf16(x, y);
} else {
x = 0xfffd;
}
}
z += x < 0200 ? 1 : _bsrl(_tpenc(x)) >> 3;
}
} else {
STRACE("%s failed %m", "GetSizeOfReparsePoint");
}
return z;
}
textwindows int sys_fstat_nt(int64_t handle, struct stat *st) {
int filetype;
uint64_t actualsize;
struct NtFileCompressionInfo fci;
struct NtByHandleFileInformation wst;
if (!st) return efault();
if ((filetype = GetFileType(handle))) {
bzero(st, sizeof(*st));
switch (filetype) {
case kNtFileTypeChar:
st->st_mode = S_IFCHR | 0644;
break;
case kNtFileTypePipe:
st->st_mode = S_IFIFO | 0644;
break;
case kNtFileTypeDisk:
if (GetFileInformationByHandle(handle, &wst)) {
st->st_mode = 0555;
st->st_flags = wst.dwFileAttributes;
if (!(wst.dwFileAttributes & kNtFileAttributeReadonly)) {
st->st_mode |= 0200;
}
if (wst.dwFileAttributes & kNtFileAttributeDirectory) {
st->st_mode |= S_IFDIR;
} else if (wst.dwFileAttributes & kNtFileAttributeReparsePoint) {
st->st_mode |= S_IFLNK;
} else {
st->st_mode |= S_IFREG;
}
st->st_atim = FileTimeToTimeSpec(wst.ftLastAccessFileTime);
st->st_mtim = FileTimeToTimeSpec(wst.ftLastWriteFileTime);
st->st_ctim = FileTimeToTimeSpec(wst.ftCreationFileTime);
st->st_birthtim = st->st_ctim;
st->st_size = (uint64_t)wst.nFileSizeHigh << 32 | wst.nFileSizeLow;
st->st_blksize = PAGESIZE;
st->st_dev = wst.dwVolumeSerialNumber;
st->st_rdev = 0;
st->st_ino = (uint64_t)wst.nFileIndexHigh << 32 | wst.nFileIndexLow;
st->st_nlink = wst.nNumberOfLinks;
if (S_ISLNK(st->st_mode)) {
if (!st->st_size) {
st->st_size = GetSizeOfReparsePoint(handle);
}
} else {
actualsize = st->st_size;
if (S_ISREG(st->st_mode) &&
GetFileInformationByHandleEx(handle, kNtFileCompressionInfo,
&fci, sizeof(fci))) {
actualsize = fci.CompressedFileSize;
}
st->st_blocks = ROUNDUP(actualsize, PAGESIZE) / 512;
}
} else {
STRACE("%s failed %m", "GetFileInformationByHandle");
}
break;
default:
break;
}
return 0;
} else {
STRACE("%s failed %m", "GetFileType");
return __winerr();
}
}
| 5,902 | 137 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/umask.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
#include "libc/sysv/consts/nr.h"
/**
* Sets file mode creation mask.
*
* @return previous mask
* @note always succeeds
*/
unsigned umask(unsigned newmask) {
int oldmask;
if (!IsWindows()) {
oldmask = sys_umask(newmask);
} else {
// TODO(jart): what should we do with this?
oldmask = newmask;
}
STRACE("umask(%#o) â %#o", oldmask);
return oldmask;
}
| 2,356 | 42 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ntreturn.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/errors.h"
#include "libc/nt/ntdll.h"
/**
* Exitpoint for Windows NT system calls.
*/
textwindows int64_t ntreturn(uint32_t status) {
if (NtSuccess(status)) {
return 0;
} else {
errno = NtFacilityCode(status);
return -1;
}
}
| 2,123 | 34 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/chown.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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.
*
* @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 fchown() if pathname is already open()'d
* @see lchown() which does not dereference symbolic links
* @see /etc/passwd for user ids
* @see /etc/group for group ids
* @asyncsignalsafe
*/
int chown(const char *pathname, uint32_t uid, uint32_t gid) {
return fchownat(AT_FDCWD, pathname, uid, gid, 0);
}
| 2,399 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/alarm.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/itimerval.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/time/time.h"
/**
* Asks for single-shot SIGALRM to be raise()'d after interval.
*
* @param seconds until we get signal, or 0 to reset previous alarm()
* @return seconds previous alarm() had remaining, or -1u w/ errno
* @see setitimer()
* @asyncsignalsafe
*/
unsigned alarm(unsigned seconds) {
struct itimerval it;
bzero(&it, sizeof(it));
it.it_value.tv_sec = seconds;
_npassert(!setitimer(ITIMER_REAL, &it, &it));
if (!it.it_value.tv_sec && !it.it_value.tv_usec) {
return 0;
} else {
return MIN(1, it.it_value.tv_sec + (it.it_value.tv_usec > 5000000));
}
}
| 2,601 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/execvpe.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/intrin/asan.internal.h"
#include "libc/mem/mem.h"
#include "libc/sysv/errfuns.h"
/**
* Executes program, with path environment search.
*
* The current process is replaced with the executed one.
*
* @param prog is the program to launch
* @param argv is [file,argvâ..argvâââ,NULL]
* @param envp is ["key=val",...,NULL]
* @return doesn't return on success, otherwise -1 w/ errno
* @asyncsignalsafe
* @vforksafe
*/
int execvpe(const char *prog, char *const argv[], char *const *envp) {
char *exe;
char pathbuf[PATH_MAX];
if (IsAsan() && !__asan_is_valid_str(prog)) return efault();
if (!(exe = commandv(prog, pathbuf, sizeof(pathbuf)))) return -1;
return execve(exe, argv, envp);
}
| 2,611 | 44 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sigignore.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/str/str.h"
/**
* Configures process to ignore signal.
*/
int sigignore(int sig) {
struct sigaction sa;
bzero(&sa, sizeof(sa));
sa.sa_handler = SIG_IGN;
return (sigaction)(sig, &sa, 0);
}
| 2,120 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/getcwd-nt.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 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/intrin/tpenc.h"
#include "libc/macros.internal.h"
#include "libc/nt/files.h"
#include "libc/str/str.h"
#include "libc/str/utf16.h"
#include "libc/sysv/errfuns.h"
textwindows char *sys_getcwd_nt(char *buf, size_t size) {
uint64_t w;
wint_t x, y;
uint32_t n, i, j;
char16_t p[PATH_MAX];
if ((n = GetCurrentDirectory(ARRAYLEN(p), p))) {
if (4 + n + 1 <= size && 4 + n + 1 <= ARRAYLEN(p)) {
tprecode16to8(buf, size, p);
i = 0;
j = 0;
if (n >= 3 && isalpha(p[0]) && p[1] == ':' && p[2] == '\\') {
// turn c:\... into \c\...
p[1] = p[0];
p[0] = '\\';
} else if (n >= 7 && p[0] == '\\' && p[1] == '\\' && p[2] == '?' &&
p[3] == '\\' && isalpha(p[4]) && p[5] == ':' && p[6] == '\\') {
// turn \\?\c:\... into \c\...
buf[j++] = '/';
buf[j++] = p[4];
buf[j++] = '/';
i += 7;
}
while (i < n) {
x = p[i++] & 0xffff;
if (!IsUcs2(x)) {
if (i < n) {
y = p[i++] & 0xffff;
x = MergeUtf16(x, y);
} else {
x = 0xfffd;
}
}
if (x < 0200) {
if (x == '\\') {
x = '/';
}
w = x;
} else {
w = _tpenc(x);
}
do {
if (j < size) {
buf[j++] = w;
}
w >>= 8;
} while (w);
}
if (j < size) {
buf[j] = 0;
return buf;
}
}
erange();
return NULL;
} else {
__winerr();
return NULL;
}
}
| 3,469 | 86 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ktmppath.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/macros.internal.h"
#include "libc/nt/systeminfo.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
/**
* RII constant holding temporary file directory.
*
* The order of precedence is:
*
* - $TMPDIR/
* - GetTempPath()
* - /tmp/
*
* This guarantees trailing slash.
* We also guarantee `kTmpPath` won't be longer than `PATH_MAX / 2`.
*/
char kTmpPath[PATH_MAX];
static inline int IsAlpha(int c) {
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
}
__attribute__((__constructor__)) static void kTmpPathInit(void) {
int i;
char *s;
uint32_t n;
char16_t path16[PATH_MAX];
if ((s = getenv("TMPDIR")) && (n = strlen(s)) < PATH_MAX / 2) {
memcpy(kTmpPath, s, n);
if (n && kTmpPath[n - 1] != '/') {
kTmpPath[n + 0] = '/';
kTmpPath[n + 1] = 0;
}
return;
}
if (IsWindows() &&
((n = GetTempPath(ARRAYLEN(path16), path16)) && n < ARRAYLEN(path16))) {
// turn c:\foo\bar\ into c:/foo/bar/
for (i = 0; i < n; ++i) {
if (path16[i] == '\\') {
path16[i] = '/';
}
}
// turn c:/... into /c/...
if (IsAlpha(path16[0]) && path16[1] == ':' && path16[2] == '/') {
path16[1] = path16[0];
path16[0] = '/';
path16[2] = '/';
}
tprecode16to8(kTmpPath, sizeof(kTmpPath), path16);
return;
}
strcpy(kTmpPath, "/tmp/");
}
| 3,258 | 79 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ioctl_tcgets-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/struct/termios.h"
#include "libc/calls/ttydefaults.h"
#include "libc/nt/console.h"
#include "libc/nt/enum/consolemodeflags.h"
#include "libc/nt/struct/consolescreenbufferinfoex.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
textwindows int ioctl_tcgets_nt(int ignored, struct termios *tio) {
int64_t in, out;
bool32 inok, outok;
uint32_t inmode, outmode;
inok = GetConsoleMode((in = __getfdhandleactual(0)), &inmode);
outok = GetConsoleMode((out = __getfdhandleactual(1)), &outmode);
if (inok | outok) {
bzero(tio, sizeof(*tio));
tio->c_cflag |= CS8;
tio->c_cc[VINTR] = CTRL('C');
tio->c_cc[VQUIT] = CTRL('\\');
tio->c_cc[VERASE] = CTRL('?');
tio->c_cc[VKILL] = CTRL('U');
tio->c_cc[VEOF] = CTRL('D');
tio->c_cc[VMIN] = CTRL('A');
tio->c_cc[VSTART] = CTRL('Q');
tio->c_cc[VSTOP] = CTRL('S');
tio->c_cc[VSUSP] = CTRL('Z');
tio->c_cc[VREPRINT] = CTRL('R');
tio->c_cc[VDISCARD] = CTRL('O');
tio->c_cc[VWERASE] = CTRL('W');
tio->c_cc[VLNEXT] = CTRL('V');
if (inok) {
if (inmode & kNtEnableLineInput) {
tio->c_lflag |= ICANON;
}
if (inmode & kNtEnableEchoInput) {
tio->c_lflag |= ECHO;
}
if (inmode & kNtEnableProcessedInput) {
tio->c_lflag |= IEXTEN | ISIG;
if (tio->c_lflag | ECHO) {
tio->c_lflag |= ECHOE;
}
}
}
if (outok) {
if (outmode & kNtEnableProcessedOutput) {
tio->c_oflag |= OPOST;
}
if (!(outmode & kNtDisableNewlineAutoReturn)) {
tio->c_oflag |= OPOST | ONLCR;
}
}
return 0;
} else {
return enotty();
}
}
| 3,648 | 85 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sigwaitinfo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Waits for signal synchronously.
*
* @param set is signals for which we'll be waiting
* @param info if not null shall receive info about signal
* @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 ENOSYS on OpenBSD, XNU, and Windows
* @see sigtimedwait()
* @cancellationpoint
*/
int sigwaitinfo(const sigset_t *mask, siginfo_t *si) {
return sigtimedwait(mask, si, 0);
}
| 2,390 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fchownat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Changes owner and/or group of path.
*
* @param dirfd is open()'d relative-to directory, or AT_FDCWD, etc.
* @param uid is user id, or -1 to not change
* @param gid is group id, or -1 to not change
* @param flags can have AT_SYMLINK_NOFOLLOW, etc.
* @return 0 on success, or -1 w/ errno
* @raise ENOTSUP if `dirfd` or `path` use zip file system
* @see chown(), lchown() for shorthand notation
* @see /etc/passwd for user ids
* @see /etc/group for group ids
* @asyncsignalsafe
*/
int fchownat(int dirfd, const char *path, uint32_t uid, uint32_t gid,
int flags) {
int rc;
if (IsAsan() && !__asan_is_valid_str(path)) {
rc = efault();
} else if (_weaken(__zipos_notat) &&
(rc = __zipos_notat(dirfd, path)) == -1) {
rc = enotsup();
} else {
rc = sys_fchownat(dirfd, path, uid, gid, flags);
}
STRACE("fchownat(%s, %#s, %d, %d, %#b) â %d% m", DescribeDirfd(dirfd), path,
uid, gid, flags, rc);
return rc;
}
| 3,145 | 58 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pwrite.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/sysv/errfuns.h"
/**
* Writes to file at offset.
*
* This function never changes the current position of `fd`.
*
* @param fd is something open()'d earlier, noting pipes might not work
* @param buf is copied from, cf. copy_file_range(), sendfile(), etc.
* @param size in range [1..0x7ffff000] is reasonable
* @param offset is bytes from start of file at which write begins,
* which can exceed or overlap the end of file, in which case your
* file will be extended
* @return [1..size] bytes on success, or -1 w/ errno; noting zero is
* impossible unless size was passed as zero to do an error check
* @see pread(), write()
* @cancellationpoint
* @asyncsignalsafe
* @threadsafe
* @vforksafe
*/
ssize_t pwrite(int fd, const void *buf, size_t size, int64_t offset) {
ssize_t rc;
size_t wrote;
BEGIN_CANCELLATION_POINT;
if (offset < 0) {
rc = einval();
} else if (fd == -1) {
rc = ebadf();
} else if (IsAsan() && !__asan_is_valid(buf, size)) {
rc = efault();
} else if (!IsWindows()) {
rc = sys_pwrite(fd, buf, size, offset, offset);
} else if (__isfdkind(fd, kFdFile)) {
rc = sys_write_nt(fd, (struct iovec[]){{buf, size}}, 1, offset);
} else {
return ebadf();
}
if (rc != -1) {
wrote = (size_t)rc;
if (!wrote) {
_npassert(size == 0);
} else {
_npassert(wrote <= size);
}
}
END_CANCELLATION_POINT;
DATATRACE("pwrite(%d, %#.*hhs%s, %'zu, %'zd) â %'zd% m", fd,
MAX(0, MIN(40, rc)), buf, rc > 40 ? "..." : "", size, offset, rc);
return rc;
}
| 3,802 | 83 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/CPU_AND.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/cpuset.h"
#include "libc/macros.internal.h"
void CPU_AND(cpu_set_t *d, cpu_set_t *x, cpu_set_t *y) {
int i;
for (i = 0; i < ARRAYLEN(d->__bits); ++i) {
d->__bits[i] = x->__bits[i] & y->__bits[i];
}
}
| 2,075 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/printfds.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/intrin/kprintf.h"
static const char *__fdkind2str(int x) {
switch (x) {
case kFdEmpty:
return "kFdEmpty";
case kFdFile:
return "kFdFile";
case kFdSocket:
return "kFdSocket";
case kFdProcess:
return "kFdProcess";
case kFdConsole:
return "kFdConsole";
case kFdSerial:
return "kFdSerial";
case kFdZip:
return "kFdZip";
case kFdEpoll:
return "kFdEpoll";
default:
return "kFdWut";
}
}
void __printfds(void) {
int i;
__fds_lock();
for (i = 0; i < g_fds.n; ++i) {
if (!g_fds.p[i].kind) continue;
kprintf("%3d %s", i, __fdkind2str(g_fds.p[i].kind));
if (g_fds.p[i].zombie) kprintf(" zombie");
if (g_fds.p[i].flags) kprintf(" flags=%#x", g_fds.p[i].flags);
if (g_fds.p[i].mode) kprintf(" mode=%#o", g_fds.p[i].mode);
if (g_fds.p[i].handle) kprintf(" handle=%ld", g_fds.p[i].handle);
if (g_fds.p[i].extra) kprintf(" extra=%ld", g_fds.p[i].extra);
kprintf("\n");
}
__fds_unlock();
}
| 2,976 | 62 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/kemptyfd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
_Hide const struct Fd kEmptyFd;
| 1,945 | 23 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timespec_getres.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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 granularity, the C23 way.
*
* @param ts receives granularity as a relative timestamp
* @param base must be `TIME_UTC`
* @return `base` on success, or `0` on failure
*/
int timespec_getres(struct timespec *ts, int base) {
if (base == TIME_UTC && !clock_getres(CLOCK_REALTIME, ts)) {
return base;
} else {
return 0;
}
}
| 2,318 | 37 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/setregid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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 group ids.
*
* @param rgid is real group id or -1 to leave it unchanged
* @param egid is effective group id or -1 to leave it unchanged
* @return 0 on success or -1 w/ errno
*/
int setregid(uint32_t rgid, uint32_t egid) {
int rc;
rc = sys_setregid(rgid, egid);
STRACE("setregid(%d, %d) â %d% m", rgid, egid, rc);
return rc;
}
| 2,329 | 36 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sched_get_priority_max.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/sched-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/sched.h"
#include "libc/sysv/errfuns.h"
static int sys_sched_get_priority_max_netbsd(int policy) {
if (policy == SCHED_OTHER) {
return -1;
} else if (policy == SCHED_RR || policy == SCHED_FIFO) {
return 63; // NetBSD Libc needs 19 system calls to compute this!
} else {
return einval();
}
}
/**
* Returns maximum `sched_param::sched_priority` for `policy`.
*
* @return priority, or -1 w/ errno
* @raise ENOSYS on XNU, Windows, OpenBSD
* @raise EINVAL if `policy` is invalid
*/
int sched_get_priority_max(int policy) {
int rc;
if (IsNetbsd()) {
rc = sys_sched_get_priority_max_netbsd(policy);
} else {
rc = sys_sched_get_priority_max(policy);
}
STRACE("sched_get_priority_max(%s) â %d% m", DescribeSchedPolicy(policy), rc);
return rc;
}
| 2,835 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pwrite64.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"
pwrite64:
jmp pwrite
.endfn pwrite64,globl
| 1,916 | 24 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/state.internal.h | #ifndef COSMOPOLITAN_LIBC_CALLS_STATE_INTERNAL_H_
#define COSMOPOLITAN_LIBC_CALLS_STATE_INTERNAL_H_
#include "libc/intrin/nopl.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
_Hide extern int __vforked;
_Hide extern bool __time_critical;
_Hide extern unsigned __sighandrvas[NSIG];
_Hide extern unsigned __sighandflags[NSIG];
_Hide extern pthread_mutex_t __fds_lock_obj;
_Hide extern pthread_mutex_t __sig_lock_obj;
_Hide extern const struct NtSecurityAttributes kNtIsInheritable;
void __fds_lock(void);
void __fds_unlock(void);
void __fds_funlock(void);
void __sig_lock(void);
void __sig_unlock(void);
void __sig_funlock(void);
#ifdef _NOPL0
#define __fds_lock() _NOPL0("__threadcalls", __fds_lock)
#define __fds_unlock() _NOPL0("__threadcalls", __fds_unlock)
#else
#define __fds_lock() (__threaded ? __fds_lock() : 0)
#define __fds_unlock() (__threaded ? __fds_unlock() : 0)
#endif
#ifdef _NOPL0
#define __sig_lock() _NOPL0("__threadcalls", __sig_lock)
#define __sig_unlock() _NOPL0("__threadcalls", __sig_unlock)
#else
#define __sig_lock() (__threaded ? __sig_lock() : 0)
#define __sig_unlock() (__threaded ? __sig_unlock() : 0)
#endif
#define __vforked (__tls_enabled && (__get_tls()->tib_flags & TIB_FLAG_VFORKED))
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_STATE_INTERNAL_H_ */
| 1,440 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/wait4-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/nt/accounting.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/processaccess.h"
#include "libc/nt/enum/status.h"
#include "libc/nt/enum/wait.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/filetime.h"
#include "libc/nt/struct/processmemorycounters.h"
#include "libc/nt/synchronization.h"
#include "libc/runtime/ezmap.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/lcg.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/w.h"
#include "libc/sysv/errfuns.h"
#ifdef __x86_64__
static textwindows int sys_wait4_nt_impl(int pid, int *opt_out_wstatus,
int options,
struct rusage *opt_out_rusage) {
int64_t handle;
int rc, pids[64];
int64_t handles[64];
uint32_t dwExitCode;
bool shouldinterrupt;
uint32_t i, j, base, count, timeout;
struct NtProcessMemoryCountersEx memcount;
struct NtFileTime createfiletime, exitfiletime, kernelfiletime, userfiletime;
if (_check_interrupts(true, g_fds.p)) return -1;
__fds_lock();
if (pid != -1 && pid != 0) {
if (pid < 0) {
/* XXX: this is sloppy */
pid = -pid;
}
if (!__isfdkind(pid, kFdProcess)) {
/* XXX: this is sloppy (see fork-nt.c) */
if (!__isfdopen(pid) &&
(handle = OpenProcess(kNtSynchronize | kNtProcessQueryInformation,
true, pid))) {
if ((pid = __reservefd_unlocked(-1)) != -1) {
g_fds.p[pid].kind = kFdProcess;
g_fds.p[pid].handle = handle;
g_fds.p[pid].flags = O_CLOEXEC;
} else {
__fds_unlock();
CloseHandle(handle);
return echild();
}
} else {
__fds_unlock();
return echild();
}
}
handles[0] = g_fds.p[pid].handle;
pids[0] = pid;
count = 1;
} else {
count = __sample_pids(pids, handles, false);
if (!count) {
__fds_unlock();
return echild();
}
}
__fds_unlock();
for (;;) {
if (_check_interrupts(true, 0)) return -1;
dwExitCode = kNtStillActive;
if (options & WNOHANG) {
i = WaitForMultipleObjects(count, handles, false, 0);
if (i == kNtWaitTimeout) {
return 0;
}
} else {
i = WaitForMultipleObjects(count, handles, false,
__SIG_POLLING_INTERVAL_MS);
if (i == kNtWaitTimeout) {
continue;
}
}
if (i == kNtWaitFailed) {
STRACE("%s failed %u", "WaitForMultipleObjects", GetLastError());
return __winerr();
}
if (!GetExitCodeProcess(handles[i], &dwExitCode)) {
STRACE("%s failed %u", "GetExitCodeProcess", GetLastError());
return __winerr();
}
if (dwExitCode == kNtStillActive) continue;
if (opt_out_wstatus) { /* @see WEXITSTATUS() */
*opt_out_wstatus = (dwExitCode & 0xff) << 8;
}
if (opt_out_rusage) {
bzero(opt_out_rusage, sizeof(*opt_out_rusage));
bzero(&memcount, sizeof(memcount));
memcount.cb = sizeof(struct NtProcessMemoryCountersEx);
if (GetProcessMemoryInfo(handles[i], &memcount, sizeof(memcount))) {
opt_out_rusage->ru_maxrss = memcount.PeakWorkingSetSize / 1024;
opt_out_rusage->ru_majflt = memcount.PageFaultCount;
} else {
STRACE("%s failed %u", "GetProcessMemoryInfo", GetLastError());
}
if (GetProcessTimes(handles[i], &createfiletime, &exitfiletime,
&kernelfiletime, &userfiletime)) {
opt_out_rusage->ru_utime =
WindowsDurationToTimeVal(ReadFileTime(userfiletime));
opt_out_rusage->ru_stime =
WindowsDurationToTimeVal(ReadFileTime(kernelfiletime));
} else {
STRACE("%s failed %u", "GetProcessTimes", GetLastError());
}
}
CloseHandle(handles[i]);
__releasefd(pids[i]);
return pids[i];
}
}
textwindows int sys_wait4_nt(int pid, int *opt_out_wstatus, int options,
struct rusage *opt_out_rusage) {
int rc;
sigset_t oldmask, mask = {0};
sigaddset(&mask, SIGCHLD);
__sig_mask(SIG_BLOCK, &mask, &oldmask);
rc = sys_wait4_nt_impl(pid, opt_out_wstatus, options, opt_out_rusage);
__sig_mask(SIG_SETMASK, &oldmask, 0);
return rc;
}
#endif /* __x86_64__ */
| 6,593 | 163 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sig.internal.h | #ifndef COSMOPOLITAN_LIBC_CALLS_SIGNALS_INTERNAL_H_
#define COSMOPOLITAN_LIBC_CALLS_SIGNALS_INTERNAL_H_
#include "libc/atomic.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/ucontext.h"
#define __SIG_QUEUE_LENGTH 32
#define __SIG_POLLING_INTERVAL_MS 50
#define __SIG_LOGGING_INTERVAL_MS 1700
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct Signal {
struct Signal *next;
bool used;
int tid;
int sig;
int si_code;
};
struct Signals {
uint64_t sigmask; /* only if tls is disabled */
struct Signal *queue;
struct Signal mem[__SIG_QUEUE_LENGTH];
};
extern struct Signals __sig;
extern atomic_long __sig_count;
bool __sig_check(bool) _Hide;
bool __sig_handle(bool, int, int, ucontext_t *) _Hide;
int __sig_add(int, int, int) _Hide;
int __sig_mask(int, const sigset_t *, sigset_t *) _Hide;
int __sig_raise(int, int) _Hide;
void __sig_check_ignore(const int, const unsigned) _Hide;
void __sig_pending(sigset_t *) _Hide;
int __sig_is_applicable(struct Signal *) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_SIGNALS_INTERNAL_H_ */
| 1,147 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/mincore.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Tells you which pages are resident in memory.
*/
int mincore(void *addr, size_t length, unsigned char *vec) {
int rc;
rc = sys_mincore(addr, length, vec);
POLLTRACE("mincore(%p, %'zu, %p) â %d% m", addr, length, vec, rc);
return rc;
}
| 2,207 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/copyfile.h | #ifndef COSMOPOLITAN_LIBC_CALLS_COPYFILE_H_
#define COSMOPOLITAN_LIBC_CALLS_COPYFILE_H_
#define COPYFILE_NOCLOBBER 1
#define COPYFILE_PRESERVE_OWNER 2
#define COPYFILE_PRESERVE_TIMESTAMPS 4
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int _copyfile(const char *, const char *, int) paramsnonnull();
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_COPYFILE_H_ */
| 449 | 16 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/stat2cosmo.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/metastat.internal.h"
#include "libc/dce.h"
void __stat2cosmo(struct stat *restrict st, const union metastat *ms) {
if (st) {
if (IsLinux()) {
st->st_dev = ms->linux.st_dev;
st->st_ino = ms->linux.st_ino;
st->st_nlink = ms->linux.st_nlink;
st->st_mode = ms->linux.st_mode;
st->st_uid = ms->linux.st_uid;
st->st_gid = ms->linux.st_gid;
st->st_flags = 0;
st->st_rdev = ms->linux.st_rdev;
st->st_size = ms->linux.st_size;
st->st_blksize = ms->linux.st_blksize;
st->st_blocks = ms->linux.st_blocks;
st->st_atim = ms->linux.st_atim;
st->st_mtim = ms->linux.st_mtim;
st->st_ctim = ms->linux.st_ctim;
st->st_birthtim = st->st_ctim;
if (st->st_atim.tv_sec < st->st_ctim.tv_sec)
st->st_birthtim = st->st_atim;
if (st->st_mtim.tv_sec < st->st_ctim.tv_sec)
st->st_birthtim = st->st_mtim;
} else if (IsXnu()) {
st->st_dev = ms->xnu.st_dev;
st->st_ino = ms->xnu.st_ino;
st->st_nlink = ms->xnu.st_nlink;
st->st_mode = ms->xnu.st_mode;
st->st_uid = ms->xnu.st_uid;
st->st_gid = ms->xnu.st_gid;
st->st_flags = ms->xnu.st_flags;
st->st_rdev = ms->xnu.st_rdev;
st->st_size = ms->xnu.st_size;
st->st_blksize = ms->xnu.st_blksize;
st->st_blocks = ms->xnu.st_blocks;
st->st_gen = ms->xnu.st_gen;
st->st_atim = ms->xnu.st_atim;
st->st_mtim = ms->xnu.st_mtim;
st->st_ctim = ms->xnu.st_ctim;
st->st_birthtim = ms->xnu.st_birthtim;
} else if (IsFreebsd()) {
st->st_dev = ms->freebsd.st_dev;
st->st_ino = ms->freebsd.st_ino;
st->st_nlink = ms->freebsd.st_nlink;
st->st_mode = ms->freebsd.st_mode;
st->st_uid = ms->freebsd.st_uid;
st->st_gid = ms->freebsd.st_gid;
st->st_flags = ms->freebsd.st_flags;
st->st_rdev = ms->freebsd.st_rdev;
st->st_size = ms->freebsd.st_size;
st->st_blksize = ms->freebsd.st_blksize;
st->st_blocks = ms->freebsd.st_blocks;
st->st_gen = ms->freebsd.st_gen;
st->st_atim = ms->freebsd.st_atim;
st->st_mtim = ms->freebsd.st_mtim;
st->st_ctim = ms->freebsd.st_ctim;
st->st_birthtim = ms->freebsd.st_birthtim;
} else if (IsOpenbsd()) {
st->st_dev = ms->openbsd.st_dev;
st->st_ino = ms->openbsd.st_ino;
st->st_nlink = ms->openbsd.st_nlink;
st->st_mode = ms->openbsd.st_mode;
st->st_uid = ms->openbsd.st_uid;
st->st_gid = ms->openbsd.st_gid;
st->st_flags = ms->openbsd.st_flags;
st->st_rdev = ms->openbsd.st_rdev;
st->st_size = ms->openbsd.st_size;
st->st_blksize = ms->openbsd.st_blksize;
st->st_blocks = ms->openbsd.st_blocks;
st->st_gen = ms->openbsd.st_gen;
st->st_atim = ms->openbsd.st_atim;
st->st_mtim = ms->openbsd.st_mtim;
st->st_ctim = ms->openbsd.st_ctim;
st->st_birthtim = ms->openbsd.st_ctim;
} else if (IsNetbsd()) {
st->st_dev = ms->netbsd.st_dev;
st->st_ino = ms->netbsd.st_ino;
st->st_nlink = ms->netbsd.st_nlink;
st->st_mode = ms->netbsd.st_mode;
st->st_uid = ms->netbsd.st_uid;
st->st_gid = ms->netbsd.st_gid;
st->st_flags = ms->netbsd.st_flags;
st->st_rdev = ms->netbsd.st_rdev;
st->st_size = ms->netbsd.st_size;
st->st_blksize = ms->netbsd.st_blksize;
st->st_blocks = ms->netbsd.st_blocks;
st->st_gen = ms->netbsd.st_gen;
st->st_atim = ms->netbsd.st_atim;
st->st_mtim = ms->netbsd.st_mtim;
st->st_ctim = ms->netbsd.st_ctim;
st->st_birthtim = ms->netbsd.st_birthtim;
}
}
}
| 5,480 | 115 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/mkdirat-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/syscall_support-nt.internal.h"
#include "libc/nt/files.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_mkdirat_nt(int dirfd, const char *path, uint32_t mode) {
int e;
char16_t *p, path16[PATH_MAX];
/* if (strlen(path) > 248) return enametoolong(); */
if (__mkntpathat(dirfd, path, 0, path16) == -1) return -1;
if (CreateDirectory(path16, 0)) return 0;
return __fix_enotdir(-1, path16);
}
| 2,290 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timespec_cmp.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Compares nanosecond timestamps.
*
* @return 0 if equal, -1 if `a < b`, or +1 if `a > b`
*/
int timespec_cmp(struct timespec a, struct timespec b) {
int cmp;
if (!(cmp = (a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec))) {
cmp = (a.tv_nsec > b.tv_nsec) - (a.tv_nsec < b.tv_nsec);
}
return cmp;
}
| 2,191 | 33 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ftruncate-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/syscall_support-nt.internal.h"
#include "libc/nt/enum/filemovemethod.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/sysv/errfuns.h"
textwindows int sys_ftruncate_nt(int64_t handle, uint64_t length) {
bool32 ok;
int64_t tell;
tell = -1;
if ((ok = SetFilePointerEx(handle, 0, &tell, kNtFileCurrent))) {
ok = SetFilePointerEx(handle, length, NULL, kNtFileBegin) &&
SetEndOfFile(handle);
_npassert(SetFilePointerEx(handle, tell, NULL, kNtFileBegin));
}
if (ok) {
return 0;
} else if (GetLastError() == kNtErrorAccessDenied) {
return einval(); // ftruncate() doesn't raise EACCES
} else {
return __winerr();
}
}
| 2,593 | 44 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/__sig_pending.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/sigset.h"
#ifdef __x86_64__
/**
* Determines the pending signals on New Technology.
*
* @param pending is to hold the pending signals
* @threadsafe
*/
textwindows void __sig_pending(sigset_t *pending) {
struct Signal *s;
sigemptyset(pending);
if (__sig.queue) {
__sig_lock();
for (s = __sig.queue; s; s = s->next) {
if (__sig_is_applicable(s) &&
__sighandrvas[s->sig] != (unsigned)(intptr_t)SIG_IGN) {
sigaddset(pending, s->sig);
}
}
__sig_unlock();
}
}
#endif /* __x86_64__ */
| 2,510 | 48 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/setfsgid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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 gid
*/
int setfsgid(unsigned gid) {
int rc;
if (IsLinux()) {
rc = sys_setfsgid(gid);
} else {
rc = getegid();
setegid(gid);
}
STRACE("setfsgid(%d) â %d% m", gid, rc);
return rc;
}
| 2,274 | 39 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/CPU_XOR.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/cpuset.h"
#include "libc/macros.internal.h"
void CPU_XOR(cpu_set_t *d, cpu_set_t *x, cpu_set_t *y) {
int i;
for (i = 0; i < ARRAYLEN(d->__bits); ++i) {
d->__bits[i] = x->__bits[i] ^ y->__bits[i];
}
}
| 2,075 | 28 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sched_setscheduler.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/calls/struct/sched_param.internal.h"
#include "libc/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/tls.h"
/**
* Sets scheduling policy of process, e.g.
*
* struct sched_param p = {sched_get_priority_max(SCHED_OTHER)};
* LOGIFNEG1(sched_setscheduler(0, SCHED_OTHER, &p));
*
* Processes with numerically higher priority values are scheduled
* before processes with numerically lower priority values.
*
* @param pid is the id of the process whose scheduling policy should be
* changed. 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`.
*
* @param policy specifies the kernel's timesharing strategy.
*
* The `policy` must have one of:
*
* - `SCHED_OTHER` (or `SCHED_NORMAL`) for the default policy
*
* - `SCHED_RR` for real-time round-robin scheduling
*
* - `SCHED_FIFO` for real-time first-in first-out scheduling
*
* - `SCHED_BATCH` for "batch" style execution of processes if
* supported (Linux), otherwise it's treated as `SCHED_OTHER`
*
* - `SCHED_IDLE` for running very low priority background jobs if
* it's supported (Linux), otherwise this is `SCHED_OTHER`.
* Pledging away scheduling privilege is permanent for your
* process; if a subsequent attempt is made to restore the
* `SCHED_OTHER` policy then this system call will `EPERM` (but on
* older kernels like RHEL7 this isn't the case). This policy
* isn't available on old Linux kernels like RHEL5, where it'll
* raise `EINVAL`.
*
* The `policy` may optionally bitwise-or any one of:
*
* - `SCHED_RESET_ON_FORK` will cause the scheduling policy to be
* automatically reset to `SCHED_NORMAL` upon fork() if supported;
* otherwise this flag is polyfilled as zero, so that it may be
* safely used (without having to check if the o/s is Linux).
*
* @param param must be set to the scheduler parameter, which should be
* greater than or equal to sched_get_priority_min(policy) and less
* than or equal to sched_get_priority_max(policy). Linux allows the
* static priority range 1 to 99 for the `SCHED_FIFO` and `SCHED_RR`
* policies, and the priority 0 is used for the remaining policies.
* You should still consider calling the function, because on NetBSD
* the correct priority might be -1.
*
* @return the former scheduling policy of the specified process. If
* this function fails, then the scheduling policy is not changed,
* and -1 w/ errno is returned.
*
* @raise ENOSYS on XNU, Windows, OpenBSD
* @raise EPERM if not authorized to use scheduler in question (e.g.
* trying to use a real-time scheduler as non-root on Linux) or
* possibly because pledge() was used and isn't allowing this
* @raise EINVAL if `param` is NULL
* @raise EINVAL if `policy` is invalid
* @raise EINVAL if `param` has value out of ranges defined by `policy`
* @vforksafe
*/
int sched_setscheduler(int pid, int policy, const struct sched_param *param) {
int rc, old;
struct sched_param p;
if (IsNetbsd()) {
rc = sys_sched_getscheduler_netbsd(pid, &p);
} else {
rc = sys_sched_getscheduler(pid);
}
if (rc != -1) {
old = rc;
if (IsNetbsd()) {
rc = sys_sched_setparam_netbsd(pid, P_ALL_LWPS, policy, param);
} else {
rc = sys_sched_setscheduler(pid, policy, param);
}
if (rc != -1) {
rc = old;
}
}
STRACE("sched_setscheduler(%d, %s, %s) â %d% m", pid,
DescribeSchedPolicy(policy), DescribeSchedParam(param), rc);
return rc;
}
| 5,968 | 122 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/mlock.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2023 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/nt/memory.h"
#include "libc/runtime/runtime.h"
static textwindows int sys_mlock_nt(const void *addr, size_t len) {
if (VirtualLock(addr, len)) {
return 0;
} else {
return __winerr();
}
}
/**
* Locks virtual memory interval into RAM, preventing it from swapping.
*
* @return 0 on success, or -1 w/ errno
*/
int mlock(const void *addr, size_t len) {
if (!IsWindows()) {
return sys_mlock(addr, len);
} else {
return sys_mlock_nt(addr, len);
}
}
| 2,431 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/pread.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Reads from file at offset.
*
* This function never changes the current position of `fd`.
*
* @param fd is something open()'d earlier, noting pipes might not work
* @param buf is copied into, cf. copy_file_range(), sendfile(), etc.
* @param size in range [1..0x7ffff000] is reasonable
* @param offset is bytes from start of file at which read begins
* @return [1..size] bytes on success, 0 on EOF, or -1 w/ errno; with
* exception of size==0, in which case return zero means no error
* @raise ESPIPE if `fd` isn't seekable
* @raise EINVAL if `offset` is negative
* @raise EBADF if `fd` isn't an open file descriptor
* @raise EIO if a complicated i/o error happened
* @raise EINTR if signal was delivered instead
* @raise ECANCELED if thread was cancelled in masked mode
* @see pwrite(), write()
* @cancellationpoint
* @asyncsignalsafe
* @threadsafe
* @vforksafe
*/
ssize_t pread(int fd, void *buf, size_t size, int64_t offset) {
ssize_t rc;
BEGIN_CANCELLATION_POINT;
if (offset < 0) {
rc = einval();
} else if (fd < 0) {
rc = ebadf();
} else if (IsAsan() && !__asan_is_valid(buf, size)) {
rc = efault();
} else if (__isfdkind(fd, kFdZip)) {
rc = _weaken(__zipos_read)(
(struct ZiposHandle *)(intptr_t)g_fds.p[fd].handle,
(struct iovec[]){{buf, size}}, 1, offset);
} else if (!IsWindows()) {
rc = sys_pread(fd, buf, size, offset, offset);
} else if (__isfdkind(fd, kFdFile)) {
rc = sys_read_nt(&g_fds.p[fd], (struct iovec[]){{buf, size}}, 1, offset);
} else {
rc = ebadf();
}
_npassert(rc == -1 || (size_t)rc <= size);
END_CANCELLATION_POINT;
DATATRACE("pread(%d, [%#.*hhs%s], %'zu, %'zd) â %'zd% m", fd,
MAX(0, MIN(40, rc)), buf, rc > 40 ? "..." : "", size, offset, rc);
return rc;
}
| 4,165 | 86 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sysinfo-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/sysinfo.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/nt/accounting.h"
#include "libc/nt/struct/memorystatusex.h"
#include "libc/nt/struct/systeminfo.h"
#include "libc/nt/systeminfo.h"
textwindows int sys_sysinfo_nt(struct sysinfo *info) {
struct NtMemoryStatusEx memstat;
struct NtSystemInfo sysinfo;
GetSystemInfo(&sysinfo);
memstat.dwLength = sizeof(struct NtMemoryStatusEx);
if (GlobalMemoryStatusEx(&memstat)) {
info->totalram = memstat.ullTotalPhys;
info->freeram = memstat.ullAvailPhys;
info->procs = sysinfo.dwNumberOfProcessors;
info->mem_unit = 1;
return 0;
} else {
return __winerr();
}
}
| 2,527 | 41 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/posix_openpt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/termios.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
/**
* Opens new pseudo teletypewriter.
*
* @return fd of master pty, or -1 w/ errno
* @params flags is usually O_RDWR|O_NOCTTY
* @return file descriptor, or -1 w/ errno
*/
int posix_openpt(int flags) {
int rc;
if ((flags & O_ACCMODE) != O_RDWR) {
rc = einval();
} else if (IsLinux() || IsXnu() || IsNetbsd()) {
rc = sys_openat(AT_FDCWD, "/dev/ptmx", flags, 0);
} else if (IsOpenbsd()) {
rc = sys_openat(AT_FDCWD, "/dev/ptm", flags, 0);
} else if (IsFreebsd()) {
rc = sys_posix_openpt(flags);
if (rc == -1 && errno == ENOSPC) errno = EAGAIN;
} else {
rc = enosys();
}
STRACE("posix_openpt(%s) â %d% m", DescribeOpenFlags(flags), rc);
return rc;
}
| 2,842 | 53 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/timeval_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/timeval.h"
#include "libc/limits.h"
/**
* Reduces `ts` from 1e-6 to 1e-3 granularity w/ ceil rounding.
*
* This function returns the absolute number of milliseconds in a
* timeval. Ceiling rounding is used. 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 valial 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 timeval_tomillis(struct timeval ts) {
int64_t ms;
// reduce precision from micros to millis
if (ts.tv_usec <= 999000) {
ts.tv_usec = (ts.tv_usec + 999) / 1000;
} else {
ts.tv_usec = 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_usec, &ms)) {
return ms;
} else if (ts.tv_sec < 0) {
return INT64_MIN;
} else {
return INT64_MAX;
}
}
| 2,992 | 57 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/setpgid.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/nt/console.h"
#include "libc/sysv/errfuns.h"
/**
* Changes process group for process.
* @vforksafe
*/
int setpgid(int pid, int pgid) {
int rc, me;
if (!IsWindows()) {
rc = sys_setpgid(pid, pgid);
} else {
me = getpid();
if ((!pid || pid == me) && (!pgid || pgid == me)) {
/*
* "When a process is created with CREATE_NEW_PROCESS_GROUP
* specified, an implicit call to SetConsoleCtrlHandler(NULL,TRUE)
* is made on behalf of the new process; this means that the new
* process has CTRL+C disabled. This lets shells handle CTRL+C
* themselves, and selectively pass that signal on to
* sub-processes. CTRL+BREAK is not disabled, and may be used to
* interrupt the process/process group."
* ââQuoth MSDN § CreateProcessW()
*/
if (SetConsoleCtrlHandler(0, 1)) {
rc = 0;
} else {
rc = __winerr();
}
} else {
// irregular use cases not supported on windows
rc = einval();
}
}
STRACE("setpgid(%d, %d) â %d% m", pid, pgid, rc);
return rc;
}
| 3,162 | 61 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/netbsdtramp.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 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/macros.internal.h"
.privileged
__restore_rt_netbsd:
mov %r15,%rdi
mov $308,%eax # setcontext
syscall
or $-1,%edi
mov $1,%rax # exit
syscall
.endfn __restore_rt_netbsd,globl,hidden
| 2,044 | 30 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/sigprocmask.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/sig.internal.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/sigset.internal.h"
#include "libc/dce.h"
#include "libc/fmt/itoa.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/str/str.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
/**
* Changes signal blocking state of calling thread, e.g.:
*
* sigset_t neu,old;
* sigfillset(&neu);
* sigprocmask(SIG_BLOCK, &neu, &old);
* sigprocmask(SIG_SETMASK, &old, NULL);
*
* @param how can be SIG_BLOCK (U), SIG_UNBLOCK (/), SIG_SETMASK (=)
* @param set is the new mask content (optional)
* @param oldset will receive the old mask (optional) and can't overlap
* @return 0 on success, or -1 w/ errno
* @raise EFAULT if `set` or `oldset` is bad memory
* @raise EINVAL if `how` is invalid
* @asyncsignalsafe
* @restartable
* @vforksafe
*/
int sigprocmask(int how, const sigset_t *opt_set, sigset_t *opt_out_oldset) {
int res, rc, arg1;
sigset_t old = {0};
const sigset_t *arg2;
if (IsAsan() &&
((opt_set && !__asan_is_valid(opt_set, sizeof(*opt_set))) ||
(opt_out_oldset &&
!__asan_is_valid(opt_out_oldset, sizeof(*opt_out_oldset))))) {
rc = efault();
} else if (IsMetal() || IsWindows()) {
rc = __sig_mask(how, opt_set, &old);
if (_weaken(__sig_check)) {
_weaken(__sig_check)(true);
}
} else {
rc = sys_sigprocmask(how, opt_set, opt_out_oldset ? &old : 0);
}
if (rc != -1 && opt_out_oldset) {
*opt_out_oldset = old;
}
STRACE("sigprocmask(%s, %s, [%s]) â %d% m", DescribeHow(how),
DescribeSigset(0, opt_set), DescribeSigset(rc, opt_out_oldset), rc);
return rc;
}
| 3,709 | 76 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/posix_madvise.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/errno.h"
/**
* Advises kernel about memory intentions, the POSIX way.
*
* @return 0 on success, or errno on error
* @returnserrno
* @threadsafe
*/
errno_t posix_madvise(void *addr, uint64_t len, int advice) {
int rc, e = errno;
rc = madvise(addr, len, advice);
if (rc == -1) {
rc = errno;
errno = e;
}
return rc;
}
| 2,221 | 38 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/onntconsoleevent_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/macros.internal.h"
.text.windows
__onntconsoleevent_nt:
ezlea __onntconsoleevent,ax
jmp __nt2sysv
.endfn __onntconsoleevent_nt,globl,hidden
.init.start 300,_init_onntconsoleevent
ezlea __onntconsoleevent_nt,cx
pushpop 1,%rdx
ntcall __imp_SetConsoleCtrlHandler
.init.end 300,_init_onntconsoleevent,globl,hidden
| 2,171 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/clock_gettime.internal.h | #ifndef COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_
#define COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_
#include "libc/calls/struct/timespec.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef int clock_gettime_f(int, struct timespec *);
extern clock_gettime_f *__clock_gettime;
clock_gettime_f *__clock_gettime_get(bool *) _Hide;
int __clock_gettime_init(int, struct timespec *) _Hide;
int sys_clock_gettime_mono(struct timespec *) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_CLOCK_GETTIME_H_ */
| 577 | 17 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/fchmod.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/sysv/errfuns.h"
/**
* Changes file permissions via open()'d file descriptor.
*
* @param mode contains octal flags (base 8)
* @asyncsignalsafe
* @see chmod()
*/
int fchmod(int fd, uint32_t mode) {
/* TODO(jart): Windows */
return sys_fchmod(fd, mode);
}
| 2,213 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ioctl_siocgifconf.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/ioctl.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/sock/internal.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/ifconf.h"
#include "libc/sock/struct/ifreq.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/sio.h"
#include "libc/sysv/errfuns.h"
/* SIOCGIFCONF:
* Takes an struct ifconf object of a given size
* Modifies the following:
* - ifc_len: set it to the number of valid ifreq structures representing
* the interfaces
* - ifc_ifcu.ifcu_req: sets the name of the interface for each interface
* The ifc_len is an input/output parameter: set it to the total size of
* the ifcu_buf (ifcu_req) buffer on input.
*/
int ioctl_siocgifconf_nt(int, struct ifconf *) _Hide;
int ioctl_siocgifaddr_nt(int, struct ifreq *) _Hide;
int ioctl_siocgifflags_nt(int, struct ifreq *) _Hide;
int ioctl_siocgifnetmask_nt(int, struct ifreq *) _Hide;
int ioctl_siocgifbrdaddr_nt(int, struct ifreq *) _Hide;
static int ioctl_siocgifconf_sysv(int fd, struct ifconf *ifc) {
/*
* We're 100% compatible with Linux.
* BSD ABIs mainly differ by having sockaddr::sa_len
* XNU uses a 32-bit length in a struct that's packed!
*/
int i, rc, fam;
char *b, *p, *e;
char ifcBsd[16];
struct ifreq *req;
struct ifreq *end;
uint32_t bufLen, ip;
size_t numReq, bufMax;
if (IsLinux()) return sys_ioctl(fd, SIOCGIFCONF, ifc);
if (!_weaken(malloc)) return enomem();
bufMax = 15000; /* conservative guesstimate */
if (!(b = _weaken(malloc)(bufMax))) return enomem();
memcpy(ifcBsd, &bufMax, 8); /* ifc_len */
memcpy(ifcBsd + (IsXnu() ? 4 : 8), &b, 8); /* ifc_buf */
if ((rc = sys_ioctl(fd, SIOCGIFCONF, &ifcBsd)) != -1) {
/*
* On XNU the size of the struct ifreq is different than Linux.
* On Linux is fixed (40 bytes), but on XNU the struct sockaddr
* has variable length, making the whole struct ifreq a variable
* sized record.
*/
memcpy(&bufLen, b, 4);
req = ifc->ifc_req;
end = req + ifc->ifc_len / sizeof(*req);
for (p = b, e = p + MIN(bufMax, READ32LE(ifcBsd)); p + 16 + 16 <= e;
p += IsBsd() ? 16 + MAX(16, p[16] & 255) : 40) {
fam = p[IsBsd() ? 17 : 16] & 255;
if (fam != AF_INET) continue;
ip = READ32BE(p + 20);
bzero(req, sizeof(*req));
memcpy(req->ifr_name, p, 16);
memcpy(&req->ifr_addr, p + 16, 16);
req->ifr_addr.sa_family = fam;
((struct sockaddr_in *)&req->ifr_addr)->sin_addr.s_addr = htonl(ip);
++req;
}
ifc->ifc_len = (char *)req - ifc->ifc_buf; /* Adjust len */
}
if (_weaken(free)) _weaken(free)(b);
return rc;
}
forceinline void Sockaddr2linux(void *saddr) {
char *p;
if (saddr) {
p = saddr;
p[0] = p[1];
p[1] = 0;
}
}
/* Used for all the ioctl that returns sockaddr structure that
* requires adjustment between Linux and XNU
*/
static int ioctl_siocgifaddr_sysv(int fd, uint64_t op, struct ifreq *ifr) {
if (sys_ioctl(fd, op, ifr) == -1) return -1;
if (IsBsd()) Sockaddr2linux(&ifr->ifr_addr);
return 0;
}
/**
* Returns information about network interfaces.
*
* @see ioctl(fd, SIOCGIFCONF, tio) dispatches here
*/
int ioctl_siocgifconf(int fd, ...) {
int rc;
va_list va;
struct ifconf *ifc;
va_start(va, fd);
ifc = va_arg(va, struct ifconf *);
va_end(va);
if (!IsWindows()) {
rc = ioctl_siocgifconf_sysv(fd, ifc);
} else {
rc = ioctl_siocgifconf_nt(fd, ifc);
}
STRACE("%s(%d) â %d% m", "ioctl_siocgifconf", fd, rc);
return rc;
}
int ioctl_siocgifaddr(int fd, ...) {
va_list va;
struct ifreq *ifr;
va_start(va, fd);
ifr = va_arg(va, struct ifreq *);
va_end(va);
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFADDR, ifr);
} else {
return ioctl_siocgifaddr_nt(fd, ifr);
}
}
int ioctl_siocgifnetmask(int fd, ...) {
va_list va;
struct ifreq *ifr;
va_start(va, fd);
ifr = va_arg(va, struct ifreq *);
va_end(va);
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFNETMASK, ifr);
} else {
return ioctl_siocgifnetmask_nt(fd, ifr);
}
}
int ioctl_siocgifbrdaddr(int fd, ...) {
va_list va;
struct ifreq *ifr;
va_start(va, fd);
ifr = va_arg(va, struct ifreq *);
va_end(va);
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFBRDADDR, ifr);
} else {
return ioctl_siocgifbrdaddr_nt(fd, ifr);
}
}
int ioctl_siocgifdstaddr(int fd, ...) {
va_list va;
struct ifreq *ifr;
va_start(va, fd);
ifr = va_arg(va, struct ifreq *);
va_end(va);
if (!IsWindows()) {
return ioctl_siocgifaddr_sysv(fd, SIOCGIFDSTADDR, ifr);
} else {
return enotsup();
/* Not supported - Unknown how to find out how to retrieve the destination
* address of a PPP from the interface list returned by the
* GetAdaptersAddresses function
*
return ioctl_siocgifdstaddr_nt(fd, ifc);
*/
}
}
int ioctl_siocgifflags(int fd, ...) {
va_list va;
struct ifreq *ifr;
va_start(va, fd);
ifr = va_arg(va, struct ifreq *);
va_end(va);
if (!IsWindows()) {
/* Both XNU and Linux are for once compatible here... */
return ioctl_default(fd, SIOCGIFFLAGS, ifr);
} else {
return ioctl_siocgifflags_nt(fd, ifr);
}
}
| 7,311 | 209 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ioctl_tcsets.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/ioctl.h"
#include "libc/calls/struct/metatermios.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/termios.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/nomultics.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
void __on_ioctl_tcsets(int);
int ioctl_tcsets_nt(int, uint64_t, const struct termios *);
static int ioctl_tcsets_metal(int fd, uint64_t request,
const struct termios *tio) {
return 0;
}
static int ioctl_tcsets_sysv(int fd, uint64_t request,
const struct termios *tio) {
union metatermios mt;
if (IsAsan() && !__asan_is_valid(tio, sizeof(*tio))) return efault();
return sys_ioctl(fd, request, __termios2host(&mt, tio));
}
/**
* Changes terminal behavior.
*
* @see tcsetattr(fd, TCSA{NOW,DRAIN,FLUSH}, tio) dispatches here
* @see ioctl(fd, TCSETS{,W,F}, tio) dispatches here
* @see ioctl(fd, TIOCGETA{,W,F}, tio) dispatches here
*/
int ioctl_tcsets(int fd, uint64_t request, ...) {
int rc;
va_list va;
static bool once;
const struct termios *tio;
va_start(va, request);
tio = va_arg(va, const struct termios *);
va_end(va);
if (0 <= fd && fd <= 2 && _weaken(__on_ioctl_tcsets)) {
if (!once) {
_weaken(__on_ioctl_tcsets)(fd);
once = true;
}
}
if (!tio || (IsAsan() && !__asan_is_valid(tio, sizeof(*tio)))) {
rc = efault();
} else if (fd >= 0) {
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
rc = enotty();
} else if (IsMetal()) {
rc = ioctl_tcsets_metal(fd, request, tio);
} else if (!IsWindows()) {
rc = ioctl_tcsets_sysv(fd, request, tio);
} else {
rc = ioctl_tcsets_nt(fd, request, tio);
}
} else {
rc = einval();
}
STRACE("ioctl_tcsets(%d, %p, %p) â %d% m", fd, request, tio, rc);
return rc;
}
| 3,865 | 86 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/close.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/state.internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sock/syscall_fd.internal.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Closes file descriptor.
*
* This function releases resources returned by functions such as:
*
* - openat()
* - socket()
* - accept()
* - epoll_create()
* - landlock_create_ruleset()
*
* This function should never be reattempted if an error is returned;
* however, that doesn't mean the error should be ignored. This goes
* against the conventional wisdom of looping on `EINTR`.
*
* @return 0 on success, or -1 w/ errno
* @raise EINTR if signal was delivered; do *not* retry
* @raise EBADF if `fd` is negative or not open; however, an exception
* is made by Cosmopolitan Libc for `close(-1)` which returns zero
* and does nothing, in order to assist with code that may wish to
* close the same resource multiple times without dirtying `errno`
* @raise EIO if a low-level i/o error occurred
* @asyncsignalsafe
* @vforksafe
*/
int close(int fd) {
int rc;
if (fd == -1) {
rc = 0;
} else if (fd < 0) {
rc = ebadf();
} else {
// for performance reasons we want to avoid holding __fds_lock()
// while sys_close() is happening. this leaves the kernel / libc
// having a temporarily inconsistent state. routines that obtain
// file descriptors the way __zipos_open() does need to retry if
// there's indication this race condition happened.
if (__isfdkind(fd, kFdZip)) {
rc = _weaken(__zipos_close)(fd);
} else {
if (!IsWindows() && !IsMetal()) {
rc = sys_close(fd);
} else if (IsMetal()) {
rc = 0;
} else {
if (__isfdkind(fd, kFdEpoll)) {
rc = _weaken(sys_close_epoll_nt)(fd);
} else if (__isfdkind(fd, kFdSocket)) {
rc = _weaken(sys_closesocket_nt)(g_fds.p + fd);
} else if (__isfdkind(fd, kFdFile) || //
__isfdkind(fd, kFdConsole) || //
__isfdkind(fd, kFdProcess)) { //
rc = sys_close_nt(g_fds.p + fd, fd);
} else {
rc = eio();
}
}
}
if (!__vforked) {
__releasefd(fd);
}
}
STRACE("%s(%d) â %d% m", "close", fd, rc);
return rc;
}
| 4,385 | 97 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/tcsetwinsize.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2023 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/ioctl.h"
#include "libc/calls/struct/winsize.h"
/**
* Sets terminal window size attributes.
*/
int tcsetwinsize(int fd, const struct winsize *ws) {
return ioctl_tiocswinsz(fd, ws);
}
| 2,075 | 29 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/unlink.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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"
/**
* Removes file.
*
* This may be used to delete files but it can't be used to delete
* directories. The exception are symlinks, which this will delete
* however not the linked directory.
*
* @return 0 on success, or -1 w/ errno
* @asyncsignalsafe
*/
int unlink(const char *name) {
return unlinkat(AT_FDCWD, name, 0);
}
| 2,233 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ttydefaults.h | #ifndef COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_
#define COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_
#include "libc/sysv/consts/baud.internal.h"
#include "libc/sysv/consts/termios.h"
#define TTYDEF_IFLAG (BRKINT | ISTRIP | ICRNL | IMAXBEL | IXON | IXANY)
#define TTYDEF_OFLAG (OPOST | ONLCR | XTABS)
#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE | ECHOKE | ECHOCTL)
#define TTYDEF_CFLAG (CREAD | CS8 | HUPCL)
#define TTYDEF_SPEED (B9600)
#define CTRL(x) ((x) ^ 0100)
#define CEOF CTRL('D')
#define CERASE CTRL('?')
#define CINTR CTRL('C')
#define CKILL CTRL('U')
#define CQUIT CTRL('\\')
#define CSUSP CTRL('Z')
#define CDSUSP CTRL('Y')
#define CSTART CTRL('Q')
#define CSTOP CTRL('S')
#define CLNEXT CTRL('V')
#define CDISCARD CTRL('O')
#define CWERASE CTRL('W')
#define CREPRINT CTRL('R')
#define CEOT CEOF
#define CBRK CEOL
#define CRPRNT CREPRINT
#define CFLUSH CDISCARD
#define CEOL 255
#define CMIN 1
#define CTIME 0
#endif /* COSMOPOLITAN_LIBC_CALLS_TTYDEFAULTS_H_ */
| 1,037 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/renameat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Renames files relative to directories.
*
* This is generally an atomic operation with the file system, since all
* it's doing is changing a name associated with an inode. However, that
* means rename() doesn't permit your `oldpathname` and `newpathname` to
* be on separate file systems, in which case this returns EXDEV. That's
* also the case on Windows.
*
* @param olddirfd is normally AT_FDCWD but if it's an open directory
* and oldpath is relative, then oldpath become relative to dirfd
* @param newdirfd is normally AT_FDCWD but if it's an open directory
* and newpath is relative, then newpath become relative to dirfd
* @return 0 on success, or -1 w/ errno
*/
int renameat(int olddirfd, const char *oldpath, int newdirfd,
const char *newpath) {
int rc;
if (IsAsan() &&
(!__asan_is_valid_str(oldpath) || !__asan_is_valid_str(newpath))) {
rc = efault();
} else if (_weaken(__zipos_notat) &&
((rc = __zipos_notat(olddirfd, oldpath)) == -1 ||
(rc = __zipos_notat(newdirfd, newpath)) == -1)) {
STRACE("zipos renameat not supported yet");
} else if (!IsWindows()) {
rc = sys_renameat(olddirfd, oldpath, newdirfd, newpath);
} else {
rc = sys_renameat_nt(olddirfd, oldpath, newdirfd, newpath);
}
STRACE("renameat(%s, %#s, %s, %#s) â %d% m", DescribeDirfd(olddirfd), oldpath,
DescribeDirfd(newdirfd), newpath, rc);
return rc;
}
| 3,687 | 65 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/utimensat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/asan.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/timespec.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/errfuns.h"
#include "libc/zipos/zipos.internal.h"
/**
* Sets access/modified time on file, the modern way.
*
* XNU only has microsecond (1e-6) accuracy and there's no
* `dirfd`-relative support. Windows only has hectonanosecond (1e-7)
* accuracy. RHEL5 doesn't support `dirfd` or `flags` and will truncate
* timestamps to seconds.
*
* If you'd rather specify an open file descriptor rather than its
* filesystem path, then consider using futimens().
*
* @param dirfd can be `AT_FDCWD` or an open directory
* @param path is filename whose timestamps should be modified
* @param ts is {access, modified} timestamps, or null for current time
* @param flags can have `AT_SYMLINK_NOFOLLOW` when `path` is specified
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if `flags` had an unrecognized value
* @raise EPERM if pledge() is in play without `fattr` promise
* @raise EACCES if unveil() is in play and `path` isn't unveiled
* @raise ENOTSUP if `path` is a zip filesystem path or `dirfd` is zip
* @raise EINVAL if `ts` specifies a nanosecond value that's out of range
* @raise ENAMETOOLONG if symlink-resolved `path` length exceeds `PATH_MAX`
* @raise ENAMETOOLONG if component in `path` exists longer than `NAME_MAX`
* @raise EBADF if `dirfd` isn't a valid fd or `AT_FDCWD`
* @raise EFAULT if `path` or `ts` memory was invalid
* @raise EROFS if `path` is on read-only filesystem
* @raise ENOSYS on bare metal or on rhel5 when `dirfd` or `flags` is used
* @asyncsignalsafe
* @threadsafe
*/
int utimensat(int dirfd, const char *path, const struct timespec ts[2],
int flags) {
int rc;
if (!path) {
rc = efault(); // linux kernel abi behavior isn't supported
} else {
rc = __utimens(dirfd, path, ts, flags);
}
STRACE("utimensat(%s, %#s, {%s, %s}, %#o) â %d% m", DescribeDirfd(dirfd),
path, DescribeTimespec(0, ts), DescribeTimespec(0, ts ? ts + 1 : 0),
flags, rc);
return rc;
}
| 4,188 | 78 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/wait.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 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"
/**
* 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.
* @return process id of terminated child or -1 w/ errno
* @cancellationpoint
* @asyncsignalsafe
* @restartable
* @vforksafe
*/
int wait(int *opt_out_wstatus) {
return wait4(-1, opt_out_wstatus, 0, NULL);
}
| 2,270 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/poll-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/sig.internal.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/strace.internal.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nt/enum/filetype.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/ipc.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/pollfd.h"
#include "libc/nt/synchronization.h"
#include "libc/nt/winsock.h"
#include "libc/sock/internal.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/sock/struct/pollfd.internal.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/poll.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
#ifdef __x86_64__
/*
* Polls on the New Technology.
*
* This function is used to implement poll() and select(). You may poll
* on both sockets and files at the same time. We also poll for signals
* while poll is polling.
*/
textwindows int sys_poll_nt(struct pollfd *fds, uint64_t nfds, uint64_t *ms,
const sigset_t *sigmask) {
bool ok;
uint32_t avail;
sigset_t oldmask;
struct sys_pollfd_nt pipefds[8];
struct sys_pollfd_nt sockfds[64];
int pipeindices[ARRAYLEN(pipefds)];
int sockindices[ARRAYLEN(sockfds)];
int i, rc, sn, pn, gotinvals, gotpipes, gotsocks, waitfor;
// check for interrupts early before doing work
if (sigmask) {
__sig_mask(SIG_SETMASK, sigmask, &oldmask);
}
if ((rc = _check_interrupts(false, g_fds.p))) {
goto ReturnPath;
}
// do the planning
// we need to read static variables
// we might need to spawn threads and open pipes
__fds_lock();
for (gotinvals = rc = sn = pn = i = 0; i < nfds; ++i) {
if (fds[i].fd < 0) continue;
if (__isfdopen(fds[i].fd)) {
if (__isfdkind(fds[i].fd, kFdSocket)) {
if (sn < ARRAYLEN(sockfds)) {
// the magnums for POLLIN/OUT/PRI on NT include the other ones too
// we need to clear ones like POLLNVAL or else WSAPoll shall whine
sockindices[sn] = i;
sockfds[sn].handle = g_fds.p[fds[i].fd].handle;
sockfds[sn].events = fds[i].events & (POLLPRI | POLLIN | POLLOUT);
sockfds[sn].revents = 0;
++sn;
} else {
// too many socket fds
rc = enomem();
break;
}
} else if (pn < ARRAYLEN(pipefds)) {
pipeindices[pn] = i;
pipefds[pn].handle = g_fds.p[fds[i].fd].handle;
pipefds[pn].events = 0;
pipefds[pn].revents = 0;
switch (g_fds.p[fds[i].fd].flags & O_ACCMODE) {
case O_RDONLY:
pipefds[pn].events = fds[i].events & POLLIN;
break;
case O_WRONLY:
pipefds[pn].events = fds[i].events & POLLOUT;
break;
case O_RDWR:
pipefds[pn].events = fds[i].events & (POLLIN | POLLOUT);
break;
default:
unreachable;
}
++pn;
} else {
// too many non-socket fds
rc = enomem();
break;
}
} else {
++gotinvals;
}
}
__fds_unlock();
if (rc) {
// failed to create a polling solution
goto ReturnPath;
}
// perform the i/o and sleeping and looping
for (;;) {
// see if input is available on non-sockets
for (gotpipes = i = 0; i < pn; ++i) {
if (pipefds[i].events & POLLOUT) {
// we have no way of polling if a non-socket is writeable yet
// therefore we assume that if it can happen, it shall happen
pipefds[i].revents = POLLOUT;
}
if (pipefds[i].events & POLLIN) {
if (GetFileType(pipefds[i].handle) == kNtFileTypePipe) {
ok = PeekNamedPipe(pipefds[i].handle, 0, 0, 0, &avail, 0);
POLLTRACE("PeekNamedPipe(%ld, 0, 0, 0, [%'u], 0) â %hhhd% m",
pipefds[i].handle, avail, ok);
if (ok) {
if (avail) {
pipefds[i].revents = POLLIN;
}
} else {
pipefds[i].revents = POLLERR;
}
} else {
// we have no way of polling if a non-socket is readable yet
// therefore we assume that if it can happen it shall happen
pipefds[i].revents = POLLIN;
}
}
if (pipefds[i].revents) {
++gotpipes;
}
}
// if we haven't found any good results yet then here we
// compute a small time slice we don't mind sleeping for
waitfor = gotinvals || gotpipes ? 0 : MIN(__SIG_POLLING_INTERVAL_MS, *ms);
if (sn) {
// we need to poll the socket handles separately because
// microsoft certainly loves to challenge us with coding
// please note that winsock will fail if we pass zero fd
#if _NTTRACE
POLLTRACE("WSAPoll(%p, %u, %'d) out of %'lu", sockfds, sn, waitfor, *ms);
#endif
if ((gotsocks = WSAPoll(sockfds, sn, waitfor)) == -1) {
rc = __winsockerr();
goto ReturnPath;
}
*ms -= waitfor;
} else {
gotsocks = 0;
if (!gotinvals && !gotpipes && waitfor) {
// if we've only got pipes and none of them are ready
// then we'll just explicitly sleep for the time left
POLLTRACE("SleepEx(%'d, false) out of %'lu", waitfor, *ms);
if (SleepEx(__SIG_POLLING_INTERVAL_MS, true) == kNtWaitIoCompletion) {
POLLTRACE("IOCP EINTR");
} else {
*ms -= waitfor;
}
}
}
// we gave all the sockets and all the named pipes a shot
// if we found anything at all then it's time to end work
if (gotinvals || gotpipes || gotsocks || *ms <= 0) {
break;
}
// otherwise loop limitlessly for timeout to elapse while
// checking for signal delivery interrupts, along the way
if ((rc = _check_interrupts(false, g_fds.p))) {
goto ReturnPath;
}
}
// the system call is going to succeed
// it's now ok to start setting the output memory
for (i = 0; i < nfds; ++i) {
if (fds[i].fd < 0 || __isfdopen(fds[i].fd)) {
fds[i].revents = 0;
} else {
fds[i].revents = POLLNVAL;
}
}
for (i = 0; i < pn; ++i) {
fds[pipeindices[i]].revents = pipefds[i].revents;
}
for (i = 0; i < sn; ++i) {
fds[sockindices[i]].revents = sockfds[i].revents;
}
// and finally return
rc = gotinvals + gotpipes + gotsocks;
ReturnPath:
if (sigmask) {
__sig_mask(SIG_SETMASK, &oldmask, 0);
}
return rc;
}
#endif /* __x86_64__ */
| 8,388 | 225 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/wait4.h | #ifndef COSMOPOLITAN_LIBC_CALLS_WAIT4_H_
#define COSMOPOLITAN_LIBC_CALLS_WAIT4_H_
#include "libc/calls/struct/rusage.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int sys_wait4_nt(int, int *, int, struct rusage *) _Hide;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_CALLS_WAIT4_H_ */
| 353 | 12 | jart/cosmopolitan | false |
cosmopolitan/libc/calls/ioctl_tiocswinsz.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-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/ioctl.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/asan.internal.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/errfuns.h"
int ioctl_tiocswinsz_nt(int, const struct winsize *);
/**
* Sets width and height of terminal.
*
* @see ioctl(fd, TIOCSWINSZ, ws) dispatches here
*/
int ioctl_tiocswinsz(int fd, ...) {
va_list va;
const struct winsize *ws;
va_start(va, fd);
ws = va_arg(va, const struct winsize *);
va_end(va);
if (IsAsan() && !__asan_is_valid(ws, sizeof(*ws))) return efault();
if (fd >= 0) {
if (fd < g_fds.n && g_fds.p[fd].kind == kFdZip) {
return enotty();
} else if (!IsWindows()) {
return sys_ioctl(fd, TIOCSWINSZ, ws);
} else {
return ioctl_tiocswinsz_nt(fd, ws);
}
} else {
return einval();
}
}
| 2,762 | 54 | jart/cosmopolitan | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.