Make improvements

- Every unit test now passes on Apple Silicon. The final piece of this
  puzzle was porting our POSIX threads cancelation support, since that
  works differently on ARM64 XNU vs. AMD64. Our semaphore support on
  Apple Silicon is also superior now compared to AMD64, thanks to the
  grand central dispatch library which lets *NSYNC locks go faster.

- The Cosmopolitan runtime is now more stable, particularly on Windows.
  To do this, thread local storage is mandatory at all runtime levels,
  and the innermost packages of the C library is no longer being built
  using ASAN. TLS is being bootstrapped with a 128-byte TIB during the
  process startup phase, and then later on the runtime re-allocates it
  either statically or dynamically to support code using _Thread_local.
  fork() and execve() now do a better job cooperating with threads. We
  can now check how much stack memory is left in the process or thread
  when functions like kprintf() / execve() etc. call alloca(), so that
  ENOMEM can be raised, reduce a buffer size, or just print a warning.

- POSIX signal emulation is now implemented the same way kernels do it
  with pthread_kill() and raise(). Any thread can interrupt any other
  thread, regardless of what it's doing. If it's blocked on read/write
  then the killer thread will cancel its i/o operation so that EINTR can
  be returned in the mark thread immediately. If it's doing a tight CPU
  bound operation, then that's also interrupted by the signal delivery.
  Signal delivery works now by suspending a thread and pushing context
  data structures onto its stack, and redirecting its execution to a
  trampoline function, which calls SetThreadContext(GetCurrentThread())
  when it's done.

- We're now doing a better job managing locks and handles. On NetBSD we
  now close semaphore file descriptors in forked children. Semaphores on
  Windows can now be canceled immediately, which means mutexes/condition
  variables will now go faster. Apple Silicon semaphores can be canceled
  too. We're now using Apple's pthread_yield() funciton. Apple _nocancel
  syscalls are now used on XNU when appropriate to ensure pthread_cancel
  requests aren't lost. The MbedTLS library has been updated to support
  POSIX thread cancelations. See tool/build/runitd.c for an example of
  how it can be used for production multi-threaded tls servers. Handles
  on Windows now leak less often across processes. All i/o operations on
  Windows are now overlapped, which means file pointers can no longer be
  inherited across dup() and fork() for the time being.

- We now spawn a thread on Windows to deliver SIGCHLD and wakeup wait4()
  which means, for example, that posix_spawn() now goes 3x faster. POSIX
  spawn is also now more correct. Like Musl, it's now able to report the
  failure code of execve() via a pipe although our approach favors using
  shared memory to do that on systems that have a true vfork() function.

- We now spawn a thread to deliver SIGALRM to threads when setitimer()
  is used. This enables the most precise wakeups the OS makes possible.

- The Cosmopolitan runtime now uses less memory. On NetBSD for example,
  it turned out the kernel would actually commit the PT_GNU_STACK size
  which caused RSS to be 6mb for every process. Now it's down to ~4kb.
  On Apple Silicon, we reduce the mandatory upstream thread size to the
  smallest possible size to reduce the memory overhead of Cosmo threads.
  The examples directory has a program called greenbean which can spawn
  a web server on Linux with 10,000 worker threads and have the memory
  usage of the process be ~77mb. The 1024 byte overhead of POSIX-style
  thread-local storage is now optional; it won't be allocated until the
  pthread_setspecific/getspecific functions are called. On Windows, the
  threads that get spawned which are internal to the libc implementation
  use reserve rather than commit memory, which shaves a few hundred kb.

- sigaltstack() is now supported on Windows, however it's currently not
  able to be used to handle stack overflows, since crash signals are
  still generated by WIN32. However the crash handler will still switch
  to the alt stack, which is helpful in environments with tiny threads.

- Test binaries are now smaller. Many of the mandatory dependencies of
  the test runner have been removed. This ensures many programs can do a
  better job only linking the the thing they're testing. This caused the
  test binaries for LIBC_FMT for example, to decrease from 200kb to 50kb

- long double is no longer used in the implementation details of libc,
  except in the APIs that define it. The old code that used long double
  for time (instead of struct timespec) has now been thoroughly removed.

- ShowCrashReports() is now much tinier in MODE=tiny. Instead of doing
  backtraces itself, it'll just print a command you can run on the shell
  using our new `cosmoaddr2line` program to view the backtrace.

- Crash report signal handling now works in a much better way. Instead
  of terminating the process, it now relies on SA_RESETHAND so that the
  default SIG_IGN behavior can terminate the process if necessary.

- Our pledge() functionality has now been fully ported to AARCH64 Linux.
This commit is contained in:
Justine Tunney 2023-09-18 20:44:45 -07:00
parent c4eb838516
commit ec480f5aa0
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
638 changed files with 7925 additions and 8282 deletions

View file

