mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-06-26 22:38:30 +00:00
vista: backport execve escaping and using cocmd as shell for system, etc. (#660)
* Introduce testlib_extract() helper * Have execve() escape double quotes in cmd.exe's preferred style This makes it possible for us to use system() and popen() with paths that redirect to filenames that contain spaces, e.g. system("echo.com hello >\"hello there.txt\"") It's difficult to solve this problem, because WIN32 only allows passing one single argument when launching programs and each program is allowed to tokenize that however it wants. Most software follows the convention of cmd.exe which is poorly documented and positively byzantine. In the future we're going to solve this by not using cmd.exe at all and instead embedding the cocmd.com interpreter into the system() function. In the meantime, our documentation has been updated to help recalibrate any expectation the user might hold regarding the security of using the Windows command interpreter. Fixes #644 * Introduce double quote support in cocmd.com shell * Add some tests for execve() * Embed cocmd.com interpreter for system() / open() This change lets you use system() in an easier and portable way. The problem with the call in the past has always been that bourne and cmd.com on Windows have less than nothing in common, so pretty much the only command system() could be used for across platforms was maybe echo. cmd.exe is also a security liability due to its escaping rules. Since cocmd.com implements 85% of what we need from bourne, in a really tiny way, it makes perfect sense to be embedded in these functionss. We get a huge performance boost too. Fixes #644 * Support whitespace after cocmd output redirection Co-authored-by: Justine Tunney <jtunney@gmail.com>
This commit is contained in:
parent
f4ff1729d1
commit
9c5a7795ad
28 changed files with 622 additions and 401 deletions
|
@ -35,6 +35,10 @@
|
||||||
/**
|
/**
|
||||||
* Replaces current process with program.
|
* Replaces current process with program.
|
||||||
*
|
*
|
||||||
|
* On Windows, `argv` and `envp` can't contain binary strings. They need
|
||||||
|
* to be valid UTF-8 in order to round-trip the WIN32 API, without being
|
||||||
|
* corrupted.
|
||||||
|
*
|
||||||
* @param program will not be PATH searched, see commandv()
|
* @param program will not be PATH searched, see commandv()
|
||||||
* @param argv[0] is the name of the program to run
|
* @param argv[0] is the name of the program to run
|
||||||
* @param argv[1,n-2] optionally specify program arguments
|
* @param argv[1,n-2] optionally specify program arguments
|
||||||
|
|
|
@ -34,8 +34,15 @@
|
||||||
static bool NeedsQuotes(const char *s) {
|
static bool NeedsQuotes(const char *s) {
|
||||||
if (!*s) return true;
|
if (!*s) return true;
|
||||||
do {
|
do {
|
||||||
if (*s == ' ' || *s == '\t') {
|
switch (*s) {
|
||||||
|
case '"':
|
||||||
|
case ' ':
|
||||||
|
case '\t':
|
||||||
|
case '\v':
|
||||||
|
case '\n':
|
||||||
return true;
|
return true;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
} while (*s++);
|
} while (*s++);
|
||||||
return false;
|
return false;
|
||||||
|
@ -45,19 +52,21 @@ static inline int IsAlpha(int c) {
|
||||||
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
|
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Converts System V argv to Windows-style command line.
|
||||||
* Converts System V argv to Windows-style command line.
|
//
|
||||||
*
|
// Escaping is performed and it's designed to round-trip with
|
||||||
* Escaping is performed and it's designed to round-trip with
|
// GetDosArgv() or GetDosArgv(). This function does NOT escape
|
||||||
* GetDosArgv() or GetDosArgv(). This function does NOT escape
|
// command interpreter syntax, e.g. $VAR (sh), %VAR% (cmd).
|
||||||
* command interpreter syntax, e.g. $VAR (sh), %VAR% (cmd).
|
//
|
||||||
*
|
// TODO(jart): this needs fuzzing and security review
|
||||||
* @param cmdline is output buffer
|
//
|
||||||
* @param prog is used as argv[0]
|
// @param cmdline is output buffer
|
||||||
* @param argv is an a NULL-terminated array of UTF-8 strings
|
// @param prog is frontloaded as argv[0]
|
||||||
* @return freshly allocated lpCommandLine or NULL w/ errno
|
// @param argv is an a NULL-terminated array of UTF-8 strings
|
||||||
* @see libc/runtime/dosargv.c
|
// @return 0 on success, or -1 w/ errno
|
||||||
*/
|
// @raise E2BIG if everything is too huge
|
||||||
|
// @see "Everyone quotes command line arguments the wrong way" MSDN
|
||||||
|
// @see libc/runtime/getdosargv.c
|
||||||
textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||||
char *const argv[]) {
|
char *const argv[]) {
|
||||||
char *arg;
|
char *arg;
|
||||||
|
@ -102,8 +111,8 @@ textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||||
} else {
|
} else {
|
||||||
// turn stuff like `less /c/...`
|
// turn stuff like `less /c/...`
|
||||||
// into `less c:/...`
|
// into `less c:/...`
|
||||||
// turn stuff like `more <\\\"/c/...\\\"`
|
// turn stuff like `more <"/c/..."`
|
||||||
// into `more <\\\"c:/...\\\"`
|
// into `more <"c:/..."`
|
||||||
if (k > 3 && IsAlpha(cmdline[k - 1]) &&
|
if (k > 3 && IsAlpha(cmdline[k - 1]) &&
|
||||||
(cmdline[k - 2] == '/' || cmdline[k - 2] == '\\') &&
|
(cmdline[k - 2] == '/' || cmdline[k - 2] == '\\') &&
|
||||||
(cmdline[k - 3] == '"' || cmdline[k - 3] == ' ')) {
|
(cmdline[k - 3] == '"' || cmdline[k - 3] == ' ')) {
|
||||||
|
@ -115,11 +124,8 @@ textwindows int mkntcmdline(char16_t cmdline[ARG_MAX / 2], const char *prog,
|
||||||
if (x == '\\') {
|
if (x == '\\') {
|
||||||
++slashes;
|
++slashes;
|
||||||
} else if (x == '"') {
|
} else if (x == '"') {
|
||||||
for (s = 0; s < slashes * 2; ++s) {
|
APPEND(u'"');
|
||||||
APPEND(u'\\');
|
APPEND(u'"');
|
||||||
}
|
|
||||||
slashes = 0;
|
|
||||||
APPEND(u'\\');
|
|
||||||
APPEND(u'"');
|
APPEND(u'"');
|
||||||
} else {
|
} else {
|
||||||
for (s = 0; s < slashes; ++s) {
|
for (s = 0; s < slashes; ++s) {
|
||||||
|
|
|
@ -173,5 +173,24 @@ textwindows int __mkntpath2(const char *path,
|
||||||
p[j] = 0;
|
p[j] = 0;
|
||||||
n = j;
|
n = j;
|
||||||
|
|
||||||
return x + m + n;
|
// our path is now stored at `path16` with length `n`
|
||||||
|
n = x + m + n;
|
||||||
|
|
||||||
|
// To avoid toil like this:
|
||||||
|
//
|
||||||
|
// CMD.EXE was started with the above path as the current directory.
|
||||||
|
// UNC paths are not supported. Defaulting to Windows directory.
|
||||||
|
// Access is denied.
|
||||||
|
//
|
||||||
|
// Remove \\?\ prefix if we're within 260 character limit.
|
||||||
|
if (n > 4 && n < 260 && //
|
||||||
|
path16[0] == '\\' && //
|
||||||
|
path16[1] == '\\' && //
|
||||||
|
path16[2] == '?' && //
|
||||||
|
path16[3] == '\\') {
|
||||||
|
memmove(path16, path16 + 4, (n - 4 + 1) * sizeof(char16_t));
|
||||||
|
n -= 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
return n;
|
||||||
}
|
}
|
||||||
|
|
|
@ -66,25 +66,23 @@ static textwindows noasan int Count(int c, struct DosArgv *st) {
|
||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Tokenizes and transcodes Windows NT CLI args, thus avoiding
|
||||||
* Tokenizes and transcodes Windows NT CLI args, thus avoiding
|
// CommandLineToArgv() schlepping in forty megs of dependencies.
|
||||||
* CommandLineToArgv() schlepping in forty megs of dependencies.
|
//
|
||||||
*
|
// @param s is the command line string provided by the executive
|
||||||
* @param s is the command line string provided by the executive
|
// @param buf is where we'll store double-NUL-terminated decoded args
|
||||||
* @param buf is where we'll store double-NUL-terminated decoded args
|
// @param size is how many bytes are available in buf
|
||||||
* @param size is how many bytes are available in buf
|
// @param argv is where we'll store the decoded arg pointer array, which
|
||||||
* @param argv is where we'll store the decoded arg pointer array, which
|
// is guaranteed to be NULL-terminated if max>0
|
||||||
* is guaranteed to be NULL-terminated if max>0
|
// @param max specifies the item capacity of argv, or 0 to do scanning
|
||||||
* @param max specifies the item capacity of argv, or 0 to do scanning
|
// @return number of args written, excluding the NULL-terminator; or,
|
||||||
* @return number of args written, excluding the NULL-terminator; or,
|
// if the output buffer wasn't passed, or was too short, then the
|
||||||
* if the output buffer wasn't passed, or was too short, then the
|
// number of args that *would* have been written is returned; and
|
||||||
* number of args that *would* have been written is returned; and
|
// there are currently no failure conditions that would have this
|
||||||
* there are currently no failure conditions that would have this
|
// return -1 since it doesn't do system calls
|
||||||
* return -1 since it doesn't do system calls
|
// @see test/libc/dosarg_test.c
|
||||||
* @see test/libc/dosarg_test.c
|
// @see libc/runtime/ntspawn.c
|
||||||
* @see libc/runtime/ntspawn.c
|
// @note kudos to Simon Tatham for figuring out quoting behavior
|
||||||
* @note kudos to Simon Tatham for figuring out quoting behavior
|
|
||||||
*/
|
|
||||||
textwindows noasan int GetDosArgv(const char16_t *cmdline, char *buf,
|
textwindows noasan int GetDosArgv(const char16_t *cmdline, char *buf,
|
||||||
size_t size, char **argv, size_t max) {
|
size_t size, char **argv, size_t max) {
|
||||||
bool inquote;
|
bool inquote;
|
||||||
|
|
|
@ -104,16 +104,14 @@ textwindows noinstrument noasan void FixPath(char *path) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Transcodes NT environment variable block from UTF-16 to UTF-8.
|
||||||
* Transcodes NT environment variable block from UTF-16 to UTF-8.
|
//
|
||||||
*
|
// @param env is a double NUL-terminated block of key=values
|
||||||
* @param env is a double NUL-terminated block of key=values
|
// @param buf is the new environment which gets double-nul'd
|
||||||
* @param buf is the new environment which gets double-nul'd
|
// @param size is the byte capacity of buf
|
||||||
* @param size is the byte capacity of buf
|
// @param envp stores NULL-terminated string pointer list (optional)
|
||||||
* @param envp stores NULL-terminated string pointer list (optional)
|
// @param max is the pointer count capacity of envp
|
||||||
* @param max is the pointer count capacity of envp
|
// @return number of variables decoded, excluding NULL-terminator
|
||||||
* @return number of variables decoded, excluding NULL-terminator
|
|
||||||
*/
|
|
||||||
textwindows noasan noinstrument int GetDosEnviron(const char16_t *env,
|
textwindows noasan noinstrument int GetDosEnviron(const char16_t *env,
|
||||||
char *buf, size_t size,
|
char *buf, size_t size,
|
||||||
char **envp, size_t max) {
|
char **envp, size_t max) {
|
||||||
|
|
275
libc/stdio/cocmd.c
Normal file
275
libc/stdio/cocmd.c
Normal file
|
@ -0,0 +1,275 @@
|
||||||
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-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/itoa.h"
|
||||||
|
#include "libc/macros.internal.h"
|
||||||
|
#include "libc/mem/mem.h"
|
||||||
|
#include "libc/runtime/runtime.h"
|
||||||
|
#include "libc/stdio/stdio.h"
|
||||||
|
#include "libc/str/errfun.h"
|
||||||
|
#include "libc/str/str.h"
|
||||||
|
#include "libc/sysv/consts/o.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @fileoverview Cosmopolitan Command Interpreter
|
||||||
|
*
|
||||||
|
* This is a lightweight command interpreter for GNU Make. It has just
|
||||||
|
* enough shell script language support to support our build config.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define STATE_SHELL 0
|
||||||
|
#define STATE_STR 1
|
||||||
|
#define STATE_QUO 2
|
||||||
|
|
||||||
|
static char *p;
|
||||||
|
static char *q;
|
||||||
|
static size_t n;
|
||||||
|
static char *cmd;
|
||||||
|
static char *args[8192];
|
||||||
|
static const char *prog;
|
||||||
|
static char argbuf[ARG_MAX];
|
||||||
|
static bool unsupported[256];
|
||||||
|
|
||||||
|
static wontreturn void Wexit(int rc, const char *s, ...) {
|
||||||
|
va_list va;
|
||||||
|
va_start(va, s);
|
||||||
|
do {
|
||||||
|
write(2, s, strlen(s));
|
||||||
|
} while ((s = va_arg(va, const char *)));
|
||||||
|
va_end(va);
|
||||||
|
exit(rc);
|
||||||
|
}
|
||||||
|
|
||||||
|
static wontreturn void UnsupportedSyntax(unsigned char c) {
|
||||||
|
char cbuf[2];
|
||||||
|
char ibuf[13];
|
||||||
|
cbuf[0] = c;
|
||||||
|
cbuf[1] = 0;
|
||||||
|
FormatOctal32(ibuf, c, true);
|
||||||
|
Wexit(4, prog, ": unsupported shell syntax '", cbuf, "' (", ibuf, "): ", cmd,
|
||||||
|
"\n", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static wontreturn void SysExit(int rc, const char *call, const char *thing) {
|
||||||
|
int err;
|
||||||
|
char ibuf[12];
|
||||||
|
const char *estr;
|
||||||
|
err = errno;
|
||||||
|
FormatInt32(ibuf, err);
|
||||||
|
estr = strerdoc(err);
|
||||||
|
if (!estr) estr = "EUNKNOWN";
|
||||||
|
Wexit(rc, thing, ": ", call, "() failed: ", estr, " (", ibuf, ")\n", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void Open(const char *path, int fd, int flags) {
|
||||||
|
const char *err;
|
||||||
|
close(fd);
|
||||||
|
if (open(path, flags, 0644) == -1) {
|
||||||
|
SysExit(7, "open", path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static wontreturn void Exec(void) {
|
||||||
|
const char *s;
|
||||||
|
if (!n) {
|
||||||
|
Wexit(5, prog, ": error: too few args\n", 0);
|
||||||
|
}
|
||||||
|
execvp(args[0], args);
|
||||||
|
SysExit(127, "execve", args[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void Pipe(void) {
|
||||||
|
int pid, pfds[2];
|
||||||
|
if (pipe2(pfds, O_CLOEXEC)) {
|
||||||
|
SysExit(8, "pipe2", prog);
|
||||||
|
}
|
||||||
|
if ((pid = vfork()) == -1) {
|
||||||
|
SysExit(9, "vfork", prog);
|
||||||
|
}
|
||||||
|
if (!pid) {
|
||||||
|
dup2(pfds[1], 1);
|
||||||
|
Exec();
|
||||||
|
}
|
||||||
|
dup2(pfds[0], 0);
|
||||||
|
n = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static char *Tokenize(void) {
|
||||||
|
char *r;
|
||||||
|
int c, t;
|
||||||
|
while (*p == ' ' || *p == '\t' || *p == '\n' ||
|
||||||
|
(p[0] == '\\' && p[1] == '\n')) {
|
||||||
|
++p;
|
||||||
|
}
|
||||||
|
if (!*p) return 0;
|
||||||
|
t = STATE_SHELL;
|
||||||
|
for (r = q;; ++p) {
|
||||||
|
switch (t) {
|
||||||
|
|
||||||
|
case STATE_SHELL:
|
||||||
|
if (unsupported[*p & 255]) {
|
||||||
|
UnsupportedSyntax(*p);
|
||||||
|
}
|
||||||
|
if (!*p || *p == ' ' || *p == '\t') {
|
||||||
|
*q++ = 0;
|
||||||
|
return r;
|
||||||
|
} else if (*p == '"') {
|
||||||
|
t = STATE_QUO;
|
||||||
|
} else if (*p == '\'') {
|
||||||
|
t = STATE_STR;
|
||||||
|
} else if (*p == '\\') {
|
||||||
|
if (!p[1]) UnsupportedSyntax(*p);
|
||||||
|
*q++ = *++p;
|
||||||
|
} else if (*p == '|') {
|
||||||
|
if (q > r) {
|
||||||
|
*q = 0;
|
||||||
|
return r;
|
||||||
|
} else {
|
||||||
|
Pipe();
|
||||||
|
++p;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*q++ = *p;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case STATE_STR:
|
||||||
|
if (!*p) {
|
||||||
|
Wexit(6, "cmd: error: unterminated single string\n", 0);
|
||||||
|
}
|
||||||
|
if (*p == '\'') {
|
||||||
|
t = STATE_SHELL;
|
||||||
|
} else {
|
||||||
|
*q++ = *p;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case STATE_QUO:
|
||||||
|
if (!*p) {
|
||||||
|
Wexit(6, "cmd: error: unterminated quoted string\n", 0);
|
||||||
|
}
|
||||||
|
if (*p == '"') {
|
||||||
|
t = STATE_SHELL;
|
||||||
|
} else if (p[0] == '\\') {
|
||||||
|
switch ((c = *++p)) {
|
||||||
|
case 0:
|
||||||
|
UnsupportedSyntax('\\');
|
||||||
|
case '\n':
|
||||||
|
break;
|
||||||
|
case '$':
|
||||||
|
case '`':
|
||||||
|
case '"':
|
||||||
|
*q++ = c;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
*q++ = '\\';
|
||||||
|
*q++ = c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*q++ = *p;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
unreachable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *GetRedirectArg(const char *prog, const char *arg, int n) {
|
||||||
|
if (arg[n]) {
|
||||||
|
return arg + n;
|
||||||
|
} else if ((arg = Tokenize())) {
|
||||||
|
return arg;
|
||||||
|
} else {
|
||||||
|
Wexit(14, prog, ": error: redirect missing path\n", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int cocmd(int argc, char *argv[]) {
|
||||||
|
char *arg;
|
||||||
|
size_t i, j;
|
||||||
|
prog = argc > 0 ? argv[0] : "cocmd.com";
|
||||||
|
|
||||||
|
for (i = 1; i < 32; ++i) {
|
||||||
|
unsupported[i] = true;
|
||||||
|
}
|
||||||
|
unsupported['\t'] = false;
|
||||||
|
unsupported[0177] = true;
|
||||||
|
unsupported['~'] = true;
|
||||||
|
unsupported['`'] = true;
|
||||||
|
unsupported['#'] = true;
|
||||||
|
unsupported['*'] = true;
|
||||||
|
unsupported['('] = true;
|
||||||
|
unsupported[')'] = true;
|
||||||
|
unsupported['['] = true;
|
||||||
|
unsupported[']'] = true;
|
||||||
|
unsupported['{'] = true;
|
||||||
|
unsupported['}'] = true;
|
||||||
|
unsupported[';'] = true;
|
||||||
|
unsupported['?'] = true;
|
||||||
|
unsupported['!'] = true;
|
||||||
|
|
||||||
|
if (argc != 3) {
|
||||||
|
Wexit(10, prog, ": error: wrong number of args\n", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strcmp(argv[1], "-c")) {
|
||||||
|
Wexit(11, prog, ": error: argv[1] should -c\n", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
p = cmd = argv[2];
|
||||||
|
if (strlen(cmd) >= ARG_MAX) {
|
||||||
|
Wexit(12, prog, ": error: cmd too long: ", cmd, "\n", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
n = 0;
|
||||||
|
q = argbuf;
|
||||||
|
while ((arg = Tokenize())) {
|
||||||
|
if (n + 1 < ARRAYLEN(args)) {
|
||||||
|
if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '&' &&
|
||||||
|
isdigit(arg[3])) {
|
||||||
|
dup2(arg[3] - '0', arg[0] - '0');
|
||||||
|
} else if (arg[0] == '>' && arg[1] == '&' && isdigit(arg[2])) {
|
||||||
|
dup2(arg[2] - '0', 1);
|
||||||
|
} else if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '>') {
|
||||||
|
Open(GetRedirectArg(prog, arg, 3), arg[0] - '0',
|
||||||
|
O_WRONLY | O_CREAT | O_APPEND);
|
||||||
|
} else if (arg[0] == '>' && arg[1] == '>') {
|
||||||
|
Open(GetRedirectArg(prog, arg, 2), 1, O_WRONLY | O_CREAT | O_APPEND);
|
||||||
|
} else if (isdigit(arg[0]) && arg[1] == '>') {
|
||||||
|
Open(GetRedirectArg(prog, arg, 2), arg[0] - '0',
|
||||||
|
O_WRONLY | O_CREAT | O_TRUNC);
|
||||||
|
} else if (arg[0] == '>') {
|
||||||
|
Open(GetRedirectArg(prog, arg, 1), 1, O_WRONLY | O_CREAT | O_TRUNC);
|
||||||
|
} else if (arg[0] == '<') {
|
||||||
|
Open(GetRedirectArg(prog, arg, 1), 0, O_RDONLY);
|
||||||
|
} else {
|
||||||
|
args[n++] = arg;
|
||||||
|
args[n] = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Wexit(13, prog, ": error: too many args\n", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Exec();
|
||||||
|
}
|
10
libc/stdio/cocmd.internal.h
Normal file
10
libc/stdio/cocmd.internal.h
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
#ifndef COSMOPOLITAN_LIBC_STDIO_COCMD_INTERNAL_H_
|
||||||
|
#define COSMOPOLITAN_LIBC_STDIO_COCMD_INTERNAL_H_
|
||||||
|
#if !(__ASSEMBLER__ + __LINKER__ + 0)
|
||||||
|
COSMOPOLITAN_C_START_
|
||||||
|
|
||||||
|
int cocmd(int, char **);
|
||||||
|
|
||||||
|
COSMOPOLITAN_C_END_
|
||||||
|
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
|
||||||
|
#endif /* COSMOPOLITAN_LIBC_STDIO_COCMD_INTERNAL_H_ */
|
|
@ -56,9 +56,9 @@ static bool have_getrandom;
|
||||||
*
|
*
|
||||||
* The following flags may be specified:
|
* The following flags may be specified:
|
||||||
*
|
*
|
||||||
* - GRND_RANDOM: Halt the entire system while I tap an entropy pool
|
* - `GRND_RANDOM`: Halt the entire system while I tap an entropy pool
|
||||||
* so small that it's hard to use statistics to test if it's random
|
* so small that it's hard to use statistics to test if it's random
|
||||||
* - GRND_NONBLOCK: Do not wait for i/o events or me to jiggle my
|
* - `GRND_NONBLOCK`: Do not wait for i/o events or me to jiggle my
|
||||||
* mouse, and instead return immediately the moment data isn't
|
* mouse, and instead return immediately the moment data isn't
|
||||||
* available, even if the result needs to be -1 w/ EAGAIN
|
* available, even if the result needs to be -1 w/ EAGAIN
|
||||||
*
|
*
|
||||||
|
@ -68,6 +68,8 @@ static bool have_getrandom;
|
||||||
* @note this function could block a nontrivial time on old computers
|
* @note this function could block a nontrivial time on old computers
|
||||||
* @note this function is indeed intended for cryptography
|
* @note this function is indeed intended for cryptography
|
||||||
* @note this function takes around 900 cycles
|
* @note this function takes around 900 cycles
|
||||||
|
* @raise EINVAL if `f` is invalid
|
||||||
|
* @raise ENOSYS on bare metal
|
||||||
* @asyncsignalsafe
|
* @asyncsignalsafe
|
||||||
* @restartable
|
* @restartable
|
||||||
* @vforksafe
|
* @vforksafe
|
||||||
|
@ -81,8 +83,10 @@ ssize_t getrandom(void *p, size_t n, unsigned f) {
|
||||||
const char *via;
|
const char *via;
|
||||||
sigset_t neu, old;
|
sigset_t neu, old;
|
||||||
if (n > 256) n = 256;
|
if (n > 256) n = 256;
|
||||||
if ((f & ~(GRND_RANDOM | GRND_NONBLOCK))) return einval();
|
if ((f & ~(GRND_RANDOM | GRND_NONBLOCK))) {
|
||||||
if (IsWindows()) {
|
rc = einval();
|
||||||
|
via = "n/a";
|
||||||
|
} else if (IsWindows()) {
|
||||||
via = "RtlGenRandom";
|
via = "RtlGenRandom";
|
||||||
if (RtlGenRandom(p, n)) {
|
if (RtlGenRandom(p, n)) {
|
||||||
rc = n;
|
rc = n;
|
||||||
|
|
|
@ -29,6 +29,16 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Spawns subprocess and returns pipe stream.
|
* Spawns subprocess and returns pipe stream.
|
||||||
|
*
|
||||||
|
* This embeds the cocmd.com shell interpreter which supports a limited
|
||||||
|
* subset of the bourne shell that's significantly faster:
|
||||||
|
*
|
||||||
|
* - pipelines
|
||||||
|
* - single quotes
|
||||||
|
* - double quotes
|
||||||
|
* - input redirection, e.g. `<path`
|
||||||
|
* - output redirection, e.g. `>path`, `>>append`, `2>err.txt, `2>&1`
|
||||||
|
*
|
||||||
* @see pclose()
|
* @see pclose()
|
||||||
*/
|
*/
|
||||||
FILE *popen(const char *cmdline, const char *mode) {
|
FILE *popen(const char *cmdline, const char *mode) {
|
||||||
|
|
|
@ -32,6 +32,15 @@
|
||||||
/**
|
/**
|
||||||
* Launches program with system command interpreter.
|
* Launches program with system command interpreter.
|
||||||
*
|
*
|
||||||
|
* This embeds the cocmd.com shell interpreter which supports a limited
|
||||||
|
* subset of the bourne shell that's significantly faster:
|
||||||
|
*
|
||||||
|
* - pipelines
|
||||||
|
* - single quotes
|
||||||
|
* - double quotes
|
||||||
|
* - input redirection, e.g. `<path`
|
||||||
|
* - output redirection, e.g. `>path`, `>>append`, `2>err.txt, `2>&1`
|
||||||
|
*
|
||||||
* @param cmdline is an interpreted Turing-complete command
|
* @param cmdline is an interpreted Turing-complete command
|
||||||
* @return -1 if child process couldn't be created, otherwise a wait
|
* @return -1 if child process couldn't be created, otherwise a wait
|
||||||
* status that can be accessed using macros like WEXITSTATUS(s)
|
* status that can be accessed using macros like WEXITSTATUS(s)
|
||||||
|
@ -40,11 +49,7 @@ int system(const char *cmdline) {
|
||||||
int pid, wstatus;
|
int pid, wstatus;
|
||||||
sigset_t chldmask, savemask;
|
sigset_t chldmask, savemask;
|
||||||
struct sigaction ignore, saveint, savequit;
|
struct sigaction ignore, saveint, savequit;
|
||||||
if (!cmdline) {
|
if (!cmdline) return 1;
|
||||||
if (IsWindows()) return 1;
|
|
||||||
if (!access(_PATH_BSHELL, X_OK)) return 1;
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
ignore.sa_flags = 0;
|
ignore.sa_flags = 0;
|
||||||
ignore.sa_handler = SIG_IGN;
|
ignore.sa_handler = SIG_IGN;
|
||||||
sigemptyset(&ignore.sa_mask);
|
sigemptyset(&ignore.sa_mask);
|
||||||
|
|
|
@ -16,35 +16,11 @@
|
||||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||||
#include "libc/calls/calls.h"
|
|
||||||
#include "libc/dce.h"
|
|
||||||
#include "libc/macros.internal.h"
|
|
||||||
#include "libc/paths.h"
|
|
||||||
#include "libc/runtime/runtime.h"
|
#include "libc/runtime/runtime.h"
|
||||||
#include "libc/str/str.h"
|
#include "libc/stdio/cocmd.internal.h"
|
||||||
#include "libc/sysv/errfuns.h"
|
#include "libc/stdio/stdio.h"
|
||||||
|
|
||||||
/**
|
// Support code for system() and popen().
|
||||||
* Executes system command replacing current process.
|
|
||||||
* @vforksafe
|
|
||||||
*/
|
|
||||||
int systemexec(const char *cmdline) {
|
int systemexec(const char *cmdline) {
|
||||||
size_t n, m;
|
_Exit(cocmd(3, (char *[]){"cocmd.com", "-c", cmdline, 0}));
|
||||||
char *a, *b, *argv[4], comspec[PATH_MAX];
|
|
||||||
if (!IsWindows()) {
|
|
||||||
argv[0] = _PATH_BSHELL;
|
|
||||||
argv[1] = "-c";
|
|
||||||
} else {
|
|
||||||
b = "cmd.exe";
|
|
||||||
a = kNtSystemDirectory;
|
|
||||||
if ((n = strlen(a)) + (m = strlen(b)) >= ARRAYLEN(comspec)) {
|
|
||||||
return enametoolong();
|
|
||||||
}
|
|
||||||
memcpy(mempcpy(comspec, a, n), b, m + 1);
|
|
||||||
argv[0] = comspec;
|
|
||||||
argv[1] = "/C";
|
|
||||||
}
|
|
||||||
argv[2] = cmdline;
|
|
||||||
argv[3] = NULL;
|
|
||||||
return execv(argv[0], argv);
|
|
||||||
}
|
}
|
||||||
|
|
40
libc/testlib/extract.c
Normal file
40
libc/testlib/extract.c
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-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/mem/io.h"
|
||||||
|
#include "libc/sysv/consts/o.h"
|
||||||
|
#include "libc/testlib/testlib.h"
|
||||||
|
|
||||||
|
STATIC_YOINK("zip_uri_support");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts zip asset to filesystem.
|
||||||
|
*
|
||||||
|
* @param zip is name of asset in zip executable central directory
|
||||||
|
* @param to is local filesystem path to which it's extracted
|
||||||
|
* @param mode is file mode used for `to`
|
||||||
|
*/
|
||||||
|
void testlib_extract(const char *zip, const char *to, int mode) {
|
||||||
|
int fdin, fdout;
|
||||||
|
ASSERT_NE(-1, (fdin = open(zip, O_RDONLY)));
|
||||||
|
ASSERT_NE(-1, (fdout = creat(to, mode)));
|
||||||
|
ASSERT_NE(-1, _copyfd(fdin, fdout, -1));
|
||||||
|
ASSERT_NE(-1, close(fdout));
|
||||||
|
ASSERT_NE(-1, close(fdin));
|
||||||
|
}
|
|
@ -395,6 +395,7 @@ bool testlib_strcaseequals(size_t, const void *, const void *) nosideeffect;
|
||||||
bool testlib_strncaseequals(size_t, const void *, const void *,
|
bool testlib_strncaseequals(size_t, const void *, const void *,
|
||||||
size_t) nosideeffect;
|
size_t) nosideeffect;
|
||||||
void testlib_free(void *);
|
void testlib_free(void *);
|
||||||
|
void testlib_extract(const char *, const char *, int);
|
||||||
bool testlib_binequals(const char16_t *, const void *, size_t) nosideeffect;
|
bool testlib_binequals(const char16_t *, const void *, size_t) nosideeffect;
|
||||||
bool testlib_hexequals(const char *, const void *, size_t) nosideeffect;
|
bool testlib_hexequals(const char *, const void *, size_t) nosideeffect;
|
||||||
bool testlib_startswith(size_t, const void *, const void *) nosideeffect;
|
bool testlib_startswith(size_t, const void *, const void *) nosideeffect;
|
||||||
|
|
|
@ -59,6 +59,7 @@ LIBC_TESTLIB_A_SRCS_C = \
|
||||||
libc/testlib/comborunner.c \
|
libc/testlib/comborunner.c \
|
||||||
libc/testlib/contains.c \
|
libc/testlib/contains.c \
|
||||||
libc/testlib/endswith.c \
|
libc/testlib/endswith.c \
|
||||||
|
libc/testlib/extract.c \
|
||||||
libc/testlib/ezbenchcontrol.c \
|
libc/testlib/ezbenchcontrol.c \
|
||||||
libc/testlib/ezbenchreport.c \
|
libc/testlib/ezbenchreport.c \
|
||||||
libc/testlib/ezbenchwarn.c \
|
libc/testlib/ezbenchwarn.c \
|
||||||
|
|
60
test/libc/calls/execve_test.c
Normal file
60
test/libc/calls/execve_test.c
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-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/fmt/conv.h"
|
||||||
|
#include "libc/fmt/itoa.h"
|
||||||
|
#include "libc/runtime/runtime.h"
|
||||||
|
#include "libc/str/str.h"
|
||||||
|
#include "libc/testlib/subprocess.h"
|
||||||
|
#include "libc/testlib/testlib.h"
|
||||||
|
|
||||||
|
#define N 127
|
||||||
|
|
||||||
|
char *GenBuf(char buf[8], int x) {
|
||||||
|
int i;
|
||||||
|
bzero(buf, 8);
|
||||||
|
for (i = 0; i < 7; ++i) {
|
||||||
|
buf[i] = x & 127; // nt doesn't respect invalid unicode?
|
||||||
|
x >>= 1;
|
||||||
|
}
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((__constructor__)) static void init(void) {
|
||||||
|
char buf[8];
|
||||||
|
if (__argc == 4 && !strcmp(__argv[1], "-")) {
|
||||||
|
ASSERT_STREQ(GenBuf(buf, atoi(__argv[2])), __argv[3]);
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(execve, testArgPassing) {
|
||||||
|
int i;
|
||||||
|
char ibuf[12], buf[8];
|
||||||
|
for (i = 0; i < N; ++i) {
|
||||||
|
FormatInt32(ibuf, i);
|
||||||
|
GenBuf(buf, i);
|
||||||
|
SPAWN(vfork);
|
||||||
|
execve(GetProgramExecutableName(),
|
||||||
|
(char *const[]){GetProgramExecutableName(), "-", ibuf, buf, 0},
|
||||||
|
(char *const[]){0});
|
||||||
|
notpossible;
|
||||||
|
EXITS(0);
|
||||||
|
}
|
||||||
|
}
|
|
@ -61,12 +61,6 @@ TEST(mkntcmdline, justSlash) {
|
||||||
EXPECT_STREQ(u"\\", cmdline);
|
EXPECT_STREQ(u"\\", cmdline);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(mkntcmdline, basicQuoting) {
|
|
||||||
char *argv[] = {"a\"b c", "d", NULL};
|
|
||||||
EXPECT_NE(-1, mkntcmdline(cmdline, argv[0], argv));
|
|
||||||
EXPECT_STREQ(u"\"a\\\"b c\" d" /* "a\"b c" d */, cmdline);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(mkntcmdline, testUnicode) {
|
TEST(mkntcmdline, testUnicode) {
|
||||||
char *argv1[] = {
|
char *argv1[] = {
|
||||||
gc(strdup("(╯°□°)╯")),
|
gc(strdup("(╯°□°)╯")),
|
||||||
|
@ -87,7 +81,7 @@ TEST(mkntcmdline, fixAsBestAsWeCanForNow1) {
|
||||||
};
|
};
|
||||||
EXPECT_NE(-1, mkntcmdline(cmdline, argv1[0], argv1));
|
EXPECT_NE(-1, mkntcmdline(cmdline, argv1[0], argv1));
|
||||||
EXPECT_STREQ(u"C:\\WINDOWS\\system32\\cmd.exe /C \"more <"
|
EXPECT_STREQ(u"C:\\WINDOWS\\system32\\cmd.exe /C \"more <"
|
||||||
u"\\\"C:/Users/jart/AppData/Local/Temp/tmplquaa_d6\\\"\"",
|
u"\"\"\"C:/Users/jart/AppData/Local/Temp/tmplquaa_d6\"\"\"\"",
|
||||||
cmdline);
|
cmdline);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -106,6 +100,6 @@ TEST(mkntcmdline, fixAsBestAsWeCanForNow2) {
|
||||||
|
|
||||||
TEST(mkntcmdline, testWut) {
|
TEST(mkntcmdline, testWut) {
|
||||||
char *argv[] = {"redbean.com", "--strace", NULL};
|
char *argv[] = {"redbean.com", "--strace", NULL};
|
||||||
EXPECT_NE(-1, mkntcmdline(cmdline, "C:\\Users\\jart\\redbean.com", argv));
|
EXPECT_NE(-1, mkntcmdline(cmdline, "C:\\Users\\jart\\𝑟𝑒𝑑𝑏𝑒𝑎𝑛.com", argv));
|
||||||
EXPECT_STREQ(u"C:\\Users\\jart\\redbean.com --strace", cmdline);
|
EXPECT_STREQ(u"C:\\Users\\jart\\𝑟𝑒𝑑𝑏𝑒𝑎𝑛.com --strace", cmdline);
|
||||||
}
|
}
|
||||||
|
|
|
@ -47,11 +47,4 @@ TEST(mkntpath, testUnicode) {
|
||||||
TEST(mkntpath, testRemoveDoubleSlash) {
|
TEST(mkntpath, testRemoveDoubleSlash) {
|
||||||
EXPECT_EQ(21, __mkntpath("C:\\Users\\jart\\\\.config", p));
|
EXPECT_EQ(21, __mkntpath("C:\\Users\\jart\\\\.config", p));
|
||||||
EXPECT_STREQ(u"C:\\Users\\jart\\.config", p);
|
EXPECT_STREQ(u"C:\\Users\\jart\\.config", p);
|
||||||
EXPECT_EQ(8, __mkntpath("\\\\?\\doge", p));
|
|
||||||
EXPECT_STREQ(u"\\\\?\\doge", p);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(mkntpath, testJustC) {
|
|
||||||
EXPECT_EQ(7, __mkntpath("/C", p));
|
|
||||||
EXPECT_STREQ(u"\\\\?\\C:\\", p);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -56,8 +56,6 @@
|
||||||
#include "libc/time/time.h"
|
#include "libc/time/time.h"
|
||||||
#include "libc/x/x.h"
|
#include "libc/x/x.h"
|
||||||
|
|
||||||
STATIC_YOINK("zip_uri_support");
|
|
||||||
|
|
||||||
char testlib_enable_tmp_setup_teardown;
|
char testlib_enable_tmp_setup_teardown;
|
||||||
|
|
||||||
void OnSig(int sig) {
|
void OnSig(int sig) {
|
||||||
|
@ -66,26 +64,11 @@ void OnSig(int sig) {
|
||||||
|
|
||||||
int sys_memfd_secret(unsigned int); // our ENOSYS threshold
|
int sys_memfd_secret(unsigned int); // our ENOSYS threshold
|
||||||
|
|
||||||
int extract(const char *from, const char *to, int mode) {
|
|
||||||
int fdin, fdout;
|
|
||||||
if ((fdin = open(from, O_RDONLY)) == -1) return -1;
|
|
||||||
if ((fdout = creat(to, mode)) == -1) {
|
|
||||||
close(fdin);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
if (_copyfd(fdin, fdout, -1) == -1) {
|
|
||||||
close(fdout);
|
|
||||||
close(fdin);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return close(fdout) | close(fdin);
|
|
||||||
}
|
|
||||||
|
|
||||||
void SetUp(void) {
|
void SetUp(void) {
|
||||||
__enable_threads();
|
__enable_threads();
|
||||||
if (!__is_linux_2_6_23() && !IsOpenbsd()) exit(0);
|
if (!__is_linux_2_6_23() && !IsOpenbsd()) exit(0);
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "life.elf", 0755));
|
testlib_extract("/zip/life.elf", "life.elf", 0755);
|
||||||
ASSERT_SYS(0, 0, extract("/zip/sock.elf", "sock.elf", 0755));
|
testlib_extract("/zip/sock.elf", "sock.elf", 0755);
|
||||||
__pledge_mode = PLEDGE_PENALTY_RETURN_EPERM;
|
__pledge_mode = PLEDGE_PENALTY_RETURN_EPERM;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -44,8 +44,6 @@
|
||||||
#include "libc/thread/spawn.h"
|
#include "libc/thread/spawn.h"
|
||||||
#include "libc/x/x.h"
|
#include "libc/x/x.h"
|
||||||
|
|
||||||
STATIC_YOINK("zip_uri_support");
|
|
||||||
|
|
||||||
#define EACCES_OR_ENOENT (IsOpenbsd() ? ENOENT : EACCES)
|
#define EACCES_OR_ENOENT (IsOpenbsd() ? ENOENT : EACCES)
|
||||||
|
|
||||||
char testlib_enable_tmp_setup_teardown;
|
char testlib_enable_tmp_setup_teardown;
|
||||||
|
@ -69,21 +67,6 @@ void SetUp(void) {
|
||||||
ASSERT_SYS(0, 0, stat("/zip/life.elf", &st));
|
ASSERT_SYS(0, 0, stat("/zip/life.elf", &st));
|
||||||
}
|
}
|
||||||
|
|
||||||
int extract(const char *from, const char *to, int mode) {
|
|
||||||
int fdin, fdout;
|
|
||||||
if ((fdin = open(from, O_RDONLY)) == -1) return -1;
|
|
||||||
if ((fdout = creat(to, mode)) == -1) {
|
|
||||||
close(fdin);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
if (_copyfd(fdin, fdout, -1) == -1) {
|
|
||||||
close(fdout);
|
|
||||||
close(fdin);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return close(fdout) | close(fdin);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(unveil, api_differences) {
|
TEST(unveil, api_differences) {
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, mkdir("foo", 0755));
|
ASSERT_SYS(0, 0, mkdir("foo", 0755));
|
||||||
|
@ -110,7 +93,7 @@ TEST(unveil, api_differences) {
|
||||||
TEST(unveil, rx_readOnlyPreexistingExecutable_worksFine) {
|
TEST(unveil, rx_readOnlyPreexistingExecutable_worksFine) {
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "folder/life.elf", 0755));
|
testlib_extract("/zip/life.elf", "folder/life.elf", 0755);
|
||||||
ASSERT_SYS(0, 0, unveil("folder", "rx"));
|
ASSERT_SYS(0, 0, unveil("folder", "rx"));
|
||||||
ASSERT_SYS(0, 0, unveil(0, 0));
|
ASSERT_SYS(0, 0, unveil(0, 0));
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
|
@ -124,7 +107,7 @@ TEST(unveil, rx_readOnlyPreexistingExecutable_worksFine) {
|
||||||
TEST(unveil, r_noExecutePreexistingExecutable_raisesEacces) {
|
TEST(unveil, r_noExecutePreexistingExecutable_raisesEacces) {
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "folder/life.elf", 0755));
|
testlib_extract("/zip/life.elf", "folder/life.elf", 0755);
|
||||||
ASSERT_SYS(0, 0, unveil("folder", "r"));
|
ASSERT_SYS(0, 0, unveil("folder", "r"));
|
||||||
ASSERT_SYS(0, 0, unveil(0, 0));
|
ASSERT_SYS(0, 0, unveil(0, 0));
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
|
@ -155,7 +138,7 @@ TEST(unveil, rwc_createExecutableFile_isAllowedButCantBeRun) {
|
||||||
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
||||||
ASSERT_SYS(0, 0, unveil("folder", "rwc"));
|
ASSERT_SYS(0, 0, unveil("folder", "rwc"));
|
||||||
ASSERT_SYS(0, 0, unveil(0, 0));
|
ASSERT_SYS(0, 0, unveil(0, 0));
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "folder/life.elf", 0755));
|
testlib_extract("/zip/life.elf", "folder/life.elf", 0755);
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, stat("folder/life.elf", &st));
|
ASSERT_SYS(0, 0, stat("folder/life.elf", &st));
|
||||||
ASSERT_SYS(EACCES, -1, execl("folder/life.elf", "folder/life.elf", 0));
|
ASSERT_SYS(EACCES, -1, execl("folder/life.elf", "folder/life.elf", 0));
|
||||||
|
@ -168,7 +151,7 @@ TEST(unveil, rwcx_createExecutableFile_canAlsoBeRun) {
|
||||||
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
ASSERT_SYS(0, 0, mkdir("folder", 0755));
|
||||||
ASSERT_SYS(0, 0, unveil("folder", "rwcx"));
|
ASSERT_SYS(0, 0, unveil("folder", "rwcx"));
|
||||||
ASSERT_SYS(0, 0, unveil(0, 0));
|
ASSERT_SYS(0, 0, unveil(0, 0));
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "folder/life.elf", 0755));
|
testlib_extract("/zip/life.elf", "folder/life.elf", 0755);
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, stat("folder/life.elf", &st));
|
ASSERT_SYS(0, 0, stat("folder/life.elf", &st));
|
||||||
execl("folder/life.elf", "folder/life.elf", 0);
|
execl("folder/life.elf", "folder/life.elf", 0);
|
||||||
|
@ -205,7 +188,7 @@ TEST(unveil, mostRestrictivePolicy) {
|
||||||
TEST(unveil, overlappingDirectories_inconsistentBehavior) {
|
TEST(unveil, overlappingDirectories_inconsistentBehavior) {
|
||||||
SPAWN(fork);
|
SPAWN(fork);
|
||||||
ASSERT_SYS(0, 0, makedirs("f1/f2", 0755));
|
ASSERT_SYS(0, 0, makedirs("f1/f2", 0755));
|
||||||
ASSERT_SYS(0, 0, extract("/zip/life.elf", "f1/f2/life.elf", 0755));
|
testlib_extract("/zip/life.elf", "f1/f2/life.elf", 0755);
|
||||||
ASSERT_SYS(0, 0, unveil("f1", "x"));
|
ASSERT_SYS(0, 0, unveil("f1", "x"));
|
||||||
ASSERT_SYS(0, 0, unveil("f1/f2", "r"));
|
ASSERT_SYS(0, 0, unveil("f1/f2", "r"));
|
||||||
ASSERT_SYS(0, 0, unveil(0, 0));
|
ASSERT_SYS(0, 0, unveil(0, 0));
|
||||||
|
|
|
@ -40,24 +40,15 @@
|
||||||
#include "libc/x/x.h"
|
#include "libc/x/x.h"
|
||||||
#include "net/http/escape.h"
|
#include "net/http/escape.h"
|
||||||
|
|
||||||
STATIC_YOINK("zip_uri_support");
|
|
||||||
STATIC_YOINK("backtrace.com");
|
STATIC_YOINK("backtrace.com");
|
||||||
STATIC_YOINK("backtrace.com.dbg");
|
STATIC_YOINK("backtrace.com.dbg");
|
||||||
|
|
||||||
char testlib_enable_tmp_setup_teardown_once;
|
char testlib_enable_tmp_setup_teardown_once;
|
||||||
|
|
||||||
void Extract(const char *from, const char *to, int mode) {
|
|
||||||
ASSERT_SYS(0, 3, open(from, O_RDONLY));
|
|
||||||
ASSERT_SYS(0, 4, creat(to, mode));
|
|
||||||
ASSERT_NE(-1, _copyfd(3, 4, -1));
|
|
||||||
EXPECT_SYS(0, 0, close(4));
|
|
||||||
EXPECT_SYS(0, 0, close(3));
|
|
||||||
}
|
|
||||||
|
|
||||||
void SetUpOnce(void) {
|
void SetUpOnce(void) {
|
||||||
ASSERT_NE(-1, mkdir("bin", 0755));
|
ASSERT_NE(-1, mkdir("bin", 0755));
|
||||||
Extract("/zip/backtrace.com", "bin/backtrace.com", 0755);
|
testlib_extract("/zip/backtrace.com", "bin/backtrace.com", 0755);
|
||||||
Extract("/zip/backtrace.com.dbg", "bin/backtrace.com.dbg", 0755);
|
testlib_extract("/zip/backtrace.com.dbg", "bin/backtrace.com.dbg", 0755);
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool OutputHasSymbol(const char *output, const char *s) {
|
static bool OutputHasSymbol(const char *output, const char *s) {
|
||||||
|
|
|
@ -169,3 +169,18 @@ TEST(GetDosArgv, waqQuoting2) {
|
||||||
free(argv);
|
free(argv);
|
||||||
free(buf);
|
free(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(GetDosArgv, cmdToil) {
|
||||||
|
size_t max = 4;
|
||||||
|
size_t size = ARG_MAX / 2;
|
||||||
|
char *buf = malloc(size * sizeof(char));
|
||||||
|
char **argv = malloc(max * sizeof(char *));
|
||||||
|
EXPECT_EQ(3, GetDosArgv(u"cmd.exe /C \"echo hi >\"\"\"𝑓𝑜𝑜 bar.txt\"\"\"\"",
|
||||||
|
buf, size, argv, max));
|
||||||
|
EXPECT_STREQ("cmd.exe", argv[0]);
|
||||||
|
EXPECT_STREQ("/C", argv[1]);
|
||||||
|
EXPECT_STREQ("echo hi >\"𝑓𝑜𝑜 bar.txt\"", argv[2]);
|
||||||
|
EXPECT_EQ(NULL, argv[3]);
|
||||||
|
free(argv);
|
||||||
|
free(buf);
|
||||||
|
}
|
||||||
|
|
|
@ -16,13 +16,14 @@
|
||||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||||
|
#include "libc/errno.h"
|
||||||
#include "libc/intrin/bits.h"
|
#include "libc/intrin/bits.h"
|
||||||
#include "libc/log/check.h"
|
#include "libc/log/check.h"
|
||||||
#include "libc/math.h"
|
#include "libc/math.h"
|
||||||
#include "libc/nexgen32e/x86feature.h"
|
#include "libc/nexgen32e/x86feature.h"
|
||||||
|
#include "libc/runtime/runtime.h"
|
||||||
#include "libc/stdio/lcg.internal.h"
|
#include "libc/stdio/lcg.internal.h"
|
||||||
#include "libc/stdio/rand.h"
|
#include "libc/stdio/rand.h"
|
||||||
#include "libc/runtime/runtime.h"
|
|
||||||
#include "libc/stdio/stdio.h"
|
#include "libc/stdio/stdio.h"
|
||||||
#include "libc/sysv/consts/grnd.h"
|
#include "libc/sysv/consts/grnd.h"
|
||||||
#include "libc/testlib/ezbench.h"
|
#include "libc/testlib/ezbench.h"
|
||||||
|
@ -241,3 +242,7 @@ TEST(getrandom, sanityTest) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(getrandom, badflags_einval) {
|
||||||
|
ASSERT_SYS(EINVAL, -1, getrandom(0, 0, -1));
|
||||||
|
}
|
||||||
|
|
55
test/libc/stdio/system_test.c
Normal file
55
test/libc/stdio/system_test.c
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-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/mem/io.h"
|
||||||
|
#include "libc/paths.h"
|
||||||
|
#include "libc/runtime/gc.h"
|
||||||
|
#include "libc/runtime/runtime.h"
|
||||||
|
#include "libc/stdio/stdio.h"
|
||||||
|
#include "libc/sysv/consts/o.h"
|
||||||
|
#include "libc/testlib/ezbench.h"
|
||||||
|
#include "libc/testlib/testlib.h"
|
||||||
|
#include "libc/x/x.h"
|
||||||
|
|
||||||
|
char testlib_enable_tmp_setup_teardown;
|
||||||
|
|
||||||
|
TEST(system, testStdoutRedirect) {
|
||||||
|
int ws;
|
||||||
|
testlib_extract("/zip/echo.com", "echo.com", 0755);
|
||||||
|
ASSERT_TRUE(system(0));
|
||||||
|
ws = system("./echo.com hello >hello.txt");
|
||||||
|
ASSERT_TRUE(WIFEXITED(ws));
|
||||||
|
ASSERT_EQ(0, WEXITSTATUS(ws));
|
||||||
|
EXPECT_STREQ("hello\n", _gc(xslurp("hello.txt", 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(system, testStdoutRedirect_withSpacesInFilename) {
|
||||||
|
int ws;
|
||||||
|
testlib_extract("/zip/echo.com", "echo.com", 0755);
|
||||||
|
ASSERT_TRUE(system(0));
|
||||||
|
ws = system("./echo.com hello >\"hello there.txt\"");
|
||||||
|
ASSERT_TRUE(WIFEXITED(ws));
|
||||||
|
ASSERT_EQ(0, WEXITSTATUS(ws));
|
||||||
|
EXPECT_STREQ("hello\n", _gc(xslurp("hello there.txt", 0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
BENCH(system, bench) {
|
||||||
|
testlib_extract("/zip/echo.com", "echo.com", 0755);
|
||||||
|
EZBENCH2("system", donothing, system("./echo.com hi >/dev/null"));
|
||||||
|
}
|
|
@ -63,6 +63,17 @@ o/$(MODE)/test/libc/stdio/%.com.dbg: \
|
||||||
$(APE_NO_MODIFY_SELF)
|
$(APE_NO_MODIFY_SELF)
|
||||||
@$(APELINK)
|
@$(APELINK)
|
||||||
|
|
||||||
|
o/$(MODE)/test/libc/stdio/system_test.com.dbg: \
|
||||||
|
$(TEST_LIBC_STDIO_DEPS) \
|
||||||
|
o/$(MODE)/test/libc/stdio/system_test.o \
|
||||||
|
o/$(MODE)/test/libc/stdio/stdio.pkg \
|
||||||
|
o/$(MODE)/tool/build/echo.com.zip.o \
|
||||||
|
o/$(MODE)/tool/build/cocmd.com.zip.o \
|
||||||
|
$(LIBC_TESTMAIN) \
|
||||||
|
$(CRT) \
|
||||||
|
$(APE_NO_MODIFY_SELF)
|
||||||
|
@$(APELINK)
|
||||||
|
|
||||||
$(TEST_LIBC_STDIO_OBJS): private \
|
$(TEST_LIBC_STDIO_OBJS): private \
|
||||||
DEFAULT_CCFLAGS += \
|
DEFAULT_CCFLAGS += \
|
||||||
-fno-builtin
|
-fno-builtin
|
||||||
|
|
|
@ -111,6 +111,8 @@ o/$(MODE)/tool/build/chmod.zip.o \
|
||||||
o/$(MODE)/tool/build/cp.zip.o \
|
o/$(MODE)/tool/build/cp.zip.o \
|
||||||
o/$(MODE)/tool/build/mv.zip.o \
|
o/$(MODE)/tool/build/mv.zip.o \
|
||||||
o/$(MODE)/tool/build/echo.zip.o \
|
o/$(MODE)/tool/build/echo.zip.o \
|
||||||
|
o/$(MODE)/tool/build/echo.com.zip.o \
|
||||||
|
o/$(MODE)/tool/build/cocmd.com.zip.o \
|
||||||
o/$(MODE)/tool/build/gzip.zip.o \
|
o/$(MODE)/tool/build/gzip.zip.o \
|
||||||
o/$(MODE)/tool/build/printf.zip.o \
|
o/$(MODE)/tool/build/printf.zip.o \
|
||||||
o/$(MODE)/tool/build/dd.zip.o: private \
|
o/$(MODE)/tool/build/dd.zip.o: private \
|
||||||
|
|
|
@ -16,226 +16,8 @@
|
||||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||||
#include "libc/calls/calls.h"
|
#include "libc/stdio/cocmd.internal.h"
|
||||||
#include "libc/errno.h"
|
|
||||||
#include "libc/fmt/itoa.h"
|
|
||||||
#include "libc/macros.internal.h"
|
|
||||||
#include "libc/mem/mem.h"
|
|
||||||
#include "libc/runtime/runtime.h"
|
|
||||||
#include "libc/stdio/stdio.h"
|
|
||||||
#include "libc/str/errfun.h"
|
|
||||||
#include "libc/str/str.h"
|
|
||||||
#include "libc/sysv/consts/o.h"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @fileoverview Cosmopolitan Command Interpreter
|
|
||||||
*
|
|
||||||
* This is a lightweight command interpreter for GNU Make. It has just
|
|
||||||
* enough shell script language support to support our build config.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#define STATE_SHELL 0
|
|
||||||
#define STATE_STR 1
|
|
||||||
|
|
||||||
char *p;
|
|
||||||
char *q;
|
|
||||||
size_t n;
|
|
||||||
char *cmd;
|
|
||||||
char *args[8192];
|
|
||||||
const char *prog;
|
|
||||||
char argbuf[ARG_MAX];
|
|
||||||
bool unsupported[256];
|
|
||||||
|
|
||||||
void Write(const char *s, ...) {
|
|
||||||
va_list va;
|
|
||||||
va_start(va, s);
|
|
||||||
do {
|
|
||||||
write(2, s, strlen(s));
|
|
||||||
} while ((s = va_arg(va, const char *)));
|
|
||||||
va_end(va);
|
|
||||||
}
|
|
||||||
|
|
||||||
wontreturn void UnsupportedSyntax(unsigned char c) {
|
|
||||||
char cbuf[2];
|
|
||||||
char ibuf[13];
|
|
||||||
cbuf[0] = c;
|
|
||||||
cbuf[1] = 0;
|
|
||||||
FormatOctal32(ibuf, c, true);
|
|
||||||
Write(prog, ": unsupported shell syntax '", cbuf, "' (", ibuf, "): ", cmd,
|
|
||||||
"\n", 0);
|
|
||||||
exit(4);
|
|
||||||
}
|
|
||||||
|
|
||||||
wontreturn void SysExit(int rc, const char *call, const char *thing) {
|
|
||||||
int err;
|
|
||||||
char ibuf[12];
|
|
||||||
const char *estr;
|
|
||||||
err = errno;
|
|
||||||
FormatInt32(ibuf, err);
|
|
||||||
estr = strerdoc(err);
|
|
||||||
if (!estr) estr = "EUNKNOWN";
|
|
||||||
Write(thing, ": ", call, "() failed: ", estr, " (", ibuf, ")\n", 0);
|
|
||||||
exit(rc);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Open(const char *path, int fd, int flags) {
|
|
||||||
const char *err;
|
|
||||||
close(fd);
|
|
||||||
if (open(path, flags, 0644) == -1) {
|
|
||||||
SysExit(7, "open", path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
wontreturn void Exec(void) {
|
|
||||||
const char *s;
|
|
||||||
if (!n) {
|
|
||||||
Write(prog, ": error: too few args\n", 0);
|
|
||||||
exit(5);
|
|
||||||
}
|
|
||||||
execv(args[0], args);
|
|
||||||
SysExit(127, "execve", args[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Pipe(void) {
|
|
||||||
int pid, pfds[2];
|
|
||||||
if (pipe2(pfds, O_CLOEXEC)) {
|
|
||||||
SysExit(8, "pipe2", prog);
|
|
||||||
}
|
|
||||||
if ((pid = vfork()) == -1) {
|
|
||||||
SysExit(9, "vfork", prog);
|
|
||||||
}
|
|
||||||
if (!pid) {
|
|
||||||
dup2(pfds[1], 1);
|
|
||||||
Exec();
|
|
||||||
}
|
|
||||||
dup2(pfds[0], 0);
|
|
||||||
n = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
char *Tokenize(void) {
|
|
||||||
int t;
|
|
||||||
char *r;
|
|
||||||
while (*p == ' ' || *p == '\t' || *p == '\n' ||
|
|
||||||
(p[0] == '\\' && p[1] == '\n')) {
|
|
||||||
++p;
|
|
||||||
}
|
|
||||||
if (!*p) return 0;
|
|
||||||
t = STATE_SHELL;
|
|
||||||
for (r = q;; ++p) {
|
|
||||||
switch (t) {
|
|
||||||
|
|
||||||
case STATE_SHELL:
|
|
||||||
if (unsupported[*p & 255]) {
|
|
||||||
UnsupportedSyntax(*p);
|
|
||||||
}
|
|
||||||
if (!*p || *p == ' ' || *p == '\t') {
|
|
||||||
*q++ = 0;
|
|
||||||
return r;
|
|
||||||
} else if (*p == '\'') {
|
|
||||||
t = STATE_STR;
|
|
||||||
} else if (*p == '\\') {
|
|
||||||
if (!p[1]) UnsupportedSyntax(*p);
|
|
||||||
*q++ = *++p;
|
|
||||||
} else if (*p == '|') {
|
|
||||||
if (q > r) {
|
|
||||||
*q = 0;
|
|
||||||
return r;
|
|
||||||
} else {
|
|
||||||
Pipe();
|
|
||||||
++p;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
*q++ = *p;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case STATE_STR:
|
|
||||||
if (!*p) {
|
|
||||||
Write("cmd: error: unterminated string\n", 0);
|
|
||||||
exit(6);
|
|
||||||
}
|
|
||||||
if (*p == '\'') {
|
|
||||||
t = STATE_SHELL;
|
|
||||||
} else {
|
|
||||||
*q++ = *p;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
unreachable;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) {
|
||||||
char *arg;
|
return cocmd(argc, argv);
|
||||||
size_t i, j;
|
|
||||||
prog = argc > 0 ? argv[0] : "cocmd.com";
|
|
||||||
|
|
||||||
for (i = 1; i < 32; ++i) {
|
|
||||||
unsupported[i] = true;
|
|
||||||
}
|
|
||||||
unsupported['\t'] = false;
|
|
||||||
unsupported[0177] = true;
|
|
||||||
unsupported['~'] = true;
|
|
||||||
unsupported['`'] = true;
|
|
||||||
unsupported['#'] = true;
|
|
||||||
unsupported['*'] = true;
|
|
||||||
unsupported['('] = true;
|
|
||||||
unsupported[')'] = true;
|
|
||||||
unsupported['['] = true;
|
|
||||||
unsupported[']'] = true;
|
|
||||||
unsupported['{'] = true;
|
|
||||||
unsupported['}'] = true;
|
|
||||||
unsupported[';'] = true;
|
|
||||||
unsupported['"'] = true;
|
|
||||||
unsupported['?'] = true;
|
|
||||||
unsupported['!'] = true;
|
|
||||||
|
|
||||||
if (argc != 3) {
|
|
||||||
Write(prog, ": error: wrong number of args\n", 0);
|
|
||||||
exit(10);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(argv[1], "-c")) {
|
|
||||||
Write(prog, ": error: argv[1] should -c\n", 0);
|
|
||||||
exit(11);
|
|
||||||
}
|
|
||||||
|
|
||||||
p = cmd = argv[2];
|
|
||||||
if (strlen(cmd) >= ARG_MAX) {
|
|
||||||
Write(prog, ": error: cmd too long: ", cmd, "\n", 0);
|
|
||||||
exit(12);
|
|
||||||
}
|
|
||||||
|
|
||||||
n = 0;
|
|
||||||
q = argbuf;
|
|
||||||
while ((arg = Tokenize())) {
|
|
||||||
if (n + 1 < ARRAYLEN(args)) {
|
|
||||||
if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '&' &&
|
|
||||||
isdigit(arg[3])) {
|
|
||||||
dup2(arg[3] - '0', arg[0] - '0');
|
|
||||||
} else if (arg[0] == '>' && arg[1] == '&' && isdigit(arg[2])) {
|
|
||||||
dup2(arg[2] - '0', 1);
|
|
||||||
} else if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '>') {
|
|
||||||
Open(arg + 3, arg[0] - '0', O_WRONLY | O_CREAT | O_APPEND);
|
|
||||||
} else if (arg[0] == '>' && arg[1] == '>') {
|
|
||||||
Open(arg + 2, 1, O_WRONLY | O_CREAT | O_APPEND);
|
|
||||||
} else if (isdigit(arg[0]) && arg[1] == '>') {
|
|
||||||
Open(arg + 2, arg[0] - '0', O_WRONLY | O_CREAT | O_TRUNC);
|
|
||||||
} else if (arg[0] == '>') {
|
|
||||||
Open(arg + 1, 1, O_WRONLY | O_CREAT | O_TRUNC);
|
|
||||||
} else if (arg[0] == '<') {
|
|
||||||
Open(arg + 1, 0, O_RDONLY);
|
|
||||||
} else {
|
|
||||||
args[n++] = arg;
|
|
||||||
args[n] = 0;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write(prog, ": error: too many args\n", 0);
|
|
||||||
exit(13);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Exec();
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue