Skip to content

Commit

Permalink
Improve ZIP filesystem and change its prefix
Browse files Browse the repository at this point in the history
The ZIP filesystem has a breaking change. You now need to use /zip/ to
open() / opendir() / etc. assets within the ZIP structure of your APE
binary, instead of the previous convention of using zip: or zip! URIs.
This is needed because Python likes to use absolute paths, and having
ZIP paths encoded like URIs simply broke too many things.

Many more system calls have been updated to be able to operate on ZIP
files and file descriptors. In particular fcntl() and ioctl() since
Python would do things like ask if a ZIP file is a terminal and get
confused when the old implementation mistakenly said yes, because the
fastest way to guarantee native file descriptors is to dup(2). This
change also improves the async signal safety of zipos and ensures it
doesn't maintain any open file descriptors beyond that which the user
has opened.

This change makes a lot of progress towards adding magic numbers that
are specific to platforms other than Linux. The philosophy here is that,
if you use an operating system like FreeBSD, then you should be able to
take advantage of FreeBSD exclusive features, even if we don't polyfill
them on other platforms. For example, you can now open() a file with the
O_VERIFY flag. If your program runs on other platforms, then Cosmo will
automatically set O_VERIFY to zero. This lets you safely use it without
the need for #ifdef or ifstatements which detract from readability.

One of the blindspots of the ASAN memory hardening we use to offer Rust
like assurances has always been that memory passed to the kernel via
system calls (e.g. writev) can't be checked automatically since the
kernel wasn't built with MODE=asan. This change makes more progress
ensuring that each system call will verify the soundness of memory
before it's passed to the kernel. The code for doing these checks is
fast, particularly for buffers, where it can verify 64 bytes a cycle.

- Correct O_LOOP definition on NT
- Introduce program_executable_name
- Add ASAN guards to more system calls
- Improve termios compatibility with BSDs
- Fix bug in Windows auxiliary value encoding
- Add BSD and XNU specific errnos and open flags
- Add check to ensure build doesn't talk to internet
  • Loading branch information
jart committed Aug 22, 2021
1 parent 2730c66 commit 00611e9
Show file tree
Hide file tree
Showing 319 changed files with 4,404 additions and 2,585 deletions.
2 changes: 1 addition & 1 deletion examples/certapp.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ STATIC_YOINK("ssl_root_support");
#define DFL_FILENAME "cert.crt"
#define DFL_CA_FILE ""
#define DFL_CRL_FILE ""
#define DFL_CA_PATH "zip:usr/share/ssl/root"
#define DFL_CA_PATH "/zip/usr/share/ssl/root"
#define DFL_SERVER_NAME "localhost"
#define DFL_SERVER_PORT "4433"
#define DFL_DEBUG_LEVEL 0
Expand Down
3 changes: 2 additions & 1 deletion examples/examples.mk
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,13 @@ EXAMPLES_DIRECTDEPS = \
NET_HTTPS \
THIRD_PARTY_COMPILER_RT \
THIRD_PARTY_DLMALLOC \
THIRD_PARTY_QUICKJS \
THIRD_PARTY_GDTOA \
THIRD_PARTY_GETOPT \
THIRD_PARTY_LINENOISE \
THIRD_PARTY_LUA \
THIRD_PARTY_MBEDTLS \
THIRD_PARTY_MUSL \
THIRD_PARTY_QUICKJS \
THIRD_PARTY_STB \
THIRD_PARTY_XED \
THIRD_PARTY_ZLIB \
Expand Down
2 changes: 1 addition & 1 deletion examples/hellolua.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ int main(int argc, char *argv[]) {
luaL_openlibs(L);
lua_pushcfunction(L, NativeAdd);
lua_setglobal(L, "NativeAdd");
luaL_dofile(L, "zip:examples/hellolua.lua");
luaL_dofile(L, "/zip/examples/hellolua.lua");
lua_close(L);
return 0;
}
2 changes: 1 addition & 1 deletion examples/ispell.c
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ void SpellChecker(void) {
}