@ -24,12 +24,14 @@
#include "libc/str/str.h"
#include "libc/sysv/consts/f.h"
#define MIN_CLANDESTINE_FD 100 // e.g. kprintf's dup'd handle
void CheckForFileLeaks(void) {
char msg[512];
char *p = msg;
char *pe = msg + 256;
bool gotsome = false;
for (int fd = 3; fd < 200; ++fd) {
for (int fd = 3; fd < MIN_CLANDESTINE_FD; ++fd) {
if (fcntl(fd, F_GETFL) != -1) {
if (!gotsome) {
p = stpcpy(p, program_invocation_short_name);
@ -46,7 +48,6 @@ void CheckForFileLeaks(void) {
}
if (gotsome) {
char proc[64];
char *p = proc;
*p++ = '\n';
*p = 0;
write(2, msg, p - msg);

View file

@ -1028,6 +1028,14 @@ int __fmt(void *fn, void *arg, const char *format, va_list va) {
flags |= FLAGS_PRECISION;
prec = 1;
goto FormatString;
} else if (flags & (FLAGS_QUOTE | FLAGS_REPR)) {
p = "'\\0'";
flags &= ~(FLAGS_QUOTE | FLAGS_REPR | FLAGS_HASH);
goto FormatString;
} else if (flags & FLAGS_HASH) {
flags &= ~FLAGS_HASH;
p = " ";
goto FormatString;
} else {
__FMT_PUT('\0');
break;

View file

@ -29,6 +29,7 @@
#include "libc/calls/struct/dirent.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/runtime/stack.h"
#include "libc/stdio/ftw.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
@ -168,9 +169,13 @@ int nftw(const char *dirpath,
int fd_limit,
int flags)
{
#pragma GCC push_options
#pragma GCC diagnostic ignored "-Wframe-larger-than="
char pathbuf[PATH_MAXIMUS+1];
CheckLargeStackAllocation(pathbuf, sizeof(pathbuf));
#pragma GCC pop_options
int r, cs;
size_t l;
char pathbuf[PATH_MAXIMUS+1];
if (fd_limit <= 0) return 0;

View file

@ -1,63 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/limits.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/x/x.h"
/**
* Displays wall of text in terminal with pagination.
*/
void __paginate(int fd, const char *s) {
int tfd, pid;
char *args[3] = {0};
char tmppath[PATH_MAX];
char progpath[PATH_MAX];
if (strcmp(nulltoempty(getenv("TERM")), "dumb") && isatty(0) && isatty(1) &&
((args[0] = commandv("less", progpath, sizeof(progpath))) ||
(args[0] = commandv("more", progpath, sizeof(progpath))))) {
snprintf(tmppath, sizeof(tmppath), "%s%s-%s-%d.txt", kTmpPath,
firstnonnull(program_invocation_short_name, "unknown"), "paginate",
getpid());
if ((tfd = open(tmppath, O_WRONLY | O_CREAT | O_TRUNC, 0644)) != -1) {
write(tfd, s, strlen(s));
close(tfd);
args[1] = tmppath;
if ((pid = fork()) != -1) {
putenv("LC_ALL=C.UTF-8");
putenv("LESSCHARSET=utf-8");
putenv("LESS=-RS");
if (!pid) {
execv(args[0], args);
_Exit(127);
}
waitpid(pid, 0, 0);
unlink(tmppath);
return;
}
unlink(tmppath);
}
}
write(fd, s, strlen(s));
}

View file

@ -1,457 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 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/stdio/posix_spawn.h"
#include "libc/assert.h"
#include "libc/atomic.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/ntspawn.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/rlimit.internal.h"
#include "libc/calls/struct/rusage.internal.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/sigset.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/fmt/magnumstrs.internal.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/handlock.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/mem/alloca.h"
#include "libc/nt/createfile.h"
#include "libc/nt/enum/processcreationflags.h"
#include "libc/nt/enum/startf.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/processinformation.h"
#include "libc/nt/struct/startupinfo.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/sock.h"
#include "libc/stdio/posix_spawn.h"
#include "libc/stdio/posix_spawn.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/limits.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/sig.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
#ifndef SYSDEBUG
#define read sys_read
#define write sys_write
#define close sys_close
#define pipe2 sys_pipe2
#define getgid sys_getgid
#define setgid sys_setgid
#define getuid sys_getuid
#define setuid sys_setuid
#define setsid sys_setsid
#define setpgid sys_setpgid
#define fcntl __sys_fcntl
#define wait4 __sys_wait4
#define openat __sys_openat
#define setrlimit sys_setrlimit
#define sigprocmask sys_sigprocmask
#endif
static atomic_bool real_vfork; // i.e. not qemu/wsl/xnu/openbsd
static void posix_spawn_unhand(int64_t hands[3]) {
for (int i = 0; i < 3; ++i) {
if (hands[i] != -1) {
CloseHandle(hands[i]);
}
}
}
static void posix_spawn_inherit(int64_t hands[3], bool32 bInherit) {
for (int i = 0; i < 3; ++i) {
if (hands[i] != -1) {
SetHandleInformation(hands[i], kNtHandleFlagInherit, bInherit);
}
}
}
static textwindows errno_t posix_spawn_windows_impl(
int *pid, const char *path, const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]) {
int i;
// create file descriptor work area
char stdio_kind[3] = {kFdEmpty, kFdEmpty, kFdEmpty};
intptr_t stdio_handle[3] = {-1, -1, -1};
for (i = 0; i < 3; ++i) {
if (g_fds.p[i].kind != kFdEmpty && !(g_fds.p[i].flags & O_CLOEXEC)) {
stdio_kind[i] = g_fds.p[i].kind;
stdio_handle[i] = g_fds.p[i].handle;
}
}
// reserve a fake pid for this spawn
int child = __reservefd(-1);
// apply user file actions
intptr_t close_handle[3] = {-1, -1, -1};
if (file_actions) {
int err = 0;
for (struct _posix_faction *a = *file_actions; a && !err; a = a->next) {
switch (a->action) {
case _POSIX_SPAWN_CLOSE:
unassert(a->fildes < 3u);
stdio_kind[a->fildes] = kFdEmpty;
stdio_handle[a->fildes] = -1;
break;
case _POSIX_SPAWN_DUP2:
unassert(a->newfildes < 3u);
if (__isfdopen(a->fildes)) {
stdio_kind[a->newfildes] = g_fds.p[a->fildes].kind;
stdio_handle[a->newfildes] = g_fds.p[a->fildes].handle;
} else {
err = EBADF;
}
break;
case _POSIX_SPAWN_OPEN: {
int64_t hand;
int e = errno;
char16_t path16[PATH_MAX];
uint32_t perm, share, disp, attr;
unassert(a->fildes < 3u);
if (__mkntpathat(AT_FDCWD, a->path, 0, path16) != -1 &&
GetNtOpenFlags(a->oflag, a->mode, //
&perm, &share, &disp, &attr) != -1 &&
(hand = CreateFile(path16, perm, share, 0, disp, attr, 0))) {
stdio_kind[a->fildes] = kFdFile;
close_handle[a->fildes] = hand;
stdio_handle[a->fildes] = hand;
} else {
err = errno;
errno = e;
}
break;
}
default:
__builtin_unreachable();
}
}
if (err) {
posix_spawn_unhand(close_handle);
__releasefd(child);
return err;
}
}
// create the windows process start info
int bits;
char buf[32], *v = 0;
if (_weaken(socket)) {
for (bits = i = 0; i < 3; ++i) {
if (stdio_kind[i] == kFdSocket) {
bits |= 1 << i;
}
}
FormatInt32(stpcpy(buf, "__STDIO_SOCKETS="), bits);
v = buf;
}
struct NtStartupInfo startinfo = {
.cb = sizeof(struct NtStartupInfo),
.dwFlags = kNtStartfUsestdhandles,
.hStdInput = stdio_handle[0],
.hStdOutput = stdio_handle[1],
.hStdError = stdio_handle[2],
};
// figure out the flags
short flags = 0;
bool bInheritHandles = false;
uint32_t dwCreationFlags = 0;
for (i = 0; i < 3; ++i) {
bInheritHandles |= stdio_handle[i] != -1;
}
if (attrp && *attrp) {
flags = (*attrp)->flags;
if (flags & POSIX_SPAWN_SETSID) {
dwCreationFlags |= kNtDetachedProcess;
}
if (flags & POSIX_SPAWN_SETPGROUP) {
dwCreationFlags |= kNtCreateNewProcessGroup;
}
}
// launch the process
int rc, e = errno;
struct NtProcessInformation procinfo;
if (!envp) envp = environ;
__hand_rlock();
posix_spawn_inherit(stdio_handle, true);
rc = ntspawn(path, argv, envp, v, 0, 0, bInheritHandles, dwCreationFlags, 0,
&startinfo, &procinfo);
posix_spawn_inherit(stdio_handle, false);
posix_spawn_unhand(close_handle);
__hand_runlock();
if (rc == -1) {
int err = errno;
__releasefd(child);
errno = e;
return err;
}
// track the process
CloseHandle(procinfo.hThread);
g_fds.p[child].kind = kFdProcess;
g_fds.p[child].handle = procinfo.hProcess;
g_fds.p[child].flags = O_CLOEXEC;
g_fds.p[child].zombie = false;
// return the result
if (pid) *pid = child;
return 0;
}
static const char *DescribePid(char buf[12], int err, int *pid) {
if (err) return "n/a";
if (!pid) return "NULL";
FormatInt32(buf, *pid);
return buf;
}
static textwindows dontinline errno_t posix_spawn_windows(
int *pid, const char *path, const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]) {
int err;
if (!path || !argv ||
(IsAsan() && (!__asan_is_valid_str(path) || //
!__asan_is_valid_strlist(argv) || //
(envp && !__asan_is_valid_strlist(envp))))) {
err = EFAULT;
} else {
err = posix_spawn_windows_impl(pid, path, file_actions, attrp, argv, envp);
}
STRACE("posix_spawn([%s], %#s, %s, %s) → %s",
DescribePid(alloca(12), err, pid), path, DescribeStringList(argv),
DescribeStringList(envp), !err ? "0" : _strerrno(err));
return err;
}
/**
* Spawns process, the POSIX way.
*
* This provides superior process creation performance across systems
* Processes are normally spawned by calling fork() and execve(), but
* that goes slow on Windows if the caller has allocated a nontrivial
* number of memory mappings, all of which need to be copied into the
* forked child, only to be destroyed a moment later. On UNIX systems
* fork() bears a similar cost that's 100x less bad, which is copying
* the page tables. So what this implementation does is on Windows it
* calls CreateProcess() directly and on UNIX it uses vfork() if it's
* possible (XNU and OpenBSD don't have it). On UNIX this API has the
* benefit of avoiding the footguns of using vfork() directly because
* this implementation will ensure signal handlers can't be called in
* the child process since that'd likely corrupt the parent's memory.
*
* @param pid if non-null shall be set to child pid on success
* @param path is resolved path of program which is not `$PATH` searched
* @param file_actions specifies close(), dup2(), and open() operations
* @param attrp specifies signal masks, user ids, scheduling, etc.
* @param envp is environment variables, or `environ` if null
* @return 0 on success or error number on failure
* @see posix_spawnp() for `$PATH` searching
* @returnserrno
* @tlsrequired
* @threadsafe
*/
errno_t posix_spawn(int *pid, const char *path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp, char *const argv[],
char *const envp[]) {
if (IsWindows()) {
return posix_spawn_windows(pid, path, file_actions, attrp, argv, envp);
}
int pfds[2];
bool use_pipe;
volatile int status = 0;
sigset_t blockall, oldmask;
int child, res, cs, e = errno;
volatile bool can_clobber = false;
sigfillset(&blockall);
sigprocmask(SIG_SETMASK, &blockall, &oldmask);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
if ((use_pipe = !atomic_load_explicit(&real_vfork, memory_order_acquire))) {
if (pipe2(pfds, O_CLOEXEC)) {
res = errno;
goto ParentFailed;
}
}
if (!(child = vfork())) {
can_clobber = true;
sigset_t *childmask;
bool lost_cloexec = 0;
struct sigaction dfl = {0};
short flags = attrp && *attrp ? (*attrp)->flags : 0;
if (use_pipe) close(pfds[0]);
for (int sig = 1; sig < _NSIG; sig++) {
if (__sighandrvas[sig] != (long)SIG_DFL &&
(__sighandrvas[sig] != (long)SIG_IGN ||
((flags & POSIX_SPAWN_SETSIGDEF) &&
sigismember(&(*attrp)->sigdefault, sig) == 1))) {
sigaction(sig, &dfl, 0);
}
}
if (flags & POSIX_SPAWN_SETSID) {
setsid();
}
if ((flags & POSIX_SPAWN_SETPGROUP) && setpgid(0, (*attrp)->pgroup)) {
goto ChildFailed;
}
if ((flags & POSIX_SPAWN_RESETIDS) && setgid(getgid())) {
goto ChildFailed;
}
if ((flags & POSIX_SPAWN_RESETIDS) && setuid(getuid())) {
goto ChildFailed;
}
if (file_actions) {
struct _posix_faction *a;
for (a = *file_actions; a; a = a->next) {
if (use_pipe && pfds[1] == a->fildes) {
int p2;
if ((p2 = dup(pfds[1])) == -1) {
goto ChildFailed;
}
lost_cloexec = true;
close(pfds[1]);
pfds[1] = p2;
}
switch (a->action) {
case _POSIX_SPAWN_CLOSE:
if (close(a->fildes)) {
goto ChildFailed;
}
break;
case _POSIX_SPAWN_DUP2:
if (dup2(a->fildes, a->newfildes) == -1) {
goto ChildFailed;
}
break;
case _POSIX_SPAWN_OPEN: {
int t;
if ((t = openat(AT_FDCWD, a->path, a->oflag, a->mode)) == -1) {
goto ChildFailed;
}
if (t != a->fildes) {
if (dup2(t, a->fildes) == -1) {
close(t);
goto ChildFailed;
}
if (close(t)) {
goto ChildFailed;
}
}
break;
}
default:
__builtin_unreachable();
}
}
}
if (IsLinux() || IsFreebsd() || IsNetbsd()) {
if (flags & POSIX_SPAWN_SETSCHEDULER) {
if (sched_setscheduler(0, (*attrp)->schedpolicy,
&(*attrp)->schedparam) == -1) {
goto ChildFailed;
}
}
if (flags & POSIX_SPAWN_SETSCHEDPARAM) {
if (sched_setparam(0, &(*attrp)->schedparam)) {
goto ChildFailed;
}
}
}
if (flags & POSIX_SPAWN_SETRLIMIT) {
for (int rez = 0; rez <= ARRAYLEN((*attrp)->rlim); ++rez) {
if ((*attrp)->rlimset & (1u << rez)) {
if (setrlimit(rez, (*attrp)->rlim + rez)) {
goto ChildFailed;
}
}
}
}
if (lost_cloexec) {
fcntl(pfds[1], F_SETFD, FD_CLOEXEC);
}
if (flags & POSIX_SPAWN_SETSIGMASK) {
childmask = &(*attrp)->sigmask;
} else {
childmask = &oldmask;
}
sigprocmask(SIG_SETMASK, childmask, 0);
if (!envp) envp = environ;
execve(path, argv, envp);
ChildFailed:
res = errno;
if (!use_pipe) {
status = res;
} else {
write(pfds[1], &res, sizeof(res));
}
_Exit(127);
}
if (use_pipe) {
close(pfds[1]);
}
if (child != -1) {
if (!use_pipe) {
res = status;
} else {
if (can_clobber) {
atomic_store_explicit(&real_vfork, true, memory_order_release);
}
res = 0;
read(pfds[0], &res, sizeof(res));
}
if (!res) {
if (pid) *pid = child;
} else {
wait4(child, 0, 0, 0);
}
} else {
res = errno;
}
if (use_pipe) {
close(pfds[0]);
}
ParentFailed:
sigprocmask(SIG_SETMASK, &oldmask, 0);
pthread_setcancelstate(cs, 0);
errno = e;
return res;
}

View file

@ -1,56 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_STDIO_SPAWN_H_
#define COSMOPOLITAN_LIBC_STDIO_SPAWN_H_
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/calls/struct/sigset.h"
#define POSIX_SPAWN_USEVFORK 0
#define POSIX_SPAWN_RESETIDS 1
#define POSIX_SPAWN_SETPGROUP 2
#define POSIX_SPAWN_SETSIGDEF 4
#define POSIX_SPAWN_SETSIGMASK 8
#define POSIX_SPAWN_SETSCHEDPARAM 16
#define POSIX_SPAWN_SETSCHEDULER 32
#define POSIX_SPAWN_SETSID 128
#define POSIX_SPAWN_SETRLIMIT 256
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef struct _posix_spawna *posix_spawnattr_t;
typedef struct _posix_faction *posix_spawn_file_actions_t;
int posix_spawn(int *, const char *, const posix_spawn_file_actions_t *,
const posix_spawnattr_t *, char *const[], char *const[]);
int posix_spawnp(int *, const char *, const posix_spawn_file_actions_t *,
const posix_spawnattr_t *, char *const[], char *const[]);
int posix_spawn_file_actions_init(posix_spawn_file_actions_t *);
int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *);
int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *, int);
int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *, int, int);
int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *, int,
const char *, int, unsigned);
int posix_spawnattr_init(posix_spawnattr_t *);
int posix_spawnattr_destroy(posix_spawnattr_t *);
int posix_spawnattr_getflags(const posix_spawnattr_t *, short *);
int posix_spawnattr_setflags(posix_spawnattr_t *, short);
int posix_spawnattr_getpgroup(const posix_spawnattr_t *, int *);
int posix_spawnattr_setpgroup(posix_spawnattr_t *, int);
int posix_spawnattr_getschedpolicy(const posix_spawnattr_t *, int *);
int posix_spawnattr_setschedpolicy(posix_spawnattr_t *, int);
int posix_spawnattr_getschedparam(const posix_spawnattr_t *,
struct sched_param *);
int posix_spawnattr_setschedparam(posix_spawnattr_t *,
const struct sched_param *);
int posix_spawnattr_getsigmask(const posix_spawnattr_t *, sigset_t *);
int posix_spawnattr_setsigmask(posix_spawnattr_t *, const sigset_t *);
int posix_spawnattr_getsigdefault(const posix_spawnattr_t *, sigset_t *);
int posix_spawnattr_setsigdefault(posix_spawnattr_t *, const sigset_t *);
int posix_spawnattr_getrlimit(const posix_spawnattr_t *, int, struct rlimit *);
int posix_spawnattr_setrlimit(posix_spawnattr_t *, int, const struct rlimit *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_STDIO_SPAWN_H_ */

View file

@ -1,41 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_STDIO_SPAWNA_INTERNAL_H_
#define COSMOPOLITAN_LIBC_STDIO_SPAWNA_INTERNAL_H_
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/calls/struct/sigset.h"
#define _POSIX_SPAWN_CLOSE 1
#define _POSIX_SPAWN_DUP2 2
#define _POSIX_SPAWN_OPEN 3
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct _posix_spawna {
short flags;
bool schedparam_isset;
bool schedpolicy_isset;
int pgroup;
int rlimset;
int schedpolicy;
struct sched_param schedparam;
sigset_t sigmask;
sigset_t sigdefault;
struct rlimit rlim[16];
};
struct _posix_faction {
struct _posix_faction *next;
int action;
int fildes;
int oflag;
union {
int newfildes;
unsigned mode;
};
char *path;
};
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_STDIO_SPAWNA_INTERNAL_H_ */

View file

@ -1,131 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/mem/mem.h"
#include "libc/stdio/posix_spawn.h"
#include "libc/stdio/posix_spawn.internal.h"
#include "libc/str/str.h"
static int AddFileAction(posix_spawn_file_actions_t *l,
struct _posix_faction a) {
struct _posix_faction *ap;
if (!(ap = malloc(sizeof(*ap)))) return ENOMEM;
*ap = a;
while (*l) l = &(*l)->next;
*l = ap;
return 0;
}
/**
* Initializes posix_spawn() file actions list.
*
* File actions get applied in the same order as they're registered.
*
* @param file_actions will need posix_spawn_file_actions_destroy()
* @return 0 on success, or errno on error
*/
int posix_spawn_file_actions_init(posix_spawn_file_actions_t *file_actions) {
*file_actions = 0;
return 0;
}
/**
* Destroys posix_spawn() file actions list.
*
* This function is safe to call multiple times.
*
* @param file_actions was initialized by posix_spawn_file_actions_init()
* @return 0 on success, or errno on error
*/
int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *file_actions) {
if (*file_actions) {
posix_spawn_file_actions_destroy(&(*file_actions)->next);
free((*file_actions)->path);
free(*file_actions);
*file_actions = 0;
}
return 0;
}
/**
* Add a close action to object.
*
* @param file_actions was initialized by posix_spawn_file_actions_init()
* @return 0 on success, or errno on error
* @raise ENOMEM if we require more vespene gas
* @raise EBADF if `fildes` is negative
*/
int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *file_actions,
int fildes) {
if (fildes < 0) return EBADF;
if (IsWindows() && fildes > 2) return 0;
return AddFileAction(file_actions, (struct _posix_faction){
.action = _POSIX_SPAWN_CLOSE,
.fildes = fildes,
});
}
/**
* Add a dup2 action to object.
*
* @param file_actions was initialized by posix_spawn_file_actions_init()
* @return 0 on success, or errno on error
* @raise ENOMEM if we require more vespene gas
* @raise EBADF if 'fildes' or `newfildes` is negative
* @raise ENOTSUP if `newfildes` isn't 0, 1, or 2 on Windows
*/
int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *file_actions,
int fildes, int newfildes) {
if (fildes < 0 || newfildes < 0) return EBADF;
if (IsWindows() && newfildes > 2) return ENOTSUP;
return AddFileAction(file_actions, (struct _posix_faction){
.action = _POSIX_SPAWN_DUP2,
.fildes = fildes,
.newfildes = newfildes,
});
}
/**
* Add an open action to object.
*
* @param file_actions was initialized by posix_spawn_file_actions_init()
* @param fildes is what open() result gets duplicated to
* @param path will be safely copied
* @return 0 on success, or errno on error
* @raise ENOMEM if we require more vespene gas
* @raise EBADF if `fildes` is negative
* @raise ENOTSUP if `fildes` isn't 0, 1, or 2 on Windows
*/
int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *file_actions,
int fildes, const char *path, int oflag,
unsigned mode) {
char *path2;
if (fildes < 0) return EBADF;
if (IsWindows() && fildes > 2) return ENOTSUP;
if (!(path2 = strdup(path))) return ENOMEM;
return AddFileAction(file_actions, (struct _posix_faction){
.action = _POSIX_SPAWN_OPEN,
.fildes = fildes,
.path = path2,
.oflag = oflag,
.mode = mode,
});
}

