path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/examples/gettimeofday.c
#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/assert.h" #include "libc/calls/struct/timeval.h" #include "libc/stdio/stdio.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "net/http/http.h" int main(int argc, char *argv[]) { int rc; int64_t t; char p[30]; struct tm tm; struct timeval tv; rc = gettimeofday(&tv, 0); assert(!rc); t = tv.tv_sec; gmtime_r(&t, &tm); FormatHttpDateTime(p, &tm); printf("%s\n", p); }
1,211
30
jart/cosmopolitan
false
cosmopolitan/examples/exec.c
#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/sigset.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/sig.h" STATIC_YOINK("strerror"); int main(int argc, char *argv[]) { sigset_t ss; if (argc < 2) { fputs("USAGE: EXEC.COM PROG [ARGV₀...]\n", stderr); return 1; } // block arbitrary signal so __printargs() looks cooler sigemptyset(&ss); sigaddset(&ss, SIGPWR); sigprocmask(SIG_BLOCK, &ss, 0); execv(argv[1], argv + 2); return 127; }
1,306
33
jart/cosmopolitan
false
cosmopolitan/examples/ctrlc.c
#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/sigaction.h" #include "libc/errno.h" #include "libc/log/check.h" #include "libc/log/color.internal.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/nt/thread.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/sig.h" volatile bool gotctrlc; void GotCtrlC(int sig) { gotctrlc = true; } int main(int argc, char *argv[]) { ssize_t rc; size_t got, wrote; unsigned char buf[512]; struct sigaction saint = {.sa_handler = GotCtrlC}; fprintf(stderr, "This echos stdio until Ctrl+C is pressed.\n"); CHECK_NE(-1, sigaction(SIGINT, &saint, NULL)); for (;;) { rc = read(0, buf, 512); if (rc != -1) { got = rc; } else { CHECK_EQ(EINTR, errno); break; } if (!got) break; rc = write(1, buf, got); if (rc != -1) { wrote = rc; } else { CHECK_EQ(EINTR, errno); break; } CHECK_EQ(got, wrote); } if (gotctrlc) { fprintf(stderr, "Got Ctrl+C\n"); } else { fprintf(stderr, "Got EOF\n"); } return 0; }
1,994
63
jart/cosmopolitan
false
cosmopolitan/examples/cosh.c
#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/dirent.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/timespec.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/log/appendresourcereport.internal.h" #include "libc/log/internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/append.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/dt.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "third_party/linenoise/linenoise.h" /** * @fileoverview Cosmopolitan Shell * * This doesn't have script language features like UNBOURNE.COM but it * works on Windows and, unlike CMD.EXE, has CTRL-P, CTRL-R, and other * GNU Emacs / Readline keyboard shortcuts. * * One day we'll have UNBOURNE.COM working on Windows but the code isn't * very maintainable sadly. */ volatile int gotint; static void OnInterrupt(int sig) { gotint = sig; } 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 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; 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; } } CompleteFilename(p, q, b, c); } static char *ShellHint(const char *p, const char **ansi1, const char **ansi2) { char *h = 0; linenoiseCompletions c = {0}; ShellCompletion(p, &c); if (c.len == 1) { h = strdup(c.cvec[0] + strlen(p)); } linenoiseFreeCompletions(&c); return h; } static char *MakePrompt(char *p) { char *s, buf[256]; if (!gethostname(buf, sizeof(buf))) { p = stpcpy(p, "\e[95m"); if ((s = getenv("USER"))) { p = stpcpy(p, s); *p++ = '@'; } p = stpcpy(p, buf); *p++ = ':'; } p = stpcpy(p, "\e[96m"); if ((s = getcwd(buf, sizeof(buf)))) { p = stpcpy(p, s); } return stpcpy(p, "\e[0m>: "); } int main(int argc, char *argv[]) { bool timeit; int64_t nanos; struct rusage ru; struct timespec ts1, ts2; char *prog, path[PATH_MAX]; sigset_t chldmask, savemask; int stdoutflags, stderrflags; const char *stdoutpath, *stderrpath; int n, rc, ws, pid, child, killcount; struct sigaction sa, saveint, savequit; char *p, *line, **args, *arg, *start, *state, prompt[1024]; linenoiseSetFreeHintsCallback(free); linenoiseSetHintsCallback(ShellHint); linenoiseSetCompletionCallback(ShellCompletion); MakePrompt(prompt); while ((line = linenoiseWithHistory(prompt, "cmd"))) { n = 0; start = line; if (_startswith(start, "time ")) { timeit = true; start += 5; } else { timeit = false; } stdoutpath = 0; stderrpath = 0; stdoutflags = 0; stderrflags = 0; args = xcalloc(1, sizeof(*args)); while ((arg = strtok_r(start, " \t\r\n", &state))) { // cmd >>stdout.txt if (arg[0] == '>' && arg[1] == '>') { stdoutflags = O_WRONLY | O_APPEND | O_CREAT; stdoutpath = arg + 2; } else if (arg[0] == '>') { // cmd >stdout.txt stdoutflags = O_WRONLY | O_CREAT | O_TRUNC; stdoutpath = arg + 1; } else if (arg[0] == '2' && arg[1] == '>' && arg[2] == '>') { // cmd 2>>stderr.txt stderrflags = O_WRONLY | O_APPEND | O_CREAT; stderrpath = arg + 3; } else if (arg[0] == '2' && arg[1] == '>') { // cmd 2>stderr.txt stderrflags = O_WRONLY | O_CREAT | O_TRUNC; stderrpath = arg + 2; } else { // arg args = xrealloc(args, (++n + 1) * sizeof(*args)); args[n - 1] = arg; args[n - 0] = 0; } start = 0; } if (n > 0) { if ((prog = commandv(args[0], path, sizeof(path)))) { // let keyboard interrupts kill child and not shell gotint = 0; killcount = 0; sa.sa_flags = 0; sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sigaction(SIGQUIT, &sa, &savequit); sa.sa_handler = OnInterrupt; sigaction(SIGINT, &sa, &saveint); sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); sigprocmask(SIG_BLOCK, &chldmask, &savemask); // record timestamp if (timeit) { clock_gettime(CLOCK_REALTIME, &ts1); } // launch process if (!(child = vfork())) { if (stdoutpath) { close(1); open(stdoutpath, stdoutflags, 0644); } if (stderrpath) { close(2); open(stderrpath, stderrflags, 0644); } sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); execv(prog, args); _Exit(127); } // wait for process for (;;) { if (gotint) { switch (killcount) { case 0: // ctrl-c // we do nothing // terminals broadcast sigint to process group rc = 0; break; case 1: // ctrl-c ctrl-c // we try sending sigterm rc = kill(child, SIGTERM); break; default: // ctrl-c ctrl-c ctrl-c ... // we use kill -9 as our last resort rc = kill(child, SIGKILL); break; } if (rc == -1) { fprintf(stderr, "kill failed: %m\n"); exit(1); } ++killcount; gotint = 0; } rc = wait4(0, &ws, 0, &ru); if (rc != -1) { break; } else if (errno == EINTR) { errno = 0; } else { fprintf(stderr, "wait failed: %m\n"); exit(1); } } // print resource consumption for `time` pseudocommand if (timeit) { clock_gettime(CLOCK_REALTIME, &ts2); if (ts2.tv_sec == ts1.tv_sec) { nanos = ts2.tv_nsec - ts1.tv_nsec; } else { nanos = (ts2.tv_sec - ts1.tv_sec) * 1000000000LL; nanos += 1000000000LL - ts1.tv_nsec; nanos += ts2.tv_nsec; } printf("took %,ldµs wall time\n", nanos / 1000); p = 0; AppendResourceReport(&p, &ru, "\n"); fputs(p, stdout); free(p); } // update prompt to reflect exit status p = prompt; if (WIFEXITED(ws)) { if (WEXITSTATUS(ws)) { if (!__nocolor) p = stpcpy(p, "\e[1;31m"); p = stpcpy(p, "rc="); p = FormatInt32(p, WEXITSTATUS(ws)); if (128 < WEXITSTATUS(ws) && WEXITSTATUS(ws) <= 128 + 32) { *p++ = ' '; p = stpcpy(p, strsignal(WEXITSTATUS(ws) - 128)); } if (!__nocolor) p = stpcpy(p, "\e[0m"); *p++ = ' '; } } else { if (!__nocolor) p = stpcpy(p, "\e[1;31m"); p = stpcpy(p, strsignal(WTERMSIG(ws))); if (!__nocolor) p = stpcpy(p, "\e[0m"); *p++ = ' '; } MakePrompt(p); sigprocmask(SIG_SETMASK, &savemask, 0); sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); } else { fprintf(stderr, "%s: %s: command not found\n", argv[0], args[0]); } } free(line); free(args); } }
9,763
320
jart/cosmopolitan
false
cosmopolitan/examples/vga.c
#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/termios.h" #include "libc/isystem/unistd.h" #include "libc/math.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/termios.h" #ifdef __x86_64__ /** * @fileoverview Bare Metal VGA TTY demo. * * This program can boot as an operating system. Try it out: * * make -j8 o//examples/vga.com * qemu-system-x86_64 -hda o//examples/vga.com -serial stdio * * Please note that, by default, APE binaries only use the serial port * for stdio. To get the VGA console as an added bonus: * * STATIC_YOINK("vga_console"); * * Should be added to the top of your main() program source file. */ STATIC_YOINK("vga_console"); int main(int argc, char *argv[]) { volatile long double x = -.5; volatile long double y = 1.5; struct termios tio; char buf[16]; ssize_t res; if (tcgetattr(0, &tio) != -1) { tio.c_lflag &= ~(ECHO | ICANON); tcsetattr(0, TCSANOW, &tio); } write(1, "\e[5n", 4); res = read(0, buf, 4); if (res != 4 || memcmp(buf, "\e[0n", 4) != 0) { printf("res = %d?\n", res); return -1; } printf("\e[92;44mHello World!\e[0m %.19Lg\n", atan2l(x, y)); // read/print loop so machine doesn't reset on metal for (;;) { if ((res = readansi(0, buf, 16)) > 0) { printf("got \e[97m%`'.*s\e[0m\r\n", res, buf); } } } #endif /* __x86_64__ */
2,179
65
jart/cosmopolitan
false
cosmopolitan/examples/forkexecwait.c
#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/stdio/stdio.h" int main(int argc, char *argv[]) { int pid; volatile void *p; if (argc < 3) { fputs("USAGE: FORKEXECWAIT.COM PROG ARGV₀ [ARGV₁...]\n", stderr); return 1; } if (!fork()) { execv(argv[1], argv + 2); return 127; } wait(0); }
1,101
26
jart/cosmopolitan
false
cosmopolitan/examples/vga2.c
#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/termios.h" #include "libc/isystem/unistd.h" #include "libc/math.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/termios.h" #ifdef __x86_64__ /** * @fileoverview Demo of program crash reporting with Bare Metal VGA TTY. * * make -j8 o//examples/vga2.com * qemu-system-x86_64 -hda o//examples/vga2.com -serial stdio */ STATIC_YOINK("vga_console"); STATIC_YOINK("_idt"); STATIC_YOINK("EfiMain"); int main(int argc, char *argv[]) { int i; volatile int x = 1; volatile int y = 2; printf("argc = %d\n", argc); for (i = 0; i < argc; ++i) { printf("argv[%d] = \"%s\"\n", i, argv[i]); } printf("\e[92;44mHello World!\e[0m %d\n", 1 / (x + y - 3)); for (;;) ; } #endif /* __x86_64__ */
1,589
45
jart/cosmopolitan
false
cosmopolitan/examples/compress.c
#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/assert.h" #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/log/check.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" #include "third_party/zlib/zlib.h" #define CHUNK 32768 #define USAGE \ " <STDIN >STDOUT\n\ \n\ SYNOPSIS\n\ \n\ Zlib Compressor\n\ \n\ FLAGS\n\ \n\ -?\n\ -h help\n\ -0 disable compression\n\ -1 fastest compression\n\ -4 coolest compression\n\ -9 maximum compression\n\ -F fixed strategy (advanced)\n\ -L filtered strategy (advanced)\n\ -R run length strategy (advanced)\n\ -H huffman only strategy (advanced)\n\ \n" // clang-format off // make -j8 o//examples && dd if=/dev/urandom count=100 | tee a | o//examples/compress.com | o//examples/decompress.com >b && sha1sum a b /* #!/bin/bash # data file is o/dbg/third_party/python/python.com # level 1 348739 compress 22.8 MB/s decompress 444 MB/s # level 2 347549 compress 37.8 MB/s decompress 457 MB/s # level 3 346902 compress 33.3 MB/s decompress 463 MB/s # level 4 345671 compress 29.3 MB/s decompress 467 MB/s # level 5 344392 compress 22.4 MB/s decompress 506 MB/s # level 6 342105 compress 10.9 MB/s decompress 516 MB/s # level 7 342046 compress 7.9 MB/s decompress 515 MB/s # level 8 342009 compress 5.8 MB/s decompress 518 MB/s # level 9 342001 compress 5.7 MB/s decompress 524 MB/s # level F 1 362426 compress 48.2 MB/s decompress 488 MB/s # level F 2 360875 compress 42.7 MB/s decompress 484 MB/s # level F 3 359992 compress 37.1 MB/s decompress 499 MB/s # level F 4 358460 compress 32.9 MB/s decompress 503 MB/s # level F 5 356431 compress 24.0 MB/s decompress 547 MB/s # level F 6 352274 compress 11.6 MB/s decompress 558 MB/s # level F 7 352155 compress 8.7 MB/s decompress 554 MB/s # level F 8 352065 compress 6.3 MB/s decompress 554 MB/s # level F 9 352051 compress 6.2 MB/s decompress 556 MB/s # level L 1 348739 compress 41.1 MB/s decompress 446 MB/s # level L 2 347549 compress 37.4 MB/s decompress 443 MB/s # level L 3 346902 compress 32.3 MB/s decompress 462 MB/s # level L 4 351932 compress 28.8 MB/s decompress 511 MB/s # level L 5 351384 compress 23.6 MB/s decompress 520 MB/s # level L 6 351328 compress 12.1 MB/s decompress 522 MB/s # level L 7 351230 compress 7.3 MB/s decompress 518 MB/s # level L 8 351192 compress 5.7 MB/s decompress 522 MB/s # level L 9 351182 compress 6.5 MB/s decompress 519 MB/s # level R 1 388209 compress 83.1 MB/s decompress 371 MB/s # level R 2 388209 compress 82.3 MB/s decompress 362 MB/s # level R 3 388209 compress 81.8 MB/s decompress 361 MB/s # level R 4 388209 compress 81.7 MB/s decompress 364 MB/s # level R 5 388209 compress 81.7 MB/s decompress 363 MB/s # level R 6 388209 compress 80.1 MB/s decompress 359 MB/s # level R 7 388209 compress 80.3 MB/s decompress 354 MB/s # level R 8 388209 compress 80.3 MB/s decompress 363 MB/s # level R 9 388209 compress 81.3 MB/s decompress 364 MB/s # level H 1 390207 compress 87.6 MB/s decompress 371 MB/s # level H 2 390207 compress 87.5 MB/s decompress 372 MB/s # level H 3 390207 compress 85.5 MB/s decompress 364 MB/s # level H 4 390207 compress 87.3 MB/s decompress 375 MB/s # level H 5 390207 compress 89.0 MB/s decompress 373 MB/s # level H 6 390207 compress 87.3 MB/s decompress 372 MB/s # level H 7 390207 compress 87.0 MB/s decompress 368 MB/s # level H 8 390207 compress 86.2 MB/s decompress 367 MB/s # level H 9 390207 compress 86.9 MB/s decompress 369 MB/s m= make -j8 MODE=$m o/$m/examples || exit for strategy in ' ' F L R H; do for level in $(seq 1 9); do o/$m/examples/compress.com -$level$strategy <o/dbg/third_party/python/python.com | dd count=10000 2>/tmp/info >/tmp/comp compspeed=$(grep -Po '[.\d]+ \w+/s' /tmp/info) o/$m/examples/decompress.com </tmp/comp | dd count=10000 2>/tmp/info >/dev/null decompspeed=$(grep -Po '[.\d]+ \w+/s' /tmp/info) size=$(o/$m/examples/compress.com -$level$strategy <o/$m/examples/compress.com | wc -c) echo "level $strategy $level $size compress $compspeed decompress $decompspeed" done done */ // clang-format on int level; int strategy; wontreturn void PrintUsage(int rc, FILE *f) { fputs("usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void GetOpts(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "?hFLRH0123456789")) != -1) { switch (opt) { case 'F': strategy = Z_FIXED; break; case 'L': strategy = Z_FILTERED; break; case 'R': strategy = Z_RLE; break; case 'H': strategy = Z_HUFFMAN_ONLY; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = opt - '0'; break; case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } int compressor(int infd, int outfd) { z_stream zs; int rc, flush; unsigned have; unsigned char *inbuf; unsigned char *outbuf; inbuf = gc(valloc(CHUNK)); outbuf = gc(valloc(CHUNK)); zs.zalloc = 0; zs.zfree = 0; zs.opaque = 0; rc = deflateInit2(&zs, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, strategy); if (rc != Z_OK) return rc; do { rc = read(infd, inbuf, CHUNK); if (rc == -1) { deflateEnd(&zs); return Z_ERRNO; } zs.avail_in = rc; flush = !rc ? Z_FINISH : Z_SYNC_FLUSH; zs.next_in = inbuf; do { zs.avail_out = CHUNK; zs.next_out = outbuf; rc = deflate(&zs, flush); assert(rc != Z_STREAM_ERROR); have = CHUNK - zs.avail_out; if (write(outfd, outbuf, have) != have) { deflateEnd(&zs); return Z_ERRNO; } } while (!zs.avail_out); assert(!zs.avail_in); } while (flush != Z_FINISH); assert(rc == Z_STREAM_END); deflateEnd(&zs); return Z_OK; } const char *zerr(int rc) { switch (rc) { case Z_ERRNO: return strerror(errno); case Z_STREAM_ERROR: return "invalid compression level"; case Z_DATA_ERROR: return "invalid or incomplete deflate data"; case Z_MEM_ERROR: return "out of memory"; case Z_VERSION_ERROR: return "zlib version mismatch!"; default: unreachable; } } int main(int argc, char *argv[]) { int rc; level = Z_DEFAULT_COMPRESSION; strategy = Z_DEFAULT_STRATEGY; GetOpts(argc, argv); rc = compressor(0, 1); if (rc == Z_OK) { return 0; } else { fprintf(stderr, "error: compressor: %s\n", zerr(rc)); return 1; } }
7,629
230
jart/cosmopolitan
false
cosmopolitan/examples/auto-launch-gdb-on-crash.c
#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/log/log.h" /** * Automatically launches GDB Debugger TUI during crash. * * Run the following inside a terminal: * * sudo apt install gdb * make -j12 o//examples/auto-launch-gdb-on-crash.com * o//examples/auto-launch-gdb-on-crash.com * * Backtrace is logged instead if run outside interactive terminal. We * also don't auto-launch GDB on non-Linux since the development tools * on other platforms generally can't be relied upon to correctly debug * binaries built with a Linux toolchain. Environmental factors such as * GDB, MAKEFLAGS, ADDR2LINE, TERM, and isatty(STDERR_FILENO) should * also be taken into consideration: * * $ export GDB=eoatuhshtuone * $ o//examples/auto-launch-gdb-on-crash.com * error: Uncaught SIGTRAP * etc. etc. * * @see https://www.felixcloutier.com/x86/intn:into:int3:int1 * @see https://en.wikipedia.org/wiki/INT_(x86_instruction)#INT3 * @see examples and reference material on using the asm() keyword * - libc/nexgen32e/bsf.h * - libc/nexgen32e/tzcnt.h * - libc/nexgen32e/cpuid4.internal.h * - https://gist.github.com/jart/fe8d104ef93149b5ba9b72912820282c */ int main(int argc, char *argv[]) { ShowCrashReports(); __builtin_trap(); return 0; }
2,050
47
jart/cosmopolitan
false
cosmopolitan/examples/gui.c
#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/dce.h" #include "libc/nexgen32e/nt2sysv.h" #include "libc/nt/dll.h" #include "libc/nt/enum/cw.h" #include "libc/nt/enum/mb.h" #include "libc/nt/enum/sw.h" #include "libc/nt/enum/wm.h" #include "libc/nt/enum/ws.h" #include "libc/nt/events.h" #include "libc/nt/messagebox.h" #include "libc/nt/struct/msg.h" #include "libc/nt/struct/wndclass.h" #include "libc/nt/windows.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview GUI Example * * Cosmopolitan has had a razor sharp focus on making sockets and stdio * work well across platforms. When you call a function like read(), it * will just work on platforms like Windows too. In order to do that we * need to support the WIN32 API, which you can use, but please note it * isn't polyfilled on other platforms in the same way as POSIX APIs. */ static const char16_t kClassName[] = u"cosmopolitan"; static int64_t WindowProc(int64_t hwnd, uint32_t uMsg, uint64_t wParam, int64_t lParam) { switch (uMsg) { case kNtWmDestroy: PostQuitMessage(0); return 0; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } } static void Gui(void) { int64_t h; struct NtMsg msg; struct NtWndClass wc; memset(&wc, 0, sizeof(wc)); wc.lpfnWndProc = NT2SYSV(WindowProc); wc.hInstance = GetModuleHandle(NULL); wc.lpszClassName = kClassName; RegisterClass(&wc); h = CreateWindowEx(0, kClassName, u"Hello Cosmopolitan", kNtWsOverlappedwindow, kNtCwUsedefault, kNtCwUsedefault, kNtCwUsedefault, kNtCwUsedefault, 0, 0, wc.hInstance, 0); ShowWindow(h, kNtSwNormal); /* * NOTE: Cosmopolitan linker script is hard-coded to change the * subsystem from CUI to GUI when GetMessage() is linked. */ while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } int main(int argc, char *argv[]) { if (!IsWindows()) { fputs("Sorry! This GUI demo only runs on Windows\n", stderr); fputs("https://github.com/jart/cosmopolitan/issues/57\n", stderr); return 1; } Gui(); }
2,914
80
jart/cosmopolitan
false
cosmopolitan/examples/printprimes.c
#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/fmt/itoa.h" #include "libc/math.h" #include "libc/stdio/stdio.h" int main(int argc, char *argv[]) { char buf[32]; bool isprime; long i, j, k, n, m; k = 0; n = pow(2, 32); printf("2\n"); for (i = 3; i < n; ++i) { isprime = true; for (m = sqrt(i) + 1, j = 2; j < m; ++j) { if (i % j == 0) { isprime = false; break; } } if (isprime) { FormatInt64(buf, i); fputs(buf, stdout); fputc('\n', stdout); if (k++ % 100 == 0) { fprintf(stderr, "\r%20d", i); } } } return 0; }
1,368
40
jart/cosmopolitan
false
cosmopolitan/examples/nomodifyself.c
#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 "ape/sections.internal.h" #include "libc/dce.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" /** * @fileoverview Non-Self-Modifying APE Binary Demo * * See examples/examples.mk for the build config, which uses the * alternative APE runtime. */ int main(int argc, char *argv[]) { if (__executable_start[0] == 'M' && __executable_start[1] == 'Z') { printf("success: %s spawned without needing to modify its " "executable header", argv[0]); if (!IsWindows()) { printf(", thanks to APE loader!\n"); } else { printf(", because you ran it on Windows :P\n"); } return 0; } else { printf("error: %s doesn't have an MZ file header!\n", argv[0]); return 1; } }
1,538
38
jart/cosmopolitan
false
cosmopolitan/examples/gc.c
#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/mem/gc.h" #include "libc/mem/mem.h" #include "libc/str/str.h" int main(int argc, char *argv[]) { char *p = _gc(malloc(64)); strcpy(p, "this memory is free'd when main() returns"); }
986
18
jart/cosmopolitan
false
cosmopolitan/examples/hello.c
#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/stdio/stdio.h" STATIC_YOINK("mmap"); // TODO: fix bandaid for MODE=asan int main() { printf("%s\n", "hello world"); return 0; }
964
19
jart/cosmopolitan
false
cosmopolitan/examples/nesemu1.cc
/* NESEMU1 :: EMULATOR FOR THE NINTENDO ENTERTAINMENT SYSTEM (R) ARCHITECTURE */ /* WRITTEN BY AND COPYRIGHT 2011 JOEL YLILUOMA ── SEE: http://iki.fi/bisqwit/ */ /* PORTED TO TELETYPEWRITERS IN YEAR 2020 BY JUSTINE ALEXANDRA ROBERTS TUNNEY */ /* TRADEMARKS ARE OWNED BY THEIR RESPECTIVE OWNERS LAWYERCATS LUV TAUTOLOGIES */ /* https://bisqwit.iki.fi/jutut/kuvat/programming_examples/nesemu1/nesemu1.cc */ #include "dsp/core/core.h" #include "dsp/core/half.h" #include "dsp/core/illumination.h" #include "dsp/scale/scale.h" #include "dsp/tty/itoa8.h" #include "dsp/tty/quant.h" #include "dsp/tty/tty.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/winsize.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/inttypes.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" #include "libc/x/xasprintf.h" #include "libc/x/xsigaction.h" #include "libc/zip.h" #include "libc/zipos/zipos.internal.h" #include "third_party/getopt/getopt.h" #include "third_party/libcxx/vector" #include "tool/viz/lib/knobs.h" STATIC_YOINK("zipos"); #define USAGE \ " [ROM] [FMV]\n\ \n\ SYNOPSIS\n\ \n\ Emulates NES Video Games in Terminal\n\ \n\ FLAGS\n\ \n\ -A ansi color mode\n\ -t normal color mode\n\ -x xterm256 color mode\n\ -4 unicode character set\n\ -3 ibm cp437 character set\n\ -1 ntsc crt artifact emulation\n\ -h\n\ -? shows this information\n\ \n\ KEYBOARD\n\ \n\ We support Emacs / Mac OS X control key bindings. We also support\n\ Vim. We support arrow keys. We also support WASD QWERTY & Dvorak.\n\ The 'A' button is mapped to SPACE. The 'B' button is mapped to b.\n\ Lastly TAB is SELECT and ENTER is START.\n\ \n\ Teletypewriters are naturally limited in terms of keyboard input.\n\ They don't exactly have n-key rollover. More like 1-key rollover.\n\ \n\ Try tapping rather than holding keys. You can tune the activation\n\ duration by pressing '8' and '9'. You can also adjust the keyboard\n\ repeat delay in your operating system settings to make it shorter.\n\ \n\ Ideally we should send patches to all the terms that introduces a\n\ new ANSI escape sequences for key down / key up events. It'd also\n\ be great to have inband audio with terminals too.\n\ \n\ GRAPHICS\n\ \n\ The '1' key toggles CRT monitor artifact emulation, which can make\n\ some games like Zelda II look better. The '3' and '4' keys toggle\n\ the selection of UNICODE block characters.\n\ \n\ ZIP\n\ \n\ This executable is also a ZIP archive. If you change the extension\n\ then you can modify its inner structure, to place roms inside it.\n\ \n\ AUTHORS\n\ \n\ Joel Yliluoma <http://iki.fi/bisqwit/>\n\ Justine Tunney <jtunney@gmail.com/>\n\ \n\ \n" #define DYN 240 #define DXN 256 #define FPS 60.0988 #define HZ 1789773 #define GAMMA 2.2 #define CTRL(C) ((C) ^ 0100) #define ALT(C) ((033 << 010) | (C)) typedef int8_t s8; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; static const struct itimerval kNesFps = { {0, 1. / FPS * 1e6}, {0, 1. / FPS * 1e6}, }; struct Frame { char *p, *w, *mem; }; struct Action { int code; int wait; }; struct Audio { size_t i; int16_t p[FRAMESIZE]; }; struct Status { int wait; char text[80]; }; struct ZipGames { size_t i, n; char** p; }; static int frame_; static int drain_; static int playfd_; static int playpid_; static bool exited_; static bool timeout_; static bool resized_; static size_t vtsize_; static bool artifacts_; static long tyn_, txn_; static struct Frame vf_[2]; static struct Audio audio_; static const char* inputfn_; static struct Status status_; static struct TtyRgb* ttyrgb_; static unsigned char *R, *G, *B; static struct ZipGames zipgames_; static struct Action arrow_, button_; static struct SamplingSolution* asx_; static struct SamplingSolution* ssy_; static struct SamplingSolution* ssx_; static unsigned char pixels_[3][DYN][DXN]; static unsigned char palette_[3][64][512][3]; static int joy_current_[2], joy_next_[2], joypos_[2]; static int keyframes_ = 10; static enum TtyBlocksSelection blocks_ = kTtyBlocksUnicode; static enum TtyQuantizationAlgorithm quant_ = kTtyQuantTrue; static int Clamp(int v) { return MAX(0, MIN(255, v)); } static double FixGamma(double x) { return tv2pcgamma(x, GAMMA); } void InitPalette(void) { // The input value is a NES color index (with de-emphasis bits). // See http://wiki.nesdev.com/w/index.php/NTSC_video for magic numbers // We need RGB values. To produce a RGB value, we emulate the NTSC circuitry. double A[3] = {-1.109, -.275, .947}; double B[3] = {1.709, -.636, .624}; double rgbc[3], lightbulb[3][3], rgbd65[3], sc[2]; int o, u, r, c, b, p, y, i, l, q, e, p0, p1, pixel; signed char volt[] = "\372\273\32\305\35\311I\330D\357\175\13D!}N"; GetChromaticAdaptationMatrix(lightbulb, kIlluminantC, kIlluminantD65); for (o = 0; o < 3; ++o) { for (p0 = 0; p0 < 512; ++p0) { for (p1 = 0; p1 < 64; ++p1) { for (u = 0; u < 3; ++u) { // Calculate the luma and chroma by emulating the relevant circuits: y = i = q = 0; // 12 samples of NTSC signal constitute a color. for (p = 0; p < 12; ++p) { // Sample either the previous or the current pixel. r = (p + o * 4) % 12; // Decode the color index. if (artifacts_) { pixel = r < 8 - u * 2 ? p0 : p1; } else { pixel = p0; } c = pixel % 16; l = c < 0xE ? pixel / 4 & 12 : 4; e = p0 / 64; // NES NTSC modulator // square wave between up to four voltage levels b = 40 + volt[(c > 12 * ((c + 8 + p) % 12 < 6)) + 2 * !(0451326 >> p / 2 * 3 & e) + l]; // Ideal TV NTSC demodulator? sincos(M_PI * p / 6, &sc[0], &sc[1]); y += b; i += b * sc[1] * 5909; q += b * sc[0] * 5909; } // Converts YIQ to RGB // Store color at subpixel precision rgbc[u] = FixGamma(y / 1980. + i * A[u] / 9e6 + q * B[u] / 9e6); } matvmul3(rgbd65, lightbulb, rgbc); for (u = 0; u < 3; ++u) { palette_[o][p1][p0][u] = Clamp(rgbd65[u] * 255); } } } } } static void WriteStringNow(const char* s) { ttywrite(STDOUT_FILENO, s, strlen(s)); } void Exit(int rc) { WriteStringNow("\r\n\e[0m\e[J"); if (rc && errno) { fprintf(stderr, "%s%s\r\n", "error: ", strerror(errno)); } exit(rc); } void Cleanup(void) { ttyraw((enum TtyRawFlags)(-1u)); ttyshowcursor(STDOUT_FILENO); if (playpid_) kill(playpid_, SIGTERM), sched_yield(); } void OnTimer(void) { timeout_ = true; // also sends EINTR to poll() } void OnResize(void) { resized_ = true; } void OnPiped(void) { exited_ = true; } void OnCtrlC(void) { drain_ = exited_ = true; } void OnSigChld(void) { exited_ = true, playpid_ = 0; } void InitFrame(struct Frame* f) { f->p = f->w = f->mem = (char*)realloc(f->mem, vtsize_); } long ChopAxis(long dn, long sn) { while (HALF(sn) > dn) { sn = HALF(sn); } return sn; } void GetTermSize(void) { struct winsize wsize_; wsize_.ws_row = 25; wsize_.ws_col = 80; _getttysize(0, &wsize_); FreeSamplingSolution(ssy_); FreeSamplingSolution(ssx_); tyn_ = wsize_.ws_row * 2; txn_ = wsize_.ws_col * 2; ssy_ = ComputeSamplingSolution(tyn_, ChopAxis(tyn_, DYN), 0, 0, 2); ssx_ = ComputeSamplingSolution(txn_, ChopAxis(txn_, DXN), 0, 0, 0); R = (unsigned char*)realloc(R, tyn_ * txn_); G = (unsigned char*)realloc(G, tyn_ * txn_); B = (unsigned char*)realloc(B, tyn_ * txn_); ttyrgb_ = (struct TtyRgb*)realloc(ttyrgb_, tyn_ * txn_ * 4); vtsize_ = ((tyn_ * txn_ * strlen("\e[48;2;255;48;2;255m▄")) + (tyn_ * strlen("\e[0m\r\n")) + 128); frame_ = 0; InitFrame(&vf_[0]); InitFrame(&vf_[1]); WriteStringNow("\e[0m\e[H\e[J"); } void IoInit(void) { GetTermSize(); xsigaction(SIGINT, (void*)OnCtrlC, 0, 0, NULL); xsigaction(SIGPIPE, (void*)OnPiped, 0, 0, NULL); xsigaction(SIGWINCH, (void*)OnResize, 0, 0, NULL); xsigaction(SIGALRM, (void*)OnTimer, 0, 0, NULL); xsigaction(SIGCHLD, (void*)OnSigChld, 0, 0, NULL); setitimer(ITIMER_REAL, &kNesFps, NULL); ttyhidecursor(STDOUT_FILENO); ttyraw(kTtySigs); ttyquantsetup(quant_, kTtyQuantRgb, blocks_); atexit(Cleanup); } void SetStatus(const char* fmt, ...) { va_list va; va_start(va, fmt); vsnprintf(status_.text, sizeof(status_.text), fmt, va); va_end(va); status_.wait = FPS / 2; } void ReadKeyboard(void) { int ch; char b[20]; ssize_t i, rc; memset(b, -1, sizeof(b)); if ((rc = read(STDIN_FILENO, b, 16)) != -1) { if (!rc) exited_ = true; for (i = 0; i < rc; ++i) { ch = b[i]; if (b[i] == '\e') { ++i; if (b[i] == '[') { ++i; switch (b[i]) { case 'A': ch = CTRL('P'); // up arrow break; case 'B': ch = CTRL('N'); // down arrow break; case 'C': ch = CTRL('F'); // right arrow break; case 'D': ch = CTRL('B'); // left arrow break; default: break; } } } switch (ch) { case ' ': button_.code = 0b00100000; // A button_.wait = keyframes_; break; case 'b': button_.code = 0b00010000; // B button_.wait = keyframes_; break; case '\r': // enter button_.code = 0b10000000; // START button_.wait = keyframes_; break; case '\t': // tab button_.code = 0b01000000; // SELECT button_.wait = keyframes_; break; case 'k': // vim case 'w': // wasd qwerty case ',': // wasd dvorak case CTRL('P'): // emacs arrow_.code = 0b00000100; // UP arrow_.wait = keyframes_; break; case 'j': // vim case 's': // wasd qwerty case 'o': // wasd dvorak case CTRL('N'): // emacs arrow_.code = 0b00001000; // DOWN arrow_.wait = keyframes_; break; case 'h': // vim case 'a': // wasd qwerty & dvorak case CTRL('B'): // emacs arrow_.code = 0b00000010; // LEFT arrow_.wait = keyframes_; break; case 'l': // vim case 'd': // wasd qwerty case 'e': // wasd dvorak case CTRL('F'): // emacs arrow_.code = 0b00000001; // RIGHT arrow_.wait = keyframes_; break; case 'A': // ansi 4-bit color mode quant_ = kTtyQuantAnsi; ttyquantsetup(quant_, kTtyQuantRgb, blocks_); SetStatus("ansi color"); break; case 'x': // xterm256 color mode quant_ = kTtyQuantXterm256; ttyquantsetup(quant_, kTtyQuantRgb, blocks_); SetStatus("xterm256 color"); break; case 't': // ansi 24bit color mode quant_ = kTtyQuantTrue; ttyquantsetup(quant_, kTtyQuantRgb, blocks_); SetStatus("24-bit color"); break; case '1': artifacts_ = !artifacts_; InitPalette(); SetStatus("artifacts %s", artifacts_ ? "on" : "off"); break; case '3': // oldskool ibm unicode rasterization blocks_ = kTtyBlocksCp437; ttyquantsetup(quant_, kTtyQuantRgb, blocks_); SetStatus("IBM CP437"); break; case '4': // newskool unicode rasterization blocks_ = kTtyBlocksUnicode; ttyquantsetup(quant_, kTtyQuantRgb, blocks_); SetStatus("UNICODE"); break; case '8': keyframes_ = MAX(1, keyframes_ - 1); SetStatus("%d key frames", keyframes_); break; case '9': keyframes_ = keyframes_ + 1; SetStatus("%d key frames", keyframes_); break; default: break; } } } } bool HasVideo(struct Frame* f) { return f->w < f->p; } bool HasPendingVideo(void) { return HasVideo(&vf_[0]) || HasVideo(&vf_[1]); } bool HasPendingAudio(void) { return playpid_ && audio_.i; } struct Frame* FlipFrameBuffer(void) { frame_ = !frame_; return &vf_[frame_]; } void TransmitVideo(void) { ssize_t rc; struct Frame* f; f = &vf_[frame_]; if (!HasVideo(f)) f = FlipFrameBuffer(); if ((rc = write(STDOUT_FILENO, f->w, f->p - f->w)) != -1) { f->w += rc; } else if (errno == EPIPE) { Exit(0); } else if (errno != EINTR) { Exit(1); } } void TransmitAudio(void) { ssize_t rc; if (!audio_.i) return; if ((rc = write(playfd_, audio_.p, audio_.i * sizeof(short))) != -1) { rc /= sizeof(short); memmove(audio_.p, audio_.p + rc, (audio_.i - rc) * sizeof(short)); audio_.i -= rc; } else if (errno == EPIPE) { Exit(0); } else if (errno != EINTR) { Exit(1); } } void ScaleVideoFrameToTeletypewriter(void) { long y, x, yn, xn; yn = DYN, xn = DXN; while (HALF(yn) > tyn_ || HALF(xn) > txn_) { if (HALF(xn) > txn_) { Magikarp2xX(DYN, DXN, pixels_[0], yn, xn); Magikarp2xX(DYN, DXN, pixels_[1], yn, xn); Magikarp2xX(DYN, DXN, pixels_[2], yn, xn); xn = HALF(xn); } if (HALF(yn) > tyn_) { Magikarp2xY(DYN, DXN, pixels_[0], yn, xn); Magikarp2xY(DYN, DXN, pixels_[1], yn, xn); Magikarp2xY(DYN, DXN, pixels_[2], yn, xn); yn = HALF(yn); } } GyaradosUint8(tyn_, txn_, R, DYN, DXN, pixels_[0], tyn_, txn_, yn, xn, 0, 255, ssy_, ssx_, true); GyaradosUint8(tyn_, txn_, G, DYN, DXN, pixels_[1], tyn_, txn_, yn, xn, 0, 255, ssy_, ssx_, true); GyaradosUint8(tyn_, txn_, B, DYN, DXN, pixels_[2], tyn_, txn_, yn, xn, 0, 255, ssy_, ssx_, true); for (y = 0; y < tyn_; ++y) { for (x = 0; x < txn_; ++x) { ttyrgb_[y * txn_ + x] = rgb2tty(R[y * txn_ + x], G[y * txn_ + x], B[y * txn_ + x]); } } } void KeyCountdown(struct Action* a) { if (a->wait <= 1) { a->code = 0; } else { a->wait--; } } void PollAndSynchronize(void) { struct pollfd fds[3]; do { errno = 0; fds[0].fd = STDIN_FILENO; fds[0].events = POLLIN; fds[1].fd = HasPendingVideo() ? STDOUT_FILENO : -1; fds[1].events = POLLOUT; fds[2].fd = HasPendingAudio() ? playfd_ : -1; fds[2].events = POLLOUT; if (poll(fds, ARRAYLEN(fds), 1. / FPS * 1e3) != -1) { if (fds[0].revents & (POLLIN | POLLERR)) ReadKeyboard(); if (fds[1].revents & (POLLOUT | POLLERR)) TransmitVideo(); if (fds[2].revents & (POLLOUT | POLLERR)) TransmitAudio(); } else if (errno != EINTR) { Exit(1); } if (exited_) { if (drain_) { while (HasPendingVideo()) { TransmitVideo(); } } Exit(0); } if (resized_) { resized_ = false; GetTermSize(); break; } } while (!timeout_); timeout_ = false; KeyCountdown(&arrow_); KeyCountdown(&button_); joy_next_[0] = arrow_.code | button_.code; joy_next_[1] = arrow_.code | button_.code; } void Raster(void) { struct Frame* f; struct TtyRgb bg = {0x12, 0x34, 0x56, 0}; struct TtyRgb fg = {0x12, 0x34, 0x56, 0}; ScaleVideoFrameToTeletypewriter(); f = &vf_[!frame_]; f->p = f->w = f->mem; f->p = stpcpy(f->p, "\e[0m\e[H"); f->p = ttyraster(f->p, ttyrgb_, tyn_, txn_, bg, fg); if (status_.wait) { status_.wait--; f->p = stpcpy(f->p, "\e[0m\e[H"); f->p = stpcpy(f->p, status_.text); } CHECK_LT(f->p - f->mem, vtsize_); PollAndSynchronize(); } void FlushScanline(unsigned py) { if (py == DYN - 1) { if (!timeout_) { Raster(); } timeout_ = false; } } static void PutPixel(unsigned px, unsigned py, unsigned pixel, int offset) { unsigned rgb; static unsigned prev; pixels_[0][py][px] = palette_[offset][prev % 64][pixel][2]; pixels_[1][py][px] = palette_[offset][prev % 64][pixel][1]; pixels_[2][py][px] = palette_[offset][prev % 64][pixel][0]; prev = pixel; } static void JoyStrobe(unsigned v) { if (v) { joy_current_[0] = joy_next_[0]; joypos_[0] = 0; } if (v) { joy_current_[1] = joy_next_[1]; joypos_[1] = 0; } } static u8 JoyRead(unsigned idx) { // http://tasvideos.org/EmulatorResources/Famtasia/FMV.html static const u8 masks[8] = { 0b00100000, // A 0b00010000, // B 0b01000000, // SELECT 0b10000000, // START 0b00000100, // UP 0b00001000, // DOWN 0b00000010, // LEFT 0b00000001, // RIGHT }; return (joy_current_[idx] & masks[joypos_[idx]++ & 7]) ? 1 : 0; } template <unsigned bitno, unsigned nbits = 1, typename T = u8> struct RegBit { T data; enum { mask = (1u << nbits) - 1u }; template <typename T2> RegBit& operator=(T2 v) { data = (data & ~(mask << bitno)) | ((nbits > 1 ? v & mask : !!v) << bitno); return *this; } operator unsigned() const { return (data >> bitno) & mask; } RegBit& operator++() { return *this = *this + 1; } unsigned operator++(int) { unsigned r = *this; ++*this; return r; } }; namespace GamePak { const unsigned VRomGranularity = 0x0400; const unsigned VRomPages = 0x2000 / VRomGranularity; const unsigned RomGranularity = 0x2000; const unsigned RomPages = 0x10000 / RomGranularity; std::vector<u8> ROM; std::vector<u8> VRAM(0x2000); unsigned mappernum; unsigned char NRAM[0x1000]; unsigned char PRAM[0x2000]; unsigned char* banks[RomPages] = {}; unsigned char* Vbanks[VRomPages] = {}; unsigned char* Nta[4] = {NRAM + 0x0000, NRAM + 0x0400, NRAM + 0x0000, NRAM + 0x0400}; template <unsigned npages, unsigned char* (&b)[npages], std::vector<u8>& r, unsigned granu> static void SetPages(unsigned size, unsigned baseaddr, unsigned index) { for (unsigned v = r.size() + index * size, p = baseaddr / granu; p < (baseaddr + size) / granu && p < npages; ++p, v += granu) { b[p] = &r[v % r.size()]; } } auto& SetROM = SetPages<RomPages, banks, ROM, RomGranularity>; auto& SetVROM = SetPages<VRomPages, Vbanks, VRAM, VRomGranularity>; u8 Access(unsigned addr, u8 value, bool write) { if (write && addr >= 0x8000 && mappernum == 7) { // e.g. Rare games SetROM(0x8000, 0x8000, (value & 7)); Nta[0] = Nta[1] = Nta[2] = Nta[3] = &NRAM[0x400 * ((value >> 4) & 1)]; } if (write && addr >= 0x8000 && mappernum == 2) { // e.g. Rockman, Castlevania SetROM(0x4000, 0x8000, value); } if (write && addr >= 0x8000 && mappernum == 3) { // e.g. Kage, Solomon's Key value &= Access(addr, 0, false); // Simulate bus conflict SetVROM(0x2000, 0x0000, (value & 3)); } if (write && addr >= 0x8000 && mappernum == 1) { // e.g. Rockman 2, Simon's Quest static u8 regs[4] = {0x0C, 0, 0, 0}, counter = 0, cache = 0; if (value & 0x80) { regs[0] = 0x0C; goto configure; } cache |= (value & 1) << counter; if (++counter == 5) { regs[(addr >> 13) & 3] = value = cache; configure: cache = counter = 0; static const u8 sel[4][4] = { {0, 0, 0, 0}, {1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}}; for (unsigned m = 0; m < 4; ++m) Nta[m] = &NRAM[0x400 * sel[regs[0] & 3][m]]; SetVROM(0x1000, 0x0000, ((regs[0] & 16) ? regs[1] : ((regs[1] & ~1) + 0))); SetVROM(0x1000, 0x1000, ((regs[0] & 16) ? regs[2] : ((regs[1] & ~1) + 1))); switch ((regs[0] >> 2) & 3) { case 0: case 1: SetROM(0x8000, 0x8000, (regs[3] & 0xE) / 2); break; case 2: SetROM(0x4000, 0x8000, 0); SetROM(0x4000, 0xC000, (regs[3] & 0xF)); break; case 3: SetROM(0x4000, 0x8000, (regs[3] & 0xF)); SetROM(0x4000, 0xC000, ~0); break; } } } if ((addr >> 13) == 3) return PRAM[addr & 0x1FFF]; return banks[(addr / RomGranularity) % RomPages][addr % RomGranularity]; } void Init() { unsigned v; SetVROM(0x2000, 0x0000, 0); for (v = 0; v < 4; ++v) { SetROM(0x4000, v * 0x4000, v == 3 ? -1 : 0); } } } // namespace GamePak /* CPU: Ricoh RP2A03 (based on MOS6502, almost the same as in Commodore 64) */ namespace CPU { u8 RAM[0x800]; bool reset = true; bool nmi = false; bool nmi_edge_detected = false; bool intr = false; template <bool write> u8 MemAccess(u16 addr, u8 v = 0); u8 RB(u16 addr) { return MemAccess<0>(addr); } u8 WB(u16 addr, u8 v) { return MemAccess<1>(addr, v); } void Tick(); } // namespace CPU namespace PPU { /* Picture Processing Unit */ union regtype { // PPU register file u32 value; /* clang-format off */ // Reg0 (write) // Reg1 (write) // Reg2 (read) RegBit<0,8,u32> sysctrl; RegBit< 8,8,u32> dispctrl; RegBit<16,8,u32> status; RegBit<0,2,u32> BaseNTA; RegBit< 8,1,u32> Grayscale; RegBit<21,1,u32> SPoverflow; RegBit<2,1,u32> Inc; RegBit< 9,1,u32> ShowBG8; RegBit<22,1,u32> SP0hit; RegBit<3,1,u32> SPaddr; RegBit<10,1,u32> ShowSP8; RegBit<23,1,u32> InVBlank; RegBit<4,1,u32> BGaddr; RegBit<11,1,u32> ShowBG; // Reg3 (write) RegBit<5,1,u32> SPsize; RegBit<12,1,u32> ShowSP; RegBit<24,8,u32> OAMaddr; RegBit<6,1,u32> SlaveFlag; RegBit<11,2,u32> ShowBGSP; RegBit<24,2,u32> OAMdata; RegBit<7,1,u32> NMIenabled; RegBit<13,3,u32> EmpRGB; RegBit<26,6,u32> OAMindex; /* clang-format on */ } reg; // Raw memory data as read&written by the game u8 palette[32]; u8 OAM[256]; // Decoded sprite information, used & changed during each scanline struct { u8 sprindex, y, index, attr, x_; u16 pattern; } OAM2[8], OAM3[8]; union scrolltype { RegBit<3, 16, u32> raw; // raw VRAM address (16-bit) RegBit<0, 8, u32> xscroll; // low 8 bits of first write to 2005 RegBit<0, 3, u32> xfine; // low 3 bits of first write to 2005 RegBit<3, 5, u32> xcoarse; // high 5 bits of first write to 2005 RegBit<8, 5, u32> ycoarse; // high 5 bits of second write to 2005 RegBit<13, 2, u32> basenta; // nametable index (copied from 2000) RegBit<13, 1, u32> basenta_h; // horizontal nametable index RegBit<14, 1, u32> basenta_v; // vertical nametable index RegBit<15, 3, u32> yfine; // low 3 bits of second write to 2005 RegBit<11, 8, u32> vaddrhi; // first write to 2006 w/ high 2 bits set to 0 RegBit<3, 8, u32> vaddrlo; // second write to 2006 } scroll, vaddr; unsigned pat_addr, sprinpos, sproutpos, sprrenpos, sprtmp; u16 tileattr, tilepat, ioaddr; u32 bg_shift_pat, bg_shift_attr; int x_ = 0; int scanline = 241; int scanline_end = 341; int VBlankState = 0; int cycle_counter = 0; int read_buffer = 0; int open_bus = 0; int open_bus_decay_timer = 0; bool even_odd_toggle = false; bool offset_toggle = false; /* Memory mapping: Convert PPU memory address into reference to relevant data */ u8& NesMmap(int i) { i &= 0x3FFF; if (i >= 0x3F00) { if (i % 4 == 0) i &= 0x0F; return palette[i & 0x1F]; } if (i < 0x2000) { return GamePak::Vbanks[(i / GamePak::VRomGranularity) % GamePak::VRomPages] [i % GamePak::VRomGranularity]; } return GamePak::Nta[(i >> 10) & 3][i & 0x3FF]; } // External I/O: read or write u8 PpuAccess(u16 index, u8 v, bool write) { auto RefreshOpenBus = [&](u8 v) { return open_bus_decay_timer = 77777, open_bus = v; }; u8 res = open_bus; if (write) RefreshOpenBus(v); switch (index) { // Which port from $200x? case 0: if (write) { reg.sysctrl = v; scroll.basenta = reg.BaseNTA; } break; case 1: if (write) { reg.dispctrl = v; } break; case 2: if (write) break; res = reg.status | (open_bus & 0x1F); reg.InVBlank = false; // Reading $2002 clears the vblank flag. offset_toggle = false; // Also resets the toggle for address updates. if (VBlankState != -5) { VBlankState = 0; // This also may cancel the setting of InVBlank. } break; case 3: if (write) reg.OAMaddr = v; break; // Index into Object Attribute Memory case 4: if (write) { OAM[reg.OAMaddr++] = v; // Write or read the OAM (sprites). } else { res = RefreshOpenBus(OAM[reg.OAMaddr] & (reg.OAMdata == 2 ? 0xE3 : 0xFF)); } break; case 5: if (!write) break; // Set background scrolling offset if (offset_toggle) { scroll.yfine = v & 7; scroll.ycoarse = v >> 3; } else { scroll.xscroll = v; } offset_toggle = !offset_toggle; break; case 6: if (!write) break; // Set video memory position for reads/writes if (offset_toggle) { scroll.vaddrlo = v; vaddr.raw = (unsigned)scroll.raw; } else { scroll.vaddrhi = v & 0x3F; } offset_toggle = !offset_toggle; break; case 7: res = read_buffer; u8& t = NesMmap(vaddr.raw); // Access the video memory. if (write) { res = t = v; } else { if ((vaddr.raw & 0x3F00) == 0x3F00) { // palette? res = read_buffer = (open_bus & 0xC0) | (t & 0x3F); } read_buffer = t; } RefreshOpenBus(res); vaddr.raw = vaddr.raw + (reg.Inc ? 32 : 1); // The address is automatically updated. break; } return res; } void RenderingTick() { int y1, y2; bool tile_decode_mode = 0x10FFFF & (1u << (x_ / 16)); // When x_ is 0..255, 320..335 // Each action happens in two steps: 1) select memory address; 2) receive data // and react on it. switch (x_ % 8) { case 2: // Point to attribute table ioaddr = 0x23C0 + 0x400 * vaddr.basenta + 8 * (vaddr.ycoarse / 4) + (vaddr.xcoarse / 4); if (tile_decode_mode) break; // Or nametable, with sprites. case 0: // Point to nametable ioaddr = 0x2000 + (vaddr.raw & 0xFFF); // Reset sprite data if (x_ == 0) { sprinpos = sproutpos = 0; if (reg.ShowSP) reg.OAMaddr = 0; } if (!reg.ShowBG) break; // Reset scrolling (vertical once, horizontal each scanline) if (x_ == 304 && scanline == -1) vaddr.raw = (unsigned)scroll.raw; if (x_ == 256) { vaddr.xcoarse = (unsigned)scroll.xcoarse; vaddr.basenta_h = (unsigned)scroll.basenta_h; sprrenpos = 0; } break; case 1: if (x_ == 337 && scanline == -1 && even_odd_toggle && reg.ShowBG) { scanline_end = 340; } // Name table access pat_addr = 0x1000 * reg.BGaddr + 16 * NesMmap(ioaddr) + vaddr.yfine; if (!tile_decode_mode) break; // Push the current tile into shift registers. // The bitmap pattern is 16 bits, while the attribute is 2 bits, repeated // 8 times. bg_shift_pat = (bg_shift_pat >> 16) + 0x00010000 * tilepat; bg_shift_attr = (bg_shift_attr >> 16) + 0x55550000 * tileattr; break; case 3: // Attribute table access if (tile_decode_mode) { tileattr = (NesMmap(ioaddr) >> ((vaddr.xcoarse & 2) + 2 * (vaddr.ycoarse & 2))) & 3; // Go to the next tile horizontally (and switch nametable if it wraps) if (!++vaddr.xcoarse) { vaddr.basenta_h = 1 - vaddr.basenta_h; } // At the edge of the screen, do the same but vertically if (x_ == 251 && !++vaddr.yfine && ++vaddr.ycoarse == 30) { vaddr.ycoarse = 0; vaddr.basenta_v = 1 - vaddr.basenta_v; } } else if (sprrenpos < sproutpos) { // Select sprite pattern instead of background pattern auto& o = OAM3[sprrenpos]; // Sprite to render on next scanline memcpy(&o, &OAM2[sprrenpos], sizeof(o)); unsigned y = (scanline)-o.y; if (o.attr & 0x80) y ^= (reg.SPsize ? 15 : 7); pat_addr = 0x1000 * (reg.SPsize ? (o.index & 0x01) : reg.SPaddr); pat_addr += 0x10 * (reg.SPsize ? (o.index & 0xFE) : (o.index & 0xFF)); pat_addr += (y & 7) + (y & 8) * 2; } break; // Pattern table bytes case 5: tilepat = NesMmap(pat_addr | 0); break; case 7: // Interleave the bits of the two pattern bytes unsigned p = tilepat | (NesMmap(pat_addr | 8) << 8); p = (p & 0xF00F) | ((p & 0x0F00) >> 4) | ((p & 0x00F0) << 4); p = (p & 0xC3C3) | ((p & 0x3030) >> 2) | ((p & 0x0C0C) << 2); p = (p & 0x9999) | ((p & 0x4444) >> 1) | ((p & 0x2222) << 1); tilepat = p; // When decoding sprites, save the sprite graphics and move to next sprite if (!tile_decode_mode && sprrenpos < sproutpos) { OAM3[sprrenpos++].pattern = tilepat; } break; } // Find which sprites are visible on next scanline (TODO: implement crazy // 9-sprite malfunction) switch (x_ >= 64 && x_ < 256 && x_ % 2 ? (reg.OAMaddr++ & 3) : 4) { default: // Access OAM (object attribute memory) sprtmp = OAM[reg.OAMaddr]; break; case 0: if (sprinpos >= 64) { reg.OAMaddr = 0; break; } ++sprinpos; // next sprite if (sproutpos < 8) OAM2[sproutpos].y = sprtmp; if (sproutpos < 8) OAM2[sproutpos].sprindex = reg.OAMindex; y1 = sprtmp; y2 = sprtmp + (reg.SPsize ? 16 : 8); if (!(scanline >= y1 && scanline < y2)) { reg.OAMaddr = sprinpos != 2 ? reg.OAMaddr + 3 : 8; } break; case 1: if (sproutpos < 8) OAM2[sproutpos].index = sprtmp; break; case 2: if (sproutpos < 8) OAM2[sproutpos].attr = sprtmp; break; case 3: if (sproutpos < 8) OAM2[sproutpos].x_ = sprtmp; if (sproutpos < 8) { ++sproutpos; } else { reg.SPoverflow = true; } if (sprinpos == 2) reg.OAMaddr = 8; break; } } void RenderPixel() { bool edge = u8(x_ + 8) < 16; // 0..7, 248..255 bool showbg = reg.ShowBG && (!edge || reg.ShowBG8); bool showsp = reg.ShowSP && (!edge || reg.ShowSP8); // Render the background unsigned fx = scroll.xfine, xpos = 15 - (((x_ & 7) + fx + 8 * !!(x_ & 7)) & 15); unsigned pixel = 0, attr = 0; if (showbg) { // Pick a pixel from the shift registers pixel = (bg_shift_pat >> (xpos * 2)) & 3; attr = (bg_shift_attr >> (xpos * 2)) & (pixel ? 3 : 0); } else if ((vaddr.raw & 0x3F00) == 0x3F00 && !reg.ShowBGSP) { pixel = vaddr.raw; } // Overlay the sprites if (showsp) { for (unsigned sno = 0; sno < sprrenpos; ++sno) { auto& s = OAM3[sno]; // Check if this sprite is horizontally in range unsigned xdiff = x_ - s.x_; if (xdiff >= 8) continue; // Also matches negative values // Determine which pixel to display; skip transparent pixels if (!(s.attr & 0x40)) xdiff = 7 - xdiff; u8 spritepixel = (s.pattern >> (xdiff * 2)) & 3; if (!spritepixel) continue; // Register sprite-0 hit if applicable if (x_ < 255 && pixel && s.sprindex == 0) reg.SP0hit = true; // Render the pixel unless behind-background placement wanted if (!(s.attr & 0x20) || !pixel) { attr = (s.attr & 3) + 4; pixel = spritepixel; } // Only process the first non-transparent sprite pixel. break; } } pixel = palette[(attr * 4 + pixel) & 0x1F] & (reg.Grayscale ? 0x30 : 0x3F); PutPixel(x_, scanline, pixel | (reg.EmpRGB << 6), cycle_counter); } void ReadToolAssistedSpeedrunRobotKeys() { static FILE* fp; if (!fp && !isempty(inputfn_)) { fp = fopen(inputfn_, "rb"); } if (fp) { static unsigned ctrlmask = 0; if (!ftell(fp)) { fseek(fp, 0x05, SEEK_SET); ctrlmask = fgetc(fp); fseek(fp, 0x90, SEEK_SET); // Famtasia Movie format. } if (ctrlmask & 0x80) { joy_next_[0] = fgetc(fp); if (feof(fp)) joy_next_[0] = 0; } if (ctrlmask & 0x40) { joy_next_[1] = fgetc(fp); if (feof(fp)) joy_next_[1] = 0; } } } // PPU::Tick() -- This function is called 3 times per each CPU cycle. // Each call iterates through one pixel of the screen. // The screen is divided into 262 scanlines, each having 341 columns, as such: // // x_=0 x_=256 x_=340 // ___|____________________|__________| // y=-1 | pre-render scanline| prepare | > // ___|____________________| sprites _| > Graphics // y=0 | visible area | for the | > processing // | - this is rendered | next | > scanlines // y=239 | on the screen. | scanline | > // ___|____________________|______ // y=240 | idle // ___|_______________________________ // y=241 | vertical blanking (idle) // | 20 scanlines long // y=260___|____________________|__________| // // On actual PPU, the scanline begins actually before x_=0, with // sync/colorburst/black/background color being rendered, and // ends after x_=256 with background/black being rendered first, // but in this emulator we only care about the visible area. // // When background rendering is enabled, scanline -1 is // 340 or 341 pixels long, alternating each frame. // In all other situations the scanline is 341 pixels long. // Thus, it takes 89341 or 89342 PPU::Tick() calls to render 1 frame. void Tick() { // Set/clear vblank where needed switch (VBlankState) { case -5: reg.status = 0; break; case 2: reg.InVBlank = true; break; case 0: CPU::nmi = reg.InVBlank && reg.NMIenabled; break; } if (VBlankState != 0) VBlankState += (VBlankState < 0 ? 1 : -1); if (open_bus_decay_timer && !--open_bus_decay_timer) open_bus = 0; // Graphics processing scanline? if (scanline < DYN) { /* Process graphics for this cycle */ if (reg.ShowBGSP) RenderingTick(); if (scanline >= 0 && x_ < 256) RenderPixel(); } // Done with the cycle. Check for end of scanline. if (++cycle_counter == 3) cycle_counter = 0; // For NTSC pixel shifting if (++x_ >= scanline_end) { // Begin new scanline FlushScanline(scanline); scanline_end = 341; x_ = 0; // Does something special happen on the new scanline? switch (scanline += 1) { case 261: // Begin of rendering scanline = -1; // pre-render line even_odd_toggle = !even_odd_toggle; // Clear vblank flag VBlankState = -5; break; case 241: // Begin of vertical blanking ReadToolAssistedSpeedrunRobotKeys(); // Set vblank flag VBlankState = 2; } } } } // namespace PPU namespace APU { /* Audio Processing Unit */ static const u8 LengthCounters[32] = { 10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14, 12, 16, 24, 18, 48, 20, 96, 22, 192, 24, 72, 26, 16, 28, 32, 30, }; static const u16 NoisePeriods[16] = { 2, 4, 8, 16, 32, 48, 64, 80, 101, 127, 190, 254, 381, 508, 1017, 2034, }; static const u16 DMCperiods[16] = { 428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54, }; bool IRQdisable = true; bool FiveCycleDivider; bool ChannelsEnabled[5]; bool PeriodicIRQ; bool DMC_IRQ; bool count(int& v, int reset) { return --v < 0 ? (v = reset), true : false; } struct channel { int length_counter, linear_counter, address, envelope; int sweep_delay, env_delay, wave_counter, hold, phase, level; union { // Per-channel register file // 4000, 4004, 400C, 4012: RegBit<0, 8, u32> reg0; RegBit<6, 2, u32> DutyCycle; RegBit<4, 1, u32> EnvDecayDisable; RegBit<0, 4, u32> EnvDecayRate; RegBit<5, 1, u32> EnvDecayLoopEnable; RegBit<0, 4, u32> FixedVolume; RegBit<5, 1, u32> LengthCounterDisable; RegBit<0, 7, u32> LinearCounterInit; RegBit<7, 1, u32> LinearCounterDisable; // 4001, 4005, 4013: RegBit<8, 8, u32> reg1; RegBit<8, 3, u32> SweepShift; RegBit<11, 1, u32> SweepDecrease; RegBit<12, 3, u32> SweepRate; RegBit<15, 1, u32> SweepEnable; RegBit<8, 8, u32> PCMlength; // 4002, 4006, 400A, 400E: RegBit<16, 8, u32> reg2; RegBit<16, 4, u32> NoiseFreq; RegBit<23, 1, u32> NoiseType; RegBit<16, 11, u32> WaveLength; // 4003, 4007, 400B, 400F, 4010: RegBit<24, 8, u32> reg3; RegBit<27, 5, u32> LengthCounterInit; RegBit<30, 1, u32> LoopEnabled; RegBit<31, 1, u32> IRQenable; } reg; // Function for updating the wave generators and taking the sample for each // channel. template <unsigned c> int Tick() { channel& ch = *this; if (!ChannelsEnabled[c]) return c == 4 ? 64 : 8; int wl = (ch.reg.WaveLength + 1) * (c >= 2 ? 1 : 2); if (c == 3) wl = NoisePeriods[ch.reg.NoiseFreq]; int volume = ch.length_counter ? ch.reg.EnvDecayDisable ? ch.reg.FixedVolume : ch.envelope : 0; // Sample may change at wavelen intervals. auto& S = ch.level; if (!count(ch.wave_counter, wl)) return S; switch (c) { default: // Square wave. With four different 8-step binary waveforms (32 // bits of data total). if (wl < 8) return S = 8; return S = (0xF33C0C04u & (1u << (++ch.phase % 8 + ch.reg.DutyCycle * 8))) ? volume : 0; case 2: // Triangle wave if (ch.length_counter && ch.linear_counter && wl >= 3) ++ch.phase; return S = (ch.phase & 15) ^ ((ch.phase & 16) ? 15 : 0); case 3: // Noise: Linear feedback shift register if (!ch.hold) ch.hold = 1; ch.hold = (ch.hold >> 1) | (((ch.hold ^ (ch.hold >> (ch.reg.NoiseType ? 6 : 1))) & 1) << 14); return S = (ch.hold & 1) ? 0 : volume; case 4: // Delta modulation channel (DMC) // hold = 8 bit value, phase = number of bits buffered if (ch.phase == 0) { // Nothing in sample buffer? if (!ch.length_counter && ch.reg.LoopEnabled) { // Loop? ch.length_counter = ch.reg.PCMlength * 16 + 1; ch.address = (ch.reg.reg0 | 0x300) << 6; } if (ch.length_counter > 0) { // Load next 8 bits if available // Note: Re-entrant! But not recursive, because even // the shortest wave length is greater than the read time. // TODO: proper clock if (ch.reg.WaveLength > 20) { for (unsigned t = 0; t < 3; ++t) { CPU::RB(u16(ch.address) | 0x8000); // timing } } ch.hold = CPU::RB(u16(ch.address++) | 0x8000); // Fetch byte ch.phase = 8; --ch.length_counter; } else { // Otherwise, disable channel or issue IRQ ChannelsEnabled[4] = ch.reg.IRQenable && (CPU::intr = DMC_IRQ = true); } } if (ch.phase != 0) { // Update the signal if sample buffer nonempty int v = ch.linear_counter; if (ch.hold & (0x80 >> --ch.phase)) { v += 2; } else { v -= 2; } if (v >= 0 && v <= 0x7F) ch.linear_counter = v; } return S = ch.linear_counter; } } } channels[5] = {}; struct { short lo, hi; } hz240counter = {0, 0}; void Write(u8 index, u8 value) { unsigned c; channel& ch = channels[(index / 4) % 5]; switch (index < 0x10 ? index % 4 : index) { case 0: if (ch.reg.LinearCounterDisable) { ch.linear_counter = value & 0x7F; } ch.reg.reg0 = value; break; case 1: ch.reg.reg1 = value; ch.sweep_delay = ch.reg.SweepRate; break; case 2: ch.reg.reg2 = value; break; case 3: ch.reg.reg3 = value; if (ChannelsEnabled[index / 4]) { ch.length_counter = LengthCounters[ch.reg.LengthCounterInit]; } ch.linear_counter = ch.reg.LinearCounterInit; ch.env_delay = ch.reg.EnvDecayRate; ch.envelope = 15; if (index < 8) ch.phase = 0; break; case 0x10: ch.reg.reg3 = value; ch.reg.WaveLength = DMCperiods[value & 0x0F]; break; case 0x12: ch.reg.reg0 = value; ch.address = (ch.reg.reg0 | 0x300) << 6; break; case 0x13: ch.reg.reg1 = value; ch.length_counter = ch.reg.PCMlength * 16 + 1; break; // sample length case 0x11: ch.linear_counter = value & 0x7F; break; // dac value case 0x15: for (c = 0; c < 5; ++c) { ChannelsEnabled[c] = value & (1 << c); } for (c = 0; c < 5; ++c) { if (!ChannelsEnabled[c]) { channels[c].length_counter = 0; } else if (c == 4 && channels[c].length_counter == 0) { channels[c].length_counter = ch.reg.PCMlength * 16 + 1; } } break; case 0x17: IRQdisable = value & 0x40; FiveCycleDivider = value & 0x80; hz240counter = {0, 0}; if (IRQdisable) { PeriodicIRQ = DMC_IRQ = false; } break; } } u8 Read() { unsigned c; u8 res = 0; for (c = 0; c < 5; ++c) { res |= channels[c].length_counter ? 1 << c : 0; } if (PeriodicIRQ) res |= 0x40; PeriodicIRQ = false; if (DMC_IRQ) res |= 0x80; DMC_IRQ = false; CPU::intr = false; return res; } void Tick() { // Invoked at CPU's rate. // Divide CPU clock by 7457.5 to get a 240 Hz, which controls certain events. if ((hz240counter.lo += 2) >= 14915) { hz240counter.lo -= 14915; if (++hz240counter.hi >= 4 + FiveCycleDivider) hz240counter.hi = 0; // 60 Hz interval: IRQ. IRQ is not invoked in five-cycle mode (48 Hz). if (!IRQdisable && !FiveCycleDivider && hz240counter.hi == 0) { CPU::intr = PeriodicIRQ = true; } // Some events are invoked at 96 Hz or 120 Hz rate. Others, 192 Hz or 240 // Hz. bool HalfTick = (hz240counter.hi & 5) == 1; bool FullTick = hz240counter.hi < 4; for (unsigned c = 0; c < 4; ++c) { channel& ch = channels[c]; int wl = ch.reg.WaveLength; // Length tick (all channels except DMC, but different disable bit for // triangle wave) if (HalfTick && ch.length_counter && !(c == 2 ? ch.reg.LinearCounterDisable : ch.reg.LengthCounterDisable)) ch.length_counter -= 1; // Sweep tick (square waves only) if (HalfTick && c < 2 && count(ch.sweep_delay, ch.reg.SweepRate)) if (wl >= 8 && ch.reg.SweepEnable && ch.reg.SweepShift) { int s = wl >> ch.reg.SweepShift, d[4] = {s, s, ~s, -s}; wl += d[ch.reg.SweepDecrease * 2 + c]; if (wl < 0x800) ch.reg.WaveLength = wl; } // Linear tick (triangle wave only) if (FullTick && c == 2) { ch.linear_counter = ch.reg.LinearCounterDisable ? ch.reg.LinearCounterInit : (ch.linear_counter > 0 ? ch.linear_counter - 1 : 0); } // Envelope tick (square and noise channels) if (FullTick && c != 2 && count(ch.env_delay, ch.reg.EnvDecayRate)) { if (ch.envelope > 0 || ch.reg.EnvDecayLoopEnable) { ch.envelope = (ch.envelope - 1) & 15; } } } } // Mix the audio: Get the momentary sample from each channel and mix them. #define s(c) channels[c].Tick<c == 1 ? 0 : c>() auto v = [](float m, float n, float d) { return n != 0.f ? m / n : d; }; short sample = 30000 * (v(95.88f, (100.f + v(8128.f, s(0) + s(1), -100.f)), 0.f) + v(159.79f, (100.f + v(1.0, s(2) / 8227.f + s(3) / 12241.f + s(4) / 22638.f, -100.f)), 0.f) - 0.5f); #undef s audio_.p[audio_.i = (audio_.i + 1) & (ARRAYLEN(audio_.p) - 1)] = sample; } } // namespace APU namespace CPU { void Tick() { // PPU clock: 3 times the CPU rate for (unsigned n = 0; n < 3; ++n) PPU::Tick(); // APU clock: 1 times the CPU rate for (unsigned n = 0; n < 1; ++n) APU::Tick(); } template <bool write> u8 MemAccess(u16 addr, u8 v) { // Memory writes are turned into reads while reset is being signalled if (reset && write) return MemAccess<0>(addr); Tick(); // Map the memory from CPU's viewpoint. /**/ if (addr < 0x2000) { u8& r = RAM[addr & 0x7FF]; if (!write) return r; r = v; } else if (addr < 0x4000) { return PPU::PpuAccess(addr & 7, v, write); } else if (addr < 0x4018) { switch (addr & 0x1F) { case 0x14: // OAM DMA: Copy 256 bytes from RAM into PPU's sprite memory if (write) for (unsigned b = 0; b < 256; ++b) WB(0x2004, RB((v & 7) * 0x0100 + b)); return 0; case 0x15: if (!write) return APU::Read(); APU::Write(0x15, v); break; case 0x16: if (!write) return JoyRead(0); JoyStrobe(v); break; case 0x17: if (!write) return JoyRead(1); // write:passthru default: if (!write) break; APU::Write(addr & 0x1F, v); } } else { return GamePak::Access(addr, v, write); } return 0; } // CPU registers: u16 PC = 0xC000; u8 A = 0, X = 0, Y = 0, S = 0; union { /* Status flags: */ u8 raw; RegBit<0> C; // carry RegBit<1> Z; // zero RegBit<2> I; // interrupt enable/disable RegBit<3> D; // decimal mode (unsupported on NES, but flag exists) // 4,5 (0x10,0x20) don't exist RegBit<6> V; // overflow RegBit<7> N; // negative } P; u16 wrap(u16 oldaddr, u16 newaddr) { return (oldaddr & 0xFF00) + u8(newaddr); } void Misfire(u16 old, u16 addr) { u16 q = wrap(old, addr); if (q != addr) RB(q); } u8 Pop() { return RB(0x100 | u8(++S)); } void Push(u8 v) { WB(0x100 | u8(S--), v); } template <u16 op> // Execute a single CPU instruction, defined by opcode "op". void Ins() { // With template magic, the compiler will literally synthesize // >256 different functions. // Note: op 0x100 means "NMI", 0x101 means "Reset", 0x102 means "IRQ". They // are implemented in terms of "BRK". User is responsible for ensuring that // WB() will not store into memory while Reset is being processed. unsigned addr = 0, d = 0, t = 0xFF, c = 0, sb = 0, pbits = op < 0x100 ? 0x30 : 0x20; // Define the opcode decoding matrix, which decides which micro-operations // constitute any particular opcode. (Note: The PLA of 6502 works on a // slightly different principle.) enum { o8 = op / 8, o8m = 1 << (op % 8) }; // Fetch op'th item from a bitstring encoded in a data-specific variant of // base64, where each character transmits 8 bits of information rather than 6. // This peculiar encoding was chosen to reduce the source code size. // Enum temporaries are used in order to ensure compile-time evaluation. #define t(s, code) \ { \ enum { \ i = o8m & \ (s[o8] > 90 ? (130 + " (),-089<>?BCFGHJLSVWZ[^hlmnxy|}"[s[o8] - 94]) \ : (s[o8] - " (("[s[o8] / 39])) \ }; \ if (i) { \ code; \ } \ } /* wow */ /* clang-format off */ /* Decode address operand */ t(" !", addr = 0xFFFA) // NMI vector location t(" *", addr = 0xFFFC) // Reset vector location t("! ,", addr = 0xFFFE) // Interrupt vector location t("zy}z{y}zzy}zzy}zzy}zzy}zzy}zzy}z ", addr = RB(PC++)) t("2 yy2 yy2 yy2 yy2 XX2 XX2 yy2 yy ", d = X) // register index t(" 62 62 62 62 om om 62 62 ", d = Y) t("2 y 2 y 2 y 2 y 2 y 2 y 2 y 2 y ", addr=u8(addr+d); d=0; Tick()) // add zeropage-index t(" y z!y z y z y z y z y z y z y z ", addr=u8(addr); addr+=256*RB(PC++)) // absolute address t("3 6 2 6 2 6 286 2 6 2 6 2 6 2 6 /", addr=RB(c=addr); addr+=256*RB(wrap(c,c+1)))// indirect w/ page wrap t(" *Z *Z *Z *Z 6z *Z *Z ", Misfire(addr, addr+d)) // abs. load: extra misread when cross-page t(" 4k 4k 4k 4k 6z 4k 4k ", RB(wrap(addr, addr+d)))// abs. store: always issue a misread /* Load source operand */ t("aa__ff__ab__,4 ____ - ____ ", t &= A) // Many operations take A or X as operand. Some try in t(" knnn 4 99 ", t &= X) // error to take both; the outcome is an AND operation. t(" 9989 99 ", t &= Y) // sty,dey,iny,tya,cpy t(" 4 ", t &= S) // tsx, las t("!!!! !! !! !! ! !! !! !!/", t &= P.raw|pbits; c = t)// php, flag test/set/clear, interrupts t("_^__dc___^__ ed__98 ", c = t; t = 0xFF) // save as second operand t("vuwvzywvvuwvvuwv zy|zzywvzywv ", t &= RB(addr+d)) // memory operand t(",2 ,2 ,2 ,2 -2 -2 -2 -2 ", t &= RB(PC++)) // immediate operand /* Operations that mogrify memory operands directly */ t(" 88 ", P.V = t & 0x40; P.N = t & 0x80) // bit t(" nink nnnk ", sb = P.C) // rol,rla, ror,rra,arr t("nnnknnnk 0 ", P.C = t & 0x80) // rol,rla, asl,slo,[arr,anc] t(" nnnknink ", P.C = t & 0x01) // lsr,sre, ror,rra,asr t("ninknink ", t = (t << 1) | (sb * 0x01)) t(" nnnknnnk ", t = (t >> 1) | (sb * 0x80)) t(" ! kink ", t = u8(t - 1)) // dec,dex,dey,dcp t(" ! khnk ", t = u8(t + 1)) // inc,inx,iny,isb /* Store modified value (memory) */ t("kgnkkgnkkgnkkgnkzy|J kgnkkgnk ", WB(addr+d, t)) t(" q ", WB(wrap(addr, addr+d), t &= ((addr+d) >> 8))) // [shx,shy,shs,sha?] /* Some operations used up one clock cycle that we did not account for yet */ t("rpstljstqjstrjst - - - -kjstkjst/", Tick()) // nop,flag ops,inc,dec,shifts,stack,transregister,interrupts /* Stack operations and unconditional jumps */ t(" ! ! ! ", Tick(); t = Pop()) // pla,plp,rti t(" ! ! ", RB(PC++); PC = Pop(); PC |= (Pop() << 8)) // rti,rts t(" ! ", RB(PC++)) // rts t("! ! /", d=PC+(op?-1:1); Push(d>>8); Push(d)) // jsr, interrupts t("! ! 8 8 /", PC = addr) // jmp, jsr, interrupts t("!! ! /", Push(t)) // pha, php, interrupts /* Bitmasks */ t("! !! !! !! !! ! !! !! !!/", t = 1) t(" ! ! !! !! ", t <<= 1) t("! ! ! !! !! ! ! !/", t <<= 2) t(" ! ! ! ! ! ", t <<= 4) t(" ! ! ! !____ ", t = u8(~t)) // sbc, isb, clear flag t("`^__ ! ! !/", t = c | t) // ora, slo, set flag t(" !!dc`_ !! ! ! !! !! ! ", t = c & t) // and, bit, rla, clear/test flag t(" _^__ ", t = c ^ t) // eor, sre /* Conditional branches */ t(" ! ! ! ! ", if(t) { Tick(); Misfire(PC, addr = s8(addr) + PC); PC=addr; }) t(" ! ! ! ! ", if(!t) { Tick(); Misfire(PC, addr = s8(addr) + PC); PC=addr; }) /* Addition and subtraction */ t(" _^__ ____ ", c = t; t += A + P.C; P.V = (c^t) & (A^t) & 0x80; P.C = t & 0x100) t(" ed__98 ", t = c - t; P.C = ~t & 0x100) // cmp,cpx,cpy, dcp, sbx /* Store modified value (register) */ t("aa__aa__aa__ab__ 4 !____ ____ ", A = t) t(" nnnn 4 ! ", X = t) // ldx, dex, tax, inx, tsx,lax,las,sbx t(" ! 9988 ! ", Y = t) // ldy, dey, tay, iny t(" 4 0 ", S = t) // txs, las, shs t("! ! ! !! ! ! ! ! !/", P.raw = t & ~0x30) // plp, rti, flag set/clear /* Generic status flag updates */ t("wwwvwwwvwwwvwxwv 5 !}}||{}wv{{wv ", P.N = t & 0x80) t("wwwv||wvwwwvwxwv 5 !}}||{}wv{{wv ", P.Z = u8(t) == 0) t(" 0 ", P.V = (((t >> 5)+1)&2)) // [arr] /* clang-format on */ /* All implemented opcodes are cycle-accurate and memory-access-accurate. * [] means that this particular separate rule exists only to provide the * indicated unofficial opcode(s). */ } void Op() { /* Check the state of NMI flag */ bool nmi_now = nmi; unsigned op = RB(PC++); if (reset) { op = 0x101; } else if (nmi_now && !nmi_edge_detected) { op = 0x100; nmi_edge_detected = true; } else if (intr && !P.I) { op = 0x102; } if (!nmi_now) nmi_edge_detected = false; // Define function pointers for each opcode (00..FF) and each interrupt // (100,101,102) #define c(n) Ins<0x##n>, Ins<0x##n + 1>, #define o(n) c(n) c(n + 2) c(n + 4) c(n + 6) static void (*const i[0x108])() = { o(00) o(08) o(10) o(18) o(20) o(28) o(30) o(38) o(40) o(48) o(50) o(58) o(60) o(68) o(70) o(78) o(80) o(88) o(90) o(98) o(A0) o(A8) o(B0) o(B8) o(C0) o(C8) o(D0) o(D8) o(E0) o(E8) o(F0) o(F8) o(100)}; #undef o #undef c i[op](); reset = false; } } // namespace CPU char* GetLine(void) { static char* line; static size_t linesize; if (getline(&line, &linesize, stdin) > 0) { return _chomp(line); } else { return NULL; } } int PlayGame(const char* romfile, const char* opt_tasfile) { FILE* fp; int devnull; int pipefds[2]; const char* ffplay; inputfn_ = opt_tasfile; if (!(fp = fopen(romfile, "rb"))) { fprintf(stderr, "%s%s\n", "failed to open: ", romfile); return 2; } if (!(fgetc(fp) == 'N' && fgetc(fp) == 'E' && fgetc(fp) == 'S' && fgetc(fp) == CTRL('Z'))) { fprintf(stderr, "%s%s\n", "not a nes rom file: ", romfile); return 3; } InitPalette(); // open speaker // todo: this needs plenty of work if ((ffplay = commandvenv("FFPLAY", "ffplay"))) { devnull = open("/dev/null", O_WRONLY | O_CLOEXEC); pipe2(pipefds, O_CLOEXEC); if (!(playpid_ = fork())) { const char* const args[] = { "ffplay", "-nodisp", "-loglevel", "quiet", "-fflags", "nobuffer", "-ac", "1", "-ar", "1789773", "-f", "s16le", "pipe:", NULL, }; dup2(pipefds[0], 0); dup2(devnull, 1); dup2(devnull, 2); execv(ffplay, (char* const*)args); abort(); } close(pipefds[0]); playfd_ = pipefds[1]; } else { fputs("\nWARNING\n\ \n\ Need `ffplay` command to play audio\n\ Try `sudo apt install ffmpeg` on Linux\n\ You can specify it on `PATH` or in `FFPLAY`\n\ \n\ Press enter to continue without sound: ", stdout); fflush(stdout); GetLine(); } // Read the ROM file header u8 rom16count = fgetc(fp); u8 vrom8count = fgetc(fp); u8 ctrlbyte = fgetc(fp); u8 mappernum = fgetc(fp) | ctrlbyte >> 4; fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); if (mappernum >= 0x40) mappernum &= 15; GamePak::mappernum = mappernum; // Read the ROM data if (rom16count) GamePak::ROM.resize(rom16count * 0x4000); if (vrom8count) GamePak::VRAM.resize(vrom8count * 0x2000); fread(&GamePak::ROM[0], rom16count, 0x4000, fp); fread(&GamePak::VRAM[0], vrom8count, 0x2000, fp); fclose(fp); printf("%u * 16kB ROM, %u * 8kB VROM, mapper %u, ctrlbyte %02X\n", rom16count, vrom8count, mappernum, ctrlbyte); // Start emulation GamePak::Init(); IoInit(); PPU::reg.value = 0; // Pre-initialize RAM the same way as FCEUX does, to improve TAS sync. for (unsigned a = 0; a < 0x800; ++a) CPU::RAM[a] = (a & 4) ? 0xFF : 0x00; // Run the CPU until the program is killed. for (;;) CPU::Op(); } wontreturn void PrintUsage(int rc, FILE* f) { fprintf(f, "%s%s%s", "Usage: ", program_invocation_name, USAGE); exit(rc); } void GetOpts(int argc, char* argv[]) { int opt; while ((opt = getopt(argc, argv, "?hAxt134")) != -1) { switch (opt) { case 'A': quant_ = kTtyQuantAnsi; break; case 'x': quant_ = kTtyQuantXterm256; break; case 't': quant_ = kTtyQuantTrue; break; case '1': artifacts_ = !artifacts_; break; case '3': blocks_ = kTtyBlocksCp437; break; case '4': blocks_ = kTtyBlocksUnicode; break; case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } size_t FindZipGames(void) { char* name; struct Zipos* zipos; size_t i, cf, namesize; if ((zipos = __zipos_get())) { for (i = 0, cf = ZIP_CDIR_OFFSET(zipos->cdir); i < ZIP_CDIR_RECORDS(zipos->cdir); ++i, cf += ZIP_CFILE_HDRSIZE(zipos->map + cf)) { if (ZIP_CFILE_NAMESIZE(zipos->map + cf) > 4 && !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), ZIP_CFILE_NAME(zipos->map + cf)))) { APPEND(&zipgames_.p, &zipgames_.i, &zipgames_.n, &name); } } } return zipgames_.i; } int SelectGameFromZip(void) { int i, rc; char *line, *uri; fputs("\nCOSMOPOLITAN NESEMU1\n\n", stdout); for (i = 0; i < zipgames_.i; ++i) { printf(" [%d] %s\n", i, zipgames_.p[i]); } fputs("\nPlease choose a game (or CTRL-C to quit) [default 0]: ", stdout); fflush(stdout); rc = 0; if ((line = GetLine())) { i = MAX(0, MIN(zipgames_.i - 1, atoi(line))); uri = zipgames_.p[i]; rc = PlayGame(uri, NULL); free(uri); } else { fputs("\n", stdout); } return rc; } int main(int argc, char** argv) { int rc; GetOpts(argc, argv); if (optind + 1 < argc) { rc = PlayGame(argv[optind], argv[optind + 1]); } else if (optind < argc) { rc = PlayGame(argv[optind], NULL); } else { if (!FindZipGames()) { PrintUsage(0, stderr); } rc = SelectGameFromZip(); } return rc; }
59,766
1,868
jart/cosmopolitan
false
cosmopolitan/examples/rlimit.c
#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/intrin/strace.internal.h" #include "libc/calls/struct/rlimit.h" #include "libc/errno.h" #include "libc/intrin/describeflags.internal.h" #include "libc/log/color.internal.h" #include "libc/macros.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/rlim.h" #include "libc/sysv/consts/rlimit.h" /** * @fileoverview tool for printing and changing system resource limits * * This is what you do if you want to not accidentally bomb your system * with runaway code. If you haven't accidentally bombed your UNIX * system before then you're not pushing it hard enough. */ static void SetLimit(int resource, uint64_t soft, uint64_t hard) { struct rlimit old; struct rlimit lim = {soft, hard}; if (resource == 127) return; if (setrlimit(resource, &lim) == -1) { if (!getrlimit(resource, &old)) { lim.rlim_max = MIN(hard, old.rlim_max); lim.rlim_cur = MIN(soft, old.rlim_max); if (!setrlimit(resource, &lim)) { fprintf(stderr, "%sNOTE: SETRLIMIT(%s) DOWNGRADED TO {%,ld, %,ld}\n", DescribeRlimitName(resource), lim.rlim_cur, lim.rlim_max); return; } } fprintf(stderr, "ERROR: SETRLIMIT(%s, %,ld, %,ld) FAILED %m%n", DescribeRlimitName(resource), soft, hard); exit(1); } } int main(int argc, char *argv[]) { int i, rc; char rlnbuf[20]; struct rlimit rlim; // // example of how you might change the limits // SetLimit(RLIMIT_CPU, 3, 33); // SetLimit(RLIMIT_NPROC, 4, 128); // SetLimit(RLIMIT_NOFILE, 32, 128); // SetLimit(RLIMIT_SIGPENDING, 16, 1024); // SetLimit(RLIMIT_AS, 8 * 1024 * 1024, 1l * 1024 * 1024 * 1024); // SetLimit(RLIMIT_RSS, 8 * 1024 * 1024, 1l * 1024 * 1024 * 1024); // SetLimit(RLIMIT_DATA, 8 * 1024 * 1024, 1l * 1024 * 1024 * 1024); // SetLimit(RLIMIT_FSIZE, 8 * 1000 * 1000, 1l * 1000 * 1000 * 1000); for (i = 0; i < RLIM_NLIMITS; ++i) { rc = getrlimit(i, &rlim); printf("SETRLIMIT(%-20s, %,16ld, %,16ld) → %d %s\n", (DescribeRlimitName)(rlnbuf, i), rlim.rlim_cur, rlim.rlim_max, rc, !rc ? "" : strerror(errno)); } return 0; }
2,975
74
jart/cosmopolitan
false
cosmopolitan/examples/clock_getres.c
#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/struct/timespec.h" #include "libc/errno.h" #include "libc/intrin/describeflags.internal.h" #include "libc/intrin/kprintf.h" #include "libc/str/str.h" #include "libc/sysv/consts/clock.h" int n; int shown[64]; void show(int clock) { int i; struct timespec ts; if (clock == 127) return; for (i = 0; i < n; ++i) { if (shown[i] == clock) { return; } } shown[n++] = clock; if (clock_getres(clock, &ts) != -1) { kprintf("%s %'ld ns\n", DescribeClockName(clock), timespec_tonanos(ts)); } else { kprintf("%s %s\n", DescribeClockName(clock), _strerrno(errno)); } } int main(int argc, char *argv[]) { show(CLOCK_REALTIME); show(CLOCK_REALTIME_FAST); show(CLOCK_REALTIME_PRECISE); show(CLOCK_REALTIME_COARSE); show(CLOCK_MONOTONIC); show(CLOCK_MONOTONIC_RAW); show(CLOCK_MONOTONIC_FAST); show(CLOCK_MONOTONIC_PRECISE); show(CLOCK_MONOTONIC_COARSE); show(CLOCK_PROCESS_CPUTIME_ID); show(CLOCK_THREAD_CPUTIME_ID); show(CLOCK_PROF); show(CLOCK_BOOTTIME); show(CLOCK_REALTIME_ALARM); show(CLOCK_BOOTTIME_ALARM); show(CLOCK_TAI); show(CLOCK_UPTIME); show(CLOCK_UPTIME_PRECISE); show(CLOCK_UPTIME_FAST); show(CLOCK_SECOND); }
1,996
59
jart/cosmopolitan
false
cosmopolitan/examples/symtab.c
#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/intrin/kprintf.h" #include "libc/log/log.h" /** * @fileoverview example of how to embed symbol table in .com file * * # build our binary * make -j16 o//examples/symtab.com * * # move binary somewhere else * # so it can't find the .com.dbg binary * cp o//examples/symtab.com /tmp * * # run program * # notice that it has a symbolic backtrace * /tmp/symtab.com * * @see examples/examples.mk */ int main(int argc, char *argv[]) { // this links all the debugging and zip functionality ShowCrashReports(); kprintf("----------------\n"); kprintf(" THIS IS A TEST \n"); kprintf("SIMULATING CRASH\n"); kprintf("----------------\n"); volatile int64_t x; return 1 / (x = 0); }
1,534
43
jart/cosmopolitan
false
cosmopolitan/examples/setitimer.c
#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/itimerval.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/ucontext.h" #include "libc/log/check.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" volatile bool gotalrm; void OnSigAlrm(int sig, siginfo_t *si, void *ctx) { gotalrm = true; } int main() { ////////////////////////////////////////////////////////////////////////////// printf("first tutorial: set singleshot alarm for 1.5 seconds from now\n"); // setup alarm in 1.5 seconds // this timer tears itself down once it's handled struct itimerval shot = {{0, 0}, {1, 500000}}; struct sigaction handler = {.sa_sigaction = OnSigAlrm, .sa_flags = SA_RESETHAND | SA_SIGINFO}; CHECK_EQ(0, sigaction(SIGALRM, &handler, 0)); CHECK_EQ(0, setitimer(ITIMER_REAL, &shot, 0)); // wait for alarm pause(); printf("got singleshot alarm!\n\n"); ////////////////////////////////////////////////////////////////////////////// printf("second tutorial: interval timer\n"); // setup timer every 1.5 seconds struct sigaction oldalrm; struct sigaction sigalrm = {.sa_sigaction = OnSigAlrm, .sa_flags = SA_SIGINFO}; CHECK_EQ(0, sigaction(SIGALRM, &sigalrm, &oldalrm)); struct itimerval oldtimer; struct itimerval timer = {{1, 500000}, {1, 500000}}; CHECK_EQ(0, setitimer(ITIMER_REAL, &timer, &oldtimer)); // wait for three timeouts int i = 0; int n = 3; while (i < n) { pause(); if (gotalrm) { ++i; printf("got timeout %d out of %d\n", i, n); gotalrm = false; } } // teardown timer CHECK_EQ(0, setitimer(ITIMER_REAL, &oldtimer, 0)); CHECK_EQ(0, sigaction(SIGALRM, &oldalrm, 0)); }
2,683
73
jart/cosmopolitan
false
cosmopolitan/examples/statfs.c
#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/struct/statfs.h" #include "libc/dce.h" #include "libc/fmt/conv.h" #include "libc/log/check.h" #include "libc/nt/enum/statfs.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/st.h" dontinline void ShowIt(const char *path) { char ibuf[21]; struct statfs sf = {0}; CHECK_NE(-1, statfs(path, &sf)); printf("filesystem %s\n", path); printf("f_type = %#x (%s)\n", sf.f_type, sf.f_fstypename); sizefmt(ibuf, sf.f_bsize, 1024); printf("f_bsize = %,zu (%sb %s)\n", sf.f_bsize, ibuf, "optimal transfer block size"); sizefmt(ibuf, sf.f_frsize, 1024); printf("f_frsize = %,zu (%sb %s)\n", sf.f_frsize, ibuf, "fragment size"); sizefmt(ibuf, sf.f_blocks * sf.f_frsize, 1024); printf("f_blocks = %,zu (%sb %s)\n", sf.f_blocks, ibuf, "total data blocks in filesystem"); sizefmt(ibuf, sf.f_bfree * sf.f_frsize, 1024); printf("f_bfree = %,zu (%sb %s)\n", sf.f_bfree, ibuf, "free blocks in filesystem"); sizefmt(ibuf, sf.f_bavail * sf.f_frsize, 1024); printf("f_bavail = %,zu (%sb %s)\n", sf.f_bavail, ibuf, "free blocks available to use"); printf("f_files = %,zu (%s)\n", sf.f_files, "total file nodes in filesystem"); printf("f_ffree = %,zu (%s)\n", sf.f_ffree, "free file nodes in filesystem"); printf("f_fsid = %#lx (%s)\n", sf.f_fsid, "filesystem id"); printf("f_owner = %#lx (%s)\n", sf.f_owner, "user that created mount"); printf("f_namelen = %,zu (%s)\n", sf.f_namelen, "maximum length of filenames"); printf("f_flags = %#x", sf.f_flags); if (!IsWindows()) { if (ST_RDONLY && (sf.f_flags & ST_RDONLY)) { printf(" ST_RDONLY"); } if (ST_NOSUID && (sf.f_flags & ST_NOSUID)) { printf(" ST_NOSUID"); } if (ST_NODEV && (sf.f_flags & ST_NODEV)) { printf(" ST_NODEV"); } if (ST_NOEXEC && (sf.f_flags & ST_NOEXEC)) { printf(" ST_NOEXEC"); } if (ST_SYNCHRONOUS && (sf.f_flags & ST_SYNCHRONOUS)) { printf(" ST_SYNCHRONOUS"); } if (ST_MANDLOCK && (sf.f_flags & ST_MANDLOCK)) { printf(" ST_MANDLOCK"); } if (ST_WRITE && (sf.f_flags & ST_WRITE)) { printf(" ST_WRITE"); } if (ST_APPEND && (sf.f_flags & ST_APPEND)) { printf(" ST_APPEND"); } if (ST_IMMUTABLE && (sf.f_flags & ST_IMMUTABLE)) { printf(" ST_IMMUTABLE"); } if (ST_NOATIME && (sf.f_flags & ST_NOATIME)) { printf(" ST_NOATIME"); } if (ST_NODIRATIME && (sf.f_flags & ST_NODIRATIME)) { printf(" ST_NODIRATIME"); } if (ST_RELATIME && (sf.f_flags & ST_RELATIME)) { printf(" ST_RELATIME"); } } else { if (sf.f_flags & kNtFileCasePreservedNames) { printf(" CasePreservedNames"); } if (sf.f_flags & kNtFileCaseSensitiveSearch) { printf(" CaseSensitiveSearch"); } if (sf.f_flags & kNtFileFileCompression) { printf(" FileCompression"); } if (sf.f_flags & kNtFileNamedStreams) { printf(" NamedStreams"); } if (sf.f_flags & kNtFilePersistentAcls) { printf(" PersistentAcls"); } if (sf.f_flags & kNtFileReadOnlyVolume) { printf(" ReadOnlyVolume"); } if (sf.f_flags & kNtFileSequentialWriteOnce) { printf(" SequentialWriteOnce"); } if (sf.f_flags & kNtFileSupportsEncryption) { printf(" SupportsEncryption"); } if (sf.f_flags & kNtFileSupportsExtendedAttributes) { printf(" SupportsExtendedAttributes"); } if (sf.f_flags & kNtFileSupportsHardLinks) { printf(" SupportsHardLinks"); } if (sf.f_flags & kNtFileSupportsObjectIds) { printf(" SupportsObjectIds"); } if (sf.f_flags & kNtFileSupportsOpenByFileId) { printf(" SupportsOpenByFileId"); } if (sf.f_flags & kNtFileSupportsReparsePoints) { printf(" SupportsReparsePoints"); } if (sf.f_flags & kNtFileSupportsSparseFiles) { printf(" SupportsSparseFiles"); } if (sf.f_flags & kNtFileSupportsTransactions) { printf(" SupportsTransactions"); } if (sf.f_flags & kNtFileSupportsUsnJournal) { printf(" SupportsUsnJournal"); } if (sf.f_flags & kNtFileUnicodeOnDisk) { printf(" UnicodeOnDisk"); } if (sf.f_flags & kNtFileVolumeIsCompressed) { printf(" VolumeIsCompressed"); } if (sf.f_flags & kNtFileVolumeQuotas) { printf(" VolumeQuotas"); } if (sf.f_flags & kNtFileSupportsBlockRefcounting) { printf(" SupportsBlockRefcounting"); } } printf("\n"); printf("\n"); } int main(int argc, char *argv[]) { if (argc <= 1) { ShowIt("/"); } else { for (int i = 1; i < argc; ++i) { ShowIt(argv[i]); } } }
5,490
164
jart/cosmopolitan
false
cosmopolitan/examples/hello2.c
#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/str/str.h" int main() { write(1, "hello world\n", 12); return 0; }
901
17
jart/cosmopolitan
false
cosmopolitan/examples/ttyinfo.c
#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 "dsp/tty/tty.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/termios.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/termios.h" #include "libc/x/xsigaction.h" #define CTRL(C) ((C) ^ 0b01000000) #define WRITE(FD, SLIT) write(FD, SLIT, strlen(SLIT)) #define ENABLE_SAFE_PASTE "\e[?2004h" #define ENABLE_MOUSE_TRACKING "\e[?1000;1002;1015;1006h" #define DISABLE_MOUSE_TRACKING "\e[?1000;1002;1015;1006l" #define PROBE_DISPLAY_SIZE "\e7\e[9979;9979H\e[6n\e8" char code[512]; struct winsize wsize; struct termios oldterm; volatile bool resized, killed; void onresize(void) { resized = true; } void onkilled(int sig) { killed = true; } void restoretty(void) { WRITE(1, DISABLE_MOUSE_TRACKING); ioctl(1, TCSETS, &oldterm); } int rawmode(void) { static bool once; struct termios t; if (!once) { if (ioctl(1, TCGETS, &oldterm) != -1) { atexit(restoretty); } else { return -1; } once = true; } memcpy(&t, &oldterm, sizeof(t)); t.c_cc[VMIN] = 1; t.c_cc[VTIME] = 1; t.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON | IGNBRK | BRKINT); t.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL | ISIG); t.c_cflag &= ~(CSIZE | PARENB); t.c_oflag &= ~OPOST; t.c_cflag |= CS8; t.c_iflag |= IUTF8; ioctl(1, TCSETS, &t); WRITE(1, ENABLE_SAFE_PASTE); WRITE(1, ENABLE_MOUSE_TRACKING); WRITE(1, PROBE_DISPLAY_SIZE); return 0; } void getsize(void) { if (_getttysize(1, &wsize) != -1) { printf("termios says terminal size is %hu×%hu\r\n", wsize.ws_col, wsize.ws_row); } else { printf("%s\n", strerror(errno)); } } const char *describemouseevent(int e) { static char buf[64]; buf[0] = 0; if (e & 0x10) { strcat(buf, " ctrl"); } if (e & 0x40) { strcat(buf, " wheel"); if (e & 0x01) { strcat(buf, " down"); } else { strcat(buf, " up"); } } else { switch (e & 3) { case 0: strcat(buf, " left"); break; case 1: strcat(buf, " middle"); break; case 2: strcat(buf, " right"); break; default: unreachable; } if (e & 0x20) { strcat(buf, " drag"); } else if (e & 0x04) { strcat(buf, " up"); } else { strcat(buf, " down"); } } return buf + 1; } int main(int argc, char *argv[]) { int e, c, y, x, n, yn, xn; xsigaction(SIGTERM, onkilled, 0, 0, NULL); xsigaction(SIGWINCH, onresize, 0, 0, NULL); xsigaction(SIGCONT, onresize, 0, 0, NULL); rawmode(); getsize(); while (!killed) { if (resized) { printf("SIGWINCH "); getsize(); resized = false; } if ((n = readansi(0, code, sizeof(code))) == -1) { if (errno == EINTR) continue; printf("ERROR: READ: %s\r\n", strerror(errno)); exit(1); } printf("%`'.*s ", n, code); if (iscntrl(code[0]) && !code[1]) { printf("is CTRL-%c a.k.a. ^%c\r\n", CTRL(code[0]), CTRL(code[0])); if (code[0] == CTRL('C') || code[0] == CTRL('D')) break; } else if (_startswith(code, "\e[") && _endswith(code, "R")) { yn = 1, xn = 1; sscanf(code, "\e[%d;%dR", &yn, &xn); printf("inband signalling says terminal size is %d×%d\r\n", xn, yn); } else if (_startswith(code, "\e[<") && (_endswith(code, "m") || _endswith(code, "M"))) { e = 0, y = 1, x = 1; sscanf(code, "\e[<%d;%d;%d%c", &e, &y, &x, &c); printf("mouse %s at %d×%d\r\n", describemouseevent(e | (c == 'm') << 2), x, y); } else { printf("\r\n"); } } return 0; }
4,799
167
jart/cosmopolitan
false
cosmopolitan/examples/check.c
#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/log/check.h" /** * @fileoverview Check Macros * * The simplest assertion is: * * assert(123 == x); * * This has some downsides: * * 1. It's nice to know what `x` is when it crashes * 2. It's sometimes nice to have the check always take effect. * 3. It's problematic that assert() can't do __builtin_assume() * * Cosmopolitan provides alternative macros like: * * - `CHECK(EXPR, ...)` * - `CHECK_EQ(WANT, GOT, ...)` * - `CHECK_NE(WANT, GOT, ...)` * - `CHECK_GT(WANT, GOT, ...)` * - `CHECK_LT(WANT, GOT, ...)` * - `CHECK_NOTNULL(EXPR, ...)` * * The CHECK macros always happen. They always kill the process when * they fail. Printf formatting information may be provided as extra * arguments. On the other hand, there exists: * * - `DCHECK(EXPR, ...)` * - `DCHECK_EQ(WANT, GOT, ...)` * - `DCHECK_NE(WANT, GOT, ...)` * - `DCHECK_GT(WANT, GOT, ...)` * - `DCHECK_LT(WANT, GOT, ...)` * - `DCHECK_NOTNULL(EXPR, ...)` * * The DCHECK macros always happen when NDEBUG isn't defined. When * NDEBUG is defined, they still happen, but in a special way that * causes the compiler to recognize their failure as undefined behavior. * What this means is that, if the provided expressions are pure without * side-effects, then the code compiles down to nothing and the compiler * may be able to use the knowledge of something being the case in order * to optimize other code adjacent to your DCHECK. * * In the default build modes, this prints lots of information: * * error:examples/check.c:23:check.com: check failed on nightmare pid 15412 * CHECK_EQ(123, some_source_code); * → 0x7b (123) * == 0x64 (some_source_code) * extra info: hello * EUNKNOWN/0/No error information * ./o//examples/check.com * 0x0000000000407404: __die at libc/log/die.c:42 * 0x0000000000407340: __check_fail at libc/log/checkfail.c:73 * 0x00000000004071d0: main at examples/check.c:23 * 0x000000000040256e: cosmo at libc/runtime/cosmo.S:69 * 0x000000000040217d: _start at libc/crt/crt.S:85 * * In NDEBUG mode (e.g. MODE=rel, MODE=tiny, etc.) this prints a much * simpler message that, most importantly, doesn't include any source * code, although it still includes the file name for reference. * * error:examples/check.c:14: check failed: 123 == 100: extra info: hello * * That way your release binaries won't leak CI. You may optionally link * the following functions to further expand the information shown by * the NDEBUG check failure: * * STATIC_YOINK("__die"); * STATIC_YOINK("strerror"); * * Please note that backtraces aren't ever available in MODE=tiny. */ int main(int argc, char *argv[]) { int some_source_code = 100; CHECK_EQ(123, some_source_code, "extra info: %s", "hello"); return 0; }
3,623
89
jart/cosmopolitan
false
cosmopolitan/examples/unbourne.c
/*bin/echo ' #-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;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. │ ├──────────────────────────────────────────────────────────────────────────────┤ │███▒ ▓░░░▒ █▓█▓ ▒▒███████▓█████ ██▓▓▓███▒██▒▓█▓████████ ▓██▓█████▓██ ░ ░▒ ░ │ │█░ ░ █░▒▒▒ █▓▓▓ ▒▓████▓░███▓█▓▓▓▓█▓▒▓▓███▓▒▒██▓▓█▓█████ ▒██▓█████▓██ ░ ▒░░░ ░│ │███▓ ▒ ▓██▓ █████▓░█▓▓█▓██░░█░████▓█▓██▒██▒▓▓▓█▓▓█▓█▒██▓█████▓██░▒ ▓░ │ │████ █▓ ▒███▓██████████████████████████████▓▓█▓█████▓████████▓██ ▒▓▓▓▒░▒ ░│ │███▓ ▓▓▓▓ ▒███████████▓████████████▓▓██▓▓▓█▓████▓███▓█████▓██ ▒░▓▒░░ ░│ │███▓ █▒▓▒▒░▓ ▒██▓████████████████████████████▓██▓▓████████▓██ ░░▒▒▓▓▒ ░│ │███▓ ▓▒▓▓▓ █▓▓ ▒███████████████████████████▓██▓▓░███████▓██ ░ ▒▒░░▓▓░│ │█▓█▓ █▒░░░ █▓██▓ ██████████████████████████▓█████████▓▓░░░ ▒░ ░░ ▒│ │█▓█▓░█▓▒▓▒ ██▓█▓ ▓ ▓██████████████████▒██▓████████ ▒░▒▒▒▒▒▒▒ ░│ │█▓▓▒░▓▓▒▓▓ █▓▓██ ██ ░ ░ ░░░░ ░░░ ░ ███████████████▓██▓██████ ░▒▓▓▒▓▓░▒▓░▒░ │ │██▓▓░▓▒▒▓▒░▓▓▓▓▓ █▓▓░ ░ ░░ ░ ░ ▓█████████████▒██▓████▒▒▒░░▓▓▒▓▒░▒░░▒░ ░│ │█▓▓▓░█▒▒▒▒ █▓▓▓▓ ██▓▓ ░ ░ ▒▒ ██████████▒██▓███░░░▒▒▓▓▓▓▒░░ ░ │ │██▓▓░█░▒▒▒░█▓▓▓▓ █▓▓█ ░ ░ ░░░░▓░ ████████▒██ ░░░▓▒▒▓▓▓▓ ▓▒░▒▒▒▒░░ │ │▒██▓▒▓░▒▓░░▓▓▓▓▓ ▓▓▓▓ ░░ ▒░░▒░░ ▓███████▒██░ ▒ ▒░░▒▓▒▒░▒▒▓▒ ░ │ │▒▓▓▓▒█▒▒▒▒░█▒▒▓▓ ▓▓█▓▓▓▓▓ ░▒ ░ ▒ ░▓▓▓░░░ █▒ ▓ ██▓███▒▓░▓▓▒░▓░░░░▒▒░░░ ░│ │▒█▒▓░▓▓░▓▓░▓▒▓▒▒ █▓████▓███ ░ ░▒░ ▓▓▒▒▒▒░░▓ ░ ░█ ▓ ▒█████░░ ▓▓▒▒░░▒▒▓▒░ ░░│ │░▓█▓▒▓▓▒▓▒░█▓▒▓▓ █▓████▓███▓▓ ░▒▒▒▓▓▒▒▓▓▒░▒▓░ ▒ ░██ ░ ███▒░▓░ ▓▒▓▒▒░ ░ │ │░█▓▓▓▓▓▓▒▒▓█▓▒▓▓ █▓▓███▓█████▓ ░▒▒▒▒▒▓▒▒░░▒░▓ ░░▓▒ ▒░▒░ ░▒ ▓░▓▓░░ ▓▓░ ░░░░ ░░ │ │ ██░ ░ ▒█▓▓▓▓ ██████▓██████▓░▒▒▒▓▓▓▓▓▓▒▒░▓▒░▓▒▒▒▒▓▓▓░▓▒▒░▒▒▓▓▒▒░▒ ░ ░ ░░│ │ ░░░▒ ▓▓▓▓ █▓▓█▓█▓███████▓░▒▓▒▓▓█▒░▒▓▓▓▒▒▓▓▒▓▓▒█░▒▓▒▒ ░▓▒▓ ▒▒░▒░ ▒ ░░░ │ │ ▒░░ ░ ▓ ░▓▓▓▓ ████▓█▓████████▒▓▒█░░▓▒▓ ▒▓▓░▒▒▓▒▒▓▒▓▒▒▓▒▓▓█▓▓ ▓░▒ ░░░░░ ░ │ │ ░▓ ▒░░░░ ▓█▓▓▓ █▓▒███▓█████████▓░░▒▒▓▒▓▒▒▓▓▒▓▓ ▓▒▓▓▒▓▒▓▒▓▓▒▓▓ ▓▒▒░▒ ▓▒ ░ │ │ ▒░ ░ ░░ ▓▒░░░ █▓▓██▓▓████▓▓▓█▓░░▒▓▓▓▒▒▓░▓▓▓▒▓▒▒▒▓▒▓▓▓▓▒▒▒▒▒░▒▒▒░██ │ │▒ ▒▒ ▒░░░ ▓▓▓▓▒ ▓▓▓███▒███▓███▓▓▒▒░░▒▒▒▒░▒▒▒▒▒▓▓▒▒░▓▓▓▒▓░▓▓▓▒▒▒▓░▓▓▓ ░ ░ │ │▒ ░ ▓ ▓▓▓▓▒ ▓▒▓▓▓█▒███▓▓▓█▒▒▓▓███████▓▒▓░▒▓░▓▒▓▒▓▓▒▒▒▓░▒▒░ ░▒▓▒░ │ │▓ ░░ ░ █ ▓▓▓▓▓ ▓▓▓█▓▓▓███▓█▓█▓████████████░▓▓▓▓▒▓▓▓▓▒▒▓▒▒▒ ▓▓ ▓░ ░▓ ░ │ │▓ ░ ░ ▒▓▓▓▒▒ ▓▓▓█▓█▒██▓▓▓█▓█▓█▓██████████░▓▒▒▓▓▓▒▓▓▓▒ ▒▓ ▒ ░▒▓▓▓█ ░ │ │▓▒░░▒▒░▒ ░░▓▓▓▓▓ ▓▓▓███▓██████████████████████░░▓▒░▓▒▒▒▒▒▒▓▓░ ░▒▒░░ │ │▓ ░▓▒▒ ░░▒▓▒ ░▓▓█▓█▓█████████████████████▒░░ ░ ░ ░▒░ ░ ░ ░▓▒ │ └──────────────────────────────────────────────────────────────────────────────┘ unbourne is a gnu/systemd init process »cosmopolitan» ╔────────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ The UNBOURNE SHELL is BASED off the Almquist Shell──colloquially known as the Debian Almquist Shell, a.k.a. dash──which perfected the work of the late Stephen Bourne whose shell set the standard for decades thanks to a spark of brilliance from Ken Thompson. git://git.kernel.org/pub/scm/utils/dash/dash.git 057cd650a4edd5856213d431a974ff35c6594489 Fri Sep 03 15:00:58 2021 +0800 The UNBOURNE SHELL pays HOMAGE to the Stewards of House California: Almquist Shell Derived from software contributed to Berkeley by Kenneth Almquist. Copyright 1991,1993 The Regents of the University of California Copyright 1997-2021 Herbert Xu Copyright 1997 Christos Zoulas Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ╔──────────────────────────────────────────────────────────────────────┬───┬───╗ │ cosmopolitan § the unbourne shell » build / / │ ╚────────────────────────────────────────────────────────────────────'>/dev/null cc -Os -o unbourne unbourne.c exit ╔────────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » macros ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/dirent.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/tms.h" #include "libc/calls/termios.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/limits.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/alg.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" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/rlim.h" #include "libc/sysv/consts/s.h" #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) #define unlikely(expr) __builtin_expect(!!(expr), 0) #undef CEOF #undef rflag /* * The follow should be set to reflect the type of system you have: * JOBS -> 1 if you have Berkeley job control, 0 otherwise. * SHORTNAMES -> 1 if your linker cannot handle long names. * define BSD if you are running 4.2 BSD or later. * define SYSV if you are running under System V. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on) * define DEBUG=2 to compile in and turn on debugging. * define DO_SHAREDVFORK to indicate that vfork(2) shares its address * with its parent. * * When debugging is on, debugging info will be written to ./trace and * a quit signal will generate a core dump. */ #define ALIASDEAD 2 #define ALIASINUSE 1 #define ARITH_MAX_PREC 8 #define ATABSIZE 39 #define CMDTABLESIZE 31 #define JOBS 1 #define NOPTS 17 #define OUTPUT_ERR 01 #define VTABSIZE 39 /* exceptions */ #define EXINT 0 #define EXERROR 1 #define EXEND 3 #define EXEXIT 4 /* * The input line number. Input.c just defines this variable, and saves * and restores it when files are pushed and popped. The user of this * package must set its value. */ #define plinno (parsefile->linno) /* Syntax classes */ #define CWORD 0 #define CNL 1 #define CBACK 2 #define CSQUOTE 3 #define CDQUOTE 4 #define CENDQUOTE 5 #define CBQUOTE 6 #define CVAR 7 #define CENDVAR 8 #define CLP 9 #define CRP 10 #define CEOF 11 #define CCTL 12 #define CSPCL 13 /* Syntax classes for is_ functions */ #define ISDIGIT 01 #define ISUPPER 02 #define ISLOWER 04 #define ISUNDER 010 #define ISSPECL 020 #define SYNBASE 129 #define PEOF -129 #define EOF_NLEFT -99 #define BASESYNTAX (basesyntax + SYNBASE) #define DQSYNTAX (dqsyntax + SYNBASE) #define SQSYNTAX (sqsyntax + SYNBASE) #define ARISYNTAX (arisyntax + SYNBASE) #define ARITH_ASS 1 #define ARITH_OR 2 #define ARITH_AND 3 #define ARITH_BAD 4 #define ARITH_NUM 5 #define ARITH_VAR 6 #define ARITH_NOT 7 #define ARITH_BINOP_MIN 8 #define ARITH_LE 8 #define ARITH_GE 9 #define ARITH_LT 10 #define ARITH_GT 11 #define ARITH_EQ 12 #define ARITH_REM 13 #define ARITH_BAND 14 #define ARITH_LSHIFT 15 #define ARITH_RSHIFT 16 #define ARITH_MUL 17 #define ARITH_ADD 18 #define ARITH_BOR 19 #define ARITH_SUB 20 #define ARITH_BXOR 21 #define ARITH_DIV 22 #define ARITH_NE 23 #define ARITH_BINOP_MAX 24 #define ARITH_ASS_MIN 24 #define ARITH_REMASS 24 #define ARITH_BANDASS 25 #define ARITH_LSHIFTASS 26 #define ARITH_RSHIFTASS 27 #define ARITH_MULASS 28 #define ARITH_ADDASS 29 #define ARITH_BORASS 30 #define ARITH_SUBASS 31 #define ARITH_BXORASS 32 #define ARITH_DIVASS 33 #define ARITH_ASS_MAX 34 #define ARITH_LPAREN 34 #define ARITH_RPAREN 35 #define ARITH_BNOT 36 #define ARITH_QMARK 37 #define ARITH_COLON 38 /* expandarg() flags */ #define EXP_FULL 0x1 #define EXP_TILDE 0x2 #define EXP_VARTILDE 0x4 #define EXP_REDIR 0x8 #define EXP_CASE 0x10 #define EXP_VARTILDE2 0x40 #define EXP_WORD 0x80 #define EXP_QUOTED 0x100 #define EXP_KEEPNUL 0x200 #define EXP_DISCARD 0x400 /* reasons for skipping commands (see comment on breakcmd routine) */ #define SKIPBREAK (1 << 0) #define SKIPCONT (1 << 1) #define SKIPFUNC (1 << 2) #define SKIPFUNCDEF (1 << 3) #define TEOF 0 #define TNL 1 #define TSEMI 2 #define TBACKGND 3 #define TAND 4 #define TOR 5 #define TPIPE 6 #define TLP 7 #define TRP 8 #define TENDCASE 9 #define TENDBQUOTE 10 #define TREDIR 11 #define TWORD 12 #define TNOT 13 #define TCASE 14 #define TDO 15 #define TDONE 16 #define TELIF 17 #define TELSE 18 #define TESAC 19 #define TFI 20 #define TFOR 21 #define TIF 22 #define TIN 23 #define TTHEN 24 #define TUNTIL 25 #define TWHILE 26 #define TBEGIN 27 #define TEND 28 /* control characters in argument strings */ #define CTL_FIRST -127 #define CTLESC -127 #define CTLVAR -126 #define CTLENDVAR -125 #define CTLBACKQ -124 #define CTLARI -122 #define CTLENDARI -121 #define CTLQUOTEMARK -120 #define CTL_LAST -120 /* variable substitution byte (follows CTLVAR) */ #define VSTYPE 0x0f #define VSNUL 0x10 /* values of VSTYPE field */ #define VSNORMAL 0x1 #define VSMINUS 0x2 #define VSPLUS 0x3 #define VSQUESTION 0x4 #define VSASSIGN 0x5 #define VSTRIMRIGHT 0x6 #define VSTRIMRIGHTMAX 0x7 #define VSTRIMLEFT 0x8 #define VSTRIMLEFTMAX 0x9 #define VSLENGTH 0xa /* VSLENGTH must come last. */ /* values of checkkwd variable */ #define CHKALIAS 0x1 #define CHKKWD 0x2 #define CHKNL 0x4 #define CHKEOFMARK 0x8 /* flags in argument to evaltree */ #define EV_EXIT 01 #define EV_TESTED 02 #define INT_CHARS (sizeof(int) * CHAR_BIT / 3) /* * These macros allow the user to suspend the handling of interrupt * signals over a period of time. This is similar to SIGHOLD to or * sigblock, but much more efficient and portable. (But hacking the * kernel is so much more fun than worrying about efficiency and * portability. :-)) */ #define barrier() ({ asm volatile("" : : : "memory"); }) #define INTOFF \ ({ \ suppressint++; \ barrier(); \ 0; \ }) #define INTON \ ({ \ barrier(); \ if (--suppressint == 0 && intpending) onint(); \ 0; \ }) #define FORCEINTON \ ({ \ barrier(); \ suppressint = 0; \ if (intpending) onint(); \ 0; \ }) #define SAVEINT(v) ((v) = suppressint) #define RESTOREINT(v) \ ({ \ barrier(); \ if ((suppressint = (v)) == 0 && intpending) onint(); \ 0; \ }) #define CLEAR_PENDING_INT intpending = 0 #define int_pending() intpending /* * Most machines require the value returned from malloc to be aligned * in some way. The following macro will get this right on many machines. */ #define SHELL_SIZE \ (sizeof(union { \ int i; \ char *cp; \ double d; \ }) - \ 1) /* * It appears that grabstackstr() will barf with such alignments * because stalloc() will return a string allocated in a new stackblock. */ #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE) /* * Minimum size of a block * * Parse trees for commands are allocated in lifo order, so we use a stack * to make this more efficient, and also to avoid all sorts of exception * handling code to handle interrupts in the middle of a parse. * * The size 504 was chosen because the Ultrix malloc handles that size * well. */ #define MINSIZE SHELL_ALIGN(504) /* flags */ #define VEXPORT 0x001 #define VREADONLY 0x002 #define VSTRFIXED 0x004 #define VTEXTFIXED 0x008 #define VSTACK 0x010 #define VUNSET 0x020 #define VNOFUNC 0x040 #define VNOSET 0x080 #define VNOSAVE 0x100 /* * Evaluate a command. */ #define ALIASCMD (kBuiltinCmds + 3) #define BGCMD (kBuiltinCmds + 4) #define BREAKCMD (kBuiltinCmds + 5) #define CDCMD (kBuiltinCmds + 6) #define COMMANDCMD (kBuiltinCmds + 8) #define DOTCMD (kBuiltinCmds + 0) #define ECHOCMD (kBuiltinCmds + 10) #define EVALCMD (kBuiltinCmds + 11) #define EXECCMD (kBuiltinCmds + 12) #define EXITCMD (kBuiltinCmds + 13) #define EXPORTCMD (kBuiltinCmds + 14) #define FALSECMD (kBuiltinCmds + 15) #define FGCMD (kBuiltinCmds + 16) #define GETOPTSCMD (kBuiltinCmds + 17) #define HASHCMD (kBuiltinCmds + 18) #define JOBSCMD (kBuiltinCmds + 19) #define KILLCMD (kBuiltinCmds + 20) #define LOCALCMD (kBuiltinCmds + 21) #define PRINTFCMD (kBuiltinCmds + 22) #define PWDCMD (kBuiltinCmds + 23) #define READCMD (kBuiltinCmds + 24) #define RETURNCMD (kBuiltinCmds + 26) #define SETCMD (kBuiltinCmds + 27) #define SHIFTCMD (kBuiltinCmds + 28) #define TESTCMD (kBuiltinCmds + 2) #define TIMESCMD (kBuiltinCmds + 30) #define TRAPCMD (kBuiltinCmds + 31) #define TRUECMD (kBuiltinCmds + 1) #define TYPECMD (kBuiltinCmds + 33) #define ULIMITCMD (kBuiltinCmds + 34) #define UMASKCMD (kBuiltinCmds + 35) #define UNALIASCMD (kBuiltinCmds + 36) #define UNSETCMD (kBuiltinCmds + 37) #define WAITCMD (kBuiltinCmds + 38) #define BUILTIN_SPECIAL 0x1 #define BUILTIN_REGULAR 0x2 #define BUILTIN_ASSIGN 0x4 /* mode flags for set_curjob */ #define CUR_DELETE 2 #define CUR_RUNNING 1 #define CUR_STOPPED 0 /* mode flags for dowait */ #define DOWAIT_NONBLOCK 0 #define DOWAIT_BLOCK 1 #define DOWAIT_WAITCMD 2 #define DOWAIT_WAITCMD_ALL 4 /* _rmescape() flags */ #define RMESCAPE_ALLOC 0x01 #define RMESCAPE_GLOB 0x02 #define RMESCAPE_GROW 0x08 #define RMESCAPE_HEAP 0x10 /* Add CTLESC when necessary. */ #define QUOTES_ESC (EXP_FULL | EXP_CASE) #define IBUFSIZ (BUFSIZ + 1) #define OUTBUFSIZ BUFSIZ #define MEM_OUT -3 /* * Sigmode records the current value of the signal handlers for the * various modes. A value of zero means that the current handler is not * known. S_HARD_IGN indicates that the signal was ignored on entry to * the shell, */ #define S_DFL 1 #define S_CATCH 2 #define S_IGN 3 #define S_HARD_IGN 4 #define S_RESET 5 #define NCMD 0 #define NPIPE 1 #define NREDIR 2 #define NBACKGND 3 #define NSUBSHELL 4 #define NAND 5 #define NOR 6 #define NSEMI 7 #define NIF 8 #define NWHILE 9 #define NUNTIL 10 #define NFOR 11 #define NCASE 12 #define NCLIST 13 #define NDEFUN 14 #define NARG 15 #define NTO 16 #define NCLOBBER 17 #define NFROM 18 #define NFROMTO 19 #define NAPPEND 20 #define NTOFD 21 #define NFROMFD 22 #define NHERE 23 #define NXHERE 24 #define NNOT 25 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */ #define FORK_FG 0 #define FORK_BG 1 #define FORK_NOJOB 2 /* mode flags for showjob(s) */ #define SHOW_PGID 0x01 #define SHOW_PID 0x04 #define SHOW_CHANGED 0x08 /* values of cmdtype */ #define CMDUNKNOWN -1 #define CMDNORMAL 0 #define CMDFUNCTION 1 #define CMDBUILTIN 2 /* action to find_command() */ #define DO_ERR 0x01 #define DO_ABS 0x02 #define DO_NOFUNC 0x04 #define DO_ALTPATH 0x08 #define DO_REGBLTIN 0x10 /* flags passed to redirect */ #define REDIR_PUSH 01 #define REDIR_SAVEFD2 03 #define CD_PHYSICAL 1 #define CD_PRINT 2 #define EMPTY -2 #define CLOSED -1 #define PIPESIZE 4096 #define rootshell (!shlvl) #define eflag optlist[0] #define fflag optlist[1] #define Iflag optlist[2] #define iflag optlist[3] #define mflag optlist[4] #define nflag optlist[5] #define sflag optlist[6] #define xflag optlist[7] #define vflag optlist[8] #define Vflag optlist[9] #define Eflag optlist[10] #define Cflag optlist[11] #define aflag optlist[12] #define bflag optlist[13] #define uflag optlist[14] #define nolog optlist[15] #define debug optlist[16] /* Used by expandstr to get here-doc like behaviour. */ #define FAKEEOFMARK (char *)1 /* * This file is included by programs which are optionally built into the * shell. If SHELL is defined, we try to map the standard UNIX library * routines to ash routines using defines. */ #define Printf out1fmt #define INITARGS(argv) #define setprogname(s) #define getprogname() commandname #define setlocate(l, s) 0 #define equal(s1, s2) (!strcmp(s1, s2)) #define isodigit(c) ((c) >= '0' && (c) <= '7') #define octtobin(c) ((c) - '0') #define scopy(s1, s2) ((void)strcpy(s2, s1)) #define TRACE(param) /* #define TRACE(param) \ */ /* do { \ */ /* printf("TRACE: "); \ */ /* printf param; \ */ /* } while (0) */ #define TRACEV(param) #define digit_val(c) ((c) - '0') #define is_alpha(c) isalpha((unsigned char)(c)) #define is_digit(c) ((unsigned)((c) - '0') <= 9) #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c))) #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c))) #define is_special(c) ((is_type + SYNBASE)[(signed char)(c)] & (ISSPECL | ISDIGIT)) #define uninitialized_var(x) x = x /* suppress uninitialized warning w/o code */ /* * Shell variables. */ #define vifs varinit[0] #define vpath (&vifs)[1] #define vps1 (&vpath)[1] #define vps2 (&vps1)[1] #define vps4 (&vps2)[1] #define voptind (&vps4)[1] #define vlineno (&voptind)[1] #define defifs (defifsvar + 4) #define defpath (defpathvar + 36) /* * The following macros access the values of the above variables. They * have to skip over the name. They return the null string for unset * variables. */ #define ifsval() (vifs.text + 4) #define ifsset() ((vifs.flags & VUNSET) == 0) #define mailval() (vmail.text + 5) #define mpathval() (vmpath.text + 9) #define pathval() (vpath.text + 5) #define ps1val() (vps1.text + 4) #define ps2val() (vps2.text + 4) #define ps4val() (vps4.text + 4) #define optindval() (voptind.text + 7) #define linenoval() (vlineno.text + 7) #define mpathset() ((vmpath.flags & VUNSET) == 0) #define environment() listvars(VEXPORT, VUNSET, 0) /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » data structures ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ typedef void *pointer; struct redirtab { struct redirtab *next; int renamed[10]; }; /* * We enclose jmp_buf in a structure so that we can declare pointers to * jump locations. The global variable handler contains the location to * jump to when an exception occurs, and the global variable exception * contains a code identifying the exception. To implement nested * exception handlers, the user should save the value of handler on * entry to an inner scope, set handler to point to a jmploc structure * for the inner scope, and restore handler on exit from the scope. */ struct jmploc { jmp_buf loc; }; /* PEOF (the end of file marker) is defined in syntax.h */ enum { INPUT_PUSH_FILE = 1, INPUT_NOFILE_OK = 2, }; struct alias { struct alias *next; char *name; char *val; int flag; }; struct shparam { int nparam; /* # of positional parameters (without $0) */ unsigned char malloc; /* if parameter list dynamically allocated */ char **p; /* parameter list */ int optind; /* next parameter to be processed by getopts */ int optoff; /* used by getopts */ }; struct strpush { struct strpush *prev; /* preceding string on stack */ char *prevstring; int prevnleft; struct alias *ap; /* if push was associated with an alias */ char *string; /* remember the string since it may change */ struct strpush *spfree; /* Delay freeing so we can stop nested aliases. */ int lastc[2]; /* Remember last two characters for pungetc. */ int unget; /* Number of outstanding calls to pungetc. */ }; /* * The parsefile structure pointed to by the global variable parsefile * contains information about the current file being read. */ struct parsefile { struct parsefile *prev; /* preceding file on stack */ int linno; /* current line */ int fd; /* file descriptor (or -1 if string) */ int nleft; /* number of chars left in this line */ int lleft; /* number of chars left in this buffer */ char *nextc; /* next char in buffer */ char *buf; /* input buffer */ struct strpush *strpush; /* for pushing strings at this level */ struct strpush basestrpush; /* so pushing one is fast */ struct strpush *spfree; /* Delay freeing so we can stop nested aliases. */ int lastc[2]; /* Remember last two characters for pungetc. */ int unget; /* Number of outstanding calls to pungetc. */ }; struct output { char *nextc; char *end; char *buf; unsigned bufsize; int fd; int flags; }; struct heredoc { struct heredoc *next; /* next here document in list */ union node *here; /* redirection node */ char *eofmark; /* string indicating end of input */ int striptabs; /* if set, strip leading tabs */ }; struct synstack { const char *syntax; struct synstack *prev; struct synstack *next; int innerdq; int varpushed; int dblquote; int varnest; /* levels of variables expansion */ int parenlevel; /* levels of parens in arithmetic */ int dqvarnest; /* levels of variables expansion within double quotes */ }; struct procstat { int pid; /* process id */ int status; /* last process status from wait() */ char *cmd; /* text of command being run */ }; /* * A job structure contains information about a job. A job is either a * single process or a set of processes contained in a pipeline. In the * latter case, pidlist will be non-NULL, and will point to a -1 terminated * array of pids. */ struct job { struct procstat ps0; /* status of process */ struct procstat *ps; /* status or processes when more than one */ int stopstatus; /* status of a stopped job */ unsigned nprocs : 16, /* number of processes */ state : 8, #define JOBRUNNING 0 #define JOBSTOPPED 1 #define JOBDONE 2 sigint : 1, /* job was killed by SIGINT */ jobctl : 1, /* job running under job control */ waited : 1, /* true if this entry has been waited for */ used : 1, /* true if this entry is in used */ changed : 1; /* true if status has changed */ struct job *prev_job; /* previous job */ }; struct ncmd { int type; int linno; union node *assign; union node *args; union node *redirect; }; struct npipe { int type; int backgnd; struct nodelist *cmdlist; }; struct nredir { int type; int linno; union node *n; union node *redirect; }; struct nbinary { int type; union node *ch1; union node *ch2; }; struct nif { int type; union node *test; union node *ifpart; union node *elsepart; }; struct nfor { int type; int linno; union node *args; union node *body; char *var_; }; struct ncase { int type; int linno; union node *expr; union node *cases; }; struct nclist { int type; union node *next; union node *pattern; union node *body; }; struct ndefun { int type; int linno; char *text; union node *body; }; struct narg { int type; union node *next; char *text; struct nodelist *backquote; }; struct nfile { int type; union node *next; int fd; union node *fname; char *expfname; }; struct ndup { int type; union node *next; int fd; int dupfd; union node *vname; }; struct nhere { int type; union node *next; int fd; union node *doc; }; struct nnot { int type; union node *com; }; union node { int type; struct ncmd ncmd; struct npipe npipe; struct nredir nredir; struct nbinary nbinary; struct nif nif; struct nfor nfor; struct ncase ncase; struct nclist nclist; struct ndefun ndefun; struct narg narg; struct nfile nfile; struct ndup ndup; struct nhere nhere; struct nnot nnot; }; struct nodelist { struct nodelist *next; union node *n; }; struct funcnode { int count; union node n; }; struct localvar_list { struct localvar_list *next; struct localvar *lv; }; struct Var { struct Var *next; /* next entry in hash list */ int flags; /* flags are defined above */ const char *text; /* name=value */ void (*func)(const char *); /* function to be called when */ /* the variable gets set/unset */ }; struct localvar { struct localvar *next; /* next local variable in list */ struct Var *vp; /* the variable that was made local */ int flags; /* saved flags */ const char *text; /* saved text */ }; union yystype { int64_t val; char *name; }; struct strlist { struct strlist *next; char *text; }; struct arglist { struct strlist *list; struct strlist **lastp; }; /* * Structure specifying which parts of the string should be searched * for IFS characters. */ struct ifsregion { struct ifsregion *next; /* next region in list */ int begoff; /* offset of start of region */ int endoff; /* offset of end of region */ int nulonly; /* search for nul bytes only */ }; struct builtincmd { const char *name; int (*builtin)(int, char **); unsigned flags; }; struct cmdentry { int cmdtype; union param { int index; const struct builtincmd *cmd; struct funcnode *func; } u; }; struct tblentry { struct tblentry *next; /* next entry in hash chain */ union param param; /* definition of builtin function */ short cmdtype; /* index identifying command */ char rehash; /* if set, cd done since entry created */ char cmdname[]; /* name of command */ }; struct backcmd { /* result of evalbackcmd */ int fd; /* file descriptor to read from */ char *buf; /* buffer */ int nleft; /* number of chars in buffer */ struct job *jp; /* job structure for command */ }; struct stack_block { struct stack_block *prev; char space[MINSIZE]; }; struct stackmark { struct stack_block *stackp; char *stacknxt; unsigned stacknleft; }; struct limits { const char *name; int cmd; int factor; /* multiply by to get rlim_{cur,max} values */ char option; }; struct t_op { const char *op_text; short op_num, op_type; }; /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » bss ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static int inter; static char **argptr; /* argument list for builtin commands */ static char **gargv; static char **t_wp; static char *arg0; /* value of $0 */ static char *cmdnextc; static char *commandname; static char *expdest; /* output of current string */ static char *expdir; static char *funcstring; /* block to allocate strings from */ static char *minusc; /* argument to -c option */ static char *optionarg; /* set by nextopt (like getopt) */ static char *optptr; /* used by nextopt */ static char *trap[NSIG]; /* trap handler commands */ static char *wordtext; /* text of last word returned by readtoken */ static char basebuf[IBUFSIZ]; /* buffer for top level input file */ static char gotsig[NSIG - 1]; /* indicates specified signal received */ static char nullstr[1]; /* zero length string */ static char optlist[NOPTS]; static char sigmode[NSIG - 1]; /* current value of signal */ static const char *arith_buf; static const char *arith_startbuf; static const char *pathopt; static int back_exitstatus; /* exit status of backquoted command */ static int checkkwd; static int doprompt; /* if set, prompt the user */ static int errlinno; static int evalskip; /* set if we are skipping commands */ static int exception; static int exitstatus; /* exit status of last command */ static int funcblocksize; /* size of structures in function */ static int funcline; /* start line of function, or 0 if not in one */ static int funcstringsize; /* size of strings in node */ static int initialpgrp; /* pgrp of shell on invocation */ static int inps4; /* Prevent PS4 nesting. */ static int job_warning; static int jobctl; static int last_token; static int lasttoken; /* last token read */ static int lineno; static int loopnest; /* current loop nesting level */ static int needprompt; /* true if interactive and at start of line */ static int quoteflag; /* set if (part of) last token was quoted */ static int rootpid; static int rval; static int shlvl; static int skipcount; /* number of levels to skip */ static int suppressint; static int tokpushback; /* last token pushed back */ static int trapcnt; /* number of non-null traps */ static int ttyfd = -1; /* control terminal */ static int vforked; /* Set if we are in the vforked child */ static int whichprompt; /* 1 == PS1, 2 == PS2 */ static int backgndpid; /* pid of last background process */ static pointer funcblock; /* block to allocate function from */ static struct arglist exparg; /* holds expanded arg list */ static struct heredoc *heredoc; static struct heredoc *heredoclist; /* list of here documents to read */ static struct ifsregion *ifslastp; /* last struct in list */ static struct ifsregion ifsfirst; /* first struct in list of ifs regions */ static struct jmploc *handler; static struct jmploc main_handler; static struct job *curjob; /* current job */ static struct job *jobtab; /* array of jobs */ static struct localvar_list *localvar_stack; static struct nodelist *argbackq; /* list of back quote expressions */ static struct nodelist *backquotelist; static struct output preverrout; static struct parsefile basepf; /* top level input file */ static struct redirtab *redirlist; static struct shparam shellparam; /* current positional parameters */ static struct stack_block stackbase; static struct t_op const *t_wp_op; static struct tblentry **lastcmdentry; static struct tblentry *cmdtable[CMDTABLESIZE]; static struct Var *vartab[VTABSIZE]; static union node *redirnode; static union yystype yylval; static unsigned closed_redirs; /* Bit map of currently closed file descriptors. */ static unsigned expdir_max; static unsigned njobs; /* size of array */ static volatile sig_atomic_t gotsigchld; /* received SIGCHLD */ static volatile sig_atomic_t intpending; static volatile sig_atomic_t pending_sig; /* last pending signal */ static struct alias *atab[ATABSIZE]; /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » data ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static char *curdir = nullstr; /* current working directory */ static char *physdir = nullstr; /* physical working directory */ static char *sstrend = stackbase.space + MINSIZE; static char *stacknxt = stackbase.space; static char defifsvar[] = "IFS= \t\n"; static char defoptindvar[] = "OPTIND=1"; static char linenovar[sizeof("LINENO=") + INT_CHARS + 1] = "LINENO="; static int builtinloc = -1; /* index in path of %builtin, or -1 */ static int savestatus = -1; /* exit status of last command outside traps */ static struct output errout = {0, 0, 0, 0, 2, 0}; static struct output output = {0, 0, 0, OUTBUFSIZ, 1, 0}; static struct parsefile *parsefile = &basepf; /* current input file */ static struct stack_block *stackp = &stackbase; static unsigned stacknleft = MINSIZE; static struct output *out1 = &output; static struct output *out2 = &errout; /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » rodata ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ /* Array indicating which tokens mark the end of a list */ static const char tokendlist[] = { 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, }; static const char *const tokname[] = { "end of file", "newline", "\";\"", "\"&\"", "\"&&\"", "\"||\"", "\"|\"", "\"(\"", "\")\"", "\";;\"", "\"`\"", "redirection", "word", "\"!\"", "\"case\"", "\"do\"", "\"done\"", "\"elif\"", "\"else\"", "\"esac\"", "\"fi\"", "\"for\"", "\"if\"", "\"in\"", "\"then\"", "\"until\"", "\"while\"", "\"{\"", "\"}\"", }; static const char *const parsekwd[] = {"!", "case", "do", "done", "elif", "else", "esac", "fi", "for", "if", "in", "then", "until", "while", "{", "}"}; static const char defpathvar[] = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; static const char *const optnames[NOPTS] = { "errexit", "noglob", "ignoreeof", "interactive", "monitor", "noexec", "stdin", "xtrace", "verbose", "vi", "emacs", "noclobber", "allexport", "notify", "nounset", "nolog", "debug", }; static const char optletters[NOPTS] = { 'e', 'f', 'I', 'i', 'm', 'n', 's', 'x', 'v', 'V', 'E', 'C', 'a', 'b', 'u', 0, 0, }; static const char spcstr[] = " "; static const char snlfmt[] = "%s\n"; static const char qchars[] = {CTLESC, CTLQUOTEMARK, 0}; static const char illnum[] = "Illegal number: %s"; static const char homestr[] = "HOME"; static const char dolatstr[] = {CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'}; /* TODO(jart): What's wrong with varinit? */ #if defined(__GNUC__) || defined(__llvm__) #pragma GCC diagnostic ignored "-Warray-bounds" #endif /* Some macros depend on the order, add new variables to the end. */ static void changepath(const char *); static void getoptsreset(const char *); static struct Var varinit[] = { {0, VSTRFIXED | VTEXTFIXED, defifsvar, 0}, {0, VSTRFIXED | VTEXTFIXED, defpathvar, changepath}, {0, VSTRFIXED | VTEXTFIXED, "PS1=$ ", 0}, {0, VSTRFIXED | VTEXTFIXED, "PS2=> ", 0}, {0, VSTRFIXED | VTEXTFIXED, "PS4=+ ", 0}, {0, VSTRFIXED | VTEXTFIXED, defoptindvar, getoptsreset}, {0, VSTRFIXED | VTEXTFIXED, linenovar, 0}, }; static const char kPrec[ARITH_BINOP_MAX - ARITH_BINOP_MIN] = { #define ARITH_PRECEDENCE(OP, PREC) [OP - ARITH_BINOP_MIN] = PREC ARITH_PRECEDENCE(ARITH_MUL, 0), ARITH_PRECEDENCE(ARITH_DIV, 0), ARITH_PRECEDENCE(ARITH_REM, 0), ARITH_PRECEDENCE(ARITH_ADD, 1), ARITH_PRECEDENCE(ARITH_SUB, 1), ARITH_PRECEDENCE(ARITH_LSHIFT, 2), ARITH_PRECEDENCE(ARITH_RSHIFT, 2), ARITH_PRECEDENCE(ARITH_LT, 3), ARITH_PRECEDENCE(ARITH_LE, 3), ARITH_PRECEDENCE(ARITH_GT, 3), ARITH_PRECEDENCE(ARITH_GE, 3), ARITH_PRECEDENCE(ARITH_EQ, 4), ARITH_PRECEDENCE(ARITH_NE, 4), ARITH_PRECEDENCE(ARITH_BAND, 5), ARITH_PRECEDENCE(ARITH_BXOR, 6), ARITH_PRECEDENCE(ARITH_BOR, 7), #undef ARITH_PRECEDENCE }; static const short nodesize[26] /* clang-format off */ = { SHELL_ALIGN(sizeof(struct ncmd)), SHELL_ALIGN(sizeof(struct npipe)), SHELL_ALIGN(sizeof(struct nredir)), SHELL_ALIGN(sizeof(struct nredir)), SHELL_ALIGN(sizeof(struct nredir)), SHELL_ALIGN(sizeof(struct nbinary)), SHELL_ALIGN(sizeof(struct nbinary)), SHELL_ALIGN(sizeof(struct nbinary)), SHELL_ALIGN(sizeof(struct nif)), SHELL_ALIGN(sizeof(struct nbinary)), SHELL_ALIGN(sizeof(struct nbinary)), SHELL_ALIGN(sizeof(struct nfor)), SHELL_ALIGN(sizeof(struct ncase)), SHELL_ALIGN(sizeof(struct nclist)), SHELL_ALIGN(sizeof(struct ndefun)), SHELL_ALIGN(sizeof(struct narg)), SHELL_ALIGN(sizeof(struct nfile)), SHELL_ALIGN(sizeof(struct nfile)), SHELL_ALIGN(sizeof(struct nfile)), SHELL_ALIGN(sizeof(struct nfile)), SHELL_ALIGN(sizeof(struct nfile)), SHELL_ALIGN(sizeof(struct ndup)), SHELL_ALIGN(sizeof(struct ndup)), SHELL_ALIGN(sizeof(struct nhere)), SHELL_ALIGN(sizeof(struct nhere)), SHELL_ALIGN(sizeof(struct nnot)), } /* clang-format on */; /* syntax table used when not in quotes */ static const char basesyntax[] /* clang-format off */ = { CEOF, CWORD, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CSPCL, CNL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CSPCL, CWORD, CDQUOTE, CWORD, CVAR, CWORD, CSPCL, CSQUOTE, CSPCL, CSPCL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CSPCL, CSPCL, CWORD, CSPCL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CBACK, CWORD, CWORD, CWORD, CBQUOTE, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CSPCL, CENDVAR, CWORD, CWORD } /* clang-format on */; /* syntax table used when in double quotes */ static const char dqsyntax[] /* clang-format off */ = { CEOF, CWORD, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CNL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CENDQUOTE, CWORD, CVAR, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CWORD, CWORD, CCTL, CWORD, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CWORD, CWORD, CCTL, CWORD, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CBACK, CCTL, CWORD, CWORD, CBQUOTE, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CENDVAR, CCTL, CWORD } /* clang-format on */; /* syntax table used when in single quotes */ static const char sqsyntax[] /* clang-format off */ = { CEOF, CWORD, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CNL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CENDQUOTE, CWORD, CWORD, CCTL, CWORD, CWORD, CCTL, CWORD, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CWORD, CWORD, CCTL, CWORD, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CCTL, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CCTL, CWORD } /* clang-format on */; /* syntax table used when in arithmetic */ static const char arisyntax[] /* clang-format off */ = { CEOF, CWORD, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CCTL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CNL, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CVAR, CWORD, CWORD, CWORD, CLP, CRP, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CBACK, CWORD, CWORD, CWORD, CBQUOTE, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CWORD, CENDVAR, CWORD, CWORD } /* clang-format on */; /* character classification table */ static const char is_type[] /* clang-format off */ = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ISSPECL, 0, ISSPECL, ISSPECL, 0, 0, 0, 0, 0, ISSPECL, 0, 0, ISSPECL, 0, 0, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, ISDIGIT, 0, 0, 0, 0, 0, ISSPECL, ISSPECL, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, ISUPPER, 0, 0, 0, 0, ISUNDER, 0, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, ISLOWER, 0, 0, 0, 0, 0 } /* clang-format on */; static int aliascmd(); static int bgcmd(); static int breakcmd(); static int cdcmd(); static int commandcmd(); static int dotcmd(); static int echocmd(); static int evalcmd(); static int execcmd(); static int exitcmd(); static int exportcmd(); static int falsecmd(); static int fgcmd(); static int getoptscmd(); static int hashcmd(); static int jobscmd(); static int killcmd(); static int localcmd(); static int printfcmd(); static int pwdcmd(); static int readcmd(); static int returncmd(); static int setcmd(); static int shiftcmd(); static int testcmd(); static int timescmd(); static int trapcmd(); static int truecmd(); static int typecmd(); static int ulimitcmd(); static int umaskcmd(); static int unaliascmd(); static int unsetcmd(); static int waitcmd(); static const struct builtincmd kBuiltinCmds[] = { {".", dotcmd, 3}, // {":", truecmd, 3}, // {"[", testcmd, 0}, // {"alias", aliascmd, 6}, // {"bg", bgcmd, 2}, // {"break", breakcmd, 3}, // {"cd", cdcmd, 2}, // {"chdir", cdcmd, 0}, // {"command", commandcmd, 2}, // {"continue", breakcmd, 3}, // {"echo", echocmd, 0}, // {"eval", NULL, 3}, // {"exec", execcmd, 3}, // {"exit", exitcmd, 3}, // {"export", exportcmd, 7}, // {"false", falsecmd, 2}, // {"fg", fgcmd, 2}, // {"getopts", getoptscmd, 2}, // {"hash", hashcmd, 2}, // {"jobs", jobscmd, 2}, // {"kill", killcmd, 2}, // {"local", localcmd, 7}, // {"printf", printfcmd, 0}, // {"pwd", pwdcmd, 2}, // {"read", readcmd, 2}, // {"readonly", exportcmd, 7}, // {"return", returncmd, 3}, // {"set", setcmd, 3}, // {"shift", shiftcmd, 3}, // {"test", testcmd, 0}, // {"times", timescmd, 3}, // {"trap", trapcmd, 3}, // {"true", truecmd, 2}, // {"type", typecmd, 2}, // {"ulimit", ulimitcmd, 2}, // {"umask", umaskcmd, 2}, // {"unalias", unaliascmd, 2}, // {"unset", unsetcmd, 3}, // {"wait", waitcmd, 2}, // }; enum token { EOI, FILRD, FILWR, FILEX, FILEXIST, FILREG, FILDIR, FILCDEV, FILBDEV, FILFIFO, FILSOCK, FILSYM, FILGZ, FILTT, FILSUID, FILSGID, FILSTCK, FILNT, FILOT, FILEQ, FILUID, FILGID, STREZ, STRNZ, STREQ, STRNE, STRLT, STRGT, INTEQ, INTNE, INTGE, INTGT, INTLE, INTLT, UNOT, BAND, BOR, LPAREN, RPAREN, OPERAND }; enum token_types { UNOP, BINOP, BUNOP, BBINOP, PAREN }; static struct t_op const ops[] = { {"-r", FILRD, UNOP}, {"-w", FILWR, UNOP}, {"-x", FILEX, UNOP}, {"-e", FILEXIST, UNOP}, {"-f", FILREG, UNOP}, {"-d", FILDIR, UNOP}, {"-c", FILCDEV, UNOP}, {"-b", FILBDEV, UNOP}, {"-p", FILFIFO, UNOP}, {"-u", FILSUID, UNOP}, {"-g", FILSGID, UNOP}, {"-k", FILSTCK, UNOP}, {"-s", FILGZ, UNOP}, {"-t", FILTT, UNOP}, {"-z", STREZ, UNOP}, {"-n", STRNZ, UNOP}, {"-h", FILSYM, UNOP}, /* for backwards compat */ {"-O", FILUID, UNOP}, {"-G", FILGID, UNOP}, {"-L", FILSYM, UNOP}, {"-S", FILSOCK, UNOP}, {"=", STREQ, BINOP}, {"!=", STRNE, BINOP}, {"<", STRLT, BINOP}, {">", STRGT, BINOP}, {"-eq", INTEQ, BINOP}, {"-ne", INTNE, BINOP}, {"-ge", INTGE, BINOP}, {"-gt", INTGT, BINOP}, {"-le", INTLE, BINOP}, {"-lt", INTLT, BINOP}, {"-nt", FILNT, BINOP}, {"-ot", FILOT, BINOP}, {"-ef", FILEQ, BINOP}, {"!", UNOT, BUNOP}, {"-a", BAND, BBINOP}, {"-o", BOR, BBINOP}, {"(", LPAREN, PAREN}, {")", RPAREN, PAREN}, {0, 0, 0}, }; /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » text ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ /* * Hack to calculate maximum length. * (length * 8 - 1) * log10(2) + 1 + 1 + 12 * The second 1 is for the minus sign and the 12 is a safety margin. */ static inline int max_int_length(int bytes) { return (bytes * 8 - 1) * 0.30102999566398119521 + 14; } /* prefix -- see if pfx is a prefix of string. */ static char *prefix(const char *string, const char *pfx) { while (*pfx) { if (*pfx++ != *string++) return 0; } return (char *)string; } /* * Wrapper around strcmp for qsort/bsearch/... */ static int pstrcmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } /* * Find a string is in a sorted array. */ static const char *const *findstring(const char *s, const char *const *array, unsigned nmemb) { return bsearch(&s, array, nmemb, sizeof(const char *), pstrcmp); } /* Types of operations (passed to the errmsg routine). */ enum ShErrorAction { E_OPEN, E_CREAT, E_EXEC }; /* * Return a string describing an error. The returned string may be a * pointer to a static buffer that will be overwritten on the next call. * Action describes the operation that got the error. */ static const char *errmsg(int e, enum ShErrorAction action) { if (e != ENOENT && e != ENOTDIR) return strerror(e); switch (action) { case E_OPEN: return "No such file"; case E_CREAT: return "Directory nonexistent"; default: return "not found"; } } static inline void sigclearmask(void) { sigset_t set; sigemptyset(&set); sigprocmask(SIG_SETMASK, &set, 0); } /* * Called to raise an exception. Since C doesn't include exceptions, we * just do a longjmp to the exception handler. The type of exception is * stored in the global variable "exception". */ wontreturn static void exraise(int e) { if (vforked) _exit(exitstatus); INTOFF; exception = e; longjmp(handler->loc, 1); } /* * Called from trap.c when a SIGINT is received. (If the user specifies * that SIGINT is to be trapped or ignored using the trap builtin, then * this routine is not called.) Suppressint is nonzero when interrupts * are held using the INTOFF macro. (The test for iflag is just * defensive programming.) */ wontreturn static void onint(void) { intpending = 0; sigclearmask(); if (!(rootshell && iflag)) { signal(SIGINT, SIG_DFL); raise(SIGINT); } exitstatus = SIGINT + 128; exraise(EXINT); } static pointer ckmalloc(unsigned nbytes) { pointer p; if (!(p = malloc(nbytes))) abort(); return p; } static pointer ckrealloc(pointer p, unsigned nbytes) { if (!(p = realloc(p, nbytes))) abort(); return p; } #define stackblock() ((void *)stacknxt) #define stackblocksize() stacknleft #define STARTSTACKSTR(p) ((p) = stackblock()) #define STPUTC(c, p) ((p) = _STPUTC((c), (p))) #define CHECKSTRSPACE(n, p) \ ({ \ char *q = (p); \ unsigned l = (n); \ unsigned m = sstrend - q; \ if (l > m) (p) = makestrspace(l, q); \ 0; \ }) #define USTPUTC(c, p) (*p++ = (c)) #define STACKSTRNUL(p) ((p) == sstrend ? (p = growstackstr(), *p = '\0') : (*p = '\0')) #define STUNPUTC(p) (--p) #define STTOPC(p) p[-1] #define STADJUST(amount, p) (p += (amount)) #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock()) #define ungrabstackstr(s, p) stunalloc((s)) #define stackstrend() ((void *)sstrend) #define ckfree(p) free((pointer)(p)) static pointer stalloc(unsigned nbytes) { char *p; unsigned aligned; aligned = SHELL_ALIGN(nbytes); if (aligned > stacknleft) { unsigned len; unsigned blocksize; struct stack_block *sp; blocksize = aligned; if (blocksize < MINSIZE) blocksize = MINSIZE; len = sizeof(struct stack_block) - MINSIZE + blocksize; if (len < blocksize) abort(); INTOFF; sp = ckmalloc(len); sp->prev = stackp; stacknxt = sp->space; stacknleft = blocksize; sstrend = stacknxt + blocksize; stackp = sp; INTON; } p = stacknxt; stacknxt += aligned; stacknleft -= aligned; return p; } static inline void grabstackblock(unsigned len) { stalloc(len); } static void pushstackmark(struct stackmark *mark, unsigned len) { mark->stackp = stackp; mark->stacknxt = stacknxt; mark->stacknleft = stacknleft; grabstackblock(len); } static void popstackmark(struct stackmark *mark) { struct stack_block *sp; INTOFF; while (stackp != mark->stackp) { sp = stackp; stackp = sp->prev; ckfree(sp); } stacknxt = mark->stacknxt; stacknleft = mark->stacknleft; sstrend = mark->stacknxt + mark->stacknleft; INTON; } static void setstackmark(struct stackmark *mark) { pushstackmark(mark, stacknxt == stackp->space && stackp != &stackbase); } static void stunalloc(pointer p) { stacknleft += stacknxt - (char *)p; stacknxt = p; } /* Like strdup but works with the ash stack. */ static char *sstrdup(const char *p) { unsigned len = strlen(p) + 1; return memcpy(stalloc(len), p, len); } int xwrite(int, const void *, uint64_t); static void flushout(struct output *dest) { unsigned len; len = dest->nextc - dest->buf; if (!len || dest->fd < 0) return; dest->nextc = dest->buf; if ((xwrite(dest->fd, dest->buf, len))) dest->flags |= OUTPUT_ERR; } static void flushall(void) { flushout(&output); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » output routines ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ When a builtin command is interrupted we have to discard any pending output. When a builtin command appears in back quotes, we want to save the output of the command in a region obtained via malloc, rather than doing a fork and reading the output of the command via a pipe. */ static int xvsnprintf(char *outbuf, unsigned length, const char *fmt, va_list ap) { int ret; INTOFF; ret = vsnprintf(outbuf, length, fmt, ap); INTON; return ret; } static int xvasprintf(char **sp, unsigned size, const char *f, va_list ap) { char *s; int len; va_list ap2; va_copy(ap2, ap); len = xvsnprintf(*sp, size, f, ap2); va_end(ap2); if (len < 0) abort(); if (len < size) return len; s = stalloc((len >= stackblocksize() ? len : stackblocksize()) + 1); *sp = s; len = xvsnprintf(s, len + 1, f, ap); return len; } static void outmem(const char *p, unsigned len, struct output *dest) { unsigned bufsize; unsigned offset; unsigned nleft; nleft = dest->end - dest->nextc; if (likely(nleft >= len)) { buffered: dest->nextc = mempcpy(dest->nextc, p, len); return; } bufsize = dest->bufsize; if (!bufsize) { (void)0; } else if (dest->buf == NULL) { offset = 0; INTOFF; dest->buf = ckrealloc(dest->buf, bufsize); dest->bufsize = bufsize; dest->end = dest->buf + bufsize; dest->nextc = dest->buf + offset; INTON; } else { flushout(dest); } nleft = dest->end - dest->nextc; if (nleft > len) goto buffered; if ((xwrite(dest->fd, p, len))) { dest->flags |= OUTPUT_ERR; } } static void outstr(const char *p, struct output *file) { unsigned len; len = strlen(p); outmem(p, len, file); } static void outcslow(int c, struct output *dest) { char buf = c; outmem(&buf, 1, dest); } printfesque(3) static int fmtstr(char *outbuf, unsigned length, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = xvsnprintf(outbuf, length, fmt, ap); va_end(ap); return ret > (int)length ? length : ret; } printfesque(2) static int Xasprintf(char **sp, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = xvasprintf(sp, 0, fmt, ap); va_end(ap); return ret; } static void doformat(struct output *dest, const char *f, va_list ap) { struct stackmark smark; char *s; int len; int olen; setstackmark(&smark); s = dest->nextc; olen = dest->end - dest->nextc; len = xvasprintf(&s, olen, f, ap); if (likely(olen > len)) { dest->nextc += len; goto out; } outmem(s, len, dest); out: popstackmark(&smark); } printfesque(1) static void out1fmt(const char *fmt, ...) { va_list ap; va_start(ap, fmt); doformat(out1, fmt, ap); va_end(ap); } printfesque(2) static void outfmt(struct output *file, const char *fmt, ...) { va_list ap; va_start(ap, fmt); doformat(file, fmt, ap); va_end(ap); } static void exvwarning(const char *msg, va_list ap) { struct output *errs; const char *name; const char *fmt; errs = out2; name = arg0 ? arg0 : "sh"; if (!commandname) { fmt = "%s: %d: "; } else { fmt = "%s: %d: %s: "; } outfmt(errs, fmt, name, errlinno, commandname); doformat(errs, msg, ap); outcslow('\n', errs); } /* error/warning routines for external builtins */ printfesque(1) static void sh_warnx(const char *fmt, ...) { va_list ap; va_start(ap, fmt); exvwarning(fmt, ap); va_end(ap); } /* * Exverror is called to raise the error exception. If the second argument * is not NULL then error prints an error message using printf style * formatting. It then raises the error exception. */ wontreturn static void exverror(int cond, const char *msg, va_list ap) { exvwarning(msg, ap); flushall(); exraise(cond); } wontreturn static void exerror(int cond, const char *msg, ...) { va_list ap; va_start(ap, msg); exverror(cond, msg, ap); va_end(ap); } wontreturn static void sh_error(const char *msg, ...) { va_list ap; exitstatus = 2; va_start(ap, msg); exverror(EXERROR, msg, ap); va_end(ap); } wontreturn static void badnum(const char *s) { sh_error(illnum, s); } wontreturn static void synerror(const char *msg) { errlinno = plinno; sh_error("Syntax error: %s", msg); } wontreturn static void yyerror(const char *s) { sh_error("arithmetic expression: %s: \"%s\"", s, arith_startbuf); } /* * Called when an unexpected token is read during the parse. The * argument is the token that is expected, or -1 if more than one type * of token can occur at this point. */ wontreturn static void synexpect(int token) { char msg[64]; if (token >= 0) { fmtstr(msg, 64, "%s unexpected (expecting %s)", tokname[lasttoken], tokname[token]); } else { fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]); } synerror(msg); } wontreturn static void varunset(const char *end, const char *var_, const char *umsg, int varflags) { const char *msg; const char *tail; tail = nullstr; msg = "parameter not set"; if (umsg) { if (*end == (char)CTLENDVAR) { if (varflags & VSNUL) tail = " or null"; } else msg = umsg; } sh_error("%.*s: %s%s", end - var_ - 1, var_, msg, tail); } /* * Convert a string into an integer of type int64. Allow trailing spaces. */ static int64_t atomax(const char *s, int base) { char *p; int64_t r; errno = 0; r = strtoimax(s, &p, base); if (errno == ERANGE) badnum(s); /* * Disallow completely blank strings in non-arithmetic (base != 0) * contexts. */ if (p == s && base) badnum(s); while (isspace((unsigned char)*p)) p++; if (*p) badnum(s); return r; } static int64_t atomax10(const char *s) { return atomax(s, 10); } /* * Convert a string of digits to an integer, printing an error message * on failure. */ static int number(const char *s) { int64_t n = atomax10(s); if (n < 0 || n > INT_MAX) badnum(s); return n; } static inline int64_t getn(const char *s) { return atomax10(s); } /* * When the parser reads in a string, it wants to stick the string on * the stack and only adjust the stack pointer when it knows how big the * string is. Stackblock (defined in stack.h) returns a pointer to a * block of space on top of the stack and stackblocklen returns the * length of this block. Growstackblock will grow this space by at least * one byte, possibly moving it (like realloc). Grabstackblock actually * allocates the part of the block that has been used. */ static void growstackblock(unsigned min) { unsigned newlen; newlen = stacknleft * 2; if (newlen < stacknleft) sh_error("Out of space"); min = SHELL_ALIGN(min | 128); if (newlen < min) newlen += min; if (stacknxt == stackp->space && stackp != &stackbase) { struct stack_block *sp; struct stack_block *prevstackp; unsigned grosslen; INTOFF; sp = stackp; prevstackp = sp->prev; grosslen = newlen + sizeof(struct stack_block) - MINSIZE; sp = ckrealloc((pointer)sp, grosslen); sp->prev = prevstackp; stackp = sp; stacknxt = sp->space; stacknleft = newlen; sstrend = sp->space + newlen; INTON; } else { char *oldspace = stacknxt; int oldlen = stacknleft; char *p = stalloc(newlen); /* free the space we just allocated */ stacknxt = memcpy(p, oldspace, oldlen); stacknleft += newlen; } } /* * The following routines are somewhat easier to use than the above. The * user declares a variable of type STACKSTR, which may be declared to * be a register. The macro STARTSTACKSTR initializes things. Then the * user uses the macro STPUTC to add characters to the string. In * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is * grown as necessary. When the user is done, she can just leave the * string there and refer to it using stackblock(). Or she can allocate * the space for it using grabstackstr(). If it is necessary to allow * someone else to use the stack temporarily and then continue to grow * the string, the user should use grabstack to allocate the space, and * then call ungrabstr(p) to return to the previous mode of operation. * * USTPUTC is like STPUTC except that it doesn't check for overflow. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there * is space for at least one character. */ static void *growstackstr(void) { unsigned len = stackblocksize(); growstackblock(0); return (char *)stackblock() + len; } static char *growstackto(unsigned len) { if (stackblocksize() < len) growstackblock(len); return stackblock(); } /* * Make a copy of a string in safe storage. */ static char *savestr(const char *s) { char *p = strdup(s); if (!p) sh_error("Out of space"); return p; } /* Called from CHECKSTRSPACE. */ static char *makestrspace(unsigned newlen, char *p) { unsigned len = p - stacknxt; return growstackto(len + newlen) + len; } static char *stnputs(const char *s, unsigned n, char *p) { p = makestrspace(n, p); p = mempcpy(p, s, n); return p; } static char *stputs(const char *s, char *p) { return stnputs(s, strlen(s), p); } static char *nodesavestr(s) char *s; { char *rtn = funcstring; funcstring = stpcpy(funcstring, s) + 1; return rtn; } wontreturn static void shellexec(char **, const char *, int); static char **listvars(int, int, char ***); static char *argstr(char *p, int flag); static char *conv_escape(char *, int *); static char *evalvar(char *, int); static char *expari(char *start, int flag); static char *exptilde(char *startp, int flag); static int shlex(void); static char *lookupvar(const char *); static char *mklong(const char *, const char *); static char *rmescapes(char *, int); static char *scanleft(char *, char *, char *, char *, int, int); static char *scanright(char *, char *, char *, char *, int, int); static char *single_quote(const char *); static const char *const *findkwd(const char *); static const char *expandstr(const char *); static const char *getprompt(void *); static double getdouble(void); static enum token t_lex(char **); static int aexpr(enum token); static int binop0(void); static int bltincmd(int, char **); static int conv_escape_str(char *, char **); static int decode_signal(const char *, int); static int decode_signum(const char *); static int describe_command(struct output *, char *, const char *, int); static int eprintlist(struct output *, struct strlist *, int); static int equalf(const char *, const char *); static int evalbltin(const struct builtincmd *, int, char **, int); static int evalcase(union node *, int); static int evalcommand(union node *, int); static int evalfor(union node *, int); static int evalfun(struct funcnode *, int, char **, int); static int evalloop(union node *, int); static int evalpipe(union node *, int); static int evalsubshell(union node *, int); static int filstat(char *, enum token); static int forkshell(struct job *, union node *, int); static int getopts(char *, char *, char **); static int isassignment(const char *p); static int isoperand(char **); static int newerf(const char *, const char *); static int nexpr(enum token); static int nextopt(const char *); static int oexpr(enum token); static int olderf(const char *, const char *); static int64_t openhere(union node *); static int openredirect(union node *); static int options(int); static int padvance_magic(const char **, const char *, int); static int patmatch(char *, const char *); static int pgetc(void); static int pgetc_eatbnl(); static int pmatch(const char *, const char *); static int preadbuffer(void); static ssize_t preadfd(void); static int primary1(enum token); static int procargs(int, char **); static int readtoken(void); static int readtoken1(int, char const *, char *, int); static int redirectsafe(union node *, int); static int savefd(int, int); static int setinputfile(const char *, int); static int sh_open(const char *pathname, int flags, int mayfail); static int showvars(const char *, int, int); static int stoppedjobs(void); static int test_file_access(const char *, int); static int unalias(const char *); static int waitforjob(struct job *); static int xxreadtoken(void); static int64_t arith(const char *); static int64_t assignment(int var_, int noeval); static int64_t lookupvarint(const char *); static long varvalue(char *, int, int, int); static int64_t setvarint(const char *name, int64_t val, int flags); static struct Var *setvar(const char *name, const char *val, int flags); static struct Var *setvareq(char *s, int flags); static struct alias **__lookupalias(const char *); static struct alias *freealias(struct alias *); static struct alias *lookupalias(const char *, int); static struct funcnode *copyfunc(union node *); static struct job *makejob(union node *, int); static struct job *vforkexec(union node *n, char **argv, const char *path, int idx); static struct localvar_list *pushlocalvars(int push); static struct nodelist *copynodelist(struct nodelist *); static struct redirtab *pushredir(union node *redir); static struct strlist *expsort(struct strlist *); static struct strlist *msort(struct strlist *, int); static struct tblentry *cmdlookup(const char *, int); static uint64_t getuintmax(int); static union node *andor(void); static union node *command(void); static union node *copynode(union node *); static union node *list(int); static union node *makename(void); static union node *parsecmd(int); static union node *pipeline(void); static union node *simplecmd(void); static unsigned esclen(const char *, const char *); static unsigned memtodest(const char *p, unsigned len, int flags); static unsigned strtodest(const char *p, int flags); static void addcmdentry(char *, struct cmdentry *); static void addfname(char *); static void check_conversion(const char *, const char *); static void clearcmdentry(void); static void defun(union node *); static void delete_cmd_entry(void); static void dotrap(void); static void dupredirect(union node *, int); static void exitreset(void); static void expandarg(union node *arg, struct arglist *arglist, int flag); static void expandmeta(struct strlist *); static void expbackq(union node *, int); static void expmeta(char *, unsigned, unsigned); static void expredir(union node *); static void find_command(char *, struct cmdentry *, int, const char *); static void fixredir(union node *, const char *, int); static void forkreset(void); static void freeparam(volatile struct shparam *); static void hashcd(void); static void ignoresig(int); static void init(void); static void minus_o(char *, int); static void mklocal(char *name, int flags); static void onsig(int); static void optschanged(void); static void parsefname(void); static void parseheredoc(void); static void popallfiles(void); static void popfile(void); static void poplocalvars(void); static void popredir(int); static void popstring(void); static void prehash(union node *); static void printalias(const struct alias *); static void printentry(struct tblentry *); static void pungetc(void); static void pushfile(void); static void pushstring(char *, void *); static void read_profile(const char *); static void redirect(union node *, int); static void reset(void); static void rmaliases(void); static void setalias(const char *, const char *); static void setinputfd(int fd, int push); static void setinputstring(char *); static void setinteractive(int); static void setjobctl(int); static void setparam(char **); static void setprompt(int); static void setsignal(int); static void showjobs(struct output *, int); static void sigblockall(sigset_t *oldmask); static void sizenodelist(struct nodelist *); static void syntax(const char *, const char *); static void tryexec(char *, char **, char **); static void unsetfunc(const char *); static void unsetvar(const char *); static void unwindfiles(struct parsefile *); static void unwindlocalvars(struct localvar_list *stop); static void unwindredir(struct redirtab *stop); static unsigned cvtnum(int64_t num, int flags); static int getchr(void) { int val = 0; if (*gargv) val = **gargv++; return val; } static char *getstr(void) { char *val = nullstr; if (*gargv) val = *gargv++; return val; } /* * Check for a valid number. This should be elsewhere. */ static int is_number(const char *p) { do { if (!is_digit(*p)) return 0; } while (*++p != '\0'); return 1; } static inline void freestdout() { output.nextc = output.buf; output.flags = 0; } static inline void outc(int ch, struct output *file) { if (file->nextc == file->end) outcslow(ch, file); else { *file->nextc = ch; file->nextc++; } } static inline char *_STPUTC(int c, char *p) { if (p == sstrend) p = growstackstr(); *p++ = c; return p; } static void ifsfree(void) { struct ifsregion *p = ifsfirst.next; if (!p) goto out; INTOFF; do { struct ifsregion *ifsp; ifsp = p->next; ckfree(p); p = ifsp; } while (p); ifsfirst.next = NULL; INTON; out: ifslastp = NULL; } static void setalias(const char *name, const char *val) { struct alias *ap, **app; app = __lookupalias(name); ap = *app; INTOFF; if (ap) { if (!(ap->flag & ALIASINUSE)) { ckfree(ap->val); } ap->val = savestr(val); ap->flag &= ~ALIASDEAD; } else { /* not found */ ap = ckmalloc(sizeof(struct alias)); ap->name = savestr(name); ap->val = savestr(val); ap->flag = 0; ap->next = 0; *app = ap; } INTON; } static int unalias(const char *name) { struct alias **app; app = __lookupalias(name); if (*app) { INTOFF; *app = freealias(*app); INTON; return (0); } return (1); } static void rmaliases(void) { struct alias *ap, **app; int i; INTOFF; for (i = 0; i < ATABSIZE; i++) { app = &atab[i]; for (ap = *app; ap; ap = *app) { *app = freealias(*app); if (ap == *app) { app = &ap->next; } } } INTON; } struct alias *lookupalias(const char *name, int check) { struct alias *ap = *__lookupalias(name); if (check && ap && (ap->flag & ALIASINUSE)) return (NULL); return (ap); } static int aliascmd(int argc, char **argv) { /* TODO - sort output */ char *n, *v; int ret = 0; struct alias *ap; if (argc == 1) { int i; for (i = 0; i < ATABSIZE; i++) for (ap = atab[i]; ap; ap = ap->next) { printalias(ap); } return (0); } while ((n = *++argv) != NULL) { if ((v = strchr(n + 1, '=')) == NULL) { /* n+1: funny ksh stuff */ if ((ap = *__lookupalias(n)) == NULL) { outfmt(out2, "%s: %s not found\n", "alias", n); ret = 1; } else printalias(ap); } else { *v++ = '\0'; setalias(n, v); } } return (ret); } static int unaliascmd(int argc, char **argv) { int i; while ((i = nextopt("a")) != '\0') { if (i == 'a') { rmaliases(); return (0); } } for (i = 0; *argptr; argptr++) { if (unalias(*argptr)) { outfmt(out2, "%s: %s not found\n", "unalias", *argptr); i = 1; } } return i; } static struct alias *freealias(struct alias *ap) { struct alias *next; if (ap->flag & ALIASINUSE) { ap->flag |= ALIASDEAD; return ap; } next = ap->next; ckfree(ap->name); ckfree(ap->val); ckfree(ap); return next; } static void printalias(const struct alias *ap) { out1fmt("%s=%s\n", ap->name, single_quote(ap->val)); } static struct alias **__lookupalias(const char *name) { unsigned int hashval; struct alias **app; const char *p; unsigned int ch; p = name; ch = (unsigned char)*p; hashval = ch << 4; while (ch) { hashval += ch; ch = (unsigned char)*++p; } app = &atab[hashval % ATABSIZE]; for (; *app; app = &(*app)->next) { if (equal(name, (*app)->name)) { break; } } return app; } static int shlex() { int value; const char *buf = arith_buf; const char *p; for (;;) { value = *buf; switch (value) { case ' ': case '\t': case '\n': buf++; continue; default: return ARITH_BAD; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yylval.val = strtoimax(buf, (char **)&arith_buf, 0); return ARITH_NUM; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': p = buf; while (buf++, is_in_name(*buf)) ; yylval.name = stalloc(buf - p + 1); *(char *)mempcpy(yylval.name, p, buf - p) = 0; value = ARITH_VAR; goto out; case '=': value += ARITH_ASS - '='; checkeq: buf++; checkeqcur: if (*buf != '=') goto out; value += 11; break; case '>': switch (*++buf) { case '=': value += ARITH_GE - '>'; break; case '>': value += ARITH_RSHIFT - '>'; goto checkeq; default: value += ARITH_GT - '>'; goto out; } break; case '<': switch (*++buf) { case '=': value += ARITH_LE - '<'; break; case '<': value += ARITH_LSHIFT - '<'; goto checkeq; default: value += ARITH_LT - '<'; goto out; } break; case '|': if (*++buf != '|') { value += ARITH_BOR - '|'; goto checkeqcur; } value += ARITH_OR - '|'; break; case '&': if (*++buf != '&') { value += ARITH_BAND - '&'; goto checkeqcur; } value += ARITH_AND - '&'; break; case '!': if (*++buf != '=') { value += ARITH_NOT - '!'; goto out; } value += ARITH_NE - '!'; break; case 0: goto out; case '(': value += ARITH_LPAREN - '('; break; case ')': value += ARITH_RPAREN - ')'; break; case '*': value += ARITH_MUL - '*'; goto checkeq; case '/': value += ARITH_DIV - '/'; goto checkeq; case '%': value += ARITH_REM - '%'; goto checkeq; case '+': value += ARITH_ADD - '+'; goto checkeq; case '-': value += ARITH_SUB - '-'; goto checkeq; case '~': value += ARITH_BNOT - '~'; break; case '^': value += ARITH_BXOR - '^'; goto checkeq; case '?': value += ARITH_QMARK - '?'; break; case ':': value += ARITH_COLON - ':'; break; } break; } buf++; out: arith_buf = buf; return value; } /* * Compares two strings up to the first = or '\0'. The first string must * be terminated by '='; the second may be terminated by either '=' or * '\0'. */ static int varcmp(const char *p, const char *q) { int c, d; while ((c = *p) == (d = *q)) { if (!c || c == '=') goto out; p++; q++; } if (c == '=') c = 0; if (d == '=') d = 0; out: return c - d; } static inline int varequal(const char *a, const char *b) { return !varcmp(a, b); } /* * Search the environment of a builtin command. */ static inline char *bltinlookup(const char *name) { return lookupvar(name); } static inline int arith_prec(int op) { return kPrec[op - ARITH_BINOP_MIN]; } static inline int higher_prec(int op1, int op2) { return arith_prec(op1) < arith_prec(op2); } static int64_t do_binop(int op, int64_t a, int64_t b) { switch (op) { default: case ARITH_REM: case ARITH_DIV: if (!b) yyerror("division by zero"); return op == ARITH_REM ? a % b : a / b; case ARITH_MUL: return a * b; case ARITH_ADD: return a + b; case ARITH_SUB: return a - b; case ARITH_LSHIFT: return a << b; case ARITH_RSHIFT: return a >> b; case ARITH_LT: return a < b; case ARITH_LE: return a <= b; case ARITH_GT: return a > b; case ARITH_GE: return a >= b; case ARITH_EQ: return a == b; case ARITH_NE: return a != b; case ARITH_BAND: return a & b; case ARITH_BXOR: return a ^ b; case ARITH_BOR: return a | b; } } static int64_t primary(int token, union yystype *val, int op, int noeval) { int64_t result; again: switch (token) { case ARITH_LPAREN: result = assignment(op, noeval); if (last_token != ARITH_RPAREN) yyerror("expecting ')'"); last_token = shlex(); return result; case ARITH_NUM: last_token = op; return val->val; case ARITH_VAR: last_token = op; return noeval ? val->val : lookupvarint(val->name); case ARITH_ADD: token = op; *val = yylval; op = shlex(); goto again; case ARITH_SUB: *val = yylval; return -primary(op, val, shlex(), noeval); case ARITH_NOT: *val = yylval; return !primary(op, val, shlex(), noeval); case ARITH_BNOT: *val = yylval; return ~primary(op, val, shlex(), noeval); default: yyerror("expecting primary"); } } static int64_t binop2(int64_t a, int op, int prec, int noeval) { for (;;) { union yystype val; int64_t b; int op2; int token; token = shlex(); val = yylval; b = primary(token, &val, shlex(), noeval); op2 = last_token; if (op2 >= ARITH_BINOP_MIN && op2 < ARITH_BINOP_MAX && higher_prec(op2, op)) { b = binop2(b, op2, arith_prec(op), noeval); op2 = last_token; } a = noeval ? b : do_binop(op, a, b); if (op2 < ARITH_BINOP_MIN || op2 >= ARITH_BINOP_MAX || arith_prec(op2) >= prec) { return a; } op = op2; } } static int64_t binop(int token, union yystype *val, int op, int noeval) { int64_t a = primary(token, val, op, noeval); op = last_token; if (op < ARITH_BINOP_MIN || op >= ARITH_BINOP_MAX) return a; return binop2(a, op, ARITH_MAX_PREC, noeval); } static int64_t and (int token, union yystype *val, int op, int noeval) { int64_t a = binop(token, val, op, noeval); int64_t b; op = last_token; if (op != ARITH_AND) return a; token = shlex(); *val = yylval; b = and(token, val, shlex(), noeval | !a); return a && b; } static int64_t or (int token, union yystype *val, int op, int noeval) { int64_t a = and(token, val, op, noeval); int64_t b; op = last_token; if (op != ARITH_OR) return a; token = shlex(); *val = yylval; b = or (token, val, shlex(), noeval | !!a); return a || b; } static int64_t cond(int token, union yystype *val, int op, int noeval) { int64_t a = or (token, val, op, noeval); int64_t b; int64_t c; if (last_token != ARITH_QMARK) return a; b = assignment(shlex(), noeval | !a); if (last_token != ARITH_COLON) yyerror("expecting ':'"); token = shlex(); *val = yylval; c = cond(token, val, shlex(), noeval | !!a); return a ? b : c; } static int64_t assignment(int var_, int noeval) { union yystype val = yylval; int op = shlex(); int64_t result; if (var_ != ARITH_VAR) return cond(var_, &val, op, noeval); if (op != ARITH_ASS && (op < ARITH_ASS_MIN || op >= ARITH_ASS_MAX)) { return cond(var_, &val, op, noeval); } result = assignment(shlex(), noeval); if (noeval) return result; return setvarint( val.name, (op == ARITH_ASS ? result : do_binop(op - 11, lookupvarint(val.name), result)), 0); } static int64_t arith(const char *s) { int64_t result; arith_buf = arith_startbuf = s; result = assignment(shlex(), 0); if (last_token) yyerror("expecting EOF"); return result; } /* * The cd and pwd commands. */ static inline int padvance(const char **path, const char *name) { return padvance_magic(path, name, 1); } static char *getpwd(void); static const char *updatepwd(const char *); static int cdopt(void); static int docd(const char *, int); static void setpwd(const char *, int); static int cdopt() { int flags = 0; int i, j; j = 'L'; while ((i = nextopt("LP"))) { if (i != j) { flags ^= CD_PHYSICAL; j = i; } } return flags; } static int cdcmd(int argc, char **argv) { const char *dest; const char *path; const char *p; char c; struct stat statb; int flags; int len; flags = cdopt(); dest = *argptr; if (!dest) dest = bltinlookup(homestr); else if (dest[0] == '-' && dest[1] == '\0') { dest = bltinlookup("OLDPWD"); flags |= CD_PRINT; } if (!dest) dest = nullstr; if (*dest == '/') goto step6; if (*dest == '.') { c = dest[1]; dotdot: switch (c) { case '\0': case '/': goto step6; case '.': c = dest[2]; if (c != '.') goto dotdot; } } if (!*dest) dest = "."; path = bltinlookup("CDPATH"); while (p = path, (len = padvance_magic(&path, dest, 0)) >= 0) { c = *p; p = stalloc(len); if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) { if (c && c != ':') flags |= CD_PRINT; docd: if (!docd(p, flags)) goto out; goto err; } } step6: p = dest; goto docd; err: sh_error("can't cd to %s", dest); unreachable; out: if (flags & CD_PRINT) out1fmt(snlfmt, curdir); return 0; } /* * Actually do the chdir. We also call hashcd to let the routines in exec.c * know that the current directory has changed. */ static int docd(const char *dest, int flags) { const char *dir = 0; int err; TRACE(("docd(\"%s\", %d) called\n", dest, flags)); INTOFF; if (!(flags & CD_PHYSICAL)) { dir = updatepwd(dest); if (dir) dest = dir; } err = chdir(dest); if (err) goto out; setpwd(dir, 1); hashcd(); out: INTON; return err; } /* * Update curdir (the name of the current directory) in response to a * cd command. */ static const char *updatepwd(const char *dir) { char *new; char *p; char *cdcomppath; const char *lim; cdcomppath = sstrdup(dir); STARTSTACKSTR(new); if (*dir != '/') { if (curdir == nullstr) return 0; new = stputs(curdir, new); } new = makestrspace(strlen(dir) + 2, new); lim = (char *)stackblock() + 1; if (*dir != '/') { if (new[-1] != '/') USTPUTC('/', new); if (new > lim &&*lim == '/') lim++; } else { USTPUTC('/', new); cdcomppath++; if (dir[1] == '/' && dir[2] != '/') { USTPUTC('/', new); cdcomppath++; lim++; } } p = strtok(cdcomppath, "/"); while (p) { switch (*p) { case '.': if (p[1] == '.' && p[2] == '\0') { while (new > lim) { STUNPUTC(new); if (new[-1] == '/') break; } break; } else if (p[1] == '\0') break; /* fall through */ default: new = stputs(p, new); USTPUTC('/', new); } p = strtok(0, "/"); } if (new > lim) STUNPUTC(new); *new = 0; return stackblock(); } /* * Find out what the current directory is. If we already know the * current directory, this routine returns immediately. */ static inline char *getpwd() { char buf[PATH_MAX]; if (getcwd(buf, sizeof(buf))) return savestr(buf); sh_warnx("getcwd() failed: %s", strerror(errno)); return nullstr; } static int pwdcmd(int argc, char **argv) { int flags; const char *dir = curdir; flags = cdopt(); if (flags) { if (physdir == nullstr) setpwd(dir, 0); dir = physdir; } out1fmt(snlfmt, dir); return 0; } static void setpwd(const char *val, int setold) { char *oldcur, *dir; oldcur = dir = curdir; if (setold) { setvar("OLDPWD", oldcur, VEXPORT); } INTOFF; if (physdir != nullstr) { if (physdir != oldcur) free(physdir); physdir = nullstr; } if (oldcur == val || !val) { char *s = getpwd(); physdir = s; if (!val) dir = s; } else dir = savestr(val); if (oldcur != dir && oldcur != nullstr) { free(oldcur); } curdir = dir; INTON; setvar("PWD", dir, VEXPORT); } /* * Errors and exceptions. */ /* * NEOF is returned by parsecmd when it encounters an end of file. It * must be distinct from NULL, so we use the address of a variable that * happens to be handy. */ #define NEOF ((union node *)&tokpushback) /* * Return of a legal variable name (a letter or underscore followed by zero or * more letters, underscores, and digits). */ static char *endofname(const char *name) { char *p; p = (char *)name; if (!is_name(*p)) return p; while (*++p) { if (!is_in_name(*p)) break; } return p; } static inline int goodname(const char *p) { return !*endofname(p); } static inline int parser_eof(void) { return tokpushback && lasttoken == TEOF; } static inline int have_traps(void) { return trapcnt; } static const struct builtincmd kBltin = { .name = nullstr, .builtin = bltincmd, .flags = BUILTIN_REGULAR, }; /* * Evaluate a parse tree. The value is left in the global variable * exitstatus. */ static int evaltree(union node *n, int flags) { int checkexit = 0; int (*evalfn)(union node *, int); struct stackmark smark; unsigned isor; int status = 0; setstackmark(&smark); if (nflag) goto out; if (n == NULL) { TRACE(("evaltree(NULL) called\n")); goto out; } dotrap(); TRACE(("pid %d, evaltree(%p: %d, %d) called\n", getpid(), n, n->type, flags)); switch (n->type) { default: case NNOT: status = !evaltree(n->nnot.com, EV_TESTED); goto setstatus; case NREDIR: errlinno = lineno = n->nredir.linno; if (funcline) lineno -= funcline - 1; expredir(n->nredir.redirect); pushredir(n->nredir.redirect); status = (redirectsafe(n->nredir.redirect, REDIR_PUSH) ?: evaltree(n->nredir.n, flags & EV_TESTED)); if (n->nredir.redirect) popredir(0); goto setstatus; case NCMD: evalfn = evalcommand; checkexit: checkexit = ~flags & EV_TESTED; goto calleval; case NFOR: evalfn = evalfor; goto calleval; case NWHILE: case NUNTIL: evalfn = evalloop; goto calleval; case NSUBSHELL: case NBACKGND: evalfn = evalsubshell; goto checkexit; case NPIPE: evalfn = evalpipe; goto checkexit; case NCASE: evalfn = evalcase; goto calleval; case NAND: case NOR: case NSEMI: isor = n->type - NAND; status = evaltree(n->nbinary.ch1, (flags | ((isor >> 1) - 1)) & EV_TESTED); if ((!status) == isor || evalskip) break; n = n->nbinary.ch2; evaln: evalfn = evaltree; calleval: status = evalfn(n, flags); goto setstatus; case NIF: status = evaltree(n->nif.test, EV_TESTED); if (evalskip) break; if (!status) { n = n->nif.ifpart; goto evaln; } else if (n->nif.elsepart) { n = n->nif.elsepart; goto evaln; } status = 0; goto setstatus; case NDEFUN: defun(n); setstatus: exitstatus = status; break; } out: dotrap(); if (eflag && checkexit & status) goto exexit; if (flags & EV_EXIT) { exexit: exraise(EXEND); } popstackmark(&smark); return exitstatus; } wontreturn static void evaltreenr(union node *n, int flags) { evaltree(n, flags); abort(); } /* * Execute a command or commands contained in a string. */ static int evalstring(char *s, int flags) { union node *n; struct stackmark smark; int status; s = sstrdup(s); setinputstring(s); setstackmark(&smark); status = 0; for (; (n = parsecmd(0)) != NEOF; popstackmark(&smark)) { int i; i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT)); if (n) status = i; if (evalskip) break; } popstackmark(&smark); popfile(); stunalloc(s); return status; } static int evalcmd(int argc, char **argv, int flags) { char *p; char *concat; char **ap; if (argc > 1) { p = argv[1]; if (argc > 2) { STARTSTACKSTR(concat); ap = argv + 2; for (;;) { concat = stputs(p, concat); if ((p = *ap++) == NULL) break; STPUTC(' ', concat); } STPUTC('\0', concat); p = grabstackstr(concat); } return evalstring(p, flags & EV_TESTED); } return 0; } static int skiploop(void) { int skip = evalskip; switch (skip) { case 0: break; case SKIPBREAK: case SKIPCONT: if (likely(--skipcount <= 0)) { evalskip = 0; break; } skip = SKIPBREAK; break; } return skip; } static int evalloop(union node *n, int flags) { int skip; int status; loopnest++; status = 0; flags &= EV_TESTED; do { int i; i = evaltree(n->nbinary.ch1, EV_TESTED); skip = skiploop(); if (skip == SKIPFUNC) status = i; if (skip) continue; if (n->type != NWHILE) i = !i; if (i != 0) break; status = evaltree(n->nbinary.ch2, flags); skip = skiploop(); } while (!(skip & ~SKIPCONT)); loopnest--; return status; } static int evalfor(union node *n, int flags) { struct arglist arglist; union node *argp; struct strlist *sp; int status; errlinno = lineno = n->nfor.linno; if (funcline) lineno -= funcline - 1; arglist.lastp = &arglist.list; for (argp = n->nfor.args; argp; argp = argp->narg.next) { expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); } *arglist.lastp = NULL; status = 0; loopnest++; flags &= EV_TESTED; for (sp = arglist.list; sp; sp = sp->next) { setvar(n->nfor.var_, sp->text, 0); status = evaltree(n->nfor.body, flags); if (skiploop() & ~SKIPCONT) break; } loopnest--; return status; } /* * See if a pattern matches in a case statement. */ static int casematch(union node *pattern, char *val) { struct stackmark smark; int result; setstackmark(&smark); argbackq = pattern->narg.backquote; STARTSTACKSTR(expdest); argstr(pattern->narg.text, EXP_TILDE | EXP_CASE); ifsfree(); result = patmatch(stackblock(), val); popstackmark(&smark); return result; } static int evalcase(union node *n, int flags) { union node *cp; union node *patp; struct arglist arglist; int status = 0; errlinno = lineno = n->ncase.linno; if (funcline) lineno -= funcline - 1; arglist.lastp = &arglist.list; expandarg(n->ncase.expr, &arglist, EXP_TILDE); for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) { for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) { if (casematch(patp, arglist.list->text)) { /* Ensure body is non-empty as otherwise * EV_EXIT may prevent us from setting the * exit status. */ if (evalskip == 0 && cp->nclist.body) { status = evaltree(cp->nclist.body, flags); } goto out; } } } out: return status; } /* * Kick off a subshell to evaluate a tree. */ static int evalsubshell(union node *n, int flags) { struct job *jp; int backgnd = (n->type == NBACKGND); int status; errlinno = lineno = n->nredir.linno; if (funcline) lineno -= funcline - 1; expredir(n->nredir.redirect); INTOFF; if (!backgnd && flags & EV_EXIT && !have_traps()) { forkreset(); goto nofork; } jp = makejob(n, 1); if (forkshell(jp, n, backgnd) == 0) { flags |= EV_EXIT; if (backgnd) flags &= ~EV_TESTED; nofork: INTON; redirect(n->nredir.redirect, 0); evaltreenr(n->nredir.n, flags); /* never returns */ } status = 0; if (!backgnd) status = waitforjob(jp); INTON; return status; } /* * Compute the names of the files in a redirection list. */ static void expredir(union node *n) { union node *redir; for (redir = n; redir; redir = redir->nfile.next) { struct arglist fn; fn.lastp = &fn.list; switch (redir->type) { case NFROMTO: case NFROM: case NTO: case NCLOBBER: case NAPPEND: expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); redir->nfile.expfname = fn.list->text; break; case NFROMFD: case NTOFD: if (redir->ndup.vname) { expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR); fixredir(redir, fn.list->text, 1); } break; } } } /* * Evaluate a pipeline. All the processes in the pipeline are children * of the process creating the pipeline. (This differs from some versions * of the shell, which make the last process in a pipeline the parent * of all the rest.) */ static int evalpipe(union node *n, int flags) { struct job *jp; struct nodelist *lp; int pipelen; int prevfd; int pip[2]; int status = 0; TRACE(("evalpipe(0x%lx) called\n", (long)n)); pipelen = 0; for (lp = n->npipe.cmdlist; lp; lp = lp->next) pipelen++; flags |= EV_EXIT; INTOFF; jp = makejob(n, pipelen); prevfd = -1; for (lp = n->npipe.cmdlist; lp; lp = lp->next) { prehash(lp->n); pip[1] = -1; if (lp->next) { if (pipe(pip) < 0) { close(prevfd); sh_error("Pipe call failed"); } } if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { INTON; if (pip[1] >= 0) { close(pip[0]); } if (prevfd > 0) { dup2(prevfd, 0); close(prevfd); } if (pip[1] > 1) { dup2(pip[1], 1); close(pip[1]); } evaltreenr(lp->n, flags); /* never returns */ } if (prevfd >= 0) close(prevfd); prevfd = pip[0]; close(pip[1]); } if (n->npipe.backgnd == 0) { status = waitforjob(jp); TRACE(("evalpipe: job done exit status %d\n", status)); } INTON; return status; } /* * Execute a command inside back quotes. If it's a builtin command, we * want to save its output in a block obtained from malloc. Otherwise * we fork off a subprocess and get the output of the command via a pipe. * Should be called with interrupts off. */ static void evalbackcmd(union node *n, struct backcmd *result) { int pip[2]; struct job *jp; result->fd = -1; result->buf = NULL; result->nleft = 0; result->jp = NULL; if (n == NULL) { goto out; } if (pipe(pip) < 0) sh_error("Pipe call failed"); jp = makejob(n, 1); if (forkshell(jp, n, FORK_NOJOB) == 0) { FORCEINTON; close(pip[0]); if (pip[1] != 1) { dup2(pip[1], 1); close(pip[1]); } ifsfree(); evaltreenr(n, EV_EXIT); unreachable; } close(pip[1]); result->fd = pip[0]; result->jp = jp; out: TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n", result->fd, result->buf, result->nleft, result->jp)); } static struct strlist *fill_arglist(struct arglist *arglist, union node **argpp) { struct strlist **lastp = arglist->lastp; union node *argp; while ((argp = *argpp)) { expandarg(argp, arglist, EXP_FULL | EXP_TILDE); *argpp = argp->narg.next; if (*lastp) break; } return *lastp; } static int parse_command_args(struct arglist *arglist, union node **argpp, const char **path) { struct strlist *sp = arglist->list; char *cp, c; for (;;) { sp = unlikely(sp->next != NULL) ? sp->next : fill_arglist(arglist, argpp); if (!sp) return 0; cp = sp->text; if (*cp++ != '-') break; if (!(c = *cp++)) break; if (c == '-' && !*cp) { if (likely(!sp->next) && !fill_arglist(arglist, argpp)) return 0; sp = sp->next; break; } do { switch (c) { case 'p': *path = defpath; break; default: /* run 'typecmd' for other options */ return 0; } } while ((c = *cp++)); } arglist->list = sp; return DO_NOFUNC; } /* * Execute a simple command. */ static int evalcommand(union node *cmd, int flags) { struct localvar_list *localvar_stop; struct parsefile *file_stop; struct redirtab *redir_stop; union node *argp; struct arglist arglist; struct arglist varlist; char **argv; int argc; struct strlist *osp; struct strlist *sp; struct cmdentry cmdentry; struct job *jp; char *lastarg; const char *path; int spclbltin; int cmd_flag; int execcmd; int status; char **nargv; int vflags; int vlocal; errlinno = lineno = cmd->ncmd.linno; if (funcline) lineno -= funcline - 1; /* First expand the arguments. */ TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags)); file_stop = parsefile; back_exitstatus = 0; cmdentry.cmdtype = CMDBUILTIN; cmdentry.u.cmd = &kBltin; varlist.lastp = &varlist.list; *varlist.lastp = NULL; arglist.lastp = &arglist.list; *arglist.lastp = NULL; cmd_flag = 0; execcmd = 0; spclbltin = -1; vflags = 0; vlocal = 0; path = NULL; argc = 0; argp = cmd->ncmd.args; if ((osp = fill_arglist(&arglist, &argp))) { int pseudovarflag = 0; for (;;) { find_command(arglist.list->text, &cmdentry, cmd_flag | DO_REGBLTIN, pathval()); vlocal++; /* implement bltin and command here */ if (cmdentry.cmdtype != CMDBUILTIN) break; pseudovarflag = cmdentry.u.cmd->flags & BUILTIN_ASSIGN; if (likely(spclbltin < 0)) { spclbltin = cmdentry.u.cmd->flags & BUILTIN_SPECIAL; vlocal = spclbltin ^ BUILTIN_SPECIAL; } execcmd = cmdentry.u.cmd == EXECCMD; if (likely(cmdentry.u.cmd != COMMANDCMD)) break; cmd_flag = parse_command_args(&arglist, &argp, &path); if (!cmd_flag) break; } for (; argp; argp = argp->narg.next) { expandarg( argp, &arglist, (pseudovarflag && isassignment(argp->narg.text)) ? EXP_VARTILDE : EXP_FULL | EXP_TILDE); } for (sp = arglist.list; sp; sp = sp->next) argc++; if (execcmd && argc > 1) vflags = VEXPORT; } localvar_stop = pushlocalvars(vlocal); /* Reserve one extra spot at the front for shellexec. */ nargv = stalloc(sizeof(char *) * (argc + 2)); argv = ++nargv; for (sp = arglist.list; sp; sp = sp->next) { TRACE(("evalcommand arg: %s\n", sp->text)); *nargv++ = sp->text; } *nargv = NULL; lastarg = NULL; if (iflag && funcline == 0 && argc > 0) lastarg = nargv[-1]; preverrout.fd = 2; expredir(cmd->ncmd.redirect); redir_stop = pushredir(cmd->ncmd.redirect); status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2); if (unlikely(status)) { bail: exitstatus = status; /* We have a redirection error. */ if (spclbltin > 0) exraise(EXERROR); goto out; } for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) { struct strlist **spp; spp = varlist.lastp; expandarg(argp, &varlist, EXP_VARTILDE); if (vlocal) mklocal((*spp)->text, VEXPORT); else setvareq((*spp)->text, vflags); } /* Print the command if xflag is set. */ if (xflag && !inps4) { struct output *out; int sep; out = &preverrout; inps4 = 1; outstr(expandstr(ps4val()), out); inps4 = 0; sep = 0; sep = eprintlist(out, varlist.list, sep); eprintlist(out, osp, sep); outcslow('\n', out); } /* Now locate the command. */ if (cmdentry.cmdtype != CMDBUILTIN || !(cmdentry.u.cmd->flags & BUILTIN_REGULAR)) { path = unlikely(path != NULL) ? path : pathval(); /* wut */ find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path); } jp = NULL; /* Execute the command. */ switch (cmdentry.cmdtype) { case CMDUNKNOWN: status = 127; goto bail; default: /* Fork off a child process if necessary. */ if (!(flags & EV_EXIT) || have_traps()) { INTOFF; jp = vforkexec(cmd, argv, path, cmdentry.u.index); break; } shellexec(argv, path, cmdentry.u.index); unreachable; case CMDBUILTIN: if (evalbltin(cmdentry.u.cmd, argc, argv, flags) && !(exception == EXERROR && spclbltin <= 0)) { raise: longjmp(handler->loc, 1); } break; case CMDFUNCTION: if (evalfun(cmdentry.u.func, argc, argv, flags)) goto raise; break; } status = waitforjob(jp); FORCEINTON; out: if (cmd->ncmd.redirect) popredir(execcmd); unwindredir(redir_stop); unwindfiles(file_stop); unwindlocalvars(localvar_stop); if (lastarg) { /* dsl: I think this is intended to be used to support * '_' in 'vi' command mode during line editing... * However I implemented that within libedit itself. */ setvar("_", lastarg, 0); } return status; } static int evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags) { char *volatile savecmdname; struct jmploc *volatile savehandler; struct jmploc jmploc; int status; int i; savecmdname = commandname; savehandler = handler; if ((i = setjmp(jmploc.loc))) goto cmddone; handler = &jmploc; commandname = argv[0]; argptr = argv + 1; optptr = NULL; /* initialize nextopt */ if (cmd == EVALCMD) status = evalcmd(argc, argv, flags); else status = (*cmd->builtin)(argc, argv); flushall(); if (out1->flags) sh_warnx("%s: I/O error", commandname); status |= out1->flags; exitstatus = status; cmddone: freestdout(); commandname = savecmdname; handler = savehandler; return i; } /* * Free a parse tree. */ static void freefunc(struct funcnode *f) { if (f && --f->count < 0) ckfree(f); } static int evalfun(struct funcnode *func, int argc, char **argv, int flags) { volatile struct shparam saveparam; struct jmploc *volatile savehandler; struct jmploc jmploc; int e; int savefuncline; int saveloopnest; saveparam = shellparam; savefuncline = funcline; saveloopnest = loopnest; savehandler = handler; if ((e = setjmp(jmploc.loc))) { goto funcdone; } INTOFF; handler = &jmploc; shellparam.malloc = 0; func->count++; funcline = func->n.ndefun.linno; loopnest = 0; INTON; shellparam.nparam = argc - 1; shellparam.p = argv + 1; shellparam.optind = 1; shellparam.optoff = -1; evaltree(func->n.ndefun.body, flags & EV_TESTED); funcdone: INTOFF; loopnest = saveloopnest; funcline = savefuncline; freefunc(func); freeparam(&shellparam); shellparam = saveparam; handler = savehandler; INTON; evalskip &= ~(SKIPFUNC | SKIPFUNCDEF); return e; } /* * Search for a command. This is called before we fork so that the * location of the command will be available in the parent as well as * the child. The check for "goodname" is an overly conservative * check that the name will not be subject to expansion. */ static void prehash(union node *n) { struct cmdentry entry; if (n->type == NCMD && n->ncmd.args) { if (goodname(n->ncmd.args->narg.text)) { find_command(n->ncmd.args->narg.text, &entry, 0, pathval()); } } } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » builtins ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ Builtin commands whose functions are closely tied to evaluation are implemented here. */ static int falsecmd(int argc, char **argv) { return 1; } static int truecmd(int argc, char **argv) { return 0; } /* No command given. */ static int bltincmd(int argc, char **argv) { /* * Preserve exitstatus of a previous possible redirection * as POSIX mandates */ return back_exitstatus; } /* * Handle break and continue commands. Break, continue, and return are * all handled by setting the evalskip flag. The evaluation routines * above all check this flag, and if it is set they start skipping * commands rather than executing them. The variable skipcount is * the number of loops to break/continue, or the number of function * levels to return. (The latter is always 1.) It should probably * be an error to break out of more loops than exist, but it isn't * in the standard shell so we don't make it one here. */ static int breakcmd(int argc, char **argv) { int n = argc > 1 ? number(argv[1]) : 1; if (n <= 0) badnum(argv[1]); if (n > loopnest) n = loopnest; if (n > 0) { evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK; skipcount = n; } return 0; } /* The return command. */ static int returncmd(int argc, char **argv) { int skip; int status; /* * If called outside a function, do what ksh does; * skip the rest of the file. */ if (argv[1]) { skip = SKIPFUNC; status = number(argv[1]); } else { skip = SKIPFUNCDEF; status = exitstatus; } evalskip = skip; return status; } static int execcmd(int argc, char **argv) { if (argc > 1) { iflag = 0; /* exit on error */ mflag = 0; optschanged(); shellexec(argv + 1, pathval(), 0); } return 0; } static int eprintlist(struct output *out, struct strlist *sp, int sep) { while (sp) { const char *p; p = &" %s"[!sep]; /* XXX: -Wstring-plus-int: p = " %s" + (1 - sep); */ sep |= 1; outfmt(out, p, sp->text); sp = sp->next; } return sep; } /* * When commands are first encountered, they are entered in a hash table. * This ensures that a full path search will not have to be done for them * on each invocation. * * We should investigate converting to a linear search, even though that * would make the command name "hash" a misnomer. */ /* * Exec a program. Never returns. If you change this routine, you may * have to change the find_command routine as well. */ wontreturn static void shellexec(char **argv, const char *path, int idx) { char *cmdname; int e; char **envp; int exerrno; envp = environment(); if (strchr(argv[0], '/') != NULL) { tryexec(argv[0], argv, envp); e = errno; } else { e = ENOENT; while (padvance(&path, argv[0]) >= 0) { cmdname = stackblock(); if (--idx < 0 && pathopt == NULL) { tryexec(cmdname, argv, envp); if (errno != ENOENT && errno != ENOTDIR) e = errno; } } } /* Map to POSIX errors */ exerrno = (e == ELOOP || e == ENAMETOOLONG || e == ENOENT || e == ENOTDIR) ? 127 : 126; exitstatus = exerrno; TRACE(("shellexec failed for %s, errno %d, suppressint %d\n", argv[0], e, suppressint)); exerror(EXEND, "%s: %s", argv[0], errmsg(e, E_EXEC)); } static void tryexec(char *cmd, char **argv, char **envp) { char *const path_bshell = _PATH_BSHELL; repeat: execve(cmd, argv, envp); if (cmd != path_bshell && errno == ENOEXEC) { *argv-- = cmd; *argv = cmd = path_bshell; goto repeat; } } static const char *legal_pathopt(const char *opt, const char *term, int magic) { switch (magic) { case 0: opt = NULL; break; case 1: opt = prefix(opt, "builtin") ?: prefix(opt, "func"); break; default: opt += strcspn(opt, term); break; } if (opt && *opt == '%') opt++; return opt; } /* * Do a path search. The variable path (passed by reference) should be * set to the start of the path before the first call; padvance will update * this value as it proceeds. Successive calls to padvance will return * the possible path expansions in sequence. If an option (indicated by * a percent sign) appears in the path entry then the global variable * pathopt will be set to point to it; otherwise pathopt will be set to * NULL. * * If magic is 0 then pathopt recognition will be disabled. If magic is * 1 we shall recognise %builtin/%func. Otherwise we shall accept any * pathopt. */ static int padvance_magic(const char **path, const char *name, int magic) { const char *term = "%:"; const char *lpathopt; const char *p; char *q; const char *start; unsigned qlen; unsigned len; if (*path == NULL) return -1; lpathopt = NULL; start = *path; if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) { lpathopt = start + 1; start = p; term = ":"; } len = strcspn(start, term); p = start + len; if (*p == '%') { unsigned extra = strchrnul(p, ':') - p; if (legal_pathopt(p + 1, term, magic)) lpathopt = p + 1; else len += extra; p += extra; } pathopt = lpathopt; *path = *p == ':' ? p + 1 : NULL; /* "2" is for '/' and '\0' */ qlen = len + strlen(name) + 2; q = growstackto(qlen); if (likely(len)) { q = mempcpy(q, start, len); *q++ = '/'; } strcpy(q, name); return qlen; } /*** Command hashing code ***/ static int hashcmd(int argc, char **argv) { struct tblentry **pp; struct tblentry *cmdp; int c; struct cmdentry entry; char *name; while ((c = nextopt("r")) != '\0') { clearcmdentry(); return 0; } if (*argptr == NULL) { for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) { for (cmdp = *pp; cmdp; cmdp = cmdp->next) { if (cmdp->cmdtype == CMDNORMAL) { printentry(cmdp); } } } return 0; } c = 0; while ((name = *argptr) != NULL) { if ((cmdp = cmdlookup(name, 0)) && (cmdp->cmdtype == CMDNORMAL || (cmdp->cmdtype == CMDBUILTIN && !(cmdp->param.cmd->flags & BUILTIN_REGULAR) && builtinloc > 0))) { delete_cmd_entry(); } find_command(name, &entry, DO_ERR, pathval()); if (entry.cmdtype == CMDUNKNOWN) c = 1; argptr++; } return c; } static void printentry(struct tblentry *cmdp) { int idx; const char *path; char *name; idx = cmdp->param.index; path = pathval(); do { padvance(&path, cmdp->cmdname); } while (--idx >= 0); name = stackblock(); outstr(name, out1); out1fmt(snlfmt, cmdp->rehash ? "*" : nullstr); } static int cmdloop(int top); /* * Read a file containing shell functions. */ static void readcmdfile(char *name) { setinputfile(name, INPUT_PUSH_FILE); cmdloop(0); popfile(); } /* * Search the table of builtin commands. */ static struct builtincmd *find_builtin(const char *name) { return bsearch(&name, kBuiltinCmds, sizeof(kBuiltinCmds) / sizeof(kBuiltinCmds[0]), sizeof(kBuiltinCmds[0]), pstrcmp); } /* * Resolve a command name. If you change this routine, you may have to * change the shellexec routine as well. */ static void find_command(char *name, struct cmdentry *entry, int act, const char *path) { char *fullname; struct stat statb; struct tblentry *cmdp; struct builtincmd *bcmd; int e, bit, idx, prev, updatetbl, len; /* If name contains a slash, don't use PATH or hash table */ if (strchr(name, '/') != NULL) { entry->u.index = -1; if (act & DO_ABS) { while (stat(name, &statb) < 0) { entry->cmdtype = CMDUNKNOWN; return; } } entry->cmdtype = CMDNORMAL; return; } updatetbl = (path == pathval()); if (!updatetbl) act |= DO_ALTPATH; /* If name is in the table, check answer will be ok */ if ((cmdp = cmdlookup(name, 0)) != NULL) { switch (cmdp->cmdtype) { default: case CMDNORMAL: bit = DO_ALTPATH | DO_REGBLTIN; break; case CMDFUNCTION: bit = DO_NOFUNC; break; case CMDBUILTIN: bit = cmdp->param.cmd->flags & BUILTIN_REGULAR ? 0 : DO_REGBLTIN; break; } if (act & bit) { if (act & bit & DO_REGBLTIN) goto fail; updatetbl = 0; cmdp = NULL; } else if (cmdp->rehash == 0) { /* if not invalidated by cd, we're done */ goto success; } } /* If %builtin not in path, check for builtin next */ bcmd = find_builtin(name); if (bcmd && ((bcmd->flags & BUILTIN_REGULAR) | (act & DO_ALTPATH) | (builtinloc <= 0))) { goto builtin_success; } if (act & DO_REGBLTIN) goto fail; /* We have to search path. */ prev = -1; /* where to start */ if (cmdp && cmdp->rehash) { /* doing a rehash */ if (cmdp->cmdtype == CMDBUILTIN) prev = builtinloc; else prev = cmdp->param.index; } e = ENOENT; idx = -1; loop: while ((len = padvance(&path, name)) >= 0) { const char *lpathopt = pathopt; fullname = stackblock(); idx++; if (lpathopt) { if (*lpathopt == 'b') { if (bcmd) goto builtin_success; continue; } else if (!(act & DO_NOFUNC)) { /* handled below */ } else { /* ignore unimplemented options */ continue; } } /* if rehash, don't redo absolute path names */ if (fullname[0] == '/' && idx <= prev) { if (idx < prev) continue; TRACE(("searchexec \"%s\": no change\n", name)); goto success; } while (stat(fullname, &statb) < 0) { if (errno != ENOENT && errno != ENOTDIR) e = errno; goto loop; } e = EACCES; /* if we fail, this will be the error */ if (!S_ISREG(statb.st_mode)) continue; if (lpathopt) { /* this is a %func directory */ stalloc(len); readcmdfile(fullname); if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION) { sh_error("%s not defined in %s", name, fullname); } stunalloc(fullname); goto success; } TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname)); if (!updatetbl) { entry->cmdtype = CMDNORMAL; entry->u.index = idx; return; } INTOFF; cmdp = cmdlookup(name, 1); cmdp->cmdtype = CMDNORMAL; cmdp->param.index = idx; INTON; goto success; } /* We failed. If there was an entry for this command, delete it */ if (cmdp && updatetbl) delete_cmd_entry(); if (act & DO_ERR) sh_warnx("%s: %s", name, errmsg(e, E_EXEC)); fail: entry->cmdtype = CMDUNKNOWN; return; builtin_success: if (!updatetbl) { entry->cmdtype = CMDBUILTIN; entry->u.cmd = bcmd; return; } INTOFF; cmdp = cmdlookup(name, 1); cmdp->cmdtype = CMDBUILTIN; cmdp->param.cmd = bcmd; INTON; success: cmdp->rehash = 0; entry->cmdtype = cmdp->cmdtype; entry->u = cmdp->param; } /* * Called when a cd is done. Marks all commands so the next time they * are executed they will be rehashed. */ static void hashcd(void) { struct tblentry **pp; struct tblentry *cmdp; for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) { for (cmdp = *pp; cmdp; cmdp = cmdp->next) { if (cmdp->cmdtype == CMDNORMAL || (cmdp->cmdtype == CMDBUILTIN && !(cmdp->param.cmd->flags & BUILTIN_REGULAR) && builtinloc > 0)) { cmdp->rehash = 1; } } } } /* * Fix command hash table when PATH changed. * Called before PATH is changed. The argument is the new value of PATH; * pathval() still returns the old value at this point. * Called with interrupts off. */ static void changepath(const char *newval) { int idx; int bltin; const char *neu; neu = newval; idx = 0; bltin = -1; for (;;) { if (*neu == '%' && prefix(neu + 1, "builtin")) { bltin = idx; break; } neu = strchr(neu, ':'); if (!neu) break; idx++; neu++; } builtinloc = bltin; clearcmdentry(); } /* * Clear out command entries. The argument specifies the first entry in * PATH which has changed. */ static void clearcmdentry(void) { struct tblentry **tblp; struct tblentry **pp; struct tblentry *cmdp; INTOFF; for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) { pp = tblp; while ((cmdp = *pp) != NULL) { if (cmdp->cmdtype == CMDNORMAL || (cmdp->cmdtype == CMDBUILTIN && !(cmdp->param.cmd->flags & BUILTIN_REGULAR) && builtinloc > 0)) { *pp = cmdp->next; ckfree(cmdp); } else { pp = &cmdp->next; } } } INTON; } /* * Locate a command in the command hash table. If "add" is nonzero, * add the command to the table if it is not already present. The * variable "lastcmdentry" is set to point to the address of the link * pointing to the entry, so that delete_cmd_entry can delete the * entry. * * Interrupts must be off if called with add != 0. */ static struct tblentry *cmdlookup(const char *name, int add) { unsigned int hashval; const char *p; struct tblentry *cmdp; struct tblentry **pp; p = name; hashval = (unsigned char)*p << 4; while (*p) hashval += (unsigned char)*p++; hashval &= 0x7FFF; pp = &cmdtable[hashval % CMDTABLESIZE]; for (cmdp = *pp; cmdp; cmdp = cmdp->next) { if (equal(cmdp->cmdname, name)) break; pp = &cmdp->next; } if (add && cmdp == NULL) { cmdp = *pp = ckmalloc(sizeof(struct tblentry) + strlen(name) + 1); cmdp->next = NULL; cmdp->cmdtype = CMDUNKNOWN; strcpy(cmdp->cmdname, name); } lastcmdentry = pp; return cmdp; } /* * Delete the command entry returned on the last lookup. */ static void delete_cmd_entry(void) { struct tblentry *cmdp; INTOFF; cmdp = *lastcmdentry; *lastcmdentry = cmdp->next; if (cmdp->cmdtype == CMDFUNCTION) freefunc(cmdp->param.func); ckfree(cmdp); INTON; } /* * Add a new command entry, replacing any existing command entry for * the same name - except special builtins. */ static void addcmdentry(char *name, struct cmdentry *entry) { struct tblentry *cmdp; cmdp = cmdlookup(name, 1); if (cmdp->cmdtype == CMDFUNCTION) { freefunc(cmdp->param.func); } cmdp->cmdtype = entry->cmdtype; cmdp->param = entry->u; cmdp->rehash = 0; } /* Define a shell function. */ static void defun(union node *func) { struct cmdentry entry; INTOFF; entry.cmdtype = CMDFUNCTION; entry.u.func = copyfunc(func); addcmdentry(func->ndefun.text, &entry); INTON; } /* Delete a function if it exists. */ static void unsetfunc(const char *name) { struct tblentry *cmdp; if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) { delete_cmd_entry(); } } /* Locate and print what a word is... */ static int typecmd(int argc, char **argv) { int i; int err = 0; for (i = 1; i < argc; i++) { err |= describe_command(out1, argv[i], NULL, 1); } return err; } static int describe_command(struct output *out, char *command, const char *path, int verbose) { struct cmdentry entry; struct tblentry *cmdp; const struct alias *ap; if (verbose) { outstr(command, out); } /* First look at the keywords */ if (findkwd(command)) { outstr(verbose ? " is a shell keyword" : command, out); goto out; } /* Then look at the aliases */ if ((ap = lookupalias(command, 0)) != NULL) { if (verbose) { outfmt(out, " is an alias for %s", ap->val); } else { outstr("alias ", out); printalias(ap); return 0; } goto out; } /* Then if the standard search path is used, check if it is * a tracked alias. */ if (path == NULL) { path = pathval(); cmdp = cmdlookup(command, 0); } else { cmdp = NULL; } if (cmdp != NULL) { entry.cmdtype = cmdp->cmdtype; entry.u = cmdp->param; } else { /* Finally use brute force */ find_command(command, &entry, DO_ABS, path); } switch (entry.cmdtype) { case CMDNORMAL: { int j = entry.u.index; char *p; if (j == -1) { p = command; } else { do { padvance(&path, command); } while (--j >= 0); p = stackblock(); } if (verbose) { outfmt(out, " is%s %s", cmdp ? " a tracked alias for" : nullstr, p); } else { outstr(p, out); } break; } case CMDFUNCTION: if (verbose) { outstr(" is a shell function", out); } else { outstr(command, out); } break; case CMDBUILTIN: if (verbose) { outfmt(out, " is a %sshell builtin", entry.u.cmd->flags & BUILTIN_SPECIAL ? "special " : nullstr); } else { outstr(command, out); } break; default: if (verbose) { outstr(": not found\n", out); } return 127; } out: outc('\n', out); return 0; } static int commandcmd(argc, argv) int argc; char **argv; { char *cmd; int c; enum { VERIFY_BRIEF = 1, VERIFY_VERBOSE = 2, } verify = 0; const char *path = NULL; while ((c = nextopt("pvV")) != '\0') if (c == 'V') verify |= VERIFY_VERBOSE; else if (c == 'v') verify |= VERIFY_BRIEF; else path = defpath; cmd = *argptr; if (verify && cmd) { return describe_command(out1, cmd, path, verify - VERIFY_BRIEF); } return 0; } /* * Prepare a pattern for a glob(3) call. * * Returns an stalloced string. */ static inline char *preglob(const char *pattern, int flag) { flag |= RMESCAPE_GLOB; return rmescapes((char *)pattern, flag); } static unsigned esclen(const char *start, const char *p) { unsigned esc = 0; while (p > start && *--p == (char)CTLESC) { esc++; } return esc; } static inline const char *getpwhome(const char *name) { struct passwd *pw = getpwnam(name); return pw ? pw->pw_dir : 0; } static void ifsbreakup(char *string, int maxargs, struct arglist *arglist); static void recordregion(int start, int end, int nulonly); /* * Perform variable substitution and command substitution on an * argument, placing the resulting list of arguments in arglist. If * EXP_FULL is true, perform splitting and file name expansion. When * arglist is NULL, perform here document expansion. */ static void expandarg(union node *arg, struct arglist *arglist, int flag) { struct strlist *sp; char *p; argbackq = arg->narg.backquote; STARTSTACKSTR(expdest); argstr(arg->narg.text, flag); if (arglist == NULL) { /* here document expanded */ goto out; } p = grabstackstr(expdest); exparg.lastp = &exparg.list; /* * TODO - EXP_REDIR */ if (flag & EXP_FULL) { ifsbreakup(p, -1, &exparg); *exparg.lastp = NULL; exparg.lastp = &exparg.list; expandmeta(exparg.list); } else { sp = (struct strlist *)stalloc(sizeof(struct strlist)); sp->text = p; *exparg.lastp = sp; exparg.lastp = &sp->next; } *exparg.lastp = NULL; if (exparg.list) { *arglist->lastp = exparg.list; arglist->lastp = exparg.lastp; } out: ifsfree(); } /* * Perform variable and command substitution. If EXP_FULL is set, output * CTLESC characters to allow for further processing. Otherwise treat $@ * like $* since no splitting will be performed. */ static char *argstr(char *p, int flag) { static const int DOLATSTRLEN = 6; static const char spclchars[] = {'=', ':', CTLQUOTEMARK, CTLENDVAR, CTLESC, CTLVAR, CTLBACKQ, CTLARI, CTLENDARI, 0}; const char *reject = spclchars; int c; int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD; int inquotes; unsigned length; int startloc; reject += !!(flag & EXP_VARTILDE2); reject += flag & EXP_VARTILDE ? 0 : 2; inquotes = 0; length = 0; if (flag & EXP_TILDE) { flag &= ~EXP_TILDE; tilde: if (*p == '~') p = exptilde(p, flag); } start: startloc = expdest - (char *)stackblock(); for (;;) { int end; length += strcspn(p + length, reject); end = 0; c = (signed char)p[length]; if (!(c & 0x80) || c == CTLENDARI || c == CTLENDVAR) { /* * c == '=' || c == ':' || c == '\0' || * c == CTLENDARI || c == CTLENDVAR */ length++; /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */ end = !!((c - 1) & 0x80); } if (length > 0 && !(flag & EXP_DISCARD)) { int newloc; char *q; q = stnputs(p, length, expdest); q[-1] &= end - 1; expdest = q - (flag & EXP_WORD ? end : 0); newloc = q - (char *)stackblock() - end; if (breakall && !inquotes && newloc > startloc) { recordregion(startloc, newloc, 0); } startloc = newloc; } p += length + 1; length = 0; if (end) break; switch (c) { case '=': flag |= EXP_VARTILDE2; reject++; /* fall through */ case ':': /* * sort of a hack - expand tildes in variable * assignments (after the first '=' and after ':'s). */ if (*--p == '~') { goto tilde; } continue; case CTLQUOTEMARK: /* "$@" syntax adherence hack */ if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) { p = evalvar(p + 1, flag | EXP_QUOTED) + 1; goto start; } inquotes ^= EXP_QUOTED; addquote: if (flag & QUOTES_ESC) { p--; length++; startloc++; } break; case CTLESC: startloc++; length++; goto addquote; case CTLVAR: p = evalvar(p, flag | inquotes); goto start; case CTLBACKQ: expbackq(argbackq->n, flag | inquotes); goto start; case CTLARI: p = expari(p, flag | inquotes); goto start; } } return p - 1; } static char *exptilde(char *startp, int flag) { signed char c; char *name; const char *home; char *p; p = startp; name = p + 1; while ((c = *++p) != '\0') { switch (c) { case CTLESC: return (startp); case CTLQUOTEMARK: return (startp); case ':': if (flag & EXP_VARTILDE) goto done; break; case '/': case CTLENDVAR: goto done; } } done: if (flag & EXP_DISCARD) goto out; *p = '\0'; if (*name == '\0') { home = lookupvar(homestr); } else { home = getpwhome(name); } *p = c; if (!home) goto lose; strtodest(home, flag | EXP_QUOTED); out: return (p); lose: return (startp); } static void removerecordregions(int endoff) { if (ifslastp == NULL) return; if (ifsfirst.endoff > endoff) { while (ifsfirst.next != NULL) { struct ifsregion *ifsp; INTOFF; ifsp = ifsfirst.next->next; ckfree(ifsfirst.next); ifsfirst.next = ifsp; INTON; } if (ifsfirst.begoff > endoff) ifslastp = NULL; else { ifslastp = &ifsfirst; ifsfirst.endoff = endoff; } return; } ifslastp = &ifsfirst; while (ifslastp->next && ifslastp->next->begoff < endoff) { ifslastp = ifslastp->next; } while (ifslastp->next != NULL) { struct ifsregion *ifsp; INTOFF; ifsp = ifslastp->next->next; ckfree(ifslastp->next); ifslastp->next = ifsp; INTON; } if (ifslastp->endoff > endoff) ifslastp->endoff = endoff; } /* * Expand arithmetic expression. Backup to start of expression, * evaluate, place result in (backed up) result, adjust string position. */ static char *expari(char *start, int flag) { struct stackmark sm; int begoff; int endoff; int len; int64_t result; char *p; p = stackblock(); begoff = expdest - p; p = argstr(start, flag & EXP_DISCARD); if (flag & EXP_DISCARD) goto out; start = stackblock(); endoff = expdest - start; start += begoff; STADJUST(start - expdest, expdest); removerecordregions(begoff); if (likely(flag & QUOTES_ESC)) rmescapes(start, 0); pushstackmark(&sm, endoff); result = arith(start); popstackmark(&sm); len = cvtnum(result, flag); if (likely(!(flag & EXP_QUOTED))) recordregion(begoff, begoff + len, 0); out: return p; } /* * Expand stuff in backwards quotes. */ static void expbackq(union node *cmd, int flag) { struct backcmd in; int i; char buf[128]; char *p; char *dest; int startloc; struct stackmark smark; if (flag & EXP_DISCARD) goto out; INTOFF; startloc = expdest - (char *)stackblock(); pushstackmark(&smark, startloc); evalbackcmd(cmd, (struct backcmd *)&in); popstackmark(&smark); p = in.buf; i = in.nleft; if (i == 0) goto read; for (;;) { memtodest(p, i, flag); read: if (in.fd < 0) break; do { i = read(in.fd, buf, sizeof buf); } while (i < 0 && errno == EINTR); TRACE(("expbackq: read returns %d\n", i)); if (i <= 0) break; p = buf; } if (in.buf) ckfree(in.buf); if (in.fd >= 0) { close(in.fd); back_exitstatus = waitforjob(in.jp); } INTON; /* Eat all trailing newlines */ dest = expdest; for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';) { STUNPUTC(dest); } expdest = dest; if (!(flag & EXP_QUOTED)) { recordregion(startloc, dest - (char *)stackblock(), 0); } TRACE(("evalbackq: size=%d: \"%.*s\"\n", (dest - (char *)stackblock()) - startloc, (dest - (char *)stackblock()) - startloc, (char *)stackblock() + startloc)); out: argbackq = argbackq->next; } static char *scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes, int zero) { char *loc; char *loc2; char c; loc = startp; loc2 = rmesc; do { int match; const char *s = loc2; c = *loc2; if (zero) { *loc2 = '\0'; s = rmesc; } match = pmatch(str, s); *loc2 = c; if (match) return loc; if (quotes && *loc == (char)CTLESC) loc++; loc++; loc2++; } while (c); return 0; } static char *scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes, int zero) { int esc = 0; char *loc; char *loc2; for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) { int match; char c = *loc2; const char *s = loc2; if (zero) { *loc2 = '\0'; s = rmesc; } match = pmatch(str, s); *loc2 = c; if (match) return loc; loc--; if (quotes) { if (--esc < 0) { esc = esclen(startp, loc); } if (esc % 2) { esc--; loc--; } } } return 0; } static char *subevalvar(char *start, char *str, int strloc, int startloc, int varflags, int flag) { int subtype = varflags & VSTYPE; int quotes = flag & QUOTES_ESC; char *startp; char *loc; long amount; char *rmesc, *rmescend; int zero; char *(*scan)(char *, char *, char *, char *, int, int); char *p; p = argstr(start, (flag & EXP_DISCARD) | EXP_TILDE | (str ? 0 : EXP_CASE)); if (flag & EXP_DISCARD) return p; startp = (char *)stackblock() + startloc; switch (subtype) { case VSASSIGN: setvar(str, startp, 0); loc = startp; goto out; case VSQUESTION: varunset(start, str, startp, varflags); unreachable; } subtype -= VSTRIMRIGHT; rmesc = startp; rmescend = (char *)stackblock() + strloc; if (quotes) { rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW); if (rmesc != startp) { rmescend = expdest; startp = (char *)stackblock() + startloc; } } rmescend--; str = (char *)stackblock() + strloc; preglob(str, 0); /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */ zero = subtype >> 1; /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */ scan = (subtype & 1) ^ zero ? scanleft : scanright; loc = scan(startp, rmesc, rmescend, str, quotes, zero); if (loc) { if (zero) { memmove(startp, loc, str - loc); loc = startp + (str - loc) - 1; } *loc = '\0'; } else loc = str - 1; out: amount = loc - expdest; STADJUST(amount, expdest); /* Remove any recorded regions beyond start of variable */ removerecordregions(startloc); return p; } /* * Expand a variable, and return a pointer to the next character in the * input string. */ static char *evalvar(char *p, int flag) { int subtype; int varflags; char *var_; int patloc; int startloc; long varlen; int discard; int quoted; varflags = *p++; subtype = varflags & VSTYPE; quoted = flag & EXP_QUOTED; var_ = p; startloc = expdest - (char *)stackblock(); p = strchr(p, '=') + 1; again: varlen = varvalue(var_, varflags, flag, quoted); if (varflags & VSNUL) varlen--; discard = varlen < 0 ? EXP_DISCARD : 0; switch (subtype) { case VSPLUS: discard ^= EXP_DISCARD; /* fall through */ case 0: case VSMINUS: p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD)); goto record; case VSASSIGN: case VSQUESTION: p = subevalvar(p, var_, 0, startloc, varflags, (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD)); if ((flag | ~discard) & EXP_DISCARD) goto record; varflags &= ~VSNUL; subtype = VSNORMAL; goto again; } if ((discard & ~flag) && uflag) varunset(p, var_, 0, 0); if (subtype == VSLENGTH) { p++; if (flag & EXP_DISCARD) return p; cvtnum(varlen > 0 ? varlen : 0, flag); goto really_record; } if (subtype == VSNORMAL) goto record; flag |= discard; if (!(flag & EXP_DISCARD)) { /* * Terminate the string and start recording the pattern * right after it */ STPUTC('\0', expdest); } patloc = expdest - (char *)stackblock(); p = subevalvar(p, NULL, patloc, startloc, varflags, flag); record: if ((flag | discard) & EXP_DISCARD) return p; really_record: if (quoted) { quoted = *var_ == '@' && shellparam.nparam; if (!quoted) return p; } recordregion(startloc, expdest - (char *)stackblock(), quoted); return p; } /* * Put a string on the stack. */ static unsigned memtodest(const char *p, unsigned len, int flags) { const char *syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX; char *q; char *s; if (unlikely(!len)) return 0; q = makestrspace(len * 2, expdest); s = q; do { int c = (signed char)*p++; if (c) { if ((flags & QUOTES_ESC) && ((syntax[c] == CCTL) || (flags & EXP_QUOTED && syntax[c] == CBACK))) { USTPUTC(CTLESC, q); } } else if (!(flags & EXP_KEEPNUL)) continue; USTPUTC(c, q); } while (--len); expdest = q; return q - s; } static unsigned strtodest(const char *p, int flags) { unsigned len = strlen(p); memtodest(p, len, flags); return len; } /* * Add the value of a specialized variable to the stack string. */ static long varvalue(char *name, int varflags, int flags, int quoted) { int num; char *p; int i; int sep; char sepc; char **ap; int subtype = varflags & VSTYPE; int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD); long len = 0; char c; if (!subtype) { if (discard) return -1; sh_error("Bad substitution"); } flags |= EXP_KEEPNUL; flags &= discard ? ~QUOTES_ESC : ~0; sep = (flags & EXP_FULL) << CHAR_BIT; switch (*name) { case '$': num = rootpid; goto numvar; case '?': num = exitstatus; goto numvar; case '#': num = shellparam.nparam; goto numvar; case '!': num = backgndpid; if (num == 0) return -1; numvar: len = cvtnum(num, flags); break; case '-': p = makestrspace(NOPTS, expdest); for (i = NOPTS - 1; i >= 0; i--) { if (optlist[i] && optletters[i]) { USTPUTC(optletters[i], p); len++; } } expdest = p; break; case '@': if (quoted && sep) goto param; /* fall through */ case '*': /* We will set c to 0 or ~0 depending on whether * we're doing field splitting. We won't do field * splitting if either we're quoted or sep is zero. * * Instead of testing (quoted || !sep) the following * trick optimises away any branches by using the * fact that EXP_QUOTED (which is the only bit that * can be set in quoted) is the same as EXP_FULL << * CHAR_BIT (which is the only bit that can be set * in sep). */ /* #if EXP_QUOTED >> CHAR_BIT != EXP_FULL */ /* #error The following two lines expect EXP_QUOTED == EXP_FULL << * CHAR_BIT */ /* #endif */ c = !((quoted | ~sep) & EXP_QUOTED) - 1; sep &= ~quoted; sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' '; param: sepc = sep; if (!(ap = shellparam.p)) return -1; while ((p = *ap++)) { len += strtodest(p, flags); if (*ap && sep) { len++; memtodest(&sepc, 1, flags); } } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': num = atoi(name); if (num < 0 || num > shellparam.nparam) return -1; p = num ? shellparam.p[num - 1] : arg0; goto value; default: p = lookupvar(name); value: if (!p) return -1; len = strtodest(p, flags); break; } if (discard) STADJUST(-len, expdest); return len; } /* * Record the fact that we have to scan this region of the * string for IFS characters. */ static void recordregion(int start, int end, int nulonly) { struct ifsregion *ifsp; if (ifslastp == NULL) { ifsp = &ifsfirst; } else { INTOFF; ifsp = (struct ifsregion *)ckmalloc(sizeof(struct ifsregion)); ifsp->next = NULL; ifslastp->next = ifsp; INTON; } ifslastp = ifsp; ifslastp->begoff = start; ifslastp->endoff = end; ifslastp->nulonly = nulonly; } /* * Break the argument string into pieces based upon IFS and add the * strings to the argument list. The regions of the string to be * searched for IFS characters have been stored by recordregion. * If maxargs is non-negative, at most maxargs arguments will be created, by * joining together the last arguments. */ static void ifsbreakup(char *string, int maxargs, struct arglist *arglist) { struct ifsregion *ifsp; struct strlist *sp; char *start; char *p; char *q; char *r = NULL; const char *ifs, *realifs; int ifsspc; int nulonly; start = string; if (ifslastp != NULL) { ifsspc = 0; nulonly = 0; realifs = ifsset() ? ifsval() : defifs; ifsp = &ifsfirst; do { int afternul; p = string + ifsp->begoff; afternul = nulonly; nulonly = ifsp->nulonly; ifs = nulonly ? nullstr : realifs; ifsspc = 0; while (p < string + ifsp->endoff) { int c; bool isifs; bool isdefifs; q = p; c = *p++; if (c == (char)CTLESC) c = *p++; isifs = !!strchr(ifs, c); isdefifs = false; if (isifs) isdefifs = !!strchr(defifs, c); /* If only reading one more argument: * If we have exactly one field, * read that field without its terminator. * If we have more than one field, * read all fields including their terminators, * except for trailing IFS whitespace. * * This means that if we have only IFS * characters left, and at most one * of them is non-whitespace, we stop * reading here. * Otherwise, we read all the remaining * characters except for trailing * IFS whitespace. * * In any case, r indicates the start * of the characters to remove, or NULL * if no characters should be removed. */ if (!maxargs) { if (isdefifs) { if (!r) r = q; continue; } if (!(isifs && ifsspc)) r = NULL; ifsspc = 0; continue; } if (ifsspc) { if (isifs) q = p; start = q; if (isdefifs) continue; isifs = false; } if (isifs) { if (!(afternul || nulonly)) ifsspc = isdefifs; /* Ignore IFS whitespace at start */ if (q == start && ifsspc) { start = p; ifsspc = 0; continue; } if (maxargs > 0 && !--maxargs) { r = q; continue; } *q = '\0'; sp = (struct strlist *)stalloc(sizeof *sp); sp->text = start; *arglist->lastp = sp; arglist->lastp = &sp->next; start = p; continue; } ifsspc = 0; } } while ((ifsp = ifsp->next) != NULL); if (nulonly) goto add; } if (r) *r = '\0'; if (!*start) return; add: sp = (struct strlist *)stalloc(sizeof *sp); sp->text = start; *arglist->lastp = sp; arglist->lastp = &sp->next; } /* * Expand shell metacharacters. At this point, the only control characters * should be escapes. The results are stored in the list exparg. */ static void expandmeta(struct strlist *str) { static const char metachars[] = {'*', '?', '[', 0}; /* TODO - EXP_REDIR */ while (str) { struct strlist **savelastp; struct strlist *sp; char *p; unsigned len; if (fflag) goto nometa; if (!strpbrk(str->text, metachars)) goto nometa; savelastp = exparg.lastp; INTOFF; p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP); len = strlen(p); expdir_max = len + PATH_MAX; expdir = ckmalloc(expdir_max); expmeta(p, len, 0); ckfree(expdir); if (p != str->text) ckfree(p); INTON; if (exparg.lastp == savelastp) { /* * no matches */ nometa: *exparg.lastp = str; rmescapes(str->text, 0); exparg.lastp = &str->next; } else { *exparg.lastp = NULL; *savelastp = sp = expsort(*savelastp); while (sp->next != NULL) sp = sp->next; exparg.lastp = &sp->next; } str = str->next; } } /* * Do metacharacter (i.e. *, ?, [...]) expansion. */ static void expmeta(char *name, unsigned name_len, unsigned expdir_len) { char *enddir = expdir + expdir_len; char *p; const char *cp; char *start; char *endname; int metaflag; struct stat statb; DIR *dirp; struct dirent *dp; int atend; int matchdot; int esc; metaflag = 0; start = name; for (p = name; esc = 0, *p; p += esc + 1) { if (*p == '*' || *p == '?') metaflag = 1; else if (*p == '[') { char *q = p + 1; if (*q == '!') q++; for (;;) { if (*q == '\\') q++; if (*q == '/' || *q == '\0') break; if (*++q == ']') { metaflag = 1; break; } } } else { if (*p == '\\' && p[1]) esc++; if (p[esc] == '/') { if (metaflag) break; start = p + esc + 1; } } } if (metaflag == 0) { /* we've reached the end of the file name */ if (!expdir_len) return; p = name; do { if (*p == '\\' && p[1]) p++; *enddir++ = *p; } while (*p++); if (lstat(expdir, &statb) >= 0) addfname(expdir); return; } endname = p; if (name < start) { p = name; do { if (*p == '\\' && p[1]) p++; *enddir++ = *p++; } while (p < start); } *enddir = 0; cp = expdir; expdir_len = enddir - cp; if (!expdir_len) cp = "."; if ((dirp = opendir(cp)) == NULL) return; if (*endname == 0) { atend = 1; } else { atend = 0; *endname = '\0'; endname += esc + 1; } name_len -= endname - name; matchdot = 0; p = start; if (*p == '\\') p++; if (*p == '.') matchdot++; while (!int_pending() && (dp = readdir(dirp)) != NULL) { if (dp->d_name[0] == '.' && !matchdot) continue; if (pmatch(start, dp->d_name)) { if (atend) { scopy(dp->d_name, enddir); addfname(expdir); } else { unsigned offset; unsigned len; p = stpcpy(enddir, dp->d_name); *p = '/'; offset = p - expdir + 1; len = offset + name_len + NAME_MAX; if (len > expdir_max) { len += PATH_MAX; expdir = ckrealloc(expdir, len); expdir_max = len; } expmeta(endname, name_len, offset); enddir = expdir + expdir_len; } } } closedir(dirp); if (!atend) endname[-esc - 1] = esc ? '\\' : '/'; } /* * Add a file name to the list. */ static void addfname(char *name) { struct strlist *sp; sp = (struct strlist *)stalloc(sizeof *sp); sp->text = sstrdup(name); *exparg.lastp = sp; exparg.lastp = &sp->next; } /* * Sort the results of file name expansion. It calculates the number of * strings to sort and then calls msort (short for merge sort) to do the * work. */ static struct strlist *expsort(struct strlist *str) { int len; struct strlist *sp; len = 0; for (sp = str; sp; sp = sp->next) len++; return msort(str, len); } static struct strlist *msort(struct strlist *list, int len) { struct strlist *p, *q = NULL; struct strlist **lpp; int half; int n; if (len <= 1) return list; half = len >> 1; p = list; for (n = half; --n >= 0;) { q = p; p = p->next; } q->next = NULL; /* terminate first half of list */ q = msort(list, half); /* sort first half of list */ p = msort(p, len - half); /* sort second half */ lpp = &list; for (;;) { if (strcmp(p->text, q->text) < 0) { *lpp = p; lpp = &p->next; if ((p = *lpp) == NULL) { *lpp = q; break; } } else { *lpp = q; lpp = &q->next; if ((q = *lpp) == NULL) { *lpp = p; break; } } } return list; } /* * Returns true if the pattern matches the string. */ static inline int patmatch(char *pattern, const char *string) { return pmatch(preglob(pattern, 0), string); } static int ccmatch(const char *p, int chr, const char **r) { static const struct class { char name[10]; int (*fn)(int); } classes[] = {{.name = ":alnum:]", .fn = isalnum}, {.name = ":cntrl:]", .fn = iscntrl}, {.name = ":lower:]", .fn = islower}, {.name = ":space:]", .fn = isspace}, {.name = ":alpha:]", .fn = isalpha}, {.name = ":digit:]", .fn = isdigit}, {.name = ":print:]", .fn = isprint}, {.name = ":upper:]", .fn = isupper}, {.name = ":blank:]", .fn = isblank}, {.name = ":graph:]", .fn = isgraph}, {.name = ":punct:]", .fn = ispunct}, {.name = ":xdigit:]", .fn = isxdigit}}; const struct class *class, *end; end = classes + sizeof(classes) / sizeof(classes[0]); for (class = classes; class < end; class ++) { const char *q; q = prefix(p, class->name); if (!q) continue; *r = q; return class->fn(chr); } *r = 0; return 0; } static int pmatch(const char *pattern, const char *string) { const char *p, *q; char c; p = pattern; q = string; for (;;) { switch (c = *p++) { case '\0': goto breakloop; case '\\': if (*p) { c = *p++; } goto dft; case '?': if (*q++ == '\0') return 0; break; case '*': c = *p; while (c == '*') c = *++p; if (c != '\\' && c != '?' && c != '*' && c != '[') { while (*q != c) { if (*q == '\0') return 0; q++; } } do { if (pmatch(p, q)) return 1; } while (*q++ != '\0'); return 0; case '[': { const char *startp; int invert, found; char chr; startp = p; invert = 0; if (*p == '!') { invert++; p++; } found = 0; chr = *q; if (chr == '\0') return 0; c = *p++; do { if (!c) { p = startp; c = '['; goto dft; } if (c == '[') { const char *r; found |= !!ccmatch(p, chr, &r); if (r) { p = r; continue; } } else if (c == '\\') c = *p++; if (*p == '-' && p[1] != ']') { p++; if (*p == '\\') p++; if (chr >= c && chr <= *p) found = 1; p++; } else { if (chr == c) found = 1; } } while ((c = *p++) != ']'); if (found == invert) return 0; q++; break; } dft: default: if (*q++ != c) return 0; break; } } breakloop: if (*q != '\0') return 0; return 1; } /* * Remove any CTLESC characters from a string. */ static char *rmescapes(char *str, int flag) { char *p, *q, *r; int notescaped; int globbing; p = strpbrk(str, qchars); if (!p) { return str; } q = p; r = str; if (flag & RMESCAPE_ALLOC) { unsigned len = p - str; unsigned fulllen = len + strlen(p) + 1; if (flag & RMESCAPE_GROW) { int strloc = str - (char *)stackblock(); r = makestrspace(fulllen, expdest); str = (char *)stackblock() + strloc; p = str + len; } else if (flag & RMESCAPE_HEAP) { r = ckmalloc(fulllen); } else { r = stalloc(fulllen); } q = r; if (len > 0) { q = mempcpy(q, str, len); } } globbing = flag & RMESCAPE_GLOB; notescaped = globbing; while (*p) { if (*p == (char)CTLQUOTEMARK) { p++; notescaped = globbing; continue; } if (*p == '\\') { /* naked back slash */ notescaped = 0; goto copy; } if (*p == (char)CTLESC) { p++; if (notescaped) *q++ = '\\'; } notescaped = globbing; copy: *q++ = *p++; } *q = '\0'; if (flag & RMESCAPE_GROW) { expdest = r; STADJUST(q - r + 1, expdest); } return r; } /* * Our own itoa(). */ static unsigned cvtnum(int64_t num, int flags) { int len = max_int_length(sizeof(num)); char buf[len]; len = fmtstr(buf, len, "%ld", num); return memtodest(buf, len, flags); } static void freestrings(struct strpush *sp) { INTOFF; do { struct strpush *psp; if (sp->ap) { sp->ap->flag &= ~ALIASINUSE; if (sp->ap->flag & ALIASDEAD) unalias(sp->ap->name); } psp = sp; sp = sp->spfree; if (psp != &(parsefile->basestrpush)) ckfree(psp); } while (sp); parsefile->spfree = NULL; INTON; } static int pgetc_nofree(void) { int c; if (parsefile->unget) return parsefile->lastc[--parsefile->unget]; if (--parsefile->nleft >= 0) c = (signed char)*parsefile->nextc++; else c = preadbuffer(); parsefile->lastc[1] = parsefile->lastc[0]; parsefile->lastc[0] = c; return c; } /* * Read a character from the script, returning PEOF on end of file. * Nul characters in the input are silently discarded. */ int pgetc(void) { struct strpush *sp = parsefile->spfree; if (unlikely(sp)) freestrings(sp); return pgetc_nofree(); } 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, const char **ansi1, const char **ansi2) { char *h = 0; linenoiseCompletions c = {0}; ShellCompletion(p, &c); if (c.len == 1) { h = strdup(c.cvec[0] + strlen(p)); } linenoiseFreeCompletions(&c); return h; } static ssize_t preadfd(void) { ssize_t nr; char *p, *buf = parsefile->buf; parsefile->nextc = buf; retry: if (!parsefile->fd && isatty(0)) { linenoiseSetFreeHintsCallback(free); linenoiseSetHintsCallback(ShellHint); linenoiseSetCompletionCallback(ShellCompletion); if ((p = linenoiseWithHistory(">: ", "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) { int flags = fcntl(0, F_GETFL, 0); if (flags >= 0 && flags & O_NONBLOCK) { flags &= ~O_NONBLOCK; if (fcntl(0, F_SETFL, flags) >= 0) { outstr("sh: turning off NDELAY mode\n", out2); goto retry; } } } } return nr; } /* * Refill the input buffer and return the next input character: * * 1) If a string was pushed back on the input, pop it; * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading * from a string so we can't refill the buffer, return EOF. * 3) If the is more stuff in this buffer, use it else call read to fill it. * 4) Process input up to the next newline, deleting nul characters. */ static int preadbuffer(void) { char *q; int more; char savec; if (unlikely(parsefile->strpush)) { popstring(); return pgetc_nofree(); } if (unlikely(parsefile->nleft == EOF_NLEFT || parsefile->buf == NULL)) return PEOF; flushall(); more = parsefile->lleft; if (more <= 0) { again: if ((more = preadfd()) <= 0) { parsefile->lleft = parsefile->nleft = EOF_NLEFT; return PEOF; } } q = parsefile->nextc; /* delete nul characters */ for (;;) { int c; more--; c = *q; if (!c) memmove(q, q + 1, more); else { q++; if (c == '\n') { parsefile->nleft = q - parsefile->nextc - 1; break; } } if (more <= 0) { parsefile->nleft = q - parsefile->nextc - 1; if (parsefile->nleft < 0) goto again; break; } } parsefile->lleft = more; savec = *q; *q = '\0'; if (vflag) { outstr(parsefile->nextc, out2); } *q = savec; return (signed char)*parsefile->nextc++; } /* * Undo a call to pgetc. Only two characters may be pushed back. * PEOF may be pushed back. */ static void pungetc(void) { parsefile->unget++; } /* * Push a string back onto the input at this current parsefile level. * We handle aliases this way. */ static void pushstring(char *s, void *ap) { struct strpush *sp; unsigned len; len = strlen(s); INTOFF; /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/ if ((unsigned long)parsefile->strpush | (unsigned long)parsefile->spfree) { sp = ckmalloc(sizeof(struct strpush)); sp->prev = parsefile->strpush; parsefile->strpush = sp; } else sp = parsefile->strpush = &(parsefile->basestrpush); sp->prevstring = parsefile->nextc; sp->prevnleft = parsefile->nleft; sp->unget = parsefile->unget; sp->spfree = parsefile->spfree; memcpy(sp->lastc, parsefile->lastc, sizeof(sp->lastc)); sp->ap = (struct alias *)ap; if (ap) { ((struct alias *)ap)->flag |= ALIASINUSE; sp->string = s; } parsefile->nextc = s; parsefile->nleft = len; parsefile->unget = 0; parsefile->spfree = NULL; INTON; } static void popstring(void) { struct strpush *sp = parsefile->strpush; INTOFF; if (sp->ap) { if (parsefile->nextc[-1] == ' ' || parsefile->nextc[-1] == '\t') { checkkwd |= CHKALIAS; } if (sp->string != sp->ap->val) { ckfree(sp->string); } } parsefile->nextc = sp->prevstring; parsefile->nleft = sp->prevnleft; parsefile->unget = sp->unget; memcpy(parsefile->lastc, sp->lastc, sizeof(sp->lastc)); /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/ parsefile->strpush = sp->prev; parsefile->spfree = sp; INTON; } /* * Set the input to take input from a file. If push is set, push the * old input onto the stack first. */ static int setinputfile(const char *fname, int flags) { int fd; INTOFF; fd = sh_open(fname, O_RDONLY, flags & INPUT_NOFILE_OK); if (fd < 0) goto out; if (fd < 10) fd = savefd(fd, fd); setinputfd(fd, flags & INPUT_PUSH_FILE); out: INTON; return fd; } /* * Like setinputfile, but takes an open file descriptor. Call this with * interrupts off. */ static void setinputfd(int fd, int push) { if (push) { pushfile(); parsefile->buf = 0; } parsefile->fd = fd; if (parsefile->buf == NULL) parsefile->buf = ckmalloc(IBUFSIZ); parsefile->lleft = parsefile->nleft = 0; plinno = 1; } /* * Like setinputfile, but takes input from a string. */ static void setinputstring(char *string) { INTOFF; pushfile(); parsefile->nextc = string; parsefile->nleft = strlen(string); parsefile->buf = NULL; plinno = 1; INTON; } /* * To handle the "." command, a stack of input files is used. Pushfile * adds a new entry to the stack and popfile restores the previous level. */ static void pushfile(void) { struct parsefile *pf; pf = (struct parsefile *)ckmalloc(sizeof(struct parsefile)); pf->prev = parsefile; pf->fd = -1; pf->strpush = NULL; pf->spfree = NULL; pf->basestrpush.prev = NULL; pf->unget = 0; parsefile = pf; } static void popfile(void) { struct parsefile *pf = parsefile; INTOFF; if (pf->fd >= 0) close(pf->fd); if (pf->buf) ckfree(pf->buf); if (parsefile->spfree) freestrings(parsefile->spfree); while (pf->strpush) { popstring(); freestrings(parsefile->spfree); } parsefile = pf->prev; ckfree(pf); INTON; } static void unwindfiles(struct parsefile *stop) { while (parsefile != stop) popfile(); } /* * Return to top level. */ static void popallfiles(void) { unwindfiles(&basepf); } static char *commandtext(union node *); static int dowait(int, struct job *); static int getstatus(struct job *); static int jobno(const struct job *); static int restartjob(struct job *, int); static int sprint_status(char *, int, int); static int waitproc(int, int *); static struct job *getjob(const char *, int); static struct job *growjobtab(void); static void cmdlist(union node *, int); static void cmdputs(const char *); static void cmdtxt(union node *); static void forkchild(struct job *, union node *, int); static void forkparent(struct job *, union node *, int, int); static void freejob(struct job *); static void set_curjob(struct job *, unsigned); static void showpipe(struct job *, struct output *); static void xtcsetpgrp(int, int); static void set_curjob(struct job *jp, unsigned mode) { struct job *jp1; struct job **jpp, **curp; /* first remove from list */ jpp = curp = &curjob; do { jp1 = *jpp; if (jp1 == jp) break; jpp = &jp1->prev_job; } while (1); *jpp = jp1->prev_job; /* Then re-insert in correct position */ jpp = curp; switch (mode) { default: case CUR_DELETE: /* job being deleted */ break; case CUR_RUNNING: /* newly created job or backgrounded job, put after all stopped jobs. */ do { jp1 = *jpp; if (!JOBS || !jp1 || jp1->state != JOBSTOPPED) break; jpp = &jp1->prev_job; } while (1); /* FALLTHROUGH */ case CUR_STOPPED: /* newly stopped job - becomes curjob */ jp->prev_job = *jpp; *jpp = jp; break; } } /* * Turn job control on and off. * * Note: This code assumes that the third arg to ioctl is a character * pointer, which is true on Berkeley systems but not System V. Since * System V doesn't have job control yet, this isn't a problem now. * * Called with interrupts off. */ static void setjobctl(int on) { int fd; int pgrp; if (IsWindows()) return; /* TODO(jart) */ if (on == jobctl || rootshell == 0) return; if (on) { int ofd; ofd = fd = sh_open(_PATH_TTY, O_RDWR, 1); if (fd < 0) { fd += 3; while (!isatty(fd)) if (--fd < 0) goto out; } fd = savefd(fd, ofd); do { /* while we are in the background */ if ((pgrp = tcgetpgrp(fd)) < 0) { out: sh_warnx("can't access tty; job control turned off"); mflag = on = 0; goto close; } if (pgrp == getpgrp()) break; killpg(0, SIGTTIN); } while (1); initialpgrp = pgrp; setsignal(SIGTSTP); setsignal(SIGTTOU); setsignal(SIGTTIN); pgrp = rootpid; setpgid(0, pgrp); xtcsetpgrp(fd, pgrp); } else { /* turning job control off */ fd = ttyfd; pgrp = initialpgrp; xtcsetpgrp(fd, pgrp); setpgid(0, pgrp); setsignal(SIGTSTP); setsignal(SIGTTOU); setsignal(SIGTTIN); close: close(fd); fd = -1; } ttyfd = fd; jobctl = on; } static int decode_signum(const char *string) { int signo = -1; if (is_number(string)) { signo = atoi(string); if (signo >= NSIG) signo = -1; } return signo; } static int killcmd(argc, argv) int argc; char **argv; { int signo = -1; int list = 0; int i; int pid; struct job *jp; if (argc <= 1) { usage: sh_error("Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n" "kill -l [exitstatus]"); } if (**++argv == '-') { signo = decode_signal(*argv + 1, 1); if (signo < 0) { int c; while ((c = nextopt("ls:")) != '\0') switch (c) { default: case 'l': list = 1; break; case 's': signo = decode_signal(optionarg, 1); if (signo < 0) { sh_error("invalid signal number or name: %s", optionarg); } break; } argv = argptr; } else argv++; } if (!list && signo < 0) signo = SIGTERM; if ((signo < 0 || !*argv) ^ list) { goto usage; } if (list) { struct output *out; out = out1; if (!*argv) { outstr("0\n", out); for (i = 1; i < NSIG; i++) { outfmt(out, snlfmt, strsignal(i)); } return 0; } signo = number(*argv); if (signo > 128) signo -= 128; if (0 < signo && signo < NSIG) outfmt(out, snlfmt, strsignal(signo)); else sh_error("invalid signal number or exit status: %s", *argv); return 0; } i = 0; do { if (**argv == '%') { jp = getjob(*argv, 0); pid = -jp->ps[0].pid; } else pid = **argv == '-' ? -number(*argv + 1) : number(*argv); if (kill(pid, signo) != 0) { sh_warnx("%s\n", strerror(errno)); i = 1; } } while (*++argv); return i; } static int jobno(const struct job *jp) { return jp - jobtab + 1; } static int fgcmd(int argc, char **argv) { struct job *jp; struct output *out; int mode; int retval; mode = (**argv == 'f') ? FORK_FG : FORK_BG; nextopt(nullstr); argv = argptr; out = out1; do { jp = getjob(*argv, 1); if (mode == FORK_BG) { set_curjob(jp, CUR_RUNNING); outfmt(out, "[%d] ", jobno(jp)); } outstr(jp->ps->cmd, out); showpipe(jp, out); retval = restartjob(jp, mode); } while (*argv && *++argv); return retval; } static int bgcmd(int argc, char **argv) __attribute__((__alias__("fgcmd"))); static int restartjob(struct job *jp, int mode) { struct procstat *ps; int i; int status; int pgid; INTOFF; if (jp->state == JOBDONE) goto out; jp->state = JOBRUNNING; pgid = jp->ps->pid; if (mode == FORK_FG) xtcsetpgrp(ttyfd, pgid); killpg(pgid, SIGCONT); ps = jp->ps; i = jp->nprocs; do { if (WIFSTOPPED(ps->status)) { ps->status = -1; } } while (ps++, --i); out: status = (mode == FORK_FG) ? waitforjob(jp) : 0; INTON; return status; } static int sprint_status(char *os, int status, int sigonly) { char *s = os; int st; st = WEXITSTATUS(status); if (!WIFEXITED(status)) { st = WSTOPSIG(status); if (!WIFSTOPPED(status)) st = WTERMSIG(status); if (sigonly) { if (st == SIGINT || st == SIGPIPE) goto out; if (WIFSTOPPED(status)) goto out; } s = stpncpy(s, strsignal(st), 32); } else if (!sigonly) { if (st) s += fmtstr(s, 16, "Done(%d)", st); else s = stpcpy(s, "Done"); } out: return s - os; } static void showjob(struct output *out, struct job *jp, int mode) { struct procstat *ps; struct procstat *psend; int col; int indent; char s[80]; ps = jp->ps; if (mode & SHOW_PGID) { /* just output process (group) id of pipeline */ outfmt(out, "%d\n", ps->pid); return; } col = fmtstr(s, 16, "[%d] ", jobno(jp)); indent = col; if (jp == curjob) s[col - 2] = '+'; else if (curjob && jp == curjob->prev_job) s[col - 2] = '-'; if (mode & SHOW_PID) col += fmtstr(s + col, 16, "%d ", ps->pid); psend = ps + jp->nprocs; if (jp->state == JOBRUNNING) { scopy("Running", s + col); col += strlen("Running"); } else { int status = psend[-1].status; if (jp->state == JOBSTOPPED) status = jp->stopstatus; col += sprint_status(s + col, status, 0); } goto start; do { /* for each process */ col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3; start: outfmt(out, "%s%*c%s", s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd); if (!(mode & SHOW_PID)) { showpipe(jp, out); break; } if (++ps == psend) { outcslow('\n', out); break; } } while (1); jp->changed = 0; if (jp->state == JOBDONE) { TRACE(("showjob: freeing job %d\n", jobno(jp))); freejob(jp); } } static int jobscmd(int argc, char **argv) { int mode, m; struct output *out; mode = 0; while ((m = nextopt("lp"))) if (m == 'l') mode = SHOW_PID; else mode = SHOW_PGID; out = out1; argv = argptr; if (*argv) do showjob(out, getjob(*argv, 0), mode); while (*++argv); else showjobs(out, mode); return 0; } /* * Print a list of jobs. If "change" is nonzero, only print jobs whose * statuses have changed since the last call to showjobs. */ static void showjobs(struct output *out, int mode) { struct job *jp; TRACE(("showjobs(%x) called\n", mode)); /* If not even one job changed, there is nothing to do */ dowait(DOWAIT_NONBLOCK, NULL); for (jp = curjob; jp; jp = jp->prev_job) { if (!(mode & SHOW_CHANGED) || jp->changed) showjob(out, jp, mode); } } /* * Mark a job structure as unused. */ static void freejob(struct job *jp) { struct procstat *ps; int i; INTOFF; for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) { if (ps->cmd != nullstr) ckfree(ps->cmd); } if (jp->ps != &jp->ps0) ckfree(jp->ps); jp->used = 0; set_curjob(jp, CUR_DELETE); INTON; } static int waitcmd(int argc, char **argv) { struct job *job; int retval; struct job *jp; nextopt(nullstr); retval = 0; argv = argptr; if (!*argv) { /* wait for all jobs */ for (;;) { jp = curjob; while (1) { if (!jp) { /* no running procs */ goto out; } if (jp->state == JOBRUNNING) break; jp->waited = 1; jp = jp->prev_job; } if (!dowait(DOWAIT_WAITCMD_ALL, 0)) goto sigout; } } retval = 127; do { if (**argv != '%') { int pid = number(*argv); job = curjob; goto start; do { if (job->ps[job->nprocs - 1].pid == pid) break; job = job->prev_job; start: if (!job) goto repeat; } while (1); } else job = getjob(*argv, 0); /* loop until process terminated or stopped */ if (!dowait(DOWAIT_WAITCMD, job)) goto sigout; job->waited = 1; retval = getstatus(job); repeat:; } while (*++argv); out: return retval; sigout: retval = 128 + pending_sig; goto out; } /* * Convert a job name to a job structure. */ static struct job *getjob(const char *name, int getctl) { struct job *jp; struct job *found; const char *err_msg = "No such job: %s"; unsigned num; int c; const char *p; char *(*match)(const char *, const char *); jp = curjob; p = name; if (!p) goto currentjob; if (*p != '%') goto err; c = *++p; if (!c) goto currentjob; if (!p[1]) { if (c == '+' || c == '%') { currentjob: err_msg = "No current job"; goto check; } else if (c == '-') { if (jp) jp = jp->prev_job; err_msg = "No previous job"; check: if (!jp) goto err; goto gotit; } } if (is_number(p)) { num = atoi(p); if (num > 0 && num <= njobs) { jp = jobtab + num - 1; if (jp->used) goto gotit; goto err; } } match = prefix; if (*p == '?') { match = strstr; p++; } found = 0; while (jp) { if (match(jp->ps[0].cmd, p)) { if (found) goto err; found = jp; err_msg = "%s: ambiguous"; } jp = jp->prev_job; } if (!found) goto err; jp = found; gotit: err_msg = "job %s not created under job control"; if (getctl && jp->jobctl == 0) goto err; return jp; err: sh_error(err_msg, name); } /* * Return a new job structure. * Called with interrupts off. */ struct job *makejob(union node *node, int nprocs) { int i; struct job *jp; for (i = njobs, jp = jobtab;; jp++) { if (--i < 0) { jp = growjobtab(); break; } if (jp->used == 0) break; if (jp->state != JOBDONE || !jp->waited) continue; if (jobctl) continue; freejob(jp); break; } memset(jp, 0, sizeof(*jp)); if (jobctl) jp->jobctl = 1; jp->prev_job = curjob; curjob = jp; jp->used = 1; jp->ps = &jp->ps0; if (nprocs > 1) { jp->ps = ckmalloc(nprocs * sizeof(struct procstat)); } TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs, jobno(jp))); return jp; } static struct job *growjobtab(void) { unsigned len; long offset; struct job *jp, *jq; len = njobs * sizeof(*jp); jq = jobtab; jp = ckrealloc(jq, len + 4 * sizeof(*jp)); offset = (char *)jp - (char *)jq; if (offset) { /* Relocate pointers */ unsigned l = len; jq = (struct job *)((char *)jq + l); while (l) { l -= sizeof(*jp); jq--; #define joff(p) ((struct job *)((char *)(p) + l)) #define jmove(p) (p) = (void *)((char *)(p) + offset) if (likely(joff(jp)->ps == &jq->ps0)) jmove(joff(jp)->ps); if (joff(jp)->prev_job) jmove(joff(jp)->prev_job); } if (curjob) jmove(curjob); #undef joff #undef jmove } njobs += 4; jobtab = jp; jp = (struct job *)((char *)jp + len); jq = jp + 3; do { jq->used = 0; } while (--jq >= jp); return jp; } /* * Fork off a subshell. If we are doing job control, give the subshell its * own process group. Jp is a job structure that the job is to be added to. * N is the command that will be evaluated by the child. Both jp and n may * be NULL. The mode parameter can be one of the following: * FORK_FG - Fork off a foreground process. * FORK_BG - Fork off a background process. * FORK_NOJOB - Like FORK_FG, but don't give the process its own * process group even if job control is on. * * When job control is turned off, background processes have their standard * input redirected to /dev/null (except for the second and later processes * in a pipeline). * * Called with interrupts off. */ static void forkchild(struct job *jp, union node *n, int mode) { int lvforked; int oldlvl; TRACE(("Child shell %d\n", getpid())); oldlvl = shlvl; lvforked = vforked; if (!lvforked) { shlvl++; forkreset(); /* do job control only in root shell */ jobctl = 0; } if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) { int pgrp; if (jp->nprocs == 0) pgrp = getpid(); else pgrp = jp->ps[0].pid; /* This can fail because we are doing it in the parent also */ (void)setpgid(0, pgrp); if (mode == FORK_FG) xtcsetpgrp(ttyfd, pgrp); setsignal(SIGTSTP); setsignal(SIGTTOU); } else if (mode == FORK_BG) { ignoresig(SIGINT); ignoresig(SIGQUIT); if (jp->nprocs == 0) { close(0); sh_open(_PATH_DEVNULL, O_RDONLY, 0); } } if (!oldlvl && iflag) { setsignal(SIGINT); setsignal(SIGQUIT); setsignal(SIGTERM); } if (lvforked) return; for (jp = curjob; jp; jp = jp->prev_job) freejob(jp); } static void forkparent(struct job *jp, union node *n, int mode, int pid) { if (pid < 0) { TRACE(("Fork failed, errno=%d", errno)); if (jp) freejob(jp); sh_error("Cannot fork"); unreachable; } TRACE(("In parent shell: child = %d\n", pid)); if (!jp) return; if (mode != FORK_NOJOB && jp->jobctl) { int pgrp; if (jp->nprocs == 0) pgrp = pid; else pgrp = jp->ps[0].pid; /* This can fail because we are doing it in the child also */ (void)setpgid(pid, pgrp); } if (mode == FORK_BG) { backgndpid = pid; /* set $! */ set_curjob(jp, CUR_RUNNING); } if (jp) { struct procstat *ps = &jp->ps[jp->nprocs++]; ps->pid = pid; ps->status = -1; ps->cmd = nullstr; if (jobctl && n) ps->cmd = commandtext(n); } } static int forkshell(struct job *jp, union node *n, int mode) { int pid; TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode)); pid = fork(); if (pid == 0) { forkchild(jp, n, mode); } else { forkparent(jp, n, mode, pid); } return pid; } static struct job *vforkexec(union node *n, char **argv, const char *path, int idx) { struct job *jp; int pid; jp = makejob(n, 1); sigblockall(NULL); vforked++; pid = vfork(); if (!pid) { forkchild(jp, n, FORK_FG); sigclearmask(); shellexec(argv, path, idx); unreachable; } vforked = 0; sigclearmask(); forkparent(jp, n, FORK_FG, pid); return jp; } /* * Wait for job to finish. * * Under job control we have the problem that while a child process is * running interrupts generated by the user are sent to the child but not * to the shell. This means that an infinite loop started by an inter- * active user may be hard to kill. With job control turned off, an * interactive user may place an interactive program inside a loop. If * the interactive program catches interrupts, the user doesn't want * these interrupts to also abort the loop. The approach we take here * is to have the shell ignore interrupt signals while waiting for a * foreground process to terminate, and then send itself an interrupt * signal if the child process was terminated by an interrupt signal. * Unfortunately, some programs want to do a bit of cleanup and then * exit on interrupt; unless these processes terminate themselves by * sending a signal to themselves (instead of calling exit) they will * confuse this approach. * * Called with interrupts off. */ static int waitforjob(struct job *jp) { int st; TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0)); dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp); if (!jp) return exitstatus; st = getstatus(jp); if (jp->jobctl) { xtcsetpgrp(ttyfd, rootpid); /* * This is truly gross. * If we're doing job control, then we did a TIOCSPGRP which * caused us (the shell) to no longer be in the controlling * session -- so we wouldn't have seen any ^C/SIGINT. So, we * intuit from the subprocess exit status whether a SIGINT * occurred, and if so interrupt ourselves. Yuck. - mycroft */ if (jp->sigint) raise(SIGINT); } if (!JOBS || jp->state == JOBDONE) freejob(jp); return st; } /* * Wait for a process to terminate. */ static int waitone(int block, struct job *job) { int pid; int status; struct job *jp; struct job *thisjob = NULL; int state; INTOFF; TRACE(("dowait(%d) called\n", block)); pid = waitproc(block, &status); TRACE(("wait returns pid %d, status=%d\n", pid, status)); if (pid <= 0) goto out; for (jp = curjob; jp; jp = jp->prev_job) { struct procstat *sp; struct procstat *spend; if (jp->state == JOBDONE) continue; state = JOBDONE; spend = jp->ps + jp->nprocs; sp = jp->ps; do { if (sp->pid == pid) { TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status)); sp->status = status; thisjob = jp; } if (sp->status == -1) state = JOBRUNNING; if (state == JOBRUNNING) continue; if (WIFSTOPPED(sp->status)) { jp->stopstatus = sp->status; state = JOBSTOPPED; } } while (++sp < spend); if (thisjob) goto gotjob; } goto out; gotjob: if (state != JOBRUNNING) { thisjob->changed = 1; if (thisjob->state != state) { TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state)); thisjob->state = state; if (state == JOBSTOPPED) { set_curjob(thisjob, CUR_STOPPED); } } } out: INTON; if (thisjob && thisjob == job) { char s[48 + 1]; int len; len = sprint_status(s, status, 1); if (len) { s[len] = '\n'; s[len + 1] = 0; outstr(s, out2); } } return pid; } static int dowait(int block, struct job *jp) { int gotchld = *(volatile int *)&gotsigchld; int rpid; int pid; if (jp && jp->state != JOBRUNNING) block = DOWAIT_NONBLOCK; if (block == DOWAIT_NONBLOCK && !gotchld) return 1; rpid = 1; do { pid = waitone(block, jp); rpid &= !!pid; block &= ~DOWAIT_WAITCMD_ALL; if (!pid || (jp && jp->state != JOBRUNNING)) block = DOWAIT_NONBLOCK; } while (pid >= 0); return rpid; } /* * Do a wait system call. If block is zero, we return -1 rather than * blocking. If block is DOWAIT_WAITCMD, we return 0 when a signal * other than SIGCHLD interrupted the wait. * * We use sigsuspend in conjunction with a non-blocking wait3 in * order to ensure that waitcmd exits promptly upon the reception * of a signal. * * For code paths other than waitcmd we either use a blocking wait3 * or a non-blocking wait3. For the latter case the caller of dowait * must ensure that it is called over and over again until all dead * children have been reaped. Otherwise zombies may linger. */ static int waitproc(int block, int *status) { sigset_t oldmask; int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG; int err; if (jobctl) flags |= WUNTRACED; do { gotsigchld = 0; do err = wait3(status, flags, NULL); while (err < 0 && errno == EINTR); if (err || (err = -!block)) break; sigblockall(&oldmask); while (!gotsigchld && !pending_sig) sigsuspend(&oldmask); sigclearmask(); } while (gotsigchld); return err; } /* * return 1 if there are stopped jobs, otherwise 0 */ static int stoppedjobs(void) { struct job *jp; int retval; retval = 0; if (job_warning) goto out; jp = curjob; if (jp && jp->state == JOBSTOPPED) { outstr("You have stopped jobs.\n", out2); job_warning = 2; retval++; } out: return retval; } /* * Return a string identifying a command (to be printed by the * jobs command). */ static char *commandtext(union node *n) { char *name; STARTSTACKSTR(cmdnextc); cmdtxt(n); name = stackblock(); TRACE(("commandtext: name %p, end %p\n", name, cmdnextc)); return savestr(name); } static void cmdtxt(union node *n) { union node *np; struct nodelist *lp; const char *p; char s[2]; if (!n) return; switch (n->type) { default: case NPIPE: lp = n->npipe.cmdlist; for (;;) { cmdtxt(lp->n); lp = lp->next; if (!lp) break; cmdputs(" | "); } break; case NSEMI: p = "; "; goto binop; case NAND: p = " && "; goto binop; case NOR: p = " || "; binop: cmdtxt(n->nbinary.ch1); cmdputs(p); n = n->nbinary.ch2; goto donode; case NREDIR: case NBACKGND: n = n->nredir.n; goto donode; case NNOT: cmdputs("!"); n = n->nnot.com; donode: cmdtxt(n); break; case NIF: cmdputs("if "); cmdtxt(n->nif.test); cmdputs("; then "); if (n->nif.elsepart) { cmdtxt(n->nif.ifpart); cmdputs("; else "); n = n->nif.elsepart; } else { n = n->nif.ifpart; } p = "; fi"; goto dotail; case NSUBSHELL: cmdputs("("); n = n->nredir.n; p = ")"; goto dotail; case NWHILE: p = "while "; goto until; case NUNTIL: p = "until "; until: cmdputs(p); cmdtxt(n->nbinary.ch1); n = n->nbinary.ch2; p = "; done"; dodo: cmdputs("; do "); dotail: cmdtxt(n); goto dotail2; case NFOR: cmdputs("for "); cmdputs(n->nfor.var_); cmdputs(" in "); cmdlist(n->nfor.args, 1); n = n->nfor.body; p = "; done"; goto dodo; case NDEFUN: cmdputs(n->ndefun.text); p = "() { ... }"; goto dotail2; case NCMD: cmdlist(n->ncmd.args, 1); cmdlist(n->ncmd.redirect, 0); break; case NARG: p = n->narg.text; dotail2: cmdputs(p); break; case NHERE: case NXHERE: p = "<<..."; goto dotail2; case NCASE: cmdputs("case "); cmdputs(n->ncase.expr->narg.text); cmdputs(" in "); for (np = n->ncase.cases; np; np = np->nclist.next) { cmdtxt(np->nclist.pattern); cmdputs(") "); cmdtxt(np->nclist.body); cmdputs(";; "); } p = "esac"; goto dotail2; case NTO: p = ">"; goto redir; case NCLOBBER: p = ">|"; goto redir; case NAPPEND: p = ">>"; goto redir; case NTOFD: p = ">&"; goto redir; case NFROM: p = "<"; goto redir; case NFROMFD: p = "<&"; goto redir; case NFROMTO: p = "<>"; redir: s[0] = n->nfile.fd + '0'; s[1] = '\0'; cmdputs(s); cmdputs(p); if (n->type == NTOFD || n->type == NFROMFD) { s[0] = n->ndup.dupfd + '0'; p = s; goto dotail2; } else { n = n->nfile.fname; goto donode; } } } static void cmdlist(union node *np, int sep) { for (; np; np = np->narg.next) { if (!sep) cmdputs(spcstr); cmdtxt(np); if (sep && np->narg.next) cmdputs(spcstr); } } static void cmdputs(const char *s) { const char *p, *str; char cc[2] = " "; char *nextc; signed char c; int subtype = 0; int quoted = 0; static const char vstype[VSTYPE + 1][4] = { "", "}", "-", "+", "?", "=", "%", "%%", "#", "##", }; nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc); p = s; while ((c = *p++) != 0) { str = 0; switch (c) { case CTLESC: c = *p++; break; case CTLVAR: subtype = *p++; if ((subtype & VSTYPE) == VSLENGTH) str = "${#"; else str = "${"; goto dostr; case CTLENDVAR: str = &"\"}"[!quoted]; quoted >>= 1; subtype = 0; goto dostr; case CTLBACKQ: str = "$(...)"; goto dostr; case CTLARI: str = "$(("; goto dostr; case CTLENDARI: str = "))"; goto dostr; case CTLQUOTEMARK: quoted ^= 1; c = '"'; break; case '=': if (subtype == 0) break; if ((subtype & VSTYPE) != VSNORMAL) quoted <<= 1; str = vstype[subtype & VSTYPE]; if (subtype & VSNUL) c = ':'; else goto checkstr; break; case '\'': case '\\': case '"': case '$': /* These can only happen inside quotes */ cc[0] = c; str = cc; c = '\\'; break; default: break; } USTPUTC(c, nextc); checkstr: if (!str) continue; dostr: while ((c = *str++)) { USTPUTC(c, nextc); } } if (quoted & 1) { USTPUTC('"', nextc); } *nextc = 0; cmdnextc = nextc; } static void showpipe(struct job *jp, struct output *out) { struct procstat *sp; struct procstat *spend; spend = jp->ps + jp->nprocs; for (sp = jp->ps + 1; sp < spend; sp++) outfmt(out, " | %s", sp->cmd); outcslow('\n', out); flushall(); } static void xtcsetpgrp(int fd, int pgrp) { int err; sigblockall(NULL); err = tcsetpgrp(fd, pgrp); sigclearmask(); if (err) sh_error("Cannot set tty process group (%s)", strerror(errno)); } static int getstatus(struct job *job) { int status; int retval; status = job->ps[job->nprocs - 1].status; retval = WEXITSTATUS(status); if (!WIFEXITED(status)) { retval = WSTOPSIG(status); if (!WIFSTOPPED(status)) { /* XXX: limits number of signals */ retval = WTERMSIG(status); if (retval == SIGINT) job->sigint = 1; } retval += 128; } TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n", jobno(job), job->nprocs, status, retval)); return retval; } /** handle one line of the read command. * more fields than variables -> remainder shall be part of last variable. * less fields than variables -> remaining variables unset. * * @param line complete line of input * @param ac argument count * @param ap argument (variable) list * @param len length of line including trailing '\0' */ static void readcmd_handle_line(char *s, int ac, char **ap) { struct arglist arglist; struct strlist *sl; s = grabstackstr(s); arglist.lastp = &arglist.list; ifsbreakup(s, ac, &arglist); *arglist.lastp = NULL; ifsfree(); sl = arglist.list; do { if (!sl) { /* nullify remaining arguments */ do { setvar(*ap, nullstr, 0); } while (*++ap); return; } /* set variable to field */ rmescapes(sl->text, 0); setvar(*ap, sl->text, 0); sl = sl->next; } while (*++ap); } /* * The read builtin. The -e option causes backslashes to escape the * following character. The -p option followed by an argument prompts * with the argument. * * This uses unbuffered input, which may be avoidable in some cases. */ static int readcmd(int argc, char **argv) { char **ap; char c; int rflag; char *prompt; char *p; int startloc; int newloc; int status; int i; rflag = 0; prompt = NULL; while ((i = nextopt("p:r")) != '\0') { if (i == 'p') prompt = optionarg; else rflag = 1; } if (prompt && isatty(0)) { outstr(prompt, out2); } if (!*(ap = argptr)) sh_error("arg count"); status = 0; STARTSTACKSTR(p); goto start; for (;;) { switch (read(0, &c, 1)) { case 1: break; default: if (errno == EINTR && !pending_sig) continue; /* fall through */ case 0: status = 1; goto out; } if (!c) continue; if (newloc >= startloc) { if (c == '\n') goto resetbs; goto put; } if (!rflag && c == '\\') { newloc = p - (char *)stackblock(); continue; } if (c == '\n') break; put: CHECKSTRSPACE(2, p); if (strchr(qchars, c)) USTPUTC(CTLESC, p); USTPUTC(c, p); if (newloc >= startloc) { resetbs: recordregion(startloc, newloc, 0); start: startloc = p - (char *)stackblock(); newloc = startloc - 1; } } out: recordregion(startloc, p - (char *)stackblock(), 0); STACKSTRNUL(p); readcmd_handle_line(p + 1, argc - (ap - argv), ap); return status; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » builtins » umask ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ This code was ripped from pdksh 5.2.14 and hacked for use with dash by Herbert Xu. Public Domain. */ static int umaskcmd(int argc, char **argv) { char *ap; int mask; int i; int symbolic_mode = 0; while ((i = nextopt("S")) != '\0') { symbolic_mode = 1; } INTOFF; mask = umask(0); umask(mask); INTON; if ((ap = *argptr) == NULL) { if (symbolic_mode) { char buf[18]; int j; mask = ~mask; ap = buf; for (i = 0; i < 3; i++) { *ap++ = "ugo"[i]; *ap++ = '='; for (j = 0; j < 3; j++) if (mask & (1u << (8 - (3 * i + j)))) *ap++ = "rwx"[j]; *ap++ = ','; } ap[-1] = '\0'; out1fmt("%s\n", buf); } else { out1fmt("%.4o\n", mask); } } else { int new_mask; if (isdigit((unsigned char)*ap)) { new_mask = 0; do { if (*ap >= '8' || *ap < '0') sh_error(illnum, *argptr); new_mask = (new_mask << 3) + (*ap - '0'); } while (*++ap != '\0'); } else { int positions, new_val; char op; mask = ~mask; new_mask = mask; positions = 0; while (*ap) { while (*ap && strchr("augo", *ap)) switch (*ap++) { case 'a': positions |= 0111; break; case 'u': positions |= 0100; break; case 'g': positions |= 0010; break; case 'o': positions |= 0001; break; } if (!positions) positions = 0111; /* default is a */ if (!strchr("=+-", op = *ap)) break; ap++; new_val = 0; while (*ap && strchr("rwxugoXs", *ap)) switch (*ap++) { case 'r': new_val |= 04; break; case 'w': new_val |= 02; break; case 'x': new_val |= 01; break; case 'u': new_val |= mask >> 6; break; case 'g': new_val |= mask >> 3; break; case 'o': new_val |= mask >> 0; break; case 'X': if (mask & 0111) new_val |= 01; break; case 's': /* ignored */ break; } new_val = (new_val & 07) * positions; switch (op) { case '-': new_mask &= ~new_val; break; case '=': new_mask = new_val | (new_mask & ~(positions * 07)); break; case '+': new_mask |= new_val; } if (*ap == ',') { positions = 0; ap++; } else if (!strchr("=+-", *ap)) break; } if (*ap) { sh_error("Illegal mode: %s", *argptr); return 1; } new_mask = ~new_mask; } umask(new_mask); } return 0; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § the unbourne shell » builtins » ulimit ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│─╝ This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with ash by J.T. Conklin. Public Domain. */ enum limtype { SOFT = 0x1, HARD = 0x2 }; static void printlim(enum limtype how, const struct rlimit *limit, const struct limits *l) { uint64_t val; val = limit->rlim_max; if (how & SOFT) val = limit->rlim_cur; if (val == RLIM_INFINITY) out1fmt("unlimited\n"); else { val /= l->factor; out1fmt("%ld\n", (int64_t)val); } } static int ulimitcmd(int argc, char **argv) { static const struct limits limits[] = {{(char *)0, 0, 0, '\0'}}; int c; uint64_t val = 0; enum limtype how = SOFT | HARD; const struct limits *l; int set, all = 0; int optc, what; struct rlimit limit; what = 'f'; while ((optc = nextopt("HSa")) != '\0') { switch (optc) { case 'H': how = HARD; break; case 'S': how = SOFT; break; case 'a': all = 1; break; default: what = optc; } } for (l = limits; l->option != what; l++) ; set = *argptr ? 1 : 0; if (set) { char *p = *argptr; if (all || argptr[1]) sh_error("too many arguments"); if (strcmp(p, "unlimited") == 0) val = RLIM_INFINITY; else { val = (uint64_t)0; while ((c = *p++) >= '0' && c <= '9') { val = (val * 10) + (long)(c - '0'); if (val < (uint64_t)0) break; } if (c) sh_error("bad number"); val *= l->factor; } } if (all) { for (l = limits; l->name; l++) { getrlimit(l->cmd, &limit); out1fmt("%-20s ", l->name); printlim(how, &limit, l); } return 0; } getrlimit(l->cmd, &limit); if (set) { if (how & HARD) limit.rlim_max = val; if (how & SOFT) limit.rlim_cur = val; if (setrlimit(l->cmd, &limit) < 0) sh_error("error setting limit (%s)", strerror(errno)); } else { printlim(how, &limit, l); } return 0; } /* * Produce a possibly single quoted string suitable as input to the shell. * The return string is allocated on the stack. */ static char *single_quote(const char *s) { char *p; STARTSTACKSTR(p); do { char *q; unsigned len; len = strchrnul(s, '\'') - s; q = p = makestrspace(len + 3, p); *q++ = '\''; q = mempcpy(q, s, len); *q++ = '\''; s += len; STADJUST(q - p, p); len = strspn(s, "'"); if (!len) break; q = p = makestrspace(len + 3, p); *q++ = '"'; q = mempcpy(q, s, len); *q++ = '"'; s += len; STADJUST(q - p, p); } while (*s); USTPUTC(0, p); return stackblock(); } /* * Process the shell command line arguments. */ static int procargs(int argc, char **argv) { int i; const char *xminusc; char **xargv; int login; xargv = argv; login = xargv[0] && xargv[0][0] == '-'; arg0 = xargv[0]; if (argc > 0) xargv++; for (i = 0; i < NOPTS; i++) optlist[i] = 2; argptr = xargv; login |= options(1); xargv = argptr; xminusc = minusc; if (*xargv == NULL) { if (xminusc) sh_error("-c requires an argument"); sflag = 1; } /* JART: fuck tty check this is documented behavior w/ no args */ if (iflag == 2 && sflag == 1 /* && isatty(0) && isatty(1) */) iflag = 1; if (mflag == 2) mflag = iflag; for (i = 0; i < NOPTS; i++) if (optlist[i] == 2) optlist[i] = 0; /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */ if (xminusc) { minusc = *xargv++; if (*xargv) goto setarg0; } else if (!sflag) { setinputfile(*xargv, 0); setarg0: arg0 = *xargv++; } shellparam.p = xargv; shellparam.optind = 1; shellparam.optoff = -1; /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */ while (*xargv) { shellparam.nparam++; xargv++; } optschanged(); return login; } static void optschanged(void) { setinteractive(iflag); setjobctl(mflag); } static void setoption(int flag, int val) { int i; for (i = 0; i < NOPTS; i++) if (optletters[i] == flag) { optlist[i] = val; if (val) { /* #%$ hack for ksh semantics */ if (flag == 'V') Eflag = 0; else if (flag == 'E') Vflag = 0; } return; } sh_error("Illegal option -%c", flag); unreachable; } /* * Process shell options. The global variable argptr contains a pointer * to the argument list; we advance it past the options. */ static int options(int cmdline) { char *p; int val; int c; int login = 0; if (cmdline) minusc = NULL; while ((p = *argptr) != NULL) { argptr++; if ((c = *p++) == '-') { val = 1; if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) { if (!cmdline) { /* "-" means turn off -x and -v */ if (p[0] == '\0') xflag = vflag = 0; /* "--" means reset params */ else if (*argptr == NULL) setparam(argptr); } break; /* "-" or "--" terminates options */ } } else if (c == '+') { val = 0; } else { argptr--; break; } while ((c = *p++) != '\0') { if (c == 'c' && cmdline) { minusc = p; /* command is after shell args*/ } else if (c == 'l' && cmdline) { login = 1; } else if (c == 'o') { minus_o(*argptr, val); if (*argptr) argptr++; } else { setoption(c, val); } } } return login; } static void minus_o(char *name, int val) { int i; if (name == NULL) { if (val) { outstr("Current option settings\n", out1); for (i = 0; i < NOPTS; i++) { out1fmt("%-16s%s\n", optnames[i], optlist[i] ? "on" : "off"); } } else { for (i = 0; i < NOPTS; i++) { out1fmt("set %s %s\n", optlist[i] ? "-o" : "+o", optnames[i]); } } } else { for (i = 0; i < NOPTS; i++) if (equal(name, optnames[i])) { optlist[i] = val; return; } sh_error("Illegal option -o %s", name); } } /* * Set the shell parameters. */ static void setparam(char **argv) { char **newparam; char **ap; int nparam; for (nparam = 0; argv[nparam]; nparam++) ; ap = newparam = ckmalloc((nparam + 1) * sizeof *ap); while (*argv) { *ap++ = savestr(*argv++); } *ap = NULL; freeparam(&shellparam); shellparam.malloc = 1; shellparam.nparam = nparam; shellparam.p = newparam; shellparam.optind = 1; shellparam.optoff = -1; } /* * Free the list of positional parameters. */ static void freeparam(volatile struct shparam *param) { char **ap; if (param->malloc) { for (ap = param->p; *ap; ap++) ckfree(*ap); ckfree(param->p); } } /* * The shift builtin command. */ static int shiftcmd(int argc, char **argv) { int n; char **ap1, **ap2; n = 1; if (argc > 1) n = number(argv[1]); if (n > shellparam.nparam) sh_error("can't shift that many"); INTOFF; shellparam.nparam -= n; for (ap1 = shellparam.p; --n >= 0; ap1++) { if (shellparam.malloc) ckfree(*ap1); } ap2 = shellparam.p; while ((*ap2++ = *ap1++) != NULL) ; shellparam.optind = 1; shellparam.optoff = -1; INTON; return 0; } /* * The set command builtin. */ static int setcmd(int argc, char **argv) { if (argc == 1) return showvars(nullstr, 0, VUNSET); INTOFF; options(0); optschanged(); if (*argptr != NULL) { setparam(argptr); } INTON; return 0; } static void getoptsreset(value) const char *value; { shellparam.optind = number(value) ?: 1; shellparam.optoff = -1; } /* * The getopts builtin. Shellparam.optnext points to the next argument * to be processed. Shellparam.optptr points to the next character to * be processed in the current argument. If shellparam.optnext is NULL, * then it's the first time getopts has been called. */ static int getoptscmd(int argc, char **argv) { char **optbase; if (argc < 3) sh_error("Usage: getopts optstring var [arg]"); else if (argc == 3) { optbase = shellparam.p; if ((unsigned)shellparam.optind > shellparam.nparam + 1) { shellparam.optind = 1; shellparam.optoff = -1; } } else { optbase = &argv[3]; if ((unsigned)shellparam.optind > argc - 2) { shellparam.optind = 1; shellparam.optoff = -1; } } return getopts(argv[1], argv[2], optbase); } static int getopts(char *optstr, char *optvar, char **optfirst) { char *p, *q; char c = '?'; int done = 0; char s[2]; char **optnext; int ind = shellparam.optind; int off = shellparam.optoff; shellparam.optind = -1; optnext = optfirst + ind - 1; if (ind <= 1 || off < 0 || strlen(optnext[-1]) < off) p = NULL; else p = optnext[-1] + off; if (p == NULL || *p == '\0') { /* Current word is done, advance */ p = *optnext; if (p == NULL || *p != '-' || *++p == '\0') { atend: p = NULL; done = 1; goto out; } optnext++; if (p[0] == '-' && p[1] == '\0') /* check for "--" */ goto atend; } c = *p++; for (q = optstr; *q != c;) { if (*q == '\0') { if (optstr[0] == ':') { s[0] = c; s[1] = '\0'; setvar("OPTARG", s, 0); } else { outfmt(&errout, "Illegal option -%c\n", c); (void)unsetvar("OPTARG"); } c = '?'; goto out; } if (*++q == ':') q++; } if (*++q == ':') { if (*p == '\0' && (p = *optnext) == NULL) { if (optstr[0] == ':') { s[0] = c; s[1] = '\0'; setvar("OPTARG", s, 0); c = ':'; } else { outfmt(&errout, "No arg for -%c option\n", c); (void)unsetvar("OPTARG"); c = '?'; } goto out; } if (p == *optnext) optnext++; setvar("OPTARG", p, 0); p = NULL; } else setvar("OPTARG", nullstr, 0); out: ind = optnext - optfirst + 1; setvarint("OPTIND", ind, VNOFUNC); s[0] = c; s[1] = '\0'; setvar(optvar, s, 0); shellparam.optoff = p ? p - *(optnext - 1) : -1; shellparam.optind = ind; return done; } /* * XXX - should get rid of. have all builtins use getopt(3). the * library getopt must have the BSD extension function variable "optreset" * otherwise it can't be used within the shell safely. * * Standard option processing (a la getopt) for builtin routines. The * only argument that is passed to nextopt is the option string; the * other arguments are unnecessary. It return the character, or '\0' on * end of input. */ static int nextopt(const char *optstring) { char *p; const char *q; char c; if ((p = optptr) == NULL || *p == '\0') { p = *argptr; if (p == NULL || *p != '-' || *++p == '\0') return '\0'; argptr++; if (p[0] == '-' && p[1] == '\0') /* check for "--" */ return '\0'; } c = *p++; for (q = optstring; *q != c;) { if (*q == '\0') sh_error("Illegal option -%c", c); if (*++q == ':') q++; } if (*++q == ':') { if (*p == '\0' && (p = *argptr++) == NULL) { sh_error("No arg for -%c option", c); } optionarg = p; p = NULL; } optptr = p; return c; } /* values returned by readtoken */ static int isassignment(const char *p) { const char *q = endofname(p); if (p == q) return 0; return *q == '='; } static inline int realeofmark(const char *eofmark) { return eofmark && eofmark != FAKEEOFMARK; } /* * Read and parse a command. Returns NEOF on end of file. (NULL is a * valid parse tree indicating a blank line.) */ static union node *parsecmd(int interact) { tokpushback = 0; checkkwd = 0; heredoclist = 0; doprompt = interact; if (doprompt) setprompt(doprompt); needprompt = 0; return list(1); } static union node *list(int nlflag) { int chknl = nlflag & 1 ? 0 : CHKNL; union node *n1, *n2, *n3; int tok; n1 = NULL; for (;;) { checkkwd = chknl | CHKKWD | CHKALIAS; tok = readtoken(); switch (tok) { case TNL: parseheredoc(); return n1; case TEOF: if (!n1 && !chknl) n1 = NEOF; out_eof: parseheredoc(); tokpushback++; lasttoken = TEOF; return n1; } tokpushback++; if (nlflag == 2 && tokendlist[tok]) return n1; nlflag |= 2; n2 = andor(); tok = readtoken(); if (tok == TBACKGND) { if (n2->type == NPIPE) { n2->npipe.backgnd = 1; } else { if (n2->type != NREDIR) { n3 = stalloc(sizeof(struct nredir)); n3->nredir.n = n2; n3->nredir.redirect = NULL; n2 = n3; } n2->type = NBACKGND; } } if (n1 == NULL) { n1 = n2; } else { n3 = (union node *)stalloc(sizeof(struct nbinary)); n3->type = NSEMI; n3->nbinary.ch1 = n1; n3->nbinary.ch2 = n2; n1 = n3; } switch (tok) { case TEOF: goto out_eof; case TNL: tokpushback++; /* fall through */ case TBACKGND: case TSEMI: break; default: if (!chknl) synexpect(-1); tokpushback++; return n1; } } } static union node *andor(void) { union node *n1, *n2, *n3; int t; n1 = pipeline(); for (;;) { if ((t = readtoken()) == TAND) { t = NAND; } else if (t == TOR) { t = NOR; } else { tokpushback++; return n1; } checkkwd = CHKNL | CHKKWD | CHKALIAS; n2 = pipeline(); n3 = (union node *)stalloc(sizeof(struct nbinary)); n3->type = t; n3->nbinary.ch1 = n1; n3->nbinary.ch2 = n2; n1 = n3; } } static union node *pipeline(void) { union node *n1, *n2, *pipenode; struct nodelist *lp, *prev; int negate; negate = 0; TRACE(("pipeline: entered\n")); if (readtoken() == TNOT) { negate = !negate; checkkwd = CHKKWD | CHKALIAS; } else tokpushback++; n1 = command(); if (readtoken() == TPIPE) { pipenode = (union node *)stalloc(sizeof(struct npipe)); pipenode->type = NPIPE; pipenode->npipe.backgnd = 0; lp = (struct nodelist *)stalloc(sizeof(struct nodelist)); pipenode->npipe.cmdlist = lp; lp->n = n1; do { prev = lp; lp = (struct nodelist *)stalloc(sizeof(struct nodelist)); checkkwd = CHKNL | CHKKWD | CHKALIAS; lp->n = command(); prev->next = lp; } while (readtoken() == TPIPE); lp->next = NULL; n1 = pipenode; } tokpushback++; if (negate) { n2 = (union node *)stalloc(sizeof(struct nnot)); n2->type = NNOT; n2->nnot.com = n1; return n2; } else return n1; } static union node *command(void) { union node *n1, *n2; union node *ap, **app; union node *cp, **cpp; union node *redir, **rpp; union node **rpp2; int t; int savelinno; redir = NULL; rpp2 = &redir; savelinno = plinno; switch (readtoken()) { default: synexpect(-1); unreachable; case TIF: n1 = (union node *)stalloc(sizeof(struct nif)); n1->type = NIF; n1->nif.test = list(0); if (readtoken() != TTHEN) synexpect(TTHEN); n1->nif.ifpart = list(0); n2 = n1; while (readtoken() == TELIF) { n2->nif.elsepart = (union node *)stalloc(sizeof(struct nif)); n2 = n2->nif.elsepart; n2->type = NIF; n2->nif.test = list(0); if (readtoken() != TTHEN) synexpect(TTHEN); n2->nif.ifpart = list(0); } if (lasttoken == TELSE) n2->nif.elsepart = list(0); else { n2->nif.elsepart = NULL; tokpushback++; } t = TFI; break; case TWHILE: case TUNTIL: { int got; n1 = (union node *)stalloc(sizeof(struct nbinary)); n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL; n1->nbinary.ch1 = list(0); if ((got = readtoken()) != TDO) { TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : "")); synexpect(TDO); } n1->nbinary.ch2 = list(0); t = TDONE; break; } case TFOR: if (readtoken() != TWORD || quoteflag || !goodname(wordtext)) synerror("Bad for loop variable"); n1 = (union node *)stalloc(sizeof(struct nfor)); n1->type = NFOR; n1->nfor.linno = savelinno; n1->nfor.var_ = wordtext; checkkwd = CHKNL | CHKKWD | CHKALIAS; if (readtoken() == TIN) { app = &ap; while (readtoken() == TWORD) { n2 = (union node *)stalloc(sizeof(struct narg)); n2->type = NARG; n2->narg.text = wordtext; n2->narg.backquote = backquotelist; *app = n2; app = &n2->narg.next; } *app = NULL; n1->nfor.args = ap; if (lasttoken != TNL && lasttoken != TSEMI) synexpect(-1); } else { n2 = (union node *)stalloc(sizeof(struct narg)); n2->type = NARG; n2->narg.text = (char *)dolatstr; n2->narg.backquote = NULL; n2->narg.next = NULL; n1->nfor.args = n2; /* * Newline or semicolon here is optional (but note * that the original Bourne shell only allowed NL). */ if (lasttoken != TSEMI) tokpushback++; } checkkwd = CHKNL | CHKKWD | CHKALIAS; if (readtoken() != TDO) synexpect(TDO); n1->nfor.body = list(0); t = TDONE; break; case TCASE: n1 = (union node *)stalloc(sizeof(struct ncase)); n1->type = NCASE; n1->ncase.linno = savelinno; if (readtoken() != TWORD) synexpect(TWORD); n1->ncase.expr = n2 = (union node *)stalloc(sizeof(struct narg)); n2->type = NARG; n2->narg.text = wordtext; n2->narg.backquote = backquotelist; n2->narg.next = NULL; checkkwd = CHKNL | CHKKWD | CHKALIAS; if (readtoken() != TIN) synexpect(TIN); cpp = &n1->ncase.cases; next_case: checkkwd = CHKNL | CHKKWD; t = readtoken(); while (t != TESAC) { if (lasttoken == TLP) readtoken(); *cpp = cp = (union node *)stalloc(sizeof(struct nclist)); cp->type = NCLIST; app = &cp->nclist.pattern; for (;;) { *app = ap = (union node *)stalloc(sizeof(struct narg)); ap->type = NARG; ap->narg.text = wordtext; ap->narg.backquote = backquotelist; if (readtoken() != TPIPE) break; app = &ap->narg.next; readtoken(); } ap->narg.next = NULL; if (lasttoken != TRP) synexpect(TRP); cp->nclist.body = list(2); cpp = &cp->nclist.next; checkkwd = CHKNL | CHKKWD; if ((t = readtoken()) != TESAC) { if (t != TENDCASE) synexpect(TENDCASE); else goto next_case; } } *cpp = NULL; goto redir; case TLP: n1 = (union node *)stalloc(sizeof(struct nredir)); n1->type = NSUBSHELL; n1->nredir.linno = savelinno; n1->nredir.n = list(0); n1->nredir.redirect = NULL; t = TRP; break; case TBEGIN: n1 = list(0); t = TEND; break; case TWORD: case TREDIR: tokpushback++; return simplecmd(); } if (readtoken() != t) synexpect(t); redir: /* Now check for redirection which may follow command */ checkkwd = CHKKWD | CHKALIAS; rpp = rpp2; while (readtoken() == TREDIR) { *rpp = n2 = redirnode; rpp = &n2->nfile.next; parsefname(); } tokpushback++; *rpp = NULL; if (redir) { if (n1->type != NSUBSHELL) { n2 = (union node *)stalloc(sizeof(struct nredir)); n2->type = NREDIR; n2->nredir.linno = savelinno; n2->nredir.n = n1; n1 = n2; } n1->nredir.redirect = redir; } return n1; } static union node *simplecmd(void) { union node *args, **app; union node *n = NULL; union node *vars, **vpp; union node **rpp, *redir; int savecheckkwd; int savelinno; args = NULL; app = &args; vars = NULL; vpp = &vars; redir = NULL; rpp = &redir; savecheckkwd = CHKALIAS; savelinno = plinno; for (;;) { checkkwd = savecheckkwd; switch (readtoken()) { case TWORD: n = (union node *)stalloc(sizeof(struct narg)); n->type = NARG; n->narg.text = wordtext; n->narg.backquote = backquotelist; if (savecheckkwd && isassignment(wordtext)) { *vpp = n; vpp = &n->narg.next; } else { *app = n; app = &n->narg.next; savecheckkwd = 0; } break; case TREDIR: *rpp = n = redirnode; rpp = &n->nfile.next; parsefname(); /* read name of redirection file */ break; case TLP: if (args && app == &args->narg.next && !vars && !redir) { struct builtincmd *bcmd; const char *name; /* We have a function */ if (readtoken() != TRP) synexpect(TRP); name = n->narg.text; if (!goodname(name) || ((bcmd = find_builtin(name)) && bcmd->flags & BUILTIN_SPECIAL)) synerror("Bad function name"); n->type = NDEFUN; checkkwd = CHKNL | CHKKWD | CHKALIAS; n->ndefun.text = n->narg.text; n->ndefun.linno = plinno; n->ndefun.body = command(); return n; } /* fall through */ default: tokpushback++; goto out; } } out: *app = NULL; *vpp = NULL; *rpp = NULL; n = (union node *)stalloc(sizeof(struct ncmd)); n->type = NCMD; n->ncmd.linno = savelinno; n->ncmd.args = args; n->ncmd.assign = vars; n->ncmd.redirect = redir; return n; } static union node *makename(void) { union node *n; n = (union node *)stalloc(sizeof(struct narg)); n->type = NARG; n->narg.next = NULL; n->narg.text = wordtext; n->narg.backquote = backquotelist; return n; } static void fixredir(union node *n, const char *text, int err) { TRACE(("Fix redir %s %d\n", text, err)); if (!err) n->ndup.vname = NULL; if (is_digit(text[0]) && text[1] == '\0') n->ndup.dupfd = digit_val(text[0]); else if (text[0] == '-' && text[1] == '\0') n->ndup.dupfd = -1; else { if (err) synerror("Bad fd number"); else n->ndup.vname = makename(); } } static void parsefname(void) { union node *n = redirnode; if (n->type == NHERE) checkkwd = CHKEOFMARK; if (readtoken() != TWORD) synexpect(-1); if (n->type == NHERE) { struct heredoc *here = heredoc; struct heredoc *p; if (quoteflag == 0) n->type = NXHERE; TRACE(("Here document %d\n", n->type)); rmescapes(wordtext, 0); here->eofmark = wordtext; here->next = NULL; if (heredoclist == NULL) heredoclist = here; else { for (p = heredoclist; p->next; p = p->next) ; p->next = here; } } else if (n->type == NTOFD || n->type == NFROMFD) { fixredir(n, wordtext, 0); } else { n->nfile.fname = makename(); } } /* * Input any here documents. */ static void parseheredoc(void) { struct heredoc *here; union node *n; here = heredoclist; heredoclist = 0; while (here) { if (needprompt) { setprompt(2); } if (here->here->type == NHERE) readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs); else readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs); n = (union node *)stalloc(sizeof(struct narg)); n->narg.type = NARG; n->narg.next = NULL; n->narg.text = wordtext; n->narg.backquote = backquotelist; here->here->nhere.doc = n; here = here->next; } } static int readtoken(void) { int t; int kwd = checkkwd; top: t = xxreadtoken(); /* * eat newlines */ if (kwd & CHKNL) { while (t == TNL) { parseheredoc(); checkkwd = 0; t = xxreadtoken(); } } kwd |= checkkwd; checkkwd = 0; if (t != TWORD || quoteflag) { goto out; } /* * check for keywords */ if (kwd & CHKKWD) { const char *const *pp; const int KWDOFFSET = 13; if ((pp = findkwd(wordtext))) { lasttoken = t = pp - parsekwd + KWDOFFSET; TRACE(("keyword %s recognized\n", tokname[t])); goto out; } } if (kwd & CHKALIAS) { struct alias *ap; if ((ap = lookupalias(wordtext, 1)) != NULL) { if (*ap->val) { pushstring(ap->val, ap); } goto top; } } out: return (t); } static void nlprompt(void) { plinno++; if (doprompt) setprompt(2); } static void nlnoprompt(void) { plinno++; needprompt = doprompt; } /* * Read the next input token. * If the token is a word, we set backquotelist to the list of cmds in * backquotes. We set quoteflag to true if any part of the word was * quoted. * If the token is TREDIR, then we set redirnode to a structure containing * the redirection. * * [Change comment: here documents and internal procedures] * [Readtoken shouldn't have any arguments. Perhaps we should make the * word parsing code into a separate routine. In this case, readtoken * doesn't need to have any internal procedures, but parseword does. * We could also make parseoperator in essence the main routine, and * have parseword (readtoken1?) handle both words and redirection.] */ static int xxreadtoken(void) { #define RETURN(token) return lasttoken = token int c; if (tokpushback) { tokpushback = 0; return lasttoken; } if (needprompt) { setprompt(2); } for (;;) { /* until token or start of word found */ c = pgetc_eatbnl(); switch (c) { case ' ': case '\t': continue; case '#': while ((c = pgetc()) != '\n' && c != PEOF) ; pungetc(); continue; case '\n': nlnoprompt(); RETURN(TNL); case PEOF: RETURN(TEOF); case '&': if (pgetc_eatbnl() == '&') RETURN(TAND); pungetc(); RETURN(TBACKGND); case '|': if (pgetc_eatbnl() == '|') RETURN(TOR); pungetc(); RETURN(TPIPE); case ';': if (pgetc_eatbnl() == ';') RETURN(TENDCASE); pungetc(); RETURN(TSEMI); case '(': RETURN(TLP); case ')': RETURN(TRP); } break; } return readtoken1(c, BASESYNTAX, (char *)NULL, 0); #undef RETURN } static int pgetc_eatbnl(void) { int c; while ((c = pgetc()) == '\\') { if (pgetc() != '\n') { pungetc(); break; } nlprompt(); } return c; } static int pgetc_top(struct synstack *stack) { return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl(); } static void synstack_push(struct synstack **stack, struct synstack *next, const char *syntax) { memset(next, 0, sizeof(*next)); next->syntax = syntax; next->next = *stack; (*stack)->prev = next; *stack = next; } static void synstack_pop(struct synstack **stack) { *stack = (*stack)->next; } /* * If eofmark is NULL, read a word or a redirection symbol. If eofmark * is not NULL, read a here document. In the latter case, eofmark is the * word which marks the end of the document and striptabs is true if * leading tabs should be stripped from the document. The argument firstc * is the first character of the input token or document. * * Because C does not have internal subroutines, I have simulated them * using goto's to implement the subroutine linkage. The following macros * will run code that appears at the end of readtoken1. */ #define CHECKEND() \ { \ goto checkend; \ checkend_return:; \ } #define PARSEREDIR() \ { \ goto parseredir; \ parseredir_return:; \ } #define PARSESUB() \ { \ goto parsesub; \ parsesub_return:; \ } #define PARSEBACKQOLD() \ { \ oldstyle = 1; \ goto parsebackq; \ parsebackq_oldreturn:; \ } #define PARSEBACKQNEW() \ { \ oldstyle = 0; \ goto parsebackq; \ parsebackq_newreturn:; \ } #define PARSEARITH() \ { \ goto parsearith; \ parsearith_return:; \ } static int readtoken1(int firstc, char const *syntax, char *eofmark, int striptabs) { int c = firstc; char *out; unsigned len; struct nodelist *bqlist; int quotef; int oldstyle; /* syntax stack */ struct synstack synbase = {.syntax = syntax}; struct synstack *synstack = &synbase; if (syntax == DQSYNTAX) synstack->dblquote = 1; quotef = 0; bqlist = NULL; STARTSTACKSTR(out); loop : { /* for each line, until end of word */ CHECKEND(); /* set c to PEOF if at end of here document */ for (;;) { /* until end of line or end of word */ CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ switch (synstack->syntax[c]) { case CNL: /* '\n' */ if (synstack->syntax == BASESYNTAX && !synstack->varnest) goto endword; /* exit outer loop */ USTPUTC(c, out); nlprompt(); c = pgetc_top(synstack); goto loop; /* continue outer loop */ case CWORD: USTPUTC(c, out); break; case CCTL: if ((!eofmark) | synstack->dblquote | synstack->varnest) USTPUTC(CTLESC, out); USTPUTC(c, out); break; /* backslash */ case CBACK: c = pgetc(); if (c == PEOF) { USTPUTC(CTLESC, out); USTPUTC('\\', out); pungetc(); } else { if (synstack->dblquote && c != '\\' && c != '`' && c != '$' && (c != '"' || (eofmark != NULL && !synstack->varnest)) && (c != '}' || !synstack->varnest)) { USTPUTC(CTLESC, out); USTPUTC('\\', out); } USTPUTC(CTLESC, out); USTPUTC(c, out); quotef++; } break; case CSQUOTE: synstack->syntax = SQSYNTAX; quotemark: if (eofmark == NULL) { USTPUTC(CTLQUOTEMARK, out); } break; case CDQUOTE: synstack->syntax = DQSYNTAX; synstack->dblquote = 1; toggledq: if (synstack->varnest) synstack->innerdq ^= 1; goto quotemark; case CENDQUOTE: if (eofmark && !synstack->varnest) { USTPUTC(c, out); break; } if (synstack->dqvarnest == 0) { synstack->syntax = BASESYNTAX; synstack->dblquote = 0; } quotef++; if (c == '"') goto toggledq; goto quotemark; case CVAR: /* '$' */ PARSESUB(); /* parse substitution */ break; case CENDVAR: /* '}' */ if (!synstack->innerdq && synstack->varnest > 0) { if (!--synstack->varnest && synstack->varpushed) synstack_pop(&synstack); else if (synstack->dqvarnest > 0) synstack->dqvarnest--; USTPUTC(CTLENDVAR, out); } else { USTPUTC(c, out); } break; case CLP: /* '(' in arithmetic */ synstack->parenlevel++; USTPUTC(c, out); break; case CRP: /* ')' in arithmetic */ if (synstack->parenlevel > 0) { USTPUTC(c, out); --synstack->parenlevel; } else { if (pgetc_eatbnl() == ')') { USTPUTC(CTLENDARI, out); synstack_pop(&synstack); } else { /* * unbalanced parens * (don't 2nd guess - no error) */ pungetc(); USTPUTC(')', out); } } break; case CBQUOTE: /* '`' */ if (checkkwd & CHKEOFMARK) { USTPUTC('`', out); break; } PARSEBACKQOLD(); break; case CEOF: goto endword; /* exit outer loop */ default: if (synstack->varnest == 0) goto endword; /* exit outer loop */ USTPUTC(c, out); } c = pgetc_top(synstack); } } endword: if (synstack->syntax == ARISYNTAX) synerror("Missing '))'"); if (synstack->syntax != BASESYNTAX && eofmark == NULL) synerror("Unterminated quoted string"); if (synstack->varnest != 0) { /* { */ synerror("Missing '}'"); } USTPUTC('\0', out); len = out - (char *)stackblock(); out = stackblock(); if (eofmark == NULL) { if ((c == '>' || c == '<') && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) { PARSEREDIR(); return lasttoken = TREDIR; } else { pungetc(); } } quoteflag = quotef; backquotelist = bqlist; grabstackblock(len); wordtext = out; return lasttoken = TWORD; /* end of readtoken routine */ /* * Check to see whether we are at the end of the here document. When this * is called, c is set to the first character of the next input line. If * we are at the end of the here document, this routine sets the c to PEOF. */ checkend : { if (realeofmark(eofmark)) { int markloc; char *p; if (striptabs) { while (c == '\t') c = pgetc(); } markloc = out - (char *)stackblock(); for (p = eofmark; STPUTC(c, out), *p; p++) { if (c != *p) goto more_heredoc; c = pgetc(); } if (c == '\n' || c == PEOF) { c = PEOF; nlnoprompt(); } else { int len2; more_heredoc: p = (char *)stackblock() + markloc + 1; len2 = out - p; if (len2) { len2 -= c < 0; c = p[-1]; if (len2) { char *str; str = alloca(len2 + 1); *(char *)mempcpy(str, p, len2) = 0; pushstring(str, NULL); } } } STADJUST((char *)stackblock() + markloc - out, out); } goto checkend_return; } /* * Parse a redirection operator. The variable "out" points to a string * specifying the fd to be redirected. The variable "c" contains the * first character of the redirection operator. */ parseredir : { char fd = *out; union node *np; np = (union node *)stalloc(sizeof(struct nfile)); if (c == '>') { np->nfile.fd = 1; c = pgetc_eatbnl(); if (c == '>') np->type = NAPPEND; else if (c == '|') np->type = NCLOBBER; else if (c == '&') np->type = NTOFD; else { np->type = NTO; pungetc(); } } else { /* c == '<' */ np->nfile.fd = 0; switch (c = pgetc_eatbnl()) { case '<': if (sizeof(struct nfile) != sizeof(struct nhere)) { np = (union node *)stalloc(sizeof(struct nhere)); np->nfile.fd = 0; } np->type = NHERE; heredoc = (struct heredoc *)stalloc(sizeof(struct heredoc)); heredoc->here = np; if ((c = pgetc_eatbnl()) == '-') { heredoc->striptabs = 1; } else { heredoc->striptabs = 0; pungetc(); } break; case '&': np->type = NFROMFD; break; case '>': np->type = NFROMTO; break; default: np->type = NFROM; pungetc(); break; } } if (fd != '\0') np->nfile.fd = digit_val(fd); redirnode = np; goto parseredir_return; } /* * Parse a substitution. At this point, we have read the dollar sign * and nothing else. */ parsesub : { int subtype; int typeloc; char *p; static const char types[] = "}-+?="; c = pgetc_eatbnl(); if ((checkkwd & CHKEOFMARK) || (c != '(' && c != '{' && !is_name(c) && !is_special(c))) { USTPUTC('$', out); pungetc(); } else if (c == '(') { /* $(command) or $((arith)) */ if (pgetc_eatbnl() == '(') { PARSEARITH(); } else { pungetc(); PARSEBACKQNEW(); } } else { const char *newsyn = synstack->syntax; USTPUTC(CTLVAR, out); typeloc = out - (char *)stackblock(); STADJUST(1, out); subtype = VSNORMAL; if (likely(c == '{')) { c = pgetc_eatbnl(); subtype = 0; } varname: if (is_name(c)) { do { STPUTC(c, out); c = pgetc_eatbnl(); } while (is_in_name(c)); } else if (is_digit(c)) { do { STPUTC(c, out); c = pgetc_eatbnl(); } while ((subtype <= 0 || subtype >= VSLENGTH) && is_digit(c)); } else if (c != '}') { int cc = c; c = pgetc_eatbnl(); if (!subtype && cc == '#') { subtype = VSLENGTH; if (c == '_' || isalnum(c)) goto varname; cc = c; c = pgetc_eatbnl(); if (cc == '}' || c != '}') { pungetc(); subtype = 0; c = cc; cc = '#'; } } if (!is_special(cc)) { if (subtype == VSLENGTH) subtype = 0; goto badsub; } USTPUTC(cc, out); } else goto badsub; if (subtype == 0) { int cc = c; switch (c) { case ':': subtype = VSNUL; c = pgetc_eatbnl(); /*FALLTHROUGH*/ default: p = strchr(types, c); if (p == NULL) break; subtype |= p - types + VSNORMAL; break; case '%': case '#': subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT; c = pgetc_eatbnl(); if (c == cc) subtype++; else pungetc(); newsyn = BASESYNTAX; break; } } else { if (subtype == VSLENGTH && c != '}') subtype = 0; badsub: pungetc(); } if (newsyn == ARISYNTAX) newsyn = DQSYNTAX; if ((newsyn != synstack->syntax || synstack->innerdq) && subtype != VSNORMAL) { synstack_push(&synstack, synstack->prev ?: alloca(sizeof(*synstack)), newsyn); synstack->varpushed++; synstack->dblquote = newsyn != BASESYNTAX; } *((char *)stackblock() + typeloc) = subtype; if (subtype != VSNORMAL) { synstack->varnest++; if (synstack->dblquote) synstack->dqvarnest++; } STPUTC('=', out); } goto parsesub_return; } /* * Called to parse command substitutions. Newstyle is set if the command * is enclosed inside $(...); nlpp is a pointer to the head of the linked * list of commands (passed by reference), and savelen is the number of * characters on the top of the stack which must be preserved. */ parsebackq : { struct nodelist **nlpp; union node *n; char *str; unsigned savelen; struct heredoc *saveheredoclist; int uninitialized_var(saveprompt); str = NULL; savelen = out - (char *)stackblock(); if (savelen > 0) { str = alloca(savelen); memcpy(str, stackblock(), savelen); } if (oldstyle) { /* We must read until the closing backquote, giving special treatment to some slashes, and then push the string and reread it as input, interpreting it normally. */ char *pout; int pc; unsigned psavelen; char *pstr; STARTSTACKSTR(pout); for (;;) { if (needprompt) { setprompt(2); } switch (pc = pgetc_eatbnl()) { case '`': goto done; case '\\': pc = pgetc(); if (pc != '\\' && pc != '`' && pc != '$' && (!synstack->dblquote || pc != '"')) STPUTC('\\', pout); break; case PEOF: synerror("EOF in backquote substitution"); case '\n': nlnoprompt(); break; default: break; } STPUTC(pc, pout); } done: STPUTC('\0', pout); psavelen = pout - (char *)stackblock(); if (psavelen > 0) { pstr = grabstackstr(pout); setinputstring(pstr); } } nlpp = &bqlist; while (*nlpp) nlpp = &(*nlpp)->next; *nlpp = (struct nodelist *)stalloc(sizeof(struct nodelist)); (*nlpp)->next = NULL; saveheredoclist = heredoclist; heredoclist = NULL; if (oldstyle) { saveprompt = doprompt; doprompt = 0; } n = list(2); if (oldstyle) doprompt = saveprompt; else { if (readtoken() != TRP) synexpect(TRP); setinputstring(nullstr); } parseheredoc(); heredoclist = saveheredoclist; (*nlpp)->n = n; /* Start reading from old file again. */ popfile(); /* Ignore any pushed back tokens left from the backquote parsing. */ if (oldstyle) tokpushback = 0; out = growstackto(savelen + 1); if (str) { memcpy(out, str, savelen); STADJUST(savelen, out); } USTPUTC(CTLBACKQ, out); if (oldstyle) goto parsebackq_oldreturn; else goto parsebackq_newreturn; } /* * Parse an arithmetic expansion (indicate start of one and set state) */ parsearith : { synstack_push(&synstack, synstack->prev ?: alloca(sizeof(*synstack)), ARISYNTAX); synstack->dblquote = 1; USTPUTC(CTLARI, out); goto parsearith_return; } } /* end of readtoken */ static void setprompt(int which) { struct stackmark smark; int show; needprompt = 0; whichprompt = which; show = 0; if (show) { pushstackmark(&smark, stackblocksize()); outstr(getprompt(NULL), out2); popstackmark(&smark); } } static const char *expandstr(const char *ps) { struct parsefile *file_stop; struct jmploc *volatile savehandler; struct heredoc *saveheredoclist; const char *result; int saveprompt; struct jmploc jmploc; union node n; int err; file_stop = parsefile; setinputstring((char *)ps); /* XXX Fix (char *) cast. */ saveheredoclist = heredoclist; heredoclist = NULL; saveprompt = doprompt; doprompt = 0; result = ps; savehandler = handler; if (unlikely(err = setjmp(jmploc.loc))) goto out; handler = &jmploc; readtoken1(pgetc_eatbnl(), DQSYNTAX, FAKEEOFMARK, 0); n.narg.type = NARG; n.narg.next = NULL; n.narg.text = wordtext; n.narg.backquote = backquotelist; expandarg(&n, NULL, EXP_QUOTED); result = stackblock(); out: handler = savehandler; if (err && exception != EXERROR) longjmp(handler->loc, 1); doprompt = saveprompt; unwindfiles(file_stop); heredoclist = saveheredoclist; return result; } /* * called by editline -- any expansions to the prompt * should be added here. */ static const char *getprompt(void *unused) { const char *prompt; switch (whichprompt) { default: case 0: return nullstr; case 1: prompt = ps1val(); break; case 2: prompt = ps2val(); break; } return expandstr(prompt); } const char *const *findkwd(const char *s) { return findstring(s, parsekwd, sizeof(parsekwd) / sizeof(const char *)); } static unsigned update_closed_redirs(int fd, int nfd) { unsigned val = closed_redirs; unsigned bit = 1 << fd; if (nfd >= 0) closed_redirs &= ~bit; else closed_redirs |= bit; return val & bit; } /* * Process a list of redirection commands. If the REDIR_PUSH flag is set, * old file descriptors are stashed away so that the redirection can be * undone by calling popredir. If the REDIR_BACKQ flag is set, then the * standard output, and the standard error if it becomes a duplicate of * stdout, is saved in memory. */ static void redirect(union node *redir, int flags) { union node *n; struct redirtab *sv; int i; int fd; int newfd; int *p; if (!redir) return; sv = NULL; INTOFF; if (likely(flags & REDIR_PUSH)) sv = redirlist; n = redir; do { newfd = openredirect(n); if (newfd < -1) continue; fd = n->nfile.fd; if (sv) { int closed; p = &sv->renamed[fd]; i = *p; closed = update_closed_redirs(fd, newfd); if (likely(i == EMPTY)) { i = CLOSED; if (fd != newfd && !closed) { i = savefd(fd, fd); fd = -1; } } *p = i; } if (fd == newfd) continue; dupredirect(n, newfd); } while ((n = n->nfile.next)); INTON; if (flags & REDIR_SAVEFD2 && sv->renamed[2] >= 0) preverrout.fd = sv->renamed[2]; } wontreturn static int sh_open_fail(const char *pathname, int flags, int e) { const char *word; int action; word = "open"; action = E_OPEN; if (flags & O_CREAT) { word = "create"; action = E_CREAT; } sh_error("cannot %s %s: %s", word, pathname, errmsg(e, action)); } static int sh_open(const char *pathname, int flags, int mayfail) { int fd; int e; do { fd = open(pathname, flags, 0666); e = errno; } while (fd < 0 && e == EINTR && !pending_sig); if (mayfail || fd >= 0) return fd; sh_open_fail(pathname, flags, e); } static int openredirect(union node *redir) { struct stat sb; char *fname; int flags; int f; switch (redir->nfile.type) { case NFROM: flags = O_RDONLY; do_open: f = sh_open(redir->nfile.expfname, flags, 0); break; case NFROMTO: flags = O_RDWR|O_CREAT; goto do_open; case NTO: /* Take care of noclobber mode. */ if (Cflag) { fname = redir->nfile.expfname; if (stat(fname, &sb) < 0) { flags = O_WRONLY|O_CREAT|O_EXCL; goto do_open; } if (S_ISREG(sb.st_mode)) goto ecreate; f = sh_open(fname, O_WRONLY, 0); if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) { close(f); goto ecreate; } break; } /* FALLTHROUGH */ case NCLOBBER: flags = O_WRONLY|O_CREAT|O_TRUNC; goto do_open; case NAPPEND: flags = O_WRONLY|O_CREAT|O_APPEND; goto do_open; case NTOFD: case NFROMFD: f = redir->ndup.dupfd; if (f == redir->nfile.fd) f = -2; break; default: /* Fall through to eliminate warning. */ case NHERE: case NXHERE: f = openhere(redir); break; } return f; ecreate: sh_open_fail(fname, O_CREAT, EEXIST); } static void dupredirect(union node *redir, int f) { int fd = redir->nfile.fd; int err = 0; if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) { /* if not ">&-" */ if (f >= 0) { if (dup2(f, fd) < 0) { err = errno; goto err; } return; } f = fd; } else if (dup2(f, fd) < 0) { err = errno; } close(f); if (err < 0) goto err; return; err: sh_error("%ld: %s", f, strerror(err)); } /* * Handle here documents. Normally we fork off a process to write the * data to a pipe. If the document is short, we can stuff the data in * the pipe without forking. */ static int64_t openhere(union node *redir) { char *p; int pip[2]; unsigned len = 0; if (pipe(pip) < 0) sh_error("Pipe call failed"); p = redir->nhere.doc->narg.text; if (redir->type == NXHERE) { expandarg(redir->nhere.doc, NULL, EXP_QUOTED); p = stackblock(); } len = strlen(p); if (len <= PIPESIZE) { xwrite(pip[1], p, len); goto out; } if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) { close(pip[0]); signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_DFL); xwrite(pip[1], p, len); _exit(0); } out: close(pip[1]); return pip[0]; } /* * Undo the effects of the last redirection. */ static void popredir(int drop) { struct redirtab *rp; int i; INTOFF; rp = redirlist; for (i = 0; i < 10; i++) { int closed; if (rp->renamed[i] == EMPTY) continue; closed = drop ? 1 : update_closed_redirs(i, rp->renamed[i]); switch (rp->renamed[i]) { case CLOSED: if (!closed) close(i); break; default: if (!drop) dup2(rp->renamed[i], i); close(rp->renamed[i]); break; } } redirlist = rp->next; ckfree(rp); INTON; } /* * Move a file descriptor to > 10. Invokes sh_error on error unless * the original file dscriptor is not open. */ static int savefd(int from, int ofd) { int newfd; int err; newfd = fcntl(from, F_DUPFD, 10); err = newfd < 0 ? errno : 0; if (err != EBADF) { close(ofd); if (err) { sh_error("%d: %s", from, strerror(err)); } else { fcntl(newfd, F_SETFD, FD_CLOEXEC); } } return newfd; } static int redirectsafe(union node *redir, int flags) { int err; volatile int saveint; struct jmploc *volatile savehandler = handler; struct jmploc jmploc; SAVEINT(saveint); if (!(err = setjmp(jmploc.loc) * 2)) { handler = &jmploc; redirect(redir, flags); } handler = savehandler; if (err && exception != EXERROR) longjmp(handler->loc, 1); RESTOREINT(saveint); return err; } static void unwindredir(struct redirtab *stop) { while (redirlist != stop) popredir(0); } static struct redirtab *pushredir(union node *redir) { struct redirtab *sv; struct redirtab *q; int i; q = redirlist; if (!redir) goto out; sv = ckmalloc(sizeof(struct redirtab)); sv->next = q; redirlist = sv; for (i = 0; i < 10; i++) sv->renamed[i] = EMPTY; out: return q; } /* * The trap builtin. */ static int trapcmd(int argc, char **argv) { char *action; char **ap; int signo; nextopt(nullstr); ap = argptr; if (!*ap) { for (signo = 0; signo < NSIG; signo++) { if (trap[signo] != NULL) { out1fmt("trap -- %s %s\n", single_quote(trap[signo]), strsignal(signo)); } } return 0; } if (!ap[1] || decode_signum(*ap) >= 0) action = NULL; else action = *ap++; while (*ap) { if ((signo = decode_signal(*ap, 0)) < 0) { outfmt(out2, "trap: %s: bad trap\n", *ap); return 1; } INTOFF; if (action) { if (action[0] == '-' && action[1] == '\0') action = NULL; else { if (*action) trapcnt++; action = savestr(action); } } if (trap[signo]) { if (*trap[signo]) trapcnt--; ckfree(trap[signo]); } trap[signo] = action; if (signo != 0) setsignal(signo); INTON; ap++; } return 0; } /* * Set the signal handler for the specified signal. The routine figures * out what it should be set to. */ static void setsignal(int signo) { int action; int lvforked; char *t, tsig; struct sigaction act; lvforked = vforked; if ((t = trap[signo]) == NULL) action = S_DFL; else if (*t != '\0') action = S_CATCH; else action = S_IGN; if (rootshell && action == S_DFL && !lvforked) { if (signo == SIGINT) { if (iflag || minusc || sflag == 0) action = S_CATCH; } else if (signo == SIGQUIT || signo == SIGTERM) { if (iflag) action = S_IGN; } else if (signo == SIGTSTP || signo == SIGTTOU) { if (mflag) action = S_IGN; } } if (signo == SIGCHLD) action = S_CATCH; t = &sigmode[signo - 1]; tsig = *t; if (tsig == 0) { /* * current setting unknown */ if (sigaction(signo, 0, &act) == -1) { /* * Pretend it worked; maybe we should give a warning * here, but other shells don't. We don't alter * sigmode, so that we retry every time. */ return; } if (act.sa_handler == SIG_IGN) { if (mflag && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)) { tsig = S_IGN; /* don't hard ignore these */ } else tsig = S_HARD_IGN; } else { tsig = S_RESET; /* force to be set */ } } if (tsig == S_HARD_IGN || tsig == action) return; switch (action) { case S_CATCH: act.sa_handler = onsig; break; case S_IGN: act.sa_handler = SIG_IGN; break; default: act.sa_handler = SIG_DFL; } if (!lvforked) *t = action; act.sa_flags = 0; sigfillset(&act.sa_mask); sigaction(signo, &act, 0); } /* * Ignore a signal. */ static void ignoresig(int signo) { if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) { signal(signo, SIG_IGN); } if (!vforked) sigmode[signo - 1] = S_HARD_IGN; } /* * Signal handler. */ static void onsig(int signo) { if (vforked) return; if (signo == SIGCHLD) { gotsigchld = 1; if (!trap[SIGCHLD]) return; } gotsig[signo - 1] = 1; pending_sig = signo; if (signo == SIGINT && !trap[SIGINT]) { if (!suppressint) onint(); intpending = 1; } } /* * Called to execute a trap. Perhaps we should avoid entering new trap * handlers while we are executing a trap handler. */ static void dotrap(void) { char *p; char *q; int i; int status, last_status; if (!pending_sig) return; status = savestatus; last_status = status; if (likely(status < 0)) { status = exitstatus; savestatus = status; } pending_sig = 0; barrier(); for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) { if (!*q) continue; if (evalskip) { pending_sig = i + 1; break; } *q = 0; p = trap[i + 1]; if (!p) continue; evalstring(p, 0); if (evalskip != SKIPFUNC) exitstatus = status; } savestatus = last_status; } /* * Controls whether the shell is interactive or not. */ static void setinteractive(int on) { static int is_interactive; if (++on == is_interactive) return; is_interactive = on; setsignal(SIGINT); setsignal(SIGQUIT); setsignal(SIGTERM); } /* * Called to exit the shell. */ wontreturn static void exitshell(void) { struct jmploc loc; char *p; savestatus = exitstatus; TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus)); if (setjmp(loc.loc)) goto out; handler = &loc; if ((p = trap[0])) { trap[0] = NULL; evalskip = 0; evalstring(p, 0); evalskip = SKIPFUNCDEF; } out: exitreset(); /* * Disable job control so that whoever had the foreground before we * started can get it back. */ if (likely(!setjmp(loc.loc))) setjobctl(0); flushall(); _exit(exitstatus); } static int decode_signal(const char *string, int minsig) { int signo; signo = decode_signum(string); if (signo >= 0) return signo; for (signo = minsig; signo < NSIG; signo++) { if (!strcasecmp(string, strsignal(signo))) { return signo; } } return -1; } static void sigblockall(sigset_t *oldmask) { sigset_t mask; sigfillset(&mask); sigprocmask(SIG_SETMASK, &mask, oldmask); } #define PF(f, func) \ { \ switch ((char *)param - (char *)array) { \ default: \ (void)Printf(f, array[0], array[1], func); \ break; \ case sizeof(*param): \ (void)Printf(f, array[0], func); \ break; \ case 0: \ (void)Printf(f, func); \ break; \ } \ } #define ASPF(sp, f, func) \ ({ \ int ret; \ switch ((char *)param - (char *)array) { \ default: \ ret = Xasprintf(sp, f, array[0], array[1], func); \ break; \ case sizeof(*param): \ ret = Xasprintf(sp, f, array[0], func); \ break; \ case 0: \ ret = Xasprintf(sp, f, func); \ break; \ } \ ret; \ }) static int print_escape_str(const char *f, int *param, int *array, char *s) { struct stackmark smark; char *p, *q; int done; int len; int total; setstackmark(&smark); done = conv_escape_str(s, &q); p = stackblock(); len = q - p; total = len - 1; q[-1] = (!!((f[1] - 's') | done) - 1) & f[2]; total += !!q[-1]; if (f[1] == 's') goto easy; p = makestrspace(len, q); memset(p, 'X', total); p[total] = 0; q = stackblock(); total = ASPF(&p, f, p); len = strchrnul(p, 'X') - p; memcpy(p + len, q, strspn(p + len, "X")); easy: outmem(p, total, out1); popstackmark(&smark); return done; } static int printfcmd(int argc, char *argv[]) { static const char kSkip1[] = "#-+ 0"; static const char kSkip2[] = "*0123456789"; char *fmt; char *format; int ch; rval = 0; nextopt(nullstr); argv = argptr; format = *argv; if (!format) sh_error("usage: printf format [arg ...]"); gargv = ++argv; do { /* * Basic algorithm is to scan the format string for conversion * specifications -- once one is found, find out if the field * width or precision is a '*'; if it is, gather up value. * Note, format strings are reused as necessary to use up the * provided arguments, arguments of zero/null string are * provided to use up the format string. */ /* find next format specification */ for (fmt = format; (ch = *fmt++);) { char *start; char nextch; int array[2]; int *param; if (ch == '\\') { int c_ch; fmt = conv_escape(fmt, &c_ch); ch = c_ch; goto pc; } if (ch != '%' || (*fmt == '%' && (++fmt || 1))) { pc: outc(ch, out1); continue; } /* Ok - we've found a format specification, Save its address for a later printf(). */ start = fmt - 1; param = array; /* skip to field width */ fmt += strspn(fmt, kSkip1); if (*fmt == '*') { ++fmt; *param++ = getuintmax(1); } else { /* skip to possible '.', * get following precision */ fmt += strspn(fmt, kSkip2); } if (*fmt == '.') { ++fmt; if (*fmt == '*') { ++fmt; *param++ = getuintmax(1); } else fmt += strspn(fmt, kSkip2); } ch = *fmt; if (!ch) sh_error("missing format character"); /* null terminate format string to we can use it as an argument to printf. */ nextch = fmt[1]; fmt[1] = 0; switch (ch) { case 'b': *fmt = 's'; /* escape if a \c was encountered */ if (print_escape_str(start, param, array, getstr())) goto out; *fmt = 'b'; break; case 'c': { int p = getchr(); PF(start, p); break; } case 's': { char *p = getstr(); PF(start, p); break; } case 'd': case 'i': { uint64_t p = getuintmax(1); start = mklong(start, fmt); PF(start, p); break; } case 'o': case 'u': case 'x': case 'X': { uint64_t p = getuintmax(0); start = mklong(start, fmt); PF(start, p); break; } case 'a': case 'A': case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': { double p = getdouble(); PF(start, p); break; } default: sh_error("%s: invalid directive", start); } *++fmt = nextch; } } while (gargv != argv && *gargv); out: return rval; } /* * Print SysV echo(1) style escape string * Halts processing string if a \c escape is encountered. */ static int conv_escape_str(char *str, char **sp) { int c; int ch; char *cp; /* convert string into a temporary buffer... */ STARTSTACKSTR(cp); do { c = ch = *str++; if (ch != '\\') continue; c = *str++; if (c == 'c') { /* \c as in SYSV echo - abort all processing.... */ c = ch = 0x100; continue; } /* * %b string octal constants are not like those in C. * They start with a \0, and are followed by 0, 1, 2, * or 3 octal digits. */ if (c == '0' && isodigit(*str)) str++; /* Finally test for sequences valid in the format string */ str = conv_escape(str - 1, &c); } while (STPUTC(c, cp), (char)ch); *sp = cp; return ch; } /* * Print "standard" escape characters */ static char *conv_escape(char *str, int *conv_ch) { int value; int ch; ch = *str; switch (ch) { default: if (!isodigit(*str)) { value = '\\'; goto out; } ch = 3; value = 0; do { value <<= 3; value += octtobin(*str++); } while (isodigit(*str) && --ch); goto out; case '\\': value = '\\'; break; /* backslash */ case 'a': value = '\a'; break; /* alert */ case 'b': value = '\b'; break; /* backspace */ case 'f': value = '\f'; break; /* form-feed */ case 'e': value = '\e'; break; /* escape */ case 'n': value = '\n'; break; /* newline */ case 'r': value = '\r'; break; /* carriage-return */ case 't': value = '\t'; break; /* tab */ case 'v': value = '\v'; break; /* vertical-tab */ } str++; out: *conv_ch = value; return str; } #define PRIdMAX "ld" static char *mklong(const char *str, const char *ch) { /* * Replace a string like "%92.3u" with "%92.3"PRIuMAX. * * Although C99 does not guarantee it, we assume PRIiMAX, * PRIoMAX, PRIuMAX, PRIxMAX, and PRIXMAX are all the same * as PRIdMAX with the final 'd' replaced by the corresponding * character. */ char *copy; unsigned len; len = ch - str + sizeof(PRIdMAX); STARTSTACKSTR(copy); copy = makestrspace(len, copy); memcpy(copy, str, len - sizeof(PRIdMAX)); memcpy(copy + len - sizeof(PRIdMAX), PRIdMAX, sizeof(PRIdMAX)); copy[len - 2] = *ch; return (copy); } static uint64_t getuintmax(int sign) { uint64_t val = 0; char *cp, *ep; cp = *gargv; if (cp == NULL) goto out; gargv++; val = (unsigned char)cp[1]; if (*cp == '\"' || *cp == '\'') goto out; errno = 0; val = sign ? strtoimax(cp, &ep, 0) : strtoumax(cp, &ep, 0); check_conversion(cp, ep); out: return val; } static double getdouble(void) { double val; char *cp, *ep; cp = *gargv; if (cp == NULL) return 0; gargv++; if (*cp == '\"' || *cp == '\'') return (unsigned char)cp[1]; errno = 0; val = strtod(cp, &ep); check_conversion(cp, ep); return val; } static void check_conversion(const char *s, const char *ep) { if (*ep) { if (ep == s) sh_warnx("%s: expected numeric value", s); else sh_warnx("%s: not completely converted", s); rval = 1; } else if (errno == ERANGE) { sh_warnx("%s: %s", s, strerror(ERANGE)); rval = 1; } } static int echocmd(int argc, char **argv) { const char *lastfmt = snlfmt; int nonl; if (*++argv && equal(*argv, "-n")) { argv++; lastfmt = "%s"; } do { const char *fmt = "%s "; char *s = *argv; if (!s || !*++argv) fmt = lastfmt; nonl = print_escape_str(fmt, NULL, NULL, s ?: nullstr); } while (!nonl && *argv); return 0; } /* * test(1); version 7-like -- author Erik Baalbergen * modified by Eric Gisin to be used as built-in. * modified by Arnold Robbins to add SVR3 compatibility * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket). * modified by J.T. Conklin for NetBSD. * * This program is in the Public Domain. */ /* test(1) accepts the following grammar: oexpr ::= aexpr | aexpr "-o" oexpr ; aexpr ::= nexpr | nexpr "-a" aexpr ; nexpr ::= primary | "!" primary primary ::= unary-operator operand | operand binary-operator operand | operand | "(" oexpr ")" ; unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"| "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S"; binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"| "-nt"|"-ot"|"-ef"; operand ::= <any legal UNIX file name> */ static inline int faccessat_confused_about_superuser(void) { return 0; } static const struct t_op *getop(const char *s) { const struct t_op *op; for (op = ops; op->op_text; op++) { if (strcmp(s, op->op_text) == 0) return op; } return NULL; } static int testcmd(int argc, char **argv) { const struct t_op *op; enum token n; int res = 1; if (*argv[0] == '[') { if (*argv[--argc] != ']') sh_error("missing ]"); argv[argc] = NULL; } t_wp_op = NULL; recheck: argv++; argc--; if (argc < 1) return res; /* * POSIX prescriptions: he who wrote this deserves the Nobel * peace prize. */ switch (argc) { case 3: op = getop(argv[1]); if (op && op->op_type == BINOP) { n = OPERAND; goto eval; } /* fall through */ case 4: if (!strcmp(argv[0], "(") && !strcmp(argv[argc - 1], ")")) { argv[--argc] = NULL; argv++; argc--; } else if (!strcmp(argv[0], "!")) { res = 0; goto recheck; } } n = t_lex(argv); eval: t_wp = argv; res ^= oexpr(n); argv = t_wp; if (argv[0] != NULL && argv[1] != NULL) syntax(argv[0], "unexpected operator"); return res; } static void syntax(const char *op, const char *msg) { if (op && *op) { sh_error("%s: %s", op, msg); } else { sh_error("%s", msg); } } static int oexpr(enum token n) { int res = 0; for (;;) { res |= aexpr(n); n = t_lex(t_wp + 1); if (n != BOR) break; n = t_lex(t_wp += 2); } return res; } static int aexpr(enum token n) { int res = 1; for (;;) { if (!nexpr(n)) res = 0; n = t_lex(t_wp + 1); if (n != BAND) break; n = t_lex(t_wp += 2); } return res; } static int nexpr(enum token n) { if (n != UNOT) return primary1(n); n = t_lex(t_wp + 1); if (n != EOI) t_wp++; return !nexpr(n); } static int primary1(enum token n) { enum token nn; int res; if (n == EOI) return 0; /* missing expression */ if (n == LPAREN) { if ((nn = t_lex(++t_wp)) == RPAREN) return 0; /* missing expression */ res = oexpr(nn); if (t_lex(++t_wp) != RPAREN) syntax(NULL, "closing paren expected"); return res; } if (t_wp_op && t_wp_op->op_type == UNOP) { /* unary expression */ if (*++t_wp == NULL) syntax(t_wp_op->op_text, "argument expected"); switch (n) { case STREZ: return strlen(*t_wp) == 0; case STRNZ: return strlen(*t_wp) != 0; case FILTT: return isatty(getn(*t_wp)); case FILRD: return test_file_access(*t_wp, R_OK); case FILWR: return test_file_access(*t_wp, W_OK); case FILEX: return test_file_access(*t_wp, X_OK); default: return filstat(*t_wp, n); } } if (t_lex(t_wp + 1), t_wp_op && t_wp_op->op_type == BINOP) { return binop0(); } return strlen(*t_wp) > 0; } static int binop0(void) { const char *opnd1, *opnd2; struct t_op const *op; opnd1 = *t_wp; (void)t_lex(++t_wp); op = t_wp_op; if ((opnd2 = *++t_wp) == (char *)0) syntax(op->op_text, "argument expected"); switch (op->op_num) { default: case STREQ: return strcmp(opnd1, opnd2) == 0; case STRNE: return strcmp(opnd1, opnd2) != 0; case STRLT: return strcmp(opnd1, opnd2) < 0; case STRGT: return strcmp(opnd1, opnd2) > 0; case INTEQ: return getn(opnd1) == getn(opnd2); case INTNE: return getn(opnd1) != getn(opnd2); case INTGE: return getn(opnd1) >= getn(opnd2); case INTGT: return getn(opnd1) > getn(opnd2); case INTLE: return getn(opnd1) <= getn(opnd2); case INTLT: return getn(opnd1) < getn(opnd2); case FILNT: return newerf(opnd1, opnd2); case FILOT: return olderf(opnd1, opnd2); case FILEQ: return equalf(opnd1, opnd2); } } static int filstat(char *nm, enum token mode) { struct stat s; if (mode == FILSYM ? lstat(nm, &s) : stat(nm, &s)) return 0; switch (mode) { case FILEXIST: return 1; case FILREG: return S_ISREG(s.st_mode); case FILDIR: return S_ISDIR(s.st_mode); case FILCDEV: return S_ISCHR(s.st_mode); case FILBDEV: return S_ISBLK(s.st_mode); case FILFIFO: return S_ISFIFO(s.st_mode); case FILSOCK: return S_ISSOCK(s.st_mode); case FILSYM: return S_ISLNK(s.st_mode); case FILSUID: return (s.st_mode & S_ISUID) != 0; case FILSGID: return (s.st_mode & S_ISGID) != 0; case FILSTCK: return (s.st_mode & S_ISVTX) != 0; case FILGZ: return !!s.st_size; case FILUID: return s.st_uid == geteuid(); case FILGID: return s.st_gid == getegid(); default: return 1; } } static enum token t_lex(char **tp) { struct t_op const *op; char *s = *tp; if (s == 0) { t_wp_op = (struct t_op *)0; return EOI; } op = getop(s); if (op && !(op->op_type == UNOP && isoperand(tp)) && !(op->op_num == LPAREN && !tp[1])) { t_wp_op = op; return op->op_num; } t_wp_op = (struct t_op *)0; return OPERAND; } static int isoperand(char **tp) { struct t_op const *op; char *s; if (!(s = tp[1])) return 1; if (!tp[2]) return 0; op = getop(s); return op && op->op_type == BINOP; } static int newerf(const char *f1, const char *f2) { struct stat b1, b2; return (stat(f1, &b1) == 0 && stat(f2, &b2) == 0 && (b1.st_mtim.tv_sec > b2.st_mtim.tv_sec || (b1.st_mtim.tv_sec == b2.st_mtim.tv_sec && (b1.st_mtim.tv_nsec > b2.st_mtim.tv_nsec)))); } static int olderf(const char *f1, const char *f2) { struct stat b1, b2; return (stat(f1, &b1) == 0 && stat(f2, &b2) == 0 && (b1.st_mtim.tv_sec < b2.st_mtim.tv_sec || (b1.st_mtim.tv_sec == b2.st_mtim.tv_sec && (b1.st_mtim.tv_nsec < b2.st_mtim.tv_nsec)))); } static int equalf(const char *f1, const char *f2) { struct stat b1, b2; return (stat(f1, &b1) == 0 && stat(f2, &b2) == 0 && b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino); } static int has_exec_bit_set(const char *path) { struct stat st; if (stat(path, &st)) return 0; return st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH); } static int test_file_access(const char *path, int mode) { if (faccessat_confused_about_superuser() && mode == X_OK && geteuid() == 0 && !has_exec_bit_set(path)) { return 0; } return !faccessat(AT_FDCWD, path, mode, AT_EACCESS); } static int timescmd() { struct tms buf; long int clk_tck = sysconf(_SC_CLK_TCK); int mutime, mstime, mcutime, mcstime; double utime, stime, cutime, cstime; times(&buf); utime = (double)buf.tms_utime / clk_tck; mutime = utime / 60; utime -= mutime * 60.0; stime = (double)buf.tms_stime / clk_tck; mstime = stime / 60; stime -= mstime * 60.0; cutime = (double)buf.tms_cutime / clk_tck; mcutime = cutime / 60; cutime -= mcutime * 60.0; cstime = (double)buf.tms_cstime / clk_tck; mcstime = cstime / 60; cstime -= mcstime * 60.0; Printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n", mutime, utime, mstime, stime, mcutime, cutime, mcstime, cstime); return 0; } /* * Find the appropriate entry in the hash table from the name. */ static struct Var **hashvar(const char *p) { unsigned int hashval; hashval = ((unsigned char)*p) << 4; while (*p && *p != '=') hashval += (unsigned char)*p++; return &vartab[hashval % VTABSIZE]; } /* * This routine initializes the builtin variables. It is called when the * shell is initialized. */ static void initvar(void) { struct Var *vp; struct Var *end; struct Var **vpp; vp = varinit; end = vp + sizeof(varinit) / sizeof(varinit[0]); do { vpp = hashvar(vp->text); vp->next = *vpp; *vpp = vp; } while (++vp < end); /* PS1 depends on uid */ if (!geteuid()) { vps1.text = "PS1=# "; } } /* * Set the value of a variable. The flags argument is ored with the * flags of the variable. If val is NULL, the variable is unset. */ static struct Var *setvar(const char *name, const char *val, int flags) { char *p, *q; unsigned namelen; char *nameeq; unsigned vallen; struct Var *vp; q = endofname(name); p = strchrnul(q, '='); namelen = p - name; if (!namelen || p != q) sh_error("%.*s: bad variable name", namelen, name); vallen = 0; if (val == NULL) { flags |= VUNSET; } else { vallen = strlen(val); } INTOFF; p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen); if (val) { *p++ = '='; p = mempcpy(p, val, vallen); } *p = '\0'; vp = setvareq(nameeq, flags | VNOSAVE); INTON; return vp; } /* * Set the given integer as the value of a variable. The flags argument is * ored with the flags of the variable. */ static int64_t setvarint(const char *name, int64_t val, int flags) { int len = max_int_length(sizeof(val)); char buf[len]; fmtstr(buf, len, "%ld", val); setvar(name, buf, flags); return val; } static struct Var **findvar(struct Var **vpp, const char *name) { for (; *vpp; vpp = &(*vpp)->next) { if (varequal((*vpp)->text, name)) { break; } } return vpp; } /* * Same as setvar except that the variable and value are passed in * the first argument as name=value. Since the first argument will * be actually stored in the table, it should not be a string that * will go away. * Called with interrupts off. */ static struct Var *setvareq(char *s, int flags) { struct Var *vp, **vpp; vpp = hashvar(s); flags |= (VEXPORT & (((unsigned)(1 - aflag)) - 1)); vpp = findvar(vpp, s); vp = *vpp; if (vp) { if (vp->flags & VREADONLY) { const char *n; if (flags & VNOSAVE) free(s); n = vp->text; sh_error("%.*s: is read only", strchrnul(n, '=') - n, n); } if (flags & VNOSET) goto out; if (vp->func && (flags & VNOFUNC) == 0) (*vp->func)(strchrnul(s, '=') + 1); if ((vp->flags & (VTEXTFIXED | VSTACK)) == 0) ckfree(vp->text); if (((flags & (VEXPORT | VREADONLY | VSTRFIXED | VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) { *vpp = vp->next; ckfree(vp); out_free: if ((flags & (VTEXTFIXED | VSTACK | VNOSAVE)) == VNOSAVE) ckfree(s); goto out; } flags |= vp->flags & ~(VTEXTFIXED | VSTACK | VNOSAVE | VUNSET); } else { if (flags & VNOSET) goto out; if ((flags & (VEXPORT | VREADONLY | VSTRFIXED | VUNSET)) == VUNSET) goto out_free; /* not found */ vp = ckmalloc(sizeof(*vp)); vp->next = *vpp; vp->func = NULL; *vpp = vp; } if (!(flags & (VTEXTFIXED | VSTACK | VNOSAVE))) s = savestr(s); vp->text = s; vp->flags = flags; out: return vp; } /* * Find the value of a variable. Returns NULL if not set. */ static char *lookupvar(const char *name) { struct Var *v; if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) { if (v == &vlineno && v->text == linenovar) { fmtstr(linenovar + 7, sizeof(linenovar) - 7, "%d", lineno); } return strchrnul(v->text, '=') + 1; } return NULL; } static int64_t lookupvarint(const char *name) { return atomax(lookupvar(name) ?: nullstr, 0); } /* * Generate a list of variables satisfying the given conditions. */ static char **listvars(int on, int off, char ***end) { struct Var **vpp; struct Var *vp; char **ep; int mask; STARTSTACKSTR(ep); vpp = vartab; mask = on | off; do { for (vp = *vpp; vp; vp = vp->next) if ((vp->flags & mask) == on) { if (ep == stackstrend()) ep = growstackstr(); *ep++ = (char *)vp->text; } } while (++vpp < vartab + VTABSIZE); if (ep == stackstrend()) ep = growstackstr(); if (end) *end = ep; *ep++ = NULL; return grabstackstr(ep); } static int vpcmp(const void *a, const void *b) { return varcmp(*(const char **)a, *(const char **)b); } /* * POSIX requires that 'set' (but not export or readonly) output the * variables in lexicographic order - by the locale's collating order (sigh). * Maybe we could keep them in an ordered balanced binary tree * instead of hashed lists. * For now just roll 'em through qsort for printing... */ static int showvars(const char *prefix, int on, int off) { const char *sep; char **ep, **epend; ep = listvars(on, off, &epend); qsort(ep, epend - ep, sizeof(char *), vpcmp); sep = *prefix ? spcstr : prefix; for (; ep < epend; ep++) { const char *p; const char *q; p = strchrnul(*ep, '='); q = nullstr; if (*p) q = single_quote(++p); out1fmt("%s%s%.*s%s\n", prefix, sep, (int)(p - *ep), *ep, q); } return 0; } /* * The export and readonly commands. */ static int exportcmd(int argc, char **argv) { struct Var *vp; char *name; const char *p; char **aptr; int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT; int notp; notp = nextopt("p") - 'p'; if (notp && ((name = *(aptr = argptr)))) { do { if ((p = strchr(name, '=')) != NULL) { p++; } else { if ((vp = *findvar(hashvar(name), name))) { vp->flags |= flag; continue; } } setvar(name, p, flag); } while ((name = *++aptr) != NULL); } else { showvars(argv[0], flag, 0); } return 0; } /* * The "local" command. */ static int localcmd(int argc, char **argv) { char *name; if (!localvar_stack) sh_error("not in a function"); argv = argptr; while ((name = *argv++) != NULL) { mklocal(name, 0); } return 0; } /* * Make a variable a local variable. When a variable is made local, it's * value and flags are saved in a localvar structure. The saved values * will be restored when the shell function returns. We handle the name * "-" as a special case. */ static void mklocal(char *name, int flags) { struct localvar *lvp; struct Var **vpp; struct Var *vp; INTOFF; lvp = ckmalloc(sizeof(struct localvar)); if (name[0] == '-' && name[1] == '\0') { char *p; p = ckmalloc(sizeof(optlist)); lvp->text = memcpy(p, optlist, sizeof(optlist)); vp = NULL; } else { char *eq; vpp = hashvar(name); vp = *findvar(vpp, name); eq = strchr(name, '='); if (vp == NULL) { if (eq) vp = setvareq(name, VSTRFIXED | flags); else vp = setvar(name, NULL, VSTRFIXED | flags); lvp->flags = VUNSET; } else { lvp->text = vp->text; lvp->flags = vp->flags; vp->flags |= VSTRFIXED | VTEXTFIXED; if (eq) setvareq(name, flags); } } lvp->vp = vp; lvp->next = localvar_stack->lv; localvar_stack->lv = lvp; INTON; } /* * Called after a function returns. * Interrupts must be off. */ static void poplocalvars(void) { struct localvar_list *ll; struct localvar *lvp, *next; struct Var *vp; INTOFF; ll = localvar_stack; localvar_stack = ll->next; next = ll->lv; ckfree(ll); while ((lvp = next) != NULL) { next = lvp->next; vp = lvp->vp; TRACE(("poplocalvar %s\n", vp ? vp->text : "-")); if (vp == NULL) { /* $- saved */ memcpy(optlist, lvp->text, sizeof(optlist)); ckfree(lvp->text); optschanged(); } else if (lvp->flags == VUNSET) { vp->flags &= ~(VSTRFIXED | VREADONLY); unsetvar(vp->text); } else { if (vp->func) (*vp->func)(strchrnul(lvp->text, '=') + 1); if ((vp->flags & (VTEXTFIXED | VSTACK)) == 0) ckfree(vp->text); vp->flags = lvp->flags; vp->text = lvp->text; } ckfree(lvp); } INTON; } /* * Create a new localvar environment. */ static struct localvar_list *pushlocalvars(int push) { struct localvar_list *ll; struct localvar_list *top; top = localvar_stack; if (!push) goto out; INTOFF; ll = ckmalloc(sizeof(*ll)); ll->lv = NULL; ll->next = top; localvar_stack = ll; INTON; out: return top; } static void unwindlocalvars(struct localvar_list *stop) { while (localvar_stack != stop) poplocalvars(); } /* * The unset builtin command. We unset the function before we unset the * variable to allow a function to be unset when there is a readonly variable * with the same name. */ static int unsetcmd(int argc, char **argv) { char **ap; int i; int flag = 0; while ((i = nextopt("vf")) != '\0') { flag = i; } for (ap = argptr; *ap; ap++) { if (flag != 'f') { unsetvar(*ap); continue; } if (flag != 'v') unsetfunc(*ap); } return 0; } static void unsetvar(const char *s) { setvar(s, 0, 0); } /* * Initialization code. */ static void init() { /* from input.c: */ { basepf.nextc = basepf.buf = basebuf; basepf.linno = 1; } /* from trap.c: */ { sigmode[SIGCHLD - 1] = S_DFL; setsignal(SIGCHLD); } /* from var.c: */ { char **envp; static char ppid[32] = "PPID="; const char *p; struct stat st1, st2; initvar(); for (envp = environ; *envp; envp++) { p = endofname(*envp); if (p != *envp && *p == '=') { setvareq(*envp, VEXPORT | VTEXTFIXED); } } setvareq(defifsvar, VTEXTFIXED); setvareq(defoptindvar, VTEXTFIXED); fmtstr(ppid + 5, sizeof(ppid) - 5, "%ld", (long)getppid()); setvareq(ppid, VTEXTFIXED); p = lookupvar("PWD"); if (p) { if (*p != '/' || stat(p, &st1) || stat(".", &st2) || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { p = 0; } } setpwd(p, 0); } } /* * This routine is called when an error or an interrupt occurs in an * interactive shell and control is returned to the main command loop * but prior to exitshell. */ static void exitreset() { /* from eval.c: */ { if (savestatus >= 0) { if (exception == EXEXIT || evalskip == SKIPFUNCDEF) exitstatus = savestatus; savestatus = -1; } evalskip = 0; loopnest = 0; inps4 = 0; } /* from expand.c: */ { ifsfree(); } /* from redir.c: */ { /* * Discard all saved file descriptors. */ unwindredir(0); } } /* * This routine is called when we enter a subshell. */ static void forkreset() { /* from input.c: */ { popallfiles(); if (parsefile->fd > 0) { close(parsefile->fd); parsefile->fd = 0; } } /* from main.c: */ { handler = &main_handler; } /* from redir.c: */ { redirlist = NULL; } /* from trap.c: */ { char **tp; INTOFF; for (tp = trap ; tp < &trap[NSIG] ; tp++) { if (*tp && **tp) { /* trap not NULL or SIG_IGN */ ckfree(*tp); *tp = NULL; if (tp != &trap[0]) setsignal(tp - trap); } } trapcnt = 0; INTON; } } /* * This routine is called when an error or an interrupt occurs in an * interactive shell and control is returned to the main command loop. */ static void reset() { /* from input.c: */ { /* clear input buffer */ basepf.lleft = basepf.nleft = 0; basepf.unget = 0; popallfiles(); } /* from var.c: */ { unwindlocalvars(0); } } static void calcsize(union node *n) { if (n == NULL) return; funcblocksize += nodesize[n->type]; switch (n->type) { case NCMD: calcsize(n->ncmd.redirect); calcsize(n->ncmd.args); calcsize(n->ncmd.assign); break; case NPIPE: sizenodelist(n->npipe.cmdlist); break; case NREDIR: case NBACKGND: case NSUBSHELL: calcsize(n->nredir.redirect); calcsize(n->nredir.n); break; case NAND: case NOR: case NSEMI: case NWHILE: case NUNTIL: calcsize(n->nbinary.ch2); calcsize(n->nbinary.ch1); break; case NIF: calcsize(n->nif.elsepart); calcsize(n->nif.ifpart); calcsize(n->nif.test); break; case NFOR: funcstringsize += strlen(n->nfor.var_) + 1; calcsize(n->nfor.body); calcsize(n->nfor.args); break; case NCASE: calcsize(n->ncase.cases); calcsize(n->ncase.expr); break; case NCLIST: calcsize(n->nclist.body); calcsize(n->nclist.pattern); calcsize(n->nclist.next); break; case NDEFUN: calcsize(n->ndefun.body); funcstringsize += strlen(n->ndefun.text) + 1; break; case NARG: sizenodelist(n->narg.backquote); funcstringsize += strlen(n->narg.text) + 1; calcsize(n->narg.next); break; case NTO: case NCLOBBER: case NFROM: case NFROMTO: case NAPPEND: calcsize(n->nfile.fname); calcsize(n->nfile.next); break; case NTOFD: case NFROMFD: calcsize(n->ndup.vname); calcsize(n->ndup.next); break; case NHERE: case NXHERE: calcsize(n->nhere.doc); calcsize(n->nhere.next); break; case NNOT: calcsize(n->nnot.com); break; }; } /* * Make a copy of a parse tree. */ static struct funcnode *copyfunc(union node *n) { struct funcnode *f; unsigned blocksize; funcblocksize = offsetof(struct funcnode, n); funcstringsize = 0; calcsize(n); blocksize = funcblocksize; f = ckmalloc(blocksize + funcstringsize); funcblock = (char *)f + offsetof(struct funcnode, n); funcstring = (char *)f + blocksize; copynode(n); f->count = 0; return f; } static void sizenodelist(struct nodelist *lp) { while (lp) { funcblocksize += SHELL_ALIGN(sizeof(struct nodelist)); calcsize(lp->n); lp = lp->next; } } static union node *copynode(union node *n) { union node *new; if (n == NULL) return NULL; new = funcblock; funcblock = (char *)funcblock + nodesize[n->type]; switch (n->type) { case NCMD: new->ncmd.redirect = copynode(n->ncmd.redirect); new->ncmd.args = copynode(n->ncmd.args); new->ncmd.assign = copynode(n->ncmd.assign); new->ncmd.linno = n->ncmd.linno; break; case NPIPE: new->npipe.cmdlist = copynodelist(n->npipe.cmdlist); new->npipe.backgnd = n->npipe.backgnd; break; case NREDIR: case NBACKGND: case NSUBSHELL: new->nredir.redirect = copynode(n->nredir.redirect); new->nredir.n = copynode(n->nredir.n); new->nredir.linno = n->nredir.linno; break; case NAND: case NOR: case NSEMI: case NWHILE: case NUNTIL: new->nbinary.ch2 = copynode(n->nbinary.ch2); new->nbinary.ch1 = copynode(n->nbinary.ch1); break; case NIF: new->nif.elsepart = copynode(n->nif.elsepart); new->nif.ifpart = copynode(n->nif.ifpart); new->nif.test = copynode(n->nif.test); break; case NFOR: new->nfor.var_ = nodesavestr(n->nfor.var_); new->nfor.body = copynode(n->nfor.body); new->nfor.args = copynode(n->nfor.args); new->nfor.linno = n->nfor.linno; break; case NCASE: new->ncase.cases = copynode(n->ncase.cases); new->ncase.expr = copynode(n->ncase.expr); new->ncase.linno = n->ncase.linno; break; case NCLIST: new->nclist.body = copynode(n->nclist.body); new->nclist.pattern = copynode(n->nclist.pattern); new->nclist.next = copynode(n->nclist.next); break; case NDEFUN: new->ndefun.body = copynode(n->ndefun.body); new->ndefun.text = nodesavestr(n->ndefun.text); new->ndefun.linno = n->ndefun.linno; break; case NARG: new->narg.backquote = copynodelist(n->narg.backquote); new->narg.text = nodesavestr(n->narg.text); new->narg.next = copynode(n->narg.next); break; case NTO: case NCLOBBER: case NFROM: case NFROMTO: case NAPPEND: new->nfile.fname = copynode(n->nfile.fname); new->nfile.fd = n->nfile.fd; new->nfile.next = copynode(n->nfile.next); break; case NTOFD: case NFROMFD: new->ndup.vname = copynode(n->ndup.vname); new->ndup.dupfd = n->ndup.dupfd; new->ndup.fd = n->ndup.fd; new->ndup.next = copynode(n->ndup.next); break; case NHERE: case NXHERE: new->nhere.doc = copynode(n->nhere.doc); new->nhere.fd = n->nhere.fd; new->nhere.next = copynode(n->nhere.next); break; case NNOT: new->nnot.com = copynode(n->nnot.com); break; }; new->type = n->type; return new; } static struct nodelist *copynodelist(struct nodelist *lp) { struct nodelist *start; struct nodelist **lpp; lpp = &start; while (lp) { *lpp = funcblock; funcblock = (char *)funcblock + SHELL_ALIGN(sizeof(struct nodelist)); (*lpp)->n = copynode(lp->n); lp = lp->next; lpp = &(*lpp)->next; } *lpp = NULL; return start; } /* * Read and execute commands. "Top" is nonzero for the top level command * loop; it turns on prompting if the shell is interactive. */ static int cmdloop(int top) { union node *n; struct stackmark smark; int inter; int status = 0; int numeof = 0; TRACE(("cmdloop(%d) called\n", top)); for (;;) { int skip; setstackmark(&smark); if (jobctl) showjobs(out2, SHOW_CHANGED); inter = 0; if (iflag && top) { inter++; /* chkmail(); */ } n = parsecmd(inter); /* showtree(n); DEBUG */ if (n == NEOF) { if (!top || numeof >= 50) break; if (!stoppedjobs()) { if (!Iflag) { if (iflag) outcslow('\n', out2); break; } outstr("\nUse \"exit\" to leave shell.\n", out2); } numeof++; } else { int i; job_warning = (job_warning == 2) ? 1 : 0; numeof = 0; i = evaltree(n, 0); if (n) status = i; } popstackmark(&smark); skip = evalskip; if (skip) { evalskip &= ~(SKIPFUNC | SKIPFUNCDEF); break; } } return status; } /* * Read /etc/profile or .profile. Return on error. */ static void read_profile(const char *name) { name = expandstr(name); if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0) return; cmdloop(0); popfile(); } /* * Take commands from a file. To be compatible we should do a path * search for the file, which is necessary to find sub-commands. */ static char *find_dot_file(char *basename) { char *fullname; const char *path = pathval(); struct stat statb; int len; /* don't try this for absolute or relative paths */ if (strchr(basename, '/')) return basename; while ((len = padvance(&path, basename)) >= 0) { fullname = stackblock(); if ((!pathopt || *pathopt == 'f') && !stat(fullname, &statb) && S_ISREG(statb.st_mode)) { /* This will be freed by the caller. */ return stalloc(len); } } /* not found in the PATH */ sh_error("%s: not found", basename); } static int dotcmd(int argc, char **argv) { int status = 0; nextopt(nullstr); argv = argptr; if (*argv) { char *fullname; fullname = find_dot_file(*argv); setinputfile(fullname, INPUT_PUSH_FILE); commandname = fullname; status = cmdloop(0); popfile(); } return status; } static int exitcmd(int argc, char **argv) { if (stoppedjobs()) return 0; if (argc > 1) savestatus = number(argv[1]); exraise(EXEXIT); } /** * Main routine. We initialize things, parse the arguments, execute * profiles if we're a login shell, and then call cmdloop to execute * commands. The setjmp call sets up the location to jump to when an * exception occurs. When an exception occurs the variable "state" * is used to figure out how far we had gotten. */ int main(int argc, char **argv) { char *shinit; volatile int state; struct stackmark smark; int login; state = 0; if (unlikely(setjmp(main_handler.loc))) { int e; int s; exitreset(); e = exception; s = state; if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) exitshell(); reset(); if (e == EXINT) { outcslow('\n', out2); } popstackmark(&smark); FORCEINTON; /* enable interrupts */ if (s == 1) { goto state1; } else if (s == 2) { goto state2; } else if (s == 3) { goto state3; } else { goto state4; } } handler = &main_handler; rootpid = getpid(); init(); setstackmark(&smark); login = procargs(argc, argv); if (login) { state = 1; read_profile("/etc/profile"); state1: state = 2; read_profile("$HOME/.profile"); } state2: state = 3; if (iflag) { if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') { read_profile(shinit); } } popstackmark(&smark); state3: state = 4; if (minusc) evalstring(minusc, sflag ? 0 : EV_EXIT); if (sflag || minusc == NULL) { state4: /* XXX ??? - why isn't this before the "if" statement */ cmdloop(1); } exitshell(); }
301,774
11,037
jart/cosmopolitan
false
cosmopolitan/examples/tls.c
#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 /** * @fileoverview thread local storage * * Cosmopolitan guarantees `_Thread_local` variables are always * accessible, even if you're not using threads. */ _Thread_local int x; _Thread_local int y = 42; int main(int argc, char *argv[]) { return x + y; }
1,049
24
jart/cosmopolitan
false
cosmopolitan/examples/datauri.c
#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/log/log.h" #include "libc/mem/gc.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/x/x.h" #include "net/http/escape.h" #include "net/http/http.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image.h" #define USAGE \ " [FLAGS] FILE...\n\ Utility for printing data:base64 URIs.\n\ \n\ FLAGS\n\ \n\ -h Help\n" void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void PrintUri(const char *path) { size_t n; void *img, *src, *mime; int opt, i; if (!(img = gc(xslurp(path, &n)))) exit(2); fputs("data:", stdout); fputs(FindContentType(path, -1), stdout); fputs(";base64,", stdout); fputs(gc(EncodeBase64(img, n, 0)), stdout); } int main(int argc, char *argv[]) { int i; while ((i = getopt(argc, argv, "?h")) != -1) { switch (i) { case '?': case 'h': PrintUsage(0, stdout); default: PrintUsage(1, stderr); } } if (optind == argc) { PrintUsage(1, stderr); } for (i = optind; i < argc; ++i) { PrintUri(argv[i]); } }
1,940
64
jart/cosmopolitan
false
cosmopolitan/examples/crashreport.c
#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/intrin/kprintf.h" #include "libc/log/log.h" #include "libc/math.h" #include "libc/runtime/symbols.internal.h" /** * @fileoverview How to print backtraces and cpu state on crash. * * make -j8 -O o//examples/crashreport.com * o//examples/crashreport.com * * To prevent the GDB GUI from popping up: * * export GDB= * make -j8 -O o//examples/crashreport.com * o//examples/crashreport.com */ noubsan int main(int argc, char *argv[]) { kprintf("----------------\n"); kprintf(" THIS IS A TEST \n"); kprintf("SIMULATING CRASH\n"); kprintf("----------------\n"); ShowCrashReports(); volatile double a = 0; volatile double b = 23; volatile double c = exp(b) / a; volatile int64_t x; return 1 / (x = 0); }
1,550
43
jart/cosmopolitan
false
cosmopolitan/examples/forkexec.c
#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/stdio/stdio.h" int main(int argc, char *argv[]) { int pid; if (argc < 3) { fputs("USAGE: FORKEXEC.COM PROG ARGV₀ [ARGV₁...]\n", stderr); return 1; } if (!fork()) { execv(argv[1], argv + 2); return 127; } }
1,066
24
jart/cosmopolitan
false
cosmopolitan/examples/hello3.c
#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/errno.h" #include "libc/fmt/fmt.h" #include "libc/stdio/stdio.h" int main() { printf("%`'s\n", "hello\1\2world→→"); return errno; }
940
18
jart/cosmopolitan
false
cosmopolitan/examples/sysinfo.c
#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/struct/sysinfo.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/log/check.h" #include "libc/stdio/stdio.h" int main(int argc, char *argv[]) { int64_t x; char ibuf[21]; struct sysinfo si; CHECK_NE(-1, sysinfo(&si)); printf("%-16s", "uptime"); x = si.uptime / (24 * 60 * 60); si.uptime %= 24 * 60 * 60; if (x) { printf(" %ld day%s", x, x == 1 ? "" : "s"); } x = si.uptime / (60 * 60); si.uptime %= 60 * 60; if (x) { printf(" %ld hour%s", x, x == 1 ? "" : "s"); } x = si.uptime / (60); si.uptime %= 60; if (x) { printf(" %ld minute%s", x, x == 1 ? "" : "s"); } x = si.uptime; if (x) { printf(" %ld second%s", x, x == 1 ? "" : "s"); } printf("\n"); printf("%-16s %g %g %g\n", "load", // 1. / 65536 * si.loads[0], // 1. / 65536 * si.loads[1], // 1. / 65536 * si.loads[2]); // sizefmt(ibuf, si.totalram * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "totalram", si.totalram, ibuf); sizefmt(ibuf, si.freeram * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "freeram", si.freeram, ibuf); sizefmt(ibuf, si.sharedram * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "sharedram", si.sharedram, ibuf); sizefmt(ibuf, si.bufferram * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "bufferram", si.bufferram, ibuf); sizefmt(ibuf, si.totalswap * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "totalswap", si.totalswap, ibuf); sizefmt(ibuf, si.freeswap * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "freeswap", si.freeswap, ibuf); printf("%-16s %lu\n", "processes", si.procs); sizefmt(ibuf, si.totalhigh * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "totalhigh", si.totalhigh, ibuf); sizefmt(ibuf, si.freehigh * si.mem_unit, 1024); printf("%-16s %ld (%s)\n", "freehigh", si.freehigh, ibuf); sizefmt(ibuf, si.mem_unit, 1024); printf("%-16s %s\n", "mem_unit", ibuf); // }
2,739
80
jart/cosmopolitan
false
cosmopolitan/examples/stackoverflow.c
#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/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/stack.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/prot.h" /** * @fileoverview Stack Overflow Demo */ #define N INT_MAX STATIC_STACK_SIZE(FRAMESIZE); int A(int f(), int n) { if (n < N) { return f(f, n + 1) - 1; } else { return N; } } int (*Ap)(int (*)(), int) = A; int main(int argc, char *argv[]) { ShowCrashReports(); return !!Ap(Ap, 0); } /* error: Uncaught SIGSEGV (Stack Overflow) on rhel5 pid 368 ./o//examples/stackoverflow.com EUNKNOWN[No error information][0] Linux rhel5 2.6.18-8.el5 #1 SMP Thu Mar 15 19:46:53 EDT 2007 0x0000000000406896: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 0x0000000000406898: A at examples/stackoverflow.c:24 etc. etc. RAX 0000000000000000 RBX 0000000000000001 RDI 000000000040687e ST(0) 0.0 RCX 0000000000417125 RDX 000000000041cd70 RSI 0000000000000efe ST(1) 0.0 RBP 00006ffffffe1000 RSP 00006ffffffe1000 RIP 0000000000406897 ST(2) 0.0 R8 0000000000000000 R9 0000000000000022 R10 0000000000000008 ST(3) 0.0 R11 0000000000000293 R12 0000000000000001 R13 00007ffc70b4fc48 ST(4) 0.0 R14 00007ffc70b4fc58 R15 00007ffc70b4fd18 VF IF XMM0 00000000000000000000000000000000 XMM8 00000000000000000000000000000000 XMM1 ffffffffffffeb030000000000000000 XMM9 00000000000000000000000000000000 XMM2 0000000000000000ffffffffffffffff XMM10 00000000000000000000000000000000 XMM3 00000000000000000000000000000000 XMM11 00000000000000000000000000000000 XMM4 00000000000000000000000000000000 XMM12 00000000000000000000000000000000 XMM5 00000000000000000000000000000000 XMM13 00000000000000000000000000000000 XMM6 00000000000000000000000000000000 XMM14 00000000000000000000000000000000 XMM7 00000000000000000000000000000000 XMM15 00000000000000000000000000000000 100080000000-100080030000 rw-pa-- 3x automap 6ffffffe0000-6fffffff0000 rw-paSF 1x stack # 4 frames mapped w/ 0 frames gapped */
3,158
78
jart/cosmopolitan
false
cosmopolitan/examples/hangman.c
/* UNIX v7 usr/src/games/hangman.c * * Copyright 2002 Caldera International Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code and documentation must retain the * above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with * the distribution. * * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * * This product includes software developed or owned by Caldera * International, Inc. * * Neither the name of Caldera International, Inc. nor the names of * other contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENCE BY CALDERA * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/stdio/rand.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/time/time.h" #include "third_party/zlib/zlib.h" // clang-format off #define DICT "usr/share/dict/hangman" #define MAXERR 7 #define MINSCORE 0 #define MINLEN 7 char *dictfile; int alive,lost; FILE *dict; long int dictlen; float errors=0, words=0; char word[26],alph[26],realword[26]; void fatal(s) char *s; { fprintf(stderr,"%s\n",s); exit(1); } void setup() { long tvec; struct stat statb; time(&tvec); srand(tvec); if((dict=fopen(dictfile,"r"))==NULL) fatal("no dictionary"); if(stat(dictfile,&statb)<0) fatal("can't stat"); dictlen=statb.st_size; } double frand() { return(rand()/32768.); } void pscore() { if(words!=0) printf("(%4.2f/%.0f) ",errors/words,words); } void getword() { char wbuf[128],c; int i,j; loop: if(fscanf(dict,"%s\n",wbuf)==EOF) { fseek(dict,0L,0); goto loop; } if((c=wbuf[0])>'z' || c<'a') goto loop; for(i=j=0;wbuf[j]!=0;i++,j++) { if(wbuf[j]=='-') j++; wbuf[i]=wbuf[j]; } wbuf[i]=0; if(i<MINLEN) goto loop; for(j=0;j<i;j++) if((c=wbuf[j])<'a' || c>'z') goto loop; pscore(); strcpy(realword,wbuf); for(j=0;j<i;word[j++]='.'); } void startnew() { int i; long int pos; char buf[128]; for(i=0;i<26;i++) word[i]=alph[i]=realword[i]=0; pos=frand()*dictlen; pos%=dictlen; fseek(dict,pos,0); fscanf(dict,"%s\n",buf); getword(); alive=MAXERR; lost=0; } void stateout() { int i; printf("guesses: "); for(i=0;i<26;i++) if(alph[i]!=0) putchar(alph[i]); printf(" word: %s ",word); printf("errors: %d/%d\n",MAXERR-alive,MAXERR); } void getguess() { char gbuf[128],c; int ok=0,i; loop: printf("guess: "); if(gets(gbuf)==NULL) { putchar('\n'); exit(0); } if((c=gbuf[0])<'a' || c>'z') { printf("lower case\n"); goto loop; } if(alph[c-'a']!=0) { printf("you guessed that\n"); goto loop; } else alph[c-'a']=c; for(i=0;realword[i]!=0;i++) if(realword[i]==c) { word[i]=c; ok=1; } if(ok==0) { alive--; errors=errors+1; if(alive<=0) lost=1; return; } for(i=0;word[i]!=0;i++) if(word[i]=='.') return; alive=0; lost=0; return; } void wordout() { errors=errors+2; printf("the answer was %s, you blew it\n",realword); } void youwon() { printf("you win, the word is %s\n",realword); } main(argc,argv) char **argv; { if(argc==1) dictfile=DICT; else dictfile=argv[1]; setup(); for(;;) { startnew(); while(alive>0) { stateout(); getguess(); } words=words+1; if(lost) wordout(); else youwon(); } }
4,474
198
jart/cosmopolitan
false
cosmopolitan/examples/hostname.c
#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/intrin/kprintf.h" #include "libc/log/check.h" int main(int argc, char *argv[]) { char name[254]; gethostname(name, sizeof(name)); kprintf("gethostname() → %#s\n", name); getdomainname(name, sizeof(name)); kprintf("getdomainname() → %#s\n", name); return 0; }
1,105
22
jart/cosmopolitan
false
cosmopolitan/examples/script.txt
SCRIPT(1) Cosmopolitan General Commands Manual SCRIPT(1) 𝐍𝐀𝐌𝐄 𝘀𝗰𝗿𝗶𝗽𝘁 — make typescript of terminal session 𝐒𝐘𝐍𝐎𝐏𝐒𝐈𝐒 𝘀𝗰𝗿𝗶𝗽𝘁 [-𝗮𝗱𝗲𝗳𝗸𝗽𝗾𝗿] [-𝐅 p̲i̲p̲e̲] [-𝘁 t̲i̲m̲e̲] [f̲i̲l̲e̲ [c̲o̲m̲m̲a̲n̲d̲ .̲.̲.̲]] 𝐃𝐄𝐒𝐂𝐑𝐈𝐏𝐓𝐈𝐎𝐍 The 𝘀𝗰𝗿𝗶𝗽𝘁 utility makes a typescript of everything printed on your termi‐ nal. It is useful for students who need a hardcopy record of an interac‐ tive session as proof of an assignment, as the typescript file can be printed out later with lpr(1). If the argument f̲i̲l̲e̲ is given, 𝘀𝗰𝗿𝗶𝗽𝘁 saves all dialogue in f̲i̲l̲e̲. If no file name is given, the typescript is saved in the file t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲. If the argument c̲o̲m̲m̲a̲n̲d̲ is given, 𝘀𝗰𝗿𝗶𝗽𝘁 will run the specified command with an optional argument vector instead of an interactive shell. The following options are available: -𝗮 Append the output to f̲i̲l̲e̲ or t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲, retaining the prior con‐ tents. -𝗱 When playing back a session with the -𝗽 flag, do not sleep between records when playing back a timestamped session. -𝗲 Accepted for compatibility with u̲t̲i̲l̲-̲l̲i̲n̲u̲x̲ 𝘀𝗰𝗿𝗶𝗽𝘁. The child com‐ mand exit status is always the exit status of 𝘀𝗰𝗿𝗶𝗽𝘁. -𝐅 p̲i̲p̲e̲ Immediately flush output after each write. This will allow a user to create a named pipe using mkfifo(1) and another user may watch the live session using a utility like cat(1). -𝗸 Log keys sent to the program as well as output. -𝗽 Play back a session recorded with the -𝗿 flag in real time. -𝗾 Run in quiet mode, omit the start, stop and command status mes‐ sages. -𝗿 Record a session with input, output, and timestamping. -𝘁 t̲i̲m̲e̲ Specify the interval at which the script output file will be flushed to disk, in seconds. A value of 0 causes 𝘀𝗰𝗿𝗶𝗽𝘁 to flush after every character I/O event. The default interval is 30 sec‐ onds. The script ends when the forked shell (or command) exits (a c̲o̲n̲t̲r̲o̲l̲-̲D̲ to exit the Bourne shell (sh(1)), and e̲x̲i̲t̲, l̲o̲g̲o̲u̲t̲ or c̲o̲n̲t̲r̲o̲l̲-̲D̲ (if i̲g̲n̲o̲r̲e̲e̲o̲f̲ is not set) for the C-shell, csh(1)). Certain interactive commands, such as vi(1), create garbage in the type‐ script file. The 𝘀𝗰𝗿𝗶𝗽𝘁 utility works best with commands that do not ma‐ nipulate the screen. The results are meant to emulate a hardcopy terminal, not an addressable one. 𝐄𝐍𝐕𝐈𝐑𝐎𝐍𝐌𝐄𝐍𝐓 The following environment variables are utilized by 𝘀𝗰𝗿𝗶𝗽𝘁: SCRIPT The SCRIPT environment variable is added to the sub-shell. If SCRIPT already existed in the users environment, its value is over‐ written within the sub-shell. The value of SCRIPT is the name of the t̲y̲p̲e̲s̲c̲r̲i̲p̲t̲ file. SHELL If the variable SHELL exists, the shell forked by 𝘀𝗰𝗿𝗶𝗽𝘁 will be that shell. If SHELL is not set, the Bourne shell is assumed. (Most shells set this variable automatically). 𝐒𝐄𝐄 𝐀𝐋𝐒𝐎 csh(1) (for the h̲i̲s̲t̲o̲r̲y̲ mechanism) 𝐇𝐈𝐒𝐓𝐎𝐑𝐘 The 𝘀𝗰𝗿𝗶𝗽𝘁 command appeared in 3.0BSD. The -𝗱, -𝗽 and -𝗿 options first appeared in NetBSD 2.0 and were ported to FreeBSD 9.2. 𝐁𝐔𝐆𝐒 The 𝘀𝗰𝗿𝗶𝗽𝘁 utility places 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 in the log file, including linefeeds and backspaces. This is not what the naive user expects. It is not possible to specify a command without also naming the script file because of argument parsing compatibility issues. When running in -𝗸 mode, echo cancelling is far from ideal. The slave ter‐ minal mode is checked for ECHO mode to check when to avoid manual echo log‐ ging. This does not work when the terminal is in a raw mode where the pro‐ gram being run is doing manual echo. If 𝘀𝗰𝗿𝗶𝗽𝘁 reads zero bytes from the terminal, it switches to a mode when it only attempts to read once a second until there is data to read. This pre‐ vents 𝘀𝗰𝗿𝗶𝗽𝘁 from spinning on zero-byte reads, but might cause a 1-second delay in processing of user input. BSD September 1, 2020 BSD
5,030
101
jart/cosmopolitan
false
cosmopolitan/examples/stat.c
#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/stat.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "libc/x/xiso8601.h" /** * @fileoverview File metadata viewer. * * This demonstrates the more powerful aspects of the printf() DSL. */ bool numeric; const char *DescribeFileType(unsigned mode) { switch (mode & S_IFMT) { case S_IFIFO: return "S_IFIFO"; /* pipe */ case S_IFCHR: return "S_IFCHR"; /* character device */ case S_IFDIR: return "S_IFDIR"; /* directory */ case S_IFBLK: return "S_IFBLK"; /* block device */ case S_IFREG: return "S_IFREG"; /* regular file */ case S_IFLNK: return "S_IFLNK"; /* symbolic link */ case S_IFSOCK: return "S_IFSOCK"; /* socket */ default: return "wut"; } } void PrintFileMetadata(const char *pathname, struct stat *st) { int fd; printf("\n%s:", pathname); if (numeric) { fd = atoi(pathname); CHECK_NE(-1, fstat(fd, st), "fd=%d", fd); } else { CHECK_NE(-1, stat(pathname, st), "pathname=%s", pathname); } printf("\n" "%-32s%,ld\n" "%-32s%,ld\n" "%-32s%#lx\n" "%-32s%#lx\n" "%-32s%ld\n" "%-32s%#o (%s)\n" "%-32s%d\n" "%-32s%d\n" "%-32s%d\n" "%-32s%d\n" "%-32s%ld\n" "%-32s%ld\n" "%-32s%s\n" "%-32s%s\n" "%-32s%s\n" "%-32s%s\n", "bytes in file", st->st_size, "physical bytes", st->st_blocks * 512, "device id w/ file", st->st_dev, "inode", st->st_ino, "hard link count", st->st_nlink, "mode / permissions", st->st_mode, DescribeFileType(st->st_mode), "owner id", st->st_uid, "group id", st->st_gid, "flags", st->st_flags, "gen", st->st_gen, "device id (if special)", st->st_rdev, "block size", st->st_blksize, "access time", _gc(xiso8601(&st->st_atim)), "modified time", _gc(xiso8601(&st->st_mtim)), "c[omplicated]time", _gc(xiso8601(&st->st_ctim)), "birthtime", _gc(xiso8601(&st->st_birthtim))); } int main(int argc, char *argv[]) { size_t i; struct stat st; for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-n")) { numeric = true; } else { PrintFileMetadata(argv[i], &st); } } return 0; }
3,314
102
jart/cosmopolitan
false
cosmopolitan/examples/mkhello.c
#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" int main(int argc, char *argv[]) { creat("hello.txt", 0644); write(3, "hello\n", 6); close(3); return 0; }
930
18
jart/cosmopolitan
false
cosmopolitan/examples/ucontext-sigfpe-recovery.c
#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/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/ucontext.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "third_party/xed/x86.h" #ifdef __x86_64__ /** * @fileoverview How to change CPU state on signal delivery * * This program redefines division by zero so that it has a definition. * The definition is the meaning of life, the universe, and everything. * Normally crash signals like `SIGSEGV`, `SIGILL`, and `SIGFPE` aren't * recoverable. This example shows how it actually can be done with Xed * and this example should work on all supported platforms even Windows */ void handler(int sig, siginfo_t *si, void *vctx) { struct XedDecodedInst xedd; struct ucontext *ctx = vctx; xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15); ctx->uc_mcontext.rip += xedd.length; ctx->uc_mcontext.rax = 42; // set the DIV result registers rdx:rax ctx->uc_mcontext.rdx = 0; } int main(int argc, char *argv[]) { struct sigaction saint = {.sa_sigaction = handler, .sa_flags = SA_SIGINFO}; sigaction(SIGFPE, &saint, NULL); volatile long x = 0; printf("123/0 = %ld\n", 123 / x); return 0; } #endif /* __x86_64__ */
2,148
50
jart/cosmopolitan
false
cosmopolitan/examples/getdomainname.c
#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/stdio/stdio.h" int main(int argc, char *argv[]) { char buf[256]; if (!getdomainname(buf, sizeof(buf))) { printf("%s\n", buf); return 0; } else { return 1; } }
1,009
22
jart/cosmopolitan
false
cosmopolitan/examples/loadavg.c
#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/log/check.h" #include "libc/stdio/stdio.h" #include "libc/time/time.h" int main(int argc, char *argv[]) { double x[3]; CHECK_NE(-1, getloadavg(x, 3)); printf("%g %g %g\n", x[0], x[1], x[2]); return 0; }
1,041
21
jart/cosmopolitan
false
cosmopolitan/examples/greenbean.c
#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/assert.h" #include "libc/atomic.h" #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timeval.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/intrin/atomic.h" #include "libc/intrin/kprintf.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/sock/struct/sockaddr.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/clone.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "libc/sysv/consts/tcp.h" #include "libc/thread/spawn.h" #include "libc/thread/thread.h" #include "libc/thread/tls.h" #include "libc/thread/wait0.internal.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "net/http/http.h" #include "net/http/url.h" /** * @fileoverview greenbean lightweighht threaded web server * * $ make -j8 o//tool/net/greenbean.com * $ o//tool/net/greenbean.com & * $ printf 'GET /\n\n' | nc 127.0.0.1 8080 * HTTP/1.1 200 OK * Server: greenbean/1.o * Referrer-Policy: origin * Cache-Control: private; max-age=0 * Content-Type: text/html; charset=utf-8 * Date: Sat, 14 May 2022 14:13:07 GMT * Content-Length: 118 * * <!doctype html> * <title>hello world</title> * <h1>hello world</h1> * <p>this is a fun webpage * <p>hosted by greenbean * * Like redbean, greenbean has superior performance too, with an * advantage on benchmarks biased towards high connection counts * * $ wrk -c 300 -t 32 --latency http://127.0.0.1:8080/ * Running 10s test @ http://127.0.0.1:8080/ * 32 threads and 300 connections * Thread Stats Avg Stdev Max +/- Stdev * Latency 661.06us 5.11ms 96.22ms 98.85% * Req/Sec 42.38k 8.90k 90.47k 84.65% * Latency Distribution * 50% 184.00us * 75% 201.00us * 90% 224.00us * 99% 11.99ms * 10221978 requests in 7.60s, 3.02GB read * Requests/sec: 1345015.69 * Transfer/sec: 406.62MB * */ #define PORT 8080 #define HEARTBEAT 100 #define KEEPALIVE 5000 #define LOGGING 0 #define STANDARD_RESPONSE_HEADERS \ "Server: greenbean/1.o\r\n" \ "Referrer-Policy: origin\r\n" \ "Cache-Control: private; max-age=0\r\n" int threads; atomic_int workers; atomic_int messages; atomic_int listening; atomic_int connections; atomic_int closingtime; const char *volatile status; void *Worker(void *id) { int server, yes = 1; // load balance incoming connections for port 8080 across all threads // hangup on any browser clients that lag for more than a few seconds struct timeval timeo = {KEEPALIVE / 1000, KEEPALIVE % 1000}; struct sockaddr_in addr = {.sin_family = AF_INET, .sin_port = htons(PORT)}; server = socket(AF_INET, SOCK_STREAM, 0); if (server == -1) { kprintf("socket() failed %m\n" " try running: sudo prlimit --pid=$$ --nofile=%d\n", threads * 2); goto WorkerFinished; } setsockopt(server, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo)); setsockopt(server, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo)); setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); setsockopt(server, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); setsockopt(server, SOL_TCP, TCP_FASTOPEN, &yes, sizeof(yes)); setsockopt(server, SOL_TCP, TCP_QUICKACK, &yes, sizeof(yes)); errno = 0; if (bind(server, (struct sockaddr *)&addr, sizeof(addr)) == -1) { kprintf("%s() failed %m\n", "socket"); goto CloseWorker; } listen(server, 1); // connection loop ++listening; while (!closingtime) { struct tm tm; int64_t unixts; struct Url url; ssize_t got, sent; struct timespec ts; struct HttpMessage msg; uint32_t clientaddrsize; struct sockaddr_in clientaddr; char inbuf[1500], outbuf[512], *p, *q; int clientip, client, inmsglen, outmsglen; // this slows the server down a lot but is needed on non-Linux to // react to keyboard ctrl-c if (!IsLinux() && poll(&(struct pollfd){server, POLLIN}, 1, HEARTBEAT) < 1) { continue; } // wait for client connection clientaddrsize = sizeof(clientaddr); client = accept(server, (struct sockaddr *)&clientaddr, &clientaddrsize); // accept() can raise a very diverse number of errors but none of // them are really true showstoppers that would necessitate us to // panic and abort the entire server, so we can just ignore these if (client == -1) { // we used SO_RCVTIMEO and SO_SNDTIMEO because those settings are // inherited by the accepted sockets, but using them also has the // side-effect that the listening socket fails with EAGAIN, every // several seconds. we can use that to our advantage to check for // the ctrl-c shutdowne event; otherwise, we retry the accept call continue; } ++connections; // message loop do { // parse the incoming http message InitHttpMessage(&msg, kHttpRequest); // we're not terrible concerned when errors happen here if ((got = read(client, inbuf, sizeof(inbuf))) <= 0) break; // check that client message wasn't fragmented into more reads if (!(inmsglen = ParseHttpMessage(&msg, inbuf, got))) break; ++messages; #if LOGGING // log the incoming http message clientip = ntohl(clientaddr.sin_addr.s_addr); kprintf("%6P get some %d.%d.%d.%d:%d %#.*s\n", (clientip & 0xff000000) >> 030, (clientip & 0x00ff0000) >> 020, (clientip & 0x0000ff00) >> 010, (clientip & 0x000000ff) >> 000, ntohs(clientaddr.sin_port), msg.uri.b - msg.uri.a, inbuf + msg.uri.a); #endif // display hello world html page for http://127.0.0.1:8080/ if (msg.method == kHttpGet && (msg.uri.b - msg.uri.a == 1 && inbuf[msg.uri.a + 0] == '/')) { q = "<!doctype html>\r\n" "<title>hello world</title>\r\n" "<h1>hello world</h1>\r\n" "<p>this is a fun webpage\r\n" "<p>hosted by greenbean\r\n"; p = stpcpy(outbuf, "HTTP/1.1 200 OK\r\n" STANDARD_RESPONSE_HEADERS "Content-Type: text/html; charset=utf-8\r\n" "Date: "); clock_gettime(0, &ts), unixts = ts.tv_sec; p = FormatHttpDateTime(p, gmtime_r(&unixts, &tm)); p = stpcpy(p, "\r\nContent-Length: "); p = FormatInt32(p, strlen(q)); p = stpcpy(p, "\r\n\r\n"); p = stpcpy(p, q); outmsglen = p - outbuf; sent = write(client, outbuf, outmsglen); } else { // display 404 not found error page for every thing else q = "<!doctype html>\r\n" "<title>404 not found</title>\r\n" "<h1>404 not found</h1>\r\n"; p = stpcpy(outbuf, "HTTP/1.1 404 Not Found\r\n" STANDARD_RESPONSE_HEADERS "Content-Type: text/html; charset=utf-8\r\n" "Date: "); clock_gettime(0, &ts), unixts = ts.tv_sec; p = FormatHttpDateTime(p, gmtime_r(&unixts, &tm)); p = stpcpy(p, "\r\nContent-Length: "); p = FormatInt32(p, strlen(q)); p = stpcpy(p, "\r\n\r\n"); p = stpcpy(p, q); outmsglen = p - outbuf; sent = write(client, outbuf, p - outbuf); } // if the client isn't pipelining and write() wrote the full // amount, then since we sent the content length and checked // that the client didn't attach a payload, we are so synced // thus we can safely process more messages } while (got == inmsglen && sent == outmsglen && !msg.headers[kHttpContentLength].a && !msg.headers[kHttpTransferEncoding].a && (msg.method == kHttpGet || msg.method == kHttpHead)); DestroyHttpMessage(&msg); close(client); --connections; } --listening; // inform the parent that this clone has finished CloseWorker: close(server); WorkerFinished: --workers; return 0; } void OnCtrlC(int sig) { closingtime = true; status = " shutting down..."; } void PrintStatus(void) { kprintf("\r\e[K\e[32mgreenbean\e[0m " "workers=%d " "listening=%d " "connections=%d " "messages=%d%s ", workers, listening, connections, messages, status); } int main(int argc, char *argv[]) { int i, rc; pthread_t *th; uint32_t *hostips; // ShowCrashReports(); // listen for ctrl-c, hangup, and kill which shut down greenbean status = ""; struct sigaction sa = {.sa_handler = OnCtrlC}; sigaction(SIGHUP, &sa, 0); sigaction(SIGINT, &sa, 0); sigaction(SIGTERM, &sa, 0); // print all the ips that 0.0.0.0 will bind for (hostips = GetHostIps(), i = 0; hostips[i]; ++i) { kprintf("listening on http://%d.%d.%d.%d:%d\n", (hostips[i] & 0xff000000) >> 030, (hostips[i] & 0x00ff0000) >> 020, (hostips[i] & 0x0000ff00) >> 010, (hostips[i] & 0x000000ff) >> 000, PORT); } threads = argc > 1 ? atoi(argv[1]) : _getcpucount(); if (!(1 <= threads && threads <= 100000)) { kprintf("error: invalid number of threads: %d\n", threads); exit(1); } // secure the server __enable_threads(); unveil("/dev/null", "rw"); unveil(0, 0); pledge("stdio inet", 0); // spawn over 9,000 worker threads th = calloc(threads, sizeof(pthread_t)); for (i = 0; i < threads; ++i) { ++workers; if ((rc = pthread_create(th + i, 0, Worker, (void *)(intptr_t)i))) { --workers; kprintf("error: pthread_create(%d) failed %s\n", i, strerror(rc)); } if (!(i % 500)) { PrintStatus(); } } // wait for workers to terminate while (workers) { PrintStatus(); usleep(HEARTBEAT * 1000); } // clean up terminal line kprintf("\r\e[K"); // join the workers for (i = 0; i < threads; ++i) { pthread_join(th[i], 0); } // clean up memory free(hostips); free(th); }
11,539
344
jart/cosmopolitan
false
cosmopolitan/examples/img.c
#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/dce.h" #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "net/http/escape.h" #include "net/http/http.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image.h" #define USAGE \ " [FLAGS] IMG...\n\ Utility for printing HTML <img> tags.\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -a Wrap with <a> tag\n\ -u Embed data:base64 URI\n" int scale; bool linktag; bool datauri; bool sizeonly; void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void PrintImg(const char *path) { size_t n; int opt, i, yn, xn, cn, w, h; void *img, *pix, *src, *mime; if (!(img = _gc(xslurp(path, &n)))) exit(2); if (!(pix = _gc(stbi_load_from_memory(img, n, &xn, &yn, &cn, 0)))) exit(3); if (linktag) { printf("<a href=\"%s\"\n >", path); } src = path; if (datauri) { src = xasprintf("data:%s;base64,%s", FindContentType(path, -1), _gc(EncodeBase64(img, n, &n))); } w = (xn + (1 << scale) / 2) >> scale; h = (yn + (1 << scale) / 2) >> scale; if (sizeonly) { printf("width=\"%d\" height=\"%d\"", w, h); } else { printf("<img width=\"%d\" height=\"%d\" alt=\"[%s]\"\n src=\"%s\">", w, h, path, src); } if (linktag) { printf("</a>"); } printf("\n"); } int main(int argc, char *argv[]) { if (!NoDebug()) ShowCrashReports(); int i; while ((i = getopt(argc, argv, "?huas01234")) != -1) { switch (i) { case '0': case '1': case '2': case '3': case '4': scale = i - '0'; break; case 's': sizeonly = true; break; case 'a': linktag = true; break; case 'u': datauri = true; break; case '?': case 'h': PrintUsage(0, stdout); default: PrintUsage(1, stderr); } } if (optind == argc) { PrintUsage(1, stderr); } for (i = optind; i < argc; ++i) { PrintImg(argv[i]); } }
2,933
107
jart/cosmopolitan
false
cosmopolitan/examples/shutdown.c
#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/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/reboot.h" int main(int argc, char *argv[]) { char line[8] = {0}; if (argc > 1 && !strcmp(argv[1], "-y")) { line[0] = 'y'; } else { printf("shutdown your computer? yes or no [no] "); fflush(stdout); fgets(line, sizeof(line), stdin); } if (line[0] == 'y' || line[0] == 'Y') { if (reboot(RB_POWER_OFF)) { printf("system is shutting down...\n"); exit(0); } else { perror("reboot"); exit(1); } } else if (line[0] == 'n' || line[0] == 'N') { exit(0); } else { printf("error: unrecognized response\n"); exit(2); } }
1,521
40
jart/cosmopolitan
false
cosmopolitan/examples/whois.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright (c) 1980, 1993 │ │ The Regents of the University of California. All rights reserved. │ │ │ │ Redistribution and use in source and binary forms, with or without │ │ modification, are permitted provided that the following conditions │ │ are met: │ │ 1. Redistributions of source code must retain the above copyright │ │ notice, this list of conditions and the following disclaimer. │ │ 2. Redistributions in binary form must reproduce the above copyright │ │ notice, this list of conditions and the following disclaimer in the │ │ documentation and/or other materials provided with the distribution. │ │ 3. Neither the name of the University nor the names of its contributors │ │ may be used to endorse or promote products derived from this software │ │ without specific prior written permission. │ │ │ │ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │ │ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │ │ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │ │ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │ │ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │ │ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │ │ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │ │ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │ │ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │ │ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │ │ SUCH DAMAGE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/dns/dns.h" #include "libc/errno.h" #include "libc/log/bsd.h" #include "libc/mem/fmt.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sock/struct/pollfd.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/sock.h" #include "third_party/getopt/getopt.h" // clang-format off asm(".ident\t\"\\n\\n\ FreeBSD Whois (BSD-3 License)\\n\ Copyright (c) 1980, 1993\\n\ \tThe Regents of the University of California.\\n\ \tAll rights reserved.\""); asm(".include \"libc/disclaimer.inc\""); #define ABUSEHOST "whois.abuse.net" #define ANICHOST "whois.arin.net" #define DENICHOST "whois.denic.de" #define DKNICHOST "whois.dk-hostmaster.dk" #define FNICHOST "whois.afrinic.net" #define GNICHOST "whois.nic.gov" #define IANAHOST "whois.iana.org" #define INICHOST "whois.internic.net" #define KNICHOST "whois.krnic.net" #define LNICHOST "whois.lacnic.net" #define MNICHOST "whois.ra.net" #define PDBHOST "whois.peeringdb.com" #define PNICHOST "whois.apnic.net" #define QNICHOST_TAIL ".whois-servers.net" #define RNICHOST "whois.ripe.net" #define VNICHOST "whois.verisign-grs.com" #define DEFAULT_PORT "whois" #define WHOIS_RECURSE 0x01 #define WHOIS_QUICK 0x02 #define WHOIS_SPAM_ME 0x04 #define CHOPSPAM ">>> Last update of WHOIS database:" #define ishost(h) (isalnum((unsigned char)h) || h == '.' || h == '-') #define SCAN(p, end, check) \ while ((p) < (end)) \ if (check) ++(p); \ else break static struct { const char *suffix, *server; } whoiswhere[] = { /* Various handles */ { "-ARIN", ANICHOST }, { "-NICAT", "at" QNICHOST_TAIL }, { "-NORID", "no" QNICHOST_TAIL }, { "-RIPE", RNICHOST }, /* Nominet's whois server doesn't return referrals to JANET */ { ".ac.uk", "ac.uk" QNICHOST_TAIL }, { ".gov.uk", "ac.uk" QNICHOST_TAIL }, { "", IANAHOST }, /* default */ { NULL, NULL } /* safety belt */ }; #define WHOIS_REFERRAL(s) { s, sizeof(s) - 1 } static struct { const char *prefix; size_t len; } whois_referral[] = { WHOIS_REFERRAL("whois:"), /* IANA */ WHOIS_REFERRAL("Whois Server:"), WHOIS_REFERRAL("Registrar WHOIS Server:"), /* corporatedomains.com */ WHOIS_REFERRAL("ReferralServer: whois://"), /* ARIN */ WHOIS_REFERRAL("ReferralServer: rwhois://"), /* ARIN */ WHOIS_REFERRAL("descr: region. Please query"), /* AfriNIC */ { NULL, 0 } }; /* * We have a list of patterns for RIRs that assert ignorance rather than * providing referrals. If that happens, we guess that ARIN will be more * helpful. But, before following a referral to an RIR, we check if we have * asked that RIR already, and if so we make another guess. */ static const char *actually_arin[] = { "netname: ERX-NETBLOCK\n", /* APNIC */ "netname: NON-RIPE-NCC-MANAGED-ADDRESS-BLOCK\n", NULL }; static struct { int loop; const char *host; } try_rir[] = { { 0, ANICHOST }, { 0, RNICHOST }, { 0, PNICHOST }, { 0, FNICHOST }, { 0, LNICHOST }, { 0, NULL } }; static void reset_rir(void) { int i; for (i = 0; try_rir[i].host != NULL; i++) try_rir[i].loop = 0; } static const char *port = DEFAULT_PORT; static const char *choose_server(char *); static struct addrinfo *gethostinfo(const char *, const char *, int); static void s_asprintf(char **ret, const char *format, ...); static void usage(void); static void whois(const char *, const char *, const char *, int); int main(int argc, char *argv[]) { const char *country, *host; int ch, flags; #ifdef SOCKS SOCKSinit(argv[0]); #endif country = host = NULL; flags = 0; while ((ch = getopt(argc, argv, "aAbc:fgh:iIklmp:PQrRS")) != -1) { switch (ch) { case 'a': host = ANICHOST; break; case 'A': host = PNICHOST; break; case 'b': host = ABUSEHOST; break; case 'c': country = optarg; break; case 'f': host = FNICHOST; break; case 'g': host = GNICHOST; break; case 'h': host = optarg; break; case 'i': host = INICHOST; break; case 'I': host = IANAHOST; break; case 'k': host = KNICHOST; break; case 'l': host = LNICHOST; break; case 'm': host = MNICHOST; break; case 'p': port = optarg; break; case 'P': host = PDBHOST; break; case 'Q': flags |= WHOIS_QUICK; break; case 'r': host = RNICHOST; break; case 'R': flags |= WHOIS_RECURSE; break; case 'S': flags |= WHOIS_SPAM_ME; break; case '?': default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (!argc || (country != NULL && host != NULL)) usage(); /* * If no host or country is specified, rely on referrals from IANA. */ if (host == NULL && country == NULL) { if ((host = getenv("WHOIS_SERVER")) == NULL && (host = getenv("RA_SERVER")) == NULL) { if (!(flags & WHOIS_QUICK)) flags |= WHOIS_RECURSE; } } while (argc-- > 0) { if (country != NULL) { char *qnichost; s_asprintf(&qnichost, "%s%s", country, QNICHOST_TAIL); whois(*argv, qnichost, port, flags); free(qnichost); } else whois(*argv, host != NULL ? host : choose_server(*argv), port, flags); reset_rir(); argv++; } exit(0); } static const char * choose_server(char *domain) { size_t len = strlen(domain); int i; for (i = 0; whoiswhere[i].suffix != NULL; i++) { size_t suffix_len = strlen(whoiswhere[i].suffix); if (len > suffix_len && strcasecmp(domain + len - suffix_len, whoiswhere[i].suffix) == 0) return (whoiswhere[i].server); } errx(EX_SOFTWARE, "no default whois server"); } static struct addrinfo * gethostinfo(const char *host, const char *hport, int exit_on_noname) { struct addrinfo hints, *res; int error; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; res = NULL; error = getaddrinfo(host, hport, &hints, &res); if (error && (exit_on_noname || error != EAI_NONAME)) err(EX_NOHOST, "%s: %s", host, gai_strerror(error)); return (res); } /* * Wrapper for asprintf(3) that exits on error. */ static void s_asprintf(char **ret, const char *format, ...) { va_list ap; va_start(ap, format); if (vasprintf(ret, format, ap) == -1) { va_end(ap); err(EX_OSERR, "vasprintf()"); } va_end(ap); } static int connect_to_any_host(struct addrinfo *hostres) { struct addrinfo *res; nfds_t i, j; size_t count; struct pollfd *fds; int timeout = 180, s = -1; for (res = hostres, count = 0; res; res = res->ai_next) count++; fds = calloc(count, sizeof(*fds)); if (fds == NULL) err(EX_OSERR, "calloc()"); /* * Traverse the result list elements and make non-block * connection attempts. */ count = i = 0; for (res = hostres; res != NULL; res = res->ai_next) { s = socket(res->ai_family, res->ai_socktype | SOCK_NONBLOCK, res->ai_protocol); if (s < 0) continue; if (connect(s, res->ai_addr, res->ai_addrlen) < 0) { if (errno == EINPROGRESS) { /* Add the socket to poll list */ fds[i].fd = s; fds[i].events = POLLERR | POLLHUP | POLLIN | POLLOUT; /* * From here until a socket connects, the * socket fd is owned by the fds[] poll array. */ s = -1; count++; i++; } else { close(s); s = -1; /* * Poll only if we have something to poll, * otherwise just go ahead and try next * address */ if (count == 0) continue; } } else goto done; /* * If we are at the last address, poll until a connection is * established or we failed all connection attempts. */ if (res->ai_next == NULL) timeout = INFTIM; /* * Poll the watched descriptors for successful connections: * if we still have more untried resolved addresses, poll only * once; otherwise, poll until all descriptors have errors, * which will be considered as ETIMEDOUT later. */ do { int n; n = poll(fds, i, timeout); if (n == 0) { /* * No event reported in time. Try with a * smaller timeout (but cap at 2-3ms) * after a new host have been added. */ if (timeout >= 3) timeout >>= 1; break; } else if (n < 0) { /* * errno here can only be EINTR which we would * want to clean up and bail out. */ s = -1; goto done; } /* * Check for the event(s) we have seen. */ for (j = 0; j < i; j++) { if (fds[j].fd == -1 || fds[j].events == 0 || fds[j].revents == 0) continue; if (fds[j].revents & ~(POLLIN | POLLOUT)) { close(fds[j].fd); fds[j].fd = -1; fds[j].events = 0; count--; continue; } else if (fds[j].revents & (POLLIN | POLLOUT)) { /* Connect succeeded. */ s = fds[j].fd; fds[j].fd = -1; goto done; } } } while (timeout == INFTIM && count != 0); } /* All attempts were failed */ s = -1; if (count == 0) errno = ETIMEDOUT; done: /* Close all watched fds except the succeeded one */ for (j = 0; j < i; j++) if (fds[j].fd != -1) close(fds[j].fd); free(fds); return (s); } static void whois(const char *query, const char *hostname, const char *hostport, int flags) { FILE *fp; struct addrinfo *hostres; char *buf, *host, *nhost, *nport, *p; int comment, s, f; size_t len, i; hostres = gethostinfo(hostname, hostport, 1); s = connect_to_any_host(hostres); if (s == -1) err(EX_OSERR, "connect()"); /* Restore default blocking behavior. */ if ((f = fcntl(s, F_GETFL)) == -1) err(EX_OSERR, "fcntl()"); f &= ~O_NONBLOCK; if (fcntl(s, F_SETFL, f) == -1) err(EX_OSERR, "fcntl()"); fp = fdopen(s, "r+"); if (fp == NULL) err(EX_OSERR, "fdopen()"); if (!(flags & WHOIS_SPAM_ME) && (strcasecmp(hostname, DENICHOST) == 0 || strcasecmp(hostname, "de" QNICHOST_TAIL) == 0)) { const char *q; int idn = 0; for (q = query; *q != '\0'; q++) if (!isascii(*q)) idn = 1; fprintf(fp, "-T dn%s %s\r\n", idn ? "" : ",ace", query); } else if (!(flags & WHOIS_SPAM_ME) && (strcasecmp(hostname, DKNICHOST) == 0 || strcasecmp(hostname, "dk" QNICHOST_TAIL) == 0)) fprintf(fp, "--show-handles %s\r\n", query); else if ((flags & WHOIS_SPAM_ME) || strchr(query, ' ') != NULL) fprintf(fp, "%s\r\n", query); else if (strcasecmp(hostname, ANICHOST) == 0) { if (strncasecmp(query, "AS", 2) == 0 && strspn(query+2, "0123456789") == strlen(query+2)) fprintf(fp, "+ a %s\r\n", query+2); else fprintf(fp, "+ %s\r\n", query); } else if (strcasecmp(hostres->ai_canonname, VNICHOST) == 0) fprintf(fp, "domain %s\r\n", query); else fprintf(fp, "%s\r\n", query); fflush(fp); comment = 0; if (!(flags & WHOIS_SPAM_ME) && (strcasecmp(hostname, ANICHOST) == 0 || strcasecmp(hostname, RNICHOST) == 0)) { comment = 2; } nhost = NULL; while ((buf = fgetln(fp, &len)) != NULL) { /* Nominet */ if (!(flags & WHOIS_SPAM_ME) && len == 5 && strncmp(buf, "-- \r\n", 5) == 0) break; /* RIRs */ if (comment == 1 && buf[0] == '#') break; else if (comment == 2) { if (strchr("#%\r\n", buf[0]) != NULL) continue; else comment = 1; } printf("%.*s", (int)len, buf); if ((flags & WHOIS_RECURSE) && nhost == NULL) { for (i = 0; whois_referral[i].prefix != NULL; i++) { p = buf; SCAN(p, buf+len, *p == ' '); if (strncasecmp(p, whois_referral[i].prefix, whois_referral[i].len) != 0) continue; p += whois_referral[i].len; SCAN(p, buf+len, *p == ' '); host = p; SCAN(p, buf+len, ishost(*p)); if (p > host) { char *pstr; s_asprintf(&nhost, "%.*s", (int)(p - host), host); if (*p != ':') { s_asprintf(&nport, "%s", port); break; } pstr = ++p; SCAN(p, buf+len, isdigit(*p)); if (p > pstr && (p - pstr) < 6) { s_asprintf(&nport, "%.*s", (int)(p - pstr), pstr); break; } /* Invalid port; don't recurse */ free(nhost); nhost = NULL; } break; } for (i = 0; actually_arin[i] != NULL; i++) { if (strncmp(buf, actually_arin[i], len) == 0) { s_asprintf(&nhost, "%s", ANICHOST); s_asprintf(&nport, "%s", port); break; } } } /* Verisign etc. */ if (!(flags & WHOIS_SPAM_ME) && len >= sizeof(CHOPSPAM)-1 && (strncasecmp(buf, CHOPSPAM, sizeof(CHOPSPAM)-1) == 0 || strncasecmp(buf, CHOPSPAM+4, sizeof(CHOPSPAM)-5) == 0)) { printf("\n"); break; } } fclose(fp); freeaddrinfo(hostres); f = 0; for (i = 0; try_rir[i].host != NULL; i++) { /* Remember visits to RIRs */ if (try_rir[i].loop == 0 && strcasecmp(try_rir[i].host, hostname) == 0) try_rir[i].loop = 1; /* Do we need to find an alternative RIR? */ if (try_rir[i].loop != 0 && nhost != NULL && strcasecmp(try_rir[i].host, nhost) == 0) { free(nhost); nhost = NULL; free(nport); nport = NULL; f = 1; } } if (f) { /* Find a replacement RIR */ for (i = 0; try_rir[i].host != NULL; i++) { if (try_rir[i].loop == 0) { s_asprintf(&nhost, "%s", try_rir[i].host); s_asprintf(&nport, "%s", port); break; } } } if (nhost != NULL) { /* Ignore self-referrals */ if (strcasecmp(hostname, nhost) != 0) { printf("# %s\n\n", nhost); whois(query, nhost, nport, flags); } free(nhost); free(nport); } } static void usage(void) { fprintf(stderr, "usage: whois [-aAbfgiIklmPQrRS] [-c country-code | -h hostname] " "[-p port] name ...\n"); exit(EX_USAGE); }
16,492
618
jart/cosmopolitan
false
cosmopolitan/examples/decompress.c
#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/assert.h" #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/zlib/zlib.h" #define CHUNK 32768 int decompressor(int infd, int outfd) { int rc; unsigned have; z_stream zs; unsigned char *inbuf; unsigned char *outbuf; inbuf = gc(valloc(CHUNK)); outbuf = gc(valloc(CHUNK)); zs.zalloc = Z_NULL; zs.zfree = Z_NULL; zs.opaque = Z_NULL; zs.avail_in = 0; zs.next_in = Z_NULL; rc = inflateInit(&zs); if (rc != Z_OK) return rc; do { rc = read(infd, inbuf, CHUNK); if (rc == -1) { inflateEnd(&zs); return Z_ERRNO; } if (!rc) { break; } zs.avail_in = rc; zs.next_in = inbuf; do { zs.avail_out = CHUNK; zs.next_out = outbuf; rc = inflate(&zs, Z_SYNC_FLUSH); assert(rc != Z_STREAM_ERROR); switch (rc) { case Z_NEED_DICT: rc = Z_DATA_ERROR; // fallthrough case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&zs); return rc; } have = CHUNK - zs.avail_out; if (write(outfd, outbuf, have) != have) { inflateEnd(&zs); return Z_ERRNO; } } while (!zs.avail_out); } while (rc != Z_STREAM_END); inflateEnd(&zs); return rc == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } const char *zerr(int rc) { switch (rc) { case Z_ERRNO: return strerror(errno); case Z_STREAM_ERROR: return "invalid compression level"; case Z_DATA_ERROR: return "invalid or incomplete deflate data"; case Z_MEM_ERROR: return "out of memory"; case Z_VERSION_ERROR: return "zlib version mismatch!"; default: unreachable; } } int main(int argc, char *argv[]) { int rc; rc = decompressor(0, 1); if (rc == Z_OK) { return 0; } else { fprintf(stderr, "error: decompressor: %s\n", zerr(rc)); return 1; } }
2,788
99
jart/cosmopolitan
false
cosmopolitan/examples/life.c
#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 int main() { return 42; }
813
14
jart/cosmopolitan
false
cosmopolitan/examples/crashreport2.c
#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/sigset.h" #include "libc/log/log.h" #include "libc/stdio/stdio.h" /** * @fileoverview CTRL+\ debugging example * * make -j8 -O o//examples/crashreport2.com * o//examples/crashreport2.com * * Assuming you call ShowCrashReports() from main(), you can press * `CTRL+\` at anny time to generate a `SIGQUIT` message that lets you * debug wrongness and freezups. * * On supported platforms, this will cause GDB to automatically attach. * The nice thing about this, is you can start stepping through your * code at the precise instruction where the interrupt happened. See * `libc/log/attachdebugger.c` to see how it works. * * If you wish to suppress the auto-GDB behavior, then: * * export GDB= * * Or alternatively: * * extern int __isworker; * __isworker = true; * * Will cause your `SIGQUIT` handler to just print a crash report * instead. This is useful for production software that might be running * in a terminal environment like GNU Screen, but it's not desirable to * have ten worker processes trying to attach GDB at once. */ int main(int argc, char *argv[]) { volatile int64_t x; ShowCrashReports(); printf("please press ctrl+\\ and see what happens...\n"); sigsuspend(0); printf("\n\n"); printf("congratulations! your program is now resuming\n"); return 0; }
2,170
54
jart/cosmopolitan
false
cosmopolitan/examples/x86split.c
#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/errno.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/errfuns.h" #include "third_party/xed/x86.h" /** * @fileoverview x86 instruction length decoder by way of hex pipe. * * Here's an example of how you can use it to decode a NOP stream: * * $ make -j8 o//examples/x86split.com * $ echo 909090 | o//examples/x86split.com * 90 * 90 * 90 * * If there was a XOR instruction in there, it'd do this: * * $ make -j8 o//examples/x86split.com * $ echo 904531FF90 | o//examples/x86split.com * 90 # NOP * 4531FF # XOR R15D,R15D * 90 # NOP * * Now that you're able to split x86 instructions the rest is easy. */ int fgethex(FILE *f) { int o, t = -1; while (!((o = fgetc(f)) & ~0xFF)) { switch (t) { case -1: t = isxdigit(o) ? hextoint(o) : -1; break; default: if (isxdigit(o)) { return t * 16 + hextoint(o); } break; } } if (t >= 0) return einval(); return -1; } int main(int argc, char *argv[argc]) { int err; unsigned c, i, j, l; struct XedDecodedInst xedd; unsigned char buf[XED_MAX_INSTRUCTION_BYTES]; memset(buf, 0, sizeof(buf)); for (i = 0;;) { if (i < XED_MAX_INSTRUCTION_BYTES) { c = fgethex(stdin); if (c != -1) { buf[i++] = c; continue; } else if (i == 0) { break; } } if ((err = xed_instruction_length_decode( xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64), buf, i))) { errno = err; break; } l = xedd.length; if (l <= 0 || l > i) abort(); for (j = 0; j < l; ++j) { fputc("0123456789ABCDEF"[(buf[j] & 0xf0) >> 4], stdout); fputc("0123456789ABCDEF"[(buf[j] & 0x0f) >> 0], stdout); } putchar('\n'); memcpy(&buf[0], &buf[l], i -= l); } return errno; }
2,781
90
jart/cosmopolitan
false
cosmopolitan/examples/printargs.c
#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/runtime/runtime.h" int main() { __printargs(""); }
853
15
jart/cosmopolitan
false
cosmopolitan/examples/system.c
#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/runtime/runtime.h" #include "libc/stdio/stdio.h" /** * @fileoverview Cosmopolitan Command Interpreter Demo * Yes this works on Windows. */ STATIC_YOINK("_tr"); STATIC_YOINK("_sed"); int main(int argc, char *argv[]) { system("x=world\n" "echo hello $x |\n" " tr a-z A-Z |\n" " sed 's/\\(.\\)/\\1 /g'"); }
1,140
27
jart/cosmopolitan
false
cosmopolitan/examples/kilo.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ │ │ Kilo ── A very simple editor in less than 1-kilo lines of code (as │ │ counted by "cloc"). Does not depend on libcurses, directly │ │ emits VT100 escapes on the terminal. │ │ │ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2016 Salvatore Sanfilippo <antirez@gmail.com> │ │ │ │ Redistribution and use in source and binary forms, with or without │ │ modification, are permitted provided that the following conditions are │ │ met: │ │ │ │ * Redistributions of source code must retain the above copyright │ │ notice, this list of conditions and the following disclaimer. │ │ │ │ * Redistributions in binary form must reproduce the above copyright │ │ notice, this list of conditions and the following disclaimer in the │ │ documentation and/or other materials provided with the distribution. │ │ │ │ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS │ │ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT │ │ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR │ │ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT │ │ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, │ │ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT │ │ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, │ │ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY │ │ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT │ │ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE │ │ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ asm(".ident \"\n\ Kilo ─ A very simple editor (BSD-2)\n\ Copyright 2016 Salvatore Sanfilippo\n\ Contact: antirez@gmail.com\"\n\ .include \"libc/disclaimer.inc\""); /* * This software has been modified by Justine Tunney to: * * 1. Have Emacs keybindings. * * 2. Be capable of editing files with ANSI color codes, in such a way * that the ANSI color codes are displayed 'as is' (since that's * something no other editor can quite do). The kinda buggy syntax * highlighting code needed to be commented out, to do this. */ #define KILO_VERSION "0.0.1" #define SYNTAX 1 #ifndef _BSD_SOURCE #define _BSD_SOURCE #endif #define _GNU_SOURCE #include "libc/calls/calls.h" #include "libc/calls/termios.h" #include "libc/calls/weirdtypes.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/log/log.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/termios.h" #include "libc/time/time.h" /* Syntax highlight types */ #define HL_NORMAL 0 #define HL_NONPRINT 1 #define HL_COMMENT 2 /* Single line comment. */ #define HL_MLCOMMENT 3 /* Multi-line comment. */ #define HL_KEYWORD1 4 #define HL_KEYWORD2 5 #define HL_STRING 6 #define HL_NUMBER 7 #define HL_MATCH 8 /* Search match. */ #define HL_HIGHLIGHT_STRINGS (1 << 0) #define HL_HIGHLIGHT_NUMBERS (1 << 1) struct editorSyntax { const char *const *filematch; const char *const *keywords; char singleline_comment_start[2]; char multiline_comment_start[3]; char multiline_comment_end[3]; int flags; }; /* This structure represents a single line of the file we are editing. */ typedef struct erow { int idx; /* Row index in the file, zero-based. */ int size; /* Size of the row, excluding the null term. */ int rsize; /* Size of the rendered row. */ char *chars; /* Row content. */ char *render; /* Row content "rendered" for screen (for TABs). */ unsigned char *hl; /* Syntax highlight type for each character in render.*/ int hl_oc; /* Row had open comment at end in last syntax highlight check. */ } erow; typedef struct hlcolor { int r, g, b; } hlcolor; struct editorConfig { int cx, cy; /* Cursor x and y position in characters */ int rowoff; /* Offset of row displayed. */ int coloff; /* Offset of column displayed. */ int screenrows; /* Number of rows that we can show */ int screencols; /* Number of cols that we can show */ int numrows; /* Number of rows */ int rawmode; /* Is terminal raw mode enabled? */ erow *row; /* Rows */ int dirty; /* File modified but not saved. */ char *filename; /* Currently open filename */ char statusmsg[80]; time_t statusmsg_time; const struct editorSyntax *syntax; /* Current syntax highlight, or NULL. */ }; static struct editorConfig E; #define CTRL(C) ((C) ^ 0b01000000) /* where ^W etc. codes come from */ enum KEY_ACTION { ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN }; void editorSetStatusMessage(const char *fmt, ...); /* =========================== Syntax highlights DB ========================= * * In order to add a new syntax, define two arrays with a list of file name * matches and keywords. The file name matches are used in order to match * a given syntax with a given file name: if a match pattern starts with a * dot, it is matched as the last past of the filename, for example ".c". * Otherwise the pattern is just searched inside the filename, like "Makefile"). * * The list of keywords to highlight is just a list of words, however if they * a trailing '|' character is added at the end, they are highlighted in * a different color, so that you can have two different sets of keywords. * * Finally add a stanza in the HLDB global variable with two two arrays * of strings, and a set of flags in order to enable highlighting of * comments and numbers. * * The characters for single and multi line comments must be exactly two * and must be provided as well (see the C language example). * * There is no support to highlight patterns currently. */ /* C / C++ */ const char *const C_HL_extensions[] = {".c", ".h", ".cpp", NULL}; const char *const C_HL_keywords[] = { /* A few C / C++ keywords */ "switch", "if", "while", "for", "break", "continue", "return", "else", "struct", "union", "typedef", "static", "enum", "class", /* C types */ "int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|", "void|", "const|", "size_t|", "ssize_t|", "uint8_t|", "int8_t|", "uint16_t|", "int16_t|", "uint32_t|", "int32_t|", "uint64_t|", "int64_t|", NULL}; /* Here we define an array of syntax highlights by extensions, keywords, * comments delimiters and flags. */ const struct editorSyntax HLDB[] = { {/* C / C++ */ C_HL_extensions, C_HL_keywords, "//", "/*", "*/", HL_HIGHLIGHT_STRINGS | HL_HIGHLIGHT_NUMBERS}}; #define HLDB_ENTRIES (sizeof(HLDB) / sizeof(HLDB[0])) /* ======================= Low level terminal handling ====================== */ static struct termios orig_termios; /* In order to restore at exit.*/ void disableRawMode(int64_t fd) { /* Don't even check the return value as it's too late. */ if (E.rawmode) { tcsetattr(fd, TCSAFLUSH, &orig_termios); E.rawmode = 0; } } /* Called at exit to avoid remaining in raw mode. */ void editorAtExit(void) { char buf[64]; disableRawMode(STDIN_FILENO); write(STDOUT_FILENO, buf, sprintf(buf, "\e[%d;%dH\r\n\r\n\r\n", E.screenrows, E.screencols)); } /* Raw mode: 1960 magic shit. */ int enableRawMode(int64_t fd) { struct termios raw; if (E.rawmode) return 0; /* Already enabled. */ if (!isatty(STDIN_FILENO)) goto fatal; atexit(editorAtExit); if (tcgetattr(fd, &orig_termios) == -1) goto fatal; raw = orig_termios; /* modify the original mode */ /* input modes: no break, no CR to NL, no parity check, no strip char, * no start/stop output control. */ raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); /* output modes - disable post processing */ raw.c_oflag &= ~(OPOST); /* control modes - set 8 bit chars */ raw.c_cflag |= (CS8); /* local modes - choing off, canonical off, no extended functions, * no signal chars (^Z,^C) */ raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); /* control chars - set return condition: min number of bytes and timer. */ raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */ raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */ /* put terminal in raw mode after flushing */ if (tcsetattr(fd, TCSAFLUSH, &raw) < 0) goto fatal; E.rawmode = 1; return 0; fatal: errno = ENOTTY; return -1; } /* Read a key from the terminal put in raw mode, trying to handle * escape sequences. */ int editorReadKey(int64_t fd) { int nread; char c, seq[3]; do { nread = read(fd, &c, 1); if (nread == -1) exit(1); } while (!nread); while (1) { switch (c) { case CTRL('J'): /* newline */ return CTRL('M'); case CTRL('V'): return PAGE_DOWN; case '\e': /* escape sequence */ /* If this is just an ESC, we'll timeout here. */ if (read(fd, seq, 1) == 0) return CTRL('['); if (seq[0] == '[') { if (read(fd, seq + 1, 1) == 0) return CTRL('['); if (seq[1] >= '0' && seq[1] <= '9') { /* Extended escape, read additional byte. */ if (read(fd, seq + 2, 1) == 0) return CTRL('['); if (seq[2] == '~') { switch (seq[1]) { case '1': return HOME_KEY; case '3': return DEL_KEY; case '4': return END_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; } } } else { /* Arrow Keys * * KEY CODE FN SHIFT OPTION * ───── ────── ────── ────── ────── * UP ←[A ←[5~ ←[A ←[A * DOWN ←[B ←[6~ ←[B ←[B * RIGHT ←[C ←[4~ ←[1;2C ←[f * LEFT ←[D ←[1~ ←[1;2C ←[b */ switch (seq[1]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } } else if (seq[0] == 'v') { return PAGE_UP; } else if (seq[0] == 'O') { if (read(fd, seq + 1, 1) == 0) return CTRL('['); /* ESC O sequences. */ switch (seq[1]) { case 'H': return HOME_KEY; case 'F': return END_KEY; } } break; default: return c; } } } /* Use the ESC [6n escape sequence to query the horizontal cursor position * and return it. On error -1 is returned, on success the position of the * cursor is stored at *rows and *cols and 0 is returned. */ int getCursorPosition(int64_t ifd, int64_t ofd, int *rows, int *cols) { char buf[32]; unsigned i = 0; /* Report cursor location */ if (write(ofd, "\e[6n", 4) != 4) return -1; /* Read the response: ESC [ rows ; cols R */ while (i < sizeof(buf) - 1) { if (read(ifd, buf + i, 1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; /* Parse it. */ if (buf[0] != CTRL('[') || buf[1] != '[') return -1; if (sscanf(buf + 2, "%d;%d", rows, cols) != 2) return -1; return 0; } /* Try to get the number of columns in the current terminal. If the ioctl() * call fails the function will try to query the terminal itself. * Returns 0 on success, -1 on error. */ int getWindowSize(int64_t ifd, int64_t ofd, int *rows, int *cols) { struct winsize ws; if (_getttysize(1, &ws) == -1 || ws.ws_col == 0) { /* ioctl() failed. Try to query the terminal itself. */ int orig_row, orig_col, retval; /* Get the initial position so we can restore it later. */ retval = getCursorPosition(ifd, ofd, &orig_row, &orig_col); if (retval == -1) goto failed; /* Go to right/bottom margin and get position. */ if (write(ofd, "\e[999C\e[999B", 12) != 12) goto failed; retval = getCursorPosition(ifd, ofd, rows, cols); if (retval == -1) goto failed; /* Restore position. */ char seq[32]; snprintf(seq, 32, "\e[%d;%dH", orig_row, orig_col); if (write(ofd, seq, strlen(seq)) == -1) { /* Can't recover... */ } return 0; } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } failed: return -1; } /* ====================== Syntax highlight color scheme ==================== */ int is_separator(int c) { return c == '\0' || isspace(c) || strchr(",.()+-/*=~%[];", c) != NULL; } /* Return true if the specified row last char is part of a multi line comment * that starts at this row or at one before, and does not end at the end * of the row but spans to the next row. */ int editorRowHasOpenComment(erow *row) { if (row->hl && row->rsize && row->hl[row->rsize - 1] == HL_MLCOMMENT && (row->rsize < 2 || (row->render[row->rsize - 2] != '*' || row->render[row->rsize - 1] != '/'))) return 1; return 0; } /* Set every byte of row->hl (that corresponds to every character in the line) * to the right syntax highlight type (HL_* defines). */ void editorUpdateSyntax(erow *row) { row->hl = realloc(row->hl, row->rsize); memset(row->hl, HL_NORMAL, row->rsize); if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */ int i, prev_sep, in_string, in_comment; char *p; const char *const *keywords = E.syntax->keywords; char *scs = E.syntax->singleline_comment_start; char *mcs = E.syntax->multiline_comment_start; char *mce = E.syntax->multiline_comment_end; /* Point to the first non-space char. */ p = row->render; i = 0; /* Current char offset */ while (*p && isspace(*p)) { p++; i++; } prev_sep = 1; /* Tell the parser if 'i' points to start of word. */ in_string = 0; /* Are we inside "" or '' ? */ in_comment = 0; /* Are we inside multi-line comment? */ /* If the previous line has an open comment, this line starts * with an open comment state. */ if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx - 1])) in_comment = 1; while (*p) { /* Handle // comments. */ if (prev_sep && *p == scs[0] && *(p + 1) == scs[1]) { /* From here to end is a comment */ memset(row->hl + i, HL_COMMENT, row->size - i); return; } /* Handle multi line comments. */ if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (*p == mce[0] && *(p + 1) == mce[1]) { row->hl[i + 1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 0; prev_sep = 1; continue; } else { prev_sep = 0; p++; i++; continue; } } else if (*p == mcs[0] && *(p + 1) == mcs[1]) { row->hl[i] = HL_MLCOMMENT; row->hl[i + 1] = HL_MLCOMMENT; p += 2; i += 2; in_comment = 1; prev_sep = 0; continue; } /* Handle "" and '' */ if (in_string) { row->hl[i] = HL_STRING; if (*p == '\\') { row->hl[i + 1] = HL_STRING; p += 2; i += 2; prev_sep = 0; continue; } if (*p == in_string) in_string = 0; p++; i++; continue; } else { if (*p == '"' || *p == '\'') { in_string = *p; row->hl[i] = HL_STRING; p++; i++; prev_sep = 0; continue; } } /* Handle non printable chars. */ if (!isprint(*p)) { row->hl[i] = HL_NONPRINT; p++; i++; prev_sep = 0; continue; } /* Handle numbers */ if ((isdigit(*p) && (prev_sep || row->hl[i - 1] == HL_NUMBER)) || (*p == '.' && i > 0 && row->hl[i - 1] == HL_NUMBER)) { row->hl[i] = HL_NUMBER; p++; i++; prev_sep = 0; continue; } /* Handle keywords and lib calls */ if (prev_sep) { int j; for (j = 0; keywords[j]; j++) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen - 1] == '|'; if (kw2) klen--; if (!memcmp(p, keywords[j], klen) && is_separator(*(p + klen))) { /* Keyword */ memset(row->hl + i, kw2 ? HL_KEYWORD2 : HL_KEYWORD1, klen); p += klen; i += klen; break; } } if (keywords[j] != NULL) { prev_sep = 0; continue; /* We had a keyword match */ } } /* Not special chars */ prev_sep = is_separator(*p); p++; i++; } /* Propagate syntax change to the next row if the open comment * state changed. This may recursively affect all the following rows * in the file. */ int oc = editorRowHasOpenComment(row); #if SYNTAX if (row->hl_oc != oc && row->idx + 1 < E.numrows) editorUpdateSyntax(&E.row[row->idx + 1]); #endif row->hl_oc = oc; } /* Maps syntax highlight token types to terminal colors. */ int editorSyntaxToColor(int hl) { switch (hl) { case HL_COMMENT: case HL_MLCOMMENT: return 36; /* cyan */ case HL_KEYWORD1: return 33; /* yellow */ case HL_KEYWORD2: return 32; /* green */ case HL_STRING: return 35; /* magenta */ case HL_NUMBER: return 31; /* red */ case HL_MATCH: return 34; /* blu */ default: return 37; /* white */ } } /* Select the syntax highlight scheme depending on the filename, * setting it in the global state E.syntax. */ void editorSelectSyntaxHighlight(char *filename) { for (unsigned j = 0; j < HLDB_ENTRIES; j++) { struct editorSyntax *s = HLDB + j; unsigned i = 0; while (s->filematch[i]) { char *p; int patlen = strlen(s->filematch[i]); if ((p = strstr(filename, s->filematch[i])) != NULL) { if (s->filematch[i][0] != '.' || p[patlen] == '\0') { E.syntax = s; return; } } i++; } } } /* ======================= Editor rows implementation ======================= */ /* Update the rendered version and the syntax highlight of a row. */ void editorUpdateRow(erow *row) { int tabs = 0, nonprint = 0, j, idx; /* Create a version of the row we can directly print on the screen, * respecting tabs, substituting non printable characters with '?'. */ free(row->render); for (j = 0; j < row->size; j++) { if (row->chars[j] == '\t') tabs++; } row->render = malloc(row->size + tabs * 8 + nonprint * 9 + 1); idx = 0; for (j = 0; j < row->size; j++) { if (row->chars[j] == '\t') { row->render[idx++] = ' '; while (idx % 8 != 0) { row->render[idx++] = ' '; } } else { row->render[idx++] = row->chars[j]; } } row->rsize = idx; row->render[idx] = '\0'; /* Update the syntax highlighting attributes of the row. */ #if SYNTAX editorUpdateSyntax(row); #endif } /* Insert a row at the specified position, shifting the other rows on the bottom * if required. */ void editorInsertRow(int at, char *s, size_t len) { if (at > E.numrows) return; E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); if (at != E.numrows) { memmove(E.row + at + 1, E.row + at, sizeof(E.row[0]) * (E.numrows - at)); for (int j = at + 1; j <= E.numrows; j++) E.row[j].idx++; } E.row[at].size = len; E.row[at].chars = malloc(len + 1); memcpy(E.row[at].chars, s, len + 1); E.row[at].hl = NULL; E.row[at].hl_oc = 0; E.row[at].render = NULL; E.row[at].rsize = 0; E.row[at].idx = at; editorUpdateRow(E.row + at); E.numrows++; E.dirty++; } /* Free row's heap allocated stuff. */ void editorFreeRow(erow *row) { free(row->render); free(row->chars); free(row->hl); } /* Remove the row at the specified position, shifting the remaining on the * top. */ void editorDelRow(int at) { erow *row; if (at >= E.numrows) return; row = E.row + at; editorFreeRow(row); memmove(E.row + at, E.row + at + 1, sizeof(E.row[0]) * (E.numrows - at - 1)); for (int j = at; j < E.numrows - 1; j++) E.row[j].idx++; E.numrows--; E.dirty++; } /* Turn the editor rows into a single heap-allocated string. * Returns the pointer to the heap-allocated string and populate the * integer pointed by 'buflen' with the size of the string, excluding * the final nulterm. */ char *editorRowsToString(int *buflen) { char *buf = NULL, *p; int totlen = 0; int j; /* Compute count of bytes */ for (j = 0; j < E.numrows; j++) { totlen += E.row[j].size + 1; /* +1 is for "\n" at end of every row */ } *buflen = totlen; totlen++; /* Also make space for nulterm */ p = buf = malloc(totlen); for (j = 0; j < E.numrows; j++) { memcpy(p, E.row[j].chars, E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } *p = '\0'; return buf; } /* Insert a character at the specified position in a row, moving the remaining * chars on the right if needed. */ void editorRowInsertChar(erow *row, int at, int c) { if (at > row->size) { /* Pad the string with spaces if the insert location is outside the * current length by more than a single character. */ int padlen = at - row->size; /* In the next line +2 means: new char and null term. */ row->chars = realloc(row->chars, row->size + padlen + 2); memset(row->chars + row->size, ' ', padlen); row->chars[row->size + padlen + 1] = '\0'; row->size += padlen + 1; } else { /* If we are in the middle of the string just make space for 1 new * char plus the (already existing) null term. */ row->chars = realloc(row->chars, row->size + 2); memmove(row->chars + at + 1, row->chars + at, row->size - at + 1); row->size++; } row->chars[at] = c; editorUpdateRow(row); E.dirty++; } /* Append the string 's' at the end of a row */ void editorRowAppendString(erow *row, char *s, size_t len) { row->chars = realloc(row->chars, row->size + len + 1); memcpy(row->chars + row->size, s, len); row->size += len; row->chars[row->size] = '\0'; editorUpdateRow(row); E.dirty++; } /* Delete the character at offset 'at' from the specified row. */ void editorRowDelChar(erow *row, int at) { if (row->size <= at) return; memmove(row->chars + at, row->chars + at + 1, row->size - at); editorUpdateRow(row); row->size--; E.dirty++; } /* Insert the specified char at the current prompt position. */ void editorInsertChar(int c) { int filerow = E.rowoff + E.cy; int filecol = E.coloff + E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; /* If the row where the cursor is currently located does not exist in our * logical representation of the file, add enough empty rows as needed. */ if (!row) { while (E.numrows <= filerow) editorInsertRow(E.numrows, "", 0); } row = &E.row[filerow]; editorRowInsertChar(row, filecol, c); if (E.cx == E.screencols - 1) { E.coloff++; } else { E.cx++; } E.dirty++; } /* Inserting a newline is slightly complex as we have to handle inserting a * newline in the middle of a line, splitting the line as needed. */ void editorInsertNewline(void) { int filerow = E.rowoff + E.cy; int filecol = E.coloff + E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row) { if (filerow == E.numrows) { editorInsertRow(filerow, "", 0); goto fixcursor; } return; } /* If the cursor is over the current line size, we want to conceptually * think it's just over the last character. */ if (filecol >= row->size) filecol = row->size; if (filecol == 0) { editorInsertRow(filerow, "", 0); } else { /* We are in the middle of a line. Split it between two rows. */ editorInsertRow(filerow + 1, row->chars + filecol, row->size - filecol); row = &E.row[filerow]; row->chars[filecol] = '\0'; row->size = filecol; editorUpdateRow(row); } fixcursor: if (E.cy == E.screenrows - 1) { E.rowoff++; } else { E.cy++; } E.cx = 0; E.coloff = 0; } /* Delete the char at the current prompt position. */ void editorDelChar(void) { int filerow = E.rowoff + E.cy; int filecol = E.coloff + E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row || (filecol == 0 && filerow == 0)) return; if (filecol == 0) { /* Handle the case of column 0, we need to move the current line * on the right of the previous one. */ filecol = E.row[filerow - 1].size; editorRowAppendString(&E.row[filerow - 1], row->chars, row->size); editorDelRow(filerow); row = NULL; if (E.cy == 0) E.rowoff--; else E.cy--; E.cx = filecol; if (E.cx >= E.screencols) { int shift = (E.screencols - E.cx) + 1; E.cx -= shift; E.coloff += shift; } } else { editorRowDelChar(row, filecol - 1); if (E.cx == 0 && E.coloff) E.coloff--; else E.cx--; } if (row) editorUpdateRow(row); E.dirty++; } /* Load the specified program in the editor memory and returns 0 on success * or 1 on error. */ int editorOpen(char *filename) { FILE *fp; E.dirty = 0; free(E.filename); E.filename = strdup(filename); fp = fopen(filename, "r"); if (!fp) { if (errno != ENOENT) { perror("Opening file"); exit(1); } return 1; } char *line = NULL; size_t linecap = 0; ssize_t linelen; while ((linelen = getline(&line, &linecap, fp)) != -1) { if (linelen && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) line[--linelen] = '\0'; editorInsertRow(E.numrows, line, linelen); } free(line); fclose(fp); E.dirty = 0; return 0; } #define UNSAFE_SAVES 1 /* Save the current file on disk. Return 0 on success, 1 on error. */ int editorSave(void) { int len; char *buf = editorRowsToString(&len); int64_t fd = open(E.filename, O_RDWR | O_CREAT, 0644); if (fd == -1) goto writeerr; /* Use truncate + a single write(2) call in order to make saving * a bit safer, under the limits of what we can do in a small editor. */ if (ftruncate(fd, len) == -1) goto writeerr; if (write(fd, buf, len) != len) goto writeerr; close(fd); free(buf); E.dirty = 0; editorSetStatusMessage("%d bytes written on disk", len); return 0; writeerr: free(buf); if (fd != -1) close(fd); editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno)); return 1; } /* ============================= Terminal update ============================ */ struct abuf { size_t i, n; char *p; }; static void abAppend(struct abuf *ab, const char *s, int len) { CONCAT(&ab->p, &ab->i, &ab->n, s, len); } /* This function writes the whole screen using VT100 escape characters * starting from the logical state of the editor in the global state 'E'. */ void editorRefreshScreen(void) { int y; erow *r; char buf[32]; struct abuf ab; memset(&ab, 0, sizeof(ab)); abAppend(&ab, "\e[?25l", 6); /* Hide cursor. */ abAppend(&ab, "\e[H", 3); /* Go home. */ for (y = 0; y < E.screenrows; y++) { int filerow = E.rowoff + y; if (filerow >= E.numrows) { if (E.numrows == 0 && y == E.screenrows / 3) { char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "Kilo editor -- version %s\e[0K\r\n", KILO_VERSION); int padding = (E.screencols - welcomelen) / 2; if (padding) { abAppend(&ab, "~", 1); padding--; } while (padding--) abAppend(&ab, " ", 1); abAppend(&ab, welcome, welcomelen); } else { abAppend(&ab, "~\e[0K\r\n", 7); } continue; } r = &E.row[filerow]; int len = r->rsize - E.coloff; #if SYNTAX int current_color = -1; #endif if (len > 0) { if (len > E.screencols) len = E.screencols; char *c = r->render + E.coloff; #if SYNTAX unsigned char *hl = r->hl + E.coloff; #endif int j; for (j = 0; j < len; j++) { #if SYNTAX if (hl[j] == HL_NONPRINT) { char sym; abAppend(&ab, "\e[7m", 4); if (c[j] <= 26) sym = '@' + c[j]; else sym = '?'; abAppend(&ab, &sym, 1); abAppend(&ab, "\e[0m", 4); } else if (hl[j] == HL_NORMAL) { if (current_color != -1) { abAppend(&ab, "\e[39m", 5); current_color = -1; } #endif abAppend(&ab, c + j, 1); #if SYNTAX } else { int color = editorSyntaxToColor(hl[j]); if (color != current_color) { char buf_[16]; int clen = snprintf(buf_, sizeof(buf_), "\e[%dm", color); current_color = color; abAppend(&ab, buf_, clen); } abAppend(&ab, c + j, 1); } #endif } } abAppend(&ab, "\e[39m", 5); abAppend(&ab, "\e[0K", 4); abAppend(&ab, "\r\n", 2); } /* Create a two rows status. First row: */ abAppend(&ab, "\e[0K", 4); abAppend(&ab, "\e[7m", 4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", E.filename, E.numrows, E.dirty ? "(modified)" : ""); int rlen = snprintf(rstatus, sizeof(rstatus), "%d/%d", E.rowoff + E.cy + 1, E.numrows); if (len > E.screencols) len = E.screencols; abAppend(&ab, status, len); while (len < E.screencols) { if (E.screencols - len == rlen) { abAppend(&ab, rstatus, rlen); break; } else { abAppend(&ab, " ", 1); len++; } } abAppend(&ab, "\e[0m\r\n", 6); /* Second row depends on E.statusmsg and the status message update time. */ abAppend(&ab, "\e[0K", 4); int msglen = strlen(E.statusmsg); if (msglen && time(NULL) - E.statusmsg_time < 5) abAppend(&ab, E.statusmsg, msglen <= E.screencols ? msglen : E.screencols); /* Put cursor at its current position. Note that the horizontal position * at which the cursor is displayed may be different compared to 'E.cx' * because of TABs. */ int j; int cx = 1; int filerow = E.rowoff + E.cy; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (row) { for (j = E.coloff; j < (E.cx + E.coloff); j++) { if (j < row->size && row->chars[j] == CTRL('I')) cx += 7 - ((cx) % 8); cx++; } } snprintf(buf, sizeof(buf), "\e[%d;%dH", E.cy + 1, cx); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\e[?25h", 6); /* Show cursor. */ write(STDOUT_FILENO, ab.p, ab.i); free(ab.p); } /* Set an editor status message for the second line of the status, at the * end of the screen. */ void editorSetStatusMessage(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap); va_end(ap); E.statusmsg_time = time(NULL); } /* =============================== Find mode ================================ */ #define KILO_QUERY_LEN 256 void editorFind(int64_t fd) { char query[KILO_QUERY_LEN + 1] = {0}; int qlen = 0; int last_match = -1; /* Last line where a match was found. -1 for none. */ int find_next = 0; /* if 1 search next, if -1 search prev. */ int saved_hl_line = -1; /* No saved HL */ char *saved_hl = NULL; #define FIND_RESTORE_HL \ do { \ if (saved_hl) { \ memcpy(E.row[saved_hl_line].hl, saved_hl, E.row[saved_hl_line].rsize); \ saved_hl = NULL; \ } \ } while (0) /* Save the cursor position in order to restore it later. */ int saved_cx = E.cx, saved_cy = E.cy; int saved_coloff = E.coloff, saved_rowoff = E.rowoff; while (1) { editorSetStatusMessage("Search: %s (Use ESC/Arrows/Enter)", query); editorRefreshScreen(); int c = editorReadKey(fd); if (c == DEL_KEY || c == CTRL('H') || c == CTRL('?')) { if (qlen != 0) query[--qlen] = '\0'; last_match = -1; } else if (c == CTRL('G')) { break; } else if (c == CTRL('[') || c == CTRL('M')) { if (c == CTRL('[')) { E.cx = saved_cx; E.cy = saved_cy; E.coloff = saved_coloff; E.rowoff = saved_rowoff; } FIND_RESTORE_HL; editorSetStatusMessage(""); return; } else if (c == ARROW_RIGHT || c == ARROW_DOWN) { find_next = 1; } else if (c == ARROW_LEFT || c == ARROW_UP) { find_next = -1; } else if (isprint(c)) { if (qlen < KILO_QUERY_LEN) { query[qlen++] = c; query[qlen] = '\0'; last_match = -1; } } /* Search occurrence. */ if (last_match == -1) find_next = 1; if (find_next) { char *match = NULL; int match_offset = 0; int i, current = last_match; for (i = 0; i < E.numrows; i++) { current += find_next; if (current == -1) current = E.numrows - 1; else if (current == E.numrows) current = 0; match = strstr(E.row[current].render, query); if (match) { match_offset = match - E.row[current].render; break; } } find_next = 0; /* Highlight */ FIND_RESTORE_HL; if (match) { erow *row = &E.row[current]; last_match = current; if (row->hl) { saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl, row->hl, row->rsize); memset(row->hl + match_offset, HL_MATCH, qlen); } E.cy = 0; E.cx = match_offset; E.rowoff = current; E.coloff = 0; /* Scroll horizontally as needed. */ if (E.cx > E.screencols) { int diff = E.cx - E.screencols; E.cx -= diff; E.coloff += diff; } } } } } /* ========================= Editor events handling ======================== */ /* Handle cursor position change because arrow keys were pressed. */ void editorMoveCursor(int key) { int filerow = E.rowoff + E.cy; int filecol = E.coloff + E.cx; int rowlen; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; switch (key) { case ARROW_LEFT: if (E.cx == 0) { if (E.coloff) { E.coloff--; } else { if (filerow > 0) { E.cy--; E.cx = E.row[filerow - 1].size; if (E.cx > E.screencols - 1) { E.coloff = E.cx - E.screencols + 1; E.cx = E.screencols - 1; } } } } else { E.cx -= 1; } break; case ARROW_RIGHT: if (row && filecol < row->size) { if (E.cx == E.screencols - 1) { E.coloff++; } else { E.cx += 1; } } else if (row && filecol == row->size) { E.cx = 0; E.coloff = 0; if (E.cy == E.screenrows - 1) { E.rowoff++; } else { E.cy += 1; } } break; case ARROW_UP: if (E.cy == 0) { if (E.rowoff) E.rowoff--; } else { E.cy -= 1; } break; case ARROW_DOWN: if (filerow < E.numrows) { if (E.cy == E.screenrows - 1) { E.rowoff++; } else { E.cy += 1; } } break; } /* Fix cx if the current line has not enough chars. */ filerow = E.rowoff + E.cy; filecol = E.coloff + E.cx; row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; rowlen = row ? row->size : 0; if (filecol > rowlen) { E.cx -= filecol - rowlen; if (E.cx < 0) { E.coloff += E.cx; E.cx = 0; } } } /* Process events arriving from the standard input, which is, the user * is typing stuff on the terminal. */ #define KILO_QUIT_TIMES 3 void editorProcessKeypress(int64_t fd) { /* When the file is modified, requires Ctrl-q to be pressed N times * before actually quitting. */ static int quit_times; int c, c2, times, oldcx; c = editorReadKey(fd); switch (c) { case CTRL('M'): /* Enter */ editorInsertNewline(); break; case CTRL('C'): /* Ctrl-c */ /* We ignore ctrl-c, it can't be so simple to lose the changes * to the edited file. */ break; case CTRL('Q'): /* Ctrl-q */ /* Quit if the file was already saved. */ if (E.dirty && quit_times < KILO_QUIT_TIMES) { editorSetStatusMessage("WARNING!!! File has unsaved changes. " "Press Ctrl-Q %d more times to quit.", KILO_QUIT_TIMES - quit_times); quit_times++; return; } exit(0); break; case CTRL('U'): case CTRL('X'): { c2 = editorReadKey(fd); switch (c2) { case CTRL('S'): editorSave(); break; case CTRL('C'): { /* write(STDOUT_FILENO, "\r\e[0J", 5); */ exit(0); break; } default: /* ignore */ break; } break; } case CTRL('S'): editorFind(fd); break; case CTRL('D'): /* Delete */ case DEL_KEY: editorMoveCursor(ARROW_RIGHT); case CTRL('?'): /* Backspace */ case CTRL('H'): editorDelChar(); break; case CTRL('K'): { /* Kill Line */ oldcx = E.cx; do { editorMoveCursor(ARROW_RIGHT); } while (E.cx); editorMoveCursor(ARROW_LEFT); if (E.cx) { /* non-empty line: preserve row */ while (E.cx > oldcx) { editorDelChar(); } } else { /* empty line: remove row */ editorMoveCursor(ARROW_RIGHT); editorDelChar(); } break; } case CTRL('L'): times = E.screenrows / 2; while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN); times = E.screenrows / 2; while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_DOWN : ARROW_UP); break; case PAGE_UP: case PAGE_DOWN: if (c == PAGE_UP && E.cy != 0) { E.cy = 0; } else if (c == PAGE_DOWN && E.cy != E.screenrows - 1) { E.cy = E.screenrows - 1; } times = E.screenrows; while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN); times = E.screenrows / 2; while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_DOWN : ARROW_UP); break; case HOME_KEY: case CTRL('A'): while (E.cx || E.coloff) editorMoveCursor(ARROW_LEFT); break; case END_KEY: case CTRL('E'): do { editorMoveCursor(ARROW_RIGHT); } while (E.cx); editorMoveCursor(ARROW_LEFT); break; case CTRL('P'): editorMoveCursor(ARROW_UP); break; case CTRL('N'): editorMoveCursor(ARROW_DOWN); break; case CTRL('B'): editorMoveCursor(ARROW_LEFT); break; case CTRL('F'): editorMoveCursor(ARROW_RIGHT); break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: editorMoveCursor(c); break; case CTRL('['): /* Nothing to do for ESC in this mode. */ break; default: editorInsertChar(c); break; } quit_times = 0; /* Reset it to the original value. */ } int editorFileWasModified(void) { return E.dirty; } void initEditor(void) { E.cx = 0; E.cy = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.dirty = 0; E.filename = NULL; E.syntax = NULL; if (getWindowSize(STDIN_FILENO, STDOUT_FILENO, &E.screenrows, &E.screencols) == -1) { perror("Unable to query the screen for size (columns / rows)"); exit(1); } E.screenrows -= 2; /* Get room for status bar. */ } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: kilo <filename>\n"); exit(1); } initEditor(); editorSelectSyntaxHighlight(argv[1]); editorOpen(argv[1]); enableRawMode(STDIN_FILENO); editorSetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"); while (1) { editorRefreshScreen(); editorProcessKeypress(STDIN_FILENO); } return 0; }
42,415
1,404
jart/cosmopolitan
false
cosmopolitan/examples/panels.c
#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/ioctl.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/dce.h" #include "libc/log/check.h" #include "libc/log/gdb.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/termios.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "tool/build/lib/panel.h" /** * @fileoverview Cosmopolitan Paneling Demo. * * This is useful for creating terminal user interfaces. We take the * simplest approach possible. The main thing we abstract is like, * truncating the lines that overflow within a panel. In order to do * that, we abstract the ANSI parsing and the implementation is able to * tell how many cells wide each UNICODE character is. * * There are smarter ways for Cosmopolitan to do this. For example, it'd * be great to have automatic flex boxes. It'd also be nice to be able * to use dynamic programming for low bandwidth display updates, like * Emacs does, but that's less of an issue these days and can actually * make things slower, since for heavy workloads like printing videos, * having ANSI codes bouncing around the display actually goes slower. * * Beyond basic paneling, a message box widget is also provided, which * makes it easier to do modal dialogs. */ struct Panels { union { struct { struct Panel left; struct Panel right; }; struct Panel p[2]; }; } pan; long tyn; long txn; char key[8]; bool shutdown; bool invalidated; struct termios oldterm; void OnShutdown(int sig) { shutdown = true; } void OnInvalidate(int sig) { invalidated = true; } void GetTtySize(void) { struct winsize wsize; wsize.ws_row = tyn; wsize.ws_col = txn; _getttysize(1, &wsize); tyn = wsize.ws_row; txn = wsize.ws_col; } int Write(const char *s) { return write(1, s, strlen(s)); } void Setup(void) { CHECK_NE(-1, ioctl(1, TCGETS, &oldterm)); } void Enter(void) { struct termios term; memcpy(&term, &oldterm, sizeof(term)); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 1; term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON); term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL); term.c_cflag &= ~(CSIZE | PARENB); term.c_cflag |= CS8; term.c_iflag |= IUTF8; CHECK_NE(-1, ioctl(1, TCSETS, &term)); Write("\e[?25l"); } void Leave(void) { Write(gc(xasprintf("\e[?25h\e[%d;%dH\e[S\r\n", tyn, txn))); ioctl(1, TCSETS, &oldterm); } void Clear(void) { long i, j; for (i = 0; i < ARRAYLEN(pan.p); ++i) { for (j = 0; j < pan.p[i].n; ++j) { free(pan.p[i].lines[j].p); } free(pan.p[i].lines); pan.p[i].lines = 0; pan.p[i].n = 0; } } void Layout(void) { long i, j; i = txn >> 1; pan.left.top = 0; pan.left.left = 0; pan.left.bottom = tyn; pan.left.right = i; pan.right.top = 0; pan.right.left = i + 1; pan.right.bottom = tyn; pan.right.right = txn; pan.left.n = pan.left.bottom - pan.left.top; pan.left.lines = xcalloc(pan.left.n, sizeof(*pan.left.lines)); pan.right.n = pan.right.bottom - pan.right.top; pan.right.lines = xcalloc(pan.right.n, sizeof(*pan.right.lines)); } void Append(struct Panel *p, int i, const char *s) { if (i >= p->n) return; AppendStr(p->lines + i, s); } void Draw(void) { Append(&pan.left, 0, gc(xasprintf("you typed %`'s", key))); Append(&pan.left, ((tyn + 1) >> 1) + 0, "hello left 1 𐌰𐌱𐌲𐌳𐌴𐌵𐌶𐌷"); Append(&pan.left, ((tyn + 1) >> 1) + 1, "hello left 2 (╯°□°)╯"); Append(&pan.right, ((tyn + 1) >> 1) + 0, "hello right 1"); Append(&pan.right, ((tyn + 1) >> 1) + 1, "hello right 2"); PrintPanels(1, ARRAYLEN(pan.p), pan.p, tyn, txn); } int main(int argc, char *argv[]) { struct sigaction sa[2] = {{.sa_handler = OnShutdown}, {.sa_handler = OnInvalidate}}; if (!NoDebug()) ShowCrashReports(); Setup(); Enter(); GetTtySize(); sigaction(SIGINT, &sa[0], 0); sigaction(SIGCONT, &sa[1], 0); sigaction(SIGWINCH, &sa[1], 0); atexit(Leave); do { Clear(); Layout(); Draw(); if (invalidated) { Enter(); GetTtySize(); invalidated = false; } else { readansi(0, key, sizeof(key)); } } while (!shutdown); }
5,275
179
jart/cosmopolitan
false
cosmopolitan/examples/forkrand.c
#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/log/check.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" dontinline void dostuff(const char *s) { int i, us; srand(_rand64()); /* seeds rand() w/ intel rdrnd, auxv, etc. */ for (i = 0; i < 5; ++i) { us = rand() % 500000; usleep(us); printf("hello no. %u from %s %u [us=%d]\n", i, s, getpid(), us); fflush(stdout); } } int main(int argc, char *argv[]) { int rc, child, wstatus; CHECK_NE(-1, (child = fork())); if (!child) { /* child process */ dostuff("child"); return 0; } else { /* parent process */ dostuff("parent"); /* note: abandoned children become zombies */ CHECK_NE(-1, (rc = wait(&wstatus))); CHECK_EQ(0, WEXITSTATUS(wstatus)); return 0; } }
1,568
42
jart/cosmopolitan
false
cosmopolitan/examples/linenoise.c
#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/mem/mem.h" #include "libc/stdio/stdio.h" #include "third_party/linenoise/linenoise.h" int main(int argc, char *argv[]) { char *line; while ((line = linenoiseWithHistory("IN> ", "foo"))) { fputs("OUT> ", stdout); fputs(line, stdout); fputs("\n", stdout); free(line); } return 0; }
1,104
24
jart/cosmopolitan
false
cosmopolitan/examples/rusage.c
#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/rusage.h" #include "libc/calls/struct/sigaction.h" #include "libc/errno.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/math.h" #include "libc/runtime/clktck.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" #define PREFIX "\e[1mRL\e[0m: " static void PrintResourceReport(struct rusage *ru) { long utime, stime; long double ticks; if (ru->ru_maxrss) { fprintf(stderr, "%sballooned to %,ldkb in size\n", PREFIX, ru->ru_maxrss); } if ((utime = ru->ru_utime.tv_sec * 1000000 + ru->ru_utime.tv_usec) | (stime = ru->ru_stime.tv_sec * 1000000 + ru->ru_stime.tv_usec)) { ticks = ceill((long double)(utime + stime) / (1000000.L / CLK_TCK)); fprintf(stderr, "%sneeded %,ldµs cpu (%d%% kernel)\n", PREFIX, utime + stime, (int)((long double)stime / (utime + stime) * 100)); if (ru->ru_idrss) { fprintf(stderr, "%sneeded %,ldkb memory on average\n", PREFIX, lroundl(ru->ru_idrss / ticks)); } if (ru->ru_isrss) { fprintf(stderr, "%sneeded %,ldkb stack on average\n", PREFIX, lroundl(ru->ru_isrss / ticks)); } if (ru->ru_ixrss) { fprintf(stderr, "%smapped %,ldkb shared on average\n", PREFIX, lroundl(ru->ru_ixrss / ticks)); } } if (ru->ru_minflt || ru->ru_majflt) { fprintf(stderr, "%scaused %,ld page faults (%d%% memcpy)\n", PREFIX, ru->ru_minflt + ru->ru_majflt, (int)((long double)ru->ru_minflt / (ru->ru_minflt + ru->ru_majflt) * 100)); } if (ru->ru_nvcsw + ru->ru_nivcsw > 1) { fprintf(stderr, "%s%,ld context switches (%d%% consensual)\n", PREFIX, ru->ru_nvcsw + ru->ru_nivcsw, (int)((long double)ru->ru_nvcsw / (ru->ru_nvcsw + ru->ru_nivcsw) * 100)); } if (ru->ru_msgrcv || ru->ru_msgsnd) { fprintf(stderr, "%sreceived %,ld message%s and sent %,ld\n", PREFIX, ru->ru_msgrcv, ru->ru_msgrcv == 1 ? "" : "s", ru->ru_msgsnd); } if (ru->ru_inblock || ru->ru_oublock) { fprintf(stderr, "%sperformed %,ld read%s and %,ld write i/o operations\n", PREFIX, ru->ru_inblock, ru->ru_inblock == 1 ? "" : "s", ru->ru_oublock); } if (ru->ru_nsignals) { fprintf(stderr, "%sreceived %,ld signals\n", PREFIX, ru->ru_nsignals); } if (ru->ru_nswap) { fprintf(stderr, "%sgot swapped %,ld times\n", PREFIX, ru->ru_nswap); } } struct rusage rusage; int main(int argc, char *argv[]) { int pid, wstatus; long double ts1, ts2; sigset_t chldmask, savemask; struct sigaction dflt, ignore, saveint, savequit; if (argc < 2) { fprintf(stderr, "Usage: %s PROG [ARGS...]\n", argv[0]); return 1; } dflt.sa_flags = 0; dflt.sa_handler = SIG_DFL; sigemptyset(&dflt.sa_mask); ignore.sa_flags = 0; ignore.sa_handler = SIG_IGN; sigemptyset(&ignore.sa_mask); sigaction(SIGINT, &ignore, &saveint); sigaction(SIGQUIT, &ignore, &savequit); sigemptyset(&chldmask); sigaddset(&chldmask, SIGCHLD); sigprocmask(SIG_BLOCK, &chldmask, &savemask); ts1 = nowl(); CHECK_NE(-1, (pid = fork())); if (!pid) { sigaction(SIGINT, &dflt, 0); sigaction(SIGQUIT, &dflt, 0); sigprocmask(SIG_SETMASK, &savemask, 0); execvp(argv[1], argv + 1); fprintf(stderr, "exec failed %d\n", errno); _Exit(127); } while (wait4(pid, &wstatus, 0, &rusage) == -1) { CHECK_EQ(EINTR, errno); } ts2 = nowl(); sigaction(SIGINT, &saveint, 0); sigaction(SIGQUIT, &savequit, 0); sigprocmask(SIG_SETMASK, &savemask, 0); fprintf(stderr, "%stook %,ldµs wall time\n", PREFIX, (int64_t)((ts2 - ts1) * 1e6)); PrintResourceReport(&rusage); if (WIFEXITED(wstatus)) { return WEXITSTATUS(wstatus); } else { return 128 + WTERMSIG(wstatus); } }
4,766
128
jart/cosmopolitan
false
cosmopolitan/examples/hellolua.c
#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 "third_party/lua/lauxlib.h" #include "third_party/lua/lualib.h" int NativeAdd(lua_State *L) { lua_Number x, y; x = luaL_checknumber(L, 1); y = luaL_checknumber(L, 2); lua_pushnumber(L, x + y); return 1; /* number of results */ } int main(int argc, char *argv[]) { lua_State *L; L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, NativeAdd); lua_setglobal(L, "NativeAdd"); luaL_dofile(L, "/zip/examples/hellolua.lua"); lua_close(L); return 0; }
1,274
31
jart/cosmopolitan
false
cosmopolitan/examples/seq.c
#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/fmt/conv.h" #include "libc/fmt/itoa.h" /** * @fileoverview Prints sequence of numbers. */ int main(int argc, char *argv[]) { long a, b, i; char buf[21], *p; switch (argc) { case 2: a = 1; b = strtol(argv[1], NULL, 0); break; case 3: a = strtol(argv[1], NULL, 0); b = strtol(argv[2], NULL, 0); break; default: return 1; } for (i = a; i <= b; ++i) { p = buf; p = FormatInt64(p, i); *p++ = '\n'; write(1, buf, p - buf); } }
1,336
40
jart/cosmopolitan
false
cosmopolitan/examples/picol.c
/* Tcl in ~ 500 lines of code. * * Copyright (c) 2007-2016, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Original from http://oldblog.antirez.com/page/picol.html * Changes on 2021-12-27 by octetta : * . Use Cosmopolitan's headers. * . Formatted as per Cosmopolitan's standards. */ #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" enum { PICOL_OK, PICOL_ERR, PICOL_RETURN, PICOL_BREAK, PICOL_CONTINUE }; enum { PT_ESC, PT_STR, PT_CMD, PT_VAR, PT_SEP, PT_EOL, PT_EOF }; struct picolParser { char *text; char *p; /* current text position */ int len; /* remaining length */ char *start; /* token start */ char *end; /* token end */ int type; /* token type, PT_... */ int insidequote; /* True if inside " " */ }; struct picolVar { char *name, *val; struct picolVar *next; }; struct picolInterp; /* forward declaration */ typedef int (*picolCmdFunc)(struct picolInterp *i, int argc, char **argv, void *privdata); struct picolCmd { char *name; picolCmdFunc func; void *privdata; struct picolCmd *next; }; struct picolCallFrame { struct picolVar *vars; struct picolCallFrame *parent; /* parent is NULL at top level */ }; struct picolInterp { int level; /* Level of nesting */ struct picolCallFrame *callframe; struct picolCmd *commands; char *result; }; void picolInitParser(struct picolParser *p, char *text) { p->text = p->p = text; p->len = strlen(text); p->start = 0; p->end = 0; p->insidequote = 0; p->type = PT_EOL; } int picolParseSep(struct picolParser *p) { p->start = p->p; while (*p->p == ' ' || *p->p == '\t' || *p->p == '\n' || *p->p == '\r') { p->p++; p->len--; } p->end = p->p - 1; p->type = PT_SEP; return PICOL_OK; } int picolParseEol(struct picolParser *p) { p->start = p->p; while (*p->p == ' ' || *p->p == '\t' || *p->p == '\n' || *p->p == '\r' || *p->p == ';') { p->p++; p->len--; } p->end = p->p - 1; p->type = PT_EOL; return PICOL_OK; } int picolParseCommand(struct picolParser *p) { int level = 1; int blevel = 0; p->start = ++p->p; p->len--; while (1) { if (p->len == 0) { break; } else if (*p->p == '[' && blevel == 0) { level++; } else if (*p->p == ']' && blevel == 0) { if (!--level) break; } else if (*p->p == '\\') { p->p++; p->len--; } else if (*p->p == '{') { blevel++; } else if (*p->p == '}') { if (blevel != 0) blevel--; } p->p++; p->len--; } p->end = p->p - 1; p->type = PT_CMD; if (*p->p == ']') { p->p++; p->len--; } return PICOL_OK; } int picolParseVar(struct picolParser *p) { p->start = ++p->p; p->len--; /* skip the $ */ while (1) { if ((*p->p >= 'a' && *p->p <= 'z') || (*p->p >= 'A' && *p->p <= 'Z') || (*p->p >= '0' && *p->p <= '9') || *p->p == '_') { p->p++; p->len--; continue; } break; } if (p->start == p->p) { /* It's just a single char string "$" */ p->start = p->end = p->p - 1; p->type = PT_STR; } else { p->end = p->p - 1; p->type = PT_VAR; } return PICOL_OK; } int picolParseBrace(struct picolParser *p) { int level = 1; p->start = ++p->p; p->len--; while (1) { if (p->len >= 2 && *p->p == '\\') { p->p++; p->len--; } else if (p->len == 0 || *p->p == '}') { level--; if (level == 0 || p->len == 0) { p->end = p->p - 1; if (p->len) { p->p++; p->len--; /* Skip final closed brace */ } p->type = PT_STR; return PICOL_OK; } } else if (*p->p == '{') level++; p->p++; p->len--; } return PICOL_OK; /* unreached */ } int picolParseString(struct picolParser *p) { int newword = (p->type == PT_SEP || p->type == PT_EOL || p->type == PT_STR); if (newword && *p->p == '{') return picolParseBrace(p); else if (newword && *p->p == '"') { p->insidequote = 1; p->p++; p->len--; } p->start = p->p; while (1) { if (p->len == 0) { p->end = p->p - 1; p->type = PT_ESC; return PICOL_OK; } switch (*p->p) { case '\\': if (p->len >= 2) { p->p++; p->len--; } break; case '$': case '[': p->end = p->p - 1; p->type = PT_ESC; return PICOL_OK; case ' ': case '\t': case '\n': case '\r': case ';': if (!p->insidequote) { p->end = p->p - 1; p->type = PT_ESC; return PICOL_OK; } break; case '"': if (p->insidequote) { p->end = p->p - 1; p->type = PT_ESC; p->p++; p->len--; p->insidequote = 0; return PICOL_OK; } break; } p->p++; p->len--; } return PICOL_OK; /* unreached */ } int picolParseComment(struct picolParser *p) { while (p->len && *p->p != '\n') { p->p++; p->len--; } return PICOL_OK; } int picolGetToken(struct picolParser *p) { while (1) { if (!p->len) { if (p->type != PT_EOL && p->type != PT_EOF) p->type = PT_EOL; else p->type = PT_EOF; return PICOL_OK; } switch (*p->p) { case ' ': case '\t': case '\r': if (p->insidequote) return picolParseString(p); return picolParseSep(p); case '\n': case ';': if (p->insidequote) return picolParseString(p); return picolParseEol(p); case '[': return picolParseCommand(p); case '$': return picolParseVar(p); case '#': if (p->type == PT_EOL) { picolParseComment(p); continue; } return picolParseString(p); default: return picolParseString(p); } } return PICOL_OK; /* unreached */ } void picolInitInterp(struct picolInterp *i) { i->level = 0; i->callframe = malloc(sizeof(struct picolCallFrame)); i->callframe->vars = NULL; i->callframe->parent = NULL; i->commands = NULL; i->result = strdup(""); } void picolSetResult(struct picolInterp *i, char *s) { free(i->result); i->result = strdup(s); } struct picolVar *picolGetVar(struct picolInterp *i, char *name) { struct picolVar *v = i->callframe->vars; while (v) { if (strcmp(v->name, name) == 0) return v; v = v->next; } return NULL; } int picolSetVar(struct picolInterp *i, char *name, char *val) { struct picolVar *v = picolGetVar(i, name); if (v) { free(v->val); v->val = strdup(val); } else { v = malloc(sizeof(*v)); v->name = strdup(name); v->val = strdup(val); v->next = i->callframe->vars; i->callframe->vars = v; } return PICOL_OK; } struct picolCmd *picolGetCommand(struct picolInterp *i, char *name) { struct picolCmd *c = i->commands; while (c) { if (strcmp(c->name, name) == 0) return c; c = c->next; } return NULL; } int picolRegisterCommand(struct picolInterp *i, char *name, picolCmdFunc f, void *privdata) { struct picolCmd *c = picolGetCommand(i, name); char errbuf[1024]; if (c) { snprintf(errbuf, 1024, "Command '%s' already defined", name); picolSetResult(i, errbuf); return PICOL_ERR; } c = malloc(sizeof(*c)); c->name = strdup(name); c->func = f; c->privdata = privdata; c->next = i->commands; i->commands = c; return PICOL_OK; } /* EVAL! */ int picolEval(struct picolInterp *i, char *t) { struct picolParser p; int argc = 0, j; char **argv = NULL; char errbuf[1024]; int retcode = PICOL_OK; picolSetResult(i, ""); picolInitParser(&p, t); while (1) { char *t; int tlen; int prevtype = p.type; picolGetToken(&p); if (p.type == PT_EOF) break; tlen = p.end - p.start + 1; if (tlen < 0) tlen = 0; t = malloc(tlen + 1); memcpy(t, p.start, tlen); t[tlen] = '\0'; if (p.type == PT_VAR) { struct picolVar *v = picolGetVar(i, t); if (!v) { snprintf(errbuf, 1024, "No such variable '%s'", t); free(t); picolSetResult(i, errbuf); retcode = PICOL_ERR; goto err; } free(t); t = strdup(v->val); } else if (p.type == PT_CMD) { retcode = picolEval(i, t); free(t); if (retcode != PICOL_OK) goto err; t = strdup(i->result); } else if (p.type == PT_ESC) { /* XXX: escape handling missing! */ } else if (p.type == PT_SEP) { prevtype = p.type; free(t); continue; } /* We have a complete command + args. Call it! */ if (p.type == PT_EOL) { struct picolCmd *c; free(t); prevtype = p.type; if (argc) { if ((c = picolGetCommand(i, argv[0])) == NULL) { snprintf(errbuf, 1024, "No such command '%s'", argv[0]); picolSetResult(i, errbuf); retcode = PICOL_ERR; goto err; } retcode = c->func(i, argc, argv, c->privdata); if (retcode != PICOL_OK) goto err; } /* Prepare for the next command */ for (j = 0; j < argc; j++) free(argv[j]); free(argv); argv = NULL; argc = 0; continue; } /* We have a new token, append to the previous or as new arg? */ if (prevtype == PT_SEP || prevtype == PT_EOL) { argv = realloc(argv, sizeof(char *) * (argc + 1)); argv[argc] = t; argc++; } else { /* Interpolation */ int oldlen = strlen(argv[argc - 1]), tlen = strlen(t); argv[argc - 1] = realloc(argv[argc - 1], oldlen + tlen + 1); memcpy(argv[argc - 1] + oldlen, t, tlen); argv[argc - 1][oldlen + tlen] = '\0'; free(t); } prevtype = p.type; } err: for (j = 0; j < argc; j++) free(argv[j]); free(argv); return retcode; } /* ACTUAL COMMANDS! */ int picolArityErr(struct picolInterp *i, char *name) { char buf[1024]; snprintf(buf, 1024, "Wrong number of args for %s", name); picolSetResult(i, buf); return PICOL_ERR; } int picolCommandMath(struct picolInterp *i, int argc, char **argv, void *pd) { char buf[64]; int a, b, c; if (argc != 3) return picolArityErr(i, argv[0]); a = atoi(argv[1]); b = atoi(argv[2]); if (argv[0][0] == '+') c = a + b; else if (argv[0][0] == '-') c = a - b; else if (argv[0][0] == '*') c = a * b; else if (argv[0][0] == '/') c = a / b; else if (argv[0][0] == '>' && argv[0][1] == '\0') c = a > b; else if (argv[0][0] == '>' && argv[0][1] == '=') c = a >= b; else if (argv[0][0] == '<' && argv[0][1] == '\0') c = a < b; else if (argv[0][0] == '<' && argv[0][1] == '=') c = a <= b; else if (argv[0][0] == '=' && argv[0][1] == '=') c = a == b; else if (argv[0][0] == '!' && argv[0][1] == '=') c = a != b; else c = 0; /* I hate warnings */ snprintf(buf, 64, "%d", c); picolSetResult(i, buf); return PICOL_OK; } int picolCommandSet(struct picolInterp *i, int argc, char **argv, void *pd) { if (argc != 3) return picolArityErr(i, argv[0]); picolSetVar(i, argv[1], argv[2]); picolSetResult(i, argv[2]); return PICOL_OK; } int picolCommandPuts(struct picolInterp *i, int argc, char **argv, void *pd) { if (argc != 2) return picolArityErr(i, argv[0]); printf("%s\n", argv[1]); return PICOL_OK; } int picolCommandIf(struct picolInterp *i, int argc, char **argv, void *pd) { int retcode; if (argc != 3 && argc != 5) return picolArityErr(i, argv[0]); if ((retcode = picolEval(i, argv[1])) != PICOL_OK) return retcode; if (atoi(i->result)) return picolEval(i, argv[2]); else if (argc == 5) return picolEval(i, argv[4]); return PICOL_OK; } int picolCommandWhile(struct picolInterp *i, int argc, char **argv, void *pd) { if (argc != 3) return picolArityErr(i, argv[0]); while (1) { int retcode = picolEval(i, argv[1]); if (retcode != PICOL_OK) return retcode; if (atoi(i->result)) { if ((retcode = picolEval(i, argv[2])) == PICOL_CONTINUE) continue; else if (retcode == PICOL_OK) continue; else if (retcode == PICOL_BREAK) return PICOL_OK; else return retcode; } else { return PICOL_OK; } } } int picolCommandRetCodes(struct picolInterp *i, int argc, char **argv, void *pd) { if (argc != 1) return picolArityErr(i, argv[0]); if (strcmp(argv[0], "break") == 0) return PICOL_BREAK; else if (strcmp(argv[0], "continue") == 0) return PICOL_CONTINUE; return PICOL_OK; } void picolDropCallFrame(struct picolInterp *i) { struct picolCallFrame *cf = i->callframe; struct picolVar *v = cf->vars, *t; while (v) { t = v->next; free(v->name); free(v->val); free(v); v = t; } i->callframe = cf->parent; free(cf); } int picolCommandCallProc(struct picolInterp *i, int argc, char **argv, void *pd) { char **x = pd, *alist = x[0], *body = x[1], *p = strdup(alist), *tofree; struct picolCallFrame *cf = malloc(sizeof(*cf)); int arity = 0, done = 0, errcode = PICOL_OK; char errbuf[1024]; cf->vars = NULL; cf->parent = i->callframe; i->callframe = cf; tofree = p; while (1) { char *start = p; while (*p != ' ' && *p != '\0') p++; if (*p != '\0' && p == start) { p++; continue; } if (p == start) break; if (*p == '\0') done = 1; else *p = '\0'; if (++arity > argc - 1) goto arityerr; picolSetVar(i, start, argv[arity]); p++; if (done) break; } free(tofree); if (arity != argc - 1) goto arityerr; errcode = picolEval(i, body); if (errcode == PICOL_RETURN) errcode = PICOL_OK; picolDropCallFrame(i); /* remove the called proc callframe */ return errcode; arityerr: snprintf(errbuf, 1024, "Proc '%s' called with wrong arg num", argv[0]); picolSetResult(i, errbuf); picolDropCallFrame(i); /* remove the called proc callframe */ return PICOL_ERR; } int picolCommandProc(struct picolInterp *i, int argc, char **argv, void *pd) { char **procdata = malloc(sizeof(char *) * 2); if (argc != 4) return picolArityErr(i, argv[0]); procdata[0] = strdup(argv[2]); /* arguments list */ procdata[1] = strdup(argv[3]); /* procedure body */ return picolRegisterCommand(i, argv[1], picolCommandCallProc, procdata); } int picolCommandReturn(struct picolInterp *i, int argc, char **argv, void *pd) { if (argc != 1 && argc != 2) return picolArityErr(i, argv[0]); picolSetResult(i, (argc == 2) ? argv[1] : ""); return PICOL_RETURN; } void picolRegisterCoreCommands(struct picolInterp *i) { int j; char *name[] = {"+", "-", "*", "/", ">", ">=", "<", "<=", "==", "!="}; for (j = 0; j < (int)(sizeof(name) / sizeof(char *)); j++) picolRegisterCommand(i, name[j], picolCommandMath, NULL); picolRegisterCommand(i, "set", picolCommandSet, NULL); picolRegisterCommand(i, "puts", picolCommandPuts, NULL); picolRegisterCommand(i, "if", picolCommandIf, NULL); picolRegisterCommand(i, "while", picolCommandWhile, NULL); picolRegisterCommand(i, "break", picolCommandRetCodes, NULL); picolRegisterCommand(i, "continue", picolCommandRetCodes, NULL); picolRegisterCommand(i, "proc", picolCommandProc, NULL); picolRegisterCommand(i, "return", picolCommandReturn, NULL); } int main(int argc, char **argv) { struct picolInterp interp; picolInitInterp(&interp); picolRegisterCoreCommands(&interp); if (argc == 1) { while (1) { char clibuf[1024]; int retcode; printf("picol> "); fflush(stdout); if (fgets(clibuf, 1024, stdin) == NULL) return 0; retcode = picolEval(&interp, clibuf); if (interp.result[0] != '\0') printf("[%d] %s\n", retcode, interp.result); } } else if (argc == 2) { char buf[1024 * 16]; FILE *fp = fopen(argv[1], "r"); if (!fp) { perror("open"); exit(1); } buf[fread(buf, 1, 1024 * 16, fp)] = '\0'; fclose(fp); if (picolEval(&interp, buf) != PICOL_OK) printf("%s\n", interp.result); } return 0; }
17,542
652
jart/cosmopolitan
false
cosmopolitan/examples/getrandom.c
#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 "ape/sections.internal.h" #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/x86feature.h" #include "libc/nt/runtime.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/stdio/xorshift.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/grnd.h" #include "libc/sysv/consts/sig.h" #include "libc/testlib/hyperion.h" #include "third_party/getopt/getopt.h" #define B 4096 bool isdone; bool isbinary; unsigned long count = -1; uint64_t bcast(uint64_t f(void)) { unsigned i; uint64_t x; for (x = i = 0; i < 8; ++i) { x <<= 8; x |= f() & 255; } return x; } uint64_t randv6(void) { static int16_t gorp; gorp = (gorp + 625) & 077777; return gorp; } uint64_t randv7(void) { static uint32_t randx = 1; return ((randx = randx * 1103515245 + 12345) >> 16) & 077777; } uint64_t zero(void) { return 0; } uint64_t inc(void) { static uint64_t x; return x++; } uint64_t unixv6(void) { return bcast(randv6); } uint64_t unixv7(void) { return bcast(randv7); } uint64_t ape(void) { static int i; if ((i += 8) > _end - __executable_start) i = 8; return READ64LE(__executable_start + i); } uint64_t moby(void) { static int i; if ((i += 8) > kMobySize) i = 8; return READ64LE(kMoby + i); } uint64_t knuth(void) { uint64_t a, b; static uint64_t x = 1; x *= 6364136223846793005; x += 1442695040888963407; a = x >> 32; x *= 6364136223846793005; x += 1442695040888963407; b = x >> 32; return a | b << 32; } uint64_t rngset64(void) { static unsigned i; static uint64_t s; if (!i) { s = _rand64(); i = (s + 1) & (511); } return MarsagliaXorshift64(&s); } uint64_t xorshift64(void) { static uint64_t s = kMarsagliaXorshift64Seed; return MarsagliaXorshift64(&s); } uint64_t xorshift32(void) { static uint32_t s = kMarsagliaXorshift32Seed; uint64_t a = MarsagliaXorshift32(&s); uint64_t b = MarsagliaXorshift32(&s); return (uint64_t)a << 32 | b; } uint64_t libc(void) { uint64_t x; CHECK_EQ(8, getrandom(&x, 8, 0)); return x; } uint64_t GetRandom(void) { uint64_t x; CHECK_EQ(8, getrandom(&x, 8, 0)); return x; } uint32_t python(void) { #define K 0 // 624 /* wut */ #define N 624 #define M 397 static int index; static char once; static uint32_t mt[N]; static const uint32_t mag01[2] = {0, 0x9908b0dfu}; uint32_t y; int kk; if (!once) { char *sp; ssize_t rc; uint32_t i, j, k, s[K]; mt[0] = 19650218; for (i = 1; i < N; i++) { mt[i] = (1812433253u * (mt[i - 1] ^ (mt[i - 1] >> 30)) + i); } if (K) { for (sp = (char *)s, i = 0; i < sizeof(s); i += rc) { if ((rc = getrandom(sp + i, sizeof(s) - i, 0)) == -1) { if (errno != EINTR) abort(); } } for (i = 1, j = 0, k = MAX(N, K); k; k--) { mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525u)) + s[j] + j; if (++i >= N) mt[0] = mt[N - 1], i = 1; if (++j >= K) j = 0; } for (k = N - 1; k; k--) { mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941u)) - i; if (++i >= N) mt[0] = mt[N - 1], i = 1; } mt[0] = 0x80000000; explicit_bzero(s, sizeof(s)); } once = 1; } if (index >= N) { for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & 0x80000000u) | (mt[kk + 1] & 0x7fffffff); mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & 0x80000000u) | (mt[kk + 1] & 0x7fffffff); mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 1]; } y = (mt[N - 1] & 0x80000000u) | (mt[0] & 0x7fffffffu); mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 1]; index = 0; } y = mt[index++]; y ^= y >> 11; y ^= (y << 7) & 0x9d2c5680u; y ^= (y << 15) & 0xefc60000u; y ^= y >> 18; return y; #undef M #undef N #undef K } uint64_t pythonx2(void) { uint64_t x = python(); x <<= 32; x |= python(); return x; } const struct Function { const char *s; uint64_t (*f)(void); } kFunctions[] = { {"ape", ape}, // {"getrandom", GetRandom}, // {"inc", inc}, // {"knuth", knuth}, // {"lemur64", lemur64}, // {"libc", libc}, // {"moby", moby}, // {"mt19937", _mt19937}, // {"python", pythonx2}, // {"rand64", _rand64}, // {"rdrand", rdrand}, // {"rdrnd", rdrand}, // {"rdseed", rdseed}, // {"rngset64", rngset64}, // {"unixv6", unixv6}, // {"unixv7", unixv7}, // {"vigna", vigna}, // {"xorshift32", xorshift32}, // {"xorshift64", xorshift64}, // {"zero", zero}, // }; void OnInt(int sig) { isdone = true; } wontreturn void PrintUsage(FILE *f, int rc) { fprintf(f, "Usage: %s [-b] [-n NUM] [FUNC]\n", program_invocation_name); exit(rc); } int main(int argc, char *argv[]) { char *p; int i, opt; ssize_t rc; uint64_t x; static char buf[B]; uint64_t (*f)(void); while ((opt = getopt(argc, argv, "hbc:n:")) != -1) { switch (opt) { case 'b': isbinary = true; break; case 'c': case 'n': count = sizetol(optarg, 1024); break; case 'h': PrintUsage(stdout, EXIT_SUCCESS); default: PrintUsage(stderr, EX_USAGE); } } if (optind == argc) { f = libc; } else { for (f = 0, i = 0; i < ARRAYLEN(kFunctions); ++i) { if (!strcasecmp(argv[optind], kFunctions[i].s)) { f = kFunctions[i].f; break; } } if (!f) { fprintf(stderr, "unknown function: %`'s\n", argv[optind]); fprintf(stderr, "try: "); for (i = 0; i < ARRAYLEN(kFunctions); ++i) { if (i) fprintf(stderr, ", "); fprintf(stderr, "%s", kFunctions[i].s); } fprintf(stderr, "\n"); return 1; } } signal(SIGINT, OnInt); signal(SIGPIPE, SIG_IGN); if (!isbinary) { for (; count && !isdone && !feof(stdout); --count) { printf("0x%016lx\n", f()); } fflush(stdout); return ferror(stdout) ? 1 : 0; } while (count && !isdone) { if (count >= B) { for (i = 0; i < B / 8; ++i) { x = f(); p = buf + i * 8; WRITE64LE(p, x); } for (i = 0; i < B; i += rc) { rc = write(1, buf + i, B - i); if (rc == -1 && errno == EPIPE) exit(1); if (rc == -1) perror("write"), exit(1); } } else { x = f(); rc = write(1, &x, MIN(8, count)); } if (!rc) break; if (rc == -1 && errno == EPIPE) exit(1); if (rc == -1) perror("write"), exit(1); count -= rc; } return 0; }
7,865
321
jart/cosmopolitan
false
cosmopolitan/examples/date.c
#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/mem/gc.h" #include "libc/stdio/stdio.h" #include "libc/x/xiso8601.h" /** * @fileoverview ISO-8601 international high-precision timestamp printer. */ int main(int argc, char *argv[]) { puts(_gc(xiso8601ts(NULL))); return 0; }
1,032
22
jart/cosmopolitan
false
cosmopolitan/examples/walk.c
#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/errno.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/s.h" #include "third_party/musl/ftw.h" /** * @fileoverview Directory walker example. * Copied from IEEE Std 1003.1-2017 */ static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { printf("%-3s %2d %7jd %-40s %d %s\n", (tflag == FTW_D) ? "d" : (tflag == FTW_DNR) ? "dnr" : (tflag == FTW_DP) ? "dp" : (tflag == FTW_F) ? (S_ISBLK(sb->st_mode) ? "f b" : S_ISCHR(sb->st_mode) ? "f c" : S_ISFIFO(sb->st_mode) ? "f p" : S_ISREG(sb->st_mode) ? "f r" : S_ISSOCK(sb->st_mode) ? "f s" : "f ?") : (tflag == FTW_NS) ? "ns" : (tflag == FTW_SL) ? "sl" : (tflag == FTW_SLN) ? "sln" : "?", ftwbuf->level, (intmax_t)sb->st_size, fpath, ftwbuf->base, fpath + ftwbuf->base); return 0; /* To tell nftw() to continue */ } int main(int argc, char *argv[]) { int flags = 0; const char *dir; if (argc > 2 && strchr(argv[2], 'd') != NULL) flags |= FTW_DEPTH; if (argc > 2 && strchr(argv[2], 'p') != NULL) flags |= FTW_PHYS; dir = argc < 2 ? "." : argv[1]; if (nftw(dir, display_info, 20, flags) == -1) { fprintf(stderr, "nftw() failed: %s: %s\n", strerror(errno), dir); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
2,464
56
jart/cosmopolitan
false
cosmopolitan/examples/cplusplus-stl.cc
/*-*-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/stdio/stdio.h" #include "third_party/libcxx/map" #include "third_party/libcxx/string" int main(int argc, char *argv[]) { printf("std::map + std::string example\n"); std::map<std::string, int> m{ {"CPU", 10}, {"GPU", 15}, {"RAM", 20}, }; printf("m[\"CPU\"] is %d\n", m["CPU"]); printf("m[\"RAM\"] is %d\n", m["RAM"]); printf("m[\"GPU\"] is %d\n", m["GPU"]); printf("setting cpu to 25\n"); m["CPU"] = 25; // update an existing value printf("m[\"CPU\"] is %d\n", m["CPU"]); printf("m[\"RAM\"] is %d\n", m["RAM"]); printf("m[\"GPU\"] is %d\n", m["GPU"]); }
2,446
39
jart/cosmopolitan
false
cosmopolitan/examples/hiredis.c
#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/runtime/runtime.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "third_party/hiredis/hiredis.h" /** * @fileoverview Demo of using hiredis to connect to a Redis server */ int main(int argc, char *argv[]) { if (argc < 3 || argc > 5) { fprintf(stderr, "Usage: %s HOST PORT [KEY] [VALUE]\n", argv[0]); exit(1); } bool setValue = (argc == 5), getValue = (argc == 4); redisContext *c = redisConnect(argv[1], atoi(argv[2])); if (c == NULL || c->err) { if (c) { fprintf(stderr, "Connection error: %s\n", c->errstr); redisFree(c); } else { fputs("Failed to allocate redis context\n", stderr); } exit(1); } redisReply *reply; if (!setValue && !getValue) { reply = redisCommand(c, "PING"); printf("PING: %s\n", reply->str); } else if (setValue) { reply = redisCommand(c, "SET %s %s", argv[3], argv[4]); printf("SET: %s\n", reply->str); } else { reply = redisCommand(c, "GET %s", argv[3]); printf("GET: %s\n", reply->str); } freeReplyObject(reply); redisFree(c); return 0; }
1,937
56
jart/cosmopolitan
false
cosmopolitan/examples/generalized-automatic-datastructure-printing.c
#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/log/gdb.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" /** * @fileovierview gdbexec(s) demo * It basically launches an ephemeral `gdb -p $PID -ex "$s"`. */ int i; int M[8][8] = { {772549, 921569, 407843, 352941, 717647, 78431, 666667, 627451}, {321569, 419608, 227451, 396078, 223529, 882353, 952941, 937255}, {15686, 545098, 31373, 7843, 15686, 298039, 976471, 352941}, {70588, 858824, 415686, 184314, 25098, 5098, 141176, 47059}, {141176, 541176, 658824, 227451, 490196, 301961, 937255, 678431}, {188235, 823529, 858824, 87451, 545098, 611765, 188235, 576471}, {580392, 913725, 996078, 592157, 7451, 176471, 862745, 784314}, {278431, 945098, 843137, 439216, 878431, 529412, 262745, 43137}, }; int main(int argc, char *argv[]) { int y, x; for (i = 0;; ++i) { for (y = 0; y < 8; ++y) { for (x = 0; x < 8; ++x) { if (!(M[y][x] % 2)) { M[y][x] /= 2; } else { M[y][x] *= 3; M[y][x] += 1; } } } if (rand() % 10000 == 0) { gdbexec("print i"); gdbexec("print M"); break; } } printf("quitting\n"); return 0; }
1,965
53
jart/cosmopolitan
false
cosmopolitan/examples/auto-memory-safety-crash.c
#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/intrin/bits.h" #include "libc/dce.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" /** * ASAN static memory safety crash example. * * make -j8 MODE=dbg o/dbg/examples/auto-memory-safety-crash.com * o/dbg/examples/auto-memory-safety-crash.com * * You should see: * * global redzone 1-byte store at 0x42700d shadow 0x8007ce01 * ./o/dbg/examples/auto-memory-safety-crash.com * x * ........................................GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG * |0 |0 |0 |0 |5 |-18 |-18 |-18 |-18 *  f.☼▼ä     f.☼▼ä     f☼▼D  hello                                                 * 000000400000-000000427000 .text * 000000427000-000000429000 .data ←address * 00007fff0000-00008000ffff * 000080070000-00008008ffff ←shadow * 0e007fff0000-0e008000ffff * 100047d20000-100047d3ffff * 6ffffffe0000-6fffffffffff * the memory in question belongs to the symbols * buffer [0x427000,0x42700c] size 13 * the crash was caused by * 0x00000000004046f3: __die at libc/log/die.c:40 * 0x0000000000404aed: __asan_report_store at libc/intrin/asan.c:1183 * 0x0000000000402552: main at examples/auto-memory-safety-crash.c:27 * 0x000000000040268d: cosmo at libc/runtime/cosmo.S:64 * 0x00000000004021ae: _start at libc/crt/crt.S:77 * * @see libc/intrin/asancodes.h for meaning of G, etc. and negative numbers * @see libc/nexgen32e/kcp437.S for meaning of symbols */ char buffer[13] = "hello"; int main(int argc, char *argv[]) { if (!IsAsan()) { printf("this example is intended for MODE=asan or MODE=dbg\n"); exit(1); } ShowCrashReports(); /* not needed but yoinks appropriate symbols */ int i = 13; asm("" : "+r"(i)); /* prevent compiler being smart */ buffer[i] = 1; return 0; }
2,808
63
jart/cosmopolitan
false
cosmopolitan/examples/nanosleep_test.c
#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/assert.h" #include "libc/calls/struct/timespec.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/clock.h" /** * @fileoverview shows how accurate clock_nanosleep() is */ int main(int argc, char *argv[]) { long i, ns; struct timespec x, y, w; timespec_sleep(timespec_fromnanos(0)); // warmup printf("\nrelative sleep\n"); for (i = 0; i < 28; ++i) { ns = 1l << i; x = timespec_real(); timespec_sleep(timespec_fromnanos(ns)); y = timespec_real(); printf("%,11ld ns sleep took %,ld ns\n", ns, timespec_tonanos(timespec_sub(y, x))); } printf("\nabsolute sleep\n"); for (i = 0; i < 28; ++i) { ns = 1l << i; x = timespec_real(); timespec_sleep_until(timespec_add(x, timespec_fromnanos(ns))); y = timespec_real(); printf("%,11ld ns sleep took %,ld ns\n", ns, timespec_tonanos(timespec_sub(y, x))); } }
1,689
44
jart/cosmopolitan
false
cosmopolitan/examples/cplusplus.cc
/*-*-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/intrin/safemacros.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" class Log { public: Log(); ~Log(); int *x(); private: int *x_; }; Log::Log() { x_ = new int[64]; } Log::~Log() { delete x_; } int *Log::x() { return x_; } class Log g_log; int main(int argc, char *argv[]) { int *x = new int[64]; memset(x, 0, 64 * sizeof(int)); for (int i = 0; i < min(64, argc); ++i) g_log.x()[i] += argc; printf("%p %d %d %d\n", (void *)(intptr_t)g_log.x(), g_log.x()[0], g_log.x()[0], g_log.x()[0]); delete[] x; return 0; }
2,422
54
jart/cosmopolitan
false
cosmopolitan/examples/examples.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += EXAMPLES ifeq ($(MODE),tiny) EXAMPLES_BOOTLOADER = $(CRT) $(APE) else EXAMPLES_BOOTLOADER = $(CRT) $(APE_NO_MODIFY_SELF) endif EXAMPLES_FILES := $(wildcard examples/*) EXAMPLES_MAINS_S = $(filter %.S,$(EXAMPLES_FILES)) EXAMPLES_MAINS_C = $(filter %.c,$(EXAMPLES_FILES)) EXAMPLES_MAINS_CC = $(filter %.cc,$(EXAMPLES_FILES)) EXAMPLES_SRCS = \ $(EXAMPLES_MAINS_S) \ $(EXAMPLES_MAINS_C) \ $(EXAMPLES_MAINS_CC) EXAMPLES_MAINS = \ $(EXAMPLES_MAINS_S) \ $(EXAMPLES_MAINS_C) \ $(EXAMPLES_MAINS_CC) EXAMPLES_OBJS = \ $(EXAMPLES_MAINS_S:%.S=o/$(MODE)/%.o) \ $(EXAMPLES_MAINS_C:%.c=o/$(MODE)/%.o) \ $(EXAMPLES_MAINS_CC:%.cc=o/$(MODE)/%.o) EXAMPLES_COMS = \ $(EXAMPLES_MAINS_S:%.S=o/$(MODE)/%.com) \ $(EXAMPLES_MAINS_C:%.c=o/$(MODE)/%.com) \ $(EXAMPLES_MAINS_CC:%.cc=o/$(MODE)/%.com) EXAMPLES_BINS = \ $(EXAMPLES_COMS) \ $(EXAMPLES_COMS:%=%.dbg) EXAMPLES_DIRECTDEPS = \ DSP_CORE \ DSP_SCALE \ DSP_TTY \ LIBC_CALLS \ LIBC_DNS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_ADVAPI32 \ LIBC_NT_IPHLPAPI \ LIBC_NT_KERNEL32 \ LIBC_NT_NTDLL \ LIBC_NT_USER32 \ LIBC_NT_WS2_32 \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TESTLIB \ LIBC_THREAD \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_VGA \ LIBC_X \ LIBC_ZIPOS \ NET_HTTP \ NET_HTTPS \ THIRD_PARTY_AWK \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_DLMALLOC \ THIRD_PARTY_DOUBLECONVERSION \ THIRD_PARTY_GDTOA \ THIRD_PARTY_GETOPT \ THIRD_PARTY_LIBCXX \ THIRD_PARTY_LINENOISE \ THIRD_PARTY_LUA \ THIRD_PARTY_HIREDIS \ THIRD_PARTY_MBEDTLS \ THIRD_PARTY_MUSL \ THIRD_PARTY_NSYNC \ THIRD_PARTY_NSYNC_MEM \ THIRD_PARTY_QUICKJS \ THIRD_PARTY_SED \ THIRD_PARTY_STB \ THIRD_PARTY_TR \ THIRD_PARTY_VQSORT \ THIRD_PARTY_XED \ THIRD_PARTY_ZLIB \ TOOL_BUILD_LIB \ TOOL_VIZ_LIB EXAMPLES_DEPS := \ $(call uniq,$(foreach x,$(EXAMPLES_DIRECTDEPS),$($(x)))) o/$(MODE)/examples/examples.pkg: \ $(EXAMPLES_OBJS) \ $(foreach x,$(EXAMPLES_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/examples/unbourne.o: private \ OVERRIDE_CPPFLAGS += \ -DSTACK_FRAME_UNLIMITED \ -fpie o/$(MODE)/examples/%.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/%.o \ o/$(MODE)/examples/examples.pkg \ $(EXAMPLES_BOOTLOADER) @$(APELINK) o/$(MODE)/examples/nomodifyself.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/nomodifyself.o \ o/$(MODE)/examples/examples.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/examples/hellolua.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/hellolua.o \ o/$(MODE)/examples/hellolua.lua.zip.o \ o/$(MODE)/examples/examples.pkg \ $(EXAMPLES_BOOTLOADER) @$(APELINK) o/$(MODE)/examples/ispell.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/ispell.o \ o/$(MODE)/usr/share/dict/words.zip.o \ o/$(MODE)/examples/examples.pkg \ $(EXAMPLES_BOOTLOADER) @$(APELINK) o/$(MODE)/examples/nesemu1.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/nesemu1.o \ o/$(MODE)/usr/share/rom/mario.nes.zip.o \ o/$(MODE)/usr/share/rom/zelda.nes.zip.o \ o/$(MODE)/usr/share/rom/tetris.nes.zip.o \ o/$(MODE)/examples/examples.pkg \ $(EXAMPLES_BOOTLOADER) @$(APELINK) # # force symtab.com to be a zip file, by pulling a zip asset into linkage # # we wouldn't need to do this if we depended on functions like localtime # o/$(MODE)/examples/symtab.com.dbg: \ # $(EXAMPLES_DEPS) \ # o/$(MODE)/examples/symtab.o \ # o/$(MODE)/examples/symtab.c.zip.o \ # o/$(MODE)/examples/examples.pkg \ # $(EXAMPLES_BOOTLOADER) # @$(APELINK) # modify .com so it can read the symbol table without needing the .com.dbg file o/$(MODE)/examples/symtab.com: \ o/$(MODE)/examples/symtab.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) o/$(MODE)/examples/picol.o: private \ OVERRIDE_CPPFLAGS += \ -DSTACK_FRAME_UNLIMITED o/$(MODE)/examples/picol.com.dbg: \ $(EXAMPLES_DEPS) \ o/$(MODE)/examples/picol.o \ o/$(MODE)/examples/examples.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/examples/nesemu1.o: private QUOTA += -M512m o/$(MODE)/usr/share/dict/words.zip.o: private ZIPOBJ_FLAGS += -C2 $(EXAMPLES_OBJS): examples/examples.mk o/$(MODE)/usr/share/dict/words: \ usr/share/dict/words.gz @$(MKDIR) $(@D) @$(GZIP) $(ZFLAGS) -cd <$< >$@ ################################################################################ .PHONY: o/$(MODE)/examples o/$(MODE)/examples: \ o/$(MODE)/examples/package \ o/$(MODE)/examples/pylife \ o/$(MODE)/examples/pyapp \ $(EXAMPLES_BINS)
5,518
201
jart/cosmopolitan
false
cosmopolitan/examples/uname.c
#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/utsname.h" #include "libc/stdio/stdio.h" int main(int argc, char *argv[]) { struct utsname names; if (uname(&names)) return 1; printf("%-10s %`'s\n", "sysname", names.sysname); printf("%-10s %`'s\n", "release", names.release); printf("%-10s %`'s\n", "version", names.version); printf("%-10s %`'s\n", "machine", names.machine); printf("%-10s %`'s\n", "nodename", names.nodename); printf("%-10s %`'s\n", "domainname", names.domainname); return 0; }
1,308
25
jart/cosmopolitan
false
cosmopolitan/examples/nc.c
#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/dns/dns.h" #include "libc/fmt/conv.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/linger.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/shut.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "third_party/getopt/getopt.h" /** * @fileoverview netcat clone * * Implemented because BusyBox's netcat doesn't detect remote close and * lingers in the CLOSE_WAIT wait possibly due to file descriptor leaks * * Here's an example usage: * * make -j8 o//examples/nc.com * printf 'GET /\r\nHost: justine.lol\r\n\r\n' | o//examples/nc.com * justine.lol 80 * * Once upon time we called this command "telnet" */ int main(int argc, char *argv[]) { ssize_t rc; size_t i, got; char buf[1500]; bool halfclose = true; const char *host, *port; int opt, err, toto, sock; struct addrinfo *ai = NULL; struct linger linger = {true, 1}; struct pollfd fds[2] = {{-1, POLLIN}, {-1, POLLIN}}; struct addrinfo hint = {AI_NUMERICSERV, AF_INET, SOCK_STREAM, IPPROTO_TCP}; while ((opt = getopt(argc, argv, "hH")) != -1) { switch (opt) { case 'H': halfclose = false; break; case 'h': fputs("Usage: ", stdout); fputs(argv[0], stdout); fputs(" [-hH] IP PORT\n", stdout); exit(0); default: fprintf(stderr, "bad option %d\n", opt); exit(1); } } if (argc - optind != 2) { fputs("missing args\n", stderr); exit(1); } host = argv[optind + 0]; port = argv[optind + 1]; switch ((rc = getaddrinfo(host, port, &hint, &ai))) { case EAI_SUCCESS: break; case EAI_SYSTEM: perror("getaddrinfo"); exit(1); default: fputs("EAI_", stderr); fputs(gai_strerror(rc), stderr); fputs("\n", stderr); exit(1); } if ((sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { perror("socket"); exit(1); } if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) == -1) { perror("setsockopt(SO_LINGER)"); exit(1); } if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) { perror("connect"); exit(1); } fds[0].fd = 0; fds[1].fd = sock; for (;;) { fds[0].revents = 0; fds[1].revents = 0; if (poll(fds, ARRAYLEN(fds), -1) == -1) { perror("poll"); exit(1); } if (fds[0].revents & (POLLIN | POLLERR | POLLHUP)) { if ((rc = read(0, buf, 1400)) == -1) { perror("read(stdin)"); exit(1); } if (!(got = rc)) { if (halfclose) { shutdown(sock, SHUT_WR); } fds[0].fd = -1; } for (i = 0; i < got; i += rc) { if ((rc = write(sock, buf + i, got - i)) == -1) { perror("write(sock)"); exit(1); } } } if (fds[1].revents & (POLLIN | POLLERR | POLLHUP)) { if ((rc = read(sock, buf, 1500)) == -1) { perror("read(sock)"); exit(1); } if (!(got = rc)) { break; } for (i = 0; i < got; i += rc) { if ((rc = write(1, buf + i, got - i)) == -1) { perror("write(stdout)"); exit(1); } } } } if (close(sock) == -1) { perror("close"); exit(1); } freeaddrinfo(ai); return 0; }
4,430
161
jart/cosmopolitan
false
cosmopolitan/examples/hellolua.lua
print(string.format("2 + 3 = %g", NativeAdd(2, 3)))
52
2
jart/cosmopolitan
false
cosmopolitan/examples/stringbuffer.c
#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/fmt/fmt.h" #include "libc/log/check.h" #include "libc/mem/mem.h" #include "libc/stdio/append.h" #include "libc/str/str.h" /** * @fileoverview Fast Growable Strings Tutorial */ int main(int argc, char *argv[]) { char *b = 0; appendf(&b, "hello "); // guarantees nul terminator CHECK_EQ(6, strlen(b)); CHECK_EQ(6, appendz(b).i); appendf(&b, " world\n"); CHECK_EQ(13, strlen(b)); CHECK_EQ(13, appendz(b).i); appendd(&b, "\0", 1); // supports binary CHECK_EQ(13, strlen(b)); CHECK_EQ(14, appendz(b).i); appendf(&b, "%d arg%s\n", argc, argc == 1 ? "" : "s"); appendf(&b, "%s\n", "have a nice day"); write(1, b, appendz(b).i); free(b); return 0; }
1,507
38
jart/cosmopolitan
false
cosmopolitan/examples/portscan.c
#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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/timeval.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/mem/alloca.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/sockaddr.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/so.h" #include "libc/sysv/consts/sock.h" #include "libc/sysv/consts/sol.h" #include "net/http/ip.h" /** * @fileoverview fast local network port scanner, e.g. * * make -j8 o//examples/portscan.com * o//examples/portscan.com 10.10.10.0/24 22 */ const char *FormatIp(char buf[16], uint32_t ip) { snprintf(buf, 16, "%hhu.%hhu.%hhu.%hhu", ip >> 24, ip >> 16, ip >> 8, ip); return buf; } #define FormatIp(x) FormatIp(alloca(16), x) int main(int argc, char *argv[]) { int port; struct Cidr in; uint32_t netmask; const char *status; struct timeval timeout; uint32_t network_address; uint32_t last_host_address; uint32_t first_host_address; if (argc != 3) { PrintUsage: fprintf(stderr, "usage: %s IP/CIDR PORT\n" "example: %s 192.168.0.0/24 22\n", argv[0], argv[0]); return 1; } in = ParseCidr(argv[1], -1); if (in.addr == -1) { fprintf(stderr, "error: bad ip/cidr\n"); goto PrintUsage; } port = atoi(argv[2]); if (!(1 <= port && port <= 65535)) { fprintf(stderr, "error: bad port\n"); goto PrintUsage; } if (in.cidr > 30) { fprintf(stderr, "error: maximum supported cidr is 30\n"); goto PrintUsage; } if (in.cidr < 22) { fprintf(stderr, "error: minimum cidr support right now is 22\n"); goto PrintUsage; } netmask = -1u << (32 - in.cidr); network_address = in.addr & netmask; first_host_address = network_address + 1; last_host_address = (network_address | ~netmask) - 1; assert(last_host_address > first_host_address); assert(last_host_address - first_host_address < 1024); fprintf(stderr, "scanning %s through %s\n", FormatIp(first_host_address), FormatIp(last_host_address)); timeout = timeval_frommillis(100); for (int64_t ip = first_host_address; ip <= last_host_address; ++ip) { if (!fork()) { socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); setsockopt(3, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); setsockopt(3, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); if (!connect(3, (struct sockaddr *)&(struct sockaddr_in){ .sin_family = AF_INET, .sin_addr.s_addr = htonl(ip), .sin_port = htons(port), }, sizeof(struct sockaddr_in))) { status = "open"; } else if (errno == ECONNREFUSED) { status = "closed"; } else if (errno != EINPROGRESS) { status = _strerrno(errno); } else { status = 0; } if (status) { printf("%-15s %s\n", FormatIp(ip), status); } _Exit(0); } } for (;;) { if (wait(0) == -1 && errno == ECHILD) { break; } } }
4,011
128
jart/cosmopolitan
false
cosmopolitan/examples/clock.c
#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/struct/timespec.h" #include "libc/stdio/stdio.h" #include "libc/time/time.h" /** * @fileoverview clock() function demo */ int main(int argc, char *argv[]) { unsigned long i; volatile unsigned long x; struct timespec now, start, next, interval; printf("hammering the cpu...\n"); next = start = timespec_mono(); interval = timespec_frommillis(500); next = timespec_add(next, interval); for (;;) { for (i = 0;; ++i) { x *= 7; if (!(i % 256)) { now = timespec_mono(); if (timespec_cmp(now, next) >= 0) { break; } } } next = timespec_add(next, interval); printf("consumed %10g seconds monotonic time and %10g seconds cpu time\n", timespec_tonanos(timespec_sub(now, start)) / 1000000000., (double)clock() / CLOCKS_PER_SEC); } }
1,639
42
jart/cosmopolitan
false
cosmopolitan/examples/script.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright (c) 2010, 2012 David E. O'Brien │ │ Copyright (c) 1980, 1992, 1993 │ │ The Regents of the University of California. All rights reserved. │ │ │ │ Redistribution and use in source and binary forms, with or without │ │ modification, are permitted provided that the following conditions │ │ are met: │ │ 1. Redistributions of source code must retain the above copyright │ │ notice, this list of conditions and the following disclaimer. │ │ 2. Redistributions in binary form must reproduce the above copyright │ │ notice, this list of conditions and the following disclaimer in the │ │ documentation and/or other materials provided with the distribution. │ │ 3. Neither the name of the University nor the names of its contributors │ │ may be used to endorse or promote products derived from this software │ │ without specific prior written permission. │ │ │ │ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │ │ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │ │ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │ │ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │ │ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │ │ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │ │ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │ │ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │ │ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │ │ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │ │ SUCH DAMAGE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/timeval.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/termios.h" #include "libc/calls/weirdtypes.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/bswap.h" #include "libc/log/bsd.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/paths.h" #include "libc/runtime/runtime.h" #include "libc/sock/select.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/s.h" #include "libc/sysv/consts/termios.h" #include "libc/time/time.h" #include "third_party/getopt/getopt.h" // clang-format off /** * @fileoverview Terminal Screencast Recorder / Player, e.g. * * make o//examples/script.com * o//examples/script.com -r * # type stuff.. * # CTRL-D * o//examples/script.com -p typescript * * @note works on Linux, OpenBSD, NetBSD, FreeBSD, MacOS * @see https://asciinema.org/ */ asm(".ident\t\"\\n\\n\ FreeBSD Script (BSD-3 License)\\n\ Copyright (c) 2010, 2012 David E. O'Brien\\n\ Copyright (c) 1980, 1992, 1993\\n\ \tThe Regents of the University of California.\\n\ \tAll rights reserved.\""); asm(".include \"libc/disclaimer.inc\""); #define DEF_BUF 65536 struct stamp { uint64_t scr_len; /* amount of data */ uint64_t scr_sec; /* time it arrived in seconds... */ uint32_t scr_usec; /* ...and microseconds */ uint32_t scr_direction; /* 'i', 'o', etc (also indicates endianness) */ }; static FILE *fscript; static int master, slave; static int child; static const char *fname; static char *fmfname; static int qflg, ttyflg; static int usesleep, rawout, showexit; static struct termios tt; static void done(int) wontreturn; static void doshell(char **); static void finish(void); static void record(FILE *, char *, size_t, int); static void consume(FILE *, off_t, char *, int); static void playback(FILE *) wontreturn; static void usage(void); int main(int argc, char *argv[]) { int cc; struct termios rtt, stt; struct winsize win; struct timeval tv, *tvp; time_t tvec, start; static char obuf[BUFSIZ]; static char ibuf[BUFSIZ]; fd_set rfd; int aflg, Fflg, kflg, pflg, ch, k, n; int flushtime, readstdin; int fm_fd, fm_log; aflg = Fflg = kflg = pflg = 0; usesleep = 1; rawout = 0; flushtime = 30; fm_fd = -1; /* Shut up stupid "may be used uninitialized" GCC warning. (not needed w/clang) */ showexit = 0; while ((ch = getopt(argc, argv, "adeFfkpqrt:")) != -1) switch(ch) { case 'a': aflg = 1; break; case 'd': usesleep = 0; break; case 'e': /* Default behavior, accepted for linux compat */ break; case 'F': Fflg = 1; break; case 'k': kflg = 1; break; case 'p': pflg = 1; break; case 'q': qflg = 1; break; case 'r': rawout = 1; break; case 't': flushtime = atoi(optarg); if (flushtime < 0) err(1, "invalid flush time %d", flushtime); break; case '?': default: usage(); } argc -= optind; argv += optind; if (argc > 0) { fname = argv[0]; argv++; argc--; } else fname = "typescript"; if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL) err(1, "%s", fname); if (pflg) playback(fscript); if (tcgetattr(STDIN_FILENO, &tt) == -1 || ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1) { if (errno != ENOTTY) /* For debugger. */ err(1, "tcgetattr/ioctl"); if (openpty(&master, &slave, NULL, NULL, NULL) == -1) err(1, "openpty"); } else { if (openpty(&master, &slave, NULL, &tt, &win) == -1) err(1, "openpty"); ttyflg = 1; } if (rawout) record(fscript, NULL, 0, 's'); if (!qflg) { tvec = time(NULL); printf("Script started, output file is %s\n", fname); if (!rawout) { fprintf(fscript, "Script started on %s", ctime(&tvec)); if (argv[0]) { showexit = 1; fprintf(fscript, "Command: "); for (k = 0 ; argv[k] ; ++k) fprintf(fscript, "%s%s", k ? " " : "", argv[k]); fprintf(fscript, "\n"); } } fflush(fscript); } if (ttyflg) { rtt = tt; cfmakeraw(&rtt); rtt.c_lflag &= ~ECHO; tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt); } child = fork(); if (child < 0) { warn("fork"); done(1); } if (child == 0) { doshell(argv); } close(slave); start = tvec = time(0); readstdin = 1; for (;;) { FD_ZERO(&rfd); FD_SET(master, &rfd); if (readstdin) FD_SET(STDIN_FILENO, &rfd); if (!readstdin && ttyflg) { tv.tv_sec = 1; tv.tv_usec = 0; tvp = &tv; readstdin = 1; } else if (flushtime > 0) { tv.tv_sec = flushtime - (tvec - start); tv.tv_usec = 0; tvp = &tv; } else { tvp = NULL; } n = select(master + 1, &rfd, 0, 0, tvp); if (n < 0 && errno != EINTR) break; if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) { cc = read(STDIN_FILENO, ibuf, BUFSIZ); if (cc < 0) break; if (cc == 0) { if (tcgetattr(master, &stt) == 0 && (stt.c_lflag & ICANON) != 0) { write(master, &stt.c_cc[VEOF], 1); } readstdin = 0; } if (cc > 0) { if (rawout) record(fscript, ibuf, cc, 'i'); write(master, ibuf, cc); if (kflg && tcgetattr(master, &stt) >= 0 && ((stt.c_lflag & ECHO) == 0)) { fwrite(ibuf, 1, cc, fscript); } } } if (n > 0 && FD_ISSET(master, &rfd)) { cc = read(master, obuf, sizeof (obuf)); if (cc <= 0) break; write(STDOUT_FILENO, obuf, cc); if (rawout) record(fscript, obuf, cc, 'o'); else fwrite(obuf, 1, cc, fscript); } tvec = time(0); if (tvec - start >= flushtime) { fflush(fscript); start = tvec; } if (Fflg) fflush(fscript); } finish(); done(0); } static void usage(void) { fprintf(stderr, "usage: script [-adfkpqr] [-t time] [file [command ...]]\n"); exit(1); } static void finish(void) { int e, status; if (waitpid(child, &status, 0) == child) { if (WIFEXITED(status)) e = WEXITSTATUS(status); else if (WIFSIGNALED(status)) e = WTERMSIG(status); else /* can't happen */ e = 1; done(e); } } static void doshell(char **av) { const char *shell; shell = getenv("SHELL"); if (shell == NULL) shell = _PATH_BSHELL; close(master); fclose(fscript); free(fmfname); login_tty(slave); setenv("SCRIPT", fname, 1); if (av[0]) { execvp(av[0], av); warn("%s", av[0]); } else { execl(shell, shell, "-i", 0); warn("%s", shell); } exit(1); } static void done(int eno) { time_t tvec; if (ttyflg) tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt); tvec = time(NULL); if (rawout) record(fscript, NULL, 0, 'e'); if (!qflg) { if (!rawout) { if (showexit) fprintf(fscript, "\nCommand exit status:" " %d", eno); fprintf(fscript,"\nScript done on %s", ctime(&tvec)); } printf("\nScript done, output file is %s\n", fname); } fclose(fscript); close(master); exit(eno); } static void record(FILE *fp, char *buf, size_t cc, int direction) { struct iovec iov[2]; struct stamp stamp; struct timeval tv; gettimeofday(&tv, NULL); stamp.scr_len = cc; stamp.scr_sec = tv.tv_sec; stamp.scr_usec = tv.tv_usec; stamp.scr_direction = direction; iov[0].iov_len = sizeof(stamp); iov[0].iov_base = &stamp; iov[1].iov_len = cc; iov[1].iov_base = buf; if (writev(fileno(fp), &iov[0], 2) == -1) err(1, "writev"); } static void consume(FILE *fp, off_t len, char *buf, int reg) { size_t l; if (reg) { if (fseeko(fp, len, SEEK_CUR) == -1) err(1, NULL); } else { while (len > 0) { l = MIN(DEF_BUF, len); if (fread(buf, sizeof(char), l, fp) != l) err(1, "cannot read buffer"); len -= l; } } } #define swapstamp(stamp) do { \ if (stamp.scr_direction > 0xff) { \ stamp.scr_len = bswap_64(stamp.scr_len); \ stamp.scr_sec = bswap_64(stamp.scr_sec); \ stamp.scr_usec = bswap_32(stamp.scr_usec); \ stamp.scr_direction = bswap_32(stamp.scr_direction); \ } \ } while (0/*CONSTCOND*/) static void termset(void) { struct termios traw; if (tcgetattr(STDOUT_FILENO, &tt) == -1) { if (errno != ENOTTY) /* For debugger. */ err(1, "tcgetattr"); return; } ttyflg = 1; traw = tt; cfmakeraw(&traw); traw.c_lflag |= ISIG; tcsetattr(STDOUT_FILENO, TCSANOW, &traw); } static void termreset(void) { if (ttyflg) { tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt); ttyflg = 0; } } static void playback(FILE *fp) { struct timespec tsi, tso; struct stamp stamp; struct stat pst; static char buf[DEF_BUF]; off_t nread, save_len; size_t l; time_t tclock; int reg; if (fstat(fileno(fp), &pst) == -1) err(1, "fstat failed"); reg = S_ISREG(pst.st_mode); for (nread = 0; !reg || nread < pst.st_size; nread += save_len) { if (fread(&stamp, sizeof(stamp), 1, fp) != 1) { if (reg) err(1, "reading playback header"); else break; } swapstamp(stamp); save_len = sizeof(stamp); if (reg && stamp.scr_len > (uint64_t)(pst.st_size - save_len) - nread) errx(1, "invalid stamp"); save_len += stamp.scr_len; tclock = stamp.scr_sec; tso.tv_sec = stamp.scr_sec; tso.tv_nsec = stamp.scr_usec * 1000; switch (stamp.scr_direction) { case 's': if (!qflg) printf("Script started on %s", ctime(&tclock)); tsi = tso; consume(fp, stamp.scr_len, buf, reg); termset(); atexit(termreset); break; case 'e': termreset(); if (!qflg) printf("\nScript done on %s", ctime(&tclock)); consume(fp, stamp.scr_len, buf, reg); break; case 'i': /* throw input away */ consume(fp, stamp.scr_len, buf, reg); break; case 'o': tsi.tv_sec = tso.tv_sec - tsi.tv_sec; tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec; if (tsi.tv_nsec < 0) { tsi.tv_sec -= 1; tsi.tv_nsec += 1000000000; } if (usesleep) nanosleep(&tsi, NULL); tsi = tso; while (stamp.scr_len > 0) { l = MIN(DEF_BUF, stamp.scr_len); if (fread(buf, sizeof(char), l, fp) != l) err(1, "cannot read buffer"); write(STDOUT_FILENO, buf, l); stamp.scr_len -= l; } break; default: errx(1, "invalid direction"); } } fclose(fp); exit(0); }
13,071
522
jart/cosmopolitan
false
cosmopolitan/examples/auto-memory-safety-crash2.c
#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/dce.h" #include "libc/intrin/bits.h" #include "libc/intrin/kprintf.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" /** * ASAN heap memory safety crash example. * * make -j8 MODE=dbg o/dbg/examples/auto-memory-safety-crash2.com * o/dbg/examples/auto-memory-safety-crash2.com * * You should see: * * heap overrun 1-byte store at 0x10008004002d shadow 0x20090000005 * ./o/dbg/examples/auto-memory-safety-crash2.com * x * OOOOOOOOOOOUUUUUUUUUUUUUUUU.............OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO * |-7 |-6 |-6 |0 |5 |-7 |-7 |-7 |-7 *    »!@     ÿ▄:Y╩≥= S       hello ∙∙∙∙∙∙∙           ♪     GT◘&@     á+@     »!@   * 000000400000-00000042b000 .text * 00000042b000-00000042d000 .data * 00007fff0000-00008000ffff * 000080070000-00008008ffff * 02008fff0000-02009000ffff ←shadow * 0e007fff0000-0e008000ffff * 10003ab90000-10003abaffff * 100080000000-10008000ffff ←address * 6ffffffe0000-6fffffffffff * * the memory was allocated by * 0x100080040020 64 bytes [dlmalloc] * 0x100080040030 13 bytes [actual] * 402608 main * 402ba0 cosmo * 4021af _start * * the crash was caused by * 0x0000000000404793: __die at libc/log/die.c:40 * 0x0000000000404f56: __asan_report_store at libc/intrin/asan.c:1183 * 0x0000000000402579: main at examples/auto-memory-safety-crash2.c:30 * 0x000000000040270f: cosmo at libc/runtime/cosmo.S:64 * 0x00000000004021ae: _start at libc/crt/crt.S:77 * * @see libc/intrin/asancodes.h for meaning of U, O, etc. and negative numbers * @see libc/nexgen32e/kcp437.S for meaning of symbols */ int main(int argc, char *argv[]) { if (!IsAsan()) { kprintf("this example is intended for MODE=asan or MODE=dbg\n"); exit(1); } kprintf("----------------\n"); kprintf(" THIS IS A TEST \n"); kprintf("SIMULATING CRASH\n"); kprintf("----------------\n"); char *buffer; ShowCrashReports(); /* not needed but yoinks appropriate symbols */ buffer = malloc(13); strcpy(buffer, "hello"); int i = 13; asm("" : "+r"(i)); /* prevent compiler being smart */ buffer[i] = 1; asm("" : "+r"(buffer)); /* prevent compiler being smart */ return 0; }
3,274
81
jart/cosmopolitan
false
cosmopolitan/examples/vqsort.c
#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 "third_party/vqsort/vqsort.h" #include "libc/macros.internal.h" #include "libc/stdio/stdio.h" #include "third_party/vqsort/vqsort.h" // how to sort one gigabyte of 64-bit integers per second int main(int argc, char *argv[]) { int64_t A[] = {9, 3, -3, 5, 23, 7}; vqsort_int64(A, ARRAYLEN(A)); for (int i = 0; i < ARRAYLEN(A); ++i) { if (i) printf(" "); printf("%ld", A[i]); } printf("\n"); }
1,204
26
jart/cosmopolitan
false
cosmopolitan/examples/reboot.c
#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/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/reboot.h" int main(int argc, char *argv[]) { char line[8] = {0}; if (argc > 1 && !strcmp(argv[1], "-y")) { line[0] = 'y'; } else { printf("reboot your computer? yes or no [no] "); fflush(stdout); fgets(line, sizeof(line), stdin); } if (line[0] == 'y' || line[0] == 'Y') { if (reboot(RB_AUTOBOOT)) { printf("system is rebooting...\n"); exit(0); } else { perror("reboot"); exit(1); } } else if (line[0] == 'n' || line[0] == 'N') { exit(0); } else { printf("error: unrecognized response\n"); exit(2); } }
1,514
40
jart/cosmopolitan
false
cosmopolitan/examples/dot.c
#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/macros.internal.h" #include "libc/stdio/stdio.h" typedef float xmm_t __attribute__((__vector_size__(16), __aligned__(4))); float dotvector(float *x, float *y, size_t n) { size_t i; float res; if (n > 64) { return dotvector(x, y, n / 2) + dotvector(x + n / 2, y + n / 2, n - n / 2); } for (res = i = 0; i < n; ++i) { if (i + 4 <= n) { xmm_t res4 = (xmm_t){0}; do { res4 += *(xmm_t *)(x + i) * *(xmm_t *)(y + i); } while ((i += 4) + 4 <= n); res += res4[0]; res += res4[1]; res += res4[2]; res += res4[3]; continue; } res += x[i] * y[i]; } return res; } int main(int argc, char *argv[]) { float x[] = {1, 2, 3, 4, 1, 2, 3, 4}; float y[] = {4, 3, 2, 1, 1, 2, 3, 4}; printf("%g\n", dotvector(x, y, ARRAYLEN(x))); }
1,605
43
jart/cosmopolitan
false
cosmopolitan/examples/package/program.c
#include "examples/package/lib/myprint.h" int main(int argc, char *argv[]) { MyPrint("welcome to your package\n"); return 0; }
132
7
jart/cosmopolitan
false
cosmopolitan/examples/package/new.sh
#!/bin/sh # # SYNOPSIS # # Creates new package in repository. # # EXAMPLE # # examples/package/new.sh com/github/user/project DIR=${1:?need directory arg} VAR=$(echo "$DIR" | tr a-z A-Z | tr / _) DIRNAME=${DIR%/*} BASENAME=${DIR##*/} FILENAME="$DIR/$BASENAME" MAKEFILE="$DIR/$BASENAME.mk" if [ -d "$DIR" ]; then echo "already exists: $DIR" >&2 exit 1 fi mkdir -p "$DIR" && cp -R examples/package/* "$DIR" && rm -f "$DIR/new.sh" && find "$DIR" -type f | xargs sed -i -e " s~EXAMPLES_PACKAGE~$VAR~g s~examples/package/package~$FILENAME~g s~examples/package~$DIR~g s~%AUTHOR%~$(git config user.name) <$(git config user.email)>~g " && sed -i -e " s~include $DIR/build.mk~# XXX: include $DIR/build.mk~ s~include $DIR/lib/build.mk~# XXX: include $DIR/lib/build.mk~ /#-φ-examples\/package\/new\.sh/i\ include $DIR/lib/build.mk /#-φ-examples\/package\/new\.sh/i\ include $DIR/build.mk " Makefile
979
41
jart/cosmopolitan
false
cosmopolitan/examples/package/build.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # SYNOPSIS # # Your package build config for executable programs # # DESCRIPTION # # We assume each .c file in this directory has a main() function, so # that it becomes as easy as possible to write lots of tiny programs # # EXAMPLE # # make o//examples/package # o/examples/package/program.com # # AUTHORS # # %AUTHOR% PKGS += EXAMPLES_PACKAGE # Reads into memory the list of files in this directory. EXAMPLES_PACKAGE_FILES := $(wildcard examples/package/*) # Defines sets of files without needing further iops. EXAMPLES_PACKAGE_SRCS = $(filter %.c,$(EXAMPLES_PACKAGE_FILES)) EXAMPLES_PACKAGE_HDRS = $(filter %.h,$(EXAMPLES_PACKAGE_FILES)) EXAMPLES_PACKAGE_COMS = $(EXAMPLES_PACKAGE_SRCS:%.c=o/$(MODE)/%.com) EXAMPLES_PACKAGE_BINS = \ $(EXAMPLES_PACKAGE_COMS) \ $(EXAMPLES_PACKAGE_COMS:%=%.dbg) # Remaps source file names to object names. # Also asks a wildcard rule to automatically run tool/build/zipobj.c EXAMPLES_PACKAGE_OBJS = \ $(EXAMPLES_PACKAGE_SRCS:%.c=o/$(MODE)/%.o) # Lists packages whose symbols are or may be directly referenced here. # Note that linking stubs is always a good idea due to synthetic code. EXAMPLES_PACKAGE_DIRECTDEPS = \ EXAMPLES_PACKAGE_LIB \ LIBC_INTRIN \ LIBC_STDIO \ LIBC_STUBS \ LIBC_TINYMATH # Evaluates the set of transitive package dependencies. EXAMPLES_PACKAGE_DEPS := \ $(call uniq,$(foreach x,$(EXAMPLES_PACKAGE_DIRECTDEPS),$($(x)))) $(EXAMPLES_PACKAGE_A).pkg: \ $(EXAMPLES_PACKAGE_OBJS) \ $(foreach x,$(EXAMPLES_PACKAGE_DIRECTDEPS),$($(x)_A).pkg) # Specifies how to build programs as ELF binaries with DWARF debug info. # @see build/rules.mk for definition of rule that does .com.dbg -> .com o/$(MODE)/examples/package/%.com.dbg: \ $(EXAMPLES_PACKAGE_DEPS) \ o/$(MODE)/examples/package/%.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) # Invalidates objects in package when makefile is edited. $(EXAMPLES_PACKAGE_OBJS): examples/package/build.mk # Creates target building everything in package and subpackages. .PHONY: o/$(MODE)/examples/package o/$(MODE)/examples/package: \ o/$(MODE)/examples/package/lib \ $(EXAMPLES_PACKAGE_BINS)
2,374
74
jart/cosmopolitan
false
cosmopolitan/examples/package/lib/myasm.S
#include "libc/macros.internal.h" // Example assembly function. // // @note param agnostic // @note we love stack frames // easiest way to do backtraces // somehow they usually make code faster // it's convention for keeping stack 16-byte aligned // cpus still devote much to pushing & popping b/c i386 MyAsm: #ifdef __x86_64__ push %rbp mov %rsp,%rbp call MyPrint2 pop %rbp #elif defined(__aarch64__) bl MyPrint2 #else #error "unsupported architecture" #endif ret .endfn MyAsm,globl
498
26
jart/cosmopolitan
false
cosmopolitan/examples/package/lib/build.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # SYNOPSIS # # Your package static library build config # # DESCRIPTION # # Your library doesn't have a main() function and can be compromised # of sources written in multiple languages. # # WARNING # # This library (examples/package/lib/) comes earlier in the # topological order of things than its parent (examples/package/) # because the parent package depends on the subpackage. Therefore, # this package needs to be written earlier in the Makefile includes. # # EXAMPLE # # make o//examples/package/lib # build library w/ sanity checks # ar t o//examples/package/lib/lib.a # # AUTHORS # # %AUTHOR% PKGS += EXAMPLES_PACKAGE_LIB # Declares package i.e. library w/ transitive dependencies. # We define packages as a thing that lumps similar sources. # It's needed, so linkage can have a higher level overview. # Mostly due to there being over 9,000 objects in the repo. EXAMPLES_PACKAGE_LIB = \ $(EXAMPLES_PACKAGE_LIB_A_DEPS) \ $(EXAMPLES_PACKAGE_LIB_A) # Declares library w/o transitive dependencies. EXAMPLES_PACKAGE_LIB_A = o/$(MODE)/examples/package/lib/lib.a EXAMPLES_PACKAGE_LIB_ARTIFACTS += EXAMPLES_PACKAGE_LIB_A # Build configs might seem somewhat complicated. Rest assured they're # mostly maintenance free. That's largely thanks to how we wildcard. EXAMPLES_PACKAGE_LIB_A_FILES := $(wildcard examples/package/lib/*) EXAMPLES_PACKAGE_LIB_A_HDRS = $(filter %.h,$(EXAMPLES_PACKAGE_LIB_A_FILES)) # Define sets of source files without needing further iops. EXAMPLES_PACKAGE_LIB_A_SRCS_S = \ $(filter %.S,$(EXAMPLES_PACKAGE_LIB_A_FILES)) EXAMPLES_PACKAGE_LIB_A_SRCS_C = \ $(filter %.c,$(EXAMPLES_PACKAGE_LIB_A_FILES)) EXAMPLES_PACKAGE_LIB_A_SRCS = \ $(EXAMPLES_PACKAGE_LIB_A_SRCS_S) \ $(EXAMPLES_PACKAGE_LIB_A_SRCS_C) # Change suffixes of different languages extensions into object names. EXAMPLES_PACKAGE_LIB_A_OBJS = \ $(EXAMPLES_PACKAGE_LIB_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(EXAMPLES_PACKAGE_LIB_A_SRCS_C:%.c=o/$(MODE)/%.o) # Does the two most important things for C/C++ code sustainability. # 1. Guarantees each header builds, i.e. includes symbols it needs. # 2. Guarantees transitive closure of packages is directed acyclic. EXAMPLES_PACKAGE_LIB_A_CHECKS = \ $(EXAMPLES_PACKAGE_LIB_A).pkg \ $(EXAMPLES_PACKAGE_LIB_A_HDRS:%=o/$(MODE)/%.ok) # Lists packages whose symbols are or may be directly referenced here. # Note that linking stubs is always a good idea due to synthetic code. EXAMPLES_PACKAGE_LIB_A_DIRECTDEPS = \ LIBC_STDIO \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_STUBS # Evaluates variable as set of transitive package dependencies. EXAMPLES_PACKAGE_LIB_A_DEPS := \ $(call uniq,$(foreach x,$(EXAMPLES_PACKAGE_LIB_A_DIRECTDEPS),$($(x)))) # Concatenates object files into single file with symbol index. # Please don't use fancy make features for mutating archives it's slow. $(EXAMPLES_PACKAGE_LIB_A): \ examples/package/lib/ \ $(EXAMPLES_PACKAGE_LIB_A).pkg \ $(EXAMPLES_PACKAGE_LIB_A_OBJS) # Asks packager to index symbols and validate their relationships. # It's the real secret sauce for having a huge Makefile w/o chaos. # @see tool/build/package.c # @see build/rules.mk $(EXAMPLES_PACKAGE_LIB_A).pkg: \ $(EXAMPLES_PACKAGE_LIB_A_OBJS) \ $(foreach x,$(EXAMPLES_PACKAGE_LIB_A_DIRECTDEPS),$($(x)_A).pkg) # Invalidates objects in package when makefile is edited. $(EXAMPLES_PACKAGE_LIB_A_OBJS): examples/package/lib/build.mk # let these assembly objects build on aarch64 o/$(MODE)/examples/package/lib/myasm.o: examples/package/lib/myasm.S @$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $< EXAMPLES_PACKAGE_LIB_LIBS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x))) EXAMPLES_PACKAGE_LIB_SRCS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_SRCS)) EXAMPLES_PACKAGE_LIB_HDRS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_HDRS)) EXAMPLES_PACKAGE_LIB_BINS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_BINS)) EXAMPLES_PACKAGE_LIB_CHECKS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_CHECKS)) EXAMPLES_PACKAGE_LIB_OBJS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_OBJS)) EXAMPLES_PACKAGE_LIB_TESTS = $(foreach x,$(EXAMPLES_PACKAGE_LIB_ARTIFACTS),$($(x)_TESTS)) .PHONY: o/$(MODE)/examples/package/lib o/$(MODE)/examples/package/lib: $(EXAMPLES_PACKAGE_LIB_CHECKS)
4,571
113
jart/cosmopolitan
false
cosmopolitan/examples/package/lib/myprint.c
#include "examples/package/lib/myprint.h" #include "libc/stdio/stdio.h" /** * Calls MyPrint2() indirected via assembly function. */ void MyPrint(const char *s) { MyAsm(s); } /** * Prints string to output. * * @param s is null-terminated c string usually having \n * @see printf() which has domain-specific language */ void MyPrint2(const char *s) { fputs(s, stdout); }
382
20
jart/cosmopolitan
false
cosmopolitan/examples/package/lib/myprint.h
#ifndef COSMOPOLITAN_EXAMPLES_PACKAGE_LIB_MYPRINT_H_ #define COSMOPOLITAN_EXAMPLES_PACKAGE_LIB_MYPRINT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void MyPrint(const char *); void MyAsm(const char *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_EXAMPLES_PACKAGE_LIB_MYPRINT_H_ */
347
12
jart/cosmopolitan
false
cosmopolitan/examples/pyapp/pyapp.py
def main(): print('cosmopolitan is cool!') if __name__ == '__main__': main()
81
5
jart/cosmopolitan
false
cosmopolitan/examples/pyapp/pyapp.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # SYNOPSIS # # Actually Portable Python Tutorial # # DESCRIPTION # # This tutorial demonstrates how to compile Python apps as tiny # static multiplatform APE executables as small as 1.9m in size # using Cosmopolitan, which is a BSD-style multitenant codebase # # GETTING STARTED # # # run these commands after cloning the cosmo repo on linux # $ make -j8 o//examples/pyapp/pyapp.com # $ o//examples/pyapp/pyapp.com # cosmopolitan is cool! # # HOW IT WORKS # # $ pyobj.com -m -o pyapp.o pyapp.py # $ ld -static -nostdlib -T o//ape/ape.lds ape.o crt.o \ # pyapp.o \ # cosmopolitan-python-stage2.a \ # cosmopolitan-sqlite3.a \ # cosmopolitan-linenoise.a \ # cosmopolitan-bzip2.a \ # cosmopolitan-python-stage1.a \ # cosmopolitan.a # $ ./pyapp.com # cosmopolitan is cool! # # NOTES # # If you enjoy this tutorial, let us know jtunney@gmail.com. If # you're building something cool, then we can we can add you to # our .gitowners file which grants you commit access so you can # indepnedently maintain your package, as part of the mono-repo PKGS += PYAPP PYAPP = $(PYAPP_DEPS) o/$(MODE)/examples/pyapp/pyapp.a PYAPP_COMS = o/$(MODE)/examples/pyapp/pyapp.com PYAPP_BINS = $(PYAPP_COMS) $(PYAPP_COMS:%=%.dbg) # Specify our Cosmopolitan library dependencies # # - THIRD_PARTY_PYTHON_STAGE1 plus THIRD_PARTY_PYTHON_STAGE2 will # define the Python CAPI and supported standard library modules # PYAPP_DIRECTDEPS = \ THIRD_PARTY_PYTHON_STAGE2 # Compute the transitive closure of dependencies. There's dozens of # other static libraries we need, in order to build a static binary # such as fmt.a, runtime.a, str.a etc. This magic statement figures # them all out and arranges them in the correct order. PYAPP_DEPS := $(call uniq,$(foreach x,$(PYAPP_DIRECTDEPS),$($(x)))) # # Asks PYOBJ.COM to turn our Python source into an ELF object which # # contains (a) embedded zip file artifacts of our .py file and .pyc # # which it it compiled; and (b) statically analyzed listings of our # # python namespaces and imports that GNU ld will use for tree shake # # NOTE: This code can be commented out since it's in build/rules.mk # o/$(MODE)/examples/pyapp/pyapp.o: examples/pyapp/pyapp.py o/$(MODE)/third_party/python/pyobj # o/$(MODE)/third_party/python/pyobj $(PYFLAGS) -o $@ $< # We need to define how the repository source code path gets mapped # into an APE ZIP file path. By convention, we place Python modules # in `.python/` (which is accessible via open() system calls, using # the synthetic path `"/zip/.python/"`) which means that if we want # to turn `pyapp/pyapp.py` into `.python/pyapp.py` so it's imported # using `import pyapp` then we can simply append to PYOBJ.COM flags # flags above asking it to strip one directory component and prefix # Lastly be sure that whenever you use this variable override trick # you only do it to .o files, since otherwise it'll ruin everything # Passing -m to PYOBJ.COM causes a C main() function to get yoinked # and it means our Python module can no longer be used as a library o/$(MODE)/examples/pyapp/pyapp.o: PYFLAGS += -m -C2 -P.python # Asks PACKAGE.COM to sanity check our DIRECTDEPS and symbol graph. # This program functions as an incremental linker. It also provides # enhancements to the object code that GCC generated similar to LTO # so be certain that your .com.dbg rule depends on the .pkg output! o/$(MODE)/examples/pyapp/pyapp.pkg: \ o/$(MODE)/examples/pyapp/pyapp.o \ $(foreach x,$(PYAPP_DIRECTDEPS),$($(x)_A).pkg) # Ask GNU LD to link our APE executable within an ELF binary shell. # The CRT and APE dependencies are special dependencies that define # your _start() / WinMain() entrpoints as well as APE linker script o/$(MODE)/examples/pyapp/pyapp.com.dbg: \ $(PYAPP_DEPS) \ o/$(MODE)/examples/pyapp/pyapp.pkg \ o/$(MODE)/examples/pyapp/pyapp.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(COMPILE) -ALINK.ape $(LINK) $(LINKARGS) -o $@ # # Unwrap the APE .COM binary, that's embedded within the linked file # # NOTE: This line can be commented out, since it's in build/rules.mk # o/$(MODE)/examples/pyapp/pyapp.com: \ # o/$(MODE)/examples/pyapp/pyapp.com.dbg # $(OBJCOPY) -S -O binary $< $@ # Ensure that build config changes will invalidate build artifacts. o/$(MODE)/examples/pyapp/pyapp.o: \ examples/pyapp/pyapp.mk # By convention we want to be able to say `make -j8 o//examples/pyapp` # and have it build all targets the package defines. .PHONY: o/$(MODE)/examples/pyapp o/$(MODE)/examples/pyapp: \ o/$(MODE)/examples/pyapp/pyapp.com \ o/$(MODE)/examples/pyapp/pyapp.com.dbg
4,844
117
jart/cosmopolitan
false
cosmopolitan/examples/pylife/pylife.py
import sys sys.exit(42)
24
3
jart/cosmopolitan
false
cosmopolitan/examples/pylife/pylife.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # SYNOPSIS # # Actually Portable Python Tutorial # # DESCRIPTION # # This tutorial demonstrates how to compile Python apps as tiny # static multiplatform APE executables as small as 1.9m in size # using Cosmopolitan, which is a BSD-style multitenant codebase # # GETTING STARTED # # # run these commands after cloning the cosmo repo on linux # $ make -j8 o//examples/pylife/pylife.com # $ o//examples/pylife/pylife.com # cosmopolitan is cool! # # HOW IT WORKS # # $ pyobj.com -m -o pylife.o pylife.py # $ ld -static -nostdlib -T o//ape/ape.lds ape.o crt.o \ # pylife.o \ # cosmopolitan-python-stage2.a \ # cosmopolitan-sqlite3.a \ # cosmopolitan-linenoise.a \ # cosmopolitan-bzip2.a \ # cosmopolitan-python-stage1.a \ # cosmopolitan.a # $ ./pylife.com # cosmopolitan is cool! # # NOTES # # If you enjoy this tutorial, let us know jtunney@gmail.com. If # you're building something cool, then we can we can add you to # our .gitowners file which grants you commit access so you can # indepnedently maintain your package, as part of the mono-repo PKGS += PYLIFE PYLIFE = $(PYLIFE_DEPS) o/$(MODE)/examples/pylife/pylife.a PYLIFE_COMS = o/$(MODE)/examples/pylife/pylife.com PYLIFE_BINS = $(PYLIFE_COMS) $(PYLIFE_COMS:%=%.dbg) # Specify our Cosmopolitan library dependencies # # - THIRD_PARTY_PYTHON_STAGE1 plus THIRD_PARTY_PYTHON_STAGE2 will # define the Python CAPI and supported standard library modules # PYLIFE_DIRECTDEPS = \ THIRD_PARTY_PYTHON_STAGE2 # Compute the transitive closure of dependencies. There's dozens of # other static libraries we need, in order to build a static binary # such as fmt.a, runtime.a, str.a etc. This magic statement figures # them all out and arranges them in the correct order. PYLIFE_DEPS := $(call uniq,$(foreach x,$(PYLIFE_DIRECTDEPS),$($(x)))) # # Asks PYOBJ.COM to turn our Python source into an ELF object which # # contains (a) embedded zip file artifacts of our .py file and .pyc # # which it it compiled; and (b) statically analyzed listings of our # # python namespaces and imports that GNU ld will use for tree shake # # NOTE: This code can be commented out since it's in build/rules.mk # o/$(MODE)/examples/pylife/pylife.o: examples/pylife/pylife.py o/$(MODE)/third_party/python/pyobj # o/$(MODE)/third_party/python/pyobj $(PYFLAGS) -o $@ $< # We need to define how the repository source code path gets mapped # into an APE ZIP file path. By convention, we place Python modules # in `.python/` (which is accessible via open() system calls, using # the synthetic path `"/zip/.python/"`) which means that if we want # to turn `pylife/pylife.py` into `.python/pylife.py` so it's imported # using `import pylife` then we can simply append to PYOBJ.COM flags # flags above asking it to strip one directory component and prefix # Lastly be sure that whenever you use this variable override trick # you only do it to .o files, since otherwise it'll ruin everything # Passing -m to PYOBJ.COM causes a C main() function to get yoinked # and it means our Python module can no longer be used as a library o/$(MODE)/examples/pylife/pylife.o: PYFLAGS += -m -C2 -P.python # Asks PACKAGE.COM to sanity check our DIRECTDEPS and symbol graph. # This program functions as an incremental linker. It also provides # enhancements to the object code that GCC generated similar to LTO # so be certain that your .com.dbg rule depends on the .pkg output! o/$(MODE)/examples/pylife/pylife.pkg: \ o/$(MODE)/examples/pylife/pylife.o \ $(foreach x,$(PYLIFE_DIRECTDEPS),$($(x)_A).pkg) # Ask GNU LD to link our APE executable within an ELF binary shell. # The CRT and APE dependencies are special dependencies that define # your _start() / WinMain() entrpoints as well as APE linker script o/$(MODE)/examples/pylife/pylife.com.dbg: \ $(PYLIFE_DEPS) \ o/$(MODE)/examples/pylife/pylife.pkg \ o/$(MODE)/examples/pylife/pylife.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(COMPILE) -ALINK.ape $(LINK) $(LINKARGS) -o $@ # # Unwrap the APE .COM binary, that's embedded within the linked file # # NOTE: This line can be commented out, since it's in build/rules.mk # o/$(MODE)/examples/pylife/pylife.com: \ # o/$(MODE)/examples/pylife/pylife.com.dbg # $(OBJCOPY) -S -O binary $< $@ # Ensure that build config changes will invalidate build artifacts. o/$(MODE)/examples/pylife/pylife.o: \ examples/pylife/pylife.mk # By convention we want to be able to say `make -j8 o//examples/pylife` # and have it build all targets the package defines. .PHONY: o/$(MODE)/examples/pylife o/$(MODE)/examples/pylife: \ o/$(MODE)/examples/pylife/pylife.com \ o/$(MODE)/examples/pylife/pylife.com.dbg
4,903
117
jart/cosmopolitan
false
cosmopolitan/test/test.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ .PHONY: o/$(MODE)/test o/$(MODE)/test: o/$(MODE)/test/dsp \ o/$(MODE)/test/libc \ o/$(MODE)/test/net \ o/$(MODE)/test/tool
331
9
jart/cosmopolitan
false
cosmopolitan/test/libc/test.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ .PHONY: o/$(MODE)/test/libc o/$(MODE)/test/libc: \ o/$(MODE)/test/libc/calls \ o/$(MODE)/test/libc/dns \ o/$(MODE)/test/libc/fmt \ o/$(MODE)/test/libc/intrin \ o/$(MODE)/test/libc/log \ o/$(MODE)/test/libc/mem \ o/$(MODE)/test/libc/nexgen32e \ o/$(MODE)/test/libc/release \ o/$(MODE)/test/libc/runtime \ o/$(MODE)/test/libc/sock \ o/$(MODE)/test/libc/stdio \ o/$(MODE)/test/libc/str \ o/$(MODE)/test/libc/thread \ o/$(MODE)/test/libc/time \ o/$(MODE)/test/libc/tinymath \ o/$(MODE)/test/libc/x \ o/$(MODE)/test/libc/zipos \ o/$(MODE)/test/libc/xed
813
24
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/arena_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/libfatal.internal.h" #include "libc/mem/arena.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "libc/stdio/append.h" #include "libc/str/str.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/hyperion.h" #include "libc/testlib/testlib.h" TEST(arena, test) { EXPECT_STREQ("hello", gc(strdup("hello"))); __arena_push(); EXPECT_STREQ("hello", strdup("hello")); __arena_push(); EXPECT_STREQ("hello", strdup("hello")); for (int i = 0; i < 5000; ++i) { EXPECT_STREQ("hello", strdup("hello")); } free(strdup("hello")); __arena_pop(); EXPECT_STREQ("", calloc(1, 16)); EXPECT_STREQ("hello", strdup("hello")); __arena_pop(); } TEST(arena, testRealloc) { char *b = 0; size_t i, n = 0; __arena_push(); for (i = 0; i < kHyperionSize; ++i) { b = realloc(b, ++n * sizeof(*b)); b[n - 1] = kHyperion[i]; } ASSERT_EQ(0, memcmp(b, kHyperion, kHyperionSize)); __arena_pop(); } void *memalign_(size_t, size_t) asm("memalign"); void *calloc_(size_t, size_t) asm("calloc"); void Ca(size_t n) { __arena_push(); for (int i = 0; i < n; ++i) { memalign_(1, 1); } __arena_pop(); } void Cb(size_t n) { void **P; P = malloc(n * sizeof(void *)); for (int i = 0; i < n; ++i) { P[i] = calloc_(1, 1); } bulk_free(P, n); free(P); } BENCH(arena, benchMalloc) { EZBENCH2("arena calloc(1)", donothing, Ca(100)); EZBENCH2("dlmalloc calloc(1)", donothing, Cb(100)); } void Ra(void) { long *b = 0; size_t i, n = 0; __arena_push(); for (i = 0; i < kHyperionSize; ++i) { b = realloc(b, ++n * sizeof(*b)); b[n - 1] = kHyperion[i]; } __arena_pop(); } void Rb(void) { long *b = 0; size_t i, n = 0; for (i = 0; i < kHyperionSize; ++i) { b = realloc(b, ++n * sizeof(*b)); b[n - 1] = kHyperion[i]; } free(b); } BENCH(arena, benchRealloc) { EZBENCH2("arena realloc", donothing, Ra()); EZBENCH2("dlmalloc realloc", donothing, Rb()); }
3,809
108
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/sortedints_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/limits.h" #include "libc/mem/mem.h" #include "libc/mem/sortedints.internal.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" struct SortedInts T; void TearDown(void) { free(T.p); bzero(&T, sizeof(T)); } TEST(sortedints, test) { EXPECT_TRUE(InsertInt(&T, 3, false)); EXPECT_TRUE(InsertInt(&T, 1, false)); EXPECT_TRUE(InsertInt(&T, -1, false)); EXPECT_TRUE(InsertInt(&T, 2, false)); EXPECT_EQ(4, T.n); EXPECT_EQ(-1, T.p[0]); EXPECT_EQ(+1, T.p[1]); EXPECT_EQ(+2, T.p[2]); EXPECT_EQ(+3, T.p[3]); EXPECT_FALSE(ContainsInt(&T, -2)); EXPECT_TRUE(ContainsInt(&T, -1)); EXPECT_FALSE(ContainsInt(&T, 0)); EXPECT_TRUE(ContainsInt(&T, 1)); EXPECT_TRUE(ContainsInt(&T, 2)); EXPECT_TRUE(ContainsInt(&T, 3)); EXPECT_FALSE(ContainsInt(&T, 4)); } TEST(sortedints, unique) { EXPECT_TRUE(InsertInt(&T, INT_MAX, true)); EXPECT_TRUE(InsertInt(&T, 1, true)); EXPECT_FALSE(InsertInt(&T, INT_MAX, true)); EXPECT_TRUE(InsertInt(&T, INT_MIN, true)); EXPECT_FALSE(InsertInt(&T, 1, true)); EXPECT_TRUE(InsertInt(&T, 2, true)); EXPECT_EQ(4, T.n); EXPECT_EQ(INT_MIN, T.p[0]); EXPECT_EQ(+1, T.p[1]); EXPECT_EQ(+2, T.p[2]); EXPECT_EQ(INT_MAX, T.p[3]); EXPECT_FALSE(ContainsInt(&T, -2)); EXPECT_TRUE(ContainsInt(&T, INT_MIN)); EXPECT_FALSE(ContainsInt(&T, 0)); EXPECT_TRUE(ContainsInt(&T, 1)); EXPECT_TRUE(ContainsInt(&T, 2)); EXPECT_TRUE(ContainsInt(&T, INT_MAX)); EXPECT_FALSE(ContainsInt(&T, 4)); EXPECT_EQ(1, CountInt(&T, 1)); EXPECT_EQ(0, CountInt(&T, -5)); } TEST(sortedints, bag) { EXPECT_TRUE(InsertInt(&T, INT_MAX, false)); EXPECT_TRUE(InsertInt(&T, 1, false)); EXPECT_TRUE(InsertInt(&T, INT_MAX, false)); EXPECT_TRUE(InsertInt(&T, INT_MIN, false)); EXPECT_TRUE(InsertInt(&T, 1, false)); EXPECT_TRUE(InsertInt(&T, 2, false)); EXPECT_EQ(6, T.n); EXPECT_EQ(INT_MIN, T.p[0]); EXPECT_EQ(1, T.p[1]); EXPECT_EQ(1, T.p[2]); EXPECT_EQ(2, T.p[3]); EXPECT_EQ(INT_MAX, T.p[4]); EXPECT_EQ(INT_MAX, T.p[5]); EXPECT_FALSE(ContainsInt(&T, -2)); EXPECT_TRUE(ContainsInt(&T, INT_MIN)); EXPECT_FALSE(ContainsInt(&T, 0)); EXPECT_TRUE(ContainsInt(&T, 1)); EXPECT_TRUE(ContainsInt(&T, 2)); EXPECT_TRUE(ContainsInt(&T, INT_MAX)); EXPECT_FALSE(ContainsInt(&T, 4)); EXPECT_EQ(1, CountInt(&T, INT_MIN)); EXPECT_EQ(2, CountInt(&T, 1)); EXPECT_EQ(0, CountInt(&T, -5)); } TEST(sortedints, fuzz) { for (int i = 0; i < 10000; ++i) { volatile bool b; volatile int y, x = lemur64(); InsertInt(&T, x, x & 1); b = ContainsInt(&T, x); b = ContainsInt(&T, -x); y = CountInt(&T, x); } for (int i = 1; i < T.n; ++i) { ASSERT_GE(T.p[i], T.p[i - 1]); } } BENCH(sortedints, bench) { volatile int x; EZBENCH2("overhead", donothing, x = lemur64()); EZBENCH2("insert small", donothing, InsertInt(&T, lemur64(), true)); EZBENCH2("contains small", donothing, ContainsInt(&T, lemur64())); for (int i = 0; i < 20000; ++i) { InsertInt(&T, lemur64(), true); } EZBENCH2("insert big", donothing, InsertInt(&T, lemur64(), true)); EZBENCH2("contains big", donothing, ContainsInt(&T, lemur64())); }
5,032
127
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/bisectcarleft_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/alg.h" #include "libc/mem/bisectcarleft.internal.h" #include "libc/intrin/bits.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/testlib/testlib.h" TEST(bisectcarleft, testEmpty) { const int32_t cells[][2] = {}; EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), 123)); } TEST(bisectcarleft, testOneEntry) { const int32_t cells[][2] = {{123, 31337}}; EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), 122)); EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), 123)); EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), 124)); } TEST(bisectcarleft, testNegativity_usesSignedBehavior) { const int32_t cells[][2] = {{-2, 31337}}; EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), -3)); EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), -2)); EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), -1)); } TEST(bisectcarleft, testMultipleEntries) { const int32_t cells[][2] = {{00, 0}, {11, 0}, {20, 0}, {33, 0}, {40, 0}, {50, 0}, {60, 0}, {70, 0}, {80, 0}, {90, 0}}; EXPECT_EQ(0, bisectcarleft(cells, ARRAYLEN(cells), 10)); EXPECT_EQ(1, bisectcarleft(cells, ARRAYLEN(cells), 11)); EXPECT_EQ(1, bisectcarleft(cells, ARRAYLEN(cells), 12)); EXPECT_EQ(1, bisectcarleft(cells, ARRAYLEN(cells), 19)); EXPECT_EQ(2, bisectcarleft(cells, ARRAYLEN(cells), 20)); EXPECT_EQ(2, bisectcarleft(cells, ARRAYLEN(cells), 21)); EXPECT_EQ(2, bisectcarleft(cells, ARRAYLEN(cells), 32)); EXPECT_EQ(3, bisectcarleft(cells, ARRAYLEN(cells), 33)); EXPECT_EQ(3, bisectcarleft(cells, ARRAYLEN(cells), 34)); }
3,441
58
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/strdup_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bits.h" #include "libc/mem/mem.h" #include "libc/testlib/testlib.h" char *s2; TEST(strdup, test) { EXPECT_STREQ("hello", (s2 = strdup("hello"))); EXPECT_NE((intptr_t) "hello", (intptr_t)s2); free(s2); } TEST(strndup, test) { EXPECT_STREQ("hello", (s2 = strndup("hello", 8))); EXPECT_NE((intptr_t) "hello", (intptr_t)s2); free(s2); } TEST(strndup, tooLong_truncatesWithNul) { EXPECT_STREQ("hell", (s2 = strndup("hello", 4))); free(s2); }
2,315
41
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/malloc_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/timespec.h" #include "libc/dce.h" #include "libc/intrin/bits.h" #include "libc/intrin/cxaatexit.internal.h" #include "libc/intrin/safemacros.internal.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/sysconf.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/subprocess.h" #include "libc/testlib/testlib.h" #include "libc/thread/thread.h" #include "libc/time/time.h" #define N 1024 #define M 20 void SetUp(void) { // TODO(jart): what is wrong? if (IsWindows()) exit(0); } TEST(malloc, zeroMeansOne) { ASSERT_GE(malloc_usable_size(gc(malloc(0))), 1); } TEST(calloc, zerosMeansOne) { ASSERT_GE(malloc_usable_size(gc(calloc(0, 0))), 1); } void AppendStuff(char **p, size_t *n) { char buf[512]; ASSERT_NE(NULL, (*p = realloc(*p, (*n += 512)))); rngset(buf, sizeof(buf), 0, 0); memcpy(*p + *n - sizeof(buf), buf, sizeof(buf)); } TEST(malloc, test) { char *big = 0; size_t n, bigsize = 0; static struct stat st; static volatile int i, j, k, *A[4096], fds[M], *maps[M], mapsizes[M]; memset(fds, -1, sizeof(fds)); memset(maps, -1, sizeof(maps)); for (i = 0; i < N * M; ++i) { /* AppendStuff(&big, &bigsize); */ j = rand() % ARRAYLEN(A); if (A[j]) { ASSERT_EQ(j, A[j][0]); n = rand() % N; n = MAX(n, 1); n = ROUNDUP(n, sizeof(int)); A[j] = realloc(A[j], n); ASSERT_NE(NULL, A[j]); ASSERT_EQ(j, A[j][0]); free(A[j]); A[j] = NULL; } else { n = rand() % N; n = MAX(n, 1); n = ROUNDUP(n, sizeof(int)); A[j] = malloc(n); ASSERT_NE(NULL, A[j]); A[j][0] = j; } if (!(i % M)) { k = rand() % M; if (fds[k] == -1) { ASSERT_NE(-1, (fds[k] = open(program_invocation_name, O_RDONLY))); ASSERT_NE(-1, fstat(fds[k], &st)); mapsizes[k] = st.st_size; ASSERT_NE(MAP_FAILED, (maps[k] = mmap(NULL, mapsizes[k], PROT_READ, MAP_SHARED, fds[k], 0))); } else { ASSERT_NE(-1, munmap(maps[k], mapsizes[k])); ASSERT_NE(-1, close(fds[k])); fds[k] = -1; } } } free(big); for (i = 0; i < ARRAYLEN(A); ++i) free(A[i]); for (i = 0; i < ARRAYLEN(maps); ++i) munmap(maps[i], mapsizes[i]); for (i = 0; i < ARRAYLEN(fds); ++i) close(fds[i]); } TEST(memalign, roundsUpAlignmentToTwoPower) { char *volatile p = memalign(129, 1); ASSERT_EQ(0, (intptr_t)p & 255); free(p); } void *bulk[1024]; void BulkFreeBenchSetup(void) { size_t i; for (i = 0; i < ARRAYLEN(bulk); ++i) { bulk[i] = malloc(rand() % 64); } } void FreeBulk(void) { size_t i; for (i = 0; i < ARRAYLEN(bulk); ++i) { free(bulk[i]); } } void MallocFree(void) { char *volatile p; p = malloc(16); free(p); } BENCH(bulk_free, bench) { EZBENCH2("free() bulk", BulkFreeBenchSetup(), FreeBulk()); EZBENCH2("bulk_free()", BulkFreeBenchSetup(), bulk_free(bulk, ARRAYLEN(bulk))); EZBENCH2("free(malloc(16)) ST", donothing, MallocFree()); __enable_threads(); EZBENCH2("free(malloc(16)) MT", donothing, MallocFree()); } #define ITERATIONS 10000 void *Worker(void *arg) { for (int i = 0; i < ITERATIONS; ++i) { char *p; ASSERT_NE(NULL, (p = malloc(lemur64() % 128))); ASSERT_NE(NULL, (p = realloc(p, max(lemur64() % 128, 1)))); free(p); } return 0; } BENCH(malloc, torture) { int i, n = _getcpucount() * 2; pthread_t *t = _gc(malloc(sizeof(pthread_t) * n)); if (!n) return; printf("\nmalloc torture test w/ %d threads and %d iterations\n", n, ITERATIONS); SPAWN(fork); struct timespec t1 = timespec_real(); for (i = 0; i < n; ++i) { ASSERT_EQ(0, pthread_create(t + i, 0, Worker, 0)); } for (i = 0; i < n; ++i) { ASSERT_EQ(0, pthread_join(t[i], 0)); } struct timespec t2 = timespec_real(); printf("consumed %g wall and %g cpu seconds\n", timespec_tomicros(timespec_sub(t2, t1)) * 1e-6, (double)clock() / CLOCKS_PER_SEC); EXITS(0); }
6,301
187
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/tarjan_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/mem/alg.h" #include "libc/testlib/testlib.h" STATIC_YOINK("realloc"); TEST(tarjan, empty_doesNothing) { int sorted_vertices[1] = {-1}; int edges[][2] = {{0, 0}}; int vertex_count = 0; int edge_count = 0; _tarjan(vertex_count, (void *)edges, edge_count, sorted_vertices, NULL, NULL); ASSERT_EQ(-1, sorted_vertices[0]); } TEST(tarjan, topologicalSort_noCycles) { enum VertexIndex { A = 0, B = 1, C = 2, D = 3 }; const char *const vertices[] = {[A] = "A", [B] = "B", [C] = "C", [D] = "D"}; int edges[][2] = {{A /* depends on → */, B /* which must come before A */}, {A /* depends on → */, C /* which must come before A */}, {A /* depends on → */, D /* which must come before A */}, {B /* depends on → */, C /* which must come before B */}, {B /* depends on → */, D /* which must come before B */}}; /* $ tsort <<EOF B A C A D A C B D B EOF C D B A */ int sorted[4], components[4], componentcount; ASSERT_EQ(0, _tarjan(ARRAYLEN(vertices), (void *)edges, ARRAYLEN(edges), sorted, components, &componentcount)); EXPECT_EQ(C, sorted[0]); EXPECT_EQ(D, sorted[1]); EXPECT_EQ(B, sorted[2]); EXPECT_EQ(A, sorted[3]); ASSERT_EQ(4, componentcount); EXPECT_EQ(1, components[0]); EXPECT_EQ(2, components[1]); EXPECT_EQ(3, components[2]); EXPECT_EQ(4, components[3]); } TEST(tarjan, testOneBigCycle_isDetected_weDontCareAboutOrderInsideTheCycle) { enum VertexIndex { A = 0, B = 1, C = 2, D = 3 }; const char *const vertices[] = {[A] = "A", [B] = "B", [C] = "C", [D] = "D"}; /* ┌─────────┐ └→A→B→C→D─┘ */ int edges[][2] = {{A /* depends on → */, B /* which must come before A */}, {B /* depends on → */, C /* which must come before B */}, {C /* depends on → */, D /* which must come before C */}, {D /* depends on → */, A /* which must come before D */}}; int sorted[4], components[4], componentcount; ASSERT_EQ(0, _tarjan(ARRAYLEN(vertices), (void *)edges, ARRAYLEN(edges), sorted, components, &componentcount)); ASSERT_EQ(1, componentcount); EXPECT_EQ(4, components[0]); } TEST(tarjan, testHeaders) { enum Headers { LIBC_STR_STR, LIBC_BITS_BITS, LIBC_INTEGRAL, LIBC_KEYWORDS, LIBC_DCE, LIBC_MACROS, LIBC_MACROS_CPP, }; const char *const vertices[] = { [LIBC_STR_STR] = "libc/str/str.h", [LIBC_BITS_BITS] = "libc/intrin/bits.h", [LIBC_INTEGRAL] = "libc/integral.h", [LIBC_KEYWORDS] = "libc/keywords.h", [LIBC_DCE] = "libc/dce.h", [LIBC_MACROS] = "libc/macros.internal.h", [LIBC_MACROS_CPP] = "libc/macros-cpp.inc", }; int edges[][2] = { {LIBC_STR_STR, LIBC_BITS_BITS}, {LIBC_STR_STR, LIBC_INTEGRAL}, {LIBC_STR_STR, LIBC_KEYWORDS}, {LIBC_BITS_BITS, LIBC_DCE}, {LIBC_BITS_BITS, LIBC_INTEGRAL}, {LIBC_BITS_BITS, LIBC_KEYWORDS}, {LIBC_BITS_BITS, LIBC_MACROS}, {LIBC_MACROS, LIBC_MACROS_CPP}, }; int sorted[ARRAYLEN(vertices)]; int components[ARRAYLEN(vertices)]; int componentcount; ASSERT_EQ(0, _tarjan(ARRAYLEN(vertices), (void *)edges, ARRAYLEN(edges), sorted, components, &componentcount)); ASSERT_EQ(ARRAYLEN(vertices), componentcount); EXPECT_STREQ("libc/dce.h", vertices[sorted[0]]); EXPECT_STREQ("libc/integral.h", vertices[sorted[1]]); EXPECT_STREQ("libc/keywords.h", vertices[sorted[2]]); EXPECT_STREQ("libc/macros-cpp.inc", vertices[sorted[3]]); EXPECT_STREQ("libc/macros.internal.h", vertices[sorted[4]]); EXPECT_STREQ("libc/intrin/bits.h", vertices[sorted[5]]); EXPECT_STREQ("libc/str/str.h", vertices[sorted[6]]); }
5,707
124
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/replacestr_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/mem/alg.h" #include "libc/mem/gc.h" #include "libc/testlib/testlib.h" TEST(_replacestr, demo) { EXPECT_STREQ("hello friends", _gc(_replacestr("hello world", "world", "friends"))); EXPECT_STREQ("bbbbbbbb", _gc(_replacestr("aaaa", "a", "bb"))); } TEST(_replacestr, emptyString) { EXPECT_STREQ("", _gc(_replacestr("", "x", "y"))); } TEST(_replacestr, emptyNeedle) { EXPECT_EQ(NULL, _gc(_replacestr("a", "", "a"))); EXPECT_EQ(EINVAL, errno); } TEST(_replacestr, needleInReplacement_doesntExplode) { EXPECT_STREQ("xxxxxxx", _gc(_replacestr("x", "x", "xxxxxxx"))); }
2,467
42
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/arraylist_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/libfatal.internal.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/testlib/testlib.h" struct string { size_t i, n; char *p; }; struct string16 { size_t i, n; char16_t *p; }; struct ArrayListInteger { size_t i, n; int *p; }; TEST(append, worksGreatForScalars) { char c = 'a'; struct string s; memset(&s, 0, sizeof(s)); for (size_t i = 0; i < 1024; ++i) { ASSERT_EQ(i, append(&s, &c)); } ASSERT_EQ(1024, s.i); for (size_t i = 0; i < s.i; ++i) ASSERT_EQ('a', s.p[i]); free(s.p); s.p = 0; } TEST(append, isGenericallyTyped) { int c = 0x31337; struct ArrayListInteger s; memset(&s, 0, sizeof(s)); for (size_t i = 0; i < 1024; ++i) { ASSERT_EQ(i, append(&s, &c)); } ASSERT_EQ(1024, s.i); ASSERT_GT(malloc_usable_size(s.p), 1024 * sizeof(int)); for (size_t i = 0; i < s.i; ++i) { ASSERT_EQ(0x31337, s.p[i]); } free(s.p); s.p = 0; } TEST(concat, worksGreatForStrings) { const char *ks = "Und wird die Welt auch in Flammen stehen\n" "Wir werden wieder auferstehen\n"; struct string s; memset(&s, 0, sizeof(s)); ASSERT_EQ(0, concat(&s, ks, strlen(ks))); ASSERT_EQ(strlen(ks), concat(&s, ks, strlen(ks) + 1)); ASSERT_STREQ("Und wird die Welt auch in Flammen stehen\n" "Wir werden wieder auferstehen\n" "Und wird die Welt auch in Flammen stehen\n" "Wir werden wieder auferstehen\n", s.p); ASSERT_EQ(strlen(ks) * 2 + 1, s.i); free(s.p); s.p = 0; } TEST(concat, isGenericallyTyped) { const char16_t *ks = u"Drum hoch die Fäuste, hoch zum Licht.\n" u"Unsere schwarzen Seelen bekommt ihr nicht.\n"; struct string16 s; memset(&s, 0, sizeof(s)); ASSERT_EQ(0, concat(&s, ks, strlen16(ks))); ASSERT_EQ(strlen16(ks), concat(&s, ks, strlen16(ks) + 1)); ASSERT_STREQ(u"Drum hoch die Fäuste, hoch zum Licht.\n" u"Unsere schwarzen Seelen bekommt ihr nicht.\n" u"Drum hoch die Fäuste, hoch zum Licht.\n" u"Unsere schwarzen Seelen bekommt ihr nicht.\n", s.p); ASSERT_EQ(strlen16(ks) * 2 + 1, s.i); free(s.p); s.p = 0; }
4,142
104
jart/cosmopolitan
false
cosmopolitan/test/libc/mem/realloc_in_place_test.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "libc/testlib/ezbench.h" #include "libc/testlib/testlib.h" TEST(realloc_in_place, test) { char *x = malloc(16); EXPECT_EQ(x, realloc_in_place(x, 0)); EXPECT_EQ(x, realloc_in_place(x, 1)); *x = 2; free(x); } BENCH(realloc_in_place, bench) { volatile int i = 1000; volatile char *x = malloc(i); EZBENCH2("malloc", donothing, free(malloc(i))); EZBENCH2("malloc", donothing, free(malloc(i))); EZBENCH2("memalign", donothing, free(memalign(16, i))); EZBENCH2("memalign", donothing, free(memalign(32, i))); EZBENCH2("realloc", donothing, x = realloc(x, --i)); EZBENCH2("realloc_in_place", donothing, realloc_in_place(x, --i)); free(x); }
2,567
43
jart/cosmopolitan
false