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/tool/decode/hex.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/stdio/stdio.h"
/**
* @fileoverview Binary to hex converter program.
*/
int main() {
int o;
while (0 <= (o = getchar()) && o <= 255) {
putchar("0123456789ABCDEF"[o / 16]);
putchar("0123456789ABCDEF"[o % 16]);
}
putchar('\n');
}
| 2,098 | 33 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/ar.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/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/log/check.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"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/x/x.h"
#define AR_MAGIC1 "!<arch>\n"
#define AR_MAGIC2 "`\n"
/**
* ar rU doge.a NOTICE # create archive and use non-deterministic stuff
* o//tool/decode/ar.com doge.a
*/
static int fd;
static uint8_t *data;
static long size;
static const char *path;
static struct stat st;
static void PrintString(uint8_t *p, long n, const char *name) {
char *s;
s = xmalloc(n + 1);
s[n] = '\0';
memcpy(s, p, n);
printf("\t.ascii\t%-`'*.*s# %s\n", 35, n, s, name);
free(s);
}
static void Open(void) {
if ((fd = open(path, O_RDONLY)) == -1) {
fprintf(stderr, "error: open() failed: %s\n", path);
exit(1);
}
CHECK_NE(-1, fstat(fd, &st));
if (!(size = st.st_size)) exit(0);
CHECK_NE(MAP_FAILED,
(data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0)));
LOGIFNEG1(close(fd));
}
static void Close(void) {
LOGIFNEG1(munmap(data, size));
}
static void Check(void) {
if (size < 8 + 60 + 4 ||
(memcmp(data, AR_MAGIC1, strlen(AR_MAGIC1)) != 0 ||
memcmp(data + 66, AR_MAGIC2, strlen(AR_MAGIC2)) != 0)) {
fprintf(stderr, "error: not a unix archive: %s\n", path);
exit(1);
}
}
static void PrintTable(void) {
}
static void PrintHeader(uint8_t *p) {
PrintString(p + 0, 16, "file identifier [ascii]");
PrintString(p + 16, 12, "file modification timestamp [decimal]");
PrintString(p + 28, 6, "owner id [decimal]");
PrintString(p + 34, 6, "group id [decimal]");
PrintString(p + 40, 8, "file mode [octal] (type and permission)");
PrintString(p + 48, 10, "file size in bytes [decimal]");
PrintString(p + 58, 2, "ending characters");
}
static void Print(void) {
int arsize;
uint64_t offset;
uint8_t *b, *p, *e;
uint32_t i, n, o, table, entries, symbols, symbolslen;
arsize = atoi((char *)(data + 8 + 48));
CHECK_LE(4, arsize);
CHECK_LE(8 + 60 + arsize, size);
entries = READ32BE(data + 8 + 60);
CHECK_LE(4 + entries * 4 + 1, arsize);
printf("\t# %'s\n", path);
PrintString(data, 8, "file signature");
PrintHeader(data + 8);
printf("\n");
printf("\t.long\t%-*.u# %s\n", 35, entries, "symbol table entries");
table = 8 + 60 + 4;
for (i = 0; i < entries; ++i) {
printf("\t.long\t%#-*.x# %u\n", 35, READ32BE(data + table + i * 4), i);
}
symbols = table + entries * 4;
symbolslen = arsize - (entries + 1) * 4;
for (i = o = 0; o < symbolslen; ++i, o += n + 1) {
b = data + symbols + o;
CHECK_NOTNULL((p = memchr(b, '\0', symbolslen - o)), "%p %p %p %p %`.s", b,
data, symbols, o, b);
n = p - b;
printf("\t.asciz\t%#-`'*.*s# %u\n", 35, n, b, i);
}
offset = 8 + 60 + arsize;
while (offset < size) {
offset += offset & 1;
CHECK_LE(offset + 60, size);
CHECK_EQ(0, memcmp(data + offset + 58, AR_MAGIC2, strlen(AR_MAGIC2)));
arsize = atoi((char *)(data + offset + 48));
CHECK_LE(offset + 60 + arsize, size);
printf("\n");
PrintHeader(data + offset);
offset += 60 + arsize;
}
}
int main(int argc, char *argv[]) {
if (argc < 2) return 1;
path = argv[1];
Open();
Check();
Print();
Close();
return 0;
}
| 5,328 | 147 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/macho.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/macho.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/str/tab.internal.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "tool/decode/lib/asmcodegen.h"
#include "tool/decode/lib/flagger.h"
#include "tool/decode/lib/machoidnames.h"
#include "tool/decode/lib/titlegen.h"
/**
* @fileoverview Apple Mach-O metadata disassembler.
*/
static const char *path;
static struct MachoHeader *macho;
static size_t machosize;
static void startfile(void) {
showtitle("αcϵαlly pδrÏαblε εxεcµÏαblε", "tool/decode/macho", NULL, NULL,
&kModelineAsm);
printf("#include \"libc/macho.internal.h\"\n\n", path);
}
static void showmachoheader(void) {
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if (sizeof(struct MachoHeader) > machosize) {
fprintf(stderr, "error: %'s: MachoHeader overruns eof\n", path);
exit(1);
}
#endif
showtitle(basename(path), "macho", "header", NULL, NULL);
printf("\n");
showinthex(macho->magic);
show(".long",
firstnonnull(findnamebyid(kMachoArchitectures, macho->arch),
format(b1, "%#x", macho->arch)),
"macho->arch");
showinthex(macho->arch2);
show(".long",
firstnonnull(findnamebyid(kMachoFileTypeNames, macho->filetype),
format(b1, "%#x", macho->filetype)),
"macho->filetype");
showinthex(macho->loadcount);
showinthex(macho->loadsize);
show(".long",
firstnonnull(RecreateFlags(kMachoFlagNames, macho->flags),
format(b1, "%#x", macho->flags)),
"macho->flags");
showinthex(macho->__reserved);
printf("\n");
}
static void showmachosection(struct MachoSection *section) {
show(".ascin", format(b1, "%`'s,16", section->name), "section->name");
show(".ascin", format(b1, "%`'s,16", section->commandname),
"section->commandname");
showint64hex(section->vaddr);
showint64hex(section->memsz);
showinthex(section->offset);
showinthex(section->alignlog2);
showinthex(section->relotaboff);
showinthex(section->relocount);
showinthex(section->attr);
show(".long",
format(b1, "%d,%d,%d", section->__reserved[0], section->__reserved[1],
section->__reserved[2]),
"section->__reserved");
}
static void showmacholoadsegment(unsigned i, struct MachoLoadSegment *loadseg) {
assert(loadseg->size ==
sizeof(struct MachoLoadSegment) +
loadseg->sectioncount * sizeof(struct MachoSection));
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if ((intptr_t)loadseg + sizeof(struct MachoLoadSegment) +
loadseg->sectioncount * sizeof(struct MachoSection) >
(intptr_t)macho + machosize) {
abort();
}
#endif
show(".ascin", format(b1, "%`'s,16", loadseg->name), "loadseg->name");
showint64hex(loadseg->vaddr);
showint64hex(loadseg->memsz);
showint64hex(loadseg->offset);
showint64hex(loadseg->filesz);
show(".long",
firstnonnull(RecreateFlags(kMachoVmProtNames, loadseg->maxprot),
format(b1, "%#x", loadseg->maxprot)),
"loadseg->maxprot");
show(".long",
firstnonnull(RecreateFlags(kMachoVmProtNames, loadseg->initprot),
format(b1, "%#x", loadseg->initprot)),
"loadseg->initprot");
showinthex(loadseg->sectioncount);
show(".long",
firstnonnull(RecreateFlags(kMachoSegmentFlagNames, loadseg->flags),
format(b1, "%#x", loadseg->flags)),
"loadseg->flags");
for (unsigned j = 0; j < loadseg->sectioncount; ++j) {
printf("%d:", (i + 1) * 100 + (j + 1) * 10);
showmachosection((struct MachoSection *)((intptr_t)loadseg +
sizeof(struct MachoLoadSegment) +
j * sizeof(struct MachoSection)));
}
}
static void showmacholoadsymtabshowall(struct MachoLoadSymtab *ls) {
assert(ls->size == sizeof(struct MachoLoadSymtab));
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if ((intptr_t)ls + sizeof(struct MachoLoadSymtab) >
(intptr_t)macho + machosize) {
abort();
}
#endif
showinthex(ls->offset);
showinthex(ls->count);
showinthex(ls->stroff);
showinthex(ls->strsize);
}
static void showmacholoaduuid(struct MachoLoadUuid *lu) {
assert(lu->size == sizeof(struct MachoLoadUuid));
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if ((intptr_t)lu + sizeof(struct MachoLoadUuid) >
(intptr_t)macho + machosize) {
abort();
}
#endif
printf("\t.byte\t");
for (unsigned i = 0; i < 16; ++i) {
if (i) {
if (i == 8) {
printf("\n\t.byte\t");
} else {
printf(",");
}
}
printf("%#02hhx", lu->uuid[i]);
}
printf("\n");
}
#define COLS 8
static void showmacholoadgeneric(struct MachoLoadCommand *lc) {
int i, c, col = 0;
int need_newline = 0;
char16_t glyphs[COLS + 1];
const unsigned char *p, *pe;
p = (const unsigned char *)(lc + 1);
pe = p + (lc->size - sizeof(*lc));
while (p < pe) {
c = *p++;
if (!col) {
need_newline = 1;
printf("\t.byte\t");
bzero(glyphs, sizeof(glyphs));
}
glyphs[col] = kCp437[c];
if (col) putchar(',');
printf("0x%02x", c);
if (++col == COLS) {
col = 0;
printf("\t//%hs\n", glyphs);
need_newline = 0;
}
}
if (need_newline) {
printf("\n");
}
}
static void showmacholoadsourceversion(
struct MachoLoadSourceVersionCommand *sv) {
assert(sv->size == sizeof(struct MachoLoadSourceVersionCommand));
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if ((intptr_t)sv + sizeof(struct MachoLoadSourceVersionCommand) >
(intptr_t)macho + machosize) {
abort();
}
#endif
showint64hex(sv->version);
}
static void showmacholoadunixthread(struct MachoLoadThreadCommand *lc) {
assert(lc->size == 4 + 4 + 4 + 4 + lc->count * 4);
showinthex(lc->flavor);
showint(lc->count);
for (unsigned i = 0; i < lc->count; ++i) {
showinthex(lc->wut[i]);
}
}
static void showmacholoadcommand(struct MachoLoadCommand *lc, unsigned i) {
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if ((intptr_t)lc > (intptr_t)macho + machosize ||
(intptr_t)lc + lc->size > (intptr_t)macho + machosize) {
abort();
}
#endif
showorg((intptr_t)lc - (intptr_t)macho);
printf("%d:", (i + 1) * 10);
char buf[256];
buf[0] = 0;
const char *name;
uint32_t command = lc->command;
if (!(name = findnamebyid(kMachoLoadCommandNames, command)) &&
(command & MAC_LC_REQ_DYLD)) {
command &= ~MAC_LC_REQ_DYLD;
strcpy(buf, "MAC_LC_REQ_DYLD|");
name = findnamebyid(kMachoLoadCommandNames, command);
}
if (name) {
strlcat(buf, name, sizeof(buf));
} else {
strlcat(buf, format(b1, "%#x", command), sizeof(buf));
}
show(".long", buf, "lc->command");
showinthex(lc->size);
switch (lc->command) {
case MAC_LC_SEGMENT_64:
showmacholoadsegment(i, (struct MachoLoadSegment *)lc);
break;
case MAC_LC_SYMTAB:
showmacholoadsymtabshowall((struct MachoLoadSymtab *)lc);
break;
case MAC_LC_UUID:
showmacholoaduuid((struct MachoLoadUuid *)lc);
break;
#if 0
case MAC_LC_SOURCE_VERSION:
showmacholoadsourceversion((struct MachoLoadSourceVersionCommand *)lc);
break;
#endif
case MAC_LC_UNIXTHREAD:
showmacholoadunixthread((struct MachoLoadThreadCommand *)lc);
break;
case MAC_LC_DYLD_INFO:
case MAC_LC_DYLD_INFO_ONLY: {
const struct MachoDyldInfoCommand *di =
(const struct MachoDyldInfoCommand *)lc;
showinthex(di->rebase_off);
showinthex(di->rebase_size);
showinthex(di->bind_off);
showinthex(di->bind_size);
showinthex(di->weak_bind_off);
showinthex(di->weak_bind_size);
showinthex(di->lazy_bind_off);
showinthex(di->lazy_bind_size);
showinthex(di->export_off);
showinthex(di->export_size);
break;
}
case MAC_LC_CODE_SIGNATURE:
case MAC_LC_SEGMENT_SPLIT_INFO:
case MAC_LC_FUNCTION_STARTS:
case MAC_LC_DATA_IN_CODE:
case MAC_LC_DYLIB_CODE_SIGN_DRS:
case MAC_LC_LINKER_OPTIMIZATION_HINT:
case MAC_LC_DYLD_EXPORTS_TRIE:
case MAC_LC_DYLD_CHAINED_FIXUPS: {
const struct MachoLinkeditDataCommand *ld =
(const struct MachoLinkeditDataCommand *)lc;
showint64hex(ld->dataoff);
showint64hex(ld->datasize);
break;
}
case MAC_LC_MAIN: {
const struct MachoEntryPointCommand *main =
(const struct MachoEntryPointCommand *)lc;
showint64hex(main->entryoff);
showint64hex(main->stacksize);
break;
}
default:
showmacholoadgeneric(lc);
break;
}
printf("\n");
}
static void showmacholoadcommands(void) {
#if !defined(TRUSTWORTHY) && !defined(MACHO_TRUSTWORTHY)
if (sizeof(struct MachoHeader) + macho->loadsize > machosize) {
fprintf(stderr, "error: %'s: macho->loadsize overruns eof\n", path);
exit(1);
}
#endif
unsigned i = 0;
const unsigned count = macho->loadcount;
for (struct MachoLoadCommand *lc =
(void *)((intptr_t)macho + sizeof(struct MachoHeader));
i < count; ++i, lc = (void *)((intptr_t)lc + lc->size)) {
showmacholoadcommand(lc, i);
}
}
void showall(void) {
startfile();
showmachoheader();
showmacholoadcommands();
}
int main(int argc, char *argv[]) {
int64_t fd;
struct stat st[1];
if (argc != 2) fprintf(stderr, "usage: %s FILE\n", argv[0]), exit(1);
if ((fd = open((path = argv[1]), O_RDONLY)) == -1 || fstat(fd, st) == -1 ||
(macho = mmap(NULL, (machosize = st->st_size), PROT_READ, MAP_SHARED, fd,
0)) == MAP_FAILED) {
fprintf(stderr, "error: %'s %m\n", path);
exit(1);
}
if (macho->magic != 0xFEEDFACF) {
fprintf(stderr, "error: %'s not a macho x64 executable\n", path);
exit(1);
}
showall();
munmap(macho, machosize);
close(fd);
return 0;
}
| 12,045 | 350 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/zip2.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/x/xasprintf.h"
#include "libc/x/xiso8601.h"
#include "libc/zip.h"
#include "tool/decode/lib/asmcodegen.h"
#include "tool/decode/lib/disassemblehex.h"
#include "tool/decode/lib/zipnames.h"
char *FormatDosDate(uint16_t dosdate) {
return xasprintf("%04u-%02u-%02u", ((dosdate >> 9) & 0b1111111) + 1980,
(dosdate >> 5) & 0b1111, dosdate & 0b11111);
}
char *FormatDosTime(uint16_t dostime) {
return xasprintf("%02u:%02u:%02u", (dostime >> 11) & 0b11111,
(dostime >> 5) & 0b111111, (dostime << 1) & 0b111110);
}
void ShowGeneralFlag(uint16_t generalflag) {
puts("\
/ ââutf8\n\
/ â ââstrong encryption\n\
/ â âââcompressed patch data\n\
/ â ââ ââcrc and size go after file content\n\
/ â ââ âââ{normal,max,fast,superfast}\n\
/ â ââ ââ ââencrypted\n\
/ rrrrâuuuuâârââââ");
show(".short", format(b1, "0b%016b", generalflag), "generalflag");
}
void ShowCompressionMethod(uint16_t compressmethod) {
show(".short",
firstnonnull(findnamebyid(kZipCompressionNames, compressmethod),
format(b1, "%hu", compressmethod)),
"compressionmethod");
}
void ShowTimestamp(uint16_t time, uint16_t date) {
show(".short", format(b1, "%#04hx", time),
_gc(xasprintf("%s (%s)", "lastmodifiedtime", _gc(FormatDosTime(time)))));
show(".short", format(b1, "%#04hx", date),
_gc(xasprintf("%s (%s)", "lastmodifieddate", _gc(FormatDosDate(date)))));
}
void ShowNtfs(uint8_t *ntfs, size_t n) {
struct timespec mtime, atime, ctime;
mtime = WindowsTimeToTimeSpec(READ64LE(ntfs + 8));
atime = WindowsTimeToTimeSpec(READ64LE(ntfs + 16));
ctime = WindowsTimeToTimeSpec(READ64LE(ntfs + 24));
show(".long", _gc(xasprintf("%d", READ32LE(ntfs))), "ntfs reserved");
show(".short", _gc(xasprintf("0x%04x", READ16LE(ntfs + 4))),
"ntfs attribute tag value #1");
show(".short", _gc(xasprintf("%hu", READ16LE(ntfs + 6))),
"ntfs attribute tag size");
show(".quad", _gc(xasprintf("%lu", READ64LE(ntfs + 8))),
_gc(xasprintf("%s (%s)", "ntfs last modified time",
_gc(xiso8601(&mtime)))));
show(".quad", _gc(xasprintf("%lu", READ64LE(ntfs + 16))),
_gc(xasprintf("%s (%s)", "ntfs last access time",
_gc(xiso8601(&atime)))));
show(".quad", _gc(xasprintf("%lu", READ64LE(ntfs + 24))),
_gc(xasprintf("%s (%s)", "ntfs creation time", _gc(xiso8601(&ctime)))));
}
void ShowExtendedTimestamp(uint8_t *p, size_t n, bool islocal) {
int flag;
if (n) {
--n;
flag = *p++;
show(".byte", _gc(xasprintf("0b%03hhb", flag)), "fields present in local");
if ((flag & 1) && n >= 4) {
show(".long", _gc(xasprintf("%u", READ32LE(p))),
_gc(xasprintf("%s (%s)", "last modified",
_gc(xiso8601(&(struct timespec){READ32LE(p)})))));
p += 4;
n -= 4;
}
flag >>= 1;
if (islocal) {
if ((flag & 1) && n >= 4) {
show(".long", _gc(xasprintf("%u", READ32LE(p))),
_gc(xasprintf("%s (%s)", "access time",
_gc(xiso8601(&(struct timespec){READ32LE(p)})))));
p += 4;
n -= 4;
}
flag >>= 1;
if ((flag & 1) && n >= 4) {
show(".long", _gc(xasprintf("%u", READ32LE(p))),
_gc(xasprintf("%s (%s)", "creation time",
_gc(xiso8601(&(struct timespec){READ32LE(p)})))));
p += 4;
n -= 4;
}
}
}
}
void ShowZip64(uint8_t *p, size_t n, bool islocal) {
if (n >= 8) {
show(".quad", _gc(xasprintf("%lu", READ64LE(p))),
_gc(xasprintf("uncompressed size (%,ld)", READ64LE(p))));
}
if (n >= 16) {
show(".quad", _gc(xasprintf("%lu", READ64LE(p + 8))),
_gc(xasprintf("compressed size (%,ld)", READ64LE(p + 8))));
}
if (n >= 24) {
show(".quad", _gc(xasprintf("%lu", READ64LE(p + 16))),
_gc(xasprintf("lfile hdr offset (%,ld)", READ64LE(p + 16))));
}
if (n >= 28) {
show(".long", _gc(xasprintf("%u", READ32LE(p + 24))), "disk number");
}
}
void ShowInfoZipNewUnixExtra(uint8_t *p, size_t n, bool islocal) {
if (p[0] == 1 && p[1] == 4 && p[6] == 4) {
show(".byte", "1", "version");
show(".byte", "4", "uid length");
show(".long", _gc(xasprintf("%u", READ32LE(p + 2))), "uid");
show(".byte", "4", "gid length");
show(".long", _gc(xasprintf("%u", READ32LE(p + 7))), "gid");
} else {
disassemblehex(p, n, stdout);
}
}
void ShowExtra(uint8_t *extra, bool islocal) {
switch (ZIP_EXTRA_HEADERID(extra)) {
case kZipExtraNtfs:
ShowNtfs(ZIP_EXTRA_CONTENT(extra), ZIP_EXTRA_CONTENTSIZE(extra));
break;
case kZipExtraExtendedTimestamp:
ShowExtendedTimestamp(ZIP_EXTRA_CONTENT(extra),
ZIP_EXTRA_CONTENTSIZE(extra), islocal);
break;
case kZipExtraZip64:
ShowZip64(ZIP_EXTRA_CONTENT(extra), ZIP_EXTRA_CONTENTSIZE(extra),
islocal);
break;
case kZipExtraInfoZipNewUnixExtra:
ShowInfoZipNewUnixExtra(ZIP_EXTRA_CONTENT(extra),
ZIP_EXTRA_CONTENTSIZE(extra), islocal);
break;
default:
disassemblehex(ZIP_EXTRA_CONTENT(extra), ZIP_EXTRA_CONTENTSIZE(extra),
stdout);
break;
}
}
void ShowExtras(uint8_t *extras, uint16_t extrassize, bool islocal) {
int i;
bool first;
uint8_t *p, *pe;
if (extrassize) {
first = true;
for (p = extras, pe = extras + extrassize, i = 0; p < pe;
p += ZIP_EXTRA_SIZE(p), ++i) {
show(".short",
firstnonnull(findnamebyid(kZipExtraNames, ZIP_EXTRA_HEADERID(p)),
_gc(xasprintf("0x%04hx", ZIP_EXTRA_HEADERID(p)))),
_gc(xasprintf("%s[%d].%s", "extras", i, "headerid")));
show(".short", _gc(xasprintf("%df-%df", (i + 2) * 10, (i + 1) * 10)),
_gc(xasprintf("%s[%d].%s (%hd %s)", "extras", i, "contentsize",
ZIP_EXTRA_CONTENTSIZE(p), "bytes")));
if (first) {
first = false;
printf("%d:", (i + 1) * 10);
}
ShowExtra(p, islocal);
printf("%d:", (i + 2) * 10);
}
}
putchar('\n');
}
void ShowLocalFileHeader(uint8_t *lf, uint16_t idx) {
printf("\n/\t%s #%hu (%zu %s)\n", "local file", idx + 1,
ZIP_LFILE_HDRSIZE(lf), "bytes");
show(".ascii", format(b1, "%`'.*s", 4, lf), "magic");
show(".byte",
firstnonnull(findnamebyid(kZipEraNames, ZIP_LFILE_VERSIONNEED(lf)),
_gc(xasprintf("%d", ZIP_LFILE_VERSIONNEED(lf)))),
"pkzip version need");
show(".byte",
firstnonnull(findnamebyid(kZipOsNames, ZIP_LFILE_OSNEED(lf)),
_gc(xasprintf("%d", ZIP_LFILE_OSNEED(lf)))),
"os need");
ShowGeneralFlag(ZIP_LFILE_GENERALFLAG(lf));
ShowCompressionMethod(ZIP_LFILE_COMPRESSIONMETHOD(lf));
ShowTimestamp(ZIP_LFILE_LASTMODIFIEDTIME(lf), ZIP_LFILE_LASTMODIFIEDDATE(lf));
show(
".long",
format(b1, "%#x", ZIP_LFILE_CRC32(lf)), _gc(xasprintf("%s (%#x)", "crc32z", GetZipLfileCompressedSize(lf) /* crc32_z(0, ZIP_LFILE_CONTENT(lf), GetZipLfileCompressedSize(lf)) */)));
if (ZIP_LFILE_COMPRESSEDSIZE(lf) == 0xFFFFFFFF) {
show(".long", "0xFFFFFFFF", "compressedsize (zip64)");
} else {
show(".long", "3f-2f",
format(b1, "%s (%u %s)", "compressedsize",
ZIP_LFILE_COMPRESSEDSIZE(lf), "bytes"));
}
show(".long",
ZIP_LFILE_UNCOMPRESSEDSIZE(lf) == 0xFFFFFFFF
? "0xFFFFFFFF"
: format(b1, "%u", ZIP_LFILE_UNCOMPRESSEDSIZE(lf)),
"uncompressedsize");
show(".short", "1f-0f",
format(b1, "%s (%hu %s)", "namesize", ZIP_LFILE_NAMESIZE(lf), "bytes"));
show(
".short", "2f-1f",
format(b1, "%s (%hu %s)", "extrasize", ZIP_LFILE_EXTRASIZE(lf), "bytes"));
printf("0:");
show(".ascii",
format(b1, "%`'s",
_gc(strndup(ZIP_LFILE_NAME(lf), ZIP_LFILE_NAMESIZE(lf)))),
"name");
printf("1:");
ShowExtras(ZIP_LFILE_EXTRA(lf), ZIP_LFILE_EXTRASIZE(lf), true);
printf("2:");
disassemblehex(ZIP_LFILE_CONTENT(lf), ZIP_LFILE_COMPRESSEDSIZE(lf), stdout);
printf("3:\n");
}
void DisassembleZip(const char *path, uint8_t *p, size_t n) {
size_t i, records;
uint8_t *eocd, *cdir, *cf, *lf;
CHECK_NOTNULL((eocd = GetZipCdir(p, n)));
records = GetZipCdirRecords(eocd);
cdir = p + GetZipCdirOffset(eocd);
for (i = 0, cf = cdir; i < records; ++i, cf += ZIP_CFILE_HDRSIZE(cf)) {
CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(cf));
lf = p + GetZipCfileOffset(cf);
CHECK_EQ(kZipLfileHdrMagic, ZIP_LFILE_MAGIC(lf));
ShowLocalFileHeader(lf, i);
}
}
int main(int argc, char *argv[]) {
int fd;
uint8_t *map;
struct stat st;
ShowCrashReports();
CHECK_EQ(2, argc);
CHECK_NE(-1, (fd = open(argv[1], O_RDONLY)));
CHECK_NE(-1, fstat(fd, &st));
CHECK_GE(st.st_size, kZipCdirHdrMinSize);
CHECK_NE(MAP_FAILED,
(map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)));
DisassembleZip(argv[1], map, st.st_size);
CHECK_NE(-1, munmap(map, st.st_size));
CHECK_NE(-1, close(fd));
return 0;
}
| 11,488 | 285 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/mkcombos.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/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.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 "libc/sysv/consts/fileno.h"
#include "third_party/getopt/getopt.h"
#include "third_party/zlib/zlib.h"
#include "tool/decode/lib/bitabuilder.h"
static size_t linecap;
static FILE *fin, *fout;
static uint32_t bit, maxbit;
static struct BitaBuilder *bitset;
static char *line, *tok, *s1, *category, *g_inpath, *g_outpath;
wontreturn void ShowUsage(FILE *f, int rc) {
fprintf(f, "Usage: %s [-o OUTPUT] [INPUT]\n", "Usage",
program_invocation_name);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
g_inpath = "/dev/stdin";
g_outpath = "/dev/stdout";
while ((opt = getopt(argc, argv, "?ho:")) != -1) {
switch (opt) {
case 'o':
g_outpath = optarg;
break;
case 'h':
case '?':
ShowUsage(stdout, EXIT_SUCCESS);
default:
ShowUsage(stderr, EX_USAGE);
}
}
if (argc - optind) {
g_inpath = argv[optind];
}
}
/**
* Builds sparse unicode dataset for combining codepoints, e.g.
*
* UNDERLINING
*
* - COMBINING MACRON BELOW U+0331 (\xCC\xB1)
* e.g. A̱ḆC̱Ḏ (too short) 41CCB1 42CCB1 43CCB1 44CCB1
*
* - COMBINING DOUBLE MACRON BELOW U+035F (\xCD\x9F)
* e.g. AÍBÍCÍDÍ (too long) 41CD9F 42CD9F 43CD9F 44CD9F
*
* - DOUBLE PLUS COMBINING MACRON BELOW 3ÃU+035F + 1ÃU+0331
* e.g. AÍBÍCÍḎ (just right) 41CCB1 42CCB1 43CCB1 44CD9F
*
* STRIKETHROUGH
*
* - COMBINING LONG STROKE OVERLAY U+0336 (\xCC\xB6)
* e.g. A̶B̶C̶D̶ 41CCB6 42CCB6 43CCB6 44CCB6
*
* - COMBINING SHORT STROKE OVERLAY U+0335 (\xCC\xB5)
* e.g. A̵B̵C̵D̵ 41CCB5 42CCB5 43CCB5 44CCB5
*
* - COMBINING SHORT SOLIDUS OVERLAY U+0337 (\xCC\xB7)
* e.g. AÌ·BÌ·CÌ·DÌ· 41CCB7 42CCB7 43CCB7 44CCB7
*
* - COMBINING LONG SOLIDUS OVERLAY U+0338 (\xCC\xB8)
* e.g. A̸B̸C̸D̸ 41CCB8 42CCB8 43CCB8 44CCB8
*
* @see unicode.org/reports/tr11/#Definitions
* @see https://www.compart.com/en/unicode/category/Sk (Modifier Symbol)
*/
int main(int argc, char *argv[]) {
GetOpts(argc, argv);
CHECK_NOTNULL(fin = fopen(g_inpath, "r"));
bitset = bitabuilder_new();
while ((getline(&line, &linecap, fin)) != -1) {
tok = line;
s1 = strsep(&tok, ";");
strsep(&tok, ";");
category = strsep(&tok, ";");
if (!s1 || !category) continue;
bit = strtol(s1, NULL, 16);
if (bit != 0x00AD &&
((0x1160 <= bit && bit <= 0x11FF) ||
(strcmp(category, "Me") == 0 || strcmp(category, "Mn") == 0 ||
strcmp(category, "Cf") == 0))) {
maxbit = max(bit, maxbit);
CHECK(bitabuilder_setbit(bitset, bit));
}
}
CHECK_NOTNULL(fout = fopen(g_outpath, "wb"));
CHECK(bitabuilder_fwrite(bitset, fout));
bitabuilder_free(&bitset);
return fclose(fin) | fclose(fout);
}
| 5,100 | 122 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/elf.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/elf/elf.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/elf/def.h"
#include "libc/elf/struct/rela.h"
#include "libc/elf/struct/shdr.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/auxv.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/x/xasprintf.h"
#include "tool/decode/lib/asmcodegen.h"
#include "tool/decode/lib/elfidnames.h"
#include "tool/decode/lib/flagger.h"
#include "tool/decode/lib/titlegen.h"
/**
* @fileoverview ELF executable metadata disassembler.
*/
static const char *path;
static struct stat st[1];
static Elf64_Ehdr *elf;
static void startfile(void) {
showtitle("αcϵαlly pδrÏαblε εxεcµÏαblε", "tool/decode/elf", basename(path),
NULL, &kModelineAsm);
printf("#include \"libc/elf.h\"\n\n", path);
}
static void printelfehdr(void) {
show(".ascii", format(b1, "%`'.*s", 4, (const char *)&elf->e_ident[0]),
"magic");
show(".byte",
firstnonnull(findnamebyid(&kElfClassNames[0], elf->e_ident[EI_CLASS]),
format(b1, "%d", elf->e_ident[EI_CLASS])),
"elf->e_ident[EI_CLASS]");
show(".byte",
firstnonnull(findnamebyid(kElfDataNames, elf->e_ident[EI_DATA]),
format(b1, "%d", elf->e_ident[EI_DATA])),
"elf->e_ident[EI_DATA]");
show(".byte", format(b1, "%d", elf->e_ident[EI_VERSION]),
"elf->e_ident[EI_VERSION]");
show(".byte",
firstnonnull(findnamebyid(kElfOsabiNames, elf->e_ident[EI_OSABI]),
format(b1, "%d", elf->e_ident[EI_OSABI])),
"elf->e_ident[EI_OSABI]");
show(".byte", format(b1, "%d", elf->e_ident[EI_ABIVERSION]),
"elf->e_ident[EI_ABIVERSION]");
show(".byte",
format(b1, "%d,%d,%d,%d,%d,%d,%d", elf->e_ident[EI_PAD + 0],
elf->e_ident[EI_PAD + 1], elf->e_ident[EI_PAD + 2],
elf->e_ident[EI_PAD + 3], elf->e_ident[EI_PAD + 4],
elf->e_ident[EI_PAD + 5], elf->e_ident[EI_PAD + 6]),
"padding");
show(".org", "0x10", NULL);
show(".short",
firstnonnull(findnamebyid(kElfTypeNames, elf->e_type),
format(b1, "%hd", elf->e_type)),
"elf->e_type");
show(".short",
firstnonnull(findnamebyid(kElfMachineNames, elf->e_machine),
format(b1, "%hd", elf->e_machine)),
"elf->e_machine");
show(".long", format(b1, "%d", elf->e_version), "elf->e_version");
show(".quad", format(b1, "%#x", elf->e_entry), "elf->e_entry");
show(".quad", format(b1, "%#x", elf->e_phoff), "elf->e_phoff");
show(".quad", format(b1, "%#x", elf->e_shoff), "elf->e_shoff");
show(".long", format(b1, "%#x", elf->e_flags), "elf->e_flags");
show(".short", format(b1, "%hd", elf->e_ehsize), "elf->e_ehsize");
show(".short", format(b1, "%hd", elf->e_phentsize), "elf->e_phentsize");
show(".short", format(b1, "%hd", elf->e_phnum), "elf->e_phnum");
show(".short", format(b1, "%hd", elf->e_shentsize), "elf->e_shentsize");
show(".short", format(b1, "%hd", elf->e_shnum), "elf->e_shnum");
show(".short", format(b1, "%hd", elf->e_shstrndx), "elf->e_shstrndx");
}
static void printelfsegmentheader(int i) {
Elf64_Phdr *phdr = GetElfSegmentHeaderAddress(elf, st->st_size, i);
printf("/\tElf64_Phdr *phdr = GetElfSegmentHeaderAddress(elf, st->st_size, "
"%d)\n",
i);
printf(".Lph%d:", i);
show(".long",
firstnonnull(findnamebyid(kElfSegmentTypeNames, phdr->p_type),
format(b1, "%#x", phdr->p_type)),
"phdr->p_type");
show(".long", RecreateFlags(kElfSegmentFlagNames, phdr->p_flags),
"phdr->p_flags");
show(".quad", format(b1, "%#x", phdr->p_offset), "phdr->p_offset");
show(".quad", format(b1, "%#x", phdr->p_vaddr), "phdr->p_vaddr");
show(".quad", format(b1, "%#x", phdr->p_paddr), "phdr->p_paddr");
show(".quad", format(b1, "%#x", phdr->p_filesz), "phdr->p_filesz");
show(".quad", format(b1, "%#x", phdr->p_memsz), "phdr->p_memsz");
show(".quad", format(b1, "%#x", phdr->p_align), "phdr->p_align");
fflush(stdout);
}
static void printelfsegmentheaders(void) {
printf("\n");
printf("\t.org\t%#x\n", elf->e_phoff);
for (unsigned i = 0; i < elf->e_phnum; ++i) printelfsegmentheader(i);
}
static void printelfsectionheader(int i, char *shstrtab) {
Elf64_Shdr *shdr;
shdr = GetElfSectionHeaderAddress(elf, st->st_size, i);
printf("/\tElf64_Shdr *shdr = GetElfSectionHeaderAddress(elf, st->st_size, "
"%d)\n",
i);
printf(".Lsh%d:", i);
show(".long", format(b1, "%d", shdr->sh_name),
format(b2,
"%`'s == GetElfString(elf, st->st_size, shstrtab, shdr->sh_name)",
GetElfString(elf, st->st_size, shstrtab, shdr->sh_name)));
show(".long",
firstnonnull(findnamebyid(kElfSectionTypeNames, shdr->sh_type),
format(b1, "%d", shdr->sh_type)),
"shdr->sh_type");
show(".long", RecreateFlags(kElfSectionFlagNames, shdr->sh_flags),
"shdr->sh_flags");
show(".quad", format(b1, "%#x", shdr->sh_addr), "shdr->sh_addr");
show(".quad", format(b1, "%#x", shdr->sh_offset), "shdr->sh_offset");
show(".quad", format(b1, "%#x", shdr->sh_size), "shdr->sh_size");
show(".long", format(b1, "%#x", shdr->sh_link), "shdr->sh_link");
show(".long", format(b1, "%#x", shdr->sh_info), "shdr->sh_info");
show(".quad", format(b1, "%#x", shdr->sh_addralign), "shdr->sh_addralign");
show(".quad", format(b1, "%#x", shdr->sh_entsize), "shdr->sh_entsize");
fflush(stdout);
}
static void printelfsectionheaders(void) {
Elf64_Half i;
char *shstrtab;
shstrtab = GetElfSectionNameStringTable(elf, st->st_size);
if (shstrtab) {
printf("\n");
printf("\t.org\t%#x\n", elf->e_shoff);
for (i = 0; i < elf->e_shnum; ++i) {
printelfsectionheader(i, shstrtab);
}
printf("\n/\t%s\n", "elf->e_shstrndx");
printf("\t.org\t%#x\n",
GetElfSectionHeaderAddress(elf, st->st_size, elf->e_shstrndx)
->sh_offset);
for (i = 0; i < elf->e_shnum; ++i) {
Elf64_Shdr *shdr = GetElfSectionHeaderAddress(elf, st->st_size, i);
const char *str = GetElfString(elf, st->st_size, shstrtab, shdr->sh_name);
show(".asciz", format(b1, "%`'s", str), NULL);
}
}
}
static void printelfgroups(void) {
for (int i = 0; i < elf->e_shnum; ++i) {
Elf64_Shdr *shdr = GetElfSectionHeaderAddress(elf, st->st_size, i);
if (shdr->sh_type == SHT_GROUP) {
const Elf64_Shdr *symhdr =
GetElfSectionHeaderAddress(elf, st->st_size, shdr->sh_link);
const Elf64_Shdr *strhdr =
GetElfSectionHeaderAddress(elf, st->st_size, symhdr->sh_link);
Elf64_Sym *syms = GetElfSectionAddress(elf, st->st_size, symhdr);
char *strs = GetElfSectionAddress(elf, st->st_size, strhdr);
printf("\n");
printf("//\t%s group\n",
GetElfString(elf, st->st_size, strs, syms[shdr->sh_info].st_name));
printf("\t.org\t%#x\n", shdr->sh_offset);
bool first = true;
for (char *p = (char *)elf + shdr->sh_offset;
p < (char *)elf + shdr->sh_offset + shdr->sh_size; p += 4) {
if (first) {
first = false;
if (READ32LE(p) == GRP_COMDAT) {
printf("\t.long\tGRP_COMDAT\n");
continue;
}
}
const Elf64_Shdr *section =
GetElfSectionHeaderAddress(elf, st->st_size, READ32LE(p));
printf("\t.long\t%#x\t\t\t# %s\n", READ32LE(p),
GetElfString(elf, st->st_size,
GetElfSectionNameStringTable(elf, st->st_size),
section->sh_name));
}
shdr->sh_offset;
}
}
}
static void printelfsymbolinfo(Elf64_Sym *sym) {
int bind = (sym->st_info >> 4) & 0xf;
const char *bindname = findnamebyid(kElfSymbolBindNames, bind);
int type = (sym->st_info >> 0) & 0xf;
const char *typename = findnamebyid(kElfSymbolTypeNames, type);
show(".byte",
format(b1, "%s%s%s", bindname ? format(b2, "%s<<4", bindname) : "",
bindname && typename ? "|" : "", firstnonnull(typename, "")),
"sym->st_info");
}
static void printelfsymbolother(Elf64_Sym *sym) {
int visibility = sym->st_other & 0x3;
const char *visibilityname =
findnamebyid(kElfSymbolVisibilityNames, visibility);
int other = sym->st_other & ~0x3;
show(".byte",
format(b1, "%s%s%s", firstnonnull(visibilityname, ""),
other && visibilityname ? "+" : "",
other ? format(b2, "%d", other) : ""),
"sym->st_other");
}
static void printelfsymbol(Elf64_Sym *sym, char *strtab, char *shstrtab) {
show(".long", format(b1, "%d", sym->st_name),
format(b2, "%`'s (sym->st_name)",
GetElfString(elf, st->st_size, strtab, sym->st_name)));
printelfsymbolinfo(sym);
printelfsymbolother(sym);
show(".short", format(b1, "%d", sym->st_shndx),
format(b2, "%s sym->st_shndx",
sym->st_shndx < 0xff00
? format(b1, "%`'s",
GetElfString(elf, st->st_size, shstrtab,
GetElfSectionHeaderAddress(
elf, st->st_size, sym->st_shndx)
->sh_name))
: findnamebyid(kElfSpecialSectionNames, sym->st_shndx)));
show(".quad", format(b1, "%#x", sym->st_value), "sym->st_value");
show(".quad", format(b1, "%#x", sym->st_size), "sym->st_size");
}
static void printelfsymboltable(void) {
size_t i, symcount = 0;
Elf64_Sym *symtab = GetElfSymbolTable(elf, st->st_size, &symcount);
char *strtab = GetElfStringTable(elf, st->st_size);
char *shstrtab = GetElfSectionNameStringTable(elf, st->st_size);
if (symtab && strtab) {
printf("\n\n");
printf("\t.org\t%#x\n", (intptr_t)symtab - (intptr_t)elf);
for (i = 0; i < symcount; ++i) {
printf(".Lsym%d:\n", i);
printelfsymbol(&symtab[i], strtab, shstrtab);
}
}
}
static void printelfdynsymboltable(void) {
size_t i, symcount = 0;
Elf64_Sym *symtab = GetElfDynSymbolTable(elf, st->st_size, &symcount);
char *strtab = GetElfDynStringTable(elf, st->st_size);
char *shstrtab = GetElfSectionNameStringTable(elf, st->st_size);
if (symtab && strtab) {
printf("\n\n");
printf("\t.org\t%#x\n", (intptr_t)symtab - (intptr_t)elf);
for (i = 0; i < symcount; ++i) {
printf(".Lsym%d:\n", i);
printelfsymbol(&symtab[i], strtab, shstrtab);
}
}
}
static char *getelfsymbolname(const Elf64_Ehdr *elf, size_t mapsize,
const char *strtab, const char *shstrtab,
const Elf64_Sym *sym) {
char *res;
const Elf64_Shdr *shdr;
if (elf && sym &&
((shstrtab && !sym->st_name &&
ELF64_ST_TYPE(sym->st_info) == STT_SECTION &&
(shdr = GetElfSectionHeaderAddress(elf, mapsize, sym->st_shndx)) &&
(res = GetElfString(elf, mapsize, shstrtab, shdr->sh_name))) ||
(strtab && (res = GetElfString(elf, mapsize, strtab, sym->st_name))))) {
return res;
} else {
return NULL;
}
}
static void printelfrelocations(void) {
int sym;
size_t i, j, count;
const Elf64_Sym *syms;
const Elf64_Rela *rela;
const Elf64_Shdr *shdr, *symtab;
char *strtab, *shstrtab, *symbolname;
strtab = GetElfStringTable(elf, st->st_size);
shstrtab = GetElfSectionNameStringTable(elf, st->st_size);
for (i = 0; i < elf->e_shnum; ++i) {
if ((shdr = GetElfSectionHeaderAddress(elf, st->st_size, i)) &&
shdr->sh_type == SHT_RELA &&
(rela = GetElfSectionAddress(elf, st->st_size, shdr))) {
printf("\n/\t%s\n", GetElfSectionName(elf, st->st_size, shdr));
printf("\t.org\t%#x\n", (intptr_t)rela - (intptr_t)elf);
for (j = 0; ((uintptr_t)rela + sizeof(Elf64_Rela) <=
min((uintptr_t)elf + st->st_size,
(uintptr_t)elf + shdr->sh_offset + shdr->sh_size));
++rela, ++j) {
symtab = GetElfSectionHeaderAddress(elf, st->st_size, shdr->sh_link);
count = symtab->sh_size / symtab->sh_entsize;
syms = GetElfSectionAddress(elf, st->st_size, symtab);
sym = ELF64_R_SYM(rela->r_info);
if (0 <= sym && sym < count) {
symbolname =
getelfsymbolname(elf, st->st_size, strtab, shstrtab, syms + sym);
} else {
symbolname = xasprintf("bad-sym-%d", sym);
}
printf("/\t%s+%#lx â %s%c%#lx\n",
GetElfString(
elf, st->st_size, shstrtab,
GetElfSectionHeaderAddress(elf, st->st_size, shdr->sh_info)
->sh_name),
rela->r_offset, symbolname, rela->r_addend >= 0 ? '+' : '-',
ABS(rela->r_addend));
printf("%s_%zu_%zu:\n", ".Lrela", i, j);
show(".quad", format(b1, "%#lx", rela->r_offset), "rela->r_offset");
show(".long",
format(b1, "%s%s", "R_X86_64_",
findnamebyid(kElfNexgen32eRelocationNames,
ELF64_R_TYPE(rela->r_info))),
"ELF64_R_TYPE(rela->r_info)");
show(".long", format(b1, "%d", ELF64_R_SYM(rela->r_info)),
"ELF64_R_SYM(rela->r_info)");
show(".quad", format(b1, "%#lx", rela->r_addend), "rela->r_addend");
}
}
}
}
int main(int argc, char *argv[]) {
int fd;
ShowCrashReports();
if (argc != 2) {
fprintf(stderr, "usage: %s FILE\n", argv[0]);
return 1;
}
path = argv[1];
fd = open(path, O_RDONLY);
if (fd == -1) {
if (errno == ENOENT) {
fprintf(stderr, "error: %`s not found\n", path);
exit(1);
}
perror("open");
exit(1);
}
fstat(fd, st);
CHECK_NE(MAP_FAILED,
(elf = mmap(NULL, st->st_size, PROT_READ, MAP_SHARED, fd, 0)));
if (memcmp(elf->e_ident, ELFMAG, 4) != 0) {
fprintf(stderr, "error: not an elf executable: %'s\n", path);
exit(1);
}
startfile();
printelfehdr();
printelfsegmentheaders();
printelfsectionheaders();
printelfgroups();
printelfrelocations();
printelfsymboltable();
printelfdynsymboltable();
munmap(elf, st->st_size);
close(fd);
return 0;
}
| 16,370 | 395 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/mkwides.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/fmt/fmt.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.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 "tool/decode/lib/bitabuilder.h"
static FILE *fin, *fout;
static char width, *line;
static size_t linecap, i, x, y;
static struct BitaBuilder *bitset;
static char *g_inpath, *g_outpath;
wontreturn void ShowUsage(FILE *f, int rc) {
fprintf(f, "Usage: %s [-o OUTPUT] [INPUT]\n", "Usage",
program_invocation_name);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
g_inpath = "/dev/stdin";
g_outpath = "/dev/stdout";
while ((opt = getopt(argc, argv, "?ho:")) != -1) {
switch (opt) {
case 'o':
g_outpath = optarg;
break;
case 'h':
case '?':
ShowUsage(stdout, EXIT_SUCCESS);
default:
ShowUsage(stderr, EX_USAGE);
}
}
if (argc - optind) {
g_inpath = argv[optind];
}
}
/**
* Converts official UNICODE âmonospace widthsâ (yup) to a bitset.
*
* (â¯Â°â¡Â°)â¯ï¸µ ̲â»Ì²â̲â»
* è¦ä¾æ³æ²»å½æ¯èµç¾é£äºè°æ¯å
¬ä¹çåæ©ç½æ¶äººã - é©é
*
* 172kB TXT â 32kB bits â 525 bytes lz4
*
* @note this tool may print binary to stdout
* @see libc/kompressor/lz4decode.c
* @see tool/viz/bing.c
* @see tool/viz/fold.c
* @see unicode.org/reports/tr11/#Definitions
*/
int main(int argc, char *argv[]) {
GetOpts(argc, argv);
bitset = bitabuilder_new();
CHECK_NOTNULL(fin = fopen(g_inpath, "r"));
while ((getline(&line, &linecap, fin)) != -1) {
x = 0;
y = 0;
if (sscanf(line, "%x..%x;%c", &x, &y, &width) != 3) {
if (sscanf(line, "%x;%c", &x, &width) == 2) {
y = x;
} else {
continue;
}
}
CHECK_LE(x, y);
if (width == 'F' /* full-width */ || width == 'W' /* wide */) {
for (i = x; i <= y; ++i) {
CHECK(bitabuilder_setbit(bitset, i));
}
}
}
CHECK_NOTNULL(fout = fopen(g_outpath, "wb"));
CHECK(bitabuilder_fwrite(bitset, fout));
bitabuilder_free(&bitset);
return fclose(fin) | fclose(fout);
}
| 4,092 | 104 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/peboff.c | #include "libc/nt/struct/peb.h"
#include "libc/stdio/stdio.h"
int main() {
printf("InheritedAddressSpace = 0x%x\n",
offsetof(struct NtPeb, InheritedAddressSpace));
printf("ReadImageFileExecOptions = 0x%x\n",
offsetof(struct NtPeb, ReadImageFileExecOptions));
printf("BeingDebugged = 0x%x\n", offsetof(struct NtPeb, BeingDebugged));
printf("Mutant = 0x%x\n", offsetof(struct NtPeb, Mutant));
printf("ImageBaseAddress = 0x%x\n", offsetof(struct NtPeb, ImageBaseAddress));
printf("Ldr = 0x%x\n", offsetof(struct NtPeb, Ldr));
printf("ProcessParameters = 0x%x\n",
offsetof(struct NtPeb, ProcessParameters));
printf("SubSystemData = 0x%x\n", offsetof(struct NtPeb, SubSystemData));
printf("ProcessHeap = 0x%x\n", offsetof(struct NtPeb, ProcessHeap));
printf("FastPebLock = 0x%x\n", offsetof(struct NtPeb, FastPebLock));
printf("KernelCallbackTable = 0x%x\n",
offsetof(struct NtPeb, KernelCallbackTable));
printf("UserSharedInfoPtr = 0x%x\n",
offsetof(struct NtPeb, UserSharedInfoPtr));
printf("SystemReserved = 0x%x\n", offsetof(struct NtPeb, SystemReserved));
printf("__wut6 = 0x%x\n", offsetof(struct NtPeb, __wut6));
printf("__wut7 = 0x%x\n", offsetof(struct NtPeb, __wut7));
printf("TlsExpansionCounter = 0x%x\n",
offsetof(struct NtPeb, TlsExpansionCounter));
printf("TlsBitmap = 0x%x\n", offsetof(struct NtPeb, TlsBitmap));
printf("TlsBitmapBits = 0x%x\n", offsetof(struct NtPeb, TlsBitmapBits));
printf("ReadOnlySharedMemoryBase = 0x%x\n",
offsetof(struct NtPeb, ReadOnlySharedMemoryBase));
printf("ReadOnlyStaticServerData = 0x%x\n",
offsetof(struct NtPeb, ReadOnlyStaticServerData));
printf("AnsiCodePageData = 0x%x\n", offsetof(struct NtPeb, AnsiCodePageData));
printf("OemCodePageData = 0x%x\n", offsetof(struct NtPeb, OemCodePageData));
printf("UnicodeCaseTableData = 0x%x\n",
offsetof(struct NtPeb, UnicodeCaseTableData));
printf("NumberOfProcessors = 0x%x\n",
offsetof(struct NtPeb, NumberOfProcessors));
printf("NtGlobalFlag = 0x%x\n", offsetof(struct NtPeb, NtGlobalFlag));
printf("CriticalSectionTimeout = 0x%x\n",
offsetof(struct NtPeb, CriticalSectionTimeout));
printf("HeapSegmentReserve = 0x%x\n",
offsetof(struct NtPeb, HeapSegmentReserve));
printf("HeapSegmentCommit = 0x%x\n",
offsetof(struct NtPeb, HeapSegmentCommit));
printf("HeapDeCommitTotalFreeThreshold = 0x%x\n",
offsetof(struct NtPeb, HeapDeCommitTotalFreeThreshold));
printf("HeapDeCommitFreeBlockThreshold = 0x%x\n",
offsetof(struct NtPeb, HeapDeCommitFreeBlockThreshold));
printf("NumberOfHeaps = 0x%x\n", offsetof(struct NtPeb, NumberOfHeaps));
printf("MaximumNumberOfHeaps = 0x%x\n",
offsetof(struct NtPeb, MaximumNumberOfHeaps));
printf("ProcessHeaps = 0x%x\n", offsetof(struct NtPeb, ProcessHeaps));
printf("GdiSharedHandleTable = 0x%x\n",
offsetof(struct NtPeb, GdiSharedHandleTable));
printf("ProcessStarterHelper = 0x%x\n",
offsetof(struct NtPeb, ProcessStarterHelper));
printf("GdiDCAttributeList = 0x%x\n",
offsetof(struct NtPeb, GdiDCAttributeList));
printf("LoaderLock = 0x%x\n", offsetof(struct NtPeb, LoaderLock));
printf("OSMajorVersion = 0x%x\n", offsetof(struct NtPeb, OSMajorVersion));
printf("OSMinorVersion = 0x%x\n", offsetof(struct NtPeb, OSMinorVersion));
printf("OSVersion = 0x%x\n", offsetof(struct NtPeb, OSVersion));
printf("OSBuildNumber = 0x%x\n", offsetof(struct NtPeb, OSBuildNumber));
printf("OSCSDVersion = 0x%x\n", offsetof(struct NtPeb, OSCSDVersion));
printf("OSPlatformId = 0x%x\n", offsetof(struct NtPeb, OSPlatformId));
printf("ImageSubsystem = 0x%x\n", offsetof(struct NtPeb, ImageSubsystem));
printf("ImageSubsystemMajorVersion = 0x%x\n",
offsetof(struct NtPeb, ImageSubsystemMajorVersion));
printf("ImageSubsystemMinorVersion = 0x%x\n",
offsetof(struct NtPeb, ImageSubsystemMinorVersion));
printf("ImageProcessAffinityMask = 0x%x\n",
offsetof(struct NtPeb, ImageProcessAffinityMask));
printf("ActiveProcessAffinityMask = 0x%x\n",
offsetof(struct NtPeb, ActiveProcessAffinityMask));
printf("GdiHandleBuffer = 0x%x\n", offsetof(struct NtPeb, GdiHandleBuffer));
printf("PostProcessInitRoutine = 0x%x\n",
offsetof(struct NtPeb, PostProcessInitRoutine));
printf("TlsExpansionBitmap = 0x%x\n",
offsetof(struct NtPeb, TlsExpansionBitmap));
printf("TlsExpansionBitmapBits = 0x%x\n",
offsetof(struct NtPeb, TlsExpansionBitmapBits));
printf("SessionId = 0x%x\n", offsetof(struct NtPeb, SessionId));
printf("AppCompatFlags = 0x%x\n", offsetof(struct NtPeb, AppCompatFlags));
printf("AppCompatFlagsUser = 0x%x\n",
offsetof(struct NtPeb, AppCompatFlagsUser));
printf("pShimData = 0x%x\n", offsetof(struct NtPeb, pShimData));
printf("AppCompatInfo = 0x%x\n", offsetof(struct NtPeb, AppCompatInfo));
printf("CSDVersion = 0x%x\n", offsetof(struct NtPeb, CSDVersion));
printf("ActivationContextData = 0x%x\n",
offsetof(struct NtPeb, ActivationContextData));
printf("ProcessAssemblyStorageMap = 0x%x\n",
offsetof(struct NtPeb, ProcessAssemblyStorageMap));
printf("SystemDefaultActivationContextData = 0x%x\n",
offsetof(struct NtPeb, SystemDefaultActivationContextData));
printf("SystemAssemblyStorageMap = 0x%x\n",
offsetof(struct NtPeb, SystemAssemblyStorageMap));
printf("MinimumStackCommit = 0x%x\n",
offsetof(struct NtPeb, MinimumStackCommit));
return 0;
}
| 5,581 | 102 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/disassemblehex.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_DISASSEMBLEHEX_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_DISASSEMBLEHEX_H_
#define kDisassembleHexColumns 8
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
void disassemblehex(uint8_t *data, size_t size, FILE *f);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_DISASSEMBLEHEX_H_ */
| 392 | 14 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/ntfileflagnames.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/nt/enum/fileflagandattributes.h"
#include "tool/decode/lib/ntfileflagnames.h"
const struct IdName kNtFileFlagNames[] = {
{kNtFileAttributeReadonly, "kNtFileAttributeReadonly"},
{kNtFileAttributeHidden, "kNtFileAttributeHidden"},
{kNtFileAttributeSystem, "kNtFileAttributeSystem"},
{kNtFileAttributeVolumelabel, "kNtFileAttributeVolumelabel"},
{kNtFileAttributeDirectory, "kNtFileAttributeDirectory"},
{kNtFileAttributeArchive, "kNtFileAttributeArchive"},
{kNtFileAttributeDevice, "kNtFileAttributeDevice"},
{kNtFileAttributeNormal, "kNtFileAttributeNormal"},
{kNtFileAttributeTemporary, "kNtFileAttributeTemporary"},
{kNtFileAttributeSparseFile, "kNtFileAttributeSparseFile"},
{kNtFileAttributeReparsePoint, "kNtFileAttributeReparsePoint"},
{kNtFileAttributeCompressed, "kNtFileAttributeCompressed"},
{kNtFileAttributeOffline, "kNtFileAttributeOffline"},
{kNtFileAttributeNotContentIndexed, "kNtFileAttributeNotContentIndexed"},
{kNtFileAttributeEncrypted, "kNtFileAttributeEncrypted"},
{kNtFileFlagWriteThrough, "kNtFileFlagWriteThrough"},
{kNtFileFlagOverlapped, "kNtFileFlagOverlapped"},
{kNtFileFlagNoBuffering, "kNtFileFlagNoBuffering"},
{kNtFileFlagRandomAccess, "kNtFileFlagRandomAccess"},
{kNtFileFlagSequentialScan, "kNtFileFlagSequentialScan"},
{kNtFileFlagDeleteOnClose, "kNtFileFlagDeleteOnClose"},
{kNtFileFlagBackupSemantics, "kNtFileFlagBackupSemantics"},
{kNtFileFlagPosixSemantics, "kNtFileFlagPosixSemantics"},
{kNtFileFlagOpenReparsePoint, "kNtFileFlagOpenReparsePoint"},
{kNtFileFlagOpenNoRecall, "kNtFileFlagOpenNoRecall"},
{kNtFileFlagFirstPipeInstance, "kNtFileFlagFirstPipeInstance"},
{0, 0},
};
| 3,580 | 51 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/titlegen.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_TITLEGEN_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_TITLEGEN_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct Modeline {
const char *emacs;
const char *vim;
};
extern const struct Modeline kModelineAsm;
void showtitle(const char *brand, const char *tool, const char *title,
const char *description, const struct Modeline *modeline);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_TITLEGEN_H_ */
| 532 | 19 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/flagger.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/arraylist2.internal.h"
#include "libc/fmt/fmt.h"
#include "libc/mem/mem.h"
#include "libc/str/str.h"
#include "tool/decode/lib/flagger.h"
/**
* Formats numeric flags integer as symbolic code.
*
* @param names maps individual flags to string names in no order
* @param id is the flags
* @return NUL-terminated string that needs free()
*/
dontdiscard char *RecreateFlags(const struct IdName *names, unsigned long id) {
bool first;
size_t bufi, bufn;
char *bufp, extrabuf[20];
bufi = 0;
bufn = 0;
bufp = NULL;
first = true;
for (; names->name; names++) {
if ((id == 0 && names->id == 0) ||
(id != 0 && names->id != 0 && (id & names->id) == names->id)) {
id &= ~names->id;
if (!first) {
APPEND(&bufp, &bufi, &bufn, "|");
} else {
first = false;
}
CONCAT(&bufp, &bufi, &bufn, names->name, strlen(names->name));
}
}
if (id) {
if (bufi) APPEND(&bufp, &bufi, &bufn, "|");
CONCAT(&bufp, &bufi, &bufn, extrabuf,
snprintf(extrabuf, sizeof(extrabuf), "%#x", id));
} else if (!bufi) {
APPEND(&bufp, &bufi, &bufn, "0");
}
return bufp;
}
| 2,996 | 61 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/elfidnames.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/elf/def.h"
#include "libc/elf/elf.h"
#include "tool/decode/lib/elfidnames.h"
const struct IdName kElfTypeNames[] = {
{ET_NONE, "ET_NONE"},
{ET_REL, "ET_REL"},
{ET_EXEC, "ET_EXEC"},
{ET_DYN, "ET_DYN"},
{ET_CORE, "ET_CORE"},
{ET_NUM, "ET_NUM"},
{ET_LOOS, "ET_LOOS"},
{ET_HIOS, "ET_HIOS"},
{ET_LOPROC, "ET_LOPROC"},
{ET_HIPROC, "ET_HIPROC"},
{0, 0},
};
const struct IdName kElfOsabiNames[] = {
{ELFOSABI_NONE, "ELFOSABI_NONE"},
{ELFOSABI_SYSV, "ELFOSABI_SYSV"},
{ELFOSABI_HPUX, "ELFOSABI_HPUX"},
{ELFOSABI_NETBSD, "ELFOSABI_NETBSD"},
{ELFOSABI_GNU, "ELFOSABI_GNU"},
{ELFOSABI_LINUX, "ELFOSABI_LINUX"},
{ELFOSABI_SOLARIS, "ELFOSABI_SOLARIS"},
{ELFOSABI_AIX, "ELFOSABI_AIX"},
{ELFOSABI_IRIX, "ELFOSABI_IRIX"},
{ELFOSABI_FREEBSD, "ELFOSABI_FREEBSD"},
{ELFOSABI_TRU64, "ELFOSABI_TRU64"},
{ELFOSABI_MODESTO, "ELFOSABI_MODESTO"},
{ELFOSABI_OPENBSD, "ELFOSABI_OPENBSD"},
{ELFOSABI_ARM, "ELFOSABI_ARM"},
{ELFOSABI_STANDALONE, "ELFOSABI_STANDALONE"},
{0, 0},
};
const struct IdName kElfClassNames[] = {
{ELFCLASSNONE, "ELFCLASSNONE"},
{ELFCLASS32, "ELFCLASS32"},
{ELFCLASS64, "ELFCLASS64"},
{0, 0},
};
const struct IdName kElfDataNames[] = {
{ELFDATANONE, "ELFDATANONE"},
{ELFDATA2LSB, "ELFDATA2LSB"},
{ELFDATA2MSB, "ELFDATA2MSB"},
{0, 0},
};
const struct IdName kElfMachineNames[] = {
{EM_M32, "EM_M32"},
{EM_386, "EM_386"},
{EM_S390, "EM_S390"},
{EM_ARM, "EM_ARM"},
{EM_NEXGEN32E, "EM_NEXGEN32E"},
{EM_PDP11, "EM_PDP11"},
{EM_CRAYNV2, "EM_CRAYNV2"},
{EM_L10M, "EM_L10M"},
{EM_K10M, "EM_K10M"},
{EM_AARCH64, "EM_AARCH64"},
{EM_CUDA, "EM_CUDA"},
{EM_Z80, "EM_Z80"},
{EM_RISCV, "EM_RISCV"},
{EM_BPF, "EM_BPF"},
{0, 0},
};
const struct IdName kElfSegmentTypeNames[] = {
{PT_NULL, "PT_NULL"}, /* Program header table entry unused */
{PT_LOAD, "PT_LOAD"}, /* Loadable program segment */
{PT_DYNAMIC, "PT_DYNAMIC"}, /* Dynamic linking information */
{PT_INTERP, "PT_INTERP"}, /* Program interpreter */
{PT_NOTE, "PT_NOTE"}, /* Auxiliary information */
{PT_SHLIB, "PT_SHLIB"}, /* Reserved */
{PT_PHDR, "PT_PHDR"}, /* Entry for header table itself */
{PT_TLS, "PT_TLS"}, /* Thread-local storage segment */
{PT_NUM, "PT_NUM"}, /* Number of defined types */
{PT_LOOS, "PT_LOOS"}, /* Start of OS-specific */
{PT_GNU_EH_FRAME, "PT_GNU_EH_FRAME"}, /* GCC .eh_frame_hdr segment */
{PT_GNU_STACK, "PT_GNU_STACK"}, /* Indicates stack executability */
{PT_GNU_RELRO, "PT_GNU_RELRO"}, /* Read-only after relocation */
{PT_LOSUNW, "PT_LOSUNW"}, /* <Reserved for Sun Micrososystems> */
{PT_SUNWBSS, "PT_SUNWBSS"}, /* Sun Specific segment */
{PT_SUNWSTACK, "PT_SUNWSTACK"}, /* Stack segment */
{PT_HISUNW, "PT_HISUNW"}, /* </Reserved for Sun Micrososystems> */
{PT_HIOS, "PT_HIOS"}, /* End of OS-specific */
{PT_LOPROC, "PT_LOPROC"}, /* Start of processor-specific */
{PT_HIPROC, "PT_HIPROC"}, /* End of processor-specific */
{0, 0},
};
const struct IdName kElfSectionTypeNames[] = {
{SHT_NULL, "SHT_NULL"},
{SHT_PROGBITS, "SHT_PROGBITS"},
{SHT_SYMTAB, "SHT_SYMTAB"},
{SHT_STRTAB, "SHT_STRTAB"},
{SHT_RELA, "SHT_RELA"},
{SHT_HASH, "SHT_HASH"},
{SHT_DYNAMIC, "SHT_DYNAMIC"},
{SHT_NOTE, "SHT_NOTE"},
{SHT_NOBITS, "SHT_NOBITS"},
{SHT_REL, "SHT_REL"},
{SHT_SHLIB, "SHT_SHLIB"},
{SHT_DYNSYM, "SHT_DYNSYM"},
{SHT_INIT_ARRAY, "SHT_INIT_ARRAY"},
{SHT_FINI_ARRAY, "SHT_FINI_ARRAY"},
{SHT_PREINIT_ARRAY, "SHT_PREINIT_ARRAY"},
{SHT_GROUP, "SHT_GROUP"},
{SHT_SYMTAB_SHNDX, "SHT_SYMTAB_SHNDX"},
{SHT_NUM, "SHT_NUM"},
{SHT_LOOS, "SHT_LOOS"},
{SHT_GNU_ATTRIBUTES, "SHT_GNU_ATTRIBUTES"},
{SHT_GNU_HASH, "SHT_GNU_HASH"},
{SHT_GNU_LIBLIST, "SHT_GNU_LIBLIST"},
{SHT_CHECKSUM, "SHT_CHECKSUM"},
{SHT_LOSUNW, "SHT_LOSUNW"},
{SHT_SUNW_move, "SHT_SUNW_move"},
{SHT_SUNW_COMDAT, "SHT_SUNW_COMDAT"},
{SHT_SUNW_syminfo, "SHT_SUNW_syminfo"},
{SHT_GNU_verdef, "SHT_GNU_verdef"},
{SHT_GNU_verneed, "SHT_GNU_verneed"},
{SHT_GNU_versym, "SHT_GNU_versym"},
{SHT_HISUNW, "SHT_HISUNW"},
{SHT_HIOS, "SHT_HIOS"},
{SHT_LOPROC, "SHT_LOPROC"},
{SHT_HIPROC, "SHT_HIPROC"},
{SHT_LOUSER, "SHT_LOUSER"},
{SHT_HIUSER, "SHT_HIUSER"},
{0, 0},
};
const struct IdName kElfSegmentFlagNames[] = {
{PF_X, "PF_X"},
{PF_W, "PF_W"},
{PF_R, "PF_R"},
{PF_MASKOS, "PF_MASKOS"},
{PF_MASKPROC, "PF_MASKPROC"},
{0, 0},
};
const struct IdName kElfSectionFlagNames[] = {
{SHF_WRITE, "SHF_WRITE"},
{SHF_ALLOC, "SHF_ALLOC"},
{SHF_EXECINSTR, "SHF_EXECINSTR"},
{SHF_MERGE, "SHF_MERGE"},
{SHF_STRINGS, "SHF_STRINGS"},
{SHF_INFO_LINK, "SHF_INFO_LINK"},
{SHF_LINK_ORDER, "SHF_LINK_ORDER"},
{SHF_OS_NONCONFORMING, "SHF_OS_NONCONFORMING"},
{SHF_GROUP, "SHF_GROUP"},
{SHF_TLS, "SHF_TLS"},
{SHF_COMPRESSED, "SHF_COMPRESSED"},
{SHF_MASKOS, "SHF_MASKOS"},
{SHF_MASKPROC, "SHF_MASKPROC"},
{SHF_ORDERED, "SHF_ORDERED"},
{SHF_EXCLUDE, "SHF_EXCLUDE"},
{0, 0},
};
const struct IdName kElfSymbolTypeNames[] = {
{STT_NOTYPE, "STT_NOTYPE"}, {STT_OBJECT, "STT_OBJECT"},
{STT_FUNC, "STT_FUNC"}, {STT_SECTION, "STT_SECTION"},
{STT_FILE, "STT_FILE"}, {STT_COMMON, "STT_COMMON"},
{STT_TLS, "STT_TLS"}, {STT_NUM, "STT_NUM"},
{STT_LOOS, "STT_LOOS"}, {STT_GNU_IFUNC, "STT_GNU_IFUNC"},
{STT_HIOS, "STT_HIOS"}, {STT_LOPROC, "STT_LOPROC"},
{STT_HIPROC, "STT_HIPROC"}, {0, 0},
};
const struct IdName kElfSymbolBindNames[] = {
{STB_LOCAL, "STB_LOCAL"}, {STB_GLOBAL, "STB_GLOBAL"},
{STB_WEAK, "STB_WEAK"}, {STB_NUM, "STB_NUM"},
{STB_LOOS, "STB_LOOS"}, {STB_GNU_UNIQUE, "STB_GNU_UNIQUE"},
{STB_HIOS, "STB_HIOS"}, {STB_LOPROC, "STB_LOPROC"},
{STB_HIPROC, "STB_HIPROC"}, {0, 0},
};
const struct IdName kElfSymbolVisibilityNames[] = {
{STV_DEFAULT, "STV_DEFAULT"},
{STV_INTERNAL, "STV_INTERNAL"},
{STV_HIDDEN, "STV_HIDDEN"},
{STV_PROTECTED, "STV_PROTECTED"},
{0, 0},
};
const struct IdName kElfSpecialSectionNames[] = {
{SHN_UNDEF, "SHN_UNDEF"},
{SHN_LORESERVE, "SHN_LORESERVE"},
{SHN_LOPROC, "SHN_LOPROC"},
{SHN_BEFORE, "SHN_BEFORE"},
{SHN_AFTER, "SHN_AFTER"},
{SHN_HIPROC, "SHN_HIPROC"},
{SHN_LOOS, "SHN_LOOS"},
{SHN_HIOS, "SHN_HIOS"},
{SHN_ABS, "SHN_ABS"},
{SHN_COMMON, "SHN_COMMON"},
{SHN_XINDEX, "SHN_XINDEX"},
{SHN_HIRESERVE, "SHN_HIRESERVE"},
{0, 0},
};
const struct IdName kElfNexgen32eRelocationNames[] = {
{R_X86_64_NONE, "NONE"},
{R_X86_64_64, "64"},
{R_X86_64_PC32, "PC32"},
{R_X86_64_GOT32, "GOT32"},
{R_X86_64_PLT32, "PLT32"},
{R_X86_64_COPY, "COPY"},
{R_X86_64_GLOB_DAT, "GLOB_DAT"},
{R_X86_64_JUMP_SLOT, "JUMP_SLOT"},
{R_X86_64_RELATIVE, "RELATIVE"},
{R_X86_64_GOTPCREL, "GOTPCREL"},
{R_X86_64_32, "32"},
{R_X86_64_32S, "32S"},
{R_X86_64_16, "16"},
{R_X86_64_PC16, "PC16"},
{R_X86_64_8, "8"},
{R_X86_64_PC8, "PC8"},
{R_X86_64_DTPMOD64, "DTPMOD64"},
{R_X86_64_DTPOFF64, "DTPOFF64"},
{R_X86_64_TPOFF64, "TPOFF64"},
{R_X86_64_TLSGD, "TLSGD"},
{R_X86_64_TLSLD, "TLSLD"},
{R_X86_64_DTPOFF32, "DTPOFF32"},
{R_X86_64_GOTTPOFF, "GOTTPOFF"},
{R_X86_64_TPOFF32, "TPOFF32"},
{R_X86_64_PC64, "PC64"},
{R_X86_64_GOTOFF64, "GOTOFF64"},
{R_X86_64_GOTPC32, "GOTPC32"},
{R_X86_64_GOT64, "GOT64"},
{R_X86_64_GOTPCREL64, "GOTPCREL64"},
{R_X86_64_GOTPC64, "GOTPC64"},
{R_X86_64_GOTPLT64, "GOTPLT64"},
{R_X86_64_PLTOFF64, "PLTOFF64"},
{R_X86_64_SIZE32, "SIZE32"},
{R_X86_64_SIZE64, "SIZE64"},
{R_X86_64_GOTPC32_TLSDESC, "GOTPC32_TLSDESC"},
{R_X86_64_TLSDESC_CALL, "TLSDESC_CALL"},
{R_X86_64_TLSDESC, "TLSDESC"},
{R_X86_64_IRELATIVE, "IRELATIVE"},
{R_X86_64_RELATIVE64, "RELATIVE64"},
{R_X86_64_GOTPCRELX, "GOTPCRELX"},
{R_X86_64_REX_GOTPCRELX, "REX_GOTPCRELX"},
{0, 0},
};
| 10,045 | 266 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/asmcodegen.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_ASMCODEGEN_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_ASMCODEGEN_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define COLUMN_WIDTH 24
#define showint(x) show(".long", format(b1, "%d", x), #x)
#define showint64(x) show(".quad", format(b1, "%ld", x), #x)
#define showbyte(x) show(".byte", format(b1, "%hhu", x), #x)
#define showshort(x) show(".short", format(b1, "%hu", x), #x)
#define showshorthex(x) show(".short", format(b1, "%#-6hx", x), #x)
#define showinthex(x) show(".long", format(b1, "%#x", x), #x)
#define showint64hex(x) show(".quad", format(b1, "%#lx", x), #x)
#define showorg(x) show(".org", format(b1, "%#lx", x), #x)
extern char b1[BUFSIZ];
extern char b2[BUFSIZ];
char *format(char *buf, const char *fmt, ...);
char *tabpad(const char *s, unsigned width) dontdiscard;
void show(const char *directive, const char *value, const char *comment);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_ASMCODEGEN_H_ */
| 1,094 | 28 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/peidnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_PEIDNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_PEIDNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kNtImageFileMachineNames[];
extern const struct IdName kNtPeOptionalHeaderMagicNames[];
extern const struct IdName kNtImageCharacteristicNames[];
extern const struct IdName kNtImageDllcharacteristicNames[];
extern const struct IdName kNtImageSubsystemNames[];
extern const struct IdName kNtImageScnNames[];
extern const struct IdName kNtImageDirectoryEntryNames[];
extern const struct IdName kNtPeSectionNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_PEIDNAMES_H_ */
| 760 | 19 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/xederrors.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_XEDERRORS_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_XEDERRORS_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kXedErrorIdNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_XEDERRORS_H_ */
| 367 | 12 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/decodelib.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 += TOOL_DECODE_LIB
TOOL_DECODE_LIB_ARTIFACTS += TOOL_DECODE_LIB_A
TOOL_DECODE_LIB = $(TOOL_DECODE_LIB_A_DEPS) $(TOOL_DECODE_LIB_A)
TOOL_DECODE_LIB_A = o/$(MODE)/tool/decode/lib/decodelib.a
TOOL_DECODE_LIB_A_FILES := $(wildcard tool/decode/lib/*)
TOOL_DECODE_LIB_A_HDRS = $(filter %.h,$(TOOL_DECODE_LIB_A_FILES))
TOOL_DECODE_LIB_A_SRCS_S = $(filter %.S,$(TOOL_DECODE_LIB_A_FILES))
TOOL_DECODE_LIB_A_SRCS_C = $(filter %.c,$(TOOL_DECODE_LIB_A_FILES))
TOOL_DECODE_LIB_A_CHECKS = $(TOOL_DECODE_LIB_A).pkg
TOOL_DECODE_LIB_A_SRCS = \
$(TOOL_DECODE_LIB_A_SRCS_S) \
$(TOOL_DECODE_LIB_A_SRCS_C)
TOOL_DECODE_LIB_A_OBJS = \
$(TOOL_DECODE_LIB_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(TOOL_DECODE_LIB_A_SRCS_C:%.c=o/$(MODE)/%.o)
TOOL_DECODE_LIB_A_DIRECTDEPS = \
LIBC_FMT \
LIBC_INTRIN \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_STDIO \
LIBC_STR \
LIBC_STUBS \
LIBC_SYSV
TOOL_DECODE_LIB_A_DEPS := \
$(call uniq,$(foreach x,$(TOOL_DECODE_LIB_A_DIRECTDEPS),$($(x))))
$(TOOL_DECODE_LIB_A): \
tool/decode/lib/ \
$(TOOL_DECODE_LIB_A).pkg \
$(TOOL_DECODE_LIB_A_OBJS)
$(TOOL_DECODE_LIB_A).pkg: \
$(TOOL_DECODE_LIB_A_OBJS) \
$(foreach x,$(TOOL_DECODE_LIB_A_DIRECTDEPS),$($(x)_A).pkg)
TOOL_DECODE_LIB_LIBS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)))
TOOL_DECODE_LIB_SRCS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_SRCS))
TOOL_DECODE_LIB_HDRS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_HDRS))
TOOL_DECODE_LIB_BINS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_BINS))
TOOL_DECODE_LIB_CHECKS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_CHECKS))
TOOL_DECODE_LIB_OBJS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_OBJS))
TOOL_DECODE_LIB_TESTS = $(foreach x,$(TOOL_DECODE_LIB_ARTIFACTS),$($(x)_TESTS))
o/$(MODE)/tool/decode/lib/elfidnames.o \
o/$(MODE)/tool/decode/lib/machoidnames.o \
o/$(MODE)/tool/decode/lib/peidnames.o: private \
DEFAULT_CFLAGS += \
-fdata-sections
.PHONY: o/$(MODE)/tool/decode/lib
o/$(MODE)/tool/decode/lib: $(TOOL_DECODE_LIB_CHECKS)
| 2,269 | 62 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/titlegen.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/fmt/fmt.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "tool/decode/lib/titlegen.h"
const struct Modeline kModelineAsm = {
" mode:asm; indent-tabs-mode:t; tab-width:8; coding:utf-8 ",
" set et ft=asm ts=8 sw=8 fenc=utf-8 "};
/**
* Displays one of those ANSI block source dividers we love so much.
*/
void showtitle(const char *brand, const char *tool, const char *title,
const char *description, const struct Modeline *modeline) {
char buf[512], *p;
p = stpcpy(buf, brand);
if (tool) {
p = stpcpy(stpcpy(p, " § "), tool);
if (title) {
p = stpcpy(stpcpy(p, " » "), title);
}
}
printf("/*");
if (modeline) {
printf("-*-%-71s-*-â\nâvi:%-72s:viâ\nâ", modeline->emacs, modeline->vim);
for (unsigned i = 0; i < 78; ++i) printf("â");
printf("â¡\nâ %-76s ", buf);
} else {
for (unsigned i = 0; i < 75; ++i) printf("â");
printf("âââ\nâ %-73s ââ¬â", buf);
}
printf("â\nââ");
for (unsigned i = 0; i < 75; ++i) printf("â");
printf("%s", modeline ? "â" : "â");
if (description) {
/* TODO(jart): paragraph fill */
printf("ââ\n%s ", description);
} else {
}
printf("*/\n");
}
| 3,082 | 60 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/peidnames.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/nt/pedef.internal.h"
#include "tool/decode/lib/peidnames.h"
const struct IdName kNtImageFileMachineNames[] = {
{kNtImageFileMachineUnknown, "kNtImageFileMachineUnknown"},
{kNtImageFileMachineTargetHost, "kNtImageFileMachineTargetHost"},
{kNtImageFileMachineI386, "kNtImageFileMachineI386"},
{kNtImageFileMachineR3000, "kNtImageFileMachineR3000"},
{kNtImageFileMachineR4000, "kNtImageFileMachineR4000"},
{kNtImageFileMachineR10000, "kNtImageFileMachineR10000"},
{kNtImageFileMachineWcemipsv2, "kNtImageFileMachineWcemipsv2"},
{kNtImageFileMachineAlpha, "kNtImageFileMachineAlpha"},
{kNtImageFileMachineSh3, "kNtImageFileMachineSh3"},
{kNtImageFileMachineSh3dsp, "kNtImageFileMachineSh3dsp"},
{kNtImageFileMachineSh3e, "kNtImageFileMachineSh3e"},
{kNtImageFileMachineSh4, "kNtImageFileMachineSh4"},
{kNtImageFileMachineSh5, "kNtImageFileMachineSh5"},
{kNtImageFileMachineArm, "kNtImageFileMachineArm"},
{kNtImageFileMachineThumb, "kNtImageFileMachineThumb"},
{kNtImageFileMachineArmnt, "kNtImageFileMachineArmnt"},
{kNtImageFileMachineAm33, "kNtImageFileMachineAm33"},
{kNtImageFileMachinePowerpc, "kNtImageFileMachinePowerpc"},
{kNtImageFileMachinePowerpcfp, "kNtImageFileMachinePowerpcfp"},
{kNtImageFileMachineIa64, "kNtImageFileMachineIa64"},
{kNtImageFileMachineMips16, "kNtImageFileMachineMips16"},
{kNtImageFileMachineAlpha64, "kNtImageFileMachineAlpha64"},
{kNtImageFileMachineMipsfpu, "kNtImageFileMachineMipsfpu"},
{kNtImageFileMachineMipsfpu16, "kNtImageFileMachineMipsfpu16"},
{kNtImageFileMachineAxp64, "kNtImageFileMachineAxp64"},
{kNtImageFileMachineTricore, "kNtImageFileMachineTricore"},
{kNtImageFileMachineCef, "kNtImageFileMachineCef"},
{kNtImageFileMachineEbc, "kNtImageFileMachineEbc"},
{kNtImageFileMachineNexgen32e, "kNtImageFileMachineNexgen32e"},
{kNtImageFileMachineM32r, "kNtImageFileMachineM32r"},
{kNtImageFileMachineArm64, "kNtImageFileMachineArm64"},
{kNtImageFileMachineCee, "kNtImageFileMachineCee"},
{0, 0},
};
const struct IdName kNtPeOptionalHeaderMagicNames[] = {
{kNtPe32bit, "kNtPe32bit"},
{kNtPe64bit, "kNtPe64bit"},
{0, 0},
};
const struct IdName kNtImageDllcharacteristicNames[] = {
{kNtImageDllcharacteristicsHighEntropyVa,
"kNtImageDllcharacteristicsHighEntropyVa"},
{kNtImageDllcharacteristicsDynamicBase,
"kNtImageDllcharacteristicsDynamicBase"},
{kNtImageDllcharacteristicsForceIntegrity,
"kNtImageDllcharacteristicsForceIntegrity"},
{kNtImageDllcharacteristicsNxCompat, "kNtImageDllcharacteristicsNxCompat"},
{kNtImageDllcharacteristicsNoIsolation,
"kNtImageDllcharacteristicsNoIsolation"},
{kNtImageDllcharacteristicsNoSeh, "kNtImageDllcharacteristicsNoSeh"},
{kNtImageDllcharacteristicsNoBind, "kNtImageDllcharacteristicsNoBind"},
{kNtImageDllcharacteristicsAppcontainer,
"kNtImageDllcharacteristicsAppcontainer"},
{kNtImageDllcharacteristicsWdmDriver,
"kNtImageDllcharacteristicsWdmDriver"},
{kNtImageDllcharacteristicsGuardCf, "kNtImageDllcharacteristicsGuardCf"},
{kNtImageDllcharacteristicsTerminalServerAware,
"kNtImageDllcharacteristicsTerminalServerAware"},
{0, 0},
};
const struct IdName kNtImageSubsystemNames[] = {
{kNtImageSubsystemUnknown, "kNtImageSubsystemUnknown"},
{kNtImageSubsystemNative, "kNtImageSubsystemNative"},
{kNtImageSubsystemWindowsGui, "kNtImageSubsystemWindowsGui"},
{kNtImageSubsystemWindowsCui, "kNtImageSubsystemWindowsCui"},
{kNtImageSubsystemOs2Cui, "kNtImageSubsystemOs2Cui"},
{kNtImageSubsystemPosixCui, "kNtImageSubsystemPosixCui"},
{kNtImageSubsystemNativeWindows, "kNtImageSubsystemNativeWindows"},
{kNtImageSubsystemWindowsCeGui, "kNtImageSubsystemWindowsCeGui"},
{kNtImageSubsystemEfiApplication, "kNtImageSubsystemEfiApplication"},
{kNtImageSubsystemEfiBootServiceDriver,
"kNtImageSubsystemEfiBootServiceDriver"},
{kNtImageSubsystemEfiRuntimeDriver, "kNtImageSubsystemEfiRuntimeDriver"},
{kNtImageSubsystemEfiRom, "kNtImageSubsystemEfiRom"},
{kNtImageSubsystemXbox, "kNtImageSubsystemXbox"},
{kNtImageSubsystemWindowsBootApplication,
"kNtImageSubsystemWindowsBootApplication"},
{kNtImageSubsystemXboxCodeCatalog, "kNtImageSubsystemXboxCodeCatalog"},
{0, 0},
};
const struct IdName kNtImageScnNames[] = {
{kNtImageScnTypeNoPad, "kNtImageScnTypeNoPad"},
{kNtImageScnCntCode, "kNtImageScnCntCode"},
{kNtImageScnCntInitializedData, "kNtImageScnCntInitializedData"},
{kNtImageScnCntUninitializedData, "kNtImageScnCntUninitializedData"},
{kNtImageScnLnkOther, "kNtImageScnLnkOther"},
{kNtImageScnLnkInfo, "kNtImageScnLnkInfo"},
{kNtImageScnLnkRemove, "kNtImageScnLnkRemove"},
{kNtImageScnLnkComdat, "kNtImageScnLnkComdat"},
{kNtImageScnNoDeferSpecExc, "kNtImageScnNoDeferSpecExc"},
{kNtImageScnGprel, "kNtImageScnGprel"},
{kNtImageScnMemFardata, "kNtImageScnMemFardata"},
{kNtImageScnMemPurgeable, "kNtImageScnMemPurgeable"},
{kNtImageScnMem16bit, "kNtImageScnMem16bit"},
{kNtImageScnMemLocked, "kNtImageScnMemLocked"},
{kNtImageScnMemPreload, "kNtImageScnMemPreload"},
{0, 0},
};
const struct IdName kNtImageDirectoryEntryNames[] = {
{kNtImageDirectoryEntryExport, "kNtImageDirectoryEntryExport"},
{kNtImageDirectoryEntryImport, "kNtImageDirectoryEntryImport"},
{kNtImageDirectoryEntryResource, "kNtImageDirectoryEntryResource"},
{kNtImageDirectoryEntryException, "kNtImageDirectoryEntryException"},
{kNtImageDirectoryEntrySecurity, "kNtImageDirectoryEntrySecurity"},
{kNtImageDirectoryEntryBasereloc, "kNtImageDirectoryEntryBasereloc"},
{kNtImageDirectoryEntryDebug, "kNtImageDirectoryEntryDebug"},
{kNtImageDirectoryEntryArchitecture, "kNtImageDirectoryEntryArchitecture"},
{kNtImageDirectoryEntryGlobalptr, "kNtImageDirectoryEntryGlobalptr"},
{kNtImageDirectoryEntryTls, "kNtImageDirectoryEntryTls"},
{kNtImageDirectoryEntryLoadConfig, "kNtImageDirectoryEntryLoadConfig"},
{kNtImageDirectoryEntryBoundImport, "kNtImageDirectoryEntryBoundImport"},
{kNtImageDirectoryEntryIat, "kNtImageDirectoryEntryIat"},
{kNtImageDirectoryEntryDelayImport, "kNtImageDirectoryEntryDelayImport"},
{kNtImageDirectoryEntryComDescriptor,
"kNtImageDirectoryEntryComDescriptor"},
{0, 0},
};
const struct IdName kNtImageCharacteristicNames[] = {
{kNtImageFileRelocsStripped, "kNtImageFileRelocsStripped"},
{kNtImageFileExecutableImage, "kNtImageFileExecutableImage"},
{kNtImageFileLineNumsStripped, "kNtImageFileLineNumsStripped"},
{kNtImageFileLocalSymsStripped, "kNtImageFileLocalSymsStripped"},
{kNtImageFileAggresiveWsTrim, "kNtImageFileAggresiveWsTrim"},
{kNtImageFileLargeAddressAware, "kNtImageFileLargeAddressAware"},
{kNtImageFileBytesReversedLo, "kNtImageFileBytesReversedLo"},
{kNtImageFile32bitMachine, "kNtImageFile32bitMachine"},
{kNtImageFileDebugStripped, "kNtImageFileDebugStripped"},
{kNtImageFileRemovableRunFromSwap, "kNtImageFileRemovableRunFromSwap"},
{kNtImageFileNetRunFromSwap, "kNtImageFileNetRunFromSwap"},
{kNtImageFileSystem, "kNtImageFileSystem"},
{kNtImageFileDll, "kNtImageFileDll"},
{kNtImageFileUpSystemOnly, "kNtImageFileUpSystemOnly"},
{kNtImageFileBytesReversedHi, "kNtImageFileBytesReversedHi"},
{0, 0},
};
const struct IdName kNtPeSectionNames[] = {
{kNtPeSectionCntCode, "kNtPeSectionCntCode"},
{kNtPeSectionCntInitializedData, "kNtPeSectionCntInitializedData"},
{kNtPeSectionCntUninitializedData, "kNtPeSectionCntUninitializedData"},
{kNtPeSectionGprel, "kNtPeSectionGprel"},
{kNtPeSectionMemDiscardable, "kNtPeSectionMemDiscardable"},
{kNtPeSectionMemNotCached, "kNtPeSectionMemNotCached"},
{kNtPeSectionMemNotPaged, "kNtPeSectionMemNotPaged"},
{kNtPeSectionMemShared, "kNtPeSectionMemShared"},
{kNtPeSectionMemExecute, "kNtPeSectionMemExecute"},
{kNtPeSectionMemRead, "kNtPeSectionMemRead"},
{kNtPeSectionMemWrite, "kNtPeSectionMemWrite"},
{0, 0},
};
| 9,965 | 179 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/ntfileflagnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_NTFILEFLAGNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_NTFILEFLAGNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kNtFileFlagNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_NTFILEFLAGNAMES_H_ */
| 385 | 12 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/asmcodegen.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 "tool/decode/lib/asmcodegen.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
char b1[BUFSIZ];
char b2[BUFSIZ];
char *format(char *buf, const char *fmt, ...) {
va_list va;
va_start(va, fmt);
vsnprintf(buf, BUFSIZ, fmt, va);
va_end(va);
return buf;
}
dontdiscard char *tabpad(const char *s, unsigned width) {
char *p;
size_t i, l, need;
l = strlen(s);
need = width > l ? (roundup(width, 8) - l - 1) / 8 + 1 : 0;
p = memcpy(malloc(l + need + 2), s, l);
for (i = 0; i < need; ++i) p[l + i] = '\t';
if (!need) {
p[l] = ' ';
++need;
}
p[l + need] = '\0';
return p;
}
void show(const char *directive, const char *value, const char *comment) {
if (comment) {
printf("\t%s\t%s// %s\n", directive, gc(tabpad(value, COLUMN_WIDTH)),
comment);
} else {
printf("\t%s\t%s\n", directive, gc(tabpad(value, COLUMN_WIDTH)));
}
}
| 2,863 | 61 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/bitabuilder.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_BITABUILDER_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_BITABUILDER_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct FILE;
struct BitaBuilder;
struct BitaBuilder *bitabuilder_new(void);
bool bitabuilder_setbit(struct BitaBuilder *, size_t);
bool bitabuilder_fwrite(const struct BitaBuilder *, struct FILE *);
void bitabuilder_free(struct BitaBuilder **);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_BITABUILDER_H_ */
| 535 | 16 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/xederrors.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 "third_party/xed/x86.h"
#include "tool/decode/lib/idname.h"
const struct IdName kXedErrorIdNames[] = {
{XED_ERROR_NONE, "NONE"},
{XED_ERROR_BUFFER_TOO_SHORT, "BUFFER_TOO_SHORT"},
{XED_ERROR_GENERAL_ERROR, "GENERAL_ERROR"},
{XED_ERROR_INVALID_FOR_CHIP, "INVALID_FOR_CHIP"},
{XED_ERROR_BAD_REGISTER, "BAD_REGISTER"},
{XED_ERROR_BAD_LOCK_PREFIX, "BAD_LOCK_PREFIX"},
{XED_ERROR_BAD_REP_PREFIX, "BAD_REP_PREFIX"},
{XED_ERROR_BAD_LEGACY_PREFIX, "BAD_LEGACY_PREFIX"},
{XED_ERROR_BAD_REX_PREFIX, "BAD_REX_PREFIX"},
{XED_ERROR_BAD_EVEX_UBIT, "BAD_EVEX_UBIT"},
{XED_ERROR_BAD_MAP, "BAD_MAP"},
{XED_ERROR_BAD_EVEX_V_PRIME, "BAD_EVEX_V_PRIME"},
{XED_ERROR_BAD_EVEX_Z_NO_MASKING, "BAD_EVEX_Z_NO_MASKING"},
{XED_ERROR_NO_OUTPUT_POINTER, "NO_OUTPUT_POINTER"},
{XED_ERROR_NO_AGEN_CALL_BACK_REGISTERED, "NO_AGEN_CALL_BACK_REGISTERED"},
{XED_ERROR_BAD_MEMOP_INDEX, "BAD_MEMOP_INDEX"},
{XED_ERROR_CALLBACK_PROBLEM, "CALLBACK_PROBLEM"},
{XED_ERROR_GATHER_REGS, "GATHER_REGS"},
{XED_ERROR_INSTR_TOO_LONG, "INSTR_TOO_LONG"},
{XED_ERROR_INVALID_MODE, "INVALID_MODE"},
{XED_ERROR_BAD_EVEX_LL, "BAD_EVEX_LL"},
{XED_ERROR_UNIMPLEMENTED, "UNIMPLEMENTED"},
{0, 0},
};
| 3,078 | 47 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/disassemblehex.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/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/str/tab.internal.h"
#include "tool/decode/lib/disassemblehex.h"
static size_t countzeroes(const uint8_t *data, size_t size) {
size_t i;
for (i = 0; i < size; ++i) {
if (data[i] != '\0') break;
}
return i;
}
void disassemblehex(uint8_t *data, size_t size, FILE *f) {
int col;
uint8_t ch;
size_t i, z;
char16_t glyphs[kDisassembleHexColumns + 1];
col = 0;
for (i = 0; i < size; ++i) {
ch = data[i];
if (!col) {
z = countzeroes(&data[i], size - i) / kDisassembleHexColumns;
if (z > 2) {
fprintf(f, "\t.%s\t%zu*%d\n", "zero", z, kDisassembleHexColumns);
i += z * kDisassembleHexColumns;
if (i == size) break;
}
fprintf(f, "\t.%s\t", "byte");
bzero(glyphs, sizeof(glyphs));
}
/* TODO(jart): Fix Emacs */
glyphs[col] = kCp437[ch == '"' || ch == '\\' || ch == '#' ? '.' : ch];
if (col) fputc(',', f);
fprintf(f, "0x%02x", ch);
if (++col == kDisassembleHexColumns) {
col = 0;
fprintf(f, "\t#%hs\n", glyphs);
}
}
if (col) fputc('\n', f);
}
| 2,970 | 61 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/zipnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_ZIPNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_ZIPNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kZipCompressionNames[];
extern const struct IdName kZipExtraNames[];
extern const struct IdName kZipIattrNames[];
extern const struct IdName kZipOsNames[];
extern const struct IdName kZipEraNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_ZIPNAMES_H_ */
| 543 | 16 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/idname.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_IDNAME_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_IDNAME_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
struct IdName {
unsigned long id;
const char *const name;
};
const char *findnamebyid(const struct IdName *names, unsigned long id);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_IDNAME_H_ */
| 413 | 16 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/elfidnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_ELFIDNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_ELFIDNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kElfTypeNames[];
extern const struct IdName kElfOsabiNames[];
extern const struct IdName kElfClassNames[];
extern const struct IdName kElfDataNames[];
extern const struct IdName kElfMachineNames[];
extern const struct IdName kElfSegmentTypeNames[];
extern const struct IdName kElfSectionTypeNames[];
extern const struct IdName kElfSegmentFlagNames[];
extern const struct IdName kElfSectionFlagNames[];
extern const struct IdName kElfSymbolTypeNames[];
extern const struct IdName kElfSymbolBindNames[];
extern const struct IdName kElfSymbolVisibilityNames[];
extern const struct IdName kElfSpecialSectionNames[];
extern const struct IdName kElfNexgen32eRelocationNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_ELFIDNAMES_H_ */
| 1,021 | 25 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/machoidnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_MACHOIDNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_MACHOIDNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kMachoArchitectures[];
extern const struct IdName kMachoFileTypeNames[];
extern const struct IdName kMachoFlagNames[];
extern const struct IdName kMachoSegmentFlagNames[];
extern const struct IdName kMachoSectionTypeNames[];
extern const struct IdName kMachoSectionAttributeNames[];
extern const struct IdName kMachoLoadCommandNames[];
extern const struct IdName kMachoVmProtNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_MACHOIDNAMES_H_ */
| 740 | 19 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/machoidnames.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 "tool/decode/lib/machoidnames.h"
#include "libc/macho.internal.h"
const struct IdName kMachoArchitectures[] = {
{MAC_CPU_MC680x0, "MAC_CPU_MC680x0"}, //
{MAC_CPU_NEXGEN32E, "MAC_CPU_NEXGEN32E"}, //
{MAC_CPU_I386, "MAC_CPU_I386"}, //
{MAC_CPU_X86, "MAC_CPU_X86"}, //
{MAC_CPU_MC98000, "MAC_CPU_MC98000"}, //
{MAC_CPU_HPPA, "MAC_CPU_HPPA"}, //
{MAC_CPU_ARM64, "MAC_CPU_ARM64"}, //
{MAC_CPU_ARM64_32, "MAC_CPU_ARM64_32"}, //
{MAC_CPU_ARM, "MAC_CPU_ARM"}, //
{MAC_CPU_MC88000, "MAC_CPU_MC88000"}, //
{MAC_CPU_SPARC, "MAC_CPU_SPARC"}, //
{MAC_CPU_I860, "MAC_CPU_I860"}, //
{MAC_CPU_POWERPC64, "MAC_CPU_POWERPC64"}, //
{MAC_CPU_POWERPC, "MAC_CPU_POWERPC"}, //
{MAC_ARCH_ABI64, "MAC_ARCH_ABI64"}, // flaggy
{MAC_ARCH_ABI64_32, "MAC_ARCH_ABI64_32"}, //
{MAC_CPU_NEXGEN32E_ALL, "MAC_CPU_NEXGEN32E_ALL"}, // subtypes
{0, 0},
};
const struct IdName kMachoFileTypeNames[] = {
{MAC_OBJECT, "MAC_OBJECT"},
{MAC_EXECUTE, "MAC_EXECUTE"},
{MAC_FVMLIB, "MAC_FVMLIB"},
{MAC_CORE, "MAC_CORE"},
{MAC_PRELOAD, "MAC_PRELOAD"},
{MAC_DYLIB, "MAC_DYLIB"},
{MAC_DYLINKER, "MAC_DYLINKER"},
{MAC_BUNDLE, "MAC_BUNDLE"},
{0, 0},
};
const struct IdName kMachoFlagNames[] = {
{MAC_NOUNDEFS, "MAC_NOUNDEFS"},
{MAC_INCRLINK, "MAC_INCRLINK"},
{MAC_DYLDLINK, "MAC_DYLDLINK"},
{MAC_BINDATLOAD, "MAC_BINDATLOAD"},
{MAC_PREBOUND, "MAC_PREBOUND"},
{MAC_SPLIT_SEGS, "MAC_SPLIT_SEGS"},
{MAC_LAZY_INIT, "MAC_LAZY_INIT"},
{MAC_TWOLEVEL, "MAC_TWOLEVEL"},
{MAC_FORCE_FLAT, "MAC_FORCE_FLAT"},
{MAC_NOMULTIDEFS, "MAC_NOMULTIDEFS"},
{MAC_NOFIXPREBINDING, "MAC_NOFIXPREBINDING"},
{MAC_PREBINDABLE, "MAC_PREBINDABLE"},
{MAC_ALLMODSBOUND, "MAC_ALLMODSBOUND"},
{MAC_SUBSECTIONS_VIA_SYMBOLS, "MAC_SUBSECTIONS_VIA_SYMBOLS"},
{MAC_CANONICAL, "MAC_CANONICAL"},
{MAC_ALLOW_STACK_EXECUTION, "MAC_ALLOW_STACK_EXECUTION"},
{MAC_ROOT_SAFE, "MAC_ROOT_SAFE"},
{MAC_SETUID_SAFE, "MAC_SETUID_SAFE"},
{MAC_PIE, "MAC_PIE"},
{MAC_HAS_TLV_DESCRIPTORS, "MAC_HAS_TLV_DESCRIPTORS"},
{MAC_NO_HEAP_EXECUTION, "MAC_NO_HEAP_EXECUTION"},
{0, 0},
};
const struct IdName kMachoSegmentFlagNames[] = {
{MAC_SG_HIGHVM, "MAC_SG_HIGHVM"},
{MAC_SG_FVMLIB, "MAC_SG_FVMLIB"},
{MAC_SG_NORELOC, "MAC_SG_NORELOC"},
{0, 0},
};
const struct IdName kMachoSectionTypeNames[] = {
{MAC_S_REGULAR, "MAC_S_REGULAR"},
{MAC_S_ZEROFILL, "MAC_S_ZEROFILL"},
{MAC_S_CSTRING_LITERALS, "MAC_S_CSTRING_LITERALS"},
{MAC_S_4BYTE_LITERALS, "MAC_S_4BYTE_LITERALS"},
{MAC_S_8BYTE_LITERALS, "MAC_S_8BYTE_LITERALS"},
{MAC_S_LITERAL_POINTERS, "MAC_S_LITERAL_POINTERS"},
{MAC_S_NON_LAZY_SYMBOL_POINTERS, "MAC_S_NON_LAZY_SYMBOL_POINTERS"},
{MAC_S_LAZY_SYMBOL_POINTERS, "MAC_S_LAZY_SYMBOL_POINTERS"},
{MAC_S_SYMBOL_STUBS, "MAC_S_SYMBOL_STUBS"},
{MAC_S_MOD_INIT_FUNC_POINTERS, "MAC_S_MOD_INIT_FUNC_POINTERS"},
{MAC_S_MOD_TERM_FUNC_POINTERS, "MAC_S_MOD_TERM_FUNC_POINTERS"},
{MAC_S_COALESCED, "MAC_S_COALESCED"},
{MAC_S_GB_ZEROFILL, "MAC_S_GB_ZEROFILL"},
{MAC_S_INTERPOSING, "MAC_S_INTERPOSING"},
{MAC_S_16BYTE_LITERALS, "MAC_S_16BYTE_LITERALS"},
{0, 0},
};
const struct IdName kMachoSectionAttributeNames[] = {
{MAC_S_ATTRIBUTES_USR, "MAC_S_ATTRIBUTES_USR"},
{MAC_S_ATTR_PURE_INSTRUCTIONS, "MAC_S_ATTR_PURE_INSTRUCTIONS"},
{MAC_S_ATTR_NO_TOC, "MAC_S_ATTR_NO_TOC"},
{MAC_S_ATTR_STRIP_STATIC_SYMS, "MAC_S_ATTR_STRIP_STATIC_SYMS"},
{MAC_S_ATTR_NO_DEAD_STRIP, "MAC_S_ATTR_NO_DEAD_STRIP"},
{MAC_S_ATTR_LIVE_SUPPORT, "MAC_S_ATTR_LIVE_SUPPORT"},
{MAC_S_ATTR_SELF_MODIFYING_CODE, "MAC_S_ATTR_SELF_MODIFYING_CODE"},
{MAC_S_ATTR_DEBUG, "MAC_S_ATTR_DEBUG"},
{MAC_S_ATTRIBUTES_SYS, "MAC_S_ATTRIBUTES_SYS"},
{MAC_S_ATTR_SOME_INSTRUCTIONS, "MAC_S_ATTR_SOME_INSTRUCTIONS"},
{MAC_S_ATTR_EXT_RELOC, "MAC_S_ATTR_EXT_RELOC"},
{MAC_S_ATTR_LOC_RELOC, "MAC_S_ATTR_LOC_RELOC"},
{0, 0},
};
const struct IdName kMachoLoadCommandNames[] = {
{MAC_LC_SEGMENT, "MAC_LC_SEGMENT"},
{MAC_LC_SYMTAB, "MAC_LC_SYMTAB"},
{MAC_LC_SYMSEG, "MAC_LC_SYMSEG"},
{MAC_LC_THREAD, "MAC_LC_THREAD"},
{MAC_LC_UNIXTHREAD, "MAC_LC_UNIXTHREAD"},
{MAC_LC_LOADFVMLIB, "MAC_LC_LOADFVMLIB"},
{MAC_LC_IDFVMLIB, "MAC_LC_IDFVMLIB"},
{MAC_LC_IDENT, "MAC_LC_IDENT"},
{MAC_LC_FVMFILE, "MAC_LC_FVMFILE"},
{MAC_LC_PREPAGE, "MAC_LC_PREPAGE"},
{MAC_LC_DYSYMTAB, "MAC_LC_DYSYMTAB"},
{MAC_LC_LOAD_DYLIB, "MAC_LC_LOAD_DYLIB"},
{MAC_LC_ID_DYLIB, "MAC_LC_ID_DYLIB"},
{MAC_LC_LOAD_DYLINKER, "MAC_LC_LOAD_DYLINKER"},
{MAC_LC_ID_DYLINKER, "MAC_LC_ID_DYLINKER"},
{MAC_LC_PREBOUND_DYLIB, "MAC_LC_PREBOUND_DYLIB"},
{MAC_LC_ROUTINES, "MAC_LC_ROUTINES"},
{MAC_LC_SUB_FRAMEWORK, "MAC_LC_SUB_FRAMEWORK"},
{MAC_LC_SUB_UMBRELLA, "MAC_LC_SUB_UMBRELLA"},
{MAC_LC_SUB_CLIENT, "MAC_LC_SUB_CLIENT"},
{MAC_LC_SUB_LIBRARY, "MAC_LC_SUB_LIBRARY"},
{MAC_LC_TWOLEVEL_HINTS, "MAC_LC_TWOLEVEL_HINTS"},
{MAC_LC_PREBIND_CKSUM, "MAC_LC_PREBIND_CKSUM"},
{MAC_LC_LOAD_WEAK_DYLIB, "MAC_LC_LOAD_WEAK_DYLIB"},
{MAC_LC_SEGMENT_64, "MAC_LC_SEGMENT_64"},
{MAC_LC_ROUTINES_64, "MAC_LC_ROUTINES_64"},
{MAC_LC_UUID, "MAC_LC_UUID"},
{MAC_LC_CODE_SIGNATURE, "MAC_LC_CODE_SIGNATURE"},
{MAC_LC_SEGMENT_SPLIT_INFO, "MAC_LC_SEGMENT_SPLIT_INFO"},
{MAC_LC_LAZY_LOAD_DYLIB, "MAC_LC_LAZY_LOAD_DYLIB"},
{MAC_LC_ENCRYPTION_INFO, "MAC_LC_ENCRYPTION_INFO"},
{MAC_LC_DYLD_INFO, "MAC_LC_DYLD_INFO"},
{MAC_LC_DYLD_INFO_ONLY, "MAC_LC_DYLD_INFO_ONLY"},
{MAC_LC_VERSION_MIN_MACOSX, "MAC_LC_VERSION_MIN_MACOSX"},
{MAC_LC_VERSION_MIN_IPHONEOS, "MAC_LC_VERSION_MIN_IPHONEOS"},
{MAC_LC_FUNCTION_STARTS, "MAC_LC_FUNCTION_STARTS"},
{MAC_LC_DYLD_ENVIRONMENT, "MAC_LC_DYLD_ENVIRONMENT"},
{MAC_LC_DATA_IN_CODE, "MAC_LC_DATA_IN_CODE"},
{MAC_LC_SOURCE_VERSION, "MAC_LC_SOURCE_VERSION"},
{MAC_LC_RPATH, "MAC_LC_RPATH"},
{MAC_LC_MAIN, "MAC_LC_MAIN"},
{MAC_LC_DYLIB_CODE_SIGN_DRS, "MAC_LC_DYLIB_CODE_SIGN_DRS"},
{MAC_LC_ENCRYPTION_INFO_64, "MAC_LC_ENCRYPTION_INFO_64"},
{MAC_LC_LINKER_OPTION, "MAC_LC_LINKER_OPTION"},
{MAC_LC_LINKER_OPTIMIZATION_HINT, "MAC_LC_LINKER_OPTIMIZATION_HINT"},
{MAC_LC_VERSION_MIN_TVOS, "MAC_LC_VERSION_MIN_TVOS"},
{MAC_LC_VERSION_MIN_WATCHOS, "MAC_LC_VERSION_MIN_WATCHOS"},
{MAC_LC_NOTE, "MAC_LC_NOTE"},
{MAC_LC_BUILD_VERSION, "MAC_LC_BUILD_VERSION"},
{MAC_LC_DYLD_EXPORTS_TRIE, "MAC_LC_DYLD_EXPORTS_TRIE"},
{MAC_LC_DYLD_CHAINED_FIXUPS, "MAC_LC_DYLD_CHAINED_FIXUPS"},
{MAC_LC_FILESET_ENTRY, "MAC_LC_FILESET_ENTRY"},
{MAC_LC_REEXPORT_DYLIB, "MAC_LC_REEXPORT_DYLIB"},
{0, 0},
};
const struct IdName kMachoVmProtNames[] = {
{VM_PROT_READ, "VM_PROT_READ"},
{VM_PROT_WRITE, "VM_PROT_WRITE"},
{VM_PROT_EXECUTE, "VM_PROT_EXECUTE"},
{VM_PROT_NO_CHANGE, "VM_PROT_NO_CHANGE"},
{VM_PROT_COPY, "VM_PROT_COPY"},
{VM_PROT_TRUSTED, "VM_PROT_TRUSTED"},
{VM_PROT_STRIP_READ, "VM_PROT_STRIP_READ"},
{0, 0},
};
| 9,124 | 189 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/x86idnames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_X86IDNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_X86IDNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kX86MarchNames[];
extern const struct IdName kX86GradeNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_X86IDNAMES_H_ */
| 413 | 13 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/bitabuilder.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 "tool/decode/lib/bitabuilder.h"
#include "libc/assert.h"
#include "libc/intrin/bits.h"
#include "libc/log/check.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
/**
* @fileoverview Sparse bit array builder.
*/
struct BitaBuilder {
size_t i, n;
uint32_t *p;
};
struct BitaBuilder *bitabuilder_new(void) {
return calloc(1, sizeof(struct BitaBuilder));
}
void bitabuilder_free(struct BitaBuilder **bbpp) {
if (*bbpp) {
free((*bbpp)->p);
free(*bbpp);
*bbpp = 0;
}
}
/**
* Sets bit.
*
* @return false if out of memory
*/
bool bitabuilder_setbit(struct BitaBuilder *bb, size_t bit) {
void *p2;
size_t i, n;
i = MAX(bb->i, ROUNDUP(bit / CHAR_BIT + 1, __BIGGEST_ALIGNMENT__));
if (i > bb->n) {
n = i + (i >> 2);
if ((p2 = realloc(bb->p, n))) {
bzero((char *)p2 + bb->n, n - bb->n);
bb->n = n;
bb->p = p2;
} else {
return false;
}
}
bb->i = i;
bb->p[bit / 32] |= 1u << (bit % 32);
return true;
}
bool bitabuilder_fwrite(const struct BitaBuilder *bb, FILE *f) {
return fwrite(bb->p, bb->i, 1, f);
}
| 3,030 | 77 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/socknames.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/dns/dns.h"
#include "libc/sock/sock.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/sock.h"
#include "tool/decode/lib/socknames.h"
const struct IdName kAddressFamilyNames[] = {
{AF_UNSPEC, "AF_UNSPEC"},
{AF_UNIX, "AF_UNIX"},
{AF_INET, "AF_INET"},
{0, 0},
};
const struct IdName kSockTypeNames[] = {
{SOCK_STREAM, "SOCK_STREAM"},
{SOCK_DGRAM, "SOCK_DGRAM"},
{SOCK_RAW, "SOCK_RAW"},
{SOCK_RDM, "SOCK_RDM"},
{SOCK_SEQPACKET, "SOCK_SEQPACKET"},
{0, 0},
};
const struct IdName kAddrInfoFlagNames[] = {
{AI_PASSIVE, "AI_PASSIVE"},
{AI_CANONNAME, "AI_CANONNAME"},
{AI_NUMERICHOST, "AI_NUMERICHOST"},
{0, 0},
};
const struct IdName kProtocolNames[] = {
{IPPROTO_IP, "IPPROTO_IP"}, {IPPROTO_ICMP, "IPPROTO_ICMP"},
{IPPROTO_TCP, "IPPROTO_TCP"}, {IPPROTO_UDP, "IPPROTO_UDP"},
{IPPROTO_RAW, "IPPROTO_RAW"}, {0, 0},
};
| 2,784 | 54 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/flagger.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_FLAGGER_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_FLAGGER_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
char *RecreateFlags(const struct IdName *, unsigned long) dontdiscard;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_FLAGGER_H_ */
| 385 | 12 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/socknames.h | #ifndef COSMOPOLITAN_TOOL_DECODE_LIB_SOCKNAMES_H_
#define COSMOPOLITAN_TOOL_DECODE_LIB_SOCKNAMES_H_
#include "tool/decode/lib/idname.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const struct IdName kAddressFamilyNames[];
extern const struct IdName kSockTypeNames[];
extern const struct IdName kAddrInfoFlagNames[];
extern const struct IdName kProtocolNames[];
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_DECODE_LIB_SOCKNAMES_H_ */
| 509 | 15 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/idname.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 "tool/decode/lib/idname.h"
const char *findnamebyid(const struct IdName *names, unsigned long id) {
for (; names->name; names++) {
if (names->id == id) {
return names->name;
}
}
return NULL;
}
| 2,059 | 29 | jart/cosmopolitan | false |
cosmopolitan/tool/decode/lib/zipnames.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/nt/enum/fileflagandattributes.h"
#include "libc/zip.h"
#include "tool/decode/lib/zipnames.h"
const struct IdName kZipCompressionNames[] = {
{kZipCompressionNone, "kZipCompressionNone"},
{kZipCompressionDeflate, "kZipCompressionDeflate"},
{0, 0},
};
const struct IdName kZipExtraNames[] = {
{kZipExtraZip64, "kZipExtraZip64"},
{kZipExtraNtfs, "kZipExtraNtfs"},
{kZipExtraUnix, "kZipExtraUnix"},
{kZipExtraExtendedTimestamp, "kZipExtraExtendedTimestamp"},
{kZipExtraInfoZipNewUnixExtra, "kZipExtraInfoZipNewUnixExtra"},
{0, 0},
};
const struct IdName kZipIattrNames[] = {
{kZipIattrBinary, "kZipIattrBinary"},
{kZipIattrText, "kZipIattrText"},
{0, 0},
};
const struct IdName kZipOsNames[] = {
{kZipOsDos, "kZipOsDos"},
{kZipOsAmiga, "kZipOsAmiga"},
{kZipOsOpenvms, "kZipOsOpenvms"},
{kZipOsUnix, "kZipOsUnix"},
{kZipOsVmcms, "kZipOsVmcms"},
{kZipOsAtarist, "kZipOsAtarist"},
{kZipOsOs2hpfs, "kZipOsOs2hpfs"},
{kZipOsMacintosh, "kZipOsMacintosh"},
{kZipOsZsystem, "kZipOsZsystem"},
{kZipOsCpm, "kZipOsCpm"},
{kZipOsWindowsntfs, "kZipOsWindowsntfs"},
{kZipOsMvsos390zos, "kZipOsMvsos390zos"},
{kZipOsVse, "kZipOsVse"},
{kZipOsAcornrisc, "kZipOsAcornrisc"},
{kZipOsVfat, "kZipOsVfat"},
{kZipOsAltmvs, "kZipOsAltmvs"},
{kZipOsBeos, "kZipOsBeos"},
{kZipOsTandem, "kZipOsTandem"},
{kZipOsOs400, "kZipOsOs400"},
{kZipOsOsxdarwin, "kZipOsOsxdarwin"},
{0, 0},
};
const struct IdName kZipEraNames[] = {
{kZipEra1989, "kZipEra1989"},
{kZipEra1993, "kZipEra1993"},
{kZipEra2001, "kZipEra2001"},
{0, 0},
};
| 3,496 | 74 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/powersave | #!/bin/sh
echo "powersave" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
| 92 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/re | #!/bin/sh
readelf -Wa "$1" |
c++filt |
exec less
| 53 | 5 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/wut | #!/bin/sh
rm -f /tmp/wut-linux
(
grep -R "$1" ~/dox/susv4-2018/ | sed '
/meta.idx/d
' >/tmp/wut-posix
) &
(
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/linux/include/ | sed '
/\/asm-/ {
/asm-\(x86\|generic\)/!d
}
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >>/tmp/wut-linux
) &
(
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/linux-2.6.18/include/ | sed '
/\/asm-/ {
/asm-\(x86\|generic\)/!d
}
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/2.6.18\t\1/
' >>/tmp/wut-linux
) &
(
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/xnu/ | sed '
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >/tmp/wut-xnu
) &
(
{
if ! grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/freebsd/sys/; then
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/freebsd/lib/libc/
fi
} | sed '
/\/contrib\//d
/\/linux\//d
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >/tmp/wut-freebsd
) &
(
{
if ! grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/openbsd/sys/; then
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/openbsd/lib/libc/
fi
} | sed '
/\/linux\//d
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >/tmp/wut-openbsd
) &
(
{
if ! grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/netbsd/sys/; then
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/netbsd/lib/libc/
fi
} | sed '
/\/linux\//d
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >/tmp/wut-netbsd
) &
(
grep -R "#define[[:blank:]]\+$1[[:blank:]]" ~/vendor/10.0.18362.0/um/ | sed '
s/\([^:]*\):\(.*\)/\2\t\t\t\1\t\1/
s/\(.*\)\/home\/jart\/vendor\/\([^\/]*\)\/[^[:blank:]]*/\2\t\1/
' >/tmp/wut-windows
) &
wait
f() {
if [ $(ls -lH /tmp/wut-$1 | awk5) -gt 0 ]; then
cat /tmp/wut-$1
else
echo $1 says nothing
fi
}
f linux
f xnu
f freebsd
f openbsd
f netbsd
f windows
f posix
| 2,275 | 99 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/cosmocc | #!/bin/sh
# replacement for cc command
#
# we assume you run the following beforehand
#
# sudo chmod 1777 /opt
# cd /opt
# git clone https://github.com/jart/cosmopolitan cosmo
# cd cosmo
# make -j
#
# you can then use it to build open source projects, e.g.
#
# export CC=cosmocc
# export CXX=cosmoc++
# export LD=cosmoc++
# ./configure --prefix=/opt/cosmos
# make -j
# make install
#
COSMO=/opt/cosmo
COSMOS=/opt/cosmos
if [ "$1" = "--version" ]; then
cat <<'EOF'
x86_64-unknown-cosmo-gcc (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
EOF
exit 0
fi
CC="/opt/cosmo/o/third_party/gcc/bin/x86_64-linux-musl-gcc"
CFLAGS="-g -O2 -fdata-sections -ffunction-sections -fno-pie -pg -mnop-mcount -mno-tls-direct-seg-refs"
CPPFLAGS="-DNDEBUG -nostdinc -iquote /opt/cosmo -isystem $COSMOS/include -isystem /opt/cosmo/libc/isystem -include libc/integral/normalize.inc"
LDFLAGS="-static -no-pie -nostdlib -fuse-ld=bfd -Wl,-melf_x86_64 -Wl,--gc-sections -Wl,-z,max-page-size=0x1000 -L$COSMOS/lib -Wl,-T,/opt/cosmo/o/ape/public/ape.lds /opt/cosmo/o/ape/ape-no-modify-self.o /opt/cosmo/o/libc/crt/crt.o"
LDLIBS="/opt/cosmo/o/cosmopolitan.a"
if [ ! -d $COSMO ]; then
echo you need to checkout cosmopolitan to your $COSMO directory >&2
exit 1
fi
if [ ! -d $COSMOS ]; then
echo you need to create your $COSMOS directory >&2
exit 1
fi
# auto-install some shell libraries
if [ ! -d $COSMOS/lib ]; then
mkdir $COSMOS/lib
for lib in c dl gcc_s m pthread resolv rt z stdc++; do
printf '\041\074\141\162\143\150\076\012' >$COSMOS/lib/lib$lib.a
done
fi
HAS_C=0
HAS_O=0
HAS_E=0
FIRST=1
for x; do
if [ $FIRST -eq 1 ]; then
set --
FIRST=0
fi
if [ "$x" = "-Werror" ]; then
# this toolchain is intended for building other people's code
# elevating warnings into errors, should only be done by devs
continue
fi
if [ "$x" = "-pedantic" ]; then
# this toolchain is intended for building other people's code
# we don't need the compiler's assistance to be more portable
continue
fi
if [ "$x" = "-c" ]; then
HAS_C=1
fi
if [ "$x" = "-E" ]; then
HAS_E=1
fi
if [ "$x" = "-o" ] || [ "${x#-o}" != "$x" ]; then
HAS_O=1
fi
set -- "$@" "$x"
done
if [ "$HAS_E" = "1" ]; then
set -- $CPPFLAGS "$@"
elif [ "$HAS_C" = "1" ]; then
set -- $CFLAGS $CPPFLAGS "$@" -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer
else
set -- $LDFLAGS $CFLAGS $CPPFLAGS "$@" $LDLIBS -Wl,-z,common-page-size=4096 -Wl,-z,max-page-size=4096
fi
set -- "$CC" "$@"
printf '(cd %s; %s)\n' "$PWD" "$*" >>/tmp/build.log
exec "$@"
| 2,768 | 101 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk5 | #!/bin/sh
exec awk "$@" '{print $5}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/man2txt | #!/bin/sh
ASCII2UTF8=$(command -v ascii2utf8.com 2>/dev/null) || {
ASCII2UTF8=$(ls -1 o/*/tool/viz/ascii2utf8.com | head -n1)
}
for x; do
nroff -mandoc -rLL=80n -rLT=80n -Tutf8 <"$x" | $ASCII2UTF8
done
| 208 | 10 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/get-deps.py | #!/usr/bin/env python.com
#
# OVERVIEW
#
# One-Off Makefile Rule Generator
#
# EXAMPLES
#
# tool/scripts/get-deps.py examples/hello.c
# asmexpr 'mov $0,%ecx' 'vmovd %ecx,%xmm1' 'vpbroadcastb %xmm1,%ymm1' 'mov $0x20202032489001ff,%rax' 'vmovq %rax,%xmm0' 'vpcmpgtb %ymm1,%ymm0,%ymm2'
#
import os
import re
import sys
def GetDeps(path):
sys.stdout.write('o/$(MODE)/%s.o:' % (os.path.splitext(path)[0]))
deps = set()
def Dive(path):
if path in deps:
return
deps.add(path)
sys.stdout.write(' \\\n\t\t%s' % (path))
with open(path) as f:
code = f.read()
for dep in re.findall(r'[.#]include "([^"]+)"', code):
Dive(dep)
Dive(path)
sys.stdout.write('\n')
for arg in sys.argv[1:]:
if os.path.isdir(arg):
for dirpath, dirs, files in os.walk(arg):
for filepath in files:
GetDeps(os.path.join(dirpath, filepath))
else:
GetDeps(arg)
| 907 | 39 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/grep | #!/bin/sh
exec grep \
--exclude=TAGS \
--exclude=HTAGS \
--exclude=*.com \
--exclude-dir=o \
--exclude-dir=gcc \
--exclude-dir=.git \
--exclude=archive-contents \
"$@"
| 292 | 11 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/asmexpr | #!/bin/sh
#
# OVERVIEW
#
# Micro-Experiment Assembler
#
# EXAMPLES
#
# asmexpr 'mov $8,%rax' 'bsr %rax,%rax'
# asmexpr 'mov $0,%ecx' 'vmovd %ecx,%xmm1' 'vpbroadcastb %xmm1,%ymm1' 'mov $0x20202032489001ff,%rax' 'vmovq %rax,%xmm0' 'vpcmpgtb %ymm1,%ymm0,%ymm2'
c=/tmp/asmexpr.c
s1=/tmp/asmexpr1.s
s2=/tmp/asmexpr2.s
s3=/tmp/asmexpr3.s
x=/tmp/asmexpr.exe
cat <<EOF >$s1
.comm rsp,8
.globl funk
funk: push %rbp
mov %rsp,%rbp
push %rbx
push %r12
push %r13
push %r14
push %r15
mov %rsp,rsp(%rip)
xor %eax,%eax
xor %ebx,%ebx
xor %ecx,%ecx
xor %edx,%edx
xor %edi,%edi
xor %esi,%esi
xor %r8d,%r8d
xor %r9d,%r9d
xor %r10d,%r10d
xor %r11d,%r11d
xor %r12d,%r12d
xor %r13d,%r13d
xor %r14d,%r14d
xor %r15d,%r15d
vzeroall
nop
nop
nop
nop
nop
nop
EOF
cat <<EOF >$s2
.comm a,8
.comm b,8
.comm c,8
.comm x,8
.comm y,8
.comm z,8
EOF
for i; do
cat <<EOF >>$s2
$i
EOF
done
cat <<EOF >$s3
.comm rsp,8
.comm regs,14*8
.comm flags,4
nop
nop
nop
nop
nop
nop
cld
mov rsp(%rip),%rsp
push %rbx
lea regs(%rip),%rbx
mov %rax,0(%rbx)
pop %rax
mov %rax,8(%rbx)
mov %rcx,16(%rbx)
mov %rdx,24(%rbx)
mov %rdi,32(%rbx)
mov %rsi,40(%rbx)
mov %r8,48(%rbx)
mov %r9,56(%rbx)
mov %r10,64(%rbx)
mov %r11,72(%rbx)
mov %r12,80(%rbx)
mov %r13,88(%rbx)
mov %r14,96(%rbx)
mov %r15,104(%rbx)
vmovaps %ymm0,0x0a0(%rbx)
vmovaps %ymm1,0x0c0(%rbx)
vmovaps %ymm2,0x0e0(%rbx)
vmovaps %ymm3,0x100(%rbx)
vmovaps %ymm4,0x120(%rbx)
vmovaps %ymm5,0x140(%rbx)
vmovaps %ymm6,0x160(%rbx)
vmovaps %ymm7,0x180(%rbx)
vmovaps %ymm8,0x1a0(%rbx)
vmovaps %ymm9,0x1c0(%rbx)
vmovaps %ymm10,0x1e0(%rbx)
vmovaps %ymm11,0x200(%rbx)
vmovaps %ymm12,0x220(%rbx)
vmovaps %ymm13,0x240(%rbx)
vmovaps %ymm14,0x260(%rbx)
vmovaps %ymm15,0x280(%rbx)
pushf
pop %rax
mov %eax,flags(%rip)
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbx
pop %rbp
vzeroupper
ret
EOF
cat <<EOF >$c
#include <stdio.h>
#include <string.h>
struct GodHatesFlags {
unsigned c : 1; /* bit 0: carry flag */
unsigned v : 1; /* bit 1: V flag: was 8085 signed-number overflow */
unsigned p : 1; /* bit 2: parity flag */
unsigned r : 1; /* bit 3: always zero */
unsigned a : 1; /* bit 4: auxiliary flag (nibble carry) */
unsigned k : 1; /* bit 5: K is for Kompressor (K = V flag â sgn(result)) */
unsigned z : 1; /* bit 6: zero flag */
unsigned s : 1; /* bit 7: sign flag */
unsigned t : 1; /* bit 8: it's a trap flag */
unsigned i : 1; /* bit 9: interrupt enable flag */
unsigned d : 1; /* bit 10: direction flag */
unsigned o : 1; /* bit 11: overflow flag */
unsigned pl : 2; /* b12-13: i/o privilege level (80286+) */
unsigned nt : 1; /* bit 14: nested task flag (80286+) */
unsigned pc : 1; /* bit 15: oldskool flag */
unsigned blah : 16;
unsigned blah2 : 32;
};
char *DescribeFlags(struct GodHatesFlags flags) {
static char buf[256];
buf[0] = 0;
if (flags.c) strcat(buf, "CF ");
if (flags.p) strcat(buf, "PF ");
if (flags.a) strcat(buf, "AF ");
if (flags.z) strcat(buf, "ZF ");
if (flags.s) strcat(buf, "SF ");
if (flags.t) strcat(buf, "TF ");
if (flags.i) strcat(buf, "IF ");
if (flags.d) strcat(buf, "DF ");
if (flags.o) strcat(buf, "OF ");
strcat(buf, "IOPL-");
switch (flags.pl) {
case 0:
strcat(buf, "0");
break;
case 1:
strcat(buf, "1");
break;
case 2:
strcat(buf, "2");
break;
case 3:
strcat(buf, "3");
break;
default:
__builtin_unreachable();
}
strcat(buf, " ");
if (flags.nt) strcat(buf, "NT ");
if (flags.r || flags.k || flags.pc) {
strcat(buf, "[WOW: ");
if (flags.v) strcat(buf, "VF ");
if (flags.k) strcat(buf, "KF ");
if (flags.r) strcat(buf, "RF ");
if (flags.pc) strcat(buf, "PC ");
strcat(buf, "] ");
}
return &buf[0];
}
void funk();
struct GodHatesFlags flags;
struct {
long gen[14];
long __pad[6];
unsigned long ymms[16][4];
} regs;
static const char regnames[][4] = {"rax", "rbx", "rcx", "rdx", "rdi", "rsi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"};
int main() {
funk();
printf("flags %45s\n\n", DescribeFlags(flags));
for (unsigned i = 0; i < 14; ++i) {
if (regs.gen[i]) {
printf("%s s 0x%08x %20d\\n", regnames[i], (signed)(regs.gen[i]), (signed)(regs.gen[i]));
printf(" u 0x%08x %20u\\n", (unsigned)(regs.gen[i]), (unsigned)(regs.gen[i]));
printf(" sll 0x%016llx %20lld\\n", (signed long long)(regs.gen[i]), (signed long long)(regs.gen[i]));
printf(" ull 0x%016llx %20llu\\n", (unsigned long long)(regs.gen[i]), (unsigned long long)(regs.gen[i]));
printf("\n");
}
}
for (unsigned i = 0; i < 16; ++i) {
if (regs.ymms[i][0] || regs.ymms[i][1] || regs.ymms[i][2] || regs.ymms[i][3]) {
printf("ymm%d%s %016lx%016lx%016lx%016lx\\n", i, i < 10 ? " " : "", regs.ymms[i][3], regs.ymms[i][2], regs.ymms[i][1], regs.ymms[i][0]);
}
}
return 0;
}
EOF
cc -c -g -o $c.o $c &&
cc -c -g -o $s1.o $s1 &&
cc -c -g -o $s2.o $s2 &&
cc -c -g -o $s3.o $s3 &&
cc -g -o $x $c $s1.o $s2.o $s3.o && {
echo
objdump -d $s2.o | sed 1,7d
echo
$x
}
exit
| 5,176 | 231 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/fix-third-party.py | #!/usr/bin/env python.com
#
# fix-third-party.py
# normalizes third party codebases to cosmopolitan style
#
# this script does the bulk of the work when it comes to fixing things
# like #include lines so they follow the local convention. this script
# won't get you all the way, but it'll get you pretty far w/ vendoring
#
# for example:
#
# cd bash-5.1.16
# mkdir ~/cosmo/third_party/bash
# cp -R *.c *.h builtins lib COPYING include/* ~/cosmo/third_party/bash
# cd ~/cosmo
# tool/scripts/fix-third-party.py third_party/bash
#
import os
import re
import sys
LIBC_ISYSTEM = 'libc/isystem/'
EXTENSIONS = ('.c', '.cc', '.cpp', '.h', '.hh', '.hpp', '.inc', '.tab', 'h.in')
isystem = {}
for dirpath, dirs, files in os.walk(LIBC_ISYSTEM):
for filepath in files:
path = os.path.join(dirpath, filepath)
with open(path) as f:
code = f.read()
name = path[len(LIBC_ISYSTEM):]
deps = re.findall(r'[.#]include "([^"]+)"', code)
isystem[name] = '\n'.join('#include "%s"' % (d) for d in deps)
def FixQuotedPath(path, incl):
p2 = os.path.join(os.path.dirname(path), incl)
if os.path.exists(incl) or not os.path.exists(p2):
return incl
else:
return os.path.normpath(p2)
def FixThirdParty(path):
# if not path.endswith(EXTENSIONS):
# return
print(path)
with open(path) as f:
code = f.read()
start = 0
res = []
if not code.startswith('// clang-format off\n'):
res.append('// clang-format off\n')
for m in re.finditer(r'(?:/[/*] MISSING )?#\s*include\s*"([^"]+)"(?: \*/)?', code):
end, newstart = m.span()
res.append(code[start:end])
inc = FixQuotedPath(path, m.group(1))
if os.path.exists(inc):
res.append('#include "%s"' % (inc))
else:
res.append('// MISSING #include "%s"' % (inc))
start = newstart
res.append(code[start:])
code = ''.join(res)
res = []
start = 0
for m in re.finditer(r'(?:/[/*] MISSING )?#\s*include\s*<([^>]+)>(?: \*/)?', code):
end, newstart = m.span()
res.append(code[start:end])
inc = m.group(1)
if inc in isystem:
res.append(isystem[inc])
else:
res.append('// MISSING #include <%s>' % (m.group(1)))
start = newstart
res.append(code[start:])
code = ''.join(res)
# print(code)
with open(path, 'wb') as f:
f.write(code.encode('utf-8'))
for arg in sys.argv[1:]:
if os.path.isdir(arg):
for dirpath, dirs, files in os.walk(arg):
for filepath in files:
FixThirdParty(os.path.join(dirpath, filepath))
else:
FixThirdParty(arg)
| 2,542 | 92 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/explain-deps.py | #!/usr/bin/env python.com
import os
import re
import sys
def GetDeps(path):
def Dive(path, depth, visited):
sys.stdout.write('%s%s' % ('\t' * depth, path))
if path in visited:
sys.stdout.write(' cycle\n')
return
sys.stdout.write('\n')
with open(path) as f:
code = f.read()
for dep in re.findall(r'[.#]include "([^"]+)"', code):
Dive(dep, depth + 1, visited + [path])
Dive(path, 0, [])
sys.stdout.write('\n')
for arg in sys.argv[1:]:
if os.path.isdir(arg):
for dirpath, dirs, files in os.walk(arg):
for filepath in files:
GetDeps(os.path.join(dirpath, filepath))
else:
GetDeps(arg)
| 660 | 28 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/pb | #!/bin/sh
exec python.com -c "
# -*- coding: utf-8 -*-
import sys
from math import *
x = $*
s = x < 0
x = abs(x)
b = str(bin(x))[2:].replace('L', '')
n = len(b)
if n <= 8: n = 8
elif n <= 16: n = 16
elif n <= 32: n = 32
elif n <= 64: n = 64
sys.stdout.write(('%%s0b%%0%dd' % n) % ('-' if s else '', int(b)))
"
| 314 | 17 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk8 | #!/bin/sh
exec awk "$@" '{print $8}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/performance | #!/bin/sh
echo "performance" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
| 94 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk6 | #!/bin/sh
exec awk "$@" '{print $6}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/bf | #!/bin/sh
bing.com <"$1" |
fold.com |
exec less
| 52 | 5 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk2 | #!/bin/sh
exec awk "$@" '{print $2}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk4 | #!/bin/sh
exec awk "$@" '{print $4}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/find-autonomous-objects | #-*-mode:sh;indent-tabs-mode:nil;tab-width:2;coding:utf-8-*-â
#âââvi: set net ft=sh ts=2 sts=2 fenc=utf-8 :viââââââââââââââ
for f; do
if [ $(nm $f | grep ' U ' | wc -l) -eq 0 ]; then
echo $f
fi
done
| 244 | 9 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk1 | #!/bin/sh
exec awk "$@" '{print $1}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/pe | #!/bin/sh
echo "# -*- coding: utf-8 -*-
import os
import sys
from math import *
s = str($*)
sys.stdout.write(s)
" >/tmp/pe
exec python.com /tmp/pe
| 147 | 10 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/bloat | #!/bin/sh
nm -C --size "$@" |
sort -r |
grep ' [bBtTRr] ' |
exec less
| 76 | 6 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/cosmoc++ | #!/bin/sh
# replacement for c++ command
#
# we assume you run the following beforehand
#
# sudo chmod 1777 /opt
# cd /opt
# git clone https://github.com/jart/cosmopolitan cosmo
# cd cosmo
# make -j
#
# you can then use it to build open source projects, e.g.
#
# export CC=cosmocc
# export CXX=cosmoc++
# export LD=cosmoc++
# ./configure --prefix=/opt/cosmos
# make -j
# make install
#
if [ "$1" = "--version" ]; then
cat <<'EOF'
x86_64-unknown-cosmo-g++ (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
EOF
exit 0
fi
CXX="/opt/cosmo/o/third_party/gcc/bin/x86_64-linux-musl-g++"
CCFLAGS="-O2 -fdata-sections -ffunction-sections -fno-pie -pg -mnop-mcount -mno-tls-direct-seg-refs"
CXXFLAGS="-fno-exceptions -fuse-cxa-atexit -fno-threadsafe-statics"
CPPFLAGS="-DNDEBUG -nostdinc -iquote /opt/cosmo -isystem /opt/cosmos/include -isystem /opt/cosmo/libc/isystem -include libc/integral/normalize.inc"
LDFLAGS="-static -no-pie -nostdlib -fuse-ld=bfd -Wl,-melf_x86_64 -Wl,--gc-sections -L/opt/cosmos/lib -Wl,-T,/opt/cosmo/o/ape/public/ape.lds /opt/cosmo/o/ape/ape-no-modify-self.o /opt/cosmo/o/libc/crt/crt.o"
LDLIBS="/opt/cosmo/o/third_party/libcxx/libcxx.a /opt/cosmo/o/cosmopolitan.a"
if [ ! -d $COSMO ]; then
echo you need to checkout cosmopolitan to your $COSMO directory >&2
exit 1
fi
if [ ! -d $COSMOS ]; then
echo you need to create your $COSMOS directory >&2
exit 1
fi
# auto-install some shell libraries
if [ ! -d $COSMOS/lib ]; then
mkdir $COSMOS/lib
for lib in c dl gcc_s m pthread resolv rt z stdc++; do
printf '\041\074\141\162\143\150\076\012' >$COSMOS/lib/lib$lib.a
done
fi
HAS_C=0
HAS_O=0
HAS_E=0
FIRST=1
for x; do
if [ $FIRST -eq 1 ]; then
set --
FIRST=0
fi
if [ "$x" = "-Werror" ]; then
# this toolchain is intended for building other people's code
# elevating warnings into errors, should only be done by devs
continue
fi
if [ "$x" = "-pedantic" ]; then
# this toolchain is intended for building other people's code
# we don't need the compiler's assistance to be more portable
continue
fi
if [ "$x" = "-c" ]; then
HAS_C=1
fi
if [ "$x" = "-E" ]; then
HAS_E=1
fi
if [ "$x" = "-o" ] || [ "${x#-o}" != "$x" ]; then
HAS_O=1
fi
set -- "$@" "$x"
done
if [ "$HAS_E" = "1" ]; then
set -- $CPPFLAGS "$@"
elif [ "$HAS_C" = "1" ]; then
set -- $CCFLAGS $CXXFLAGS $CPPFLAGS "$@" -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer
else
set -- $LDFLAGS $CXXFLAGS $CPPFLAGS "$@" $LDLIBS -Wl,-z,common-page-size=4096 -Wl,-z,max-page-size=4096
fi
set -- "$CXX" "$@"
printf '(cd %s; %s)\n' "$PWD" "$*" >>/tmp/build.log
exec "$@"
| 2,834 | 99 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk3 | #!/bin/sh
exec awk "$@" '{print $3}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/ezgdb | #!/bin/sh
PROG="$1"
shift
exec gdb "$PROG" -ex "set args $*" -ex run
| 69 | 5 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/resurrect-file | #-*-mode:sh;indent-tabs-mode:nil;tab-width:2;coding:utf-8-*-â
#âââvi: set net ft=sh ts=2 sts=2 fenc=utf-8 :viââââââââââââââ
git checkout $(git rev-list -n 1 HEAD -- "$1")^ -- "${1:?FILE}"
| 225 | 5 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/renameheader | #!/usr/bin/env bash
FROM="${1?from}"
TO="${2?to}"
if [ -f "$TO" ]; then
rm -f "$FROM" || exit
else
mv "$FROM" "$TO" || exit
fi
sed -i -e "s/$(echo "${FROM//\//_}" | sed 's/\./_/' | tr a-z A-Z)_H_/$(echo "${TO//\//_}" | sed 's/\./_/' | tr a-z A-Z)_H_/" "$TO" || exit
tool/scripts/grep -nH -RPie "\"$FROM\"" |
tool/scripts/awk1 -F: |
xargs sed -i -e "s/${FROM//\//\\/}/${TO//\//\\/}/"
| 394 | 16 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/awk7 | #!/bin/sh
exec awk "$@" '{print $7}'
| 37 | 3 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/loc | #!/bin/bash
echo $(( $(find ape dsp libc examples net test third_party tool -name \*.c | xargs cat | wc -l) +
$(find ape dsp libc examples net test third_party tool -name \*.h | xargs cat | wc -l) +
$(find ape dsp libc examples net test third_party tool -name \*.S | xargs cat | wc -l) +
$(find ape dsp libc examples net test third_party tool -name \*.el | xargs cat | wc -l) +
$(find ape dsp libc examples net test third_party tool -name \*.mk | xargs cat | wc -l) ))
| 508 | 7 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/obj | #!/bin/sh
objdump -Cwd "$@" |
exec less
| 42 | 4 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/px | #!/bin/sh
exec python.com -c "
# -*- coding: utf-8 -*-
import sys
from math import *
x = $*
s = x < 0
x = abs(x)
b = str(hex(x))[2:].replace('L', '')
n = len(b)
if n <= 2: n = 2
elif n <= 4: n = 4
elif n <= 8: n = 8
elif n <= 12: n = 12
elif n <= 16: n = 16
sys.stdout.write(('%%s0x%%0%dx' % n) % ('-' if s else '', int(b,16)))
"
| 338 | 18 | jart/cosmopolitan | false |
cosmopolitan/tool/scripts/po | #!/bin/sh
exec python.com -c "
import sys
from math import *
s = str(oct($*).replace('o',''))
if len(s) > 1: s = s[1:]
b = s.replace('L', '')
n = len(b)
if n <= 3: n = 3
elif n <= 6: n = 6
elif n <= 11: n = 11
elif n <= 22: n = 22
sys.stdout.write(('0%%0%dd' % n) % int(b))
"
| 282 | 15 | jart/cosmopolitan | false |
cosmopolitan/tool/curl/curl.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 += TOOL_CURL
TOOL_CURL_ARTIFACTS += TOOL_CURL_A
TOOL_CURL = $(TOOL_CURL_DEPS) $(TOOL_CURL_A)
TOOL_CURL_A = o/$(MODE)/tool/curl/curl.a
TOOL_CURL_FILES := $(wildcard tool/curl/*)
TOOL_CURL_HDRS = $(filter %.h,$(TOOL_CURL_FILES))
TOOL_CURL_INCS = $(filter %.inc,$(TOOL_CURL_FILES))
TOOL_CURL_SRCS = $(filter %.c,$(TOOL_CURL_FILES))
TOOL_CURL_OBJS = $(TOOL_CURL_SRCS:%.c=o/$(MODE)/%.o)
TOOL_CURL_DIRECTDEPS = \
LIBC_CALLS \
LIBC_DNS \
LIBC_FMT \
LIBC_INTRIN \
LIBC_LOG \
LIBC_MEM \
LIBC_NEXGEN32E \
LIBC_RUNTIME \
LIBC_SOCK \
LIBC_STDIO \
LIBC_STR \
LIBC_STUBS \
LIBC_SYSV \
LIBC_TIME \
LIBC_X \
LIBC_ZIPOS \
NET_HTTP \
NET_HTTPS \
THIRD_PARTY_GETOPT \
THIRD_PARTY_MBEDTLS
TOOL_CURL_DEPS := \
$(call uniq,$(foreach x,$(TOOL_CURL_DIRECTDEPS),$($(x))))
TOOL_CURL_CHECKS = \
$(TOOL_CURL_A).pkg \
$(TOOL_CURL_HDRS:%=o/$(MODE)/%.ok)
$(TOOL_CURL_A): \
tool/curl/ \
$(TOOL_CURL_A).pkg \
$(TOOL_CURL_OBJS)
$(TOOL_CURL_A).pkg: \
$(TOOL_CURL_OBJS) \
$(foreach x,$(TOOL_CURL_DIRECTDEPS),$($(x)_A).pkg)
o/$(MODE)/tool/curl/curl.com.dbg: \
$(TOOL_CURL) \
o/$(MODE)/tool/curl/cmd.o \
o/$(MODE)/tool/curl/curl.o \
$(CRT) \
$(APE_NO_MODIFY_SELF)
@$(APELINK)
TOOL_CURL_LIBS = $(TOOL_CURL_A)
TOOL_CURL_BINS = $(TOOL_CURL_COMS) $(TOOL_CURL_COMS:%=%.dbg)
TOOL_CURL_COMS = o/$(MODE)/tool/curl/curl.com
$(TOOL_CURL_OBJS): $(BUILD_FILES) tool/curl/curl.mk
.PHONY: o/$(MODE)/tool/curl
o/$(MODE)/tool/curl: \
$(TOOL_CURL_BINS) \
$(TOOL_CURL_CHECKS)
| 1,772 | 70 | jart/cosmopolitan | false |
cosmopolitan/tool/curl/curl.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/iovec.h"
#include "libc/dce.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/gc.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/goodsocket.internal.h"
#include "libc/sock/sock.h"
#include "libc/stdio/append.h"
#include "libc/stdio/rand.h"
#include "libc/stdio/stdio.h"
#include "libc/str/slice.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/shut.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/time/struct/tm.h"
#include "libc/x/x.h"
#include "libc/x/xsigaction.h"
#include "net/http/http.h"
#include "net/http/url.h"
#include "net/https/https.h"
#include "net/https/sslcache.h"
#include "third_party/getopt/getopt.h"
#include "third_party/mbedtls/ctr_drbg.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/pk.h"
#include "third_party/mbedtls/ssl.h"
#include "third_party/mbedtls/ssl_ticket.h"
#include "tool/curl/cmd.h"
/**
* @fileoverview Downloads HTTP URL to stdout.
*/
#define HasHeader(H) (!!msg.headers[H].a)
#define HeaderData(H) (p + msg.headers[H].a)
#define HeaderLength(H) (msg.headers[H].b - msg.headers[H].a)
#define HeaderEqualCase(H, S) \
SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))
int sock;
static bool TuneSocket(int fd, int a, int b, int x) {
if (!b) return false;
return setsockopt(fd, a, b, &x, sizeof(x)) != -1;
}
static void Write(const void *p, size_t n) {
ssize_t rc;
rc = write(1, p, n);
if (rc == -1 && errno == EPIPE) {
close(sock);
exit(128 + SIGPIPE);
}
if (rc != n) {
fprintf(stderr, "write failed: %m\n");
exit(1);
}
}
static int TlsSend(void *c, const unsigned char *p, size_t n) {
int rc;
NOISEF("begin send %zu", n);
CHECK_NE(-1, (rc = write(*(int *)c, p, n)));
NOISEF("end send %zu", n);
return rc;
}
static int TlsRecv(void *c, unsigned char *p, size_t n, uint32_t o) {
int r;
struct iovec v[2];
static unsigned a, b;
static unsigned char t[4096];
if (a < b) {
r = MIN(n, b - a);
memcpy(p, t + a, r);
if ((a += r) == b) a = b = 0;
return r;
}
v[0].iov_base = p;
v[0].iov_len = n;
v[1].iov_base = t;
v[1].iov_len = sizeof(t);
NOISEF("begin recv %zu", n + sizeof(t) - b);
CHECK_NE(-1, (r = readv(*(int *)c, v, 2)));
NOISEF("end recv %zu", r);
if (r > n) b = r - n;
return MIN(n, r);
}
static wontreturn void PrintUsage(FILE *f, int rc) {
fprintf(f, "usage: %s [-iksvV] URL\n", program_invocation_name);
exit(rc);
}
int _curl(int argc, char *argv[]) {
if (!NoDebug()) ShowCrashReports();
/*
* Read flags.
*/
int opt;
struct Headers {
size_t n;
char **p;
} headers = {0};
int method = 0;
bool authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
bool includeheaders = false;
const char *postdata = NULL;
const char *agent = "hurl/1.o (https://github.com/jart/cosmopolitan)";
__log_level = kLogWarn;
while ((opt = getopt(argc, argv, "qiksvVIX:H:A:d:")) != -1) {
switch (opt) {
case 's':
case 'q':
break;
case 'v':
++__log_level;
break;
case 'i':
includeheaders = true;
break;
case 'I':
method = kHttpHead;
break;
case 'A':
agent = optarg;
break;
case 'H':
headers.p = realloc(headers.p, ++headers.n * sizeof(*headers.p));
headers.p[headers.n - 1] = optarg;
break;
case 'd':
postdata = optarg;
break;
case 'X':
CHECK((method = GetHttpMethod(optarg, strlen(optarg))));
break;
case 'V':
++mbedtls_debug_threshold;
break;
case 'k':
authmode = MBEDTLS_SSL_VERIFY_NONE;
break;
case 'h':
PrintUsage(stdout, EXIT_SUCCESS);
default:
PrintUsage(stderr, EX_USAGE);
}
}
/*
* Get argument.
*/
const char *urlarg;
if (optind == argc) PrintUsage(stderr, EX_USAGE);
urlarg = argv[optind];
/*
* Parse URL.
*/
struct Url url;
char *host, *port;
bool usessl = false;
_gc(ParseUrl(urlarg, -1, &url, kUrlPlus));
_gc(url.params.p);
if (url.scheme.n) {
if (url.scheme.n == 5 && !memcasecmp(url.scheme.p, "https", 5)) {
usessl = true;
} else if (!(url.scheme.n == 4 && !memcasecmp(url.scheme.p, "http", 4))) {
fprintf(stderr, "error: not an http/https url: %s\n", urlarg);
exit(1);
}
}
if (url.host.n) {
host = _gc(strndup(url.host.p, url.host.n));
if (url.port.n) {
port = _gc(strndup(url.port.p, url.port.n));
} else {
port = usessl ? "443" : "80";
}
} else {
host = "127.0.0.1";
port = usessl ? "443" : "80";
}
if (!IsAcceptableHost(host, -1)) {
fprintf(stderr, "error: invalid host: %s\n", urlarg);
exit(1);
}
url.fragment.p = 0, url.fragment.n = 0;
url.scheme.p = 0, url.scheme.n = 0;
url.user.p = 0, url.user.n = 0;
url.pass.p = 0, url.pass.n = 0;
url.host.p = 0, url.host.n = 0;
url.port.p = 0, url.port.n = 0;
if (!url.path.n || url.path.p[0] != '/') {
char *p = _gc(xmalloc(1 + url.path.n));
mempcpy(mempcpy(p, "/", 1), url.path.p, url.path.n);
url.path.p = p;
++url.path.n;
}
/*
* Create HTTP message.
*/
if (!method) method = postdata ? kHttpPost : kHttpGet;
char *request = 0;
appendf(&request,
"%s %s HTTP/1.1\r\n"
"Connection: close\r\n"
"User-Agent: %s\r\n",
kHttpMethod[method], _gc(EncodeUrl(&url, 0)), agent);
bool senthost = false, sentcontenttype = false, sentcontentlength = false;
for (int i = 0; i < headers.n; ++i) {
appendf(&request, "%s\r\n", headers.p[i]);
if (!strncasecmp("Host:", headers.p[i], 5))
senthost = true;
else if (!strncasecmp("Content-Type:", headers.p[i], 13))
sentcontenttype = true;
else if (!strncasecmp("Content-Length:", headers.p[i], 15))
sentcontentlength = true;
}
if (!senthost) appendf(&request, "Host: %s:%s\r\n", host, port);
if (postdata) {
if (!sentcontenttype)
appends(&request, "Content-Type: application/x-www-form-urlencoded\r\n");
if (!sentcontentlength)
appendf(&request, "Content-Length: %d\r\n", strlen(postdata));
}
appendf(&request, "\r\n");
if (postdata) appends(&request, postdata);
/*
* Setup crypto.
*/
mbedtls_ssl_config conf;
mbedtls_ssl_context ssl;
mbedtls_ctr_drbg_context drbg;
if (usessl) {
mbedtls_ssl_init(&ssl);
mbedtls_ctr_drbg_init(&drbg);
mbedtls_ssl_config_init(&conf);
CHECK_EQ(0, mbedtls_ctr_drbg_seed(&drbg, GetEntropy, 0, "justine", 7));
CHECK_EQ(0, mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT));
mbedtls_ssl_conf_authmode(&conf, authmode);
mbedtls_ssl_conf_ca_chain(&conf, GetSslRoots(), 0);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &drbg);
if (!IsTiny()) mbedtls_ssl_conf_dbg(&conf, TlsDebug, 0);
CHECK_EQ(0, mbedtls_ssl_setup(&ssl, &conf));
CHECK_EQ(0, mbedtls_ssl_set_hostname(&ssl, host));
}
/*
* Perform DNS lookup.
*/
struct addrinfo *addr;
struct addrinfo hints = {.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP,
.ai_flags = AI_NUMERICSERV};
CHECK_EQ(EAI_SUCCESS, getaddrinfo(host, port, &hints, &addr));
/*
* Connect to server.
*/
int ret;
CHECK_NE(-1, (sock = GoodSocket(addr->ai_family, addr->ai_socktype,
addr->ai_protocol, false,
&(struct timeval){-60})));
CHECK_NE(-1, connect(sock, addr->ai_addr, addr->ai_addrlen));
freeaddrinfo(addr);
if (usessl) {
mbedtls_ssl_set_bio(&ssl, &sock, TlsSend, 0, TlsRecv);
if ((ret = mbedtls_ssl_handshake(&ssl))) {
TlsDie("ssl handshake", ret);
}
}
/*
* Send HTTP Message.
*/
size_t n;
n = appendz(request).i;
if (usessl) {
ret = mbedtls_ssl_write(&ssl, request, n);
if (ret != n) TlsDie("ssl write", ret);
} else {
CHECK_EQ(n, write(sock, request, n));
}
xsigaction(SIGPIPE, SIG_IGN, 0, 0, 0);
/*
* Handle response.
*/
int t;
char *p;
ssize_t rc;
struct HttpMessage msg;
struct HttpUnchunker u;
size_t g, i, hdrlen, paylen;
InitHttpMessage(&msg, kHttpResponse);
for (p = 0, hdrlen = paylen = t = i = n = 0;;) {
if (i == n) {
n += 1000;
n += n >> 1;
p = realloc(p, n);
}
if (usessl) {
if ((rc = mbedtls_ssl_read(&ssl, p + i, n - i)) < 0) {
if (rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
rc = 0;
} else {
TlsDie("ssl read", rc);
}
}
} else {
CHECK_NE(-1, (rc = read(sock, p + i, n - i)));
}
g = rc;
i += g;
switch (t) {
case kHttpClientStateHeaders:
CHECK(g);
CHECK_NE(-1, (rc = ParseHttpMessage(&msg, p, i)));
if (rc) {
hdrlen = rc;
if (100 <= msg.status && msg.status <= 199) {
CHECK(!HasHeader(kHttpContentLength) ||
HeaderEqualCase(kHttpContentLength, "0"));
CHECK(!HasHeader(kHttpTransferEncoding) ||
HeaderEqualCase(kHttpTransferEncoding, "identity"));
DestroyHttpMessage(&msg);
InitHttpMessage(&msg, kHttpResponse);
memmove(p, p + hdrlen, i - hdrlen);
i -= hdrlen;
break;
}
if (method == kHttpHead || includeheaders) {
Write(p, hdrlen);
}
if (method == kHttpHead || msg.status == 204 || msg.status == 304) {
goto Finished;
}
if (HasHeader(kHttpTransferEncoding) &&
!HeaderEqualCase(kHttpTransferEncoding, "identity")) {
CHECK(HeaderEqualCase(kHttpTransferEncoding, "chunked"));
t = kHttpClientStateBodyChunked;
memset(&u, 0, sizeof(u));
goto Chunked;
} else if (HasHeader(kHttpContentLength)) {
CHECK_NE(-1, (rc = ParseContentLength(
HeaderData(kHttpContentLength),
HeaderLength(kHttpContentLength))));
t = kHttpClientStateBodyLengthed;
paylen = rc;
if (paylen > i - hdrlen) {
Write(p + hdrlen, i - hdrlen);
} else {
Write(p + hdrlen, paylen);
goto Finished;
}
} else {
t = kHttpClientStateBody;
Write(p + hdrlen, i - hdrlen);
}
}
break;
case kHttpClientStateBody:
if (!g) goto Finished;
Write(p + i - g, g);
break;
case kHttpClientStateBodyLengthed:
CHECK(g);
if (i - hdrlen > paylen) g = hdrlen + paylen - (i - g);
Write(p + i - g, g);
if (i - hdrlen >= paylen) goto Finished;
break;
case kHttpClientStateBodyChunked:
Chunked:
CHECK_NE(-1, (rc = Unchunk(&u, p + hdrlen, i - hdrlen, &paylen)));
if (rc) {
Write(p + hdrlen, paylen);
goto Finished;
}
break;
default:
abort();
}
}
/*
* Close connection.
*/
Finished:
CHECK_NE(-1, close(sock));
/*
* Free memory.
*/
free(p);
free(headers.p);
if (usessl) {
mbedtls_ssl_free(&ssl);
mbedtls_ctr_drbg_free(&drbg);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&drbg);
}
return 0;
}
| 12,931 | 443 | jart/cosmopolitan | false |
cosmopolitan/tool/curl/cmd.h | #ifndef COSMOPOLITAN_TOOL_CURL_CMD_H_
#define COSMOPOLITAN_TOOL_CURL_CMD_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
int _curl(int, char *[]);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_TOOL_CURL_CMD_H_ */
| 274 | 11 | jart/cosmopolitan | false |
cosmopolitan/tool/curl/cmd.c | #include "tool/curl/cmd.h"
int main(int argc, char *argv[]) {
return _curl(argc, argv);
}
| 93 | 6 | jart/cosmopolitan | false |
cosmopolitan/tool/build/zipobj.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/elf/def.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/kprintf.h"
#include "libc/limits.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/mem/gc.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/s.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "libc/zip.h"
#include "third_party/getopt/getopt.h"
#include "tool/build/lib/elfwriter.h"
#include "tool/build/lib/stripcomponents.h"
char *name_;
char *yoink_;
char *symbol_;
char *outpath_;
bool nocompress_;
bool basenamify_;
int64_t image_base_;
int strip_components_;
const char *path_prefix_;
struct timespec timestamp;
size_t kZipCdirHdrLinkableSizeBootstrap;
wontreturn void PrintUsage(int rc) {
kprintf("%s%s%s\n", "Usage: ", program_invocation_name,
" [-n] [-B] [-C INT] [-P PREFIX] [-o FILE] [-s SYMBOL] [-y YOINK] "
"[FILE...]");
exit(rc);
}
void GetOpts(int *argc, char ***argv) {
int opt;
yoink_ = "__zip_start";
image_base_ = IMAGE_BASE_VIRTUAL;
kZipCdirHdrLinkableSizeBootstrap = kZipCdirHdrLinkableSize;
while ((opt = getopt(*argc, *argv, "?0nhBL:N:C:P:o:s:y:b:")) != -1) {
switch (opt) {
case 'o':
outpath_ = optarg;
break;
case 'n':
exit(0);
case 's':
symbol_ = optarg;
break;
case 'y':
yoink_ = optarg;
break;
case 'N':
name_ = optarg;
break;
case 'P':
path_prefix_ = optarg;
break;
case 'C':
strip_components_ = atoi(optarg);
break;
case 'B':
basenamify_ = true;
break;
case 'b':
image_base_ = strtol(optarg, NULL, 0);
break;
case '0':
nocompress_ = true;
break;
case 'L':
kZipCdirHdrLinkableSizeBootstrap = strtoul(optarg, NULL, 0);
break;
case '?':
case 'h':
PrintUsage(EXIT_SUCCESS);
default:
PrintUsage(EX_USAGE);
}
}
*argc -= optind;
*argv += optind;
CHECK_NOTNULL(outpath_);
}
void ProcessFile(struct ElfWriter *elf, const char *path) {
int fd;
void *map;
size_t pathlen;
struct stat st;
const char *name;
CHECK_NE(-1, (fd = open(path, O_RDONLY)));
CHECK_NE(-1, fstat(fd, &st));
if (S_ISDIR(st.st_mode)) {
map = "";
st.st_size = 0;
} else if (st.st_size) {
CHECK_NE(MAP_FAILED,
(map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)));
} else {
map = NULL;
}
if (name_) {
name = name_;
} else {
name = path;
if (basenamify_) name = basename(name);
name = StripComponents(name, strip_components_);
if (path_prefix_) name = gc(xjoinpaths(path_prefix_, name));
}
if (S_ISDIR(st.st_mode)) {
st.st_size = 0;
if (!_endswith(name, "/")) {
name = gc(xstrcat(name, '/'));
}
}
elfwriter_zip(elf, name, name, strlen(name), map, st.st_size, st.st_mode,
timestamp, timestamp, timestamp, nocompress_, image_base_,
kZipCdirHdrLinkableSizeBootstrap);
if (st.st_size) CHECK_NE(-1, munmap(map, st.st_size));
close(fd);
}
void PullEndOfCentralDirectoryIntoLinkage(struct ElfWriter *elf) {
elfwriter_align(elf, 1, 0);
elfwriter_startsection(elf, ".yoink", SHT_PROGBITS,
SHF_ALLOC | SHF_EXECINSTR);
elfwriter_yoink(elf, yoink_, STB_GLOBAL);
elfwriter_finishsection(elf);
}
void CheckFilenameKosher(const char *path) {
CHECK_LE(kZipCfileHdrMinSize + strlen(path),
kZipCdirHdrLinkableSizeBootstrap);
CHECK(!_startswith(path, "/"));
CHECK(!strstr(path, ".."));
}
void zipobj(int argc, char **argv) {
size_t i;
struct ElfWriter *elf;
CHECK_LT(argc, UINT16_MAX / 3 - 64); /* ELF 64k section limit */
GetOpts(&argc, &argv);
for (i = 0; i < argc; ++i) CheckFilenameKosher(argv[i]);
elf = elfwriter_open(outpath_, 0644);
elfwriter_cargoculting(elf);
for (i = 0; i < argc; ++i) ProcessFile(elf, argv[i]);
PullEndOfCentralDirectoryIntoLinkage(elf);
elfwriter_close(elf);
}
int main(int argc, char **argv) {
timestamp.tv_sec = 1647414000; /* determinism */
/* clock_gettime(CLOCK_REALTIME, ×tamp); */
zipobj(argc, argv);
return 0;
}
| 6,339 | 186 | jart/cosmopolitan | false |
cosmopolitan/tool/build/compile.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/copyfile.h"
#include "libc/calls/ioctl.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/winsize.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/limits.h"
#include "libc/log/appendresourcereport.internal.h"
#include "libc/log/color.internal.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/math.h"
#include "libc/mem/alg.h"
#include "libc/mem/copyfd.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/kcpuids.h"
#include "libc/nexgen32e/x86feature.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/auxv.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/termios.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "third_party/getopt/getopt.h"
#define MANUAL \
"\
SYNOPSIS\n\
\n\
compile.com [FLAGS] COMMAND [ARGS...]\n\
\n\
OVERVIEW\n\
\n\
Build Command Harness\n\
\n\
DESCRIPTION\n\
\n\
This is a generic command wrapper, e.g.\n\
\n\
compile.com gcc -o program program.c\n\
\n\
This wrapper provides the following services:\n\
\n\
- Logging latency and memory usage\n\
- Ensures the output directory exists\n\
- Discarding stderr when commands succeed\n\
- Imposing cpu / memory / file size quotas\n\
- Mapping stdin to /dev/null when not a file or fifo\n\
- Buffering stderr to minimize build log interleaving\n\
- Schlepping stdout into stderr when not a file or fifo\n\
- Magic filtering of GCC vs. Clang flag incompatibilities\n\
- Echo the launched subcommand (silent mode supported if V=0)\n\
- Unzips the vendored GCC toolchain if it hasn't happened yet\n\
- Making temporary copies of APE executables w/o side-effects\n\
- Truncating long lines in \"TERM=dumb\" terminals like emacs\n\
\n\
Programs running under make that don't wish to have their output\n\
suppressed (e.g. unit tests with the -b benchmarking flag) shall\n\
use the exit code `254` which is remapped to `0` with the output\n\
\n\
FLAGS\n\
\n\
-t touch target on success\n\
-T TARGET specifies target name for V=0 logging\n\
-A ACTION specifies short command name for V=0 logging\n\
-V NUMBER specifies compiler version\n\
-C SECS set cpu limit [default 16]\n\
-L SECS set lat limit [default 90]\n\
-P PROCS set pro limit [default 2048]\n\
-M BYTES set mem limit [default 512m]\n\
-F BYTES set fsz limit [default 256m]\n\
-O BYTES set out limit [default 1m]\n\
-s decrement verbosity [default 4]\n\
-v increments verbosity [default 4]\n\
-n do nothing (prime ape executable)\n\
-w disable landlock tmp workaround\n\
-h print help\n\
\n\
ENVIRONMENT\n\
\n\
V=0 print shortened ephemerally\n\
V=1 print shortened\n\
V=2 print command\n\
V=3 print shortened w/ wall+cpu+mem usage\n\
V=4 print command w/ wall+cpu+mem usage\n\
V=5 print output when exitcode is zero\n\
COLUMNS=INT explicitly set terminal width for output truncation\n\
TERM=dumb disable ansi x3.64 sequences and thousands separators\n\
\n"
struct Strings {
size_t n;
char **p;
};
bool isar;
bool iscc;
bool ispkg;
bool isgcc;
bool isbfd;
bool wantpg;
bool wantnop;
bool isclang;
bool wantnopg;
bool wantasan;
bool wantframe;
bool wantubsan;
bool wantfentry;
bool wantrecord;
bool fulloutput;
bool touchtarget;
bool noworkaround;
bool wantnoredzone;
bool stdoutmustclose;
bool no_sanitize_null;
bool no_sanitize_alignment;
bool no_sanitize_pointer_overflow;
int verbose;
int timeout;
int gotalrm;
int gotchld;
int ccversion;
int pipefds[2];
long cpuquota;
long fszquota;
long memquota;
long proquota;
long outquota;
char *cmd;
char *mode;
char *outdir;
char *action;
char *target;
char *output;
char *outpath;
char *command;
char *movepath;
char *shortened;
char *colorflag;
char ccpath[PATH_MAX];
struct stat st;
struct Strings env;
struct Strings args;
struct sigaction sa;
struct rusage usage;
struct timespec start;
struct timespec finish;
struct itimerval timer;
struct timespec signalled;
sigset_t mask;
sigset_t savemask;
char buf[PAGESIZE];
char tmpout[PATH_MAX];
const char *const kSafeEnv[] = {
"ADDR2LINE", // needed by GetAddr2linePath
"HOME", // needed by ~/.runit.psk
"HOMEDRIVE", // needed by ~/.runit.psk
"HOMEPATH", // needed by ~/.runit.psk
"MAKEFLAGS", // needed by IsRunningUnderMake
"MODE", // needed by test scripts
"PATH", // needed by clang
"PWD", // just seems plain needed
"STRACE", // useful for troubleshooting
"TERM", // needed to detect colors
"TMPDIR", // needed by compiler
};
const char *const kGccOnlyFlags[] = {
"--nocompress-debug-sections",
"--noexecstack",
"-Wa,--nocompress-debug-sections",
"-Wa,--noexecstack",
"-Wa,-msse2avx",
"-Wno-unused-but-set-variable",
"-Wunsafe-loop-optimizations",
"-fbranch-target-load-optimize",
"-fcx-limited-range",
"-fdelete-dead-exceptions",
"-femit-struct-debug-baseonly",
"-fipa-pta",
"-fivopts",
"-flimit-function-alignment",
"-fmerge-constants",
"-fmodulo-sched",
"-fmodulo-sched-allow-regmoves",
"-fno-align-jumps",
"-fno-align-labels",
"-fno-align-loops",
"-fno-fp-int-builtin-inexact",
"-fno-gnu-unique",
"-fno-gnu-unique",
"-fno-instrument-functions",
"-fno-schedule-insns2",
"-fno-whole-program",
"-fopt-info-vec",
"-fopt-info-vec-missed",
"-freg-struct-return",
"-freschedule-modulo-scheduled-loops",
"-frounding-math",
"-fsched2-use-superblocks",
"-fschedule-insns",
"-fschedule-insns2",
"-fshrink-wrap",
"-fshrink-wrap-separate",
"-fsignaling-nans",
"-fstack-clash-protection",
"-ftracer",
"-ftrapv",
"-ftree-loop-im",
"-ftree-loop-vectorize",
"-funsafe-loop-optimizations",
"-fversion-loops-for-strides",
"-fwhole-program",
"-gdescribe-dies",
"-gstabs",
"-mcall-ms2sysv-xlogues",
"-mdispatch-scheduler",
"-mfpmath=sse+387",
"-mmitigate-rop",
"-mno-fentry",
};
void OnAlrm(int sig) {
++gotalrm;
}
void OnChld(int sig, siginfo_t *si, void *ctx) {
if (!gotchld++) {
clock_gettime(CLOCK_MONOTONIC, &signalled);
}
}
void PrintBold(void) {
if (!__nocolor) {
appends(&output, "\e[1m");
}
}
void PrintRed(void) {
if (!__nocolor) {
appends(&output, "\e[91;1m");
}
}
void PrintReset(void) {
if (!__nocolor) {
appends(&output, "\e[0m");
}
}
void PrintMakeCommand(void) {
const char *s;
appends(&output, "make MODE=");
appends(&output, mode);
appends(&output, " -j");
appendd(&output, buf, FormatUint64(buf, _getcpucount()) - buf);
appendw(&output, ' ');
appends(&output, target);
}
uint64_t GetTimevalMicros(struct timeval tv) {
return tv.tv_sec * 1000000ull + tv.tv_usec;
}
uint64_t GetTimespecMicros(struct timespec ts) {
return ts.tv_sec * 1000000ull + ts.tv_nsec / 1000;
}
ssize_t WriteAllUntilSignalledOrError(int fd, const char *p, size_t n) {
ssize_t rc;
size_t i, got;
for (i = 0; i < n; i += got) {
if ((rc = write(fd, p + i, n - i)) != -1) {
got = rc;
} else {
return -1;
}
}
return i;
}
int GetTerminalWidth(void) {
char *s;
struct winsize ws;
if ((s = getenv("COLUMNS"))) {
return atoi(s);
} else {
ws.ws_col = 0;
ioctl(2, TIOCGWINSZ, &ws);
return ws.ws_col;
}
}
int GetLineWidth(bool *isineditor) {
char *s;
struct winsize ws = {0};
s = getenv("COLUMNS");
if (isineditor) {
*isineditor = !!s;
}
if (s) {
return atoi(s);
} else if (ioctl(2, TIOCGWINSZ, &ws) != -1) {
if (ws.ws_col && ws.ws_row) {
return ws.ws_col * ws.ws_row / 3;
} else {
return 2048;
}
} else {
return INT_MAX;
}
}
bool IsSafeEnv(const char *s) {
const char *p;
int n, m, l, r, x;
p = strchr(s, '=');
n = p ? p - s : -1;
l = 0;
r = ARRAYLEN(kSafeEnv) - 1;
while (l <= r) {
m = (l + r) >> 1;
x = strncmp(s, kSafeEnv[m], n);
if (x < 0) {
r = m - 1;
} else if (x > 0) {
l = m + 1;
} else {
return true;
}
}
return false;
}
bool IsGccOnlyFlag(const char *s) {
int m, l, r, x;
l = 0;
r = ARRAYLEN(kGccOnlyFlags) - 1;
while (l <= r) {
m = (l + r) >> 1;
x = strcmp(s, kGccOnlyFlags[m]);
if (x < 0) {
r = m - 1;
} else if (x > 0) {
l = m + 1;
} else {
return true;
}
}
if (_startswith(s, "-ffixed-")) return true;
if (_startswith(s, "-fcall-saved")) return true;
if (_startswith(s, "-fcall-used")) return true;
if (_startswith(s, "-fgcse-")) return true;
if (_startswith(s, "-fvect-cost-model=")) return true;
if (_startswith(s, "-fsimd-cost-model=")) return true;
if (_startswith(s, "-fopt-info")) return true;
if (_startswith(s, "-mstringop-strategy=")) return true;
if (_startswith(s, "-mpreferred-stack-boundary=")) return true;
if (_startswith(s, "-Wframe-larger-than=")) return true;
return false;
}
bool FileExistsAndIsNewerThan(const char *filepath, const char *thanpath) {
struct stat st1, st2;
if (stat(filepath, &st1) == -1) return false;
if (stat(thanpath, &st2) == -1) return false;
if (st1.st_mtim.tv_sec < st2.st_mtim.tv_sec) return false;
if (st1.st_mtim.tv_sec > st2.st_mtim.tv_sec) return true;
return st1.st_mtim.tv_nsec >= st2.st_mtim.tv_nsec;
}
static size_t TallyArgs(char **p) {
size_t n;
for (n = 0; *p; ++p) {
n += sizeof(*p);
n += strlen(*p) + 1;
}
return n;
}
void AddStr(struct Strings *l, char *s) {
l->p = realloc(l->p, (++l->n + 1) * sizeof(*l->p));
l->p[l->n - 1] = s;
l->p[l->n - 0] = 0;
}
void AddEnv(char *s) {
AddStr(&env, s);
}
char *StripPrefix(char *s, char *p) {
if (_startswith(s, p)) {
return s + strlen(p);
} else {
return s;
}
}
void AddArg(char *s) {
if (args.n) {
appendw(&command, ' ');
}
appends(&command, s);
if (!args.n) {
appends(&shortened, StripPrefix(basename(s), "x86_64-linux-musl-"));
} else if (*s != '-') {
appendw(&shortened, ' ');
if ((isar || isbfd || ispkg) &&
(strcmp(args.p[args.n - 1], "-o") &&
(_endswith(s, ".o") || _endswith(s, ".pkg") ||
(_endswith(s, ".a") && !isar)))) {
appends(&shortened, basename(s));
} else {
appends(&shortened, s);
}
} else if (/*
* a in ('-', '--') or
* a._startswith('-o') or
* c == 'ld' and a == '-T' or
* c == 'cc' and a._startswith('-O') or
* c == 'cc' and a._startswith('-x') or
* c == 'cc' and a in ('-c', '-E', '-S')
*/
s[0] == '-' && (!s[1] || s[1] == 'o' || (s[1] == '-' && !s[2]) ||
(isbfd && (s[1] == 'T' && !s[2])) ||
(iscc && (s[1] == 'O' || s[1] == 'x' ||
(!s[2] && (s[1] == 'c' || s[1] == 'E' ||
s[1] == 'S')))))) {
appendw(&shortened, ' ');
appends(&shortened, s);
}
AddStr(&args, s);
}
static int GetBaseCpuFreqMhz(void) {
return KCPUIDS(16H, EAX) & 0x7fff;
}
void SetCpuLimit(int secs) {
int mhz, lim;
struct rlimit rlim;
if (secs <= 0) return;
if (IsWindows()) return;
#ifdef __x86_64__
if (!(mhz = GetBaseCpuFreqMhz())) return;
lim = ceil(3100. / mhz * secs);
rlim.rlim_cur = lim;
rlim.rlim_max = lim + 1;
if (setrlimit(RLIMIT_CPU, &rlim) == -1) {
if (getrlimit(RLIMIT_CPU, &rlim) == -1) return;
if (lim < rlim.rlim_cur) {
rlim.rlim_cur = lim;
setrlimit(RLIMIT_CPU, &rlim);
}
}
#endif
}
void SetFszLimit(long n) {
struct rlimit rlim;
if (n <= 0) return;
if (IsWindows()) return;
rlim.rlim_cur = n;
rlim.rlim_max = n + (n >> 1);
if (setrlimit(RLIMIT_FSIZE, &rlim) == -1) {
if (getrlimit(RLIMIT_FSIZE, &rlim) == -1) return;
rlim.rlim_cur = n;
setrlimit(RLIMIT_FSIZE, &rlim);
}
}
void SetMemLimit(long n) {
struct rlimit rlim = {n, n};
if (n <= 0) return;
if (IsWindows() || IsXnu()) return;
setrlimit(RLIMIT_AS, &rlim);
}
void SetProLimit(long n) {
struct rlimit rlim = {n, n};
if (n <= 0) return;
setrlimit(RLIMIT_NPROC, &rlim);
}
bool ArgNeedsShellQuotes(const char *s) {
if (*s) {
for (;;) {
switch (*s++ & 255) {
case 0:
return false;
case '-':
case '.':
case '/':
case '_':
case '=':
case ':':
case '0' ... '9':
case 'A' ... 'Z':
case 'a' ... 'z':
break;
default:
return true;
}
}
} else {
return true;
}
}
char *AddShellQuotes(const char *s) {
char *p, *q;
size_t i, j, n;
n = strlen(s);
p = malloc(1 + n * 5 + 1 + 1);
j = 0;
p[j++] = '\'';
for (i = 0; i < n; ++i) {
if (s[i] != '\'') {
p[j++] = s[i];
} else {
p[j + 0] = '\'';
p[j + 1] = '"';
p[j + 2] = '\'';
p[j + 3] = '"';
p[j + 4] = '\'';
j += 5;
}
}
p[j++] = '\'';
p[j] = 0;
if ((q = realloc(p, j + 1))) p = q;
return p;
}
void MakeDirs(const char *path, int mode) {
if (makedirs(path, mode)) {
kprintf("error: makedirs(%#s) failed\n", path);
exit(1);
}
}
int Launch(void) {
size_t got;
ssize_t rc;
int ws, pid;
uint64_t us;
gotchld = 0;
if (pipe2(pipefds, O_CLOEXEC) == -1) {
kprintf("pipe2 failed: %s\n", _strerrno(errno));
exit(1);
}
clock_gettime(CLOCK_MONOTONIC, &start);
if (timeout > 0) {
timer.it_value.tv_sec = timeout;
timer.it_interval.tv_sec = timeout;
setitimer(ITIMER_REAL, &timer, 0);
}
pid = vfork();
if (pid == -1) {
kprintf("vfork failed: %s\n", _strerrno(errno));
exit(1);
}
#if 0
int fd;
size_t n;
char b[1024], *p;
size_t t = strlen(cmd) + 1 + TallyArgs(args.p) + 9 + TallyArgs(env.p) + 9;
n = ksnprintf(b, sizeof(b), "%ld %s %s\n", t, cmd, outpath);
fd = open("o/argmax.txt", O_APPEND | O_CREAT | O_WRONLY, 0644);
write(fd, b, n);
close(fd);
#endif
if (!pid) {
SetCpuLimit(cpuquota);
SetFszLimit(fszquota);
SetMemLimit(memquota);
SetProLimit(proquota);
if (stdoutmustclose) dup2(pipefds[1], 1);
dup2(pipefds[1], 2);
sigprocmask(SIG_SETMASK, &savemask, 0);
execve(cmd, args.p, env.p);
kprintf("execve(%#s) failed: %s\n", cmd, _strerrno(errno));
_Exit(127);
}
close(pipefds[1]);
for (;;) {
if (gotchld) {
rc = 0;
break;
}
if (gotalrm) {
PrintRed();
appends(&output, "\n\n`");
PrintMakeCommand();
appends(&output, "` timed out after ");
appendd(&output, buf, FormatInt64(buf, timeout) - buf);
appends(&output, " seconds! ");
PrintReset();
kill(pid, SIGXCPU);
rc = -1;
break;
}
if ((rc = read(pipefds[0], buf, sizeof(buf))) != -1) {
if (!(got = rc)) break;
appendd(&output, buf, got);
if (outquota > 0 && appendz(output).i > outquota) {
kill(pid, SIGXFSZ);
PrintRed();
appendw(&output, '`');
PrintMakeCommand();
appends(&output, "` printed ");
appendd(&output, buf,
FormatUint64Thousands(buf, appendz(output).i) - buf);
appends(&output, " bytes of output which exceeds the limit ");
appendd(&output, buf, FormatUint64Thousands(buf, outquota) - buf);
appendw(&output, READ16LE("! "));
PrintReset();
rc = -1;
break;
}
} else if (errno == EINTR) {
continue;
} else {
/* this should never happen */
PrintRed();
appends(&output, "error: compile.com read() failed w/ ");
appendd(&output, buf, FormatInt64(buf, errno) - buf);
PrintReset();
appendw(&output, READ16LE(": "));
kill(pid, SIGTERM);
break;
}
}
close(pipefds[0]);
while (wait4(pid, &ws, 0, &usage) == -1) {
if (errno == EINTR) {
if (gotalrm > 1) {
PrintRed();
appends(&output, "and it willfully ignored our SIGXCPU signal! ");
PrintReset();
kill(pid, SIGKILL);
gotalrm = 1;
}
} else if (errno == ECHILD) {
break;
} else {
/* this should never happen */
PrintRed();
appends(&output, "error: compile.com wait4() failed w/ ");
appendd(&output, buf, FormatInt64(buf, errno) - buf);
PrintReset();
appendw(&output, READ16LE(": "));
ws = -1;
break;
}
}
clock_gettime(CLOCK_MONOTONIC, &finish);
if (gotchld) {
us = GetTimespecMicros(finish) - GetTimespecMicros(signalled);
if (us > 1000000) {
appends(&output, "wut: compile.com needed ");
appendd(&output, buf, FormatUint64Thousands(buf, us) - buf);
appends(&output, "µs to wait() for zombie ");
rc = -1;
}
if (gotchld > 1) {
appends(&output, "wut: compile.com got multiple sigchld?! ");
rc = -1;
}
}
return ws | rc;
}
void ReportResources(void) {
uint64_t us;
appendw(&output, '\n');
if ((us = GetTimespecMicros(finish) - GetTimespecMicros(start))) {
appends(&output, "consumed ");
appendd(&output, buf, FormatUint64Thousands(buf, us) - buf);
appends(&output, "µs wall time\n");
}
AppendResourceReport(&output, &usage, "\n");
appendw(&output, '\n');
}
bool MovePreservingDestinationInode(const char *from, const char *to) {
bool res;
ssize_t rc;
size_t remain;
struct stat st;
int fdin, fdout;
if ((fdin = open(from, O_RDONLY)) == -1) {
return false;
}
fstat(fdin, &st);
if ((fdout = creat(to, st.st_mode)) == -1) {
close(fdin);
return false;
}
fadvise(fdin, 0, st.st_size, MADV_SEQUENTIAL);
ftruncate(fdout, st.st_size);
for (res = true, remain = st.st_size; remain;) {
rc = copy_file_range(fdin, 0, fdout, 0, remain, 0);
if (rc != -1) {
remain -= rc;
} else if (errno == EXDEV || errno == ENOSYS) {
if (lseek(fdin, 0, SEEK_SET) == -1) {
kprintf("%s: failed to lseek\n", from);
res = false;
break;
}
if (lseek(fdout, 0, SEEK_SET) == -1) {
kprintf("%s: failed to lseek\n", to);
res = false;
break;
}
res = _copyfd(fdin, fdout, -1) != -1;
break;
} else {
res = false;
break;
}
}
close(fdin);
close(fdout);
return res;
}
bool IsNativeExecutable(const char *path) {
bool res;
char buf[4];
int got, fd;
res = false;
if ((fd = open(path, O_RDONLY)) != -1) {
if ((got = read(fd, buf, 4)) == 4) {
if (IsWindows()) {
res = READ16LE(buf) == READ16LE("MZ");
} else if (IsXnu()) {
res = READ32LE(buf) == 0xFEEDFACEu + 1;
} else {
res = READ32LE(buf) == READ32LE("\177ELF");
}
}
close(fd);
}
return res;
}
char *MakeTmpOut(const char *path) {
int c;
char *p = tmpout;
char *e = tmpout + sizeof(tmpout) - 1;
p = stpcpy(p, kTmpPath);
while ((c = *path++)) {
if (c == '/') c = '_';
if (p == e) {
kprintf("MakeTmpOut path too long: %s\n", tmpout);
exit(1);
}
*p++ = c;
}
*p = 0;
return tmpout;
}
int main(int argc, char *argv[]) {
int columns;
uint64_t us;
bool isineditor;
size_t i, j, n, m;
bool isproblematic;
int ws, opt, exitcode;
char *s, *p, *q, **envp;
mode = firstnonnull(getenv("MODE"), MODE);
/*
* parse prefix arguments
*/
verbose = 4;
timeout = 90; /* secs */
cpuquota = 16; /* secs */
proquota = 2048; /* procs */
fszquota = 256 * 1000 * 1000; /* bytes */
memquota = 512 * 1024 * 1024; /* bytes */
if ((s = getenv("V"))) verbose = atoi(s);
while ((opt = getopt(argc, argv, "hnstvwA:C:F:L:M:O:P:T:V:")) != -1) {
switch (opt) {
case 'n':
exit(0);
case 's':
--verbose;
break;
case 'v':
++verbose;
break;
case 'A':
action = optarg;
break;
case 'T':
target = optarg;
break;
case 't':
touchtarget = true;
break;
case 'w':
noworkaround = true;
break;
case 'L':
timeout = atoi(optarg);
break;
case 'C':
cpuquota = atoi(optarg);
break;
case 'V':
ccversion = atoi(optarg);
break;
case 'P':
proquota = atoi(optarg);
break;
case 'F':
fszquota = sizetol(optarg, 1000);
break;
case 'M':
memquota = sizetol(optarg, 1024);
break;
case 'O':
outquota = sizetol(optarg, 1024);
break;
case 'h':
fputs(MANUAL, stdout);
exit(0);
default:
fputs(MANUAL, stderr);
exit(1);
}
}
if (optind == argc) {
fputs("error: missing arguments\n", stderr);
exit(1);
}
/*
* extend limits for slow UBSAN in particular
*/
if (!strcmp(mode, "dbg") || !strcmp(mode, "ubsan")) {
cpuquota *= 2;
fszquota *= 2;
memquota *= 2;
timeout *= 2;
}
cmd = argv[optind];
if (!strchr(cmd, '/')) {
if (!(cmd = commandv(cmd, ccpath, sizeof(ccpath)))) exit(127);
}
s = basename(strdup(cmd));
if (strstr(s, "gcc")) {
iscc = true;
isgcc = true;
} else if (strstr(s, "clang")) {
iscc = true;
isclang = true;
} else if (strstr(s, "ld.bfd")) {
isbfd = true;
} else if (strstr(s, "ar.com")) {
isar = true;
} else if (strstr(s, "package.com")) {
ispkg = true;
}
/*
* ingest arguments
*/
for (i = optind; i < argc; ++i) {
/*
* replace output filename argument
*
* some commands (e.g. ar) don't use the `-o PATH` notation. in that
* case we assume the output path was passed to compile.com -TTARGET
* which means we can replace the appropriate command line argument.
*/
if (!noworkaround && //
!movepath && //
!outpath && //
target && //
!strcmp(target, argv[i])) {
AddArg(MakeTmpOut(argv[i]));
outpath = target;
movepath = target;
MovePreservingDestinationInode(target, tmpout);
continue;
}
/*
* capture arguments
*/
if (argv[i][0] != '-') {
AddArg(argv[i]);
continue;
}
/*
* capture flags
*/
if (_startswith(argv[i], "-o")) {
if (!strcmp(argv[i], "-o")) {
outpath = argv[++i];
} else {
outpath = argv[i] + 2;
}
AddArg("-o");
if (noworkaround) {
AddArg(outpath);
} else {
movepath = outpath;
AddArg(MakeTmpOut(outpath));
}
continue;
}
if (!iscc) {
AddArg(argv[i]);
continue;
}
if (isclang && IsGccOnlyFlag(argv[i])) {
continue;
}
if (!X86_HAVE(AVX) &&
(!strcmp(argv[i], "-msse2avx") || !strcmp(argv[i], "-Wa,-msse2avx"))) {
// Avoid any chance of people using Intel's older or low power
// CPUs encountering a SIGILL error due to these awesome flags
continue;
}
if (!strcmp(argv[i], "-w")) {
AddArg(argv[i]);
AddArg("-D__W__");
} else if (!strcmp(argv[i], "-Oz")) {
if (isclang) {
AddArg(argv[i]);
} else {
AddArg("-Os");
}
} else if (!strcmp(argv[i], "-pg")) {
wantpg = true;
} else if (!strcmp(argv[i], "-x-no-pg")) {
wantnopg = true;
} else if (!strcmp(argv[i], "-mfentry")) {
wantfentry = true;
} else if (!strcmp(argv[i], "-mnop-mcount")) {
wantnop = true;
} else if (!strcmp(argv[i], "-mrecord-mcount")) {
wantrecord = true;
} else if (!strcmp(argv[i], "-fno-omit-frame-pointer")) {
wantframe = true;
} else if (!strcmp(argv[i], "-fomit-frame-pointer")) {
wantframe = false;
} else if (!strcmp(argv[i], "-mno-red-zone")) {
wantnoredzone = true;
} else if (!strcmp(argv[i], "-mred-zone")) {
wantnoredzone = false;
} else if (!strcmp(argv[i], "-mno-vzeroupper")) {
if (isgcc) {
AddArg("-Wa,-msse2avx");
AddArg("-D__MNO_VZEROUPPER__");
} else if (isclang) {
AddArg("-mllvm");
AddArg("-x86-use-vzeroupper=0");
}
} else if (!strcmp(argv[i], "-msse2avx")) {
if (isgcc) {
AddArg(argv[i]);
}
} else if (!strcmp(argv[i], "-fsanitize=address")) {
if (isgcc && ccversion >= 6) wantasan = true;
} else if (!strcmp(argv[i], "-fsanitize=undefined")) {
if (isgcc && ccversion >= 6) wantubsan = true;
} else if (!strcmp(argv[i], "-fno-sanitize=address")) {
wantasan = false;
} else if (!strcmp(argv[i], "-fno-sanitize=undefined")) {
wantubsan = false;
} else if (!strcmp(argv[i], "-fno-sanitize=all")) {
wantasan = false;
wantubsan = false;
} else if (!strcmp(argv[i], "-fno-sanitize=null")) {
if (isgcc && ccversion >= 6) no_sanitize_null = true;
} else if (!strcmp(argv[i], "-fno-sanitize=alignment")) {
if (isgcc && ccversion >= 6) no_sanitize_alignment = true;
} else if (!strcmp(argv[i], "-fno-sanitize=pointer-overflow")) {
if (isgcc && ccversion >= 6) no_sanitize_pointer_overflow = true;
} else if (_startswith(argv[i], "-fsanitize=implicit") &&
strstr(argv[i], "integer")) {
if (isgcc) AddArg(argv[i]);
} else if (_startswith(argv[i], "-fvect-cost") ||
_startswith(argv[i], "-mstringop") ||
_startswith(argv[i], "-gz") ||
strstr(argv[i], "stack-protector") ||
strstr(argv[i], "sanitize") ||
_startswith(argv[i], "-fvect-cost") ||
_startswith(argv[i], "-fvect-cost")) {
if (isgcc && ccversion >= 6) {
AddArg(argv[i]);
}
} else if (_startswith(argv[i], "-fdiagnostic-color=")) {
colorflag = argv[i];
} else if (_startswith(argv[i], "-R") ||
!strcmp(argv[i], "-fsave-optimization-record")) {
if (isclang) AddArg(argv[i]);
} else if (isclang && _startswith(argv[i], "--debug-prefix-map")) {
/* llvm doesn't provide a gas interface so simulate w/ clang */
AddArg(xstrcat("-f", argv[i] + 2));
} else if (isgcc && (!strcmp(argv[i], "-Os") || !strcmp(argv[i], "-O2") ||
!strcmp(argv[i], "-O3"))) {
/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97623 */
AddArg(argv[i]);
AddArg("-fno-code-hoisting");
} else {
AddArg(argv[i]);
}
}
if (outpath) {
if (!target) {
target = outpath;
}
} else if (target) {
outpath = target;
} else {
fputs("error: compile.com needs -TTARGET or -oOUTPATH\n", stderr);
exit(7);
}
/*
* append special args
*/
if (iscc) {
if (isclang) {
AddArg("-Wno-unused-command-line-argument");
AddArg("-Wno-incompatible-pointer-types-discards-qualifiers");
}
if (!__nocolor) {
AddArg(firstnonnull(colorflag, "-fdiagnostics-color=always"));
}
if (wantpg && !wantnopg) {
AddArg("-pg");
AddArg("-D__PG__");
if (wantnop && !isclang) {
AddArg("-mnop-mcount");
AddArg("-D__MNOP_MCOUNT__");
}
if (wantrecord) {
AddArg("-mrecord-mcount");
AddArg("-D__MRECORD_MCOUNT__");
}
if (wantfentry) {
AddArg("-mfentry");
AddArg("-D__MFENTRY__");
}
}
if (wantasan) {
AddArg("-fsanitize=address");
/* compiler adds this by default */
/* AddArg("-D__SANITIZE_ADDRESS__"); */
}
if (wantubsan) {
AddArg("-fsanitize=undefined");
AddArg("-fno-data-sections");
AddArg("-D__SANITIZE_UNDEFINED__");
}
if (no_sanitize_null) {
AddArg("-fno-sanitize=null");
}
if (no_sanitize_alignment) {
AddArg("-fno-sanitize=alignment");
}
if (no_sanitize_pointer_overflow) {
AddArg("-fno-sanitize=pointer-overflow");
}
if (wantnoredzone) {
AddArg("-mno-red-zone");
AddArg("-D__MNO_RED_ZONE__");
}
if (wantframe) {
AddArg("-fno-omit-frame-pointer");
AddArg("-D__FNO_OMIT_FRAME_POINTER__");
} else {
AddArg("-fomit-frame-pointer");
}
}
/*
* scrub environment for determinism and great justice
*/
for (envp = environ; *envp; ++envp) {
if (_startswith(*envp, "MODE=")) {
mode = *envp + 5;
}
if (IsSafeEnv(*envp)) {
AddEnv(*envp);
}
}
AddEnv("LC_ALL=C");
AddEnv("SOURCE_DATE_EPOCH=0");
/*
* ensure output directory exists
*/
if (outpath) {
outdir = xdirname(outpath);
if (!isdirectory(outdir)) {
MakeDirs(outdir, 0755);
}
}
/*
* make sense of standard i/o file descriptors
* we want to permit pipelines but prevent talking to terminal
*/
stdoutmustclose = fstat(1, &st) == -1 || S_ISCHR(st.st_mode);
if (fstat(0, &st) == -1 || S_ISCHR(st.st_mode)) {
close(0);
open("/dev/null", O_RDONLY);
}
/*
* SIGINT (CTRL-C) and SIGQUIT (CTRL-\) are delivered to process group
* so the correct thing to do is to do nothing, and wait for the child
* to die as a result of those signals. SIGPIPE shouldn't happen until
* the very end since we buffer so it is safe to let it kill the prog.
* Most importantly we need SIGCHLD to interrupt the read() operation!
*/
sigfillset(&mask);
sigdelset(&mask, SIGILL);
sigdelset(&mask, SIGBUS);
sigdelset(&mask, SIGPIPE);
sigdelset(&mask, SIGALRM);
sigdelset(&mask, SIGSEGV);
sigdelset(&mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &mask, &savemask);
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
sa.sa_sigaction = OnChld;
if (sigaction(SIGCHLD, &sa, 0) == -1) exit(83);
if (timeout > 0) {
sa.sa_flags = 0;
sa.sa_handler = OnAlrm;
sigaction(SIGALRM, &sa, 0);
}
/*
* run command
*/
ws = Launch();
/*
* propagate exit
*/
if (ws != -1) {
if (WIFEXITED(ws)) {
if (!(exitcode = WEXITSTATUS(ws)) || exitcode == 254) {
if (touchtarget && target) {
MakeDirs(xdirname(target), 0755);
if (touch(target, 0644)) {
exitcode = 90;
appends(&output, "\nfailed to touch output file\n");
}
}
if (movepath) {
if (!MovePreservingDestinationInode(tmpout, movepath)) {
unlink(tmpout);
exitcode = 90;
appends(&output, "\nfailed to move output file\n");
appends(&output, tmpout);
appends(&output, "\n");
appends(&output, movepath);
appends(&output, "\n");
} else {
unlink(tmpout);
}
}
} else {
appendw(&output, '\n');
PrintRed();
appendw(&output, '`');
PrintMakeCommand();
appends(&output, "` exited with ");
appendd(&output, buf, FormatUint64(buf, exitcode) - buf);
PrintReset();
appendw(&output, READ16LE(":\n"));
}
} else if (WTERMSIG(ws) == SIGINT) {
appendr(&output, 0);
appends(&output, "\rinterrupted: ");
PrintMakeCommand();
appendw(&output, '\n');
WriteAllUntilSignalledOrError(2, output, appendz(output).i);
return 128 + SIGINT;
} else {
exitcode = 128 + WTERMSIG(ws);
appendw(&output, '\n');
PrintRed();
appendw(&output, '`');
PrintMakeCommand();
appends(&output, "` terminated by ");
appends(&output, strsignal(WTERMSIG(ws)));
PrintReset();
appendw(&output, READ16LE(":\n"));
appends(&output, "env -i ");
for (i = 0; i < env.n; ++i) {
if (ArgNeedsShellQuotes(env.p[i])) {
q = AddShellQuotes(env.p[i]);
appends(&output, q);
free(q);
} else {
appends(&output, env.p[i]);
}
appendw(&output, ' ');
}
}
} else {
exitcode = 89;
}
/*
* describe command that was run
*/
if (!exitcode || exitcode == 254) {
if (exitcode == 254) {
exitcode = 0;
fulloutput = true;
} else if (verbose < 5) {
appendr(&output, 0);
fulloutput = false;
} else {
fulloutput = !!appendz(output).i;
}
if (fulloutput) {
ReportResources();
}
if (!__nocolor && ischardev(2)) {
/* clear line forward */
appendw(&output, READ32LE("\e[K"));
}
if (verbose < 1) {
/* make silent mode, i.e. `V=0 make o//target` */
appendr(&command, 0);
if (!action) action = "BUILD";
if (!outpath) outpath = shortened;
n = strlen(action);
appends(&command, action);
do appendw(&command, ' '), ++n;
while (n < 15);
appends(&command, outpath);
n += strlen(outpath);
m = GetTerminalWidth();
if (m > 3 && n > m) {
appendd(&output, command, m - 3);
appendw(&output, READ32LE("..."));
} else {
if (n < m && (__nocolor || !ischardev(2))) {
while (n < m) appendw(&command, ' '), ++n;
}
appendd(&output, command, n);
}
appendw(&output, m > 0 ? '\r' : '\n');
} else {
n = 0;
if (verbose >= 3) {
/* make bonus mode (shows resource usage) */
if (timeout > 0) {
us = GetTimespecMicros(finish) - GetTimespecMicros(start);
i = FormatUint64Thousands(buf, us) - buf;
j = ceil(log10(timeout));
j += (j - 1) / 3;
j += 1 + 3;
j += 1 + 3;
while (i < j) appendw(&output, ' '), ++i;
if (us > timeout * 1000000ull / 2) {
if (us > timeout * 1000000ull) {
PrintRed();
} else {
PrintBold();
}
appends(&output, buf);
PrintReset();
} else {
appends(&output, buf);
}
appendw(&output, READ32LE("â° "));
n += i + 2 + 1;
}
if (cpuquota > 0) {
if (!(us = GetTimevalMicros(usage.ru_utime) +
GetTimevalMicros(usage.ru_stime))) {
us = GetTimespecMicros(finish) - GetTimespecMicros(start);
}
i = FormatUint64Thousands(buf, us) - buf;
j = ceil(log10(cpuquota));
j += (j - 1) / 3;
j += 1 + 3;
j += 1 + 3;
while (i < j) appendw(&output, ' '), ++i;
if ((isproblematic = us > cpuquota * 1000000ull / 2)) {
if (us > cpuquota * 1000000ull - (cpuquota * 1000000ull) / 5) {
PrintRed();
} else {
PrintBold();
}
}
appends(&output, buf);
appendw(&output, READ32LE("â³ "));
if (isproblematic) {
PrintReset();
}
n += i + 2 + 1;
}
if (memquota > 0) {
i = FormatUint64Thousands(buf, usage.ru_maxrss) - buf;
j = ceil(log10(memquota / 1024));
j += (j - 1) / 3;
while (i < j) appendw(&output, ' '), ++i;
if ((isproblematic = usage.ru_maxrss * 1024 > memquota / 2)) {
if (usage.ru_maxrss * 1024 > memquota - memquota / 5) {
PrintRed();
} else {
PrintBold();
}
}
appends(&output, buf);
appendw(&output, READ16LE("k "));
if (isproblematic) {
PrintReset();
}
n += i + 1 + 1;
}
if (fszquota > 0) {
us = usage.ru_inblock + usage.ru_oublock;
i = FormatUint64Thousands(buf, us) - buf;
while (i < 7) appendw(&output, ' '), ++i;
appends(&output, buf);
appendw(&output, READ32LE("iop "));
n += i + 4;
}
}
/* make normal mode (echos run commands) */
if (verbose < 2 || verbose == 3) {
command = shortened;
}
m = GetLineWidth(&isineditor);
if (m > n + 3 && appendz(command).i > m - n) {
if (isineditor) {
if (m > n + 3 && appendz(shortened).i > m - n) {
appendd(&output, shortened, m - n - 3);
appendw(&output, READ32LE("..."));
} else {
appendd(&output, shortened, appendz(shortened).i);
}
} else {
appendd(&output, command, m - n - 3);
appendw(&output, READ32LE("..."));
}
} else {
appendd(&output, command, appendz(command).i);
}
appendw(&output, '\n');
}
} else {
n = appendz(command).i;
if (n > 2048) {
appendr(&command, (n = 2048));
appendw(&command, READ32LE("..."));
}
appendd(&output, command, n);
ReportResources();
}
/*
* flush output
*/
if (WriteAllUntilSignalledOrError(2, output, appendz(output).i) == -1) {
if (errno == EINTR) {
s = "notice: compile.com output truncated\n";
} else {
if (!exitcode) exitcode = 55;
s = "error: compile.com failed to write result\n";
}
write(2, s, strlen(s));
}
/*
* all done!
*/
return exitcode;
}
| 39,701 | 1,448 | jart/cosmopolitan | false |
cosmopolitan/tool/build/dropcache.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/log/check.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
/**
* Removes file system caches from RAM.
*
* make o//tool/build/dropcache.com
* sudo mv o//tool/build/dropcache.com /usr/local/bin/
* sudo chown root /usr/local/bin/dropcache.com
* sudo chmod u+s /usr/local/bin/dropcache.com
*/
static void Write(int fd, const char *s) {
write(fd, s, strlen(s));
}
int main(int argc, char *argv[]) {
int fd;
sync();
fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
if (fd == -1) {
if (errno == EACCES) {
Write(1, "error: need root privileges\n");
} else if (errno == ENOENT) {
Write(1, "error: need /proc filesystem\n");
}
exit(1);
}
Write(fd, "3\n");
close(fd);
return 0;
}
| 2,676 | 55 | jart/cosmopolitan | false |
cosmopolitan/tool/build/cocmd.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/runtime/runtime.h"
STATIC_YOINK("glob");
int main(int argc, char **argv, char **envp) {
return _cocmd(argc, argv, envp);
}
| 1,978 | 26 | jart/cosmopolitan | false |
cosmopolitan/tool/build/calculator.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/morton.h"
#include "libc/intrin/popcnt.h"
#include "libc/limits.h"
#include "libc/log/color.internal.h"
#include "libc/log/internal.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/stdio/rand.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/sig.h"
#include "libc/tinymath/emodl.h"
#include "libc/x/xsigaction.h"
#include "third_party/gdtoa/gdtoa.h"
#include "third_party/getopt/getopt.h"
#define INT int128_t
#define FLOAT long double
#define EPSILON 1e-16l
#define BANNER \
"\
Reverse Polish Notation Calculator\n\
Copyright 2020 Justine Alexandra Roberts Tunney\n\
This is fast portable lightweight software. You have the freedom to build\n\
software just like it painlessly. See http://github.com/jart/cosmopolitan\n\
"
#define USAGE1 \
"SYNOPSIS\n\
\n\
Reverse Polish Notation Calculator\n\
\n\
USAGE\n\
\n"
#define USAGE2 \
" [FLAGS] [FILE...]\n\
\n\
FLAGS\n\
\n\
-h\n\
-? shows this information\n\
-i force interactive mode\n\
\n\
KEYBOARD SHORTCUTS\n\
\n\
CTRL-D Closes standard input\n\
CTRL-C Sends SIGINT to program\n\
CTRL-U Redraw line\n\
CTRL-L Redraw display\n\
\n\
FUNCTIONS\n\
\n"
#define USAGE3 \
"\n\
EXAMPLES\n\
\n\
calculator.com\n\
40 2 +\n\
42\n\
\n\
echo '2 2 + . cr' | calculator.com\n\
4\n\
\n\
calculator.com <<EOF\n\
true assert\n\
-1 ~ 0 = assert\n\
3 2 / 1.5 = assert\n\
81 3 // 27 = assert\n\
2 8 ** 256 = assert\n\
pi cos -1 = assert\n\
pi sqrt pi sqrt * pi - abs epsilon < assert\n\
nan isnormal ! assert\n\
0b1010101 0b0110101 ^ 0b1100000 = assert\n\
0b1010101 popcnt 4 = assert\n\
EOF\n\
\n\
CONTACT\n\
\n\
Justine Tunney <[email protected]>\n\
https://github.com/jart/cosmooplitan\n\
\n\
"
#define CTRL(C) ((C) ^ 0100)
#define Fatal(...) Log(kFatal, __VA_ARGS__)
#define Warning(...) Log(kWarning, __VA_ARGS__)
enum Severity {
kFatal,
kWarning,
};
enum Exception {
kUnderflow = 1,
kDivideError,
};
struct Bytes {
size_t i, n;
char *p;
};
struct History {
size_t i, n;
struct Bytes *p;
};
struct Value {
enum Type {
kInt,
kFloat,
} t;
union {
INT i;
FLOAT f;
};
};
struct Function {
const char sym[16];
void (*fun)(void);
const char *doc;
};
jmp_buf thrower;
const char *file;
struct Bytes token;
struct History history;
struct Value stack[128];
int sp, comment, line, column, interactive;
INT Popcnt(INT x) {
uint128_t word = x;
return popcnt(word >> 64) + popcnt(word);
}
char *Repr(struct Value x) {
static char buf[64];
if (x.t == kFloat) {
g_xfmt_p(buf, &x.f, 16, sizeof(buf), 0);
} else {
sprintf(buf, "%jjd", x.i);
}
return buf;
}
char *ReprStack(void) {
int i, j, l;
char *s, *p;
static char buf[80];
p = memset(buf, 0, sizeof(buf));
for (i = 0; i < sp; ++i) {
s = Repr(stack[i]);
l = strlen(s);
if (p + l + 2 > buf + sizeof(buf)) break;
p = mempcpy(p, s, l);
*p++ = ' ';
}
return buf;
}
void ShowStack(void) {
if (interactive) {
printf("\r\e[K");
fputs(ReprStack(), stdout);
}
}
void Cr(FILE *f) {
fputs(interactive || IsWindows() ? "\r\n" : "\n", f);
}
void Log(enum Severity l, const char *fmt, ...) {
va_list va;
const char *severity[] = {"FATAL", "WARNING"};
if (interactive) fflush(/* key triggering throw not echo'd yet */ stdout);
fprintf(stderr, "%s:%d:%d:%s: ", file, line + 1, column, severity[l & 1]);
va_start(va, fmt);
vfprintf(stderr, fmt, va);
va_end(va);
Cr(stderr);
if (l == kFatal) exit(EXIT_FAILURE);
if (interactive) ShowStack();
}
void __on_arithmetic_overflow(void) {
Warning("arithmetic overflow");
}
void OnDivideError(void) {
longjmp(thrower, kDivideError);
}
struct Value Push(struct Value x) {
if (sp >= ARRAYLEN(stack)) Fatal("stack overflow");
return (stack[sp++] = x);
}
struct Value Pop(void) {
if (sp) {
return stack[--sp];
} else {
longjmp(thrower, kUnderflow);
}
}
INT Popi(void) {
struct Value x = Pop();
return x.t == kInt ? x.i : x.f;
}
void Pushi(INT i) {
struct Value x;
x.t = kInt;
x.i = i;
Push(x);
}
FLOAT Popf(void) {
struct Value x = Pop();
return x.t == kInt ? x.i : x.f;
}
void Pushf(FLOAT f) {
struct Value x;
x.t = kFloat;
x.f = f;
Push(x);
}
void OpDrop(void) {
Pop();
}
void OpDup(void) {
Push(Push(Pop()));
}
void OpExit(void) {
exit(Popi());
}
void OpSrand(void) {
srand(Popi());
}
void OpEmit(void) {
fputwc(Popi(), stdout);
}
void OpCr(void) {
Cr(stdout);
}
void OpPrint(void) {
printf("%s ", Repr(Pop()));
}
void OpComment(void) {
comment = true;
}
void Glue0f(FLOAT fn(void)) {
Pushf(fn());
}
void Glue0i(INT fn(void)) {
Pushi(fn());
}
void Glue1f(FLOAT fn(FLOAT)) {
Pushf(fn(Popf()));
}
void Glue1i(INT fn(INT)) {
Pushi(fn(Popi()));
}
void OpSwap(void) {
struct Value a, b;
b = Pop();
a = Pop();
Push(b);
Push(a);
}
void OpOver(void) {
struct Value a, b;
b = Pop();
a = Pop();
Push(a);
Push(b);
Push(a);
}
void OpKey(void) {
wint_t c;
ttyraw(kTtyCursor | kTtySigs | kTtyLfToCrLf);
c = fgetwc(stdin);
ttyraw(-1);
if (c != -1) Pushi(c);
}
void OpAssert(void) {
if (!Popi()) Fatal("assert failed");
}
void OpExpect(void) {
if (!Popi()) Warning("expect failed");
}
void OpMeminfo(void) {
OpCr();
OpCr();
fflush(stdout);
_meminfo(fileno(stdout));
}
void Glue2f(FLOAT fn(FLOAT, FLOAT)) {
FLOAT x, y;
y = Popf();
x = Popf();
Pushf(fn(x, y));
}
void Glue2i(INT fn(INT, INT)) {
INT x, y;
y = Popi();
x = Popi();
Pushi(fn(x, y));
}
void Glue1g(FLOAT fnf(FLOAT), INT fni(INT)) {
struct Value x;
x = Pop();
switch (x.t) {
case kInt:
Pushi(fni(x.i));
break;
case kFloat:
Pushf(fnf(x.f));
break;
default:
Warning("type mismatch");
}
}
void Glue2g(FLOAT fnf(FLOAT, FLOAT), INT fni(INT, INT)) {
struct Value x, y;
y = Pop();
x = Pop();
if (x.t == kInt && y.t == kInt) {
Pushi(fni(x.i, y.i));
} else if (x.t == kFloat && y.t == kFloat) {
Pushf(fnf(x.f, y.f));
} else if (x.t == kInt && y.t == kFloat) {
Pushf(fnf(x.i, y.f));
} else if (x.t == kFloat && y.t == kInt) {
Pushf(fnf(x.f, y.i));
} else {
Warning("type mismatch");
}
}
#define LB {
#define RB }
#define SEMI ;
#define FNTYPEi INT
#define FNTYPEf FLOAT
#define FORM(F) LB F SEMI RB
#define FNPL0(T) void
#define FNPL1(T) FNTYPE##T x
#define FNPL2(T) FNTYPE##T x, FNTYPE##T y
#define FNDEF(A, T, S, C) FNTYPE##T Fn##S##T(FNPL##A(T)) FORM(return C)
#define FNDEFf(A, S, C) FNDEF(A, f, S, C)
#define FNDEFi(A, S, C) FNDEF(A, i, S, C)
#define FNDEFg(A, S, C) FNDEF(A, f, S, C) FNDEF(A, i, S, C)
#define OPDEF(A, T, S, C) void Op##S(void) FORM(Glue##A##T(Fn##S##T))
#define OPDEFf(A, S, C) OPDEF(A, f, S, C)
#define OPDEFi(A, S, C) OPDEF(A, i, S, C)
#define OPDEFg(A, S, C) void Op##S(void) FORM(Glue##A##g(Fn##S##f, Fn##S##i))
#define M(A, T, N, S, C, D) FNDEF##T(A, S, C) OPDEF##T(A, S, C)
#include "tool/build/calculator.inc"
#undef M
const struct Function kFunctions[] = {
{".", OpPrint, "pops prints value repr"},
{"#", OpComment, "line comment"},
#define M(A, T, N, S, C, D) {N, Op##S, D},
#include "tool/build/calculator.inc"
#undef M
{"dup", OpDup, "pushes copy of last item on stack"},
{"drop", OpDrop, "pops and discards"},
{"swap", OpSwap, "swaps last two items on stack"},
{"over", OpOver, "pushes second item on stack"},
{"cr", OpCr, "prints newline"},
{"key", OpKey, "reads and pushes unicode character from keyboard"},
{"emit", OpEmit, "pops and writes unicode character to output"},
{"assert", OpAssert, "crashes if top of stack isn't nonzero"},
{"expect", OpExpect, "prints warning if top of stack isn't nonzero"},
{"meminfo", OpMeminfo, "prints memory mappings"},
{"exit", OpExit, "exits program with status"},
};
bool CallFunction(const char *sym) {
int i;
char s[16];
strncpy(s, sym, sizeof(s));
for (i = 0; i < ARRAYLEN(kFunctions); ++i) {
if (memcmp(kFunctions[i].sym, s, sizeof(s)) == 0) {
kFunctions[i].fun();
return true;
}
}
return false;
}
volatile const char *literal_;
bool ConsumeLiteral(const char *literal) {
bool r;
char *e;
struct Value x;
literal_ = literal;
errno = 0;
x.t = kInt;
x.i = strtoi128(literal, &e, 0);
if (*e) {
x.t = kFloat;
x.f = strtod(literal, &e);
r = !(!e || *e);
} else if (errno == ERANGE) {
r = false;
} else {
r = true;
}
Push(x);
return r;
}
void ConsumeToken(void) {
enum Exception ex;
if (!token.i) return;
token.p[token.i] = 0;
token.i = 0;
if (history.i) history.p[history.i - 1].i = 0;
if (comment) return;
if (_startswith(token.p, "#!")) return;
switch (setjmp(thrower)) {
default:
if (CallFunction(token.p)) return;
if (ConsumeLiteral(token.p)) return;
Warning("bad token: %`'s", token.p);
break;
case kUnderflow:
Warning("stack underflow");
break;
case kDivideError:
Warning("divide error");
break;
}
}
void CleanupRepl(void) {
if (sp && interactive) {
Cr(stdout);
}
}
void AppendByte(struct Bytes *a, char b) {
APPEND(&a->p, &a->i, &a->n, &b);
}
void AppendHistory(void) {
struct Bytes line;
if (interactive) {
bzero(&line, sizeof(line));
APPEND(&history.p, &history.i, &history.n, &line);
}
}
void AppendLine(char b) {
if (interactive) {
if (!history.i) AppendHistory();
AppendByte(&history.p[history.i - 1], b);
}
}
void Echo(int c) {
if (interactive) {
fputc(c, stdout);
}
}
void Backspace(int c) {
struct Bytes *line;
if (interactive) {
if (history.i) {
line = &history.p[history.i - 1];
if (line->i && token.i) {
do {
line->i--;
token.i--;
} while (line->i && token.i && (line->p[line->i] & 0x80));
fputs("\e[D \e[D", stdout);
}
}
}
}
void NewLine(void) {
line++;
column = 0;
comment = false;
if (interactive) {
Cr(stdout);
AppendHistory();
ShowStack();
}
}
void KillLine(void) {
if (interactive) {
if (history.i) {
history.p[history.i - 1].i--;
}
}
}
void ClearLine(void) {
if (interactive) {
if (token.i) sp = 0;
ShowStack();
}
}
void RedrawDisplay(void) {
int i;
struct Bytes *line;
if (interactive) {
printf("\e[H\e[2J%s", BANNER);
ShowStack();
if (history.i) {
line = &history.p[history.i - 1];
for (i = 0; i < line->i; ++i) {
fputc(line->p[i], stdout);
}
}
}
}
void GotoStartOfLine(void) {
if (interactive) {
printf("\r");
}
}
void GotoEndOfLine(void) {
}
void GotoPrevLine(void) {
}
void GotoNextLine(void) {
}
void GotoPrevChar(void) {
}
void GotoNextChar(void) {
}
void Calculator(FILE *f) {
int c;
while (!feof(f)) {
switch ((c = getc(f))) {
case -1:
case CTRL('D'):
goto Done;
case CTRL('@'):
break;
case ' ':
column++;
Echo(c);
AppendLine(c);
ConsumeToken();
break;
case '\t':
column = ROUNDUP(column, 8);
Echo(c);
AppendLine(c);
ConsumeToken();
break;
case '\r':
case '\n':
ConsumeToken();
NewLine();
break;
case CTRL('A'):
GotoStartOfLine();
break;
case CTRL('E'):
GotoEndOfLine();
break;
case CTRL('P'):
GotoPrevLine();
break;
case CTRL('N'):
GotoNextLine();
break;
case CTRL('B'):
GotoPrevChar();
break;
case CTRL('F'):
GotoNextChar();
break;
case CTRL('L'):
RedrawDisplay();
break;
case CTRL('U'):
ClearLine();
break;
case CTRL('K'):
KillLine();
break;
case CTRL('?'):
case CTRL('H'):
Backspace(c);
break;
default:
column++;
/* fallthrough */
case 0x80 ... 0xff:
Echo(c);
AppendLine(c);
AppendByte(&token, c);
break;
}
fflush(/* needed b/c this is event loop */ stdout);
}
Done:
CleanupRepl();
}
int Calculate(const char *path) {
FILE *f;
file = path;
line = column = 0;
if (!(f = fopen(file, "r"))) Fatal("file not found: %s", file);
Calculator(f);
return fclose(f);
}
void CleanupTerminal(void) {
ttyraw(-1);
}
void StartInteractive(void) {
if (!interactive && !__nocolor && isatty(fileno(stdin)) &&
isatty(fileno(stdout)) && !__nocolor) {
interactive = true;
}
errno = 0;
if (interactive) {
fputs(BANNER, stdout);
fflush(/* needed b/c entering tty mode */ stdout);
ttyraw(kTtyCursor | kTtySigs);
atexit(CleanupTerminal);
}
}
void PrintUsage(int rc, FILE *f) {
char c;
int i, j;
fprintf(f, "%s %s%s", USAGE1, program_invocation_name, USAGE2);
for (i = 0; i < ARRAYLEN(kFunctions); ++i) {
fputs(" ", f);
for (j = 0; j < ARRAYLEN(kFunctions[i].sym); ++j) {
c = kFunctions[i].sym[j];
fputc(c ? c : ' ', f);
}
fprintf(f, " %s\n", kFunctions[i].doc);
}
fputs(USAGE3, f);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "?hi")) != -1) {
switch (opt) {
case 'i':
interactive = true;
break;
case 'h':
case '?':
PrintUsage(EXIT_SUCCESS, stdout);
default:
PrintUsage(EX_USAGE, stderr);
}
}
}
int main(int argc, char *argv[]) {
int i, rc;
ShowCrashReports();
GetOpts(argc, argv);
xsigaction(SIGFPE, OnDivideError, 0, 0, 0);
if (optind == argc) {
file = "/dev/stdin";
StartInteractive();
Calculator(stdin);
return fclose(stdin);
} else {
for (i = optind; i < argc; ++i) {
if (Calculate(argv[i]) == -1) {
return -1;
}
}
}
return 0;
}
| 15,324 | 748 | jart/cosmopolitan | false |
cosmopolitan/tool/build/deltaify.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/ucontext.h"
#include "libc/errno.h"
#include "libc/log/check.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/time/time.h"
#include "libc/x/xgetline.h"
static int pid;
static void RelaySig(int sig, struct siginfo *si, void *uc) {
kill(pid, sig);
}
int main(int argc, char *argv[]) {
FILE *f;
bool ok;
char *s, *p;
int64_t micros;
long double t1, t2;
int ws, pipefds[2];
setvbuf(stdout, malloc(BUFSIZ), _IOLBF, BUFSIZ);
setvbuf(stderr, malloc(BUFSIZ), _IOLBF, BUFSIZ);
if (argc < 2) {
f = stdin;
t1 = nowl();
} else {
sigset_t block, mask;
struct sigaction saignore = {.sa_handler = SIG_IGN};
struct sigaction sadefault = {.sa_handler = SIG_DFL};
struct sigaction sarelay = {.sa_sigaction = RelaySig,
.sa_flags = SA_RESTART};
sigemptyset(&block);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
sigaddset(&mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &block, &mask);
sigaction(SIGHUP, &sarelay, 0);
sigaction(SIGTERM, &sarelay, 0);
sigaction(SIGINT, &saignore, 0);
sigaction(SIGQUIT, &saignore, 0);
CHECK_NE(-1, pipe(pipefds));
CHECK_NE(-1, (pid = vfork()));
if (!pid) {
close(pipefds[0]);
dup2(pipefds[1], 1);
sigaction(SIGHUP, &sadefault, NULL);
sigaction(SIGTERM, &sadefault, NULL);
sigaction(SIGINT, &sadefault, NULL);
sigaction(SIGQUIT, &sadefault, NULL);
sigprocmask(SIG_SETMASK, &mask, NULL);
execvp(argv[1], argv + 1);
_exit(127);
}
t1 = nowl();
close(pipefds[1]);
sigprocmask(SIG_SETMASK, &mask, NULL);
CHECK((f = fdopen(pipefds[0], "r")));
CHECK_NE(-1, setvbuf(f, malloc(4096), _IOLBF, 4096));
}
if ((p = xgetline(f))) {
t2 = nowl();
micros = (t2 - t1) * 1e6;
t1 = t2;
printf("%16ld\n", micros);
do {
s = xgetline(f);
t2 = nowl();
micros = (t2 - t1) * 1e6;
t1 = t2;
printf("%16ld %s", micros, p);
free(p);
} while ((p = s));
}
ok = !ferror(f);
if (argc < 2) return ok ? 0 : 1;
fclose(f);
while (waitpid(pid, &ws, 0) == -1) CHECK_EQ(EINTR, errno);
return !WIFEXITED(ws) ? 128 + WTERMSIG(ws) : ok ? WEXITSTATUS(ws) : 1;
}
| 4,304 | 105 | jart/cosmopolitan | false |
cosmopolitan/tool/build/rollup.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 "ape/relocations.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/mem/arraylist2.internal.h"
#include "libc/mem/mem.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/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "tool/build/lib/getargs.h"
#include "tool/build/lib/interner.h"
#define LOOKINGAT(p, pe, s) LookingAt(p, pe, s, strlen(s))
struct Visited {
size_t i, n;
const char **p;
};
char *output;
struct Interner *visited;
void Visit(const char *);
size_t GetFdSize(int fd) {
struct stat st;
CHECK_NE(-1, fstat(fd, &st));
return st.st_size;
}
bool LookingAt(const char *p, const char *pe, const char *s, size_t n) {
return pe - p >= n && memcmp(p, s, n) == 0;
}
void Process(const char *p, const char *pe, const char *path, bool isheader) {
int level;
bool noformat;
const char *p2, *dq, *name;
for (noformat = level = 0; p < pe; p = p2) {
p2 = memchr(p, '\n', pe - p);
p2 = p2 ? p2 + 1 : pe;
if (LOOKINGAT(p, pe, "#if")) {
if (isheader && !level++) continue;
}
if (LOOKINGAT(p, pe, "#endif")) {
if (isheader && !--level) continue;
}
if (LOOKINGAT(p, pe, "/* clang-format off */")) {
noformat = true;
} else if (LOOKINGAT(p, pe, "/* clang-format on */")) {
noformat = false;
}
if (LOOKINGAT(p, pe, "#include \"")) {
name = p + strlen("#include \"");
dq = memchr(name, '"', pe - name);
if (dq) {
Visit(strndup(name, dq - name));
continue;
}
}
appendd(&output, p, p2 - p);
}
if (noformat) {
appends(&output, "/* clang-format on */\n");
}
kprintf("finished%n");
}
void Visit(const char *path) {
int fd;
char *map;
size_t size;
bool isheader;
if (!_endswith(path, ".h") && !_endswith(path, ".inc")) return;
if (_endswith(path, ".internal.h")) return;
if (_endswith(path, "/internal.h")) return;
if (_endswith(path, ".internal.inc")) return;
if (_endswith(path, "/internal.inc")) return;
if (_startswith(path, "libc/isystem/")) return;
isheader = _endswith(path, ".h");
if (isheader && isinterned(visited, path)) return;
appends(&output, "\n\f\n/*!BEGIN ");
appends(&output, path);
appends(&output, " */\n\n");
intern(visited, path);
if ((fd = open(path, O_RDONLY)) == -1) {
fprintf(stderr, "error: %s: failed to open\n", path);
exit(1);
}
if ((size = GetFdSize(fd))) {
kprintf("size 1 = %'zu%n", size);
CHECK_NE(MAP_FAILED,
(map = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0)));
Process(map, map + size, path, isheader);
kprintf("size = %'zu%n", size);
CHECK_EQ(0, munmap(map, size), "p=%p z=%'zu path=%s", map, size, path);
}
CHECK_EQ(0, close(fd));
}
ssize_t WriteAll(int fd, const char *p, size_t n) {
ssize_t rc;
size_t i, got;
for (i = 0; i < n;) {
rc = write(fd, p + i, n - i);
if (rc != -1) {
got = rc;
i += got;
} else if (errno != EINTR) {
return -1;
}
}
return i;
}
int main(int argc, char *argv[]) {
const char *src;
struct GetArgs ga;
ShowCrashReports();
visited = newinterner();
appends(&output, "#ifndef COSMOPOLITAN_H_\n");
appends(&output, "#define COSMOPOLITAN_H_\n");
/* appends(&output, "#define IMAGE_BASE_VIRTUAL "); */
/* appendf(&output, "%p", IMAGE_BASE_VIRTUAL); */
/* appends(&output, "\n"); */
/* appends(&output, "#define IMAGE_BASE_PHYSICAL "); */
/* appendf(&output, "%p", IMAGE_BASE_PHYSICAL); */
/* appends(&output, "\n"); */
getargs_init(&ga, argv + 1);
while ((src = getargs_next(&ga))) {
Visit(src);
}
getargs_destroy(&ga);
appends(&output, "\n");
appends(&output, "#endif /* COSMOPOLITAN_H_ */\n");
CHECK_NE(-1, WriteAll(1, output, appendz(output).i));
freeinterner(visited);
return 0;
}
| 5,907 | 166 | jart/cosmopolitan | false |
cosmopolitan/tool/build/false.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2023 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
int main(int argc, char *argv[]) {
return 1;
}
| 1,886 | 23 | jart/cosmopolitan | false |
cosmopolitan/tool/build/dis.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 "tool/build/lib/dis.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/elf/def.h"
#include "libc/elf/elf.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/elf/struct/shdr.h"
#include "libc/elf/struct/sym.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/nt/struct/importobjectheader.internal.h"
#include "libc/runtime/runtime.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 "third_party/xed/x86.h"
#include "tool/build/lib/high.h"
#include "tool/build/lib/loader.h"
#define HEXWIDTH 8
const char *const kRealSymbols[] = {
"a20", "ape.mbrpad", "ape.str",
"ape_disk", "ape_grub", "ape_mz",
"apesh", "dsknfo", "e820",
"gdt", "golong", "hiload",
"lcheck", "longmodeloader", "pc",
"pcread", "pinit", "realmodeloader",
"rldie", "rvputs", "sconf",
"sinit", "sinit4", "str.cpuid",
"str.crlf", "str.dsknfo", "str.e820",
"str.error", "str.long", "str.memory",
"str.oldskool", "stub", "unreal",
};
const char *const kLegacySymbols[] = {
"ape_grub_entry",
};
bool boop;
long cursym;
Elf64_Ehdr *elf;
Elf64_Shdr *sec;
struct Dis dis[1];
struct Machine m[1];
struct Elf diself[1];
char codebuf[256];
char optspecbuf[128];
const Elf64_Sym *syms;
char *symstrs, *secstrs;
size_t i, j, k, l, size, skip, symcount;
bool IsRealSymbol(const char *s) {
int m, l, r, x;
l = 0;
r = ARRAYLEN(kRealSymbols) - 1;
while (l <= r) {
m = (l + r) >> 1;
x = strcmp(s, kRealSymbols[m]);
if (x < 0) {
r = m - 1;
} else if (x > 0) {
l = m + 1;
} else {
return true;
}
}
return false;
}
bool IsLegacySymbol(const char *s) {
int m, l, r, x;
l = 0;
r = ARRAYLEN(kLegacySymbols) - 1;
while (l <= r) {
m = (l + r) >> 1;
x = strcmp(s, kLegacySymbols[m]);
if (x < 0) {
r = m - 1;
} else if (x > 0) {
l = m + 1;
} else {
return true;
}
}
return false;
}
void SetSymbol(bool printit) {
if (!boop) {
printf("\n");
boop = true;
}
if (printit) {
printf("\e[38;5;%dm%s\e[0m:\n", g_high.label, symstrs + syms[k].st_name);
}
if (IsRealSymbol(symstrs + syms[k].st_name)) {
if (m->mode != XED_MACHINE_MODE_REAL) {
printf("\t\e[38;5;%dm.code16\e[0m\n", g_high.keyword);
}
m->mode = XED_MACHINE_MODE_REAL;
} else if (IsLegacySymbol(symstrs + syms[k].st_name)) {
if (m->mode != XED_MACHINE_MODE_LEGACY_32) {
printf("\t\e[38;5;%dm.code32\e[0m\n", g_high.keyword);
}
m->mode = XED_MACHINE_MODE_LEGACY_32;
} else {
if (m->mode != XED_MACHINE_MODE_LONG_64) {
printf("\t\e[38;5;%dm.code64\e[0m\n", g_high.keyword);
}
m->mode = XED_MACHINE_MODE_LONG_64;
}
cursym = k;
if (syms[k].st_size) {
skip = syms[k].st_size;
} else {
skip = -1;
for (l = 0; l < symcount; ++l) {
if (syms[l].st_shndx == i && syms[l].st_name &&
syms[l].st_value > syms[cursym].st_value) {
skip = MIN(skip, syms[l].st_value - syms[cursym].st_value);
}
}
if (skip == -1) {
skip = sec->sh_addr + sec->sh_size - syms[cursym].st_value;
}
}
}
void PrintSymbolName(void) {
bool done;
done = false;
boop = false;
for (k = 0; k < symcount; ++k) {
if (syms[k].st_value == sec->sh_addr + j && syms[k].st_name) {
if (!done && syms[k].st_size) {
SetSymbol(true);
done = true;
} else {
if (!boop) {
printf("\n");
boop = true;
}
printf("\e[38;5;%dm%s\e[0m:\n", g_high.label,
symstrs + syms[k].st_name);
}
}
}
if (done) {
return;
}
for (k = 0; k < symcount; ++k) {
if (ELF64_ST_TYPE(syms[k].st_info) && syms[k].st_name &&
syms[k].st_value == sec->sh_addr + j) {
SetSymbol(false);
return;
}
}
for (k = 0; k < symcount; ++k) {
if (syms[k].st_name && syms[k].st_value == sec->sh_addr + j) {
SetSymbol(false);
return;
}
}
if (cursym != -1 && syms[cursym].st_size &&
sec->sh_addr + j >= syms[cursym].st_value + syms[cursym].st_size) {
cursym = -1;
skip = 1;
}
}
bool Ild(void) {
int remain;
remain = 15;
if (cursym != -1 && syms[cursym].st_size) {
remain =
(syms[cursym].st_value + syms[cursym].st_size) - (sec->sh_addr + j);
}
xed_decoded_inst_zero_set_mode(dis->xedd, m->mode);
xed_instruction_length_decode(dis->xedd, (char *)elf + sec->sh_offset + j,
remain);
skip = dis->xedd->op.error ? 1 : MAX(1, dis->xedd->length);
return !dis->xedd->op.error;
}
bool IsCode(void) {
if (!(sec->sh_flags & SHF_EXECINSTR)) return false;
if (cursym != -1 && ELF64_ST_TYPE(syms[cursym].st_info) == STT_OBJECT) {
return false;
}
return true;
}
bool IsBss(void) {
return sec->sh_type == SHT_NOBITS;
}
void Disassemble(void) {
int c;
bool istext;
cursym = -1;
secstrs = GetElfSectionNameStringTable(elf, size);
symstrs = GetElfStringTable(elf, size);
syms = GetElfSymbolTable(elf, size, &symcount);
for (i = 0; i < elf->e_shnum; ++i) {
sec = GetElfSectionHeaderAddress(elf, size, i);
if (!sec->sh_size) continue;
if (!(sec->sh_flags & SHF_ALLOC)) continue;
printf("\n\t\e[38;5;%dm.section\e[0m %s\n", g_high.keyword,
secstrs + sec->sh_name);
for (j = 0; j < sec->sh_size; j += MAX(1, skip)) {
PrintSymbolName();
if (cursym == -1) continue;
if (sec->sh_type == SHT_NOBITS) {
printf("\t\e[38;5;%dm.zero\e[0m\t%ld\n", g_high.keyword, skip);
} else if (IsCode()) {
if (Ild()) {
dis->addr = sec->sh_addr + j;
DisInst(dis, codebuf, DisSpec(dis->xedd, optspecbuf));
printf("\t%s\n", codebuf);
} else {
printf("\t.wut\t%ld\n", dis->xedd->op.error);
}
} else {
for (k = 0; k < skip; ++k) {
if (!(k & (HEXWIDTH - 1))) {
if (k) {
printf(" \e[38;5;%dm# %#.*s\e[0m\n", g_high.comment, HEXWIDTH,
(unsigned char *)elf + sec->sh_offset + j + k - HEXWIDTH);
}
printf("\t\e[38;5;%dm.byte\e[0m\t", g_high.keyword);
} else if (k) {
printf(",");
}
printf("0x%02x", ((unsigned char *)elf)[sec->sh_offset + j + k]);
}
if (k) {
if (!(k & (HEXWIDTH - 1))) {
printf(" \e[38;5;%dm# %#.*s\e[0m\n", g_high.comment, HEXWIDTH,
(unsigned char *)elf + sec->sh_offset + j + skip - HEXWIDTH);
} else {
for (l = 0; l < HEXWIDTH - (k & (HEXWIDTH - 1)); ++l) {
printf(" ");
}
printf(" \e[38;5;%dm# %#.*s\e[0m\n", g_high.comment,
skip - ROUNDDOWN(skip, HEXWIDTH),
(unsigned char *)elf + sec->sh_offset + j +
ROUNDDOWN(skip, HEXWIDTH));
}
}
}
}
}
}
int main(int argc, char *argv[]) {
ShowCrashReports();
int fd;
void *map;
struct stat st;
const char *path;
if (argc == 1) {
fprintf(stderr, "USAGE: %s ELF\n", program_invocation_name);
exit(1);
} else {
path = argv[1];
}
if ((fd = open(path, O_RDONLY)) == -1) {
fprintf(stderr, "ERROR: NOT FOUND: %`'s\n", path);
exit(1);
}
CHECK_NE(-1, fstat(fd, &st));
CHECK_NE(0, st.st_size);
CHECK_NE(MAP_FAILED,
(map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)));
if (memcmp(map, ELFMAG, 4)) {
fprintf(stderr, "ERROR: NOT AN ELF: %`'s\n", path);
exit(1);
}
m->mode = XED_MACHINE_MODE_LONG_64;
g_high.keyword = 155;
g_high.reg = 215;
g_high.literal = 182;
g_high.label = 221;
g_high.comment = 112;
g_high.quote = 180;
dis->m = m;
diself->prog = path;
LoadDebugSymbols(diself);
DisLoadElf(dis, diself);
LOGIFNEG1(close(fd));
elf = map;
size = st.st_size;
Disassemble();
LOGIFNEG1(munmap(map, st.st_size));
return 0;
}
| 10,068 | 319 | jart/cosmopolitan | false |
cosmopolitan/tool/build/fixupobj.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/dce.h"
#include "libc/elf/elf.h"
#include "libc/elf/scalar.h"
#include "libc/elf/struct/rela.h"
#include "libc/elf/struct/shdr.h"
#include "libc/elf/struct/sym.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/msync.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "third_party/getopt/getopt.h"
/**
* @fileoverview GCC Codegen Fixer-Upper.
*/
#define GETOPTS "h"
#define USAGE \
"\
Usage: fixupobj.com [-h] ARGS...\n\
-?\n\
-h show help\n\
"
#define COSMO_TLS_REG 28
#define MRS_TPIDR_EL0 0xd53bd040u
#define MOV_REG(DST, SRC) (0xaa0003e0u | (SRC) << 16 | (DST))
void Write(const char *s, ...) {
va_list va;
va_start(va, s);
do {
write(2, s, strlen(s));
} while ((s = va_arg(va, const char *)));
va_end(va);
}
wontreturn void SysExit(int rc, const char *call, const char *thing) {
int err;
char ibuf[12];
const char *estr;
err = errno;
FormatInt32(ibuf, err);
estr = _strerdoc(err);
if (!estr) estr = "EUNKNOWN";
Write(thing, ": ", call, "() failed: ", estr, " (", ibuf, ")\n", NULL);
exit(rc);
}
static void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, GETOPTS)) != -1) {
switch (opt) {
case 'h':
case '?':
write(1, USAGE, sizeof(USAGE) - 1);
exit(0);
default:
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
}
}
// Modify ARM64 code to use x28 for TLS rather than tpidr_el0.
void RewriteTlsCode(Elf64_Ehdr *elf, size_t elfsize) {
int i, dest;
Elf64_Shdr *shdr;
uint32_t *p, *pe;
for (i = 0; i < elf->e_shnum; ++i) {
shdr = GetElfSectionHeaderAddress(elf, elfsize, i);
if (shdr->sh_type == SHT_PROGBITS && //
(shdr->sh_flags & SHF_ALLOC) && //
(shdr->sh_flags & SHF_EXECINSTR) && //
(p = GetElfSectionAddress(elf, elfsize, shdr))) {
for (pe = p + shdr->sh_size / 4; p <= pe; ++p) {
if ((*p & -32) == MRS_TPIDR_EL0) {
*p = MOV_REG(*p & 31, COSMO_TLS_REG);
}
}
}
}
}
void OptimizeRelocations(Elf64_Ehdr *elf, size_t elfsize) {
char *strs;
Elf64_Half i;
Elf64_Sym *syms;
Elf64_Rela *rela;
Elf64_Xword symcount;
unsigned char *code, *p;
Elf64_Shdr *shdr, *shdrcode;
CHECK_NOTNULL((strs = GetElfStringTable(elf, elfsize)));
CHECK_NOTNULL((syms = GetElfSymbolTable(elf, elfsize, &symcount)));
for (i = 0; i < elf->e_shnum; ++i) {
shdr = GetElfSectionHeaderAddress(elf, elfsize, i);
if (shdr->sh_type == SHT_RELA) {
CHECK_EQ(sizeof(struct Elf64_Rela), shdr->sh_entsize);
CHECK_NOTNULL(
(shdrcode = GetElfSectionHeaderAddress(elf, elfsize, shdr->sh_info)));
if (!(shdrcode->sh_flags & SHF_EXECINSTR)) continue;
CHECK_NOTNULL((code = GetElfSectionAddress(elf, elfsize, shdrcode)));
for (rela = GetElfSectionAddress(elf, elfsize, shdr);
((uintptr_t)rela + shdr->sh_entsize <=
MIN((uintptr_t)elf + elfsize,
(uintptr_t)elf + shdr->sh_offset + shdr->sh_size));
++rela) {
/*
* GCC isn't capable of -mnop-mcount when using -fpie.
* Let's fix that. It saves ~14 cycles per function call.
* Then libc/runtime/ftrace.greg.c morphs it back at runtime.
*/
if (ELF64_R_TYPE(rela->r_info) == R_X86_64_GOTPCRELX &&
strcmp(GetElfString(elf, elfsize, strs,
syms[ELF64_R_SYM(rela->r_info)].st_name),
"mcount") == 0) {
rela->r_info = R_X86_64_NONE;
p = code + rela->r_offset - 2;
p[0] = 0x66; /* nopw 0x00(%rax,%rax,1) */
p[1] = 0x0f;
p[2] = 0x1f;
p[3] = 0x44;
p[4] = 0x00;
p[5] = 0x00;
}
/*
* Let's just try to nop mcount calls in general due to the above.
*/
if ((ELF64_R_TYPE(rela->r_info) == R_X86_64_PC32 ||
ELF64_R_TYPE(rela->r_info) == R_X86_64_PLT32) &&
strcmp(GetElfString(elf, elfsize, strs,
syms[ELF64_R_SYM(rela->r_info)].st_name),
"mcount") == 0) {
rela->r_info = R_X86_64_NONE;
p = code + rela->r_offset - 1;
p[0] = 0x0f; /* nopl 0x00(%rax,%rax,1) */
p[1] = 0x1f;
p[2] = 0x44;
p[3] = 0x00;
p[4] = 0x00;
}
}
}
}
}
void RewriteObject(const char *path) {
int fd;
struct stat st;
Elf64_Ehdr *elf;
if ((fd = open(path, O_RDWR)) == -1) {
SysExit(__COUNTER__ + 1, "open", path);
}
if (fstat(fd, &st) == -1) {
SysExit(__COUNTER__ + 1, "fstat", path);
}
if (st.st_size >= 64) {
if ((elf = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
0)) == MAP_FAILED) {
SysExit(__COUNTER__ + 1, "mmap", path);
}
if (elf->e_machine == EM_NEXGEN32E) {
OptimizeRelocations(elf, st.st_size);
}
if (elf->e_machine == EM_AARCH64) {
RewriteTlsCode(elf, st.st_size);
}
if (msync(elf, st.st_size, MS_ASYNC | MS_INVALIDATE)) {
SysExit(__COUNTER__ + 1, "msync", path);
}
if (munmap(elf, st.st_size)) {
SysExit(__COUNTER__ + 1, "munmap", path);
}
}
if (close(fd)) {
SysExit(__COUNTER__ + 1, "close", path);
}
}
int main(int argc, char *argv[]) {
int i, opt;
if (IsModeDbg()) ShowCrashReports();
GetOpts(argc, argv);
for (i = optind; i < argc; ++i) {
RewriteObject(argv[i]);
}
}
| 7,623 | 218 | jart/cosmopolitan | false |
cosmopolitan/tool/build/mkdeps.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/alg.h"
#include "libc/mem/alloca.h"
#include "libc/mem/arraylist.internal.h"
#include "libc/mem/arraylist2.internal.h"
#include "libc/mem/bisectcarleft.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/crc32.h"
#include "libc/runtime/ezmap.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/stdio/append.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/clone.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.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/time.h"
#include "libc/x/x.h"
#include "third_party/getopt/getopt.h"
#include "tool/build/lib/getargs.h"
/**
* @fileoverview Make dependency generator.
*
* This generates Makefile code for source -> header dependencies.
*
* Includes look like this:
*
* - #include "root/of/repository/foo.h"
* - .include "root/of/repository/foo.inc"
*
* They do not look like this:
*
* - #include "foo.h"
* - # include "foo.h"
* - #include "foo.h"
*
*/
#define kIncludePrefix "include \""
#define THREADS 1 // _getcpucount()
#define LOCK (void) // if (__threaded) pthread_spin_lock
#define UNLOCK (void) // pthread_spin_unlock
const char kSourceExts[][5] = {".s", ".S", ".c", ".cc", ".cpp"};
const char *const kIgnorePrefixes[] = {
#if 0
"libc/sysv/consts/", "libc/sysv/calls/", "libc/nt/kernel32/",
"libc/nt/KernelBase/", "libc/nt/advapi32/", "libc/nt/gdi32/",
"libc/nt/ntdll/", "libc/nt/user32/", "libc/nt/shell32/",
#endif
};
struct Strings {
size_t i, n;
char *p;
};
struct Source {
unsigned hash;
unsigned name;
unsigned id;
};
struct Edge {
unsigned to;
unsigned from;
};
struct Sources {
size_t i, n;
struct Source *p;
};
struct Sauce {
unsigned name;
unsigned id;
};
struct Edges {
size_t i, n;
struct Edge *p;
};
char *out;
char **bouts;
pthread_t *th;
unsigned counter;
struct GetArgs ga;
struct Edges edges;
struct Sauce *sauces;
struct Strings strings;
struct Sources sources;
const char *buildroot;
pthread_spinlock_t galock;
pthread_spinlock_t readlock;
pthread_spinlock_t writelock;
pthread_spinlock_t reportlock;
unsigned Hash(const void *s, size_t l) {
return max(1, crc32c(0, s, l));
}
unsigned FindFirstFromEdge(unsigned id) {
unsigned m, l, r;
l = 0;
r = edges.i;
while (l < r) {
m = (l + r) >> 1;
if (edges.p[m].from < id) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
void Crunch(void) {
size_t i, j;
sauces = malloc(sizeof(*sauces) * sources.n);
for (j = i = 0; i < sources.n; ++i) {
if (sources.p[i].hash) {
sauces[j].name = sources.p[i].name;
sauces[j].id = sources.p[i].id;
j++;
}
}
free(sources.p);
sources.p = 0;
sources.i = j;
_longsort((const long *)sauces, sources.i);
_longsort((const long *)edges.p, edges.i);
}
void Rehash(void) {
size_t i, j, step;
struct Sources old;
memcpy(&old, &sources, sizeof(sources));
sources.n = sources.n ? sources.n << 1 : 16;
sources.p = calloc(sources.n, sizeof(struct Source));
for (i = 0; i < old.n; ++i) {
if (!old.p[i].hash) continue;
step = 0;
do {
j = (old.p[i].hash + step * (step + 1) / 2) & (sources.n - 1);
step++;
} while (sources.p[j].hash);
sources.p[j] = old.p[i];
}
free(old.p);
}
unsigned GetSourceId(const char *name, size_t len) {
size_t i, step;
unsigned hash;
i = 0;
hash = Hash(name, len);
if (sources.n) {
step = 0;
do {
i = (hash + step * (step + 1) / 2) & (sources.n - 1);
if (sources.p[i].hash == hash &&
!memcmp(name, &strings.p[sources.p[i].name], len)) {
return sources.p[i].id;
}
step++;
} while (sources.p[i].hash);
}
if (++sources.i >= (sources.n >> 1)) {
Rehash();
step = 0;
do {
i = (hash + step * (step + 1) / 2) & (sources.n - 1);
step++;
} while (sources.p[i].hash);
}
sources.p[i].hash = hash;
sources.p[i].name = CONCAT(&strings.p, &strings.i, &strings.n, name, len);
strings.p[strings.i++] = '\0';
return (sources.p[i].id = counter++);
}
bool ShouldSkipSource(const char *src) {
unsigned j;
for (j = 0; j < ARRAYLEN(kIgnorePrefixes); ++j) {
if (_startswith(src, kIgnorePrefixes[j])) {
return true;
}
}
return false;
}
wontreturn void OnMissingFile(const char *list, const char *src) {
kprintf("%s is missing\n", src);
DCHECK_EQ(ENOENT, errno, "%s", src);
/*
* This code helps GNU Make automatically fix itself when we
* delete a source file. It removes o/.../srcs.txt or
* o/.../hdrs.txt and exits nonzero. Since we use hyphen
* notation on mkdeps related rules, the build will
* automatically restart itself.
*/
if (list) {
kprintf("%s %s...\n", "Refreshing", list);
unlink(list);
}
exit(1);
}
void *LoadRelationshipsWorker(void *arg) {
int fd;
ssize_t rc;
bool skipme;
struct stat st;
struct Edge edge;
size_t i, n, size, inclen;
unsigned srcid, dependency;
char *buf, srcbuf[PATH_MAX];
const char *p, *pe, *src, *path, *pathend;
inclen = strlen(kIncludePrefix);
for (;;) {
LOCK(&galock);
if ((src = getargs_next(&ga))) strcpy(srcbuf, src);
UNLOCK(&galock);
if (!src) break;
src = srcbuf;
if (ShouldSkipSource(src)) continue;
n = strlen(src);
LOCK(&readlock);
srcid = GetSourceId(src, n);
UNLOCK(&readlock);
if ((fd = open(src, O_RDONLY)) == -1) {
LOCK(&reportlock);
OnMissingFile(ga.path, src);
}
CHECK_NE(-1, fstat(fd, &st));
if ((size = st.st_size)) {
CHECK_NE(MAP_FAILED, (buf = mmap(0, size, PROT_READ, MAP_SHARED, fd, 0)));
for (p = buf + 1, pe = buf + size; p < pe; ++p) {
if (!(p = memmem(p, pe - p, kIncludePrefix, inclen))) break;
path = p + inclen;
pathend = memchr(path, '"', pe - path);
if (pathend && //
(p[-1] == '#' || p[-1] == '.') && //
(p - buf == 1 || p[-2] == '\n')) { //
LOCK(&readlock);
dependency = GetSourceId(path, pathend - path);
UNLOCK(&readlock);
edge.from = srcid;
edge.to = dependency;
LOCK(&writelock);
append(&edges, &edge);
UNLOCK(&writelock);
p = pathend;
}
}
munmap(buf, size);
}
close(fd);
}
return 0;
}
void LoadRelationships(int argc, char *argv[]) {
int i;
getargs_init(&ga, argv + optind);
if (THREADS == 1) {
LoadRelationshipsWorker((void *)(intptr_t)0);
} else {
for (i = 0; i < THREADS; ++i) {
if (pthread_create(th + i, 0, LoadRelationshipsWorker,
(void *)(intptr_t)i)) {
LOCK(&reportlock);
kprintf("error: _spawn(%d) failed %m\n", i);
exit(1);
}
}
for (i = 0; i < THREADS; ++i) {
pthread_join(th[i], 0);
}
}
getargs_destroy(&ga);
}
void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "ho:r:")) != -1) {
switch (opt) {
case 'o':
out = optarg;
break;
case 'r':
buildroot = optarg;
break;
default:
kprintf("%s: %s [-r %s] [-o %s] [%s...]\n", "Usage", argv[0],
"BUILDROOT", "OUTPUT", "PATHSFILE");
exit(1);
}
}
if (isempty(out)) kprintf("need -o FILE"), exit(1);
if (isempty(buildroot)) kprintf("need -r o/$(MODE)"), exit(1);
}
const char *StripExt(char pathbuf[PATH_MAX], const char *s) {
static char *dot;
strcpy(pathbuf, s);
dot = strrchr(pathbuf, '.');
if (dot) *dot = '\0';
return pathbuf;
}
bool IsObjectSource(const char *name) {
int i;
for (i = 0; i < ARRAYLEN(kSourceExts); ++i) {
if (_endswith(name, kSourceExts[i])) return true;
}
return false;
}
forceinline bool Bts(uint32_t *p, size_t i) {
bool r;
uint32_t k;
k = 1u << (i & 31);
if (p[i >> 5] & k) return true;
p[i >> 5] |= k;
return false;
}
size_t GetFileSizeOrZero(const char *path) {
struct stat st;
st.st_size = 0;
stat(path, &st);
return st.st_size;
}
void Dive(char **bout, uint32_t *visited, unsigned id) {
int i;
for (i = FindFirstFromEdge(id); i < edges.i && edges.p[i].from == id; ++i) {
if (Bts(visited, edges.p[i].to)) continue;
appendw(bout, READ32LE(" \\\n\t"));
appends(bout, strings.p + sauces[edges.p[i].to].name);
Dive(bout, visited, edges.p[i].to);
}
}
void *Diver(void *arg) {
char *bout = 0;
const char *path;
uint32_t *visited;
size_t i, visilen;
char pathbuf[PATH_MAX];
int x = (intptr_t)arg;
visilen = (sources.i + sizeof(*visited) * CHAR_BIT - 1) /
(sizeof(*visited) * CHAR_BIT);
visited = malloc(visilen * sizeof(*visited));
for (i = x; i < sources.i; i += THREADS) {
path = strings.p + sauces[i].name;
if (!IsObjectSource(path)) continue;
appendw(&bout, '\n');
if (!_startswith(path, "o/")) {
appends(&bout, buildroot);
}
appends(&bout, StripExt(pathbuf, path));
appendw(&bout, READ64LE(".o: \\\n\t"));
appends(&bout, path);
bzero(visited, visilen * sizeof(*visited));
Bts(visited, i);
Dive(&bout, visited, i);
appendw(&bout, '\n');
}
free(visited);
appendw(&bout, '\n');
bouts[x] = bout;
return 0;
}
void Explore(void) {
int i;
if (THREADS == 1) {
Diver((void *)(intptr_t)0);
} else {
for (i = 0; i < THREADS; ++i) {
if (pthread_create(th + i, 0, Diver, (void *)(intptr_t)i)) {
LOCK(&reportlock);
kprintf("error: _spawn(%d) failed %m\n", i);
exit(1);
}
}
for (i = 0; i < THREADS; ++i) {
pthread_join(th[i], 0);
}
}
}
int main(int argc, char *argv[]) {
int i, fd;
ShowCrashReports();
if (argc == 2 && !strcmp(argv[1], "-n")) exit(0);
GetOpts(argc, argv);
th = calloc(THREADS, sizeof(*th));
bouts = calloc(THREADS, sizeof(*bouts));
LoadRelationships(argc, argv);
Crunch();
Explore();
CHECK_NE(-1, (fd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0644)),
"open(%#s)", out);
for (i = 0; i < THREADS; ++i) {
CHECK_NE(-1, xwrite(fd, bouts[i], appendz(bouts[i]).i));
}
CHECK_NE(-1, close(fd));
for (i = 0; i < THREADS; ++i) {
free(bouts[i]);
}
free(strings.p);
free(edges.p);
free(sauces);
free(bouts);
free(th);
return 0;
}
| 12,776 | 462 | jart/cosmopolitan | false |
cosmopolitan/tool/build/runit.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 "tool/build/runit.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/stat.h"
#include "libc/dns/dns.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/limits.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/ipclassify.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/limits.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/sock.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "libc/x/xasprintf.h"
#include "net/https/https.h"
#include "third_party/mbedtls/ssl.h"
#include "third_party/zlib/zlib.h"
#include "tool/build/lib/eztls.h"
#include "tool/build/lib/psk.h"
#define MAX_WAIT_CONNECT_SECONDS 12
#define INITIAL_CONNECT_TIMEOUT 100000
/**
* @fileoverview Remote test runner.
*
* We want to scp .com binaries to remote machines and run them. The
* problem is that SSH is the slowest thing imaginable, taking about
* 300ms to connect to a host that's merely half a millisecond away.
*
* This program takes 17ms using elliptic curve diffie hellman exchange
* where we favor a 32-byte binary preshared key (~/.runit.psk) instead
* of certificates. It's how long it takes to connect, copy the binary,
* and run it. The remote daemon is deployed via SSH if it's not there.
*
* o/default/tool/build/runit.com \
* o/default/tool/build/runitd.com \
* o/default/test/libc/mem/qsort_test.com \
* freebsd.test.:31337:22
*
* APE binaries are hermetic and embed dependent files within their zip
* structure, which is why all we need is this simple test runner tool.
* The only thing that needs to be configured is /etc/hosts or Bind, to
* assign numbers to the officially reserved canned names. For example:
*
* 192.168.0.10 windows.test. windows
* 192.168.0.11 freebsd.test. freebsd
* 192.168.0.12 openbsd.test. openbsd
*
* Life is easiest if SSH public key authentication is configured too.
* It can be tuned as follows in ~/.ssh/config:
*
* host windows.test.
* user testacct
* host freebsd.test.
* user testacct
* host openbsd.test.
* user testacct
*
* Firewalls may need to be configured as well, to allow port tcp:31337
* from the local subnet. For example:
*
* iptables -L -vn
* iptables -I INPUT 1 -s 10.0.0.0/8 -p tcp --dport 31337 -j ACCEPT
* iptables -I INPUT 1 -s 192.168.0.0/16 -p tcp --dport 31337 -j ACCEPT
*
* This tool may be used in zero trust environments.
*/
static const struct addrinfo kResolvHints = {.ai_family = AF_INET,
.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP};
int g_sock;
char *g_prog;
long g_backoff;
char *g_runitd;
jmp_buf g_jmpbuf;
uint16_t g_sshport;
char g_hostname[128];
uint16_t g_runitdport;
volatile bool alarmed;
int __sys_execve(const char *, char *const[], char *const[]) _Hide;
static void OnAlarm(int sig) {
alarmed = true;
}
wontreturn void ShowUsage(FILE *f, int rc) {
fprintf(f, "Usage: %s RUNITD PROGRAM HOSTNAME[:RUNITDPORT[:SSHPORT]]...\n",
program_invocation_name);
exit(rc);
unreachable;
}
void CheckExists(const char *path) {
if (!isregularfile(path)) {
fprintf(stderr, "error: %s: not found or irregular\n", path);
ShowUsage(stderr, EX_USAGE);
unreachable;
}
}
void Connect(void) {
const char *ip4;
int rc, err, expo;
long double t1, t2;
struct addrinfo *ai;
if ((rc = getaddrinfo(g_hostname, _gc(xasprintf("%hu", g_runitdport)),
&kResolvHints, &ai)) != 0) {
FATALF("%s:%hu: EAI_%s %m", g_hostname, g_runitdport, gai_strerror(rc));
unreachable;
}
ip4 = (const char *)&ai->ai_addr4->sin_addr;
if (ispublicip(ai->ai_family, &ai->ai_addr4->sin_addr)) {
FATALF("%s points to %hhu.%hhu.%hhu.%hhu"
" which isn't part of a local/private/testing subnet",
g_hostname, ip4[0], ip4[1], ip4[2], ip4[3]);
unreachable;
}
DEBUGF("connecting to %d.%d.%d.%d port %d", ip4[0], ip4[1], ip4[2], ip4[3],
ntohs(ai->ai_addr4->sin_port));
CHECK_NE(-1,
(g_sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)));
expo = INITIAL_CONNECT_TIMEOUT;
t1 = nowl();
LOGIFNEG1(sigaction(SIGALRM, &(struct sigaction){.sa_handler = OnAlarm}, 0));
DEBUGF("connecting to %s (%hhu.%hhu.%hhu.%hhu) to run %s", g_hostname, ip4[0],
ip4[1], ip4[2], ip4[3], g_prog);
TryAgain:
alarmed = false;
LOGIFNEG1(setitimer(
ITIMER_REAL,
&(const struct itimerval){{0, 0}, {expo / 1000000, expo % 1000000}},
NULL));
rc = connect(g_sock, ai->ai_addr, ai->ai_addrlen);
err = errno;
t2 = nowl();
if (rc == -1) {
if (err == EINTR) {
expo *= 1.5;
if (t2 > t1 + MAX_WAIT_CONNECT_SECONDS) {
FATALF("timeout connecting to %s (%hhu.%hhu.%hhu.%hhu:%d)", g_hostname,
ip4[0], ip4[1], ip4[2], ip4[3], ntohs(ai->ai_addr4->sin_port));
unreachable;
}
goto TryAgain;
}
FATALF("%s(%s:%hu): %s", "connect", g_hostname, g_runitdport,
strerror(err));
} else {
DEBUGF("connected to %s", g_hostname);
}
setitimer(ITIMER_REAL, &(const struct itimerval){0}, 0);
freeaddrinfo(ai);
}
bool Send(int tmpfd, const void *output, size_t outputsize) {
bool ok;
char *zbuf;
size_t zsize;
int rc, have;
static bool once;
static z_stream zs;
zsize = 32768;
zbuf = _gc(malloc(zsize));
if (!once) {
CHECK_EQ(Z_OK, deflateInit2(&zs, 4, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY));
once = true;
}
zs.next_in = output;
zs.avail_in = outputsize;
ok = true;
do {
zs.avail_out = zsize;
zs.next_out = (unsigned char *)zbuf;
rc = deflate(&zs, Z_SYNC_FLUSH);
CHECK_NE(Z_STREAM_ERROR, rc);
have = zsize - zs.avail_out;
rc = write(tmpfd, zbuf, have);
if (rc != have) {
DEBUGF("write(%d, %d) â %d", tmpfd, have, rc);
ok = false;
break;
}
} while (!zs.avail_out);
return ok;
}
bool SendRequest(int tmpfd) {
int fd;
char *p;
size_t i;
bool okall;
ssize_t rc;
uint32_t crc;
struct stat st;
const char *name;
unsigned char *hdr, *q;
size_t progsize, namesize, hdrsize;
unsigned have;
CHECK_NE(-1, (fd = open(g_prog, O_RDONLY)));
CHECK_NE(-1, fstat(fd, &st));
CHECK_NE(MAP_FAILED, (p = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0)));
CHECK_LE((namesize = strlen((name = basename(g_prog)))), PATH_MAX);
CHECK_LE((progsize = st.st_size), INT_MAX);
CHECK_NOTNULL((hdr = _gc(calloc(1, (hdrsize = 17 + namesize)))));
crc = crc32_z(0, (unsigned char *)p, st.st_size);
q = hdr;
q = WRITE32BE(q, RUNITD_MAGIC);
*q++ = kRunitExecute;
q = WRITE32BE(q, namesize);
q = WRITE32BE(q, progsize);
q = WRITE32BE(q, crc);
q = mempcpy(q, name, namesize);
assert(hdrsize == q - hdr);
okall = true;
okall &= Send(tmpfd, hdr, hdrsize);
okall &= Send(tmpfd, p, progsize);
CHECK_NE(-1, munmap(p, st.st_size));
CHECK_NE(-1, close(fd));
return okall;
}
void RelayRequest(void) {
int i, rc, have, transferred;
char *buf = _gc(malloc(PIPE_BUF));
for (transferred = 0;;) {
rc = read(13, buf, PIPE_BUF);
CHECK_NE(-1, rc);
have = rc;
if (!rc) break;
transferred += have;
for (i = 0; i < have; i += rc) {
rc = mbedtls_ssl_write(&ezssl, buf + i, have - i);
if (rc <= 0) {
TlsDie("relay request failed", rc);
}
}
}
CHECK_NE(0, transferred);
rc = EzTlsFlush(&ezbio, 0, 0);
if (rc < 0) {
TlsDie("relay request failed to flush", rc);
}
close(13);
}
bool Recv(unsigned char *p, size_t n) {
size_t i, rc;
for (i = 0; i < n; i += rc) {
do {
rc = mbedtls_ssl_read(&ezssl, p + i, n - i);
} while (rc == MBEDTLS_ERR_SSL_WANT_READ);
if (!rc) return false;
if (rc < 0) {
TlsDie("read response failed", rc);
}
}
return true;
}
int ReadResponse(void) {
int res;
ssize_t rc;
size_t n, m;
uint32_t size;
unsigned char b[512];
for (res = -1; res == -1;) {
if (!Recv(b, 5)) break;
CHECK_EQ(RUNITD_MAGIC, READ32BE(b), "%#.5s", b);
switch (b[4]) {
case kRunitExit:
if (!Recv(b, 1)) break;
if ((res = *b)) {
WARNF("%s on %s exited with %d", g_prog, g_hostname, res);
}
break;
case kRunitStderr:
if (!Recv(b, 4)) break;
size = READ32BE(b);
for (; size; size -= n) {
n = MIN(size, sizeof(b));
if (!Recv(b, n)) goto drop;
CHECK_EQ(n, write(2, b, n));
}
break;
default:
fprintf(stderr, "error: received invalid runit command\n");
_exit(1);
}
}
drop:
close(g_sock);
return res;
}
static inline bool IsElf(const char *p, size_t n) {
return n >= 4 && READ32LE(p) == READ32LE("\177ELF");
}
static inline bool IsMachO(const char *p, size_t n) {
return n >= 4 && READ32LE(p) == 0xFEEDFACEu + 1;
}
int RunOnHost(char *spec) {
int rc;
char *p;
for (p = spec; *p; ++p) {
if (*p == ':') *p = ' ';
}
CHECK_GE(sscanf(spec, "%100s %hu %hu", g_hostname, &g_runitdport, &g_sshport),
1);
if (!strchr(g_hostname, '.')) strcat(g_hostname, ".test.");
DEBUGF("connecting to %s port %d", g_hostname, g_runitdport);
for (;;) {
Connect();
EzFd(g_sock);
if (!(rc = EzHandshake2())) {
break;
}
WARNF("got reset in handshake -0x%04x", rc);
close(g_sock);
}
RelayRequest();
return ReadResponse();
}
bool IsParallelBuild(void) {
const char *makeflags;
return (makeflags = getenv("MAKEFLAGS")) && strstr(makeflags, "-j");
}
bool ShouldRunInParallel(void) {
return !IsWindows() && IsParallelBuild();
}
int SpawnSubprocesses(int argc, char *argv[]) {
const char *tpath;
sigset_t chldmask, savemask;
int i, rc, ws, pid, tmpfd, *pids, exitcode;
struct sigaction ignore, saveint, savequit;
char *args[5] = {argv[0], argv[1], argv[2]};
// create compressed network request ahead of time
CHECK_NE(-1, (tmpfd = open(
(tpath = _gc(xasprintf(
"%s/runit.%d", firstnonnull(getenv("TMPDIR"), "/tmp"),
getpid()))),
O_WRONLY | O_CREAT | O_TRUNC, 0755)));
CHECK(SendRequest(tmpfd));
CHECK_NE(-1, close(tmpfd));
// fork off ð subprocesses for each host on which we run binary.
// what's important here is htop in tree mode will report like:
//
// runit.com xnu freebsd netbsd
// âârunit.com xnu
// âârunit.com freebsd
// âârunit.com netbsd
//
// That way when one hangs, it's easy to know what o/s it is.
argc -= 3;
argv += 3;
exitcode = 0;
pids = calloc(argc, sizeof(int));
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);
for (i = 0; i < argc; ++i) {
args[3] = argv[i];
CHECK_NE(-1, (pids[i] = vfork()));
if (!pids[i]) {
dup2(open(tpath, O_RDONLY | O_CLOEXEC), 13);
sigaction(SIGINT, &(struct sigaction){0}, 0);
sigaction(SIGQUIT, &(struct sigaction){0}, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
execve(args[0], args, environ); // for htop
_Exit(127);
}
}
// wait for children to terminate
for (;;) {
if ((pid = wait(&ws)) == -1) {
if (errno == EINTR) continue;
if (errno == ECHILD) break;
FATALF("wait failed");
}
for (i = 0; i < argc; ++i) {
if (pids[i] != pid) continue;
if (WIFEXITED(ws)) {
if (WEXITSTATUS(ws)) {
INFOF("%s exited with %d", argv[i], WEXITSTATUS(ws));
} else {
DEBUGF("%s exited with %d", argv[i], WEXITSTATUS(ws));
}
if (!exitcode) exitcode = WEXITSTATUS(ws);
} else {
INFOF("%s terminated with %s", argv[i], strsignal(WTERMSIG(ws)));
if (!exitcode) exitcode = 128 + WTERMSIG(ws);
}
break;
}
}
CHECK_NE(-1, unlink(tpath));
sigprocmask(SIG_SETMASK, &savemask, 0);
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGINT, &saveint, 0);
free(pids);
return exitcode;
}
int main(int argc, char *argv[]) {
ShowCrashReports();
if (getenv("DEBUG")) {
__log_level = kLogDebug;
}
if (argc > 1 &&
(strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
ShowUsage(stdout, 0);
unreachable;
}
if (argc < 3) {
ShowUsage(stderr, EX_USAGE);
unreachable;
}
CheckExists((g_runitd = argv[1]));
CheckExists((g_prog = argv[2]));
if (argc == 3) {
/* hosts list empty */
return 0;
} else if (argc == 4) {
/* TODO(jart): this is broken */
/* single host */
SetupPresharedKeySsl(MBEDTLS_SSL_IS_CLIENT, GetRunitPsk());
g_sshport = 22;
g_runitdport = RUNITD_PORT;
return RunOnHost(argv[3]);
} else {
/* multiple hosts */
return SpawnSubprocesses(argc, argv);
}
}
| 15,510 | 489 | jart/cosmopolitan | false |
cosmopolitan/tool/build/xlat.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/fmt/conv.h"
#include "libc/log/check.h"
#include "libc/math.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/str/tab.internal.h"
#include "libc/x/xasprintf.h"
/**
* @fileoverview Tool for generating rldecode'd character sets, e.g.
*
* # generate http token table
* o//tool/build/xlat.com -TiC ' ()<>@,;:\"/[]?={}' -i
*/
int dig;
int xlat[256];
bool identity;
const char *symbol;
static int Bing(int c) {
if (!c) return L'â
';
if (c == ' ') return L'â ';
if (c == '$') return L'§';
if (c == '\\') return L'â';
return kCp437[c & 255];
}
static void Fill(int f(int)) {
int i;
for (i = 0; i < 256; ++i) {
if (f(i)) {
xlat[i] = identity ? i : 1;
}
}
}
static void Invert(void) {
int i;
for (i = 0; i < 256; ++i) {
xlat[i] = !xlat[i];
}
}
static void Negate(void) {
int i;
for (i = 0; i < 256; ++i) {
xlat[i] = ~xlat[i] & 255;
}
}
static void Negative(void) {
int i;
for (i = 0; i < 256; ++i) {
xlat[i] = -xlat[i] & 255;
}
}
static bool ArgNeedsShellQuotes(const char *s) {
if (*s) {
for (;;) {
switch (*s++ & 255) {
case 0:
return false;
case '-':
case '.':
case '/':
case '_':
case '=':
case ':':
case '0' ... '9':
case 'A' ... 'Z':
case 'a' ... 'z':
break;
default:
return true;
}
}
} else {
return true;
}
}
static char *AddShellQuotes(const char *s) {
char *p, *q;
size_t i, j, n;
n = strlen(s);
p = malloc(1 + n * 5 + 1 + 1);
j = 0;
p[j++] = '\'';
for (i = 0; i < n; ++i) {
if (s[i] != '\'') {
p[j++] = s[i];
} else {
p[j + 0] = '\'';
p[j + 1] = '"';
p[j + 2] = '\'';
p[j + 3] = '"';
p[j + 4] = '\'';
j += 5;
}
}
p[j++] = '\'';
p[j] = 0;
if ((q = realloc(p, j + 1))) p = q;
return p;
}
static const char *GetArg(char *argv[], int i, int *k) {
if (argv[*k][i + 1]) {
return argv[*k] + i + 1;
} else {
return argv[++*k];
}
}
int main(int argc, char *argv[]) {
const char *arg;
int i, j, k, opt;
dig = 1;
symbol = "kXlatTab";
for (k = 1; k < argc; ++k) {
if (argv[k][0] != '-') {
for (i = 0; argv[k][i]; ++i) {
/* xlat[argv[k][i] & 255] = identity ? i : dig; */
xlat[argv[k][i] & 255] = identity ? (argv[k][i] & 255) : dig;
}
} else {
i = 0;
moar:
++i;
if ((opt = argv[k][i])) {
switch (opt) {
case 's':
symbol = GetArg(argv, i, &k);
break;
case 'x':
dig = atoi(GetArg(argv, i, &k)) & 255;
break;
case 'i':
Invert();
goto moar;
case 'I':
identity = !identity;
goto moar;
case 'n':
Negative();
goto moar;
case 'N':
Negate();
goto moar;
case 'T':
Fill(isascii);
goto moar;
case 'C':
Fill(iscntrl);
goto moar;
case 'A':
Fill(isalpha);
goto moar;
case 'B':
Fill(isblank);
goto moar;
case 'G':
Fill(isgraph);
goto moar;
case 'P':
Fill(ispunct);
goto moar;
case 'D':
Fill(isdigit);
goto moar;
case 'U':
Fill(isupper);
goto moar;
case 'L':
Fill(islower);
goto moar;
default:
fprintf(stderr, "error: unrecognized option: %c\n", opt);
return 1;
}
}
}
}
////////////////////////////////////////////////////////////
printf("#include \"libc/macros.internal.h\"\n");
printf("\n");
printf("//\tgenerated by:\n");
printf("//\t");
for (i = 0; i < argc; ++i) {
if (i) printf(" ");
printf("%s", !ArgNeedsShellQuotes(argv[i]) ? argv[i]
: _gc(AddShellQuotes(argv[i])));
}
printf("\n");
////////////////////////////////////////////////////////////
printf("//\n");
printf("//\t present absent\n");
printf("//\t ââââââââââââââââ ââââââââââââââââ\n");
for (i = 0; i < 16; ++i) {
char16_t absent[16];
char16_t present[16];
for (j = 0; j < 16; ++j) {
if (xlat[i * 16 + j]) {
absent[j] = L' ';
present[j] = Bing(i * 16 + j);
} else {
absent[j] = Bing(i * 16 + j);
present[j] = L' ';
}
}
printf("//\t %.16hs %.16hs 0x%02x\n", present, absent, i * 16);
}
////////////////////////////////////////////////////////////
printf("//\n");
printf("//\tconst char %s[256] = {\n//\t", symbol);
for (i = 0; i < 16; ++i) {
printf(" ");
for (j = 0; j < 16; ++j) {
printf("%2d,", (char)xlat[i * 16 + j]);
}
printf(" // 0x%02x\n//\t", i * 16);
}
printf("};\n");
printf("\n");
////////////////////////////////////////////////////////////
printf("\t.initbss 300,_init_%s\n", symbol);
printf("%s:\n", symbol);
printf("\t.zero\t256\n");
printf("\t.endobj\t%s,globl\n", symbol);
printf("\t.previous\n");
printf("\n");
////////////////////////////////////////////////////////////
printf("\t.initro 300,_init_%s\n", symbol);
printf("%s.rom:\n", symbol);
int thebloat = 0;
int thetally = 0;
int thecount = 0;
int runstart = 0;
int runchar = -1;
int runcount = 0;
for (i = 0;; ++i) {
if (i < 256 && xlat[i] == runchar) {
++runcount;
} else {
if (runcount) {
printf("\t.byte\t%-24s# %02x-%02x %hc-%hc\n",
_gc(xasprintf("%3d,%d", runcount, runchar)), runstart,
runstart + runcount - 1, Bing(runstart),
Bing(runstart + runcount - 1));
thetally += 2;
thecount += runcount;
}
if (i < 256) {
runcount = 1;
runchar = xlat[i];
runstart = i;
}
}
if (i == 256) {
break;
}
}
CHECK_EQ(256, thecount);
printf("\t.byte\t%-24s# terminator\n", "0,0");
thetally += 2;
thebloat = thetally;
for (i = 0; (thetally + i) % 8; i += 2) {
printf("\t.byte\t%-24s# padding\n", "0,0");
thebloat += 2;
}
printf("\t.endobj\t%s.rom,globl\n", symbol);
printf("\n");
////////////////////////////////////////////////////////////
printf("\t.init.start 300,_init_%s\n", symbol);
printf("\tcall\trldecode\n");
thebloat += 5;
int padding = 8 - thetally % 8;
if (padding < 8) {
if (padding >= 4) {
thebloat += 1;
printf("\tlodsl\n");
padding -= 4;
}
if (padding >= 2) {
thebloat += 2;
printf("\tlodsw\n");
}
}
printf("\t.init.end 300,_init_%s\n", symbol);
////////////////////////////////////////////////////////////
printf("\n");
printf("//\t%d bytes total (%d%% original size)\n", thebloat,
(int)round((double)thebloat / 256 * 100));
}
| 9,105 | 331 | jart/cosmopolitan | false |
cosmopolitan/tool/build/runit.h | #ifndef COSMOPOLITAN_TOOL_BUILD_RUNIT_H_
#define COSMOPOLITAN_TOOL_BUILD_RUNIT_H_
#define RUNITD_PORT 31337
#define RUNITD_MAGIC 0xFEEDABEEu
#define RUNITD_TIMEOUT_MS (1000 * 60 * 60)
enum RunitCommand {
kRunitExecute,
kRunitStdout,
kRunitStderr,
kRunitExit,
};
#endif /* COSMOPOLITAN_TOOL_BUILD_RUNIT_H_ */
| 330 | 16 | jart/cosmopolitan | false |
cosmopolitan/tool/build/pstrace.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.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/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 "libc/sysv/consts/nr.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/x/xasprintf.h"
#include "libc/x/xgetline.h"
#include "third_party/dlmalloc/dlmalloc.h"
#include "third_party/getopt/getopt.h"
/**
* @fileoverview Pythonic System Call Trace
*
* This program invokes `strace` as a subprocess and turns its output
* into Python data structures. It is useful because strace output is
* this weird plaintext format that's so famously difficult to parse.
*
* For example, you can run this command:
*
* pstrace -o trace.pylog echo hello world
*
* After which you may parse the output with Python:
*
* for line in open('trace.pylog'):
* pid,time,elap,kind,x = eval(line)
* if kind == 1:
* name,ret,args = x
* print "%s%r -> %d" % (name, args, ret)
*
* This program traces the subset of system calls governing processes
* and files. To do that we must track file descriptor lifetimes too.
* We also track system calls that are problematic for build configs,
* such as sockets, since compiling code shouldn't need the Internet.
*
* @note this tool is linux only
* @note freebsd: truss PROC ARGS
* @note appleos: sudo dtruss PROC ARGS
* @note openbsd: ktrace PROC ARGS && kdump -f ktrace.out
* @note windows: https://github.com/rogerorr/NtTrace
*/
#define DEBUG "%ld: %s", lineno, line
#define READ128BE(S) ((uint128_t)READ64BE(S) << 64 | READ64BE((S) + 8))
#define APPEND(L) \
do { \
if (++L.n > L.c) { \
L.c = MAX(11, L.c); \
L.c += L.c >> 1; \
L.p = realloc(L.p, L.c * sizeof(*L.p)); \
} \
bzero(L.p + L.n - 1, sizeof(*L.p)); \
} while (0)
struct Trace {
struct Slices {
long n, c;
struct Slice {
int n, c;
char *p;
} * p;
} slices;
struct HashTable {
long i, n;
struct HashEntry {
long h;
long i;
} * p;
} sliceindex;
struct Strlists {
long n, c;
struct Strlist {
long n, c;
long *p; // slices.p[p[i]]
} * p;
} strlists;
struct Events {
long n, c;
struct Event {
enum EventKind {
EK_NONE,
EK_CALL,
EK_EXIT, // ret is kernel code
EK_SIGNAL, // ret is signal code
EK_KILLED, // ret is signal code
} kind;
unsigned char arity;
unsigned char syscall_;
bool is_interrupted;
int us;
int elap;
int pid;
long sec;
long ret;
long lineno;
struct Arg {
enum ArgKind {
AK_LONG, // x
AK_STR, // slices.p[x]
AK_STRLIST, // strlists.p[x]
AK_INTPAIR, // (x&0xffffffff, x>>32)
} kind;
long name;
long x;
} arg[6];
} * p;
} events;
};
static const struct Syscall {
char name[16];
} kSyscalls[] = {
{"accept"}, //
{"accept4"}, //
{"access"}, //
{"bind"}, //
{"chdir"}, //
{"chmod"}, //
{"chown"}, //
{"chroot"}, //
{"clone"}, //
{"close"}, //
{"connect"}, //
{"creat"}, //
{"dup"}, //
{"dup2"}, //
{"dup3"}, //
{"epoll_create"}, //
{"epoll_create1"}, //
{"eventfd"}, //
{"eventfd2"}, //
{"execve"}, //
{"execveat"}, //
{"faccessat"}, //
{"fchmodat"}, //
{"fchownat"}, //
{"fdatasync"}, //
{"fcntl"}, //
{"flock"}, //
{"fork"}, //
{"fsync"}, //
{"lchown"}, //
{"link"}, //
{"linkat"}, //
{"listen"}, //
{"memfd_create"}, //
{"mkdir"}, //
{"mkdirat"}, //
{"mknod"}, //
{"mknodat"}, //
{"open"}, //
{"openat"}, //
{"pipe"}, //
{"pipe2"}, //
{"readlink"}, //
{"readlinkat"}, //
{"rename"}, //
{"renameat"}, //
{"renameat2"}, //
{"rmdir"}, //
{"signalfd"}, //
{"signalfd4"}, //
{"socket"}, //
{"socketpair"}, //
{"statfs"}, //
{"symlink"}, //
{"symlinkat"}, //
{"sync"}, //
{"syncfs"}, //
{"timerfd_create"}, //
{"truncate"}, //
{"unlink"}, //
{"unlinkat"}, //
{"utimensat"}, //
{"vfork"}, //
};
static const struct Signal {
char name[8];
unsigned char number;
} kSignals[] = {
{"SIGABRT", 6}, //
{"SIGALRM", 14}, //
{"SIGBUS", 7}, //
{"SIGCHLD", 17}, //
{"SIGCONT", 18}, //
{"SIGFPE", 8}, //
{"SIGHUP", 1}, //
{"SIGILL", 4}, //
{"SIGINT", 2}, //
{"SIGIO", 29}, //
{"SIGIOT", 6}, //
{"SIGKILL", 9}, //
{"SIGPIPE", 13}, //
{"SIGPOLL", 29}, //
{"SIGPROF", 27}, //
{"SIGPWR", 30}, //
{"SIGQUIT", 3}, //
{"SIGSEGV", 11}, //
{"SIGSTOP", 19}, //
{"SIGSYS", 31}, //
{"SIGTERM", 15}, //
{"SIGTRAP", 5}, //
{"SIGTSTP", 20}, //
{"SIGTTIN", 21}, //
{"SIGTTOU", 22}, //
{"SIGURG", 23}, //
{"SIGUSR1", 10}, //
{"SIGUSR2", 12}, //
{"SIGWINCH", 28}, //
{"SIGXCPU", 24}, //
{"SIGXFSZ", 25}, //
};
static const struct Errno {
char name[16];
unsigned char number;
} kErrnos[] = {
{"E2BIG", 7}, //
{"EACCES", 13}, //
{"EADDRINUSE", 98}, //
{"EADDRNOTAVAIL", 99}, //
{"EADV", 68}, //
{"EAFNOSUPPORT", 97}, //
{"EAGAIN", 11}, //
{"EALREADY", 114}, //
{"EBADE", 52}, //
{"EBADF", 9}, //
{"EBADFD", 77}, //
{"EBADMSG", 74}, //
{"EBADR", 53}, //
{"EBADRQC", 56}, //
{"EBADSLT", 57}, //
{"EBFONT", 59}, //
{"EBUSY", 16}, //
{"ECANCELED", 125}, //
{"ECHILD", 10}, //
{"ECHRNG", 44}, //
{"ECOMM", 70}, //
{"ECONNABORTED", 103}, //
{"ECONNREFUSED", 111}, //
{"ECONNRESET", 104}, //
{"EDEADLK", 35}, //
{"EDESTADDRREQ", 89}, //
{"EDOM", 33}, //
{"EDOTDOT", 73}, //
{"EDQUOT", 122}, //
{"EEXIST", 17}, //
{"EFAULT", 14}, //
{"EFBIG", 27}, //
{"EHOSTDOWN", 112}, //
{"EHOSTUNREACH", 113}, //
{"EHWPOISON", 133}, //
{"EIDRM", 43}, //
{"EILSEQ", 84}, //
{"EINPROGRESS", 115}, //
{"EINTR", 4}, //
{"EINVAL", 22}, //
{"EIO", 5}, //
{"EISCONN", 106}, //
{"EISDIR", 21}, //
{"EISNAM", 120}, //
{"EKEYEXPIRED", 127}, //
{"EKEYREJECTED", 129}, //
{"EKEYREVOKED", 128}, //
{"EL2HLT", 51}, //
{"EL2NSYNC", 45}, //
{"EL3HLT", 46}, //
{"EL3RST", 47}, //
{"ELIBACC", 79}, //
{"ELIBBAD", 80}, //
{"ELIBEXEC", 83}, //
{"ELIBMAX", 82}, //
{"ELIBSCN", 81}, //
{"ELNRNG", 48}, //
{"ELOOP", 40}, //
{"EMEDIUMTYPE", 124}, //
{"EMFILE", 24}, //
{"EMLINK", 31}, //
{"EMSGSIZE", 90}, //
{"EMULTIHOP", 72}, //
{"ENAMETOOLONG", 36}, //
{"ENAVAIL", 119}, //
{"ENETDOWN", 100}, //
{"ENETRESET", 102}, //
{"ENETUNREACH", 101}, //
{"ENFILE", 23}, //
{"ENOANO", 55}, //
{"ENOBUFS", 105}, //
{"ENOCSI", 50}, //
{"ENODATA", 61}, //
{"ENODEV", 19}, //
{"ENOENT", 2}, //
{"ENOEXEC", 8}, //
{"ENOKEY", 126}, //
{"ENOLCK", 37}, //
{"ENOLINK", 67}, //
{"ENOMEDIUM", 123}, //
{"ENOMEM", 12}, //
{"ENOMSG", 42}, //
{"ENONET", 64}, //
{"ENOPKG", 65}, //
{"ENOPROTOOPT", 92}, //
{"ENOSPC", 28}, //
{"ENOSR", 63}, //
{"ENOSTR", 60}, //
{"ENOSYS", 38}, //
{"ENOTBLK", 15}, //
{"ENOTCONN", 107}, //
{"ENOTDIR", 20}, //
{"ENOTEMPTY", 39}, //
{"ENOTNAM", 118}, //
{"ENOTRECOVERABLE", 131}, //
{"ENOTSOCK", 88}, //
{"ENOTSUP", 95}, //
{"ENOTTY", 25}, //
{"ENOTUNIQ", 76}, //
{"ENXIO", 6}, //
{"EOPNOTSUPP", 95}, //
{"EOVERFLOW", 75}, //
{"EOWNERDEAD", 130}, //
{"EPERM", 1}, //
{"EPFNOSUPPORT", 96}, //
{"EPIPE", 32}, //
{"EPROTO", 71}, //
{"EPROTONOSUPPORT", 93}, //
{"EPROTOTYPE", 91}, //
{"ERANGE", 34}, //
{"EREMCHG", 78}, //
{"EREMOTE", 66}, //
{"EREMOTEIO", 121}, //
{"ERESTART", 85}, //
{"ERFKILL", 132}, //
{"EROFS", 30}, //
{"ESHUTDOWN", 108}, //
{"ESOCKTNOSUPPORT", 94}, //
{"ESPIPE", 29}, //
{"ESRCH", 3}, //
{"ESRMNT", 69}, //
{"ESTALE", 116}, //
{"ESTRPIPE", 86}, //
{"ETIME", 62}, //
{"ETIMEDOUT", 110}, //
{"ETOOMANYREFS", 109}, //
{"ETXTBSY", 26}, //
{"EUCLEAN", 117}, //
{"EUNATCH", 49}, //
{"EUSERS", 87}, //
{"EWOULDBLOCK", 11}, //
{"EXDEV", 18}, //
{"EXFULL", 54}, //
};
static char **strace_args;
static size_t strace_args_len;
static volatile bool interrupted;
static long Hash(const void *p, size_t n) {
unsigned h, i;
for (h = i = 0; i < n; i++) {
h += ((unsigned char *)p)[i];
h *= 0x9e3779b1;
}
return MAX(1, h);
}
static uint64_t MakeKey64(const char *p, size_t n) {
char k[8] = {0};
memcpy(k, p, n);
return READ64BE(k);
}
static uint128_t MakeKey128(const char *p, size_t n) {
char k[16] = {0};
memcpy(k, p, n);
return READ128BE(k);
}
static int GetSyscall(const char *name, size_t namelen) {
int m, l, r;
uint128_t x, y;
char *endofname;
if (namelen && namelen <= 16) {
x = MakeKey128(name, namelen);
l = 0;
r = ARRAYLEN(kSyscalls) - 1;
while (l <= r) {
m = (l + r) >> 1;
y = READ128BE(kSyscalls[m].name);
if (x < y) {
r = m - 1;
} else if (x > y) {
l = m + 1;
} else {
return m;
}
}
}
return -1;
}
static int GetErrno(const char *name, size_t namelen) {
int m, l, r;
uint128_t x, y;
char *endofname;
if (namelen && namelen <= 16) {
x = MakeKey128(name, namelen);
l = 0;
r = ARRAYLEN(kErrnos) - 1;
while (l <= r) {
m = (l + r) >> 1;
y = READ128BE(kErrnos[m].name);
if (x < y) {
r = m - 1;
} else if (x > y) {
l = m + 1;
} else {
return kErrnos[m].number;
}
}
}
return -1;
}
static int GetSignal(const char *name, size_t namelen) {
int m, l, r;
uint64_t x, y;
char *endofname;
if (namelen && namelen <= 8) {
x = MakeKey64(name, namelen);
l = 0;
r = ARRAYLEN(kSignals) - 1;
while (l <= r) {
m = (l + r) >> 1;
y = READ64BE(kSignals[m].name);
if (x < y) {
r = m - 1;
} else if (x > y) {
l = m + 1;
} else {
return kSignals[m].number;
}
}
}
return -1;
}
static struct Trace *NewTrace(void) {
return calloc(1, sizeof(struct Trace));
}
static void FreeTrace(struct Trace *t) {
long i;
if (t) {
for (i = 0; i < t->slices.n; ++i) {
free(t->slices.p[i].p);
}
free(t->slices.p);
free(t->sliceindex.p);
for (i = 0; i < t->strlists.n; ++i) {
free(t->strlists.p[i].p);
}
free(t->strlists.p);
free(t->events.p);
free(t);
}
}
static void AppendStrlists(struct Trace *t) {
APPEND(t->strlists);
}
static void AppendStrlist(struct Strlist *l) {
APPEND((*l));
}
static void AppendEvent(struct Trace *t) {
APPEND(t->events);
}
static void AppendSlices(struct Trace *t) {
APPEND(t->slices);
}
static void AppendSlice(struct Slice *s, int c) {
APPEND((*s));
s->p[s->n - 1] = c;
}
static long Intern(struct Trace *t, char *data, long size) {
struct HashEntry *p;
long i, j, k, n, m, h, n2;
h = Hash(data, size);
n = t->sliceindex.n;
i = 0;
if (n) {
k = 0;
do {
i = (h + k + ((k + 1) >> 1)) & (n - 1);
if (t->sliceindex.p[i].h == h &&
t->slices.p[t->sliceindex.p[i].i].n == size &&
!memcmp(t->slices.p[t->sliceindex.p[i].i].p, data, size)) {
free(data);
return t->sliceindex.p[i].i;
}
++k;
} while (t->sliceindex.p[i].h);
}
if (++t->sliceindex.i >= (n >> 1)) {
m = n ? n << 1 : 16;
p = calloc(m, sizeof(struct HashEntry));
for (j = 0; j < n; ++j) {
if (t->sliceindex.p[j].h) {
k = 0;
do {
i = (t->sliceindex.p[j].h + k + ((k + 1) >> 1)) & (m - 1);
++k;
} while (p[i].h);
p[i].h = t->sliceindex.p[j].h;
p[i].i = t->sliceindex.p[j].i;
}
}
k = 0;
do {
i = (h + k + ((k + 1) >> 1)) & (m - 1);
++k;
} while (p[i].h);
free(t->sliceindex.p);
t->sliceindex.p = p;
t->sliceindex.n = m;
}
AppendSlices(t);
t->slices.p[t->slices.n - 1].p = data;
t->slices.p[t->slices.n - 1].n = size;
t->sliceindex.p[i].i = t->slices.n - 1;
t->sliceindex.p[i].h = h;
return t->slices.n - 1;
}
static long ReadCharLiteral(struct Slice *buf, long c, char *p, long *i) {
if (c != '\\') return c;
switch ((c = p[(*i)++])) {
case 'a':
return '\a';
case 'b':
return '\b';
case 't':
return '\t';
case 'n':
return '\n';
case 'v':
return '\v';
case 'f':
return '\f';
case 'r':
return '\r';
case 'e':
return 033;
case 'x':
if (isxdigit(p[*i])) {
c = hextoint(p[(*i)++]);
if (isxdigit(p[*i])) {
c = c * 16 + hextoint(p[(*i)++]);
}
}
return c;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
c -= '0';
if ('0' <= p[*i] && p[*i] <= '7') {
c = c * 8 + (p[(*i)++] - '0');
if ('0' <= p[*i] && p[*i] <= '7') {
c = c * 8 + (p[(*i)++] - '0');
}
}
return c;
default:
return c;
}
}
static long GetDuration(long sec1, long us1, long sec2, long us2) {
long elap;
if ((elap = (sec2 - sec1) * 1000000)) {
return elap + 1000000 - us1 + us2;
} else {
return elap + us2 - us1;
}
}
static void Parse(struct Trace *t, const char *line, long lineno) {
char *p, *q;
struct Slice b;
long c, i, j, k, arg, pid, event, sec, us;
p = line;
pid = strtol(p, &p, 10);
while (*p == ' ') ++p;
sec = strtol(p, &p, 10);
CHECK_EQ('.', *p++, DEBUG);
us = strtol(p, &p, 10);
CHECK_EQ(' ', *p++, DEBUG);
if (_startswith(p, "<... ")) {
CHECK_NOTNULL((p = strchr(p, '>')));
++p;
for (event = t->events.n; event--;) {
if (t->events.p[event].pid == pid) {
CHECK(t->events.p[event].is_interrupted, DEBUG);
t->events.p[event].is_interrupted = false;
t->events.p[event].elap =
GetDuration(t->events.p[event].sec, t->events.p[event].us, sec, us);
break;
}
}
CHECK_GE(event, 0);
} else {
AppendEvent(t);
event = t->events.n - 1;
t->events.p[event].pid = pid;
t->events.p[event].sec = sec;
t->events.p[event].us = us;
t->events.p[event].lineno = lineno;
if (_startswith(p, "+++ exited with ")) {
p += strlen("+++ exited with ");
t->events.p[event].kind = EK_EXIT;
t->events.p[event].ret = atoi(p);
return;
} else if (_startswith(p, "+++ killed by ")) {
p += strlen("+++ killed by ");
CHECK((q = strchr(p, ' ')), DEBUG);
t->events.p[event].kind = EK_KILLED;
t->events.p[event].ret = GetSignal(p, q - p);
return;
} else if (_startswith(p, "--- ")) {
p += 4;
CHECK(isalpha(*p), DEBUG);
CHECK((q = strchr(p, ' ')), DEBUG);
t->events.p[event].kind = EK_SIGNAL;
t->events.p[event].ret = GetSignal(p, q - p);
return;
} else if (isalpha(*p) && (q = strchr(p, '('))) {
t->events.p[event].kind = EK_CALL;
CHECK_NE(-1, (t->events.p[event].syscall_ = GetSyscall(p, q - p)), DEBUG);
p = q + 1;
}
}
for (;;) {
if (*p == ',') ++p;
while (*p == ' ') ++p;
CHECK(*p, DEBUG);
if (_startswith(p, "<unfinished ...>")) {
t->events.p[event].is_interrupted = true;
break;
} else if (*p == ')') {
++p;
while (isspace(*p)) ++p;
CHECK_EQ('=', *p++, DEBUG);
while (isspace(*p)) ++p;
CHECK(isdigit(*p) || *p == '-', DEBUG);
t->events.p[event].ret = strtol(p, &p, 0);
if (t->events.p[event].ret == -1) {
while (isspace(*p)) ++p;
CHECK((q = strchr(p, ' ')), DEBUG);
if ((t->events.p[event].ret = GetErrno(p, q - p)) != -1) {
t->events.p[event].ret = -t->events.p[event].ret;
}
}
break;
}
CHECK_LT((arg = t->events.p[event].arity++), 6);
if (isalpha(*p) && !_startswith(p, "NULL")) {
bzero(&b, sizeof(b));
for (; isalpha(*p) || *p == '_'; ++p) {
AppendSlice(&b, *p);
}
t->events.p[event].arg[arg].name = Intern(t, b.p, b.n);
CHECK_EQ('=', *p++, DEBUG);
} else {
t->events.p[event].arg[arg].name = -1;
}
if (_startswith(p, "NULL")) {
p += 4;
t->events.p[event].arg[arg].kind = AK_LONG;
t->events.p[event].arg[arg].x = 0;
} else if (*p == '-' || isdigit(*p)) {
t->events.p[event].arg[arg].kind = AK_LONG;
for (;;) {
t->events.p[event].arg[arg].x |= strtol(p, &p, 0);
if (*p == '|') {
++p;
} else {
break;
}
}
} else if (*p == '{') {
CHECK_NOTNULL((p = strchr(p, '}')), DEBUG);
++p;
} else if (*p == '"') {
bzero(&b, sizeof(b));
for (j = 0; (c = p[++j]);) {
if (c == '"') {
p += j + 1;
break;
}
c = ReadCharLiteral(&b, c, p, &j);
AppendSlice(&b, c);
}
t->events.p[event].arg[arg].kind = AK_STR;
t->events.p[event].arg[arg].x = Intern(t, b.p, b.n);
} else if (*p == '[') {
++p;
if (isdigit(*p)) {
t->events.p[event].arg[arg].kind = AK_INTPAIR;
t->events.p[event].arg[arg].x = strtol(p, &p, 0) & 0xffffffff;
CHECK_EQ(',', *p++, DEBUG);
CHECK_EQ(' ', *p++, DEBUG);
t->events.p[event].arg[arg].x |= strtol(p, &p, 0) << 32;
CHECK_EQ(']', *p++, DEBUG);
} else {
AppendStrlists(t);
for (j = 0;; ++j) {
if (*p == ']') {
++p;
break;
}
if (*p == ',') ++p;
if (*p == ' ') ++p;
CHECK_EQ('"', *p, DEBUG);
bzero(&b, sizeof(b));
for (k = 0; (c = p[++k]);) {
if (c == '"') {
p += k + 1;
break;
}
c = ReadCharLiteral(&b, c, p, &k);
AppendSlice(&b, c);
}
AppendStrlist(&t->strlists.p[t->strlists.n - 1]);
t->strlists.p[t->strlists.n - 1]
.p[t->strlists.p[t->strlists.n - 1].n - 1] = Intern(t, b.p, b.n);
}
t->events.p[event].arg[arg].kind = AK_STRLIST;
t->events.p[event].arg[arg].x = t->strlists.n - 1;
}
} else {
CHECK(false, DEBUG);
}
}
}
static void PrintArg(FILE *f, struct Trace *t, long ev, long arg) {
long i, x;
x = t->events.p[ev].arg[arg].name;
if (x != -1) {
fprintf(f, "b%`'.*s:", t->slices.p[x].n, t->slices.p[x].p);
}
x = t->events.p[ev].arg[arg].x;
switch (t->events.p[ev].arg[arg].kind) {
case AK_LONG:
fprintf(f, "%ld", x);
break;
case AK_STR:
fprintf(f, "b%`'.*s", t->slices.p[x].n, t->slices.p[x].p);
break;
case AK_INTPAIR:
fprintf(f, "(%d,%d)", x >> 32, x);
break;
case AK_STRLIST:
fprintf(f, "(");
for (i = 0; i < t->strlists.p[x].n; ++i) {
fprintf(f, "b%`'.*s,", t->slices.p[t->strlists.p[x].p[i]].n,
t->slices.p[t->strlists.p[x].p[i]].p);
}
fprintf(f, ")");
break;
default:
abort();
}
}
static void PrintEvent(FILE *f, struct Trace *t, long ev) {
long arg;
fprintf(f, "(%d,%ld,%d,%d,", t->events.p[ev].pid,
t->events.p[ev].sec * 1000000 + t->events.p[ev].us,
t->events.p[ev].elap, t->events.p[ev].kind);
switch (t->events.p[ev].kind) {
case EK_EXIT:
case EK_SIGNAL:
case EK_KILLED:
fprintf(f, "%d", t->events.p[ev].ret);
break;
case EK_CALL:
CHECK_LT(t->events.p[ev].syscall_, ARRAYLEN(kSyscalls));
fprintf(f, "(b%`'s,%ld,", kSyscalls[t->events.p[ev].syscall_].name,
t->events.p[ev].ret);
fprintf(f, "%c",
t->events.p[ev].arity && t->events.p[ev].arg[0].name != -1 ? '{'
: '(');
for (arg = 0; arg < t->events.p[ev].arity; ++arg) {
PrintArg(f, t, ev, arg);
fprintf(f, ",");
}
fprintf(f, "%c)",
t->events.p[ev].arity && t->events.p[ev].arg[0].name != -1 ? '}'
: ')');
break;
default:
break;
}
fprintf(f, ")");
}
static void AppendArg(char *arg) {
strace_args = realloc(strace_args, ++strace_args_len * sizeof(*strace_args));
strace_args[strace_args_len - 1] = arg;
}
static wontreturn void PrintUsage(FILE *f, int rc) {
fprintf(f, "Usage: %s [-o OUT] PROG [ARGS...]\n", program_invocation_name);
exit(rc);
}
int main(int argc, char *argv[]) {
int i;
int ws;
int opt;
int pid;
long ev;
FILE *fin;
FILE *fout;
char *line;
long lineno;
char *strace;
int pipefds[2];
struct Trace *t;
sigset_t block, mask;
struct sigaction ignore, saveint, savequit;
/*
* parse prefix arguments
*/
fout = stderr;
while ((opt = getopt(argc, argv, "?ho:")) != -1) {
switch (opt) {
case 'o':
fout = fopen(optarg, "w");
break;
case 'h':
case '?':
PrintUsage(stdout, EXIT_SUCCESS);
default:
PrintUsage(stderr, EX_USAGE);
}
}
if (optind == argc) {
PrintUsage(stderr, EX_USAGE);
}
/*
* resolve full paths of dependencies
*/
if ((strace = commandvenv("STRACE", "strace"))) {
strace = strdup(strace);
} else {
fprintf(stderr, "error: please install strace\n");
exit(1);
}
/*
* create strace argument list
*/
AppendArg("strace");
AppendArg("-q"); // don't log attach/detach noise
AppendArg("-v"); // don't abbreviate arrays
AppendArg("-f"); // follow subprocesses
AppendArg("-ttt"); // print unixseconds.micros
AppendArg("-X"); // print numbers instead of symbols
AppendArg("raw"); // e.g. 2 vs. O_RDWR
AppendArg("-s"); // don't abbreviate data
AppendArg("805306368"); // strace won't let us go higher
AppendArg("-e"); // system calls that matter
AppendArg(
"open,close,access,pipe,dup,dup2,socket,connect,accept,bind,listen,"
"socketpair,fork,vfork,execve,clone,flock,fsync,fdatasync,truncate,chdir,"
"rename,mkdir,rmdir,creat,link,unlink,symlink,readlink,chmod,chown,fcntl,"
"lchown,mknod,mknodat,statfs,chroot,sync,epoll_create,openat,mkdirat,"
"fchownat,unlinkat,renameat,linkat,symlinkat,readlinkat,fchmodat,fchdir,"
"faccessat,utimensat,accept4,dup3,pipe2,epoll_create1,signalfd,signalfd4,"
"eventfd,eventfd2,timerfd_create,syncfs,renameat2,memfd_create,execveat");
CHECK_NE(-1, pipe(pipefds));
AppendArg("-o");
AppendArg(xasprintf("/dev/fd/%d", pipefds[1]));
for (i = optind; i < argc; ++i) {
AppendArg(argv[i]);
}
AppendArg(NULL);
/*
* spawn strace
*/
ignore.sa_flags = 0;
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
sigaction(SIGINT, &ignore, &saveint);
sigaction(SIGQUIT, &ignore, &savequit);
sigfillset(&block);
sigprocmask(SIG_BLOCK, &block, &mask);
CHECK_NE(-1, (pid = vfork()));
if (!pid) {
close(pipefds[0]);
sigaction(SIGINT, &saveint, NULL);
sigaction(SIGQUIT, &savequit, NULL);
sigprocmask(SIG_SETMASK, &mask, NULL);
execv(strace, strace_args);
_exit(127);
}
close(pipefds[1]);
sigaddset(&mask, SIGCHLD);
sigprocmask(SIG_SETMASK, &mask, NULL);
/*
* read output of strace until eof
*/
fin = fdopen(pipefds[0], "r");
t = NewTrace();
for (ev = 0, lineno = 1; !interrupted && (line = xgetline(fin)); ++lineno) {
_chomp(line);
Parse(t, line, lineno);
free(line);
for (; ev < t->events.n && !t->events.p[ev].is_interrupted; ++ev) {
PrintEvent(fout, t, ev);
fprintf(fout, "\n");
}
}
FreeTrace(t);
CHECK_NE(-1, fclose(fout));
/*
* wait for strace to exit
*/
while (waitpid(pid, &ws, 0) == -1) {
CHECK_EQ(EINTR, errno);
}
CHECK_NE(-1, fclose(fin));
/*
* propagate exit
*/
if (WIFEXITED(ws)) {
return WEXITSTATUS(ws);
} else {
return 128 + WTERMSIG(ws);
}
}
| 28,481 | 991 | jart/cosmopolitan | false |
cosmopolitan/tool/build/pwd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/stdio/stdio.h"
/**
* @fileoverview Tool for printing current directory.
*/
char path[PATH_MAX];
int main(int argc, char *argv[]) {
char *p;
if ((p = getcwd(path, sizeof(path)))) {
fputs(p, stdout);
fputc('\n', stdout);
return 0;
} else {
return 1;
}
}
| 2,162 | 38 | jart/cosmopolitan | false |
cosmopolitan/tool/build/dd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/limits.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
char buf[65536];
wontreturn void SysFail(const char *func, const char *file) {
int e = errno;
fputs("dd: ", stderr);
fputs(func, stderr);
fputs(" failed: ", stderr);
fputs(file, stderr);
fputs(": ", stderr);
fputs(nulltoempty(_strerdoc(e)), stderr);
fputs("\n", stderr);
exit(__COUNTER__ + 1);
}
int main(int argc, char *argv[]) {
long i;
char *p;
long skip = 0;
long count = LONG_MAX;
long blocksize = 1;
int oflags = O_WRONLY | O_TRUNC | O_CREAT;
const char *infile = "/dev/stdin";
const char *oufile = "/dev/stdout";
for (i = 1; i < argc; ++i) {
if (argv[i][0] == 'b' && //
argv[i][1] == 's' && //
argv[i][2] == '=') {
blocksize = strtol(argv[i] + 3 + (argv[i][3] == '"'), 0, 10);
if (!(0 < blocksize && blocksize <= sizeof(buf))) {
fputs("dd: bad block size\n", stderr);
return __COUNTER__ + 1;
}
} else if (argv[i][0] == 'i' && //
argv[i][1] == 'f' && //
argv[i][2] == '=') {
infile = argv[i] + 3 + (argv[i][3] == '"');
p = strchr(infile, '"');
if (p) *p = 0;
} else if (argv[i][0] == 'o' && //
argv[i][1] == 'f' && //
argv[i][2] == '=') {
oufile = argv[i] + 3 + (argv[i][3] == '"');
p = strchr(infile, '"');
if (p) *p = 0;
} else if (argv[i][0] == 's' && //
argv[i][1] == 'k' && //
argv[i][2] == 'i' && //
argv[i][3] == 'p' && //
argv[i][4] == '=') {
count = strtol(argv[i] + 5 + (argv[i][5] == '"'), 0, 10);
if (!(skip < 0)) {
fputs("dd: bad skip\n", stderr);
return __COUNTER__ + 1;
}
} else if (argv[i][0] == 'c' && //
argv[i][1] == 'o' && //
argv[i][2] == 'u' && //
argv[i][3] == 'n' && //
argv[i][4] == 't' && //
argv[i][5] == '=') {
count = strtol(argv[i] + 6 + (argv[i][6] == '"'), 0, 10);
if (!(count < 0)) {
fputs("dd: bad count\n", stderr);
return __COUNTER__ + 1;
}
} else if (!strcmp(argv[i], "conv=notrunc")) {
oflags &= ~O_TRUNC;
} else {
fputs("dd: unrecognized arg: ", stderr);
fputs(argv[i], stderr);
fputs("\n", stderr);
return __COUNTER__ + 1;
}
}
ssize_t rc;
int fdin, fdout;
if ((fdin = open(infile, O_RDONLY)) == -1) {
SysFail("open", infile);
}
if ((fdout = open(oufile, oflags, 0644)) == -1) {
SysFail("open", oufile);
}
if (skip) {
if (lseek(fdin, skip, SEEK_SET) == -1) {
SysFail("lseek", infile);
}
}
for (i = 0; i < count; ++i) {
rc = read(fdin, buf, blocksize);
if (rc == -1) {
SysFail("read", infile);
}
if (rc != blocksize) {
int e = errno;
fputs("dd: failed to read blocksize: ", stderr);
fputs(infile, stderr);
fputs("\n", stderr);
return __COUNTER__ + 1;
}
rc = write(fdout, buf, blocksize);
if (rc == -1) {
SysFail("write", oufile);
}
if (rc != blocksize) {
int e = errno;
fputs("dd: failed to write blocksize: ", stderr);
fputs(infile, stderr);
fputs("\n", stderr);
return __COUNTER__ + 1;
}
}
if (close(fdin) == -1) SysFail("close", infile);
if (close(fdout) == -1) SysFail("close", oufile);
return 0;
}
| 5,500 | 161 | jart/cosmopolitan | false |
cosmopolitan/tool/build/x86combos.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/log/check.h"
#include "libc/macros.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "third_party/xed/x86.h"
const char kPrefixes[][8] = {
{},
{0x66},
{0x67},
{0x40},
{0x6F},
{0x66, 0x6F},
{0x66, 0x40},
{0x66, 0x6F},
{0x67, 0x40},
{0x67, 0x6F},
{0x66, 0x67},
{0x66, 0x67, 0x40},
{0x66, 0x67, 0x6F},
{0x0F},
{0x0F, 0x66},
{0x0F, 0x67},
{0x0F, 0x40},
{0x0F, 0x6F},
{0x0F, 0x66, 0x6F},
{0x0F, 0x66, 0x40},
{0x0F, 0x66, 0x6F},
{0x0F, 0x67, 0x40},
{0x0F, 0x67, 0x6F},
{0x0F, 0x66, 0x67},
{0x0F, 0x66, 0x67, 0x40},
{0x0F, 0x66, 0x67, 0x6F},
{0xF3, 0x0F},
{0xF3, 0x66, 0x0F},
{0xF3, 0x67, 0x0F},
{0xF3, 0x40, 0x0F},
{0xF3, 0x6F, 0x0F},
{0xF3, 0x66, 0x6F, 0x0F},
{0xF3, 0x66, 0x40, 0x0F},
{0xF3, 0x66, 0x6F, 0x0F},
{0xF3, 0x67, 0x40, 0x0F},
{0xF3, 0x67, 0x6F, 0x0F},
{0xF3, 0x66, 0x67, 0x0F},
{0xF3, 0x66, 0x67, 0x40, 0x0F},
{0xF3, 0x66, 0x67, 0x6F, 0x0F},
{0xF2, 0x0F},
{0xF2, 0x66, 0x0F},
{0xF2, 0x67, 0x0F},
{0xF2, 0x40, 0x0F},
{0xF2, 0x6F, 0x0F},
{0xF2, 0x66, 0x6F, 0x0F},
{0xF2, 0x66, 0x40, 0x0F},
{0xF2, 0x66, 0x6F, 0x0F},
{0xF2, 0x67, 0x40, 0x0F},
{0xF2, 0x67, 0x6F, 0x0F},
{0xF2, 0x66, 0x67, 0x0F},
{0xF2, 0x66, 0x67, 0x40, 0x0F},
{0xF2, 0x66, 0x67, 0x6F, 0x0F},
};
const uint8_t kModrmPicks[] = {
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x0, 0x8, 0x10,
0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
0x46, 0x47, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78, 0x80,
0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x80, 0x88, 0x90, 0x98,
0xa0, 0xa8, 0xb0, 0xb8, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
0xc7, 0xc0, 0xc8, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8,
};
const uint8_t kOpMap0[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255,
};
void WriteOp(int fd, struct XedDecodedInst *xedd) {
int i;
char buf[128], *p;
p = stpcpy(buf, ".byte ");
for (i = 0; i < xedd->length; ++i) {
if (i) *p++ = ',';
*p++ = '0';
*p++ = 'x';
*p++ = "0123456789abcdef"[(xedd->bytes[i] & 0xf0) >> 4];
*p++ = "0123456789abcdef"[xedd->bytes[i] & 0x0f];
}
*p++ = '\n';
CHECK_NE(-1, write(fd, buf, p - buf));
}
int main(int argc, char *argv[]) {
int i, j, k, l, m, n, p, o, fd;
uint8_t op[16];
struct XedDecodedInst xedd[1];
fd = open("/tmp/ops.s", O_CREAT | O_TRUNC | O_RDWR, 0644);
for (o = 0; o < ARRAYLEN(kOpMap0); ++o) {
for (p = 0; p < ARRAYLEN(kPrefixes); ++p) {
memset(op, 0x55, 16);
n = strlen(kPrefixes[p]);
memcpy(op, kPrefixes[p], n);
op[n] = kOpMap0[o];
xed_decoded_inst_zero_set_mode(xedd, XED_MACHINE_MODE_LONG_64);
if (!xed_instruction_length_decode(xedd, op, XED_MAX_INSTRUCTION_BYTES)) {
if (xedd->op.has_modrm && xedd->op.has_sib) {
for (i = 0; i < ARRAYLEN(kModrmPicks); ++i) {
for (j = 0; j < ARRAYLEN(kModrmPicks); ++j) {
memset(op, 0x55, 16);
n = strlen(kPrefixes[p]);
memcpy(op, kPrefixes[p], n);
op[n] = kOpMap0[o];
op[xedd->op.pos_modrm] = kModrmPicks[i];
op[xedd->op.pos_sib] = kModrmPicks[j];
xed_decoded_inst_zero_set_mode(xedd, XED_MACHINE_MODE_LONG_64);
if (!xed_instruction_length_decode(xedd, op,
XED_MAX_INSTRUCTION_BYTES)) {
WriteOp(fd, xedd);
}
}
}
} else if (xedd->op.has_modrm) {
for (i = 0; i < ARRAYLEN(kModrmPicks); ++i) {
memset(op, 0x55, 16);
n = strlen(kPrefixes[p]);
memcpy(op, kPrefixes[p], n);
op[n] = kOpMap0[o];
op[xedd->op.pos_modrm] = kModrmPicks[i];
xed_decoded_inst_zero_set_mode(xedd, XED_MACHINE_MODE_LONG_64);
if (!xed_instruction_length_decode(xedd, op,
XED_MAX_INSTRUCTION_BYTES)) {
WriteOp(fd, xedd);
}
}
} else {
WriteOp(fd, xedd);
}
}
}
}
close(fd);
system("as -o /tmp/ops.o /tmp/ops.s");
system("objdump -wd /tmp/ops.o |"
" grep -v data16 |"
" grep -v addr32 |"
" grep -v '(bad)' |"
" sed 's/^[ :[:xdigit:]]*//' |"
" sed 's/^[ :[:xdigit:]]*//' |"
" sed 's/[[:space:]]#.*$//' |"
" grep -v 'rex\\.' |"
" sort -u");
return 0;
}
| 7,797 | 192 | jart/cosmopolitan | false |
cosmopolitan/tool/build/calculator.inc | M(2, g, "+", Add, x + y, "add")
M(2, g, "-", Sub, x - y, "sub")
M(2, g, "*", Mul, x *y, "multiply")
M(2, f, "/", Div, x / y, "division")
M(2, i, "%", Rem, x % y, "integer remainder")
M(2, i, "//", Idiv, x / y, "integer division")
M(2, g, "**", Expo, powl(x, y), "exponentiation")
M(1, i, "~", Not, ~x, "bitwise not")
M(2, i, "^", Xor, x ^ y, "bitwise xor")
M(2, i, "|", Or, x | y, "bitwise or")
M(2, i, "&", And, x &y, "bitwise and")
M(2, i, ">>", Shr, x >> y, "shift right")
M(2, i, "<<", Shl, x << y, "shift left")
M(1, i, "!", LogicalNot, !x, "logical not")
M(2, i, "||", LogicalOr, x || y, "logical or")
M(2, i, "&&", LogicalAnd, x &&y, "logical and")
M(2, g, "=", Equal1, x == y, "equal to")
M(2, g, "!=", Notequal, x != y, "not equal to")
M(2, g, "<", LessThan, x < y, "less than")
M(2, g, ">", GreaterThan, x > y, "greater than")
M(2, g, "<=", LessThanEqual, x <= y, "less than or equal to")
M(2, g, ">=", GreaterThanEqual, x >= y, "greater than or equal to")
M(1, i, "gray", Gray, gray(x), "gray coding")
M(1, i, "ungray", Ungray, ungray(x), "inverse gray coding")
M(1, i, "popcnt", Popcnt, Popcnt(x), "count bits")
M(1, g, "abs", Abs, fabsl(x), "absolute value")
M(2, g, "min", Min, fminl(x, y), "pops two values and pushes minimum")
M(2, g, "max", Max, fmaxl(x, y), "pops two values and pushes maximum")
M(2, g, "fmod", Fmod, fmodl(x, y), "trunc remainder")
M(2, g, "emod", Emod, emodl(x, y), "euclidean remainder")
M(2, g, "remainder", Remainder, remainderl(x, y), "rint remainder")
M(2, g, "hypot", Hypot, hypotl(x, y), "euclidean distance")
M(0, i, "false", False, 0, "0")
M(0, i, "true", True, 1, "1")
M(0, i, "intmin", IntMin, INT128_MIN, "native integer minimum")
M(0, i, "intmax", IntMax, INT128_MAX, "native integer maximum")
M(0, f, "e", Euler, M_E, "ð")
M(0, f, "pi", Fldpi, M_PI, "Ï")
M(0, f, "epsilon", Epsilon, EPSILON, "É")
M(0, f, "inf", Inf, INFINITY, "â")
M(0, f, "nan", Nan, NAN, "NAN")
M(0, f, "-0", Negzero, -0., "wut")
M(0, f, "l2t", Fldl2t, M_LOG2_10, "logâ10")
M(0, f, "lg2", Fldlg2, M_LOG10_2, "logââ2")
M(0, f, "ln2", Fldln2, M_LN2, "logâ2")
M(0, f, "l2e", Fldl2e, M_LOG2E, "logâ10")
M(2, f, "nextafter", Nextafter, nextafterl(x, y), "next ulp")
M(1, f, "significand", Significand, significandl(x), "mantissa")
M(1, f, "sqrt", Sqrt, sqrtl(x), "âð¥")
M(1, f, "exp", Exp, expl(x), "ðË£")
M(1, g, "expm1", Expm1, expm1l(x), "ðË£-1")
M(1, g, "exp2", Exp2, exp2l(x), "2Ë£")
M(1, g, "exp10", Exp10, exp10l(x), "10Ë£")
M(2, g, "ldexp", Ldexp, ldexpl(x, y), "ð¥Ã2ʸ")
M(1, f, "log", Log, logl(x), "logâð¥")
M(1, g, "log2", Log2, log2l(x), "logâð¥")
M(1, g, "log10", Log10, log10l(x), "logââð¥")
M(1, g, "ilogb", Ilogb, ilogbl(x), "exponent")
M(1, g, "sin", Sin, sinl(x), "sine")
M(1, g, "cos", Cos, cosl(x), "cosine")
M(1, g, "tan", Tan, tanl(x), "tangent")
M(1, g, "asin", Asin, asinl(x), "arcsine")
M(1, g, "acos", Acos, acosl(x), "arccosine")
M(1, g, "atan", Atan, atanl(x), "arctangent")
M(2, g, "atan2", Atan2, atan2l(x, y), "arctangent of ð¥/ð¦")
M(1, g, "sinh", Sinh, sinhl(x), "hyperbolic sine")
M(1, g, "cosh", Cosh, coshl(x), "hyperbolic cosine")
M(1, g, "tanh", Tanh, tanhl(x), "hyperbolic tangent")
M(1, g, "asinh", Asinh, asinhl(x), "hyperbolic arcsine")
M(1, g, "acosh", Acosh, acoshl(x), "hyperbolic arccosine")
M(1, g, "atanh", Atanh, atanhl(x), "hyperbolic arctangent")
M(1, g, "round", Round, roundl(x), "round away from zero")
M(1, g, "trunc", Trunc, truncl(x), "round towards zero")
M(1, g, "rint", Rint, rintl(x), "round to even")
M(1, g, "nearbyint", Nearbyint, nearbyintl(x), "round to nearest integer")
M(1, g, "ceil", Ceil, ceill(x), "smallest integral not less than ð¥")
M(1, g, "floor", Floor, floorl(x), "largest integral not greater than ð¥")
M(1, f, "isnan", Isnan, isnan(x), "returns true if ð¥=NAN")
M(1, f, "isinf", Isinf, isinf(x), "returns true if ð¥=INFINITY")
M(1, f, "signbit", Signbit, signbit(x), "clears all bits but sign bit")
M(1, f, "isfinite", Isfinite, isfinite(x), "returns true if ð¥â INFINITY")
M(1, f, "isnormal", Isnormal, isnormal(x), "returns true if not denormal")
M(1, f, "fpclassify", Fpclassify, fpclassify(x),
"nan=0,inf=1,zero=2,subnorm=3,normal=4")
M(0, i, "rand", Rand, rand(), "deterministic random number")
M(0, i, "rand64", _Rand64, _rand64(), "64-bit random number")
| 4,334 | 101 | jart/cosmopolitan | false |
cosmopolitan/tool/build/symtab.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "libc/sysv/consts/o.h"
#include "third_party/getopt/getopt.h"
/**
* @fileoverview elf to symbol table file dump tool
*/
void PrintUsage(FILE *f) {
fprintf(f, "%s%s%s\n", "usage: ", program_invocation_name,
" [-?h] -o PATH COMDBG");
}
int main(int argc, char *argv[]) {
int fd, opt;
const char *outpath;
struct SymbolTable *tab;
outpath = 0;
while ((opt = getopt(argc, argv, "?ho:")) != -1) {
switch (opt) {
case 'o':
outpath = optarg;
break;
case '?':
case 'h':
PrintUsage(stdout);
return 0;
default:
PrintUsage(stderr);
return EX_USAGE;
}
}
if (!outpath) {
fprintf(stderr, "error: need output path\n");
PrintUsage(stderr);
return 1;
}
if (optind + 1 != argc) {
fprintf(stderr, "error: need exactly one input path\n");
PrintUsage(stderr);
return 2;
}
if (!(tab = OpenSymbolTable(argv[optind]))) {
fprintf(stderr, "error: %s(%`'s) failed %m\n", "OpenSymbolTable",
argv[optind]);
return 3;
}
tab->names = 0;
tab->name_base = 0;
if ((fd = open(outpath, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1) {
fprintf(stderr, "error: %s(%`'s) failed %m\n", "open", outpath);
return 4;
}
if (write(fd, (const char *)tab, tab->size) != tab->size) {
fprintf(stderr, "error: %s(%`'s) failed %m\n", "write", outpath);
return 5;
}
if (close(fd) == -1) {
fprintf(stderr, "error: %s(%`'s) failed %m\n", "close", outpath);
return 6;
}
CloseSymbolTable(&tab);
return 0;
}
| 3,641 | 99 | jart/cosmopolitan | false |
cosmopolitan/tool/build/unveil.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/log/bsd.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "third_party/getopt/getopt.h"
#define USAGE \
"\
usage: unveil.com [-h] PROG ARGS...\n\
-h show help\n\
\n\
unveil.com v1.o\n\
copyright 2022 justine alexandra roberts tunney\n\
https://twitter.com/justinetunney\n\
https://linkedin.com/in/jtunney\n\
https://justine.lol/pledge/\n\
https://github.com/jart\n\
\n\
this program lets you launch linux commands in a filesystem sandbox\n\
inspired by the design of openbsd's unveil() system call.\n\
"
wontreturn void usage(void) {
write(2, USAGE, sizeof(USAGE) - 1);
exit(1);
}
int main(int argc, char *argv[]) {
const char *prog;
char pathbuf[PATH_MAX];
char *line = NULL;
size_t size = 0;
size_t count = 0;
ssize_t len;
int opt;
const char *fields[2];
if (!(IsLinux() || IsOpenbsd()))
errx(1, "this program is only intended for Linux and OpenBSD");
while ((opt = getopt(argc, argv, "h")) != -1) {
switch (opt) {
case 'h':
case '?':
default:
usage();
}
}
if (optind == argc) {
warnx("No command provided");
usage();
}
if (!(prog = commandv(argv[optind], pathbuf, sizeof(pathbuf))))
err(1, "command not found: %s", argv[optind]);
while ((len = getline(&line, &size, stdin)) != -1) {
count++;
bool chomped = false;
while (!chomped)
if (line[len - 1] == '\r' || line[len - 1] == '\n')
line[--len] = '\0';
else
chomped = true;
char *tok = line;
const char *p;
size_t i = 0;
while ((p = strsep(&tok, " \t")) != NULL) {
if (*p == '\0') {
p++;
continue;
}
if (i > 1) errx(1, "<stdin>:%zu - too many fields", count);
fields[i++] = p;
}
if (i != 2) errx(1, "<stdin>:%zu - malformed line", count);
if (unveil(fields[0], fields[1]) == -1)
err(1, "unveil(%s, %s)", fields[0], fields[1]);
}
free(line);
if (ferror(stdin)) {
err(1, "getline");
}
if (unveil(NULL, NULL) == -1) err(1, "unveil(NULL, NULL)");
__sys_execve(prog, argv + optind, environ);
err(127, "execve");
}
| 4,130 | 114 | jart/cosmopolitan | false |
cosmopolitan/tool/build/strace.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/user_regs_struct.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/nomultics.internal.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/append.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/nr.h"
#include "libc/sysv/consts/ptrace.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/w.h"
/**
* @fileoverview ptrace() tutorial
*/
#define PROLOGUE "%r%8d %'18T "
#undef __NR_execve
#define __WALL 0x40000000
#define PTR 0
#define ULONG 0
#define INT 1
#define LONG 2
#define STR 3
#define BUF 4
#define IOV 5
#define STRLIST 6
#define INTPTR 7
#define STAT 8
#define SIG 9
#define SIGSET 10
#define PIPE 11
#define OCTAL 0x80
static const long __NR_brk = 12;
static const long __NR_sigreturn = 15;
static const struct Syscall {
long *number;
const char *name;
char arity;
char eager;
unsigned char ret;
unsigned char arg[6];
} kSyscalls[] = {
// clang-format off
{&__NR_exit, "exit", 1, 1, INT, {INT}},
{&__NR_exit_group, "exit_group", 1, 1, INT, {INT}},
{&__NR_read, "read", 3, 1, LONG, {INT, BUF, ULONG}},
{&__NR_write, "write", 3, 3, LONG, {INT, BUF, ULONG}},
{&__NR_open, "open", 3, 3, INT, {STR, INT, OCTAL|INT}},
{&__NR_close, "close", 1, 1, INT, {INT}},
{&__NR_brk, "brk", 1, 1, ULONG, {ULONG}},
{&__NR_stat, "stat", 2, 1, INT, {STR, STAT}},
{&__NR_fstat, "fstat", 2, 1, INT, {INT, STAT}},
{&__NR_lstat, "lstat", 2, 1, INT, {INT, STAT}},
{&__NR_poll, "poll", 3, 3, INT, {PTR, INT, INT}},
{&__NR_ppoll, "ppoll", 4, 4, INT},
{&__NR_lseek, "lseek", 3, 3, LONG, {INT, LONG, INT}},
{&__NR_mmap, "mmap", 6, 6, ULONG, {PTR, ULONG, INT, INT, INT, ULONG}},
{&__NR_msync, "msync", 3, 3, INT, {PTR, ULONG, INT}},
{&__NR_mprotect, "mprotect", 3, 3, INT, {PTR, ULONG, INT}},
{&__NR_munmap, "munmap", 2, 2, INT, {PTR, ULONG}},
{&__NR_sigreturn, "rt_sigreturn", 6, 6, LONG},
{&__NR_sigaction, "rt_sigaction", 4, 4, INT, {SIG}},
{&__NR_sigprocmask, "rt_sigprocmask", 4, 4, INT, {INT, SIGSET, SIGSET, LONG}},
{&__NR_sigpending, "rt_sigpending", 2, 2, INT, {SIGSET, LONG}},
{&__NR_sigsuspend, "rt_sigsuspend", 2, 2, INT, {SIGSET, LONG}},
{&__NR_sigqueueinfo, "rt_sigqueueinfo", 6, 6},
{&__NR_ioctl, "ioctl", 3, 3, INT, {INT, ULONG, ULONG}},
{&__NR_pread, "pread64", 4, 1, LONG, {INT, BUF, ULONG, ULONG}},
{&__NR_pwrite, "pwrite64", 4, 4, LONG, {INT, BUF, ULONG, ULONG}},
{&__NR_readv, "readv", 3, 1, LONG, {INT, IOV, INT}},
{&__NR_writev, "writev", 3, 3, LONG, {INT, IOV, INT}},
{&__NR_access, "access", 2, 2, INT, {STR, OCTAL|INT}},
{&__NR_pipe, "pipe", 1, 0, INT, {PIPE}},
{&__NR_pipe2, "pipe2", 2, 0, INT, {PIPE, INT}},
{&__NR_select, "select", 5, 5},
{&__NR_pselect, "pselect", 6, 6},
{&__NR_pselect6, "pselect6", 6, 6},
{&__NR_sched_yield, "sched_yield", 0, 0, INT},
{&__NR_mremap, "mremap", 5, 5},
{&__NR_mincore, "mincore", 6, 6},
{&__NR_madvise, "madvise", 6, 6},
{&__NR_shmget, "shmget", 6, 6},
{&__NR_shmat, "shmat", 6, 6},
{&__NR_shmctl, "shmctl", 6, 6},
{&__NR_dup, "dup", 1, 1, INT, {INT}},
{&__NR_dup2, "dup2", 2, 2, INT, {INT, INT}},
{&__NR_pause, "pause", 0, 0, INT},
{&__NR_nanosleep, "nanosleep", 2, 1},
{&__NR_getitimer, "getitimer", 2, 2},
{&__NR_setitimer, "setitimer", 3, 3},
{&__NR_alarm, "alarm", 1, 1},
{&__NR_getpid, "getpid", 0, 0, INT},
{&__NR_sendfile, "sendfile", 6, 6},
{&__NR_socket, "socket", 3, 3, INT, {INT, INT, INT}},
{&__NR_connect, "connect", 3, 3},
{&__NR_accept, "accept", 3, 3},
{&__NR_sendto, "sendto", 6, 6},
{&__NR_recvfrom, "recvfrom", 6, 6},
{&__NR_sendmsg, "sendmsg", 6, 6},
{&__NR_recvmsg, "recvmsg", 6, 6},
{&__NR_shutdown, "shutdown", 6, 6},
{&__NR_bind, "bind", 6, 6},
{&__NR_listen, "listen", 6, 6},
{&__NR_getsockname, "getsockname", 6, 6},
{&__NR_getpeername, "getpeername", 6, 6},
{&__NR_socketpair, "socketpair", 6, 6},
{&__NR_setsockopt, "setsockopt", 6, 6},
{&__NR_getsockopt, "getsockopt", 6, 6},
{&__NR_fork, "fork", 0, 0, INT},
{&__NR_vfork, "vfork", 0, 0, INT},
{&__NR_posix_spawn, "posix_spawn", 6, 6},
{&__NR_execve, "execve", 3, 3, INT, {STR, STRLIST, STRLIST}},
{&__NR_wait4, "wait4", 4, 4, INT, {INT, INTPTR, INT, PTR}},
{&__NR_kill, "kill", 2, 2, INT, {INT, SIG}},
{&__NR_killpg, "killpg", 2, 2, INT, {INT, SIG}},
{&__NR_clone, "clone", 5, 5, INT, {PTR, PTR, INTPTR, INTPTR, ULONG}},
{&__NR_tkill, "tkill", 2, 2, INT, {INT, SIG}},
{&__NR_futex, "futex", 6, 6},
{&__NR_set_robust_list, "set_robust_list", 6, 6},
{&__NR_get_robust_list, "get_robust_list", 6, 6},
{&__NR_uname, "uname", 6, 6},
{&__NR_semget, "semget", 6, 6},
{&__NR_semop, "semop", 6, 6},
{&__NR_semctl, "semctl", 6, 6},
{&__NR_shmdt, "shmdt", 6, 6},
{&__NR_msgget, "msgget", 6, 6},
{&__NR_msgsnd, "msgsnd", 6, 6},
{&__NR_msgrcv, "msgrcv", 6, 6},
{&__NR_msgctl, "msgctl", 6, 6},
{&__NR_fcntl, "fcntl", 3, 3, INT, {INT, INT, ULONG}},
{&__NR_flock, "flock", 6, 6},
{&__NR_fsync, "fsync", 6, 6},
{&__NR_fdatasync, "fdatasync", 6, 6},
{&__NR_truncate, "truncate", 2, 2, INT, {STR, ULONG}},
{&__NR_ftruncate, "ftruncate", 6, 6, INT, {INT, ULONG}},
{&__NR_getcwd, "getcwd", 2, 2, INT, {BUF, ULONG}},
{&__NR_chdir, "chdir", 1, 1, INT, {STR}},
{&__NR_fchdir, "fchdir", 1, 1, INT, {INT}},
{&__NR_rename, "rename", 2, 2, INT, {STR, STR}},
{&__NR_mkdir, "mkdir", 2, 2, INT, {STR, OCTAL|INT}},
{&__NR_rmdir, "rmdir", 1, 1, INT, {STR}},
{&__NR_creat, "creat", 2, 2, INT, {STR, OCTAL|INT}},
{&__NR_link, "link", 2, 2, INT, {STR, STR}},
{&__NR_unlink, "unlink", 1, 1, INT, {STR}},
{&__NR_symlink, "symlink", 6, 6},
{&__NR_readlink, "readlink", 3, 1, INT, {STR, BUF, ULONG}},
{&__NR_chmod, "chmod", 6, 6},
{&__NR_fchmod, "fchmod", 6, 6},
{&__NR_chown, "chown", 6, 6},
{&__NR_fchown, "fchown", 6, 6},
{&__NR_lchown, "lchown", 6, 6},
{&__NR_umask, "umask", 1, 1, OCTAL|INT, {OCTAL|INT}},
{&__NR_gettimeofday, "gettimeofday", 6, 6},
{&__NR_getrlimit, "getrlimit", 6, 6},
{&__NR_getrusage, "getrusage", 6, 6},
{&__NR_sysinfo, "sysinfo", 6, 6},
{&__NR_times, "times", 6, 6},
{&__NR_ptrace, "ptrace", 6, 6},
{&__NR_syslog, "syslog", 6, 6},
{&__NR_getuid, "getuid", 0, 0, INT},
{&__NR_getgid, "getgid", 0, 0, INT},
{&__NR_getppid, "getppid", 0, 0, INT},
{&__NR_getpgrp, "getpgrp", 0, 0, INT},
{&__NR_setsid, "setsid", 1, 1, INT, {INT}},
{&__NR_getsid, "getsid", 0, 0, INT},
{&__NR_getpgid, "getpgid", 0, 0, INT},
{&__NR_setpgid, "setpgid", 2, 2, INT, {INT, INT}},
{&__NR_geteuid, "geteuid", 0, 0, INT},
{&__NR_getegid, "getegid", 0, 0, INT},
{&__NR_getgroups, "getgroups", 6, 6},
{&__NR_setgroups, "setgroups", 6, 6},
{&__NR_setreuid, "setreuid", 6, 6},
{&__NR_setregid, "setregid", 6, 6},
{&__NR_setuid, "setuid", 1, 1, INT, {INT}},
{&__NR_setgid, "setgid", 1, 1, INT, {INT}},
{&__NR_setresuid, "setresuid", 6, 6},
{&__NR_setresgid, "setresgid", 6, 6},
{&__NR_getresuid, "getresuid", 6, 6},
{&__NR_getresgid, "getresgid", 6, 6},
{&__NR_sigaltstack, "sigaltstack", 6, 6},
{&__NR_mknod, "mknod", 6, 6},
{&__NR_mknodat, "mknodat", 6, 6},
{&__NR_mkfifo, "mkfifo", 6, 6},
{&__NR_mkfifoat, "mkfifoat", 6, 6},
{&__NR_statfs, "statfs", 6, 6},
{&__NR_fstatfs, "fstatfs", 6, 6},
{&__NR_getpriority, "getpriority", 6, 6},
{&__NR_setpriority, "setpriority", 6, 6},
{&__NR_mlock, "mlock", 6, 6},
{&__NR_munlock, "munlock", 6, 6},
{&__NR_mlockall, "mlockall", 6, 6},
{&__NR_munlockall, "munlockall", 6, 6},
{&__NR_setrlimit, "setrlimit", 6, 6},
{&__NR_chroot, "chroot", 6, 6},
{&__NR_sync, "sync", 6, 6},
{&__NR_acct, "acct", 6, 6},
{&__NR_settimeofday, "settimeofday", 6, 6},
{&__NR_mount, "mount", 6, 6},
{&__NR_reboot, "reboot", 6, 6},
{&__NR_quotactl, "quotactl", 6, 6},
{&__NR_setfsuid, "setfsuid", 6, 6},
{&__NR_setfsgid, "setfsgid", 6, 6},
{&__NR_capget, "capget", 6, 6},
{&__NR_capset, "capset", 6, 6},
{&__NR_sigtimedwait, "sigtimedwait", 6, 6},
{&__NR_personality, "personality", 6, 6},
{&__NR_ustat, "ustat", 6, 6},
{&__NR_sysfs, "sysfs", 6, 6},
{&__NR_sched_setparam, "sched_setparam", 6, 6},
{&__NR_sched_getparam, "sched_getparam", 6, 6},
{&__NR_sched_setscheduler, "sched_setscheduler", 6, 6},
{&__NR_sched_getscheduler, "sched_getscheduler", 6, 6},
{&__NR_sched_get_priority_max, "sched_get_priority_max", 6, 6},
{&__NR_sched_get_priority_min, "sched_get_priority_min", 6, 6},
{&__NR_sched_rr_get_interval, "sched_rr_get_interval", 6, 6},
{&__NR_vhangup, "vhangup", 6, 6},
{&__NR_modify_ldt, "modify_ldt", 6, 6},
{&__NR_pivot_root, "pivot_root", 6, 6},
{&__NR__sysctl, "_sysctl", 6, 6},
{&__NR_prctl, "prctl", 6, 6},
{&__NR_arch_prctl, "arch_prctl", 2, 2, INT, {INT, ULONG}},
{&__NR_adjtimex, "adjtimex", 6, 6},
{&__NR_umount2, "umount2", 6, 6},
{&__NR_swapon, "swapon", 6, 6},
{&__NR_swapoff, "swapoff", 6, 6},
{&__NR_sethostname, "sethostname", 6, 6},
{&__NR_setdomainname, "setdomainname", 6, 6},
{&__NR_iopl, "iopl", 6, 6},
{&__NR_ioperm, "ioperm", 6, 6},
{&__NR_init_module, "init_module", 6, 6},
{&__NR_delete_module, "delete_module", 6, 6},
{&__NR_gettid, "gettid", 6, 6},
{&__NR_readahead, "readahead", 6, 6},
{&__NR_setxattr, "setxattr", 6, 6},
{&__NR_fsetxattr, "fsetxattr", 6, 6},
{&__NR_getxattr, "getxattr", 6, 6},
{&__NR_fgetxattr, "fgetxattr", 6, 6},
{&__NR_listxattr, "listxattr", 6, 6},
{&__NR_flistxattr, "flistxattr", 6, 6},
{&__NR_removexattr, "removexattr", 6, 6},
{&__NR_fremovexattr, "fremovexattr", 6, 6},
{&__NR_lsetxattr, "lsetxattr", 6, 6},
{&__NR_lgetxattr, "lgetxattr", 6, 6},
{&__NR_llistxattr, "llistxattr", 6, 6},
{&__NR_lremovexattr, "lremovexattr", 6, 6},
{&__NR_sched_setaffinity, "sched_setaffinity", 6, 6},
{&__NR_sched_getaffinity, "sched_getaffinity", 6, 6},
{&__NR_cpuset_getaffinity, "cpuset_getaffinity", 6, 6},
{&__NR_cpuset_setaffinity, "cpuset_setaffinity", 6, 6},
{&__NR_io_setup, "io_setup", 6, 6},
{&__NR_io_destroy, "io_destroy", 6, 6},
{&__NR_io_getevents, "io_getevents", 6, 6},
{&__NR_io_submit, "io_submit", 6, 6},
{&__NR_io_cancel, "io_cancel", 6, 6},
{&__NR_lookup_dcookie, "lookup_dcookie", 6, 6},
{&__NR_epoll_create, "epoll_create", 6, 6},
{&__NR_epoll_wait, "epoll_wait", 6, 6},
{&__NR_epoll_ctl, "epoll_ctl", 6, 6},
{&__NR_getdents, "getdents64", 6, 6},
{&__NR_set_tid_address, "set_tid_address", 1, 1},
{&__NR_restart_syscall, "restart_syscall", 6, 6},
{&__NR_semtimedop, "semtimedop", 6, 6},
{&__NR_fadvise, "fadvise", 6, 6},
{&__NR_timer_create, "timer_create", 6, 6},
{&__NR_timer_settime, "timer_settime", 6, 6},
{&__NR_timer_gettime, "timer_gettime", 6, 6},
{&__NR_timer_getoverrun, "timer_getoverrun", 6, 6},
{&__NR_timer_delete, "timer_delete", 6, 6},
{&__NR_clock_settime, "clock_settime", 6, 6},
{&__NR_clock_gettime, "clock_gettime", 6, 6},
{&__NR_clock_getres, "clock_getres", 6, 6},
{&__NR_clock_nanosleep, "clock_nanosleep", 6, 6},
{&__NR_tgkill, "tgkill", 6, 6},
{&__NR_mbind, "mbind", 6, 6},
{&__NR_set_mempolicy, "set_mempolicy", 6, 6},
{&__NR_get_mempolicy, "get_mempolicy", 6, 6},
{&__NR_mq_open, "mq_open", 6, 6},
{&__NR_mq_unlink, "mq_unlink", 6, 6},
{&__NR_mq_timedsend, "mq_timedsend", 6, 6},
{&__NR_mq_timedreceive, "mq_timedreceive", 6, 6},
{&__NR_mq_notify, "mq_notify", 6, 6},
{&__NR_mq_getsetattr, "mq_getsetattr", 6, 6},
{&__NR_kexec_load, "kexec_load", 6, 6},
{&__NR_waitid, "waitid", 6, 6},
{&__NR_add_key, "add_key", 6, 6},
{&__NR_request_key, "request_key", 6, 6},
{&__NR_keyctl, "keyctl", 6, 6},
{&__NR_ioprio_set, "ioprio_set", 6, 6},
{&__NR_ioprio_get, "ioprio_get", 6, 6},
{&__NR_inotify_init, "inotify_init", 6, 6},
{&__NR_inotify_add_watch, "inotify_add_watch", 6, 6},
{&__NR_inotify_rm_watch, "inotify_rm_watch", 6, 6},
{&__NR_openat, "openat", 4, 4, INT, {INT, STR, INT, OCTAL|INT}},
{&__NR_mkdirat, "mkdirat", 3, 3, INT, {INT, STR, OCTAL|INT}},
{&__NR_fchownat, "fchownat", 6, 6},
{&__NR_utime, "utime", 6, 6},
{&__NR_utimes, "utimes", 6, 6},
{&__NR_futimesat, "futimesat", 6, 6},
{&__NR_futimes, "futimes", 6, 6},
{&__NR_futimens, "futimens", 6, 6},
{&__NR_fstatat, "newfstatat", 4, 2, INT, {INT, STR, STAT, INT}},
{&__NR_unlinkat, "unlinkat", 3, 3, INT, {INT, STR, INT}},
{&__NR_renameat, "renameat", 4, 4, INT, {INT, STR, INT, STR}},
{&__NR_linkat, "linkat", 6, 6},
{&__NR_symlinkat, "symlinkat", 6, 6},
{&__NR_readlinkat, "readlinkat", 6, 6},
{&__NR_fchmodat, "fchmodat", 6, 6},
{&__NR_faccessat, "faccessat", 4, 4, INT, {INT, STR, INT, INT}},
{&__NR_unshare, "unshare", 6, 6},
{&__NR_splice, "splice", 6, 6},
{&__NR_tee, "tee", 6, 6},
{&__NR_sync_file_range, "sync_file_range", 4, 4},
{&__NR_vmsplice, "vmsplice", 6, 6},
{&__NR_migrate_pages, "migrate_pages", 6, 6},
{&__NR_move_pages, "move_pages", 6, 6},
{&__NR_preadv, "preadv", 4, 1, LONG, {INT, IOV, ULONG, ULONG}},
{&__NR_pwritev, "pwritev", 6, 6, LONG, {INT, IOV, ULONG, ULONG}},
{&__NR_utimensat, "utimensat", 6, 6},
{&__NR_fallocate, "fallocate", 6, 6},
{&__NR_posix_fallocate, "posix_fallocate", 6, 6},
{&__NR_accept4, "accept4", 4, 4},
{&__NR_dup3, "dup3", 3, 3, INT},
{&__NR_epoll_pwait, "epoll_pwait", 6, 6},
{&__NR_epoll_create1, "epoll_create1", 6, 6},
{&__NR_perf_event_open, "perf_event_open", 6, 6},
{&__NR_inotify_init1, "inotify_init1", 6, 6},
{&__NR_tgsigqueueinfo, "rt_tgsigqueueinfo", 6, 6},
{&__NR_signalfd, "signalfd", 6, 6},
{&__NR_signalfd4, "signalfd4", 6, 6},
{&__NR_eventfd, "eventfd", 6, 6},
{&__NR_eventfd2, "eventfd2", 6, 6},
{&__NR_timerfd_create, "timerfd_create", 6, 6},
{&__NR_timerfd_settime, "timerfd_settime", 6, 6},
{&__NR_timerfd_gettime, "timerfd_gettime", 6, 6},
{&__NR_recvmmsg, "recvmmsg", 6, 6},
{&__NR_fanotify_init, "fanotify_init", 6, 6},
{&__NR_fanotify_mark, "fanotify_mark", 6, 6},
{&__NR_prlimit, "prlimit", 6, 6},
{&__NR_name_to_handle_at, "name_to_handle_at", 6, 6},
{&__NR_open_by_handle_at, "open_by_handle_at", 6, 6},
{&__NR_clock_adjtime, "clock_adjtime", 6, 6},
{&__NR_syncfs, "syncfs", 6, 6},
{&__NR_sendmmsg, "sendmmsg", 6, 6},
{&__NR_setns, "setns", 6, 6},
{&__NR_getcpu, "getcpu", 6, 6},
{&__NR_process_vm_readv, "process_vm_readv", 6, 6},
{&__NR_process_vm_writev, "process_vm_writev", 6, 6},
{&__NR_kcmp, "kcmp", 6, 6},
{&__NR_finit_module, "finit_module", 6, 6},
{&__NR_sched_setattr, "sched_setattr", 6, 6},
{&__NR_sched_getattr, "sched_getattr", 6, 6},
{&__NR_renameat2, "renameat2", 6, 6},
{&__NR_seccomp, "seccomp", 6, 6},
{&__NR_getrandom, "getrandom", 6, 6},
{&__NR_memfd_create, "memfd_create", 6, 6},
{&__NR_kexec_file_load, "kexec_file_load", 6, 6},
{&__NR_bpf, "bpf", 6, 6},
{&__NR_execveat, "execveat", 6, 6},
{&__NR_userfaultfd, "userfaultfd", 6, 6},
{&__NR_membarrier, "membarrier", 6, 6},
{&__NR_mlock2, "mlock2", 6, 6},
{&__NR_copy_file_range, "copy_file_range", 6, 6},
{&__NR_preadv2, "preadv2", 6, 6},
{&__NR_pwritev2, "pwritev2", 6, 6},
{&__NR_pkey_mprotect, "pkey_mprotect", 6, 6},
{&__NR_pkey_alloc, "pkey_alloc", 6, 6},
{&__NR_pkey_free, "pkey_free", 6, 6},
{&__NR_statx, "statx", 6, 6},
{&__NR_io_pgetevents, "io_pgetevents", 6, 6},
{&__NR_rseq, "rseq", 6, 6},
{&__NR_pidfd_send_signal, "pidfd_send_signal", 6, 6},
{&__NR_io_uring_setup, "io_uring_setup", 6, 6},
{&__NR_io_uring_enter, "io_uring_enter", 6, 6},
{&__NR_io_uring_register, "io_uring_register", 6, 6},
// clang-format on
};
static const struct Errno {
errno_t *number;
const char *name;
} kErrnos[] = {
{&ENOSYS, "ENOSYS"}, //
{&EPERM, "EPERM"}, //
{&ENOENT, "ENOENT"}, //
{&ESRCH, "ESRCH"}, //
{&EINTR, "EINTR"}, //
{&EIO, "EIO"}, //
{&ENXIO, "ENXIO"}, //
{&E2BIG, "E2BIG"}, //
{&ENOEXEC, "ENOEXEC"}, //
{&EBADF, "EBADF"}, //
{&ECHILD, "ECHILD"}, //
{&EAGAIN, "EAGAIN"}, //
{&ENOMEM, "ENOMEM"}, //
{&EACCES, "EACCES"}, //
{&EFAULT, "EFAULT"}, //
{&ENOTBLK, "ENOTBLK"}, //
{&EBUSY, "EBUSY"}, //
{&EEXIST, "EEXIST"}, //
{&EXDEV, "EXDEV"}, //
{&ENODEV, "ENODEV"}, //
{&ENOTDIR, "ENOTDIR"}, //
{&EISDIR, "EISDIR"}, //
{&EINVAL, "EINVAL"}, //
{&ENFILE, "ENFILE"}, //
{&EMFILE, "EMFILE"}, //
{&ENOTTY, "ENOTTY"}, //
{&ETXTBSY, "ETXTBSY"}, //
{&EFBIG, "EFBIG"}, //
{&ENOSPC, "ENOSPC"}, //
{&EDQUOT, "EDQUOT"}, //
{&ESPIPE, "ESPIPE"}, //
{&EROFS, "EROFS"}, //
{&EMLINK, "EMLINK"}, //
{&EPIPE, "EPIPE"}, //
{&EDOM, "EDOM"}, //
{&ERANGE, "ERANGE"}, //
{&EDEADLK, "EDEADLK"}, //
{&ENAMETOOLONG, "ENAMETOOLONG"}, //
{&ENOLCK, "ENOLCK"}, //
{&ENOTEMPTY, "ENOTEMPTY"}, //
{&ELOOP, "ELOOP"}, //
{&ENOMSG, "ENOMSG"}, //
{&EIDRM, "EIDRM"}, //
{&ETIME, "ETIME"}, //
{&EPROTO, "EPROTO"}, //
{&EOVERFLOW, "EOVERFLOW"}, //
{&EILSEQ, "EILSEQ"}, //
{&EUSERS, "EUSERS"}, //
{&ENOTSOCK, "ENOTSOCK"}, //
{&EDESTADDRREQ, "EDESTADDRREQ"}, //
{&EMSGSIZE, "EMSGSIZE"}, //
{&EPROTOTYPE, "EPROTOTYPE"}, //
{&ENOPROTOOPT, "ENOPROTOOPT"}, //
{&EPROTONOSUPPORT, "EPROTONOSUPPORT"}, //
{&ESOCKTNOSUPPORT, "ESOCKTNOSUPPORT"}, //
{&ENOTSUP, "ENOTSUP"}, //
{&EOPNOTSUPP, "EOPNOTSUPP"}, //
{&EPFNOSUPPORT, "EPFNOSUPPORT"}, //
{&EAFNOSUPPORT, "EAFNOSUPPORT"}, //
{&EADDRINUSE, "EADDRINUSE"}, //
{&EADDRNOTAVAIL, "EADDRNOTAVAIL"}, //
{&ENETDOWN, "ENETDOWN"}, //
{&ENETUNREACH, "ENETUNREACH"}, //
{&ENETRESET, "ENETRESET"}, //
{&ECONNABORTED, "ECONNABORTED"}, //
{&ECONNRESET, "ECONNRESET"}, //
{&ENOBUFS, "ENOBUFS"}, //
{&EISCONN, "EISCONN"}, //
{&ENOTCONN, "ENOTCONN"}, //
{&ESHUTDOWN, "ESHUTDOWN"}, //
{&ETOOMANYREFS, "ETOOMANYREFS"}, //
{&ETIMEDOUT, "ETIMEDOUT"}, //
{&ECONNREFUSED, "ECONNREFUSED"}, //
{&EHOSTDOWN, "EHOSTDOWN"}, //
{&EHOSTUNREACH, "EHOSTUNREACH"}, //
{&EALREADY, "EALREADY"}, //
{&EINPROGRESS, "EINPROGRESS"}, //
{&ESTALE, "ESTALE"}, //
{&EREMOTE, "EREMOTE"}, //
{&EBADRPC, "EBADRPC"}, //
{&ERPCMISMATCH, "ERPCMISMATCH"}, //
{&EPROGUNAVAIL, "EPROGUNAVAIL"}, //
{&EPROGMISMATCH, "EPROGMISMATCH"}, //
{&EPROCUNAVAIL, "EPROCUNAVAIL"}, //
{&EFTYPE, "EFTYPE"}, //
{&EAUTH, "EAUTH"}, //
{&ENEEDAUTH, "ENEEDAUTH"}, //
{&EPROCLIM, "EPROCLIM"}, //
{&ENOATTR, "ENOATTR"}, //
{&EPWROFF, "EPWROFF"}, //
{&EDEVERR, "EDEVERR"}, //
{&EBADEXEC, "EBADEXEC"}, //
{&EBADARCH, "EBADARCH"}, //
{&ESHLIBVERS, "ESHLIBVERS"}, //
{&EBADMACHO, "EBADMACHO"}, //
{&ENOPOLICY, "ENOPOLICY"}, //
{&EBADMSG, "EBADMSG"}, //
{&ECANCELED, "ECANCELED"}, //
{&EOWNERDEAD, "EOWNERDEAD"}, //
{&ENOTRECOVERABLE, "ENOTRECOVERABLE"}, //
{&ENONET, "ENONET"}, //
{&ERESTART, "ERESTART"}, //
{&ENOSR, "ENOSR"}, //
{&ENOSTR, "ENOSTR"}, //
{&ENODATA, "ENODATA"}, //
{&EMULTIHOP, "EMULTIHOP"}, //
{&ENOLINK, "ENOLINK"}, //
{&ENOMEDIUM, "ENOMEDIUM"}, //
{&EMEDIUMTYPE, "EMEDIUMTYPE"}, //
{&EWOULDBLOCK, "EWOULDBLOCK"}, //
};
struct Pid {
int pid;
uint32_t hash;
bool insyscall;
struct Syscall *call;
struct Syscall fakecall;
struct user_regs_struct args;
char fakename[12];
};
struct PidList {
uint32_t i, n;
struct Pid *p;
};
char *ob; // output buffer
struct Pid *sp; // active subprocess
static uint32_t Hash(uint64_t pid) {
uint32_t hash;
hash = (pid * 6364136223846793005 + 1442695040888963407) >> 32;
if (!hash) hash = 1;
return hash;
}
static struct Pid *GetPid(struct PidList *list, int pid) {
uint32_t i, hash, step;
DCHECK_NE(0, pid);
DCHECK_LE(list->i, list->n >> 1);
if (list->n) {
i = 0;
step = 0;
hash = Hash(pid);
do {
i = (hash + step * (step + 1) / 2) & (list->n - 1);
if (list->p[i].pid == pid) {
return list->p + i;
}
step++;
} while (list->p[i].hash);
}
return 0;
}
static void ReservePid(struct PidList *list, int count) {
size_t i, j, step;
struct PidList old;
DCHECK_LE(list->i, list->n >> 1);
while (list->i + count >= (list->n >> 1)) {
memcpy(&old, list, sizeof(*list));
list->n = list->n ? list->n << 1 : 16;
list->p = calloc(list->n, sizeof(*list->p));
for (i = 0; i < old.n; ++i) {
if (!old.p[i].hash) continue;
step = 0;
do {
j = (old.p[i].hash + step * (step + 1) / 2) & (list->n - 1);
step++;
} while (list->p[j].hash);
list->p[j] = old.p[i];
}
free(old.p);
}
}
static struct Pid *AddPid(struct PidList *list, int pid) {
struct Pid *item;
uint32_t i, hash, step;
DCHECK_NE(0, pid);
DCHECK_LE(list->i, list->n >> 1);
if (!(item = GetPid(list, pid))) {
ReservePid(list, 1);
hash = Hash(pid);
++list->i;
i = 0;
step = 0;
do {
i = (hash + step * (step + 1) / 2) & (list->n - 1);
step++;
} while (list->p[i].hash);
list->p[i].hash = hash;
list->p[i].pid = pid;
item = list->p + i;
}
return item;
}
static void RemovePid(struct PidList *list, int pid) {
uint32_t i, hash, step;
DCHECK_NE(0, pid);
DCHECK_LE(list->i, list->n >> 1);
if (list->n) {
i = 0;
step = 0;
hash = Hash(pid);
do {
i = (hash + step * (step + 1) / 2) & (list->n - 1);
if (list->p[i].pid == pid) {
bzero(list->p + i, sizeof(*list->p));
list->i--;
assert(list->i < 99999);
return;
}
step++;
} while (list->p[i].hash);
}
}
static ssize_t WriteAll(int fd, const char *p, size_t n) {
ssize_t rc;
size_t i, got;
for (i = 0; i < n;) {
rc = write(fd, p + i, n - i);
if (rc != -1) {
got = rc;
i += got;
} else if (errno != EINTR) {
return -1;
}
}
return i;
}
static void Flush(void) {
WriteAll(2, ob, appendz(ob).i);
appendr(&ob, 0);
}
static const char *GetErrnoName(int x) {
const char *s;
static char buf[16];
if ((s = _strerrno(x))) return s;
FormatInt64(buf, x);
return buf;
}
static struct Syscall *GetSyscall(int x) {
int i;
if (x >= 0) {
for (i = 0; i < ARRAYLEN(kSyscalls); ++i) {
if (x == *kSyscalls[i].number) {
return kSyscalls + i;
}
}
}
return NULL;
}
static char *PeekString(unsigned long x) {
union {
char buf[8];
long word;
} u;
char *p;
unsigned offset;
unsigned long addr, i, n;
if (!x) return NULL;
addr = ROUNDDOWN(x, 8);
offset = x - addr;
errno = 0;
u.word = ptrace(PTRACE_PEEKTEXT, sp->pid, addr);
if (errno) return 0;
n = strnlen(u.buf + offset, 8 - offset);
p = calloc(1, n);
memcpy(p, u.buf + offset, n);
if (n == 8 - offset) {
do {
addr += 8;
errno = 0;
u.word = ptrace(PTRACE_PEEKDATA, sp->pid, addr);
if (errno) break;
i = strnlen(u.buf, 8);
p = realloc(p, n + i);
memcpy(p + n, u.buf, i);
n += i;
} while (i == 8);
}
p = realloc(p, n + 1);
p[n] = 0;
return p;
}
static char *PrintString(char *s) {
kappendf(&ob, "%#s", s);
return s;
}
static void *PeekData(unsigned long x, size_t size) {
union {
char buf[8];
long word;
} u;
char *p;
unsigned offset;
unsigned long addr, i, n;
if (!x) return NULL;
addr = ROUNDDOWN(x, 8);
offset = x - addr;
errno = 0;
u.word = ptrace(PTRACE_PEEKTEXT, sp->pid, addr);
if (errno) return 0;
p = calloc(1, size);
memcpy(p, u.buf + offset, MIN(size, 8 - offset));
for (i = 8 - offset; i < size; i += MIN(8, size - i)) {
addr += 8;
errno = 0;
u.word = ptrace(PTRACE_PEEKDATA, sp->pid, addr);
if (errno) break;
memcpy(p + i, u.buf, MIN(8, size - i));
}
return p;
}
static char *PrintData(char *data, size_t size) {
kappendf(&ob, "%#.*hhs%s", MIN(40, size), data, size > 40 ? "..." : "", data);
return data;
}
static struct iovec *PeekIov(unsigned long addr, int len) {
int i;
char *p;
long word;
struct iovec *iov;
if (!addr) return NULL;
p = calloc(1, len * 16);
for (i = 0; i < len * 2; ++i, addr += sizeof(word)) {
errno = 0;
word = ptrace(PTRACE_PEEKTEXT, sp->pid, addr);
if (errno) break;
memcpy(p + i * sizeof(word), &word, sizeof(word));
}
iov = (struct iovec *)p;
for (i = 0; i < len; ++i) {
errno = 0;
iov[i].iov_base = PeekData((long)iov[i].iov_base, iov[i].iov_len);
if (errno) break;
}
return iov;
}
static struct iovec *PrintIov(struct iovec *iov, int iovlen) {
int i;
if (iov) {
appendw(&ob, '{');
for (i = 0; i < iovlen; ++i) {
if (i) appendw(&ob, READ16LE(", "));
appendw(&ob, '{');
PrintData(iov[i].iov_base, iov[i].iov_len);
kappendf(&ob, ", %#lx}", iov[i].iov_len);
}
appendw(&ob, '}');
} else {
appendw(&ob, READ32LE("NULL"));
}
return iov;
}
static void FreeIov(struct iovec *iov, int iovlen) {
int i;
if (iov) {
for (i = 0; i < iovlen; ++i) {
free(iov[i].iov_base);
}
free(iov);
}
}
static char **PeekStringList(unsigned long addr) {
char *p;
long word;
size_t i, n;
char **list;
if (!addr) return NULL;
for (p = NULL, n = 0;; ++n) {
p = realloc(p, (n + 1) * sizeof(word));
word = ptrace(PTRACE_PEEKTEXT, sp->pid, addr + n * sizeof(word));
memcpy(p + n * sizeof(word), &word, sizeof(word));
if (!word) break;
}
list = (char **)p;
for (i = 0; i < n; ++i) {
list[i] = PeekString((long)list[i]);
}
return list;
}
static char **PrintStringList(char **list) {
int i;
if (list) {
appendw(&ob, '{');
for (i = 0;; ++i) {
if (i) appendw(&ob, READ16LE(", "));
PrintString(list[i]);
if (!list[i]) break;
}
appendw(&ob, '}');
} else {
appendw(&ob, READ32LE("NULL"));
}
return list;
}
static void FreeStringList(char **list) {
int i;
if (list) {
for (i = 0; list[i]; ++i) {
free(list[i]);
}
free(list);
}
}
static void PrintPipe(unsigned long addr) {
unsigned long word;
word = ptrace(PTRACE_PEEKDATA, sp->pid, addr);
kappendf(&ob, "[{%d, %d}]", (int)word, (int)(word >> 32));
}
static struct stat *PeekStat(unsigned long addr) {
int i;
char *p;
long word;
if (!addr) return NULL;
p = calloc(1, sizeof(struct stat));
for (i = 0; i < sizeof(struct stat); i += sizeof(word)) {
errno = 0;
word = ptrace(PTRACE_PEEKTEXT, sp->pid, addr + i);
if (errno) break;
memcpy(p + i, &word, sizeof(word));
}
return (struct stat *)p;
}
static struct stat *PrintStat(struct stat *st) {
bool printed;
printed = false;
appendw(&ob, '{');
if (st->st_size) {
kappendf(&ob, ".st_size = %#lx", st->st_size);
printed = true;
}
if (st->st_mode) {
if (printed) appendw(&ob, READ16LE(", "));
kappendf(&ob, ".st_mode = %#o", st->st_mode);
printed = true;
}
appendw(&ob, '}');
return st;
}
static void PrintSigset(unsigned long p) {
kappendf(&ob, "{%#lx}", ptrace(PTRACE_PEEKTEXT, sp->pid, p));
}
static void PrintSyscallArg(int type, unsigned long x, unsigned long y) {
char *s;
switch (type & 31) {
case ULONG:
kappendf(&ob, "%#lx", x);
break;
case INT:
if (type & OCTAL) {
kappendf(&ob, "%#o", x);
} else {
kappendf(&ob, "%d", x);
}
break;
case LONG:
kappendf(&ob, "%ld", x);
break;
case STR:
free(PrintString(PeekString(x)));
break;
case BUF:
free(PrintData(PeekData(x, MIN(32, y)), MIN(32, y)));
break;
case IOV:
FreeIov(PrintIov(PeekIov(x, y), y), y);
break;
case STAT:
free(PrintStat(PeekStat(x)));
break;
case PIPE:
PrintPipe(x);
break;
case SIG:
appends(&ob, strsignal(x));
break;
case SIGSET:
PrintSigset(x);
break;
case STRLIST:
FreeStringList(PrintStringList(PeekStringList(x)));
break;
case INTPTR:
if (x) {
s = PeekData(x, 4);
kappendf(&ob, "{%d}", READ32LE(s));
free(s);
}
break;
default:
kappendf(&ob, "wut[%'ld]", x);
break;
}
}
static void PrintSyscall(bool issecond) {
int a, b, eager, arity;
bool gotsome, isresuming, isunfinished;
gotsome = false;
if (issecond) {
if (!sp->call) {
return;
}
} else {
if (!(sp->call = GetSyscall(sp->args.orig_rax))) {
ksnprintf(sp->fakename, sizeof(sp->fakename), "%d", sp->args.orig_rax);
bzero(&sp->fakecall, sizeof(sp->fakecall));
sp->call = &sp->fakecall;
sp->call->name = sp->fakename;
sp->call->arity = 6;
sp->call->eager = 6;
}
if (sp->args.orig_rax == __NR_execve) {
if (sp->args.rax == -ENOSYS) {
sp->args.rax = 0;
}
} else if (sp->args.rax == -ENOSYS) {
return;
}
}
isresuming = false;
isunfinished = false;
if (!isunfinished) {
a = 0;
b = sp->call->arity;
} else if (!isresuming) {
a = 0;
b = sp->call->eager;
} else {
a = sp->call->eager;
b = sp->call->arity;
}
kappendf(&ob, PROLOGUE " %s%s(", sp->pid, isresuming ? "<resuming> " : "",
sp->call->name);
if (a <= 0 && 0 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[0], sp->args.rdi, sp->args.rsi);
gotsome = true;
}
if (a <= 1 && 1 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[1], sp->args.rsi, sp->args.rdx);
gotsome = true;
}
if (a <= 2 && 2 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[2], sp->args.rdx, sp->args.r10);
gotsome = true;
}
if (a <= 3 && 3 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[3], sp->args.r10, sp->args.r8);
gotsome = true;
}
if (a <= 4 && 4 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[4], sp->args.r8, sp->args.r9);
gotsome = true;
}
if (a <= 5 && 5 < b) {
if (gotsome) appendw(&ob, READ16LE(", "));
PrintSyscallArg(sp->call->arg[5], sp->args.r9, 0);
gotsome = true;
}
if (isunfinished) {
appends(&ob, ") â <unfinished>");
} else {
appends(&ob, ") â ");
if (sp->args.rax > (unsigned long)-4096) {
kappendf(&ob, "-1 %s", GetErrnoName(-sp->args.rax));
} else {
PrintSyscallArg(sp->call->ret, sp->args.rax, 0);
}
}
kappendf(&ob, "%n");
Flush();
sp->call = 0;
}
wontreturn void PropagateExit(int wstatus) {
exit(WEXITSTATUS(wstatus));
}
wontreturn void PropagateTermination(int wstatus) {
sigset_t mask;
// if signal that terminated program was sent to our whole
// process group, then that signal should be delivered and kill
// this process the moment it's unblocked here. we only unblock
// here because if the child process ignores the signal and does
// exit(0) then we want to propagate that intent too.
sigemptyset(&mask);
sigaddset(&mask, WTERMSIG(wstatus));
sigprocmask(SIG_UNBLOCK, &mask, 0);
// otherwise we can propagate it by the exit code convention
// commonly used with shell scripts
exit(128 + WTERMSIG(wstatus));
}
wontreturn void StraceMain(int argc, char *argv[]) {
unsigned long msg;
struct siginfo si;
struct Pid *s, *child;
struct PidList pidlist;
sigset_t mask, origmask;
int i, sig, evpid, root, wstatus, signal;
struct sigaction sigign, saveint, savequit;
if (!IsLinux()) {
kprintf("error: ptrace() is only supported on linux right now%n");
exit(1);
}
if (IsModeDbg()) ShowCrashReports();
if (argc < 2) {
kprintf("Usage: %s PROGRAM [ARGS...]%n", argv[0]);
exit(1);
}
pidlist.i = 0;
pidlist.n = 0;
pidlist.p = 0;
sigign.sa_flags = 0;
sigign.sa_handler = SIG_IGN;
sigemptyset(&sigign.sa_mask);
sigaction(SIGINT, &sigign, &saveint);
sigaction(SIGQUIT, &sigign, &savequit);
sigemptyset(&mask);
/* sigaddset(&mask, SIGCHLD); */
sigprocmask(SIG_BLOCK, &mask, &origmask);
CHECK_NE(-1, (root = fork()));
if (!root) {
sigaction(SIGINT, &saveint, 0);
sigaction(SIGQUIT, &savequit, 0);
sigprocmask(SIG_SETMASK, &origmask, 0);
ptrace(PTRACE_TRACEME);
execvp(argv[1], argv + 1);
_Exit(127);
}
sp = AddPid(&pidlist, root);
// wait for ptrace(PTRACE_TRACEME) to be called
CHECK_EQ(sp->pid, waitpid(sp->pid, &wstatus, 0));
// configure linux process tracing
CHECK_NE(-1, ptrace(PTRACE_SETOPTIONS, sp->pid, 0,
(PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK |
PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC |
PTRACE_O_TRACEEXIT | PTRACE_O_TRACESYSGOOD)));
// continue child process setting breakpoint at next system call
CHECK_NE(-1, ptrace(PTRACE_SYSCALL, sp->pid, 0, 0));
for (;;) {
CHECK_NE(-1, (evpid = waitpid(-1, &wstatus, __WALL)));
// prevent rehash in second addpid call
ReservePid(&pidlist, 2);
// we can get wait notifications before fork/vfork/etc. events
sp = AddPid(&pidlist, evpid);
// handle actual exit
if (WIFEXITED(wstatus)) {
kprintf(PROLOGUE " exited with %d%n", sp->pid, WEXITSTATUS(wstatus));
RemovePid(&pidlist, sp->pid);
sp = 0;
// we exit when the last process being monitored exits
if (!pidlist.i) {
PropagateExit(wstatus);
} else {
continue;
}
}
// handle actual kill
if (WIFSIGNALED(wstatus)) {
kprintf(PROLOGUE " exited with signal %G%n", sp->pid, WTERMSIG(wstatus));
RemovePid(&pidlist, sp->pid);
sp = 0;
// we die when the last process being monitored dies
if (!pidlist.i) {
PropagateTermination(wstatus);
} else {
continue;
}
}
// handle core dump
if (WCOREDUMP(wstatus)) {
kprintf(PROLOGUE " exited with core%n", sp->pid);
RemovePid(&pidlist, sp->pid);
sp = 0;
// we die when the last process being monitored dies
if (!pidlist.i) {
PropagateTermination(wstatus);
} else {
continue;
}
}
// handle trace events
sig = 0;
signal = (wstatus >> 8) & 0xffff;
assert(WIFSTOPPED(wstatus));
if (signal == SIGTRAP | PTRACE_EVENT_STOP) {
CHECK_NE(-1, ptrace(PTRACE_GETSIGINFO, sp->pid, 0, &si));
if (si.si_code == SIGTRAP || si.si_code == SIGTRAP | 0x80) {
CHECK_NE(-1, ptrace(PTRACE_GETREGS, sp->pid, 0, &sp->args));
PrintSyscall(sp->insyscall);
sp->insyscall = !sp->insyscall;
ptrace(PTRACE_SYSCALL, sp->pid, 0, 0);
} else {
sig = signal & 127;
kappendf(&ob, PROLOGUE " got signal %G%n", sp->pid, sig);
Flush();
ptrace(PTRACE_SYSCALL, sp->pid, 0, sig);
}
} else if (signal == (SIGTRAP | (PTRACE_EVENT_EXIT << 8))) {
CHECK_NE(-1, ptrace(PTRACE_GETEVENTMSG, sp->pid, 0, &msg));
sig = WSTOPSIG(wstatus);
ptrace(PTRACE_SYSCALL, sp->pid, 0, 0);
} else if (signal == (SIGTRAP | (PTRACE_EVENT_EXEC << 8))) {
CHECK_NE(-1, ptrace(PTRACE_GETEVENTMSG, sp->pid, 0, &msg));
ptrace(PTRACE_SYSCALL, sp->pid, 0, 0);
} else if (signal == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
signal == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) ||
signal == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
CHECK_NE(-1, ptrace(PTRACE_GETEVENTMSG, evpid, 0, &msg));
child = AddPid(&pidlist, msg);
child->pid = msg;
if (signal == (SIGTRAP | (PTRACE_EVENT_FORK << 8))) {
kappendf(&ob, PROLOGUE " fork() â %d%n", sp->pid, child->pid);
} else if (signal == (SIGTRAP | (PTRACE_EVENT_VFORK << 8))) {
kappendf(&ob, PROLOGUE " vfork() â %d%n", sp->pid, child->pid);
} else {
kappendf(&ob, PROLOGUE " clone() â %d%n", sp->pid, child->pid);
}
Flush();
ptrace(PTRACE_SYSCALL, child->pid, 0, 0);
ptrace(PTRACE_SYSCALL, sp->pid, 0, 0);
} else {
kappendf(&ob, PROLOGUE " gottish signal %G%n", sp->pid, sig);
Flush();
ptrace(PTRACE_SYSCALL, sp->pid, 0, signal & 127);
}
}
}
int main(int argc, char *argv[]) {
StraceMain(argc, argv);
}
| 54,806 | 1,199 | jart/cosmopolitan | false |
cosmopolitan/tool/build/gzip.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/errno.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 "libc/sysv/consts/ok.h"
#include "third_party/getopt/getopt.h"
#include "third_party/zlib/zlib.h"
#define USAGE \
" PATH...\n\
\n\
SYNOPSIS\n\
\n\
Compress Files\n\
\n\
FLAGS\n\
\n\
-?\n\
-h help\n\
-f force\n\
-c use stdout\n\
-d decompress\n\
-A append mode\n\
-x exclusive mode\n\
-k keep input file\n\
-0 disable compression\n\
-1 fastest compression\n\
-4 coolest compression\n\
-9 maximum compression\n\
-a ascii mode (ignored)\n\
-F fixed strategy (advanced)\n\
-L filtered strategy (advanced)\n\
-R run length strategy (advanced)\n\
-H huffman only strategy (advanced)\n\
\n"
bool opt_keep;
bool opt_force;
char opt_level;
bool opt_append;
char opt_strategy;
bool opt_exclusive;
bool opt_usestdout;
bool opt_decompress;
const char *prog;
char databuf[32768];
char pathbuf[PATH_MAX];
wontreturn void PrintUsage(int rc, FILE *f) {
fputs("usage: ", f);
fputs(prog, f);
fputs(USAGE, f);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "?hfcdakxALFRHF0123456789")) != -1) {
switch (opt) {
case 'k':
opt_keep = true;
break;
case 'f':
opt_force = true;
break;
case 'A':
opt_append = true;
break;
case 'c':
opt_usestdout = true;
break;
case 'x':
opt_exclusive = true;
break;
case 'd':
opt_decompress = true;
break;
case 'F':
opt_strategy = 'F'; // Z_FIXED
break;
case 'L':
opt_strategy = 'f'; // Z_FILTERED
break;
case 'R':
opt_strategy = 'R'; // Z_RLE
break;
case 'H':
opt_strategy = 'h'; // Z_HUFFMAN_ONLY
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
opt_level = opt;
break;
case 'h':
case '?':
PrintUsage(EXIT_SUCCESS, stdout);
default:
PrintUsage(EX_USAGE, stderr);
}
}
}
void Compress(const char *inpath) {
FILE *input;
gzFile output;
int rc, n, errnum;
const char *outpath;
char *p, openflags[5];
if ((!inpath || opt_usestdout) && (!isatty(1) || opt_force)) {
opt_usestdout = true;
} else {
fputs(prog, stderr);
fputs(": compressed data not written to a terminal."
" Use -f to force compression.\n",
stderr);
exit(1);
}
if (inpath) {
input = fopen(inpath, "rb");
} else {
inpath = "/dev/stdin";
input = stdin;
}
p = openflags;
*p++ = opt_append ? 'a' : 'w';
*p++ = 'b';
if (opt_exclusive) *p++ = 'x';
if (opt_level) *p++ = opt_level;
if (opt_strategy) *p++ = opt_strategy;
*p = 0;
if (opt_usestdout) {
outpath = "/dev/stdout";
output = gzdopen(1, openflags);
} else {
if (strlen(inpath) + 3 + 1 > PATH_MAX) _Exit(2);
stpcpy(stpcpy(pathbuf, inpath), ".gz");
outpath = pathbuf;
output = gzopen(outpath, openflags);
}
if (!output) {
fputs(outpath, stderr);
fputs(": gzopen() failed\n", stderr);
fputs(_strerdoc(errno), stderr);
fputs("\n", stderr);
exit(1);
}
do {
rc = fread(databuf, 1, sizeof(databuf), input);
if (rc == -1) {
errnum = 0;
fputs(inpath, stderr);
fputs(": read failed: ", stderr);
fputs(_strerdoc(ferror(input)), stderr);
fputs("\n", stderr);
_Exit(1);
}
if (!gzwrite(output, databuf, rc)) {
fputs(outpath, stderr);
fputs(": gzwrite failed: ", stderr);
fputs(gzerror(output, &errnum), stderr);
fputs("\n", stderr);
_Exit(1);
}
} while (rc == sizeof(databuf));
if (input != stdin) {
if (fclose(input)) {
fputs(inpath, stderr);
fputs(": close failed\n", stderr);
_Exit(1);
}
}
if (gzclose(output)) {
fputs(outpath, stderr);
fputs(": gzclose failed\n", stderr);
_Exit(1);
}
if (!opt_keep && !opt_usestdout && (opt_force || !access(inpath, W_OK))) {
unlink(inpath);
}
}
void Decompress(const char *inpath) {
FILE *output;
gzFile input;
int rc, n, errnum;
const char *outpath;
outpath = 0;
if (inpath) {
input = gzopen(inpath, "rb");
} else {
opt_usestdout = true;
inpath = "/dev/stdin";
input = gzdopen(0, "rb");
}
if (!input) {
fputs(inpath, stderr);
fputs(": gzopen() failed\n", stderr);
fputs(_strerdoc(errno), stderr);
fputs("\n", stderr);
exit(1);
}
if (opt_usestdout) {
output = stdout;
outpath = "/dev/stdout";
} else if (_endswith(inpath, ".gz")) {
n = strlen(inpath);
if (n - 3 + 1 > PATH_MAX) _Exit(2);
memcpy(pathbuf, inpath, n - 3);
pathbuf[n - 3] = 0;
outpath = pathbuf;
if (!(output = fopen(outpath, opt_append ? "wa" : "wb"))) {
fputs(outpath, stderr);
fputs(": open failed: ", stderr);
fputs(_strerdoc(errno), stderr);
fputs("\n", stderr);
_Exit(1);
}
} else {
fputs(inpath, stderr);
fputs(": needs to end with .gz unless -c is passed\n", stderr);
_Exit(1);
}
do {
rc = gzread(input, databuf, sizeof(databuf));
if (rc == -1) {
errnum = 0;
fputs(inpath, stderr);
fputs(": gzread failed: ", stderr);
fputs(gzerror(input, &errnum), stderr);
fputs("\n", stderr);
_Exit(1);
}
if (fwrite(databuf, rc, 1, output) != 1) {
fputs(outpath, stderr);
fputs(": write failed: ", stderr);
fputs(_strerdoc(ferror(output)), stderr);
fputs("\n", stderr);
_Exit(1);
}
} while (rc == sizeof(databuf));
if (gzclose(input)) {
fputs(inpath, stderr);
fputs(": gzclose failed\n", stderr);
_Exit(1);
}
if (output != stdout) {
if (fclose(output)) {
fputs(outpath, stderr);
fputs(": close failed\n", stderr);
_Exit(1);
}
}
if (!opt_keep && !opt_usestdout && (opt_force || !access(inpath, W_OK))) {
unlink(inpath);
}
}
int main(int argc, char *argv[]) {
int i;
prog = argc > 0 ? argv[0] : "cp.com";
GetOpts(argc, argv);
if (opt_decompress) {
if (optind == argc) {
Decompress(0);
} else {
for (i = optind; i < argc; ++i) {
Decompress(argv[i]);
}
}
} else {
if (optind == argc) {
Compress(0);
} else {
for (i = optind; i < argc; ++i) {
Compress(argv[i]);
}
}
}
return 0;
}
| 8,571 | 312 | jart/cosmopolitan | false |
cosmopolitan/tool/build/tinyemu.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/log/check.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/x/x.h"
#include "tool/build/lib/loader.h"
#include "tool/build/lib/machine.h"
#include "tool/build/lib/syscall.h"
static void AddHostFd(struct Machine *m, int fd) {
int i = m->fds.i++;
CHECK_NE(-1, (m->fds.p[i].fd = dup(fd)));
m->fds.p[i].cb = &kMachineFdCbHost;
}
int main(int argc, char *argv[]) {
int rc;
struct Elf elf;
struct Machine *m;
if (argc < 2) {
fputs("Usage: ", stderr);
fputs(argv[0], stderr);
fputs(" PROG [ARGS...]\n", stderr);
return EX_USAGE;
}
m = NewMachine();
m->mode = XED_MACHINE_MODE_LONG_64;
LoadProgram(m, argv[1], argv + 2, environ, &elf);
m->fds.p = xcalloc((m->fds.n = 8), sizeof(struct MachineFd));
AddHostFd(m, STDIN_FILENO);
AddHostFd(m, STDOUT_FILENO);
AddHostFd(m, STDERR_FILENO);
if (!(rc = setjmp(m->onhalt))) {
for (;;) {
LoadInstruction(m);
ExecuteInstruction(m);
}
} else {
return rc;
}
}
| 2,916 | 61 | jart/cosmopolitan | false |
cosmopolitan/tool/build/summy.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/stdio/stdio.h"
#include "libc/str/str.h"
/**
* @fileoverview Sums per-line integers from stdin.
*/
int main(int argc, char *argv[]) {
long x, sum = 0;
if (argc == 2 && !strcmp(argv[1], "-x")) {
while (scanf("%lx", &x) > 0) sum += x;
} else {
while (scanf("%ld", &x) > 0) sum += x;
}
printf("%,ld\n", sum);
return 0;
}
| 2,193 | 36 | jart/cosmopolitan | false |
cosmopolitan/tool/build/rle.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/log/check.h"
#include "libc/macros.internal.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 "libc/sysv/errfuns.h"
#include "third_party/getopt/getopt.h"
#define USAGE1 \
"NAME\n\
\n\
rle - Run Length Encoder\n\
\n\
SYNOPSIS\n\
\n\
"
#define USAGE2 \
" [FLAGS] [FILE...]\n\
\n\
DESCRIPTION\n\
\n\
This is a primitive compression algorithm. Its advantage is that\n\
the concomitant rldecode() library is seventeen bytes, and works\n\
on IA-16, IA-32, and NexGen32e without needing to be recompiled.\n\
\n\
This CLI is consistent with gzip, bzip2, lzma, etc.\n\
\n\
FLAGS\n\
\n\
-1 .. -9 ignored\n\
-a ignored\n\
-c send to stdout\n\
-d decompress\n\
-f ignored\n\
-t test integrity\n\
-S SUFFIX overrides .rle extension\n\
-h shows this information\n"
FILE *fin_, *fout_;
bool decompress_, test_;
const char *suffix_, *hint_;
void StartErrorMessage(void) {
fputs("error: ", stderr);
fputs(hint_, stderr);
fputs(": ", stderr);
}
void PrintIoErrorMessage(void) {
int err;
err = errno;
StartErrorMessage();
fputs(strerror(err), stderr);
fputc('\n', stderr);
}
void PrintUsage(int rc, FILE *f) {
fputs(USAGE1, f);
fputs(program_invocation_name, f);
fputs(USAGE2, f);
exit(rc);
}
void GetOpts(int argc, char *argv[]) {
int opt;
fin_ = stdin;
suffix_ = ".rle";
while ((opt = getopt(argc, argv, "123456789S:acdfho:t")) != -1) {
switch (opt) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'f':
break;
case 'c':
fout_ = stdout;
break;
case 'd':
decompress_ = true;
break;
case 't':
test_ = true;
break;
case 'o':
fclose(fout_);
if (!(fout_ = fopen((hint_ = optarg), "w"))) {
PrintIoErrorMessage();
exit(1);
}
break;
case 'S':
suffix_ = optarg;
break;
case 'h':
case '?':
PrintUsage(EXIT_SUCCESS, stdout);
default:
PrintUsage(EX_USAGE, stderr);
}
}
}
int RunLengthEncode1(void) {
int byte1, byte2, runlength;
byte2 = -1;
runlength = 0;
if ((byte1 = fgetc(fin_)) == -1) return -1;
do {
while (++runlength < 255) {
if ((byte2 = fgetc(fin_)) != byte1) break;
}
if (fputc(runlength, fout_) == -1 || fputc(byte1, fout_) == -1) {
return -1;
}
runlength = 0;
} while ((byte1 = byte2) != -1);
return feof(fin_) ? 0 : -1;
}
int RunLengthEncode2(void) {
return fputc(0, fout_) | fputc(0, fout_);
}
int EmitRun(unsigned char count, unsigned char byte) {
do {
if (fputc(byte, fout_) == -1) return -1;
} while (--count);
return 0;
}
int RunLengthDecode(void) {
int byte1, byte2;
if ((byte1 = fgetc(fin_)) == -1) return einval();
if ((byte2 = fgetc(fin_)) == -1) return einval();
while (byte1) {
if (!test_ && EmitRun(byte1, byte2) == -1) return -1;
if ((byte1 = fgetc(fin_)) == -1) break;
if ((byte2 = fgetc(fin_)) == -1) return einval();
}
if (byte1 != 0 || byte2 != 0) return einval();
fgetc(fin_);
return feof(fin_) ? 0 : -1;
}
int RunLengthCode(void) {
if (test_ || decompress_) {
return RunLengthDecode();
} else {
return RunLengthEncode1();
}
}
int Run(char **paths, size_t count) {
int rc;
char *p;
size_t i, suffixlen;
const char pathbuf[PATH_MAX];
if (!count) {
hint_ = "/dev/stdin";
if (!fout_) fout_ = stdout;
rc = RunLengthCode();
rc |= fclose(fin_);
fin_ = 0;
} else {
rc = fclose(fin_);
fin_ = 0;
for (i = 0; i < count && rc != -1; ++i) {
rc = -1;
if ((fin_ = fopen((hint_ = paths[i]), "r"))) {
if (test_ || fout_) {
rc = RunLengthCode();
} else {
suffixlen = strlen(suffix_);
if (!IsTrustworthy() &&
strlen(paths[i]) + suffixlen >= ARRAYLEN(pathbuf)) {
return eoverflow();
}
p = stpcpy(pathbuf, paths[i]);
if (!decompress_) {
strcpy(p, suffix_);
} else if (p - pathbuf > suffixlen &&
memcmp(p - suffixlen, suffix_, suffixlen) == 0) {
p[-suffixlen] = '\0';
} else {
return enotsup();
}
if ((fout_ = fopen((hint_ = pathbuf), "w"))) {
rc = RunLengthCode();
if (rc != -1 && !decompress_) {
rc = RunLengthEncode2();
}
if ((rc |= fclose(fout_)) != -1) {
unlink(paths[i]);
}
fout_ = 0;
}
}
rc |= fclose(fin_);
fin_ = 0;
}
}
}
if (rc != -1 && fout_) {
rc = RunLengthEncode2();
rc |= fclose(fout_);
fout_ = 0;
}
return rc;
}
int main(int argc, char *argv[]) {
GetOpts(argc, argv);
if (Run(argv + optind, argc - optind) != -1) {
return EXIT_SUCCESS;
} else {
PrintIoErrorMessage();
return EXIT_FAILURE;
}
}
| 7,154 | 252 | jart/cosmopolitan | false |
cosmopolitan/tool/build/unbuffer.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/termios.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/termios.h"
#include "libc/calls/ttydefaults.h"
#include "libc/errno.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/consts/w.h"
#include "third_party/getopt/getopt.h"
#define GETOPTS "o:"
#define USAGE \
"\
Usage: unbuffer.com [FLAGS] PROG ARGS...\n\
-o PATH output file\n\
"
int outfd;
struct winsize wsz;
struct termios tio, oldterm;
sigset_t chldmask, savemask;
struct sigaction ignore, saveint, savequit;
char databuf[512];
char pathbuf[PATH_MAX];
const char *outputpath;
static void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, GETOPTS)) != -1) {
switch (opt) {
case 'o':
outputpath = optarg;
break;
case '?':
write(1, USAGE, sizeof(USAGE) - 1);
exit(0);
default:
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
}
}
int main(int argc, char *argv[]) {
ssize_t rc;
const char *prog;
size_t i, got, wrote;
int e, ws, mfd, sfd, pid;
GetOpts(argc, argv);
if (optind == argc) {
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
if (!(prog = commandv(argv[optind], pathbuf, sizeof(pathbuf)))) {
kprintf("%s: command not found\n", argv[optind]);
return __COUNTER__ + 1;
}
if (outputpath) {
if ((outfd = creat(outputpath, 0644)) == -1) {
perror(outputpath);
return __COUNTER__ + 1;
}
}
bzero(&wsz, sizeof(wsz));
wsz.ws_col = 80;
wsz.ws_row = 45;
if (ioctl(1, TCGETS, &tio)) {
perror("tcgets");
return __COUNTER__ + 1;
}
if (openpty(&mfd, &sfd, 0, &tio, &wsz)) {
perror("openpty");
return __COUNTER__ + 1;
}
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);
if ((pid = fork()) == -1) {
perror("fork");
return __COUNTER__ + 1;
}
if (!pid) {
close(0);
dup(sfd);
close(1);
dup(sfd);
close(2);
dup(sfd);
close(mfd);
sigaction(SIGINT, &saveint, 0);
sigaction(SIGQUIT, &savequit, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
execv(prog, argv + optind);
perror("execve");
return 127;
}
close(sfd);
for (;;) {
if (waitpid(pid, &ws, WNOHANG) == pid) {
break;
}
e = errno;
rc = read(mfd, databuf, sizeof(databuf));
if (rc == -1) {
if (errno == EIO) {
errno = e;
rc = 0;
} else {
perror("read");
return __COUNTER__ + 1;
}
}
if (!(got = rc)) {
if (waitpid(pid, &ws, 0) == -1) {
perror("waitpid");
return __COUNTER__ + 1;
}
break;
}
for (i = 0; i < got; i += wrote) {
rc = write(1, databuf + i, got - i);
if (rc != -1) {
wrote = rc;
} else {
perror("write");
return __COUNTER__ + 1;
}
}
if (outputpath) {
for (i = 0; i < got; i += wrote) {
rc = write(outfd, databuf + i, got - i);
if (rc != -1) {
wrote = rc;
} else {
perror("write");
return __COUNTER__ + 1;
}
}
}
}
sigaction(SIGINT, &saveint, 0);
sigaction(SIGQUIT, &savequit, 0);
sigprocmask(SIG_SETMASK, &savemask, 0);
if (WIFEXITED(ws)) {
return WEXITSTATUS(ws);
} else {
return 128 + WTERMSIG(ws);
}
}
| 5,640 | 193 | jart/cosmopolitan | false |
cosmopolitan/tool/build/assimilate.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/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/dce.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/log/check.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/msync.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "third_party/getopt/getopt.h"
#include "third_party/regex/regex.h"
STATIC_YOINK("strerror_wr");
// options used: fhem
// letters not used: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdgijklnopqrstuvwxyz
// digits not used: 0123456789
// puncts not used: !"#$%&'()*+,-./;<=>@[\]^_`{|}~
// letters duplicated: none
#define GETOPTS "fem"
#define USAGE \
"\
Usage: assimilate.com [-hfem] COMFILE...\n\
-h show help\n\
-e force elf\n\
-m force macho\n\
-f continue on soft errors\n\
\n\
αcϵαlly pδrÏαblε εxεcµÏαblε assimilate v1.o\n\
copyright 2022 justine alexandra roberts tunney\n\
https://twitter.com/justinetunney\n\
https://linkedin.com/in/jtunney\n\
https://justine.lol/ape.html\n\
https://github.com/jart\n\
\n\
This program converts Actually Portable Executable files so they're\n\
in the platform-local executable format, rather than the multiplatform\n\
APE shell script format. This is useful on UNIX operating systems when\n\
you want to use your APE programs as script interpreter or for setuid.\n\
"
#define MODE_NATIVE 0
#define MODE_ELF 1
#define MODE_MACHO 2
#define MODE_PE 3
int g_mode;
bool g_force;
int exitcode;
const char *prog;
char errstr[128];
void GetOpts(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, GETOPTS)) != -1) {
switch (opt) {
case 'f':
g_force = true;
break;
case 'e':
g_mode = MODE_ELF;
break;
case 'm':
g_mode = MODE_MACHO;
break;
case 'h':
case '?':
write(1, USAGE, sizeof(USAGE) - 1);
exit(0);
default:
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
}
if (g_mode == MODE_NATIVE) {
if (IsXnu()) {
g_mode = MODE_MACHO;
} else if (IsLinux() || IsFreebsd() || IsNetbsd() || IsOpenbsd()) {
g_mode = MODE_ELF;
} else {
g_mode = MODE_PE;
}
}
}
void GetElfHeader(char ehdr[hasatleast 64], const char *image) {
char *p;
int c, i;
for (p = image; p < image + 4096; ++p) {
if (READ64LE(p) != READ64LE("printf '")) continue;
for (i = 0, p += 8; p + 3 < image + 4096 && (c = *p++) != '\'';) {
if (c == '\\') {
if ('0' <= *p && *p <= '7') {
c = *p++ - '0';
if ('0' <= *p && *p <= '7') {
c *= 8;
c += *p++ - '0';
if ('0' <= *p && *p <= '7') {
c *= 8;
c += *p++ - '0';
}
}
}
}
if (i < 64) {
ehdr[i++] = c;
} else {
kprintf("%s: ape printf elf header too long\n", prog);
exit(1);
}
}
if (i != 64) {
kprintf("%s: ape printf elf header too short\n", prog);
exit(2);
}
if (READ32LE(ehdr) != READ32LE("\177ELF")) {
kprintf("%s: ape printf elf header didn't have elf magic\n", prog);
exit(3);
}
return;
}
kprintf("%s: printf statement not found in first 4096 bytes\n", prog);
exit(4);
}
void GetMachoPayload(const char *image, size_t imagesize, int *out_offset,
int *out_size) {
regex_t rx;
const char *script;
regmatch_t rm[1 + 3] = {0};
int rc, skip, count, bs, offset, size;
if ((script = memmem(image, imagesize, "'\n#'\"\n", 6))) {
script += 6;
} else if ((script = memmem(image, imagesize, "#'\"\n", 4))) {
script += 4;
} else {
kprintf("%s: ape shell script not found\n", prog);
exit(5);
}
DCHECK_EQ(REG_OK, regcomp(&rx,
"bs=([ [:digit:]]+) "
"skip=\"?([ [:digit:]]+)\"? "
"count=\"?([ [:digit:]]+)\"?",
REG_EXTENDED));
rc = regexec(&rx, script, 4, rm, 0);
if (rc != REG_OK) {
if (rc == REG_NOMATCH) {
kprintf("%s: ape macho dd command not found\n", prog);
exit(6);
}
regerror(rc, &rx, errstr, sizeof(errstr));
kprintf("%s: ape macho dd regex failed: %s\n", prog, errstr);
exit(7);
}
bs = atoi(script + rm[1].rm_so);
skip = atoi(script + rm[2].rm_so);
count = atoi(script + rm[3].rm_so);
if (__builtin_mul_overflow(skip, bs, &offset) ||
__builtin_mul_overflow(count, bs, &size)) {
kprintf("%s: integer overflow parsing macho\n");
exit(8);
}
if (offset < 64) {
kprintf("%s: ape macho dd offset should be â¥64: %d\n", prog, offset);
exit(9);
}
if (offset >= imagesize) {
kprintf("%s: ape macho dd offset is outside file: %d\n", prog, offset);
exit(10);
}
if (size < 32) {
kprintf("%s: ape macho dd size should be â¥32: %d\n", prog, size);
exit(11);
}
if (size > imagesize - offset) {
kprintf("%s: ape macho dd size is outside file: %d\n", prog, size);
exit(12);
}
*out_offset = offset;
*out_size = size;
regfree(&rx);
}
void AssimilateElf(char *p, size_t n) {
char ehdr[64];
GetElfHeader(ehdr, p);
memcpy(p, ehdr, 64);
msync(p, 4096, MS_SYNC);
}
void AssimilateMacho(char *p, size_t n) {
int offset, size;
GetMachoPayload(p, n, &offset, &size);
memmove(p, p + offset, size);
msync(p, n, MS_SYNC);
}
void Assimilate(void) {
int fd;
char *p;
struct stat st;
if ((fd = open(prog, O_RDWR)) == -1) {
kprintf("%s: open(O_RDWR) failed: %m\n", prog);
exit(13);
}
if (fstat(fd, &st) == -1) {
kprintf("%s: fstat() failed: %m\n", prog);
exit(14);
}
if (st.st_size < 8192) {
kprintf("%s: ape binaries must be at least 4096 bytes\n", prog);
exit(15);
}
if ((p = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
MAP_FAILED) {
kprintf("%s: mmap failed: %m\n", prog);
exit(16);
}
if (g_mode == MODE_PE) {
if (READ16LE(p) == READ16LE("MZ")) {
if (!g_force) {
kprintf("%s: program is already an elf binary\n", prog);
if (g_mode != MODE_ELF) {
exitcode = 1;
}
}
goto Finish;
} else {
kprintf("%s: currently cannot back-convert to pe\n", prog);
exit(17);
}
}
if (READ32LE(p) == READ32LE("\177ELF")) {
if (!g_force) {
kprintf("%s: program is already an elf binary\n", prog);
if (g_mode != MODE_ELF) {
exitcode = 1;
}
}
goto Finish;
}
if (READ32LE(p) == 0xFEEDFACE + 1) {
if (!g_force) {
kprintf("%s: program is already a mach-o binary\n", prog);
if (g_mode != MODE_MACHO) {
exitcode = 1;
}
}
goto Finish;
}
if (READ64LE(p) != READ64LE("MZqFpD='")) {
kprintf("%s: this file is not an actually portable executable\n", prog);
exit(17);
}
if (g_mode == MODE_ELF) {
AssimilateElf(p, st.st_size);
} else if (g_mode == MODE_MACHO) {
AssimilateMacho(p, st.st_size);
}
Finish:
if (munmap(p, st.st_size) == -1) {
kprintf("%s: munmap() failed: %m\n", prog);
exit(18);
}
}
int main(int argc, char *argv[]) {
int i;
GetOpts(argc, argv);
if (optind == argc) {
kprintf("error: need at least one program path to assimilate\n");
write(2, USAGE, sizeof(USAGE) - 1);
exit(64);
}
for (i = optind; i < argc; ++i) {
prog = argv[i];
Assimilate();
}
return exitcode;
}
| 9,435 | 307 | jart/cosmopolitan | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.