View file

@ -1,291 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigset.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/posix_spawn.h"
#include "libc/stdio/posix_spawn.internal.h"
#include "libc/sysv/consts/sig.h"
/**
* Initialize posix_spawn() attributes object with default values.
*
* @param attr needs to be passed to posix_spawnattr_destroy() later
* @return 0 on success, or errno on error
* @raise ENOMEM if we require more vespene gas
*/
int posix_spawnattr_init(posix_spawnattr_t *attr) {
int rc, e = errno;
struct _posix_spawna *a;
if ((a = calloc(1, sizeof(struct _posix_spawna)))) {
*attr = a;
rc = 0;
} else {
rc = errno;
errno = e;
}
return rc;
}
/**
* Destroys posix_spawn() attributes object.
*
* This function is safe to call multiple times.
*
* @param attr was initialized by posix_spawnattr_init()
* @return 0 on success, or errno on error
*/
int posix_spawnattr_destroy(posix_spawnattr_t *attr) {
if (*attr) {
free(*attr);
*attr = 0;
}
return 0;
}
/**
* Gets posix_spawn() flags.
*
* @param attr was initialized by posix_spawnattr_init()
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getflags(const posix_spawnattr_t *attr, short *flags) {
*flags = (*attr)->flags;
return 0;
}
/**
* Sets posix_spawn() flags.
*
* @param attr was initialized by posix_spawnattr_init()
* @param flags may have any of the following
* - `POSIX_SPAWN_RESETIDS`
* - `POSIX_SPAWN_SETPGROUP`
* - `POSIX_SPAWN_SETSIGDEF`
* - `POSIX_SPAWN_SETSIGMASK`
* - `POSIX_SPAWN_SETSCHEDPARAM`
* - `POSIX_SPAWN_SETSCHEDULER`
* - `POSIX_SPAWN_SETSID`
* @return 0 on success, or errno on error
* @raise EINVAL if `flags` has invalid bits
*/
int posix_spawnattr_setflags(posix_spawnattr_t *attr, short flags) {
if (flags &
~(POSIX_SPAWN_RESETIDS | POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGDEF |
POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSCHEDPARAM |
POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSID)) {
return EINVAL;
}
(*attr)->flags = flags;
return 0;
}
/**
* Gets process group id associated with attributes.
*
* @param attr was initialized by posix_spawnattr_init()
* @param pgroup receives the result on success
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getpgroup(const posix_spawnattr_t *attr, int *pgroup) {
*pgroup = (*attr)->pgroup;
return 0;
}
/**
* Specifies process group into which child process is placed.
*
* Setting `pgroup` to zero will ensure newly created processes are
* placed within their own brand new process group.
*
* This setter also sets the `POSIX_SPAWN_SETPGROUP` flag.
*
* @param attr was initialized by posix_spawnattr_init()
* @param pgroup is the process group id, or 0 for self
* @return 0 on success, or errno on error
*/
int posix_spawnattr_setpgroup(posix_spawnattr_t *attr, int pgroup) {
(*attr)->flags |= POSIX_SPAWN_SETPGROUP;
(*attr)->pgroup = pgroup;
return 0;
}
/**
* Gets signal mask for sigprocmask() in child process.
*
* The signal mask is applied to the child process in such a way that
* signal handlers from the parent process can't get triggered in the
* child process.
*
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getsigmask(const posix_spawnattr_t *attr,
sigset_t *sigmask) {
*sigmask = (*attr)->sigmask;
return 0;
}
/**
* Specifies signal mask for sigprocmask() in child process.
*
* This setter also sets the `POSIX_SPAWN_SETSIGMASK` flag.
*
* @return 0 on success, or errno on error
*/
int posix_spawnattr_setsigmask(posix_spawnattr_t *attr,
const sigset_t *sigmask) {
(*attr)->flags |= POSIX_SPAWN_SETSIGMASK;
(*attr)->sigmask = *sigmask;
return 0;
}
/**
* Retrieves which signals will be restored to `SIG_DFL`.
*
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getsigdefault(const posix_spawnattr_t *attr,
sigset_t *sigdefault) {
*sigdefault = (*attr)->sigdefault;
return 0;
}
/**
* Specifies which signals should be restored to `SIG_DFL`.
*
* This routine isn't necessary in most cases, since posix_spawn() by
* default will try to avoid vfork() race conditions by tracking what
* signals have a handler function and then resets them automatically
* within the child process, before applying the child's signal mask.
* This function may be used to ensure the `SIG_IGN` disposition will
* not propagate across execve in cases where this process explicitly
* set the signals to `SIG_IGN` earlier (since posix_spawn() will not
* issue O(128) system calls just to be totally pedantic about that).
*
* Using this setter automatically sets `POSIX_SPAWN_SETSIGDEF`.
*
* @return 0 on success, or errno on error
*/
int posix_spawnattr_setsigdefault(posix_spawnattr_t *attr,
const sigset_t *sigdefault) {
(*attr)->flags |= POSIX_SPAWN_SETSIGDEF;
(*attr)->sigdefault = *sigdefault;
return 0;
}
/**
* Gets resource limit for spawned process.
*
* @return 0 on success, or errno on error
* @raise EINVAL if `resource` is invalid
* @raise ENOENT if `resource` is absent
*/
int posix_spawnattr_getrlimit(const posix_spawnattr_t *attr, int resource,
struct rlimit *rlim) {
if ((0 <= resource && resource < ARRAYLEN((*attr)->rlim))) {
if (((*attr)->rlimset & (1u << resource))) {
*rlim = (*attr)->rlim[resource];
return 0;
} else {
return ENOENT;
}
} else {
return EINVAL;
}
}
/**
* Sets resource limit on spawned process.
*
* Using this setter automatically sets `POSIX_SPAWN_SETRLIMIT`.
*
* @return 0 on success, or errno on error
* @raise EINVAL if resource is invalid
*/
int posix_spawnattr_setrlimit(posix_spawnattr_t *attr, int resource,
const struct rlimit *rlim) {
if (0 <= resource && resource < ARRAYLEN((*attr)->rlim)) {
(*attr)->flags |= POSIX_SPAWN_SETRLIMIT;
(*attr)->rlimset |= 1u << resource;
(*attr)->rlim[resource] = *rlim;
return 0;
} else {
return EINVAL;
}
}
/**
* Gets scheduler policy that'll be used for spawned process.
*
* @param attr was initialized by posix_spawnattr_init()
* @param schedpolicy receives the result
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getschedpolicy(const posix_spawnattr_t *attr,
int *schedpolicy) {
*schedpolicy = (*attr)->schedpolicy;
return 0;
}
/**
* Specifies scheduler policy override for spawned process.
*
* Using this setter automatically sets `POSIX_SPAWN_SETSCHEDULER`.
*
* @param attr was initialized by posix_spawnattr_init()
* @return 0 on success, or errno on error
*/
int posix_spawnattr_setschedpolicy(posix_spawnattr_t *attr, int schedpolicy) {
(*attr)->flags |= POSIX_SPAWN_SETSCHEDULER;
(*attr)->schedpolicy = schedpolicy;
return 0;
}
/**
* Gets scheduler parameter.
*
* @param attr was initialized by posix_spawnattr_init()
* @param schedparam receives the result
* @return 0 on success, or errno on error
*/
int posix_spawnattr_getschedparam(const posix_spawnattr_t *attr,
struct sched_param *schedparam) {
*schedparam = (*attr)->schedparam;
return 0;
}
/**
* Specifies scheduler parameter override for spawned process.
*
* Using this setter automatically sets `POSIX_SPAWN_SETSCHEDPARAM`.
*
* @param attr was initialized by posix_spawnattr_init()
* @param schedparam receives the result
* @return 0 on success, or errno on error
*/
int posix_spawnattr_setschedparam(posix_spawnattr_t *attr,
const struct sched_param *schedparam) {
(*attr)->flags |= POSIX_SPAWN_SETSCHEDPARAM;
(*attr)->schedparam = *schedparam;
return 0;
}