void LoadWords(void) {
CHECK_NOTNULL((f = fopen("zip:usr/share/dict/words", "r")));
CHECK_NOTNULL((f = fopen("/zip/usr/share/dict/words", "r")));
while (getline(&line, &linesize, f) > 0) {
critbit0_insert(&words, strtolower(chomp(line)));
}
Expand Down
2 changes: 1 addition & 1 deletion examples/nesemu1.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1818,7 +1818,7 @@ size_t FindZipGames(void) {
!memcmp((ZIP_CFILE_NAME(zipos->map + cf) +
ZIP_CFILE_NAMESIZE(zipos->map + cf) - 4),
".nes", 4) &&
(name = xasprintf("zip:%.*s", ZIP_CFILE_NAMESIZE(zipos->map + cf),
(name = xasprintf("/zip/%.*s", ZIP_CFILE_NAMESIZE(zipos->map + cf),
ZIP_CFILE_NAME(zipos->map + cf)))) {
APPEND(&zipgames_.p, &zipgames_.i, &zipgames_.n, &name);
}
Expand Down
98 changes: 98 additions & 0 deletions examples/time.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#if 0
/*─────────────────────────────────────────────────────────────────╗
│ To the extent possible under law, Justine Tunney has waived │
│ all copyright and related or neighboring rights to this file, │
│ as it is written in the following disclaimers: │
│ • http://unlicense.org/ │
│ • http://creativecommons.org/publicdomain/zero/1.0/ │
╚─────────────────────────────────────────────────────────────────*/
#endif
#include "libc/calls/calls.h"
#include "libc/calls/struct/timespec.h"
#include "libc/fmt/itoa.h"
#include "libc/log/log.h"
#include "libc/math.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/ex.h"
#include "libc/time/time.h"
#include "libc/x/x.h"

/**
* @fileoverview command for showing how long a command takes
*
* This offers the following improvements over the existing `time`
* command that's incorporated into most shells:
*
* - This will show microseconds if seconds < 1
* - This will launch APE binaries on systems with broken libc execv()
*/

#define WRITE(FD, STR) write(FD, STR, strlen(STR))

void OnChild(void *arg) {
char **argv = arg;
execv(argv[0], argv);
_exit(127);
}

long double GetTimeval(struct timeval t) {
return t.tv_sec + t.tv_usec * 1e-6l;
}

void PrintMetric(const char *name, long double d) {
char buf[256], *p = buf;
long mins, secs, mils, mics;
mins = d / 60;
secs = fmodl(d, 60);
mils = fmodl(d * 1000, 1000);
mics = fmodl(d * 1000000, 1000);
p = stpcpy(p, name), *p++ = '\t';
p += int64toarray_radix10(mins, p), *p++ = 'm';
p += int64toarray_radix10(secs, p), *p++ = '.';
*p++ = '0' + mils / 100;
*p++ = '0' + mils / 10 % 10;
*p++ = '0' + mils % 10;
if (!secs) {
*p++ = '0' + mics / 100;
*p++ = '0' + mics / 10 % 10;
*p++ = '0' + mics % 10;
}
*p++ = 's';
*p++ = '\n';
write(2, buf, p - buf);
}

int main(int argc, char *argv[]) {
int ws;
char *exepath;
struct rusage r;
long double real;
char exebuf[PATH_MAX];
if (argc >= 2) {
if ((exepath = commandv(argv[1], exebuf))) {
real = nowl();
argv[1] = exepath;
if ((ws = xvspawn(OnChild, argv + 1, &r)) != -1) {
PrintMetric("real", nowl() - real);
PrintMetric("user", GetTimeval(r.ru_utime));
PrintMetric("sys", GetTimeval(r.ru_stime));
if (WIFEXITED(ws)) {
return WEXITSTATUS(ws);
} else {
return 128 + WTERMSIG(ws);
}
} else {
perror("xvspawn");
return 127;
}
} else {
perror(argv[1]);
return 127;
}
} else {
WRITE(2, "Usage: ");
WRITE(2, argv[0]);
WRITE(2, " PROG [ARGS...]\n");
return EX_USAGE;
}
}
145 changes: 133 additions & 12 deletions examples/unbourne.c
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@
╚────────────────────────────────────────────────────────────────────────────│*/

#include "libc/alg/alg.h"
#include "libc/assert.h"
#include "libc/bits/safemacros.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/sigbits.h"
#include "libc/calls/struct/dirent.h"
Expand All @@ -125,13 +127,15 @@
#include "libc/fmt/fmt.h"
#include "libc/limits.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/alloca.h"
#include "libc/mem/mem.h"
#include "libc/paths.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/sysconf.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/fileno.h"
Expand All @@ -141,6 +145,7 @@
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/w.h"
#include "third_party/gdtoa/gdtoa.h"
#include "third_party/linenoise/linenoise.h"
#include "third_party/musl/passwd.h"

#define likely(expr) __builtin_expect(!!(expr), 1)
Expand Down Expand Up @@ -1030,6 +1035,7 @@ struct t_op {
│ cosmopolitan § the unbourne shell » bss ─╬─│┼
╚────────────────────────────────────────────────────────────────────────────│*/

static int inter;
static char **argptr; /* argument list for builtin commands */
static char **gargv;
static char **t_wp;
Expand Down Expand Up @@ -1827,7 +1833,7 @@ printfesque(3) static int fmtstr(char *outbuf, unsigned length, const char *fmt,
return ret > (int)length ? length : ret;
}

printfesque(2) static int xasprintf(char **sp, const char *fmt, ...) {
printfesque(2) static int Xasprintf(char **sp, const char *fmt, ...) {
va_list ap;
int ret;
va_start(ap, fmt);
Expand Down Expand Up @@ -5629,12 +5635,129 @@ static int pgetc2() {
return c;
}

static void AddUniqueCompletion(linenoiseCompletions *c, char *s) {
size_t i;
if (!s) return;
for (i = 0; i < c->len; ++i) {
if (!strcmp(s, c->cvec[i])) {
return;
}
}
c->cvec = realloc(c->cvec, ++c->len * sizeof(*c->cvec));
c->cvec[c->len - 1] = s;
}

static void CompleteCommand(const char *p, const char *q, const char *b, linenoiseCompletions *c) {
DIR *d;
size_t i;
struct dirent *e;
const char *x, *y, *path;
struct tblentry **pp, *cmdp;
for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
if (cmdp->cmdtype >= 0 && !strncmp(cmdp->cmdname, p, q - p)) {
AddUniqueCompletion(c, strdup(cmdp->cmdname));
}
}
}
for (i = 0; i < ARRAYLEN(kBuiltinCmds); ++i) {
if (!strncmp(kBuiltinCmds[i].name, p, q - p)) {
AddUniqueCompletion(c, strdup(kBuiltinCmds[i].name));
}
}
for (y = x = lookupvar("PATH"); *y; x = y + 1) {
if ((path = strndup(x, (y = strchrnul(x, ':')) - x))) {
if ((d = opendir(path))) {
while ((e = readdir(d))) {
if (e->d_type == DT_REG && !strncmp(e->d_name, p, q - p)) {
AddUniqueCompletion(c, strdup(e->d_name));
}
}
closedir(d);
}
free(path);
}
}
}

static void CompleteFilename(const char *p, const char *q, const char *b, linenoiseCompletions *c) {
DIR *d;
char *buf;
const char *g;
struct dirent *e;
if ((buf = malloc(512))) {
if ((g = memrchr(p, '/', q - p))) {
*(char *)mempcpy(buf, p, MIN(g - p, 511)) = 0;
p = ++g;
} else {
strcpy(buf, ".");
}
if ((d = opendir(buf))) {
while ((e = readdir(d))) {
if (!strcmp(e->d_name, ".")) continue;
if (!strcmp(e->d_name, "..")) continue;
if (!strncmp(e->d_name, p, q - p)) {
snprintf(buf, 512, "%.*s%s%s", p - b, b, e->d_name, e->d_type == DT_DIR ? "/" : "");
AddUniqueCompletion(c, strdup(buf));
}
}
closedir(d);
}
free(buf);
}
}

static void ShellCompletion(const char *p, linenoiseCompletions *c) {
bool slashed;
const char *q, *b;
struct tblentry **pp, *cmdp;
for (slashed = false, b = p, q = (p += strlen(p)); p > b; --p) {
if (p[-1] == '/' && p[-1] == '\\') slashed = true;
if (!isalnum(p[-1]) && (p[-1] != '.' && p[-1] != '_' && p[-1] != '-' && p[-1] != '+' &&
p[-1] != '[' && p[-1] != '/' && p[-1] != '\\')) {
break;
}
}
if (b == p && !slashed) {
CompleteCommand(p, q, b, c);
} else {
CompleteFilename(p, q, b, c);
}
}

static char *ShellHint(const char *p, int *color, int *bold) {
char *h = 0;
linenoiseCompletions c = {0};
ShellCompletion(p, &c);
if (c.len == 1) {
h = strdup(c.cvec[0] + strlen(p));
*bold = 2;
}
linenoiseFreeCompletions(&c);
return h;
}

static ssize_t preadfd(void) {
ssize_t nr;
char *buf = parsefile->buf;
char *p, *buf = parsefile->buf;
parsefile->nextc = buf;
retry:
nr = read(parsefile->fd, buf, IBUFSIZ - 1);
if (!parsefile->fd && isatty(0)) {
linenoiseSetFreeHintsCallback(free);
linenoiseSetHintsCallback(ShellHint);
linenoiseSetCompletionCallback(ShellCompletion);
if ((p = ezlinenoise(getprompt(NULL), "unbourne"))) {
nr = min(strlen(p), IBUFSIZ - 2);
memcpy(buf, p, nr);
buf[nr++] = '\n';
free(p);
} else {
write(1, "\n", 1);
nr = 0;
}
} else {
nr = read(parsefile->fd, buf, IBUFSIZ - 1);
}
if (nr < 0) {
if (errno == EINTR) goto retry;
if (parsefile->fd == 0 && errno == EAGAIN) {
Expand Down Expand Up @@ -7036,12 +7159,12 @@ static int readcmd(int argc, char **argv) {
if (prompt && isatty(0)) {
outstr(prompt, out2);
}
if (*(ap = argptr) == NULL) sh_error("arg count");
if (!*(ap = argptr)) sh_error("arg count");
status = 0;
STARTSTACKSTR(p);
goto start;
for (;;) {
switch (read(STDIN_FILENO, &c, 1)) {
switch (read(0, &c, 1)) {
case 1:
break;
default:
Expand All @@ -7051,7 +7174,7 @@ static int readcmd(int argc, char **argv) {
status = 1;
goto out;
}
if (c == '\0') continue;
if (!c) continue;
if (newloc >= startloc) {
if (c == '\n') goto resetbs;
goto put;
Expand Down Expand Up @@ -8820,7 +8943,7 @@ static void setprompt(int which) {
int show;
needprompt = 0;
whichprompt = which;
show = 1;
show = 0;
if (show) {
pushstackmark(&smark, stackblocksize());
outstr(getprompt(NULL), out2);
Expand Down Expand Up @@ -9377,13 +9500,13 @@ static void sigblockall(sigset_t *oldmask) {
int ret; \
switch ((char *)param - (char *)array) { \
default: \
ret = xasprintf(sp, f, array[0], array[1], func); \
ret = Xasprintf(sp, f, array[0], array[1], func); \
break; \
case sizeof(*param): \
ret = xasprintf(sp, f, array[0], func); \
ret = Xasprintf(sp, f, array[0], func); \
break; \
case 0: \
ret = xasprintf(sp, f, func); \
ret = Xasprintf(sp, f, func); \
break; \
} \
ret; \
Expand Down Expand Up @@ -10788,8 +10911,6 @@ static int exitcmd(int argc, char **argv) {
* is used to figure out how far we had gotten.
*/
int main(int argc, char **argv) {
showcrashreports();
unsetenv("PS1");
char *shinit;
volatile int state;
struct jmploc jmploc;
Expand Down
Loading

0 comments on commit 00611e9

Please sign in to comment.