View file

@ -1,38 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2021 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/limits.h"
#include "libc/stdio/posix_spawn.h"
/**
* Spawns process the POSIX way w/ PATH search.
*
* @param pid is non-NULL and will be set to child pid in parent
* @param path of executable is PATH searched unless it contains a slash
* @return 0 on success or error number on failure
*/
int posix_spawnp(int *pid, const char *path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp, char *const argv[],
char *const envp[]) {
char pathbuf[PATH_MAX];
if (!(path = commandv(path, pathbuf, sizeof(pathbuf)))) return errno;
return posix_spawn(pid, path, file_actions, attrp, argv, envp);
}

View file

@ -32,6 +32,7 @@ LIBC_STDIO_A_DIRECTDEPS = \
LIBC_NT_ADVAPI32 \
LIBC_NT_KERNEL32 \
LIBC_RUNTIME \
LIBC_PROC \
LIBC_STR \
LIBC_SYSV \
LIBC_SYSV_CALLS \
@ -48,6 +49,9 @@ $(LIBC_STDIO_A).pkg: \
$(LIBC_STDIO_A_OBJS) \
$(foreach x,$(LIBC_STDIO_A_DIRECTDEPS),$($(x)_A).pkg)
# offer assurances about the stack safety of cosmo libc
$(LIBC_STDIO_A_OBJS): private COPTS += -Wframe-larger-than=4096 -Walloca-larger-than=4096
o/$(MODE)/libc/stdio/fputc.o: private \
CFLAGS += \
-O3
@ -57,8 +61,6 @@ o//libc/stdio/appendw.o: private \
-Os
o/$(MODE)/libc/stdio/dirstream.o \
o/$(MODE)/libc/stdio/posix_spawnattr.o \
o/$(MODE)/libc/stdio/posix_spawn_file_actions.o \
o/$(MODE)/libc/stdio/mt19937.o: private \
CFLAGS += \
-ffunction-sections

View file

@ -1,98 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/weaken.h"
#include "libc/log/log.h"
#include "libc/paths.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/sig.h"
#include "libc/thread/thread.h"
/**
* Launches program with system command interpreter.
*
* This implementation embeds the Cosmopolitan Command Interpreter which
* provides Bourne-like syntax on all platforms, including Windows. Many
* builtin commands are included, e.g. exit, cd, rm, [, cat, wait, exec,
* env, echo, read, true, test, kill, touch, rmdir, mkdir, false, mktemp
* and usleep. It's also possible to __static_yoink() the symbols `_tr`,
* `_sed`, `_awk`, and `_curl` for the tr, sed, awk and curl commands if
* you're using the Cosmopolitan mono-repo.
*
* If you just have a program name and arguments, and you don't need the
* full power of a UNIX-like shell, then consider using the Cosmopolitan
* provided API systemvpe() instead. It provides a safer alternative for
* variable arguments than shell script escaping. It lets you clean your
* environment variables, for even more safety. Finally it's 10x faster.
*
* It's important to check the returned status code. For example, if you
* press CTRL-C while running your program you'll expect it to terminate
* however that won't be the case if the SIGINT gets raised while inside
* the system() function. If the child process doesn't handle the signal
* then this will return e.g. WIFSIGNALED(ws) && WTERMSIG(ws) == SIGINT.
*
* @param cmdline is a unix shell script
* @return -1 if child process couldn't be created, otherwise a wait
* status that can be accessed using macros like WEXITSTATUS(s),
* WIFSIGNALED(s), WTERMSIG(s), etc.
* @see systemve()
* @threadsafe
*/
int system(const char *cmdline) {
int pid, wstatus;
sigset_t chldmask, savemask;
if (!cmdline) return 1;
sigemptyset(&chldmask);
sigaddset(&chldmask, SIGINT);
sigaddset(&chldmask, SIGQUIT);
sigaddset(&chldmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &chldmask, &savemask);
if (!(pid = fork())) {
sigprocmask(SIG_SETMASK, &savemask, 0);
_Exit(_cocmd(3, (char *[]){"system", "-c", (char *)cmdline, 0}, environ));
} else if (pid == -1) {
wstatus = -1;
} else {
struct sigaction ignore, saveint, savequit;
ignore.sa_flags = 0;
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
sigaction(SIGINT, &ignore, &saveint);
sigaction(SIGQUIT, &ignore, &savequit);
BLOCK_CANCELLATIONS;
while (wait4(pid, &wstatus, 0, 0) == -1) {
if (errno != EINTR) {
wstatus = -1;
break;
}
}
ALLOW_CANCELLATIONS;
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGINT, &saveint, 0);
}
sigprocmask(SIG_SETMASK, &savemask, 0);
return wstatus;
}

View file

@ -1,90 +0,0 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 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/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/errno.h"
#include "libc/limits.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/sig.h"
/**
* Executes program and waits for it to complete, e.g.
*
* systemvpe("ls", (char *[]){"ls", dir, 0}, environ);
*
* This function is designed to do the same thing as system() except
* rather than taking a shell script argument it accepts an array of
* strings which are safely passed directly to execve().
*
* This function is 5x faster than system() and generally safer, for
* most command running use cases that don't need to control the i/o
* file descriptors.
*
* @param prog is path searched (if it doesn't contain a slash) from
* the $PATH environment variable in `environ` (not your `envp`)
* @return -1 if child process couldn't be created, otherwise a wait
* status that can be accessed using macros like WEXITSTATUS(s),
* WIFSIGNALED(s), WTERMSIG(s), etc.
* @see system()
* @threadsafe
*/
int systemvpe(const char *prog, char *const argv[], char *const envp[]) {
char *exe;
int pid, wstatus;
char pathbuf[PATH_MAX + 1];
sigset_t chldmask, savemask;
if (!(exe = commandv(prog, pathbuf, sizeof(pathbuf)))) {
return -1;
}
sigemptyset(&chldmask);
sigaddset(&chldmask, SIGINT);
sigaddset(&chldmask, SIGQUIT);
sigaddset(&chldmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &chldmask, &savemask);
if (!(pid = vfork())) {
sigprocmask(SIG_SETMASK, &savemask, 0);
execve(prog, argv, envp);
_Exit(127);
} else if (pid == -1) {
wstatus = -1;
} else {
struct sigaction ignore, saveint, savequit;
ignore.sa_flags = 0;
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
sigaction(SIGINT, &ignore, &saveint);
sigaction(SIGQUIT, &ignore, &savequit);
BLOCK_CANCELLATIONS;
while (wait4(pid, &wstatus, 0, 0) == -1) {
if (errno != EINTR) {
wstatus = -1;
break;
}
}
ALLOW_CANCELLATIONS;
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGINT, &saveint, 0);
}
sigprocmask(SIG_SETMASK, &savemask, 0);
return wstatus;
}

View file

@ -33,8 +33,7 @@
*
* This creates a secure temporary file inside $TMPDIR. If it isn't
* defined, then /tmp is used on UNIX and GetTempPath() is used on the
* New Technology. This resolution of $TMPDIR happens once in a ctor,
* which is copied to the `kTmpPath` global.
* New Technology. This resolution of $TMPDIR happens once in a ctor.
*
* Once fclose() is called, the returned file is guaranteed to be
* deleted automatically. On UNIX the file is unlink()'d before this

View file

@ -18,7 +18,6 @@
*/
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/weaken.h"
#include "libc/limits.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
@ -303,9 +302,9 @@ int __vcscanf(int callback(void *), //
if (discard) {
buf = NULL;
} else if (ismalloc) {
buf = _weaken(malloc)(bufsize * charbytes);
buf = malloc(bufsize * charbytes);
struct FreeMe *entry;
if (buf && (entry = _weaken(calloc)(1, sizeof(struct FreeMe)))) {
if (buf && (entry = calloc(1, sizeof(struct FreeMe)))) {
entry->ptr = buf;
entry->next = freeme;
freeme = entry;
@ -317,7 +316,7 @@ int __vcscanf(int callback(void *), //
size_t j = 0;
for (;;) {
if (ismalloc && !width && j + 2 + 1 >= bufsize &&
!_weaken(__grow)(&buf, &bufsize, charbytes, 0)) {
!__grow(&buf, &bufsize, charbytes, 0)) {
width = bufsize - 1;
}
if (c != -1 && j + !rawmode < bufsize && (rawmode || !isspace(c))) {
@ -372,11 +371,11 @@ int __vcscanf(int callback(void *), //
}
}
Done:
while (freeme && _weaken(free)) {
while (freeme) {
struct FreeMe *entry = freeme;
freeme = entry->next;
if (items == -1) _weaken(free)(entry->ptr);
_weaken(free)(entry);
if (items == -1) free(entry->ptr);
free(entry);
}
return items;
}