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/build/blinkenlights.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 "dsp/scale/cdecimate2xuint8x8.h" #include "dsp/tty/tty.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/cpuset.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/termios.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/bing.internal.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/bits.h" #include "libc/intrin/pcmpeqb.h" #include "libc/intrin/pmovmskb.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/tpenc.h" #include "libc/limits.h" #include "libc/log/check.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/gc.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/append.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/str/tab.internal.h" #include "libc/str/thompike.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/errfuns.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "libc/x/xsigaction.h" #include "third_party/gdtoa/gdtoa.h" #include "third_party/getopt/getopt.h" #include "tool/build/lib/address.h" #include "tool/build/lib/breakpoint.h" #include "tool/build/lib/case.h" #include "tool/build/lib/cga.h" #include "tool/build/lib/demangle.h" #include "tool/build/lib/dis.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/fds.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/fpu.h" #include "tool/build/lib/high.h" #include "tool/build/lib/loader.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/mda.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/panel.h" #include "tool/build/lib/pml4t.h" #include "tool/build/lib/pty.h" #include "tool/build/lib/signal.h" #include "tool/build/lib/stats.h" #include "tool/build/lib/syscall.h" #include "tool/build/lib/throw.h" #include "tool/build/lib/xmmtype.h" #define USAGE \ " [-?HhrRstv] [ROM] [ARGS...]\n\ \n\ DESCRIPTION\n\ \n\ Emulates x86 Linux Programs w/ Dense Machine State Visualization\n\ Please keep still and only watchen astaunished das blinkenlights\n\ \n\ FLAGS\n\ \n\ -h help\n\ -z zoom\n\ -v verbosity\n\ -r real mode\n\ -s statistics\n\ -H disable highlight\n\ -t tui debugger mode\n\ -R reactive tui mode\n\ -b ADDR push a breakpoint\n\ -L PATH log file location\n\ \n\ ARGUMENTS\n\ \n\ ROM files can be ELF or a flat αcτµαlly pδrταblε εxεcµταblε.\n\ It should use x86_64 in accordance with the System Five ABI.\n\ The SYSCALL ABI is defined as it is written in Linux Kernel.\n\ \n\ FEATURES\n\ \n\ 8086, 8087, i386, x86_64, SSE3, SSSE3, POPCNT, MDA, CGA, TTY\n\ \n" #define HELP \ "\e[1mBLINKENLIGHTS v1.o\e[22m\ https://justine.lol/blinkenlights/\n\ \n\ KEYBOARD SHORTCUTS CLI FLAGS\n\ \n\ ctrl-c interrupt -t tui mode\n\ s step -r real mode\n\ n next -s statistics\n\ c continue -b ADDR push breakpoint\n\ C continue harder -L PATH log file location\n\ q quit -R reactive tui mode\n\ f finish -H disable highlighting\n\ R restart -v increase verbosity\n\ x hex -? help\n\ ? help\n\ t sse type\n\ w sse width\n\ B pop breakpoint\n\ ctrl-t turbo\n\ alt-t slowmo" #define MAXZOOM 16 #define DISWIDTH 40 #define DUMPWIDTH 64 #define DISPWIDTH 80 #define WHEELDELTA 1 #define RESTART 0x001 #define REDRAW 0x002 #define CONTINUE 0x004 #define STEP 0x008 #define NEXT 0x010 #define FINISH 0x020 #define FAILURE 0x040 #define WINCHED 0x080 #define INT 0x100 #define QUIT 0x200 #define EXIT 0x400 #define ALARM 0x800 #define kXmmDecimal 0 #define kXmmHex 1 #define kXmmChar 2 #define kMouseLeftDown 0 #define kMouseMiddleDown 1 #define kMouseRightDown 2 #define kMouseLeftUp 4 #define kMouseMiddleUp 5 #define kMouseRightUp 6 #define kMouseLeftDrag 32 #define kMouseMiddleDrag 33 #define kMouseRightDrag 34 #define kMouseWheelUp 64 #define kMouseWheelDown 65 #define kMouseCtrlWheelUp 80 #define kMouseCtrlWheelDown 81 #define CTRL(C) ((C) ^ 0100) struct Mouse { short y; short x; int e; }; struct MemoryView { int64_t start; int zoom; }; struct Keystrokes { unsigned i; char p[4][32]; long double s[4]; }; struct MachineState { uint64_t ip; uint8_t cs[8]; uint8_t ss[8]; uint8_t es[8]; uint8_t ds[8]; uint8_t fs[8]; uint8_t gs[8]; uint8_t reg[16][8]; uint8_t xmm[16][16]; struct MachineFpu fpu; struct MachineSse sse; struct MachineMemstat memstat; }; struct Panels { union { struct { struct Panel disassembly; struct Panel breakpointshr; struct Panel breakpoints; struct Panel mapshr; struct Panel maps; struct Panel frameshr; struct Panel frames; struct Panel displayhr; struct Panel display; struct Panel registers; struct Panel ssehr; struct Panel sse; struct Panel codehr; struct Panel code; struct Panel readhr; struct Panel readdata; struct Panel writehr; struct Panel writedata; struct Panel stackhr; struct Panel stack; struct Panel status; }; struct Panel p[21]; }; }; static const signed char kThePerfectKernel[8] = {-1, -3, 3, 17, 17, 3, -3, -1}; static const char kRipName[3][4] = {"IP", "EIP", "RIP"}; static const char kRegisterNames[3][16][4] = { {"AX", "CX", "DX", "BX", "SP", "BP", "SI", "DI"}, {"EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI"}, {"RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"}, }; static bool belay; static bool react; static bool tuimode; static bool alarmed; static bool colorize; static bool mousemode; static bool printstats; static bool showhighsse; static int tyn; static int txn; static int tick; static int speed; static int vidya; static int ttyin; static int focus; static int ttyout; static int opline; static int action; static int xmmdisp; static int exitcode; static long ips; static long rombase; static long codesize; static int64_t oldlen; static int64_t opstart; static int64_t mapsstart; static uint64_t readaddr; static uint64_t readsize; static uint64_t writeaddr; static uint64_t writesize; static int64_t framesstart; static int64_t breakpointsstart; static uint64_t last_opcount; static char *codepath; static void *onbusted; static char *dialog; static char *statusmessage; static struct Pty *pty; static struct Machine *m; static struct Panels pan; static struct Keystrokes keystrokes; static struct Breakpoints breakpoints; static struct MemoryView codeview; static struct MemoryView readview; static struct MemoryView writeview; static struct MemoryView stackview; static struct MachineState laststate; static struct MachineMemstat lastmemstat; static struct XmmType xmmtype; static struct Elf elf[1]; static struct Dis dis[1]; static long double last_seconds; static long double statusexpires; static struct termios oldterm; static char logpath[PATH_MAX]; static char systemfailure[128]; static struct sigaction oldsig[4]; static void SetupDraw(void); static void Redraw(void); static void HandleKeyboard(const char *); static char *FormatDouble(char buf[32], long double x) { g_xfmt_p(buf, &x, 15, 32, 0); return buf; } static int64_t SignExtend(uint64_t x, char b) { char k; assert(1 <= b && b <= 64); k = 64 - b; return (int64_t)(x << k) >> k; } static void SetCarry(bool cf) { m->flags = SetFlag(m->flags, FLAGS_CF, cf); } static bool IsCall(void) { return (m->xedd->op.dispatch == 0x0E8 || (m->xedd->op.dispatch == 0x0FF && m->xedd->op.reg == 2)); } static bool IsDebugBreak(void) { return m->xedd->op.map == XED_ILD_MAP0 && m->xedd->op.opcode == 0xCC; } static bool IsRet(void) { switch (m->xedd->op.dispatch) { case 0x0C2: case 0x0C3: case 0x0CA: case 0x0CB: case 0x0CF: return true; default: return false; } } static int GetXmmTypeCellCount(int r) { switch (xmmtype.type[r]) { case kXmmIntegral: return 16 / xmmtype.size[r]; case kXmmFloat: return 4; case kXmmDouble: return 2; default: unreachable; } } static uint8_t CycleXmmType(uint8_t t) { switch (t) { default: case kXmmIntegral: return kXmmFloat; case kXmmFloat: return kXmmDouble; case kXmmDouble: return kXmmIntegral; } } static uint8_t CycleXmmDisp(uint8_t t) { switch (t) { default: case kXmmDecimal: return kXmmHex; case kXmmHex: return kXmmChar; case kXmmChar: return kXmmDecimal; } } static uint8_t CycleXmmSize(uint8_t w) { switch (w) { default: case 1: return 2; case 2: return 4; case 4: return 8; case 8: return 1; } } static int GetPointerWidth(void) { return 2 << (m->mode & 3); } static int64_t GetIp(void) { switch (GetPointerWidth()) { default: case 8: return m->ip; case 4: return Read64(m->cs) + (m->ip & 0xffff); case 2: return Read64(m->cs) + (m->ip & 0xffff); } } static int64_t GetSp(void) { switch (GetPointerWidth()) { default: case 8: return Read64(m->sp); case 4: return Read64(m->ss) + Read32(m->sp); case 2: return Read64(m->ss) + Read16(m->sp); } } static int64_t ReadWord(uint8_t *p) { switch (GetPointerWidth()) { default: case 8: return Read64(p); case 4: return Read32(p); case 2: return Read16(p); } } static void CopyMachineState(struct MachineState *ms) { ms->ip = m->ip; memcpy(ms->cs, m->cs, sizeof(m->cs)); memcpy(ms->ss, m->ss, sizeof(m->ss)); memcpy(ms->es, m->es, sizeof(m->es)); memcpy(ms->ds, m->ds, sizeof(m->ds)); memcpy(ms->fs, m->fs, sizeof(m->fs)); memcpy(ms->gs, m->gs, sizeof(m->gs)); memcpy(ms->reg, m->reg, sizeof(m->reg)); memcpy(ms->xmm, m->xmm, sizeof(m->xmm)); memcpy(&ms->fpu, &m->fpu, sizeof(m->fpu)); memcpy(&ms->sse, &m->sse, sizeof(m->sse)); } /** * Handles file mapped page faults in valid page but past eof. */ static void OnSigBusted(void) { CHECK(onbusted); longjmp(onbusted, 1); } /** * Returns true if 𝑣 is a shadow memory virtual address. */ static bool IsShadow(int64_t v) { return 0x7fff8000 <= v && v < 0x100080000000; } /** * Returns glyph representing byte at virtual address 𝑣. */ static int VirtualBing(int64_t v) { int rc; uint8_t *p; jmp_buf busted; onbusted = busted; if ((p = FindReal(m, v))) { if (!setjmp(busted)) { rc = bing(p[0], 0); } else { rc = u'≀'; } } else { rc = u'⋅'; } onbusted = NULL; return rc; } /** * Returns ASAN shadow uint8 concomitant to address 𝑣 or -1. */ static int VirtualShadow(int64_t v) { int rc; char *p; jmp_buf busted; if (IsShadow(v)) return -2; onbusted = busted; if ((p = FindReal(m, (v >> 3) + 0x7fff8000))) { if (!setjmp(busted)) { rc = p[0] & 0xff; } else { rc = -1; } } else { rc = -1; } onbusted = NULL; return rc; } static void ScrollOp(struct Panel *p, long op) { long n; opline = op; if ((n = p->bottom - p->top) > 1) { if (!(opstart + 1 <= op && op < opstart + n)) { opstart = MIN(MAX(0, op - n / 8), MAX(0, dis->ops.i - n)); } } } static int TtyWriteString(const char *s) { return write(ttyout, s, strlen(s)); } static void OnFeed(void) { TtyWriteString("\e[K\e[2J"); } static void HideCursor(void) { TtyWriteString("\e[?25l"); } static void ShowCursor(void) { TtyWriteString("\e[?25h"); } static void EnableSafePaste(void) { TtyWriteString("\e[?2004h"); } static void DisableSafePaste(void) { TtyWriteString("\e[?2004l"); } static void EnableMouseTracking(void) { mousemode = true; TtyWriteString("\e[?1000;1002;1015;1006h"); } static void DisableMouseTracking(void) { mousemode = false; TtyWriteString("\e[?1000;1002;1015;1006l"); } static void ToggleMouseTracking(void) { if (mousemode) { DisableMouseTracking(); } else { EnableMouseTracking(); } } static void LeaveScreen(void) { TtyWriteString(_gc(xasprintf("\e[%d;%dH\e[S\r\n", tyn, txn))); } static void GetTtySize(int fd) { struct winsize wsize; wsize.ws_row = tyn; wsize.ws_col = txn; _getttysize(fd, &wsize); tyn = wsize.ws_row; txn = wsize.ws_col; } static void TuiRejuvinate(void) { struct termios term; DEBUGF("TuiRejuvinate"); GetTtySize(ttyout); HideCursor(); memcpy(&term, &oldterm, sizeof(term)); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 1; term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON); term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL); term.c_cflag &= ~(CSIZE | PARENB); term.c_cflag |= CS8; term.c_iflag |= IUTF8; CHECK_NE(-1, ioctl(ttyout, TCSETS, &term)); xsigaction(SIGBUS, OnSigBusted, SA_NODEFER, 0, NULL); EnableMouseTracking(); EnableSafePaste(); } static void OnQ(void) { INFOF("OnQ"); action |= EXIT; } static void OnV(void) { vidya = !vidya; } static void OnSigWinch(void) { action |= WINCHED; } static void OnSigInt(void) { if (tuimode) { action |= INT; } else { action |= EXIT; } } static void OnSigAlarm(void) { action |= ALARM; } static void OnSigCont(void) { TuiRejuvinate(); Redraw(); } static void TtyRestore1(void) { DEBUGF("TtyRestore1"); ShowCursor(); TtyWriteString("\e[0m"); } static void TtyRestore2(void) { DEBUGF("TtyRestore2"); ioctl(ttyout, TCSETS, &oldterm); DisableMouseTracking(); DisableSafePaste(); } static void TuiCleanup(void) { sigaction(SIGCONT, oldsig + 2, NULL); TtyRestore1(); DisableMouseTracking(); DisableSafePaste(); tuimode = false; LeaveScreen(); } static void ResolveBreakpoints(void) { long i, sym; for (i = 0; i < breakpoints.i; ++i) { if (breakpoints.p[i].symbol && !breakpoints.p[i].addr) { if ((sym = DisFindSymByName(dis, breakpoints.p[i].symbol)) != -1) { breakpoints.p[i].addr = dis->syms.p[sym].addr; } else { fprintf( stderr, "error: breakpoint not found: %s (out of %,ld loaded symbols)\n", breakpoints.p[i].symbol, dis->syms.i); exit(1); } } } } static void BreakAtNextInstruction(void) { struct Breakpoint b; bzero(&b, sizeof(b)); b.addr = GetIp() + m->xedd->length; b.oneshot = true; PushBreakpoint(&breakpoints, &b); } static void LoadSyms(void) { LoadDebugSymbols(elf); DisLoadElf(dis, elf); } static int DrainInput(int fd) { char buf[32]; struct pollfd fds[1]; if (!IsWindows()) { for (;;) { fds[0].fd = fd; fds[0].events = POLLIN; if (poll(fds, ARRAYLEN(fds), 0) == -1) return -1; if (!(fds[0].revents & POLLIN)) break; if (read(fd, buf, sizeof(buf)) == -1) return -1; } } return 0; } static int ReadCursorPosition(int *out_y, int *out_x) { int y, x; char *p, buf[32]; if (readansi(ttyin, buf, sizeof(buf)) == 1) return -1; p = buf; if (*p == '\e') ++p; if (*p == '[') ++p; y = strtol(p, &p, 10); if (*p == ';') ++p; x = strtol(p, &p, 10); if (*p != 'R') return ebadmsg(); if (out_y) *out_y = MAX(1, y) - 1; if (out_x) *out_x = MAX(1, x) - 1; return 0; } static int GetCursorPosition(int *out_y, int *out_x) { TtyWriteString("\e[6n"); return ReadCursorPosition(out_y, out_x); } static int GetTerminalDimensions(int *out_y, int *out_x) { TtyWriteString("\e7\e[9979;9979H\e[6n\e8"); return ReadCursorPosition(out_y, out_x); } void CommonSetup(void) { static bool once; if (!once) { if (tuimode || breakpoints.i) { LoadSyms(); ResolveBreakpoints(); } once = true; } } void TuiSetup(void) { int y, x; bool report; static bool once; report = false; if (!once) { INFOF("loaded program %s\n%s", codepath, _gc(FormatPml4t(m))); CommonSetup(); ioctl(ttyout, TCGETS, &oldterm); xsigaction(SIGINT, OnSigInt, 0, 0, oldsig + 3); atexit(TtyRestore2); once = true; report = true; } setitimer(ITIMER_REAL, &((struct itimerval){0}), NULL); xsigaction(SIGCONT, OnSigCont, SA_RESTART | SA_NODEFER, 0, oldsig + 2); CopyMachineState(&laststate); TuiRejuvinate(); if (report) { DrainInput(ttyin); y = 0; if (GetCursorPosition(&y, NULL) != -1) { TtyWriteString(_gc(xasprintf("\e[%dS", y))); } } } static void ExecSetup(void) { CommonSetup(); setitimer(ITIMER_REAL, &((struct itimerval){{0, 1. / 60 * 1e6}, {0, 1. / 60 * 1e6}}), NULL); } static void AppendPanel(struct Panel *p, long line, const char *s) { if (0 <= line && line < p->bottom - p->top) { AppendStr(&p->lines[line], s); } } static bool IsXmmNonZero(long start, long end) { long i; uint8_t v1[16], vz[16]; for (i = start; i < end; ++i) { bzero(vz, 16); memcpy(v1, m->xmm[i], 16); pcmpeqb(v1, v1, vz); if (pmovmskb(v1) != 0xffff) { return true; } } return false; } static bool IsSegNonZero(void) { unsigned i; for (i = 0; i < 6; ++i) { if (Read64(GetSegment(m, 0, i))) { return true; } } return false; } static int PickNumberOfXmmRegistersToShow(void) { if (IsXmmNonZero(0, 8) || IsXmmNonZero(8, 16)) { if (showhighsse || IsXmmNonZero(8, 16)) { showhighsse = true; return 16; } else { return 8; } } else { showhighsse = false; return 0; } } static int GetRegHexWidth(void) { switch (m->mode & 3) { case XED_MODE_LONG: return 16; case XED_MODE_LEGACY: return 8; case XED_MODE_REAL: if ((Read64(m->ax) >> 16) || (Read64(m->cx) >> 16) || (Read64(m->dx) >> 16) || (Read64(m->bx) >> 16) || (Read64(m->sp) >> 16) || (Read64(m->bp) >> 16) || (Read64(m->si) >> 16) || (Read64(m->di) >> 16)) { return 8; } else { return 4; } default: unreachable; } } static int GetAddrHexWidth(void) { switch (m->mode & 3) { case XED_MODE_LONG: return 12; case XED_MODE_LEGACY: return 8; case XED_MODE_REAL: if (Read64(m->fs) >= 0x10fff0 || Read64(m->gs) >= 0x10fff0) { return 8; } else { return 6; } default: unreachable; } } void SetupDraw(void) { int i, j, n, a, b, c, yn, cpuy, ssey, dx[2], c2y[3], c3y[5]; cpuy = 9; if (IsSegNonZero()) cpuy += 2; ssey = PickNumberOfXmmRegistersToShow(); if (ssey) ++ssey; a = GetAddrHexWidth() + 1 + DUMPWIDTH; b = DISPWIDTH + 1; c = GetAddrHexWidth() + 1 + DISWIDTH; dx[1] = txn >= a + b ? txn - a : txn; dx[0] = txn >= c + b + a ? txn - a - b : dx[1]; yn = tyn - 1; a = 1 / 8. * yn; b = 3 / 8. * yn; c2y[0] = a * .7; c2y[1] = a * 2; c2y[2] = a * 2 + b; if (yn - c2y[2] > 26) { c2y[1] -= yn - c2y[2] - 26; c2y[2] = yn - 26; } if (yn - c2y[2] < 26) { c2y[2] = yn - 26; } a = (yn - (cpuy + ssey) - 3) / 4; c3y[0] = cpuy; c3y[1] = cpuy + ssey; c3y[2] = cpuy + ssey + 1 + 1 + a * 1; c3y[3] = cpuy + ssey + 1 + 1 + a * 2 + 1; c3y[4] = cpuy + ssey + 1 + 1 + 1 + a * 3 + 1; /* COLUMN #1: DISASSEMBLY */ pan.disassembly.top = 0; pan.disassembly.left = 0; pan.disassembly.bottom = yn; pan.disassembly.right = dx[0] - 1; /* COLUMN #2: BREAKPOINTS, MEMORY MAPS, BACKTRACE, DISPLAY */ pan.breakpointshr.top = 0; pan.breakpointshr.left = dx[0]; pan.breakpointshr.bottom = 1; pan.breakpointshr.right = dx[1] - 1; pan.breakpoints.top = 1; pan.breakpoints.left = dx[0]; pan.breakpoints.bottom = c2y[0]; pan.breakpoints.right = dx[1] - 1; pan.mapshr.top = c2y[0]; pan.mapshr.left = dx[0]; pan.mapshr.bottom = c2y[0] + 1; pan.mapshr.right = dx[1] - 1; pan.maps.top = c2y[0] + 1; pan.maps.left = dx[0]; pan.maps.bottom = c2y[1]; pan.maps.right = dx[1] - 1; pan.frameshr.top = c2y[1]; pan.frameshr.left = dx[0]; pan.frameshr.bottom = c2y[1] + 1; pan.frameshr.right = dx[1] - 1; pan.frames.top = c2y[1] + 1; pan.frames.left = dx[0]; pan.frames.bottom = c2y[2]; pan.frames.right = dx[1] - 1; pan.displayhr.top = c2y[2]; pan.displayhr.left = dx[0]; pan.displayhr.bottom = c2y[2] + 1; pan.displayhr.right = dx[1] - 1; pan.display.top = c2y[2] + 1; pan.display.left = dx[0]; pan.display.bottom = yn; pan.display.right = dx[1] - 1; /* COLUMN #3: REGISTERS, VECTORS, CODE, MEMORY READS, MEMORY WRITES, STACK */ pan.registers.top = 0; pan.registers.left = dx[1]; pan.registers.bottom = c3y[0]; pan.registers.right = txn; pan.ssehr.top = c3y[0]; pan.ssehr.left = dx[1]; pan.ssehr.bottom = c3y[0] + (ssey ? 1 : 0); pan.ssehr.right = txn; pan.sse.top = c3y[0] + (ssey ? 1 : 0); pan.sse.left = dx[1]; pan.sse.bottom = c3y[1]; pan.sse.right = txn; pan.codehr.top = c3y[1]; pan.codehr.left = dx[1]; pan.codehr.bottom = c3y[1] + 1; pan.codehr.right = txn; pan.code.top = c3y[1] + 1; pan.code.left = dx[1]; pan.code.bottom = c3y[2]; pan.code.right = txn; pan.readhr.top = c3y[2]; pan.readhr.left = dx[1]; pan.readhr.bottom = c3y[2] + 1; pan.readhr.right = txn; pan.readdata.top = c3y[2] + 1; pan.readdata.left = dx[1]; pan.readdata.bottom = c3y[3]; pan.readdata.right = txn; pan.writehr.top = c3y[3]; pan.writehr.left = dx[1]; pan.writehr.bottom = c3y[3] + 1; pan.writehr.right = txn; pan.writedata.top = c3y[3] + 1; pan.writedata.left = dx[1]; pan.writedata.bottom = c3y[4]; pan.writedata.right = txn; pan.stackhr.top = c3y[4]; pan.stackhr.left = dx[1]; pan.stackhr.bottom = c3y[4] + 1; pan.stackhr.right = txn; pan.stack.top = c3y[4] + 1; pan.stack.left = dx[1]; pan.stack.bottom = yn; pan.stack.right = txn; pan.status.top = yn; pan.status.left = 0; pan.status.bottom = yn + 1; pan.status.right = txn; for (i = 0; i < ARRAYLEN(pan.p); ++i) { if (pan.p[i].left > pan.p[i].right) { pan.p[i].left = pan.p[i].right = 0; } if (pan.p[i].top > pan.p[i].bottom) { pan.p[i].top = pan.p[i].bottom = 0; } n = pan.p[i].bottom - pan.p[i].top; if (n == pan.p[i].n) { for (j = 0; j < n; ++j) { pan.p[i].lines[j].i = 0; } } else { for (j = 0; j < pan.p[i].n; ++j) { free(pan.p[i].lines[j].p); } free(pan.p[i].lines); pan.p[i].lines = xcalloc(n, sizeof(struct Buffer)); pan.p[i].n = n; } } PtyResize(pty, pan.display.bottom - pan.display.top, pan.display.right - pan.display.left); } static long Disassemble(void) { long lines, current; lines = pan.disassembly.bottom - pan.disassembly.top * 2; if (Dis(dis, m, GetIp(), m->ip, lines) != -1) { return DisFind(dis, GetIp()); } else { return -1; } } static long GetDisIndex(void) { long i; if ((i = DisFind(dis, GetIp())) == -1) { i = Disassemble(); } while (i + 1 < dis->ops.i && !dis->ops.p[i].size) ++i; return i; } static void DrawDisassembly(struct Panel *p) { long i, j; for (i = 0; i < p->bottom - p->top; ++i) { j = opstart + i; if (0 <= j && j < dis->ops.i) { if (j == opline) AppendPanel(p, i, "\e[7m"); AppendPanel(p, i, DisGetLine(dis, m, j)); if (j == opline) AppendPanel(p, i, "\e[27m"); } } } static void DrawHr(struct Panel *p, const char *s) { long i, wp, ws, wl, wr; if (p->bottom - p->top < 1) return; wp = p->right - p->left; ws = strwidth(s, 0); wl = wp / 4 - ws / 2; wr = wp - (wl + ws); for (i = 0; i < wl; ++i) AppendWide(&p->lines[0], u'─'); AppendStr(&p->lines[0], s); for (i = 0; i < wr; ++i) AppendWide(&p->lines[0], u'─'); AppendStr(&p->lines[0], "\e[0m"); } static void DrawTerminalHr(struct Panel *p) { long i; if (p->bottom == p->top) return; if (pty->conf & kPtyBell) { if (!alarmed) { alarmed = true; setitimer(ITIMER_REAL, &((struct itimerval){{0, 0}, {0, 800000}}), NULL); } AppendStr(&p->lines[0], "\e[1m"); } AppendFmt(&p->lines[0], "──────────TELETYPEWRITER──%s──%s──%s──%s", (pty->conf & kPtyLed1) ? "\e[1;31m◎\e[0m" : "○", (pty->conf & kPtyLed2) ? "\e[1;32m◎\e[0m" : "○", (pty->conf & kPtyLed3) ? "\e[1;33m◎\e[0m" : "○", (pty->conf & kPtyLed4) ? "\e[1;34m◎\e[0m" : "○"); for (i = 36; i < p->right - p->left; ++i) { AppendWide(&p->lines[0], u'─'); } } static void DrawTerminal(struct Panel *p) { long y, yn; if (p->top == p->bottom) return; for (yn = MIN(pty->yn, p->bottom - p->top), y = 0; y < yn; ++y) { PtyAppendLine(pty, p->lines + y, y); AppendStr(p->lines + y, "\e[0m"); } } static void DrawDisplay(struct Panel *p) { switch (vidya) { case 7: DrawHr(&pan.displayhr, "MONOCHROME DISPLAY ADAPTER"); if (0xb0000 + 25 * 80 * 2 > m->real.n) return; DrawMda(p, (void *)(m->real.p + 0xb0000)); break; case 3: DrawHr(&pan.displayhr, "COLOR GRAPHICS ADAPTER"); if (0xb8000 + 25 * 80 * 2 > m->real.n) return; DrawCga(p, (void *)(m->real.p + 0xb8000)); break; default: DrawTerminalHr(&pan.displayhr); DrawTerminal(p); break; } } static void DrawFlag(struct Panel *p, long i, char name, bool value) { char str[3] = " "; if (value) str[1] = name; AppendPanel(p, i, str); } static void DrawRegister(struct Panel *p, long i, long r) { char buf[32]; uint64_t value, previous; value = Read64(m->reg[r]); previous = Read64(laststate.reg[r]); if (value != previous) AppendPanel(p, i, "\e[7m"); snprintf(buf, sizeof(buf), "%-3s", kRegisterNames[m->mode & 3][r]); AppendPanel(p, i, buf); AppendPanel(p, i, " "); snprintf(buf, sizeof(buf), "%0*lx", GetRegHexWidth(), value); AppendPanel(p, i, buf); if (value != previous) AppendPanel(p, i, "\e[27m"); AppendPanel(p, i, " "); } static void DrawSegment(struct Panel *p, long i, const uint8_t seg[8], const uint8_t last[8], const char *name) { char buf[32]; uint64_t value, previous; value = Read64(seg); previous = Read64(last); if (value != previous) AppendPanel(p, i, "\e[7m"); snprintf(buf, sizeof(buf), "%-3s", name); AppendPanel(p, i, buf); AppendPanel(p, i, " "); if ((m->mode & 3) == XED_MODE_REAL) { snprintf(buf, sizeof(buf), "%0*lx", GetRegHexWidth(), value >> 4); } else { snprintf(buf, sizeof(buf), "%0*lx", GetRegHexWidth(), value); } AppendPanel(p, i, buf); if (value != previous) AppendPanel(p, i, "\e[27m"); AppendPanel(p, i, " "); } static void DrawSt(struct Panel *p, long i, long r) { char buf[32]; long double value; bool isempty, changed; isempty = FpuGetTag(m, r) == kFpuTagEmpty; if (isempty) AppendPanel(p, i, "\e[38;5;241m"); value = m->fpu.st[(r + m->fpu.sp) & 0b111]; changed = value != laststate.fpu.st[(r + m->fpu.sp) & 0b111]; if (!isempty && changed) AppendPanel(p, i, "\e[7m"); snprintf(buf, sizeof(buf), "ST%d ", r); AppendPanel(p, i, buf); AppendPanel(p, i, FormatDouble(buf, value)); if (changed) AppendPanel(p, i, "\e[27m"); AppendPanel(p, i, " "); if (isempty) AppendPanel(p, i, "\e[39m"); } static void DrawCpu(struct Panel *p) { char buf[48]; if (p->top == p->bottom) return; DrawRegister(p, 0, 7), DrawRegister(p, 0, 0), DrawSt(p, 0, 0); DrawRegister(p, 1, 6), DrawRegister(p, 1, 3), DrawSt(p, 1, 1); DrawRegister(p, 2, 2), DrawRegister(p, 2, 5), DrawSt(p, 2, 2); DrawRegister(p, 3, 1), DrawRegister(p, 3, 4), DrawSt(p, 3, 3); DrawRegister(p, 4, 8), DrawRegister(p, 4, 12), DrawSt(p, 4, 4); DrawRegister(p, 5, 9), DrawRegister(p, 5, 13), DrawSt(p, 5, 5); DrawRegister(p, 6, 10), DrawRegister(p, 6, 14), DrawSt(p, 6, 6); DrawRegister(p, 7, 11), DrawRegister(p, 7, 15), DrawSt(p, 7, 7); snprintf(buf, sizeof(buf), "%-3s %0*x FLG", kRipName[m->mode & 3], GetRegHexWidth(), m->ip); AppendPanel(p, 8, buf); DrawFlag(p, 8, 'C', GetFlag(m->flags, FLAGS_CF)); DrawFlag(p, 8, 'P', GetFlag(m->flags, FLAGS_PF)); DrawFlag(p, 8, 'A', GetFlag(m->flags, FLAGS_AF)); DrawFlag(p, 8, 'Z', GetFlag(m->flags, FLAGS_ZF)); DrawFlag(p, 8, 'S', GetFlag(m->flags, FLAGS_SF)); DrawFlag(p, 8, 'I', GetFlag(m->flags, FLAGS_IF)); DrawFlag(p, 8, 'D', GetFlag(m->flags, FLAGS_DF)); DrawFlag(p, 8, 'O', GetFlag(m->flags, FLAGS_OF)); AppendPanel(p, 8, " "); if (m->fpu.ie) AppendPanel(p, 8, " IE"); if (m->fpu.de) AppendPanel(p, 8, " DE"); if (m->fpu.ze) AppendPanel(p, 8, " ZE"); if (m->fpu.oe) AppendPanel(p, 8, " OE"); if (m->fpu.ue) AppendPanel(p, 8, " UE"); if (m->fpu.pe) AppendPanel(p, 8, " PE"); if (m->fpu.sf) AppendPanel(p, 8, " SF"); if (m->fpu.es) AppendPanel(p, 8, " ES"); if (m->fpu.c0) AppendPanel(p, 8, " C0"); if (m->fpu.c1) AppendPanel(p, 8, " C1"); if (m->fpu.c2) AppendPanel(p, 8, " C2"); if (m->fpu.bf) AppendPanel(p, 8, " BF"); DrawSegment(p, 9, m->fs, laststate.fs, "FS"); DrawSegment(p, 9, m->ds, laststate.ds, "DS"); DrawSegment(p, 9, m->cs, laststate.cs, "CS"); DrawSegment(p, 10, m->gs, laststate.gs, "GS"); DrawSegment(p, 10, m->es, laststate.es, "ES"); DrawSegment(p, 10, m->ss, laststate.ss, "SS"); } static void DrawXmm(struct Panel *p, long i, long r) { float f; double d; long j, k, n; bool changed; char buf[32]; uint8_t xmm[16]; uint64_t ival, itmp; int cells, left, cellwidth, panwidth; memcpy(xmm, m->xmm[r], sizeof(xmm)); changed = memcmp(xmm, laststate.xmm[r], sizeof(xmm)) != 0; if (changed) AppendPanel(p, i, "\e[7m"); left = sprintf(buf, "XMM%-2d", r); AppendPanel(p, i, buf); cells = GetXmmTypeCellCount(r); panwidth = p->right - p->left; cellwidth = MIN(MAX(0, (panwidth - left) / cells - 1), sizeof(buf) - 1); for (j = 0; j < cells; ++j) { AppendPanel(p, i, " "); switch (xmmtype.type[r]) { case kXmmFloat: memcpy(&f, xmm + j * sizeof(f), sizeof(f)); FormatDouble(buf, f); break; case kXmmDouble: memcpy(&d, xmm + j * sizeof(d), sizeof(d)); FormatDouble(buf, d); break; case kXmmIntegral: ival = 0; for (k = 0; k < xmmtype.size[r]; ++k) { itmp = xmm[j * xmmtype.size[r] + k] & 0xff; itmp <<= k * 8; ival |= itmp; } if (xmmdisp == kXmmHex || xmmdisp == kXmmChar) { if (xmmdisp == kXmmChar && iswalnum(ival)) { sprintf(buf, "%lc", ival); } else { uint64toarray_fixed16(ival, buf, xmmtype.size[r] * 8); } } else { FormatInt64(buf, SignExtend(ival, xmmtype.size[r] * 8)); } break; default: unreachable; } buf[cellwidth] = '\0'; AppendPanel(p, i, buf); n = cellwidth - strlen(buf); for (k = 0; k < n; ++k) { AppendPanel(p, i, " "); } } if (changed) AppendPanel(p, i, "\e[27m"); } static void DrawSse(struct Panel *p) { long i, n; n = p->bottom - p->top; if (n > 0) { for (i = 0; i < MIN(16, n); ++i) { DrawXmm(p, i, i); } } } static void ScrollMemoryView(struct Panel *p, struct MemoryView *v, int64_t a) { long i, n, w; w = DUMPWIDTH * (1ull << v->zoom); n = p->bottom - p->top; i = a / w; if (!(v->start <= i && i < v->start + n)) { v->start = i - n / 4; } } static void ZoomMemoryView(struct MemoryView *v, long y, long x, int dy) { long a, b, i, s; s = v->start; a = v->zoom; b = MIN(MAXZOOM, MAX(0, a + dy)); i = y * DUMPWIDTH - x; s *= DUMPWIDTH * (1L << a); s += i * (1L << a) - i * (1L << b); s /= DUMPWIDTH * (1L << b); v->zoom = b; v->start = s; } static void ScrollMemoryViews(void) { ScrollMemoryView(&pan.code, &codeview, GetIp()); ScrollMemoryView(&pan.readdata, &readview, readaddr); ScrollMemoryView(&pan.writedata, &writeview, writeaddr); ScrollMemoryView(&pan.stack, &stackview, GetSp()); } static void ZoomMemoryViews(struct Panel *p, int y, int x, int dy) { if (p == &pan.code) { ZoomMemoryView(&codeview, y, x, dy); } else if (p == &pan.readdata) { ZoomMemoryView(&readview, y, x, dy); } else if (p == &pan.writedata) { ZoomMemoryView(&writeview, y, x, dy); } else if (p == &pan.stack) { ZoomMemoryView(&stackview, y, x, dy); } } static void DrawMemoryZoomed(struct Panel *p, struct MemoryView *view, long histart, long hiend) { bool high, changed; uint8_t *canvas, *chunk, *invalid; int64_t a, b, c, d, n, i, j, k, size; struct ContiguousMemoryRanges ranges; a = view->start * DUMPWIDTH * (1ull << view->zoom); b = (view->start + (p->bottom - p->top)) * DUMPWIDTH * (1ull << view->zoom); size = (p->bottom - p->top) * DUMPWIDTH; canvas = xcalloc(1, size); invalid = xcalloc(1, size); bzero(&ranges, sizeof(ranges)); FindContiguousMemoryRanges(m, &ranges); for (k = i = 0; i < ranges.i; ++i) { if ((a >= ranges.p[i].a && a < ranges.p[i].b) || (b >= ranges.p[i].a && b < ranges.p[i].b) || (a < ranges.p[i].a && b >= ranges.p[i].b)) { c = MAX(a, ranges.p[i].a); d = MIN(b, ranges.p[i].b); n = ROUNDUP(ROUNDUP(d - c, 16), 1ull << view->zoom); chunk = xmalloc(n); VirtualSend(m, chunk, c, d - c); bzero(chunk + (d - c), n - (d - c)); for (j = 0; j < view->zoom; ++j) { cDecimate2xUint8x8(ROUNDUP(n, 16), chunk, kThePerfectKernel); n >>= 1; } j = (c - a) / (1ull << view->zoom); memset(invalid + k, -1, j - k); memcpy(canvas + j, chunk, MIN(n, size - j)); k = j + MIN(n, size - j); free(chunk); } } memset(invalid + k, -1, size - k); free(ranges.p); high = false; for (c = i = 0; i < p->bottom - p->top; ++i) { AppendFmt(&p->lines[i], "%0*lx ", GetAddrHexWidth(), ((view->start + i) * DUMPWIDTH * (1ull << view->zoom)) & 0x0000ffffffffffff); for (j = 0; j < DUMPWIDTH; ++j, ++c) { a = ((view->start + i) * DUMPWIDTH + j + 0) * (1ull << view->zoom); b = ((view->start + i) * DUMPWIDTH + j + 1) * (1ull << view->zoom); changed = ((histart >= a && hiend < b) || (histart && hiend && histart >= a && hiend < b)); if (changed && !high) { high = true; AppendStr(&p->lines[i], "\e[7m"); } else if (!changed && high) { AppendStr(&p->lines[i], "\e[27m"); high = false; } if (invalid[c]) { AppendWide(&p->lines[i], u'⋅'); } else { AppendWide(&p->lines[i], kCp437[canvas[c]]); } } if (high) { AppendStr(&p->lines[i], "\e[27m"); high = false; } } free(invalid); free(canvas); } static void DrawMemoryUnzoomed(struct Panel *p, struct MemoryView *view, long histart, long hiend) { long i, j, k; int c, s, x, sc; bool high, changed; high = false; for (i = 0; i < p->bottom - p->top; ++i) { AppendFmt(&p->lines[i], "%0*lx ", GetAddrHexWidth(), ((view->start + i) * DUMPWIDTH) & 0x0000ffffffffffff); for (j = 0; j < DUMPWIDTH; ++j) { k = (view->start + i) * DUMPWIDTH + j; c = VirtualBing(k); s = VirtualShadow(k); if (s != -1) { if (s == -2) { /* grey for shadow memory */ x = 235; } else { sc = (signed char)s; if (sc > 7) { x = 129; /* PURPLE: shadow corruption */ } else if (sc == kAsanHeapFree) { x = 20; /* BLUE: heap freed */ } else if (sc == kAsanHeapRelocated) { x = 16; /* BLACK: heap relocated */ } else if (sc == kAsanHeapUnderrun || sc == kAsanAllocaUnderrun) { x = 53; /* RED+PURPLETINGE: heap underrun */ } else if (sc == kAsanHeapOverrun || sc == kAsanAllocaOverrun) { x = 52; /* RED: heap overrun */ } else if (sc < 0) { x = 52; /* RED: uncategorized invalid */ } else if (sc > 0 && (k & 7) >= sc) { x = 88; /* BRIGHTRED: invalid address (skew) */ } else if (!sc || (sc > 0 && (k & 7) < sc)) { x = 22; /* GREEN: valid address */ } else { abort(); } } AppendFmt(&p->lines[i], "\e[38;5;253;48;5;%dm", x); } changed = histart <= k && k < hiend; if (changed && !high) { high = true; AppendStr(&p->lines[i], "\e[7m"); } else if (!changed && high) { AppendStr(&p->lines[i], "\e[27m"); high = false; } AppendWide(&p->lines[i], c); if (s != -1) { AppendStr(&p->lines[i], "\e[39;49m"); } } if (high) { AppendStr(&p->lines[i], "\e[27m"); high = false; } } } static void DrawMemory(struct Panel *p, struct MemoryView *view, long histart, long hiend) { if (p->top == p->bottom) return; if (view->zoom) { DrawMemoryZoomed(p, view, histart, hiend); } else { DrawMemoryUnzoomed(p, view, histart, hiend); } } static void DrawMaps(struct Panel *p) { int i; char *text, *p1, *p2; if (p->top == p->bottom) return; p1 = text = FormatPml4t(m); for (i = 0; p1; ++i, p1 = p2) { if ((p2 = strchr(p1, '\n'))) *p2++ = '\0'; if (i >= mapsstart) { AppendPanel(p, i - mapsstart, p1); } } free(text); } static void DrawBreakpoints(struct Panel *p) { int64_t addr; const char *name; char *s, buf[256]; long i, line, sym; if (p->top == p->bottom) return; for (line = 0, i = breakpoints.i; i--;) { if (breakpoints.p[i].disable) continue; if (line >= breakpointsstart) { addr = breakpoints.p[i].addr; sym = DisFindSym(dis, addr); name = sym != -1 ? dis->syms.stab + dis->syms.p[sym].name : "UNKNOWN"; s = buf; s += sprintf(s, "%0*lx ", GetAddrHexWidth(), addr & 0x0000ffffffffffff); CHECK_LT(Demangle(s, name, DIS_MAX_SYMBOL_LENGTH), buf + ARRAYLEN(buf)); AppendPanel(p, line - breakpointsstart, buf); if (sym != -1 && addr != dis->syms.p[sym].addr) { snprintf(buf, sizeof(buf), "+%#lx", addr - dis->syms.p[sym].addr); AppendPanel(p, line, buf); } } ++line; } } static int GetPreferredStackAlignmentMask(void) { switch (m->mode & 3) { case XED_MODE_LONG: return 15; case XED_MODE_LEGACY: return 3; case XED_MODE_REAL: return 3; default: unreachable; } } static void DrawFrames(struct Panel *p) { int i, n; long sym; uint8_t *r; const char *name; char *s, line[256]; int64_t sp, bp, rp; if (p->top == p->bottom) return; rp = m->ip; bp = Read64(m->bp); sp = Read64(m->sp); for (i = 0; i < p->bottom - p->top;) { sym = DisFindSym(dis, rp); name = sym != -1 ? dis->syms.stab + dis->syms.p[sym].name : "UNKNOWN"; s = line; s += sprintf(s, "%0*lx %0*lx ", GetAddrHexWidth(), (Read64(m->ss) + bp) & 0x0000ffffffffffff, GetAddrHexWidth(), rp & 0x0000ffffffffffff); s = Demangle(s, name, DIS_MAX_SYMBOL_LENGTH); AppendPanel(p, i - framesstart, line); if (sym != -1 && rp != dis->syms.p[sym].addr) { snprintf(line, sizeof(line), "+%#lx", rp - dis->syms.p[sym].addr); AppendPanel(p, i - framesstart, line); } if (!bp) break; if (bp < sp) { AppendPanel(p, i - framesstart, " [STRAY]"); } else if (bp - sp <= 0x1000) { snprintf(line, sizeof(line), " %,ld bytes", bp - sp); AppendPanel(p, i - framesstart, line); } if (bp & GetPreferredStackAlignmentMask() && i) { AppendPanel(p, i - framesstart, " [MISALIGN]"); } ++i; if (((Read64(m->ss) + bp) & 0xfff) > 0xff0) break; if (!(r = FindReal(m, Read64(m->ss) + bp))) { AppendPanel(p, i - framesstart, "CORRUPT FRAME POINTER"); break; } sp = bp; bp = ReadWord(r + 0); rp = ReadWord(r + 8); } } static void CheckFramePointerImpl(void) { uint8_t *r; int64_t bp, sp, rp; static int64_t lastbp; bp = Read64(m->bp); if (bp && bp == lastbp) return; lastbp = bp; rp = m->ip; sp = Read64(m->sp); while (bp) { if (!(r = FindReal(m, Read64(m->ss) + bp))) { INFOF("corrupt frame: %0*lx", GetAddrHexWidth(), bp & 0x0000ffffffffffff); ThrowProtectionFault(m); } sp = bp; bp = Read64(r + 0) - 0; rp = Read64(r + 8) - 1; if (!bp && !(m->bofram[0] <= rp && rp <= m->bofram[1])) { INFOF("bad frame !(%0*lx <= %0*lx <= %0*lx)", GetAddrHexWidth(), m->bofram[0], GetAddrHexWidth(), rp, GetAddrHexWidth(), m->bofram[1]); ThrowProtectionFault(m); } } } forceinline void CheckFramePointer(void) { if (m->bofram[0]) { CheckFramePointerImpl(); } } static bool IsExecuting(void) { return (action & (CONTINUE | STEP | NEXT | FINISH)) && !(action & FAILURE); } static int AppendStat(struct Buffer *b, const char *name, int64_t value, bool changed) { int width; AppendChar(b, ' '); if (changed) AppendStr(b, "\e[31m"); width = AppendFmt(b, "%,8ld %s", value, name); if (changed) AppendStr(b, "\e[39m"); return 1 + width; } static char *GetStatus(int m) { bool first; char *b = 0; unsigned i, n; long double t; if (statusmessage && nowl() < statusexpires) { appends(&b, statusmessage); } else { appends(&b, "das blinkenlights"); } n = ARRAYLEN(keystrokes.p); for (first = true, t = nowl(), i = 1; i <= n; --i) { if (!keystrokes.p[(keystrokes.i - i) % n][0]) continue; if (t - keystrokes.s[(keystrokes.i - i) % n] > 1) continue; if (first) { first = false; appends(&b, " (keystroke: "); } else { appendw(&b, ' '); } appends(&b, keystrokes.p[(keystrokes.i - i) % n]); } if (!first) { appendw(&b, ')'); } if (action & RESTART) appends(&b, " RESTART"); if (action & REDRAW) appends(&b, " REDRAW"); if (action & CONTINUE) appends(&b, " CONTINUE"); if (action & STEP) appends(&b, " STEP"); if (action & NEXT) appends(&b, " NEXT"); if (action & FINISH) appends(&b, " FINISH"); if (action & FAILURE) appends(&b, " FAILURE"); if (action & WINCHED) appends(&b, " WINCHED"); if (action & INT) appends(&b, " INT"); if (action & QUIT) appends(&b, " QUIT"); if (action & EXIT) appends(&b, " EXIT"); if (action & ALARM) appends(&b, " ALARM"); return b; } static void DrawStatus(struct Panel *p) { int yn, xn, rw; struct Buffer *s; struct MachineMemstat *a, *b; yn = p->top - p->bottom; xn = p->right - p->left; if (!yn || !xn) return; rw = 0; a = &m->memstat; b = &lastmemstat; s = xmalloc(sizeof(struct Buffer)); bzero(s, sizeof(*s)); if (ips > 0) rw += AppendStat(s, "ips", ips, false); rw += AppendStat(s, "kb", m->real.n / 1024, false); rw += AppendStat(s, "reserve", a->reserved, a->reserved != b->reserved); rw += AppendStat(s, "commit", a->committed, a->committed != b->committed); rw += AppendStat(s, "freed", a->freed, a->freed != b->freed); rw += AppendStat(s, "tables", a->pagetables, a->pagetables != b->pagetables); rw += AppendStat(s, "fds", m->fds.i, false); AppendFmt(&p->lines[0], "\e[7m%-*s%s\e[0m", xn - rw, _gc(GetStatus(xn - rw)), s->p); free(s->p); free(s); memcpy(b, a, sizeof(*a)); } static void PreventBufferbloat(void) { long double now, rate; static long double last; now = nowl(); rate = 1. / 60; if (now - last < rate) { dsleep(rate - (now - last)); } last = now; } static void Redraw(void) { int i, j; if (belay) return; oldlen = m->xedd->length; if (!IsShadow(m->readaddr) && !IsShadow(m->readaddr + m->readsize)) { readaddr = m->readaddr; readsize = m->readsize; } if (!IsShadow(m->writeaddr) && !IsShadow(m->writeaddr + m->writesize)) { writeaddr = m->writeaddr; writesize = m->writesize; } ScrollOp(&pan.disassembly, GetDisIndex()); if (last_opcount) { ips = unsignedsubtract(opcount, last_opcount) / (nowl() - last_seconds); } SetupDraw(); for (i = 0; i < ARRAYLEN(pan.p); ++i) { for (j = 0; j < pan.p[i].bottom - pan.p[i].top; ++j) { pan.p[i].lines[j].i = 0; } } DrawDisassembly(&pan.disassembly); DrawDisplay(&pan.display); DrawCpu(&pan.registers); DrawSse(&pan.sse); DrawHr(&pan.breakpointshr, "BREAKPOINTS"); DrawHr(&pan.mapshr, "PML4T"); DrawHr(&pan.frameshr, m->bofram[0] ? "PROTECTED FRAMES" : "FRAMES"); DrawHr(&pan.ssehr, "SSE"); DrawHr(&pan.codehr, "CODE"); DrawHr(&pan.readhr, "READ"); DrawHr(&pan.writehr, "WRITE"); DrawHr(&pan.stackhr, "STACK"); DrawMaps(&pan.maps); DrawFrames(&pan.frames); DrawBreakpoints(&pan.breakpoints); DrawMemory(&pan.code, &codeview, GetIp(), GetIp() + m->xedd->length); DrawMemory(&pan.readdata, &readview, readaddr, readaddr + readsize); DrawMemory(&pan.writedata, &writeview, writeaddr, writeaddr + writesize); DrawMemory(&pan.stack, &stackview, GetSp(), GetSp() + GetPointerWidth()); DrawStatus(&pan.status); PreventBufferbloat(); if (PrintPanels(ttyout, ARRAYLEN(pan.p), pan.p, tyn, txn) == -1) { INFOF("PrintPanels Interrupted"); CHECK_EQ(EINTR, errno); } last_opcount = opcount; last_seconds = nowl(); CopyMachineState(&laststate); } static void ReactiveDraw(void) { if (tuimode) { Redraw(); tick = speed; } } static void DescribeKeystroke(char *b, const char *p) { int c; do { c = *p++ & 255; if (c == '\e') { b = stpcpy(b, "ALT-"); c = *p++ & 255; } if (c <= 32) { b = stpcpy(b, "CTRL-"); c = CTRL(c); } *b++ = c; *b = 0; } while (*p); } static void RecordKeystroke(const char *k) { keystrokes.s[keystrokes.i] = nowl(); DescribeKeystroke(keystrokes.p[keystrokes.i], k); keystrokes.i = (keystrokes.i + 1) % ARRAYLEN(keystrokes.p); } static void HandleAlarm(void) { alarmed = false; action &= ~ALARM; pty->conf &= ~kPtyBell; free(statusmessage); statusmessage = NULL; } static void HandleAppReadInterrupt(void) { DEBUGF("HandleAppReadInterrupt"); if (action & ALARM) { HandleAlarm(); } if (action & WINCHED) { GetTtySize(ttyout); action &= ~WINCHED; } if (action & INT) { action &= ~INT; RecordKeystroke("\3"); ReactiveDraw(); if (action & CONTINUE) { action &= ~CONTINUE; } else { if (tuimode) { LeaveScreen(); TuiCleanup(); } exit(0); } } } static int OnPtyFdClose(int fd) { return close(fd); } static bool HasPendingInput(int fd) { struct pollfd fds[1]; fds[0].fd = fd; fds[0].events = POLLIN; fds[0].revents = 0; poll(fds, ARRAYLEN(fds), 0); return fds[0].revents & (POLLIN | POLLERR); } static struct Panel *LocatePanel(int y, int x) { int i; for (i = 0; i < ARRAYLEN(pan.p); ++i) { if ((pan.p[i].left <= x && x < pan.p[i].right) && (pan.p[i].top <= y && y < pan.p[i].bottom)) { return &pan.p[i]; } } return NULL; } static struct Mouse ParseMouse(char *p) { int e, x, y; struct Mouse m; e = strtol(p, &p, 10); if (*p == ';') ++p; x = min(txn, max(1, strtol(p, &p, 10))) - 1; if (*p == ';') ++p; y = min(tyn, max(1, strtol(p, &p, 10))) - 1; e |= (*p == 'm') << 2; m.y = y; m.x = x; m.e = e; return m; } static ssize_t ReadAnsi(int fd, char *p, size_t n) { ssize_t rc; struct Mouse m; for (;;) { ReactiveDraw(); if ((rc = readansi(fd, p, n)) != -1) { if (tuimode && rc > 3 && p[0] == '\e' && p[1] == '[') { if (p[2] == '2' && p[3] == '0' && p[4] == '0' && p[5] == '~') { belay = true; continue; } if (p[2] == '2' && p[3] == '0' && p[4] == '1' && p[5] == '~') { belay = false; continue; } if (p[2] == '<') { m = ParseMouse(p + 3); if (LocatePanel(m.y, m.x) != &pan.display) { HandleKeyboard(p); continue; } } } return rc; } else { CHECK_EQ(EINTR, errno); HandleAppReadInterrupt(); } } } static ssize_t ReadPtyFdDirect(int fd) { ssize_t rc; char buf[32]; pty->conf |= kPtyBlinkcursor; rc = ReadAnsi(fd, buf, sizeof(buf)); pty->conf &= ~kPtyBlinkcursor; if (rc > 0) { PtyWriteInput(pty, buf, rc); ReactiveDraw(); rc = 0; } return rc; } static ssize_t OnPtyFdReadv(int fd, const struct iovec *iov, int iovlen) { int i; ssize_t rc; void *data; size_t size; for (size = i = 0; i < iovlen; ++i) { if (iov[i].iov_len) { data = iov[i].iov_base; size = iov[i].iov_len; break; } } if (size) { for (;;) { if ((rc = PtyRead(pty, data, size))) { return rc; } if (ReadPtyFdDirect(fd) == -1) { return -1; } } } else { return 0; } } static int OnPtyFdPoll(struct pollfd *fds, size_t nfds, int ms) { bool once, rem; int i, t, re, rc; struct pollfd p2; ms &= INT_MAX; for (once = t = i = 0; i < nfds; ++i) { re = 0; if (fds[i].fd >= 0) { if (pty->input.i) { re = POLLIN | POLLOUT; ++t; } else { if (!once) { ReactiveDraw(); once = true; } p2.fd = fds[i].fd; p2.events = fds[i].events; if (!IsWindows()) { switch (poll(&p2, 1, ms)) { case -1: re = POLLERR; ++t; break; case 0: break; case 1: re = p2.revents; ++t; break; default: unreachable; } } } } fds[i].revents = re; } return t; } static void DrawDisplayOnly(struct Panel *p) { struct Buffer b; int i, y, yn, xn, tly, tlx, conf; yn = MIN(tyn, p->bottom - p->top); xn = MIN(txn, p->right - p->left); for (i = 0; i < yn; ++i) { p->lines[i].i = 0; } DrawDisplay(p); bzero(&b, sizeof(b)); tly = tyn / 2 - yn / 2; tlx = txn / 2 - xn / 2; AppendStr(&b, "\e[0m\e[H"); for (y = 0; y < tyn; ++y) { if (y) AppendStr(&b, "\r\n"); if (tly <= y && y <= tly + yn) { for (i = 0; i < tlx; ++i) { AppendChar(&b, ' '); } AppendData(&b, p->lines[y - tly].p, p->lines[y - tly].i); } AppendStr(&b, "\e[0m\e[K"); } write(ttyout, b.p, b.i); free(b.p); } static ssize_t OnPtyFdWritev(int fd, const struct iovec *iov, int iovlen) { int i; size_t size; for (size = i = 0; i < iovlen; ++i) { PtyWrite(pty, iov[i].iov_base, iov[i].iov_len); size += iov[i].iov_len; } return size; } static int OnPtyFdTiocgwinsz(int fd, struct winsize *ws) { ws->ws_row = pty->yn; ws->ws_col = pty->xn; return 0; } static int OnPtyFdTcgets(int fd, struct termios *c) { bzero(c, sizeof(*c)); if (!(pty->conf & kPtyNocanon)) c->c_iflag |= ICANON; if (!(pty->conf & kPtyNoecho)) c->c_iflag |= ECHO; if (!(pty->conf & kPtyNoopost)) c->c_oflag |= OPOST; return 0; } static int OnPtyFdTcsets(int fd, uint64_t request, struct termios *c) { if (c->c_iflag & ICANON) { pty->conf &= ~kPtyNocanon; } else { pty->conf |= kPtyNocanon; } if (c->c_iflag & ECHO) { pty->conf &= ~kPtyNoecho; } else { pty->conf |= kPtyNoecho; } if (c->c_oflag & OPOST) { pty->conf &= ~kPtyNoopost; } else { pty->conf |= kPtyNoopost; } return 0; } static int OnPtyFdIoctl(int fd, int request, void *memory) { if (request == TIOCGWINSZ) { return OnPtyFdTiocgwinsz(fd, memory); } else if (request == TCGETS) { return OnPtyFdTcgets(fd, memory); } else if (request == TCSETS || request == TCSETSW || request == TCSETSF) { return OnPtyFdTcsets(fd, request, memory); } else { return einval(); } } static const struct MachineFdCb kMachineFdCbPty = { .close = OnPtyFdClose, .readv = OnPtyFdReadv, .writev = OnPtyFdWritev, .ioctl = (void *)OnPtyFdIoctl, .poll = OnPtyFdPoll, }; static void LaunchDebuggerReactively(void) { INFOF("%s", systemfailure); if (tuimode) { action |= FAILURE; } else { if (react) { tuimode = true; action |= FAILURE; } else { fprintf(stderr, "ERROR: %s\n", systemfailure); exit(1); } } } static void OnDebug(void) { strcpy(systemfailure, "IT'S A TRAP"); LaunchDebuggerReactively(); } static void OnSegmentationFault(void) { snprintf(systemfailure, sizeof(systemfailure), "SEGMENTATION FAULT %0*lx", GetAddrHexWidth(), m->faultaddr & 0x0000ffffffffffff); LaunchDebuggerReactively(); } static void OnProtectionFault(void) { strcpy(systemfailure, "PROTECTION FAULT"); LaunchDebuggerReactively(); } static void OnSimdException(void) { strcpy(systemfailure, "SIMD FAULT"); LaunchDebuggerReactively(); } static void OnUndefinedInstruction(void) { strcpy(systemfailure, "UNDEFINED INSTRUCTION"); LaunchDebuggerReactively(); } static void OnDecodeError(void) { strcpy(stpcpy(systemfailure, "DECODE: "), IndexDoubleNulString(kXedErrorNames, m->xedd->op.error)); LaunchDebuggerReactively(); } static void OnDivideError(void) { strcpy(systemfailure, "DIVIDE BY ZERO OR BANE/-1"); LaunchDebuggerReactively(); } static void OnFpuException(void) { strcpy(systemfailure, "FPU EXCEPTION"); LaunchDebuggerReactively(); } static void OnExit(int rc) { exitcode = rc; action |= EXIT; } static size_t GetLastIndex(size_t size, unsigned unit, int i, unsigned limit) { unsigned q, r; if (!size) return 0; q = size / unit; r = size % unit; if (!r) --q; q += i; if (q > limit) q = limit; return q; } static void OnDiskServiceReset(void) { m->ax[1] = 0x00; SetCarry(false); } static void OnDiskServiceBadCommand(void) { m->ax[1] = 0x01; SetCarry(true); } static void OnDiskServiceGetParams(void) { size_t lastsector, lastcylinder, lasthead; lastcylinder = GetLastIndex(elf->mapsize, 512 * 63 * 255, 0, 1023); lasthead = GetLastIndex(elf->mapsize, 512 * 63, 0, 255); lastsector = GetLastIndex(elf->mapsize, 512, 1, 63); m->dx[0] = 1; m->dx[1] = lasthead; m->cx[0] = lastcylinder >> 8 << 6 | lastsector; m->cx[1] = lastcylinder; m->ax[1] = 0; Write64(m->es, 0); Write16(m->di, 0); SetCarry(false); } static void OnDiskServiceReadSectors(void) { static int x; uint64_t addr, size; int64_t sectors, drive, head, cylinder, sector, offset; sectors = m->ax[0]; drive = m->dx[0]; head = m->dx[1]; cylinder = (m->cx[0] & 0b11000000) << 2 | m->cx[1]; sector = (m->cx[0] & 0b00111111) - 1; size = sectors * 512; offset = sector * 512 + head * 512 * 63 + cylinder * 512 * 63 * 255; VERBOSEF("bios read sectors %d " "@ sector %ld cylinder %ld head %ld drive %ld offset %#lx", sectors, sector, cylinder, head, drive, offset); if (0 <= sector && offset + size <= elf->mapsize) { addr = Read64(m->es) + Read16(m->bx); if (addr + size <= m->real.n) { SetWriteAddr(m, addr, size); memcpy(m->real.p + addr, elf->map + offset, size); m->ax[1] = 0x00; SetCarry(false); } else { m->ax[0] = 0x00; m->ax[1] = 0x02; SetCarry(true); } } else { WARNF("bios read sector failed 0 <= %d && %lx + %lx <= %lx", sector, offset, size, elf->mapsize); m->ax[0] = 0x00; m->ax[1] = 0x0d; SetCarry(true); } } static void OnDiskService(void) { switch (m->ax[1]) { case 0x00: OnDiskServiceReset(); break; case 0x02: OnDiskServiceReadSectors(); break; case 0x08: OnDiskServiceGetParams(); break; default: OnDiskServiceBadCommand(); break; } } static void OnVidyaServiceSetMode(void) { if (FindReal(m, 0xB0000)) { vidya = m->ax[0]; } else { WARNF("maybe you forgot -r flag"); } } static void OnVidyaServiceGetMode(void) { m->ax[0] = vidya; m->ax[1] = 80; // columns m->bx[1] = 0; // page } static void OnVidyaServiceSetCursorPosition(void) { PtySetY(pty, m->dx[1]); PtySetX(pty, m->dx[0]); } static void OnVidyaServiceGetCursorPosition(void) { m->dx[1] = pty->y; m->dx[0] = pty->x; m->cx[1] = 5; // cursor ▂ scan lines 5..7 of 0..7 m->cx[0] = 7 | !!(pty->conf & kPtyNocursor) << 5; } static int GetVidyaByte(unsigned char b) { if (0x20 <= b && b <= 0x7F) return b; #if 0 /* * The original hardware displayed 0x00, 0x20, and 0xff as space. It * made sense for viewing sparse binary data that 0x00 be blank. But * it doesn't make sense for dense data too, and we don't need three * space characters. So we diverge in our implementation and display * 0xff as lambda. */ if (b == 0xFF) b = 0x00; #endif return kCp437[b]; } static void OnVidyaServiceWriteCharacter(void) { uint64_t w; int i, n, y, x; char *p, buf[32]; p = buf; p += FormatCga(m->bx[0], p); p = stpcpy(p, "\e7"); w = _tpenc(GetVidyaByte(m->ax[0])); do { *p++ = w; } while ((w >>= 8)); p = stpcpy(p, "\e8"); for (i = Read16(m->cx); i--;) { PtyWrite(pty, buf, p - buf); } } static char16_t VidyaServiceXlatTeletype(uint8_t c) { switch (c) { case '\a': case '\b': case '\r': case '\n': case 0177: return c; default: return GetVidyaByte(c); } } static void OnVidyaServiceTeletypeOutput(void) { int n; uint64_t w; char buf[12]; n = 0 /* FormatCga(m->bx[0], buf) */; w = _tpenc(VidyaServiceXlatTeletype(m->ax[0])); do buf[n++] = w; while ((w >>= 8)); PtyWrite(pty, buf, n); } static void OnVidyaService(void) { switch (m->ax[1]) { case 0x00: OnVidyaServiceSetMode(); break; case 0x02: OnVidyaServiceSetCursorPosition(); break; case 0x03: OnVidyaServiceGetCursorPosition(); break; case 0x09: OnVidyaServiceWriteCharacter(); break; case 0x0E: OnVidyaServiceTeletypeOutput(); break; case 0x0F: OnVidyaServiceGetMode(); break; default: break; } } static void OnKeyboardServiceReadKeyPress(void) { wint_t x; uint8_t b; size_t i, n; struct Mouse mo; static char buf[32]; static size_t pending; pty->conf |= kPtyBlinkcursor; if (!pending && !(pending = ReadAnsi(ttyin, buf, sizeof(buf)))) { exitcode = 0; action |= EXIT; return; } b = buf[0]; memmove(buf, buf + 1, pending - 1); --pending; pty->conf &= ~kPtyBlinkcursor; ReactiveDraw(); if (b == 0x7F) b = '\b'; m->ax[0] = b; m->ax[1] = 0; } static void OnKeyboardService(void) { switch (m->ax[1]) { case 0x00: OnKeyboardServiceReadKeyPress(); break; default: break; } } static void OnApmService(void) { if (Read16(m->ax) == 0x5300 && Read16(m->bx) == 0x0000) { Write16(m->bx, 'P' << 8 | 'M'); SetCarry(false); } else if (Read16(m->ax) == 0x5301 && Read16(m->bx) == 0x0000) { SetCarry(false); } else if (Read16(m->ax) == 0x5307 && m->bx[0] == 1 && m->cx[0] == 3) { INFOF("APM SHUTDOWN"); exit(0); } else { SetCarry(true); } } static void OnE820(void) { uint8_t p[20]; uint64_t addr; addr = Read64(m->es) + Read16(m->di); if (Read32(m->dx) == 0x534D4150 && Read32(m->cx) == 24 && addr + sizeof(p) <= m->real.n) { if (!Read32(m->bx)) { Write64(p + 0, 0); Write64(p + 8, m->real.n); Write32(p + 16, 1); memcpy(m->real.p + addr, p, sizeof(p)); SetWriteAddr(m, addr, sizeof(p)); Write32(m->cx, sizeof(p)); Write32(m->bx, 1); } else { Write32(m->bx, 0); Write32(m->cx, 0); } Write32(m->ax, 0x534D4150); SetCarry(false); } else { SetCarry(true); } } static void OnInt15h(void) { if (Read32(m->ax) == 0xE820) { OnE820(); } else if (m->ax[1] == 0x53) { OnApmService(); } else { SetCarry(true); } } static bool OnHalt(int interrupt) { ReactiveDraw(); switch (interrupt) { case 1: case 3: OnDebug(); return false; case 0x13: OnDiskService(); return true; case 0x10: OnVidyaService(); return true; case 0x15: OnInt15h(); return true; case 0x16: OnKeyboardService(); return true; case kMachineSegmentationFault: OnSegmentationFault(); return false; case kMachineProtectionFault: OnProtectionFault(); return false; case kMachineSimdException: OnSimdException(); return false; case kMachineUndefinedInstruction: OnUndefinedInstruction(); return false; case kMachineDecodeError: OnDecodeError(); return false; case kMachineDivideError: OnDivideError(); return false; case kMachineFpuException: OnFpuException(); return false; case kMachineExit: case kMachineHalt: default: OnExit(interrupt); return false; } } static void OnBinbase(struct Machine *m) { unsigned i; int64_t skew; skew = m->xedd->op.disp * 512; INFOF("skew binbase %,ld @ %0*lx", skew, GetAddrHexWidth(), GetIp() & 0x0000ffffffffffff); for (i = 0; i < dis->syms.i; ++i) dis->syms.p[i].addr += skew; for (i = 0; i < dis->loads.i; ++i) dis->loads.p[i].addr += skew; for (i = 0; i < breakpoints.i; ++i) breakpoints.p[i].addr += skew; Disassemble(); } static void OnLongBranch(struct Machine *m) { if (tuimode) { Disassemble(); } } static void OnPageUp(void) { opstart -= tyn / 2; } static void OnPageDown(void) { opstart += tyn / 2; } static void SetStatus(const char *fmt, ...) { char *s; va_list va; int y, x, n; va_start(va, fmt); s = xvasprintf(fmt, va); va_end(va); free(statusmessage); statusmessage = s; statusexpires = nowl() + 1; setitimer(ITIMER_REAL, &((struct itimerval){{0, 0}, {1, 0}}), NULL); } static int ClampSpeed(int s) { return MAX(-0x1000, MIN(0x40000000, s)); } static void OnTurbo(void) { if (!speed || speed == -1) { speed = 1; } else if (speed > 0) { speed = ClampSpeed(speed << 1); } else { speed = ClampSpeed(speed >> 1); } SetStatus("speed %,d", speed); } static void OnSlowmo(void) { if (!speed || speed == 1) { speed = -1; } else if (speed > 0) { speed = ClampSpeed(speed >> 1); } else { speed = ClampSpeed((unsigned)speed << 1); } SetStatus("speed %,d", speed); } static void OnUpArrow(void) { --opstart; } static void OnDownArrow(void) { ++opstart; } static void OnHome(void) { opstart = 0; } static void OnEnd(void) { opstart = dis->ops.i - (pan.disassembly.bottom - pan.disassembly.top); } static void OnEnter(void) { action &= ~FAILURE; } static void OnTab(void) { focus = (focus + 1) % ARRAYLEN(pan.p); } static void OnUp(void) { } static void OnDown(void) { } static void OnStep(void) { if (action & FAILURE) return; action |= STEP; action &= ~NEXT; action &= ~CONTINUE; } static void OnNext(void) { if (action & FAILURE) return; action ^= NEXT; action &= ~STEP; action &= ~FINISH; action &= ~CONTINUE; } static void OnFinish(void) { if (action & FAILURE) return; action ^= FINISH; action &= ~NEXT; action &= ~FAILURE; action &= ~CONTINUE; } static void OnContinueTui(void) { action ^= CONTINUE; action &= ~STEP; action &= ~NEXT; action &= ~FINISH; action &= ~FAILURE; } static void OnContinueExec(void) { tuimode = false; action |= CONTINUE; action &= ~STEP; action &= ~NEXT; action &= ~FINISH; action &= ~FAILURE; } static void OnQuit(void) { action |= QUIT; } static void OnRestart(void) { action |= RESTART; } static void OnXmmType(void) { uint8_t t; unsigned i; t = CycleXmmType(xmmtype.type[0]); for (i = 0; i < 16; ++i) { xmmtype.type[i] = t; } } static void SetXmmSize(int bytes) { unsigned i; for (i = 0; i < 16; ++i) { xmmtype.size[i] = bytes; } } static void SetXmmDisp(int disp) { xmmdisp = disp; } static void OnXmmSize(void) { SetXmmSize(CycleXmmSize(xmmtype.size[0])); } static void OnXmmDisp(void) { SetXmmDisp(CycleXmmDisp(xmmdisp)); } static bool HasPendingKeyboard(void) { return HasPendingInput(ttyin); } static void Sleep(int ms) { if (IsWindows()) { usleep(ms * 1000L); } else { poll((struct pollfd[]){{ttyin, POLLIN}}, 1, ms); } } static void OnMouseWheelUp(struct Panel *p, int y, int x) { if (p == &pan.disassembly) { opstart -= WHEELDELTA; } else if (p == &pan.code) { codeview.start -= WHEELDELTA; } else if (p == &pan.readdata) { readview.start -= WHEELDELTA; } else if (p == &pan.writedata) { writeview.start -= WHEELDELTA; } else if (p == &pan.stack) { stackview.start -= WHEELDELTA; } else if (p == &pan.maps) { mapsstart = MAX(0, mapsstart - 1); } else if (p == &pan.frames) { framesstart = MAX(0, framesstart - 1); } else if (p == &pan.breakpoints) { breakpointsstart = MAX(0, breakpointsstart - 1); } } static void OnMouseWheelDown(struct Panel *p, int y, int x) { if (p == &pan.disassembly) { opstart += WHEELDELTA; } else if (p == &pan.code) { codeview.start += WHEELDELTA; } else if (p == &pan.readdata) { readview.start += WHEELDELTA; } else if (p == &pan.writedata) { writeview.start += WHEELDELTA; } else if (p == &pan.stack) { stackview.start += WHEELDELTA; } else if (p == &pan.maps) { mapsstart += 1; } else if (p == &pan.frames) { framesstart += 1; } else if (p == &pan.breakpoints) { breakpointsstart += 1; } } static void OnMouseCtrlWheelUp(struct Panel *p, int y, int x) { ZoomMemoryViews(p, y, x, -1); } static void OnMouseCtrlWheelDown(struct Panel *p, int y, int x) { ZoomMemoryViews(p, y, x, +1); } static void OnMouse(char *p) { int e, x, y; struct Mouse m; struct Panel *ep; m = ParseMouse(p); if ((ep = LocatePanel(m.y, m.x))) { m.y -= ep->top; m.x -= ep->left; switch (m.e) { CASE(kMouseWheelUp, OnMouseWheelUp(ep, m.y, m.x)); CASE(kMouseWheelDown, OnMouseWheelDown(ep, m.y, m.x)); CASE(kMouseCtrlWheelUp, OnMouseCtrlWheelUp(ep, m.y, m.x)); CASE(kMouseCtrlWheelDown, OnMouseCtrlWheelDown(ep, m.y, m.x)); default: break; } } } static void OnHelp(void) { DEBUGF("setting dialog"); dialog = HELP; } static void HandleKeyboard(const char *k) { const char *p = k; switch (*p++) { CASE('q', OnQ()); CASE('v', OnV()); CASE('?', OnHelp()); CASE('s', OnStep()); CASE('n', OnNext()); CASE('f', OnFinish()); CASE('c', OnContinueTui()); CASE('C', OnContinueExec()); CASE('R', OnRestart()); CASE('x', OnXmmDisp()); CASE('t', OnXmmType()); CASE('T', OnXmmSize()); CASE('u', OnUp()); CASE('d', OnDown()); CASE('B', PopBreakpoint(&breakpoints)); CASE('M', ToggleMouseTracking()); CASE('\t', OnTab()); CASE('\r', OnEnter()); CASE('\n', OnEnter()); CASE(CTRL('C'), OnSigInt()); CASE(CTRL('D'), OnSigInt()); CASE(CTRL('\\'), OnQuit()); CASE(CTRL('Z'), raise(SIGSTOP)); CASE(CTRL('L'), OnFeed()); CASE(CTRL('P'), OnUpArrow()); CASE(CTRL('N'), OnDownArrow()); CASE(CTRL('V'), OnPageDown()); CASE(CTRL('T'), OnTurbo()); case '\e': switch (*p++) { CASE('v', OnPageUp()); /* alt+v */ CASE('t', OnSlowmo()); /* alt+t */ case 'O': switch (*p++) { CASE('P', OnHelp()); /* \eOP is F1 */ default: return; } return; case '[': switch (*p++) { CASE('<', OnMouse(p)); CASE('A', OnUpArrow()); /* \e[A is up */ CASE('B', OnDownArrow()); /* \e[B is down */ CASE('F', OnEnd()); /* \e[F is end */ CASE('H', OnHome()); /* \e[H is home */ CASE('1', OnHome()); /* \e[1~ is home */ CASE('4', OnEnd()); /* \e[1~ is end */ CASE('5', OnPageUp()); /* \e[1~ is pgup */ CASE('6', OnPageDown()); /* \e[1~ is pgdn */ default: return; } return; default: return; } break; default: return; } RecordKeystroke(k); } static void ReadKeyboard(void) { char buf[64]; bzero(buf, sizeof(buf)); dialog = NULL; if (readansi(ttyin, buf, sizeof(buf)) == -1) { if (errno == EINTR) { INFOF("ReadKeyboard interrupted"); return; } FATALF("ReadKeyboard failed: %s", strerror(errno)); } HandleKeyboard(buf); } static int64_t ParseHexValue(const char *s) { char *ep; int64_t x; x = strtoll(s, &ep, 16); if (*ep) { fputs("ERROR: bad hexadecimal: ", stderr); fputs(s, stderr); fputc('\n', stderr); exit(EXIT_FAILURE); } return x; } static void HandleBreakpointFlag(const char *s) { struct Breakpoint b; bzero(&b, sizeof(b)); if (isdigit(*s)) { b.addr = ParseHexValue(s); } else { b.symbol = optarg; } PushBreakpoint(&breakpoints, &b); } static wontreturn void PrintUsage(int rc, FILE *f) { fprintf(f, "SYNOPSIS\n\n %s%s", program_invocation_name, USAGE); exit(rc); } static void Exec(void) { long op; ssize_t bp; int interrupt; ExecSetup(); if (!(interrupt = setjmp(m->onhalt))) { if (!(action & CONTINUE) && (bp = IsAtBreakpoint(&breakpoints, GetIp())) != -1) { INFOF("BREAK1 %0*lx", GetAddrHexWidth(), breakpoints.p[bp].addr & 0x0000ffffffffffff); tuimode = true; LoadInstruction(m); ExecuteInstruction(m); if (m->signals.i < m->signals.n) { ConsumeSignal(m); } ++opcount; CheckFramePointer(); } else { action &= ~CONTINUE; for (;;) { LoadInstruction(m); if ((bp = IsAtBreakpoint(&breakpoints, GetIp())) != -1) { INFOF("BREAK2 %0*lx", GetAddrHexWidth(), breakpoints.p[bp].addr & 0x0000ffffffffffff); action &= ~(FINISH | NEXT | CONTINUE); tuimode = true; break; } ExecuteInstruction(m); if (m->signals.i < m->signals.n) { ConsumeSignal(m); } ++opcount; KeepGoing: CheckFramePointer(); if (action & ALARM) { /* TODO(jart): Fix me */ /* DrawDisplayOnly(&pan.display); */ action &= ~ALARM; } if (action & EXIT) { INFOF("EXEC EXIT"); break; } if (action & INT) { INFOF("EXEC INT"); if (react) { INFOF("REACT"); action &= ~(INT | STEP | FINISH | NEXT); tuimode = true; } break; } } } } else { if (OnHalt(interrupt)) { goto KeepGoing; } } } static void Tui(void) { long op; ssize_t bp; int interrupt; bool interactive; INFOF("TUI"); TuiSetup(); SetupDraw(); ScrollOp(&pan.disassembly, GetDisIndex()); if (!(interrupt = setjmp(m->onhalt))) { do { if (!(action & FAILURE)) { LoadInstruction(m); if ((action & (FINISH | NEXT | CONTINUE)) && (bp = IsAtBreakpoint(&breakpoints, GetIp())) != -1) { action &= ~(FINISH | NEXT | CONTINUE); INFOF("BREAK %0*lx", GetAddrHexWidth(), breakpoints.p[bp].addr & 0x0000ffffffffffff); } } else { m->xedd = (struct XedDecodedInst *)m->icache[0]; m->xedd->length = 1; m->xedd->bytes[0] = 0xCC; m->xedd->op.opcode = 0xCC; } if (action & WINCHED) { GetTtySize(ttyout); action &= ~WINCHED; } interactive = ++tick > speed; if (interactive && speed < 0) { Sleep(-speed); } if (action & ALARM) { HandleAlarm(); } if (action & FAILURE) { ScrollMemoryViews(); } if (!(action & CONTINUE) || interactive) { tick = 0; Redraw(); } if (dialog) { PrintMessageBox(ttyout, dialog, tyn, txn); } if (action & FAILURE) { INFOF("TUI FAILURE"); PrintMessageBox(ttyout, systemfailure, tyn, txn); ReadKeyboard(); if (action & INT) { INFOF("TUI INT"); LeaveScreen(); exit(1); } } else if (dialog || !IsExecuting() || (!(action & CONTINUE) && !(action & INT) && HasPendingKeyboard())) { ReadKeyboard(); } if (action & INT) { INFOF("TUI INT"); action &= ~INT; RecordKeystroke("\3"); ReactiveDraw(); if (action & (CONTINUE | NEXT | FINISH)) { action &= ~(CONTINUE | NEXT | FINISH); } else { action |= EXIT; break; } } if (action & EXIT) { INFOF("TUI EXIT"); break; } if (action & QUIT) { INFOF("TUI QUIT"); action &= ~QUIT; raise(SIGQUIT); continue; } if (action & RESTART) { INFOF("TUI RESTART"); break; } if (IsExecuting()) { if (!(action & CONTINUE)) { action &= ~STEP; if (action & NEXT) { action &= ~NEXT; if (IsCall()) { BreakAtNextInstruction(); break; } } if (action & FINISH) { if (IsCall()) { BreakAtNextInstruction(); break; } else if (IsRet()) { action &= ~FINISH; } } } if (!IsDebugBreak()) { UpdateXmmType(m, &xmmtype); ExecuteInstruction(m); if (m->signals.i < m->signals.n) { ConsumeSignal(m); } ++opcount; if (!(action & CONTINUE) || interactive) { if (!(action & CONTINUE)) ReactiveDraw(); ScrollMemoryViews(); } } else { m->ip += m->xedd->length; action &= ~NEXT; action &= ~FINISH; action &= ~CONTINUE; } KeepGoing: CheckFramePointer(); if (!(action & CONTINUE)) { ScrollOp(&pan.disassembly, GetDisIndex()); if ((action & FINISH) && IsRet()) action &= ~FINISH; if (((action & NEXT) && IsRet()) || (action & FINISH)) { action &= ~NEXT; } } } } while (tuimode); } else { if (OnHalt(interrupt)) { ReactiveDraw(); ScrollMemoryViews(); goto KeepGoing; } ReactiveDraw(); ScrollOp(&pan.disassembly, GetDisIndex()); } TuiCleanup(); } static void GetOpts(int argc, char *argv[]) { int opt; stpcpy(stpcpy(stpcpy(logpath, kTmpPath), basename(argv[0])), ".log"); while ((opt = getopt(argc, argv, "hvtrzRsb:HL:")) != -1) { switch (opt) { case 't': tuimode = true; break; case 'R': react = true; break; case 'r': m->ismetal = true; m->mode = XED_MACHINE_MODE_REAL; g_disisprog_disable = true; break; case 's': printstats = true; break; case 'b': HandleBreakpointFlag(optarg); break; case 'H': bzero(&g_high, sizeof(g_high)); break; case 'v': ++__log_level; break; case 'L': strcpy(logpath, optarg); break; case 'z': ++codeview.zoom; ++readview.zoom; ++writeview.zoom; ++stackview.zoom; break; case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } __log_file = fopen(logpath, "a"); setvbuf(__log_file, xmalloc(PAGESIZE), _IOLBF, PAGESIZE); } static int OpenDevTty(void) { return open("/dev/tty", O_RDWR | O_NOCTTY); } static void AddHostFd(int fd) { int i = m->fds.i++; CHECK_NE(-1, (m->fds.p[i].fd = fd)); m->fds.p[i].cb = &kMachineFdCbHost; } int Emulator(int argc, char *argv[]) { void *code; int rc, fd; codepath = argv[optind++]; m->fds.p = xcalloc((m->fds.n = 8), sizeof(struct MachineFd)); do { action = 0; LoadProgram(m, codepath, argv + optind, environ, elf); AddHostFd(0); AddHostFd(1); AddHostFd(2); if (tuimode) { ttyin = isatty(0) ? 0 : OpenDevTty(); ttyout = isatty(1) ? 1 : OpenDevTty(); } else { ttyin = -1; ttyout = -1; } if (ttyout != -1) { atexit(TtyRestore1); xsigaction(SIGWINCH, OnSigWinch, 0, 0, 0); tyn = 24; txn = 80; GetTtySize(ttyout); if (isatty(0)) m->fds.p[0].cb = &kMachineFdCbPty; if (isatty(1)) m->fds.p[1].cb = &kMachineFdCbPty; if (isatty(2)) m->fds.p[2].cb = &kMachineFdCbPty; } do { if (!tuimode) { Exec(); } else { Tui(); } } while (!(action & (RESTART | EXIT))); } while (action & RESTART); if (printstats) { fprintf(stderr, "taken: %,ld\n", taken); fprintf(stderr, "ntaken: %,ld\n", ntaken); fprintf(stderr, "ops: %,ld\n", opcount); } munmap(elf->ehdr, elf->size); DisFree(dis); return exitcode; } static void OnlyRunOnFirstCpu(void) { cpu_set_t bs; CPU_ZERO(&bs); CPU_SET(0, &bs); sched_setaffinity(0, sizeof(bs), &bs); } static void OnSignal(int sig, siginfo_t *si, void *uc) { EnqueueSignal(m, sig, si->si_code); } int main(int argc, char *argv[]) { struct sigaction sa; if (!NoDebug()) { ShowCrashReports(); } pty = NewPty(); pty->conf |= kPtyNocanon; m = NewMachine(); m->mode = XED_MACHINE_MODE_LONG_64; m->redraw = Redraw; m->onbinbase = OnBinbase; m->onlongbranch = OnLongBranch; speed = 4; SetXmmSize(2); SetXmmDisp(kXmmHex); if ((colorize = !__nocolor)) { g_high.keyword = 155; g_high.reg = 215; g_high.literal = 182; g_high.label = 221; g_high.comment = 112; g_high.quote = 215; } GetOpts(argc, argv); if (optind == argc) { PrintUsage(EX_USAGE, stderr); } xsigaction(SIGALRM, OnSigAlarm, 0, 0, 0); memset(&sa, 0, sizeof(sa)); sigfillset(&sa.sa_mask); sa.sa_flags |= SA_SIGINFO; sa.sa_sigaction = OnSignal; sigaction(SIGHUP, &sa, 0); sigaction(SIGQUIT, &sa, 0); sigaction(SIGABRT, &sa, 0); sigaction(SIGUSR1, &sa, 0); sigaction(SIGUSR2, &sa, 0); sigaction(SIGPIPE, &sa, 0); sigaction(SIGTERM, &sa, 0); sigaction(SIGCHLD, &sa, 0); sigaction(SIGWINCH, &sa, 0); return Emulator(argc, argv); }
81,415
3,181
jart/cosmopolitan
false
cosmopolitan/tool/build/fastdiff.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" #include "libc/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview scalable diff tool * * The normal `diff` command can take hours to diff text files that are * hundreds of megabytes in size. This tool is a useful replacement for * use cases like comparing a log of CPU registers. */ char line1[4096]; char line2[4096]; int main(int argc, char *argv[]) { int line; char *l1, *l2; FILE *f1, *f2; int differences; if (argc < 3) { fprintf(stderr, "usage: %s FILE1 FILE2\n", argv[0]); exit(1); } if (!(f1 = fopen(argv[1], "r"))) { perror(argv[1]); exit(1); } if (!(f2 = fopen(argv[2], "r"))) { perror(argv[2]); exit(1); } for (differences = 0, line = 1;; ++line) { l1 = fgets(line1, sizeof(line1), f1); l2 = fgets(line2, sizeof(line2), f2); if (!l1 && !l2) { exit(0); } if (l1) _chomp(l1); if (l2) _chomp(l2); if (!l1 || !l2) { printf("> %s\n", l1 ? l1 : "EOF"); printf("< %s\n", l2 ? l2 : "EOF"); exit(0); } if (!strcmp(l1, l2)) { printf("%s\n", l1); } else { printf("# line %d differed!\n", line); printf("> %s\n", l1); printf("< %s\n", l2); } } }
3,074
73
jart/cosmopolitan
false
cosmopolitan/tool/build/lz4toasm.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/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/kompressor.h" #include "libc/nexgen32e/lz4.h" #include "libc/runtime/ezmap.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/x/x.h" #include "third_party/getopt/getopt.h" /** * @fileoverview LZ4 content embedder. * * This tool converts an LZ4-compressed file into assembly source code, * that will appear to C/C++ code as a global constant holding the * uncompressed contents, which is unpacked automatically. * * @note this is a build tool that assumes input data is trustworthy */ #define COLS 8 struct stat st_; size_t extractedsize; wontreturn void usage(char *argv[], FILE *f, int rc) { fprintf(f, "%s: %s [-o %s] [-s %s] %s\n", "Usage", argv[0], "PATH", "SYMBOL", "FILE"); exit(rc); } int main(int argc, char *argv[]) { const char *symbol = "kData"; const char *lz4path = "/dev/stdin"; const char *outpath = "/dev/stdout"; const char *initprio = "400,_init_"; const unsigned char *lz4data; int opt; FILE *fin, *fout; ShowCrashReports(); while ((opt = getopt(argc, argv, "ho:s:z:")) != -1) { switch (opt) { case 's': symbol = optarg; break; case 'o': outpath = optarg; break; case 'z': extractedsize = strtoul(optarg, NULL, 0); break; case 'h': case '?': usage(argv, stdout, 0); default: usage(argv, stderr, 1); } } if (argc - optind) { lz4path = argv[optind]; } CHECK_NOTNULL((fin = fopen(lz4path, "r"))); CHECK_NE(-1, fstat(fileno(fin), &st_)); CHECK_NOTNULL((lz4data = malloc(st_.st_size))); CHECK_EQ(1, fread(lz4data, st_.st_size, 1, fin)); CHECK_NE(-1, fclose(fin)); CHECK_NOTNULL((fout = fopen(outpath, "w"))); CHECK_EQ(LZ4_MAGICNUMBER, LZ4_MAGIC(lz4data)); CHECK_EQ(1, LZ4_FRAME_VERSION(lz4data)); const unsigned char *frame = /* lz4check( */ lz4data /* ) */; const unsigned char *block1 = frame + LZ4_FRAME_HEADERSIZE(frame); const unsigned char *block2 = block1 + LZ4_BLOCK_SIZE(frame, block1); CHECK(LZ4_BLOCK_ISCOMPRESSED(block1)); CHECK(LZ4_BLOCK_ISEOF(block2)); const unsigned char *data = LZ4_BLOCK_DATA(block1); size_t size = LZ4_BLOCK_DATASIZE(block1); fprintf(fout, "/\t%s -o %s -s %s %s\n" "#include \"libc/macros.internal.h\"\n" "\n", argv[0], outpath, symbol, lz4path); if (!extractedsize) { if (LZ4_FRAME_BLOCKCONTENTSIZEFLAG(frame)) { extractedsize = LZ4_FRAME_BLOCKCONTENTSIZE(frame); } else { fprintf(stderr, "error: need extractedsize\n"); exit(1); } } size_t bss = ROUNDUP(extractedsize, 8); size_t misalign = bss - extractedsize; fprintf(fout, "\t.rodata\n"); fprintf(fout, "\t.align\t4\n"); fprintf(fout, "%sLen:\n", symbol); fprintf(fout, "\t.long\t%lu\n", extractedsize); fprintf(fout, "\t.endobj\t%sLen,globl,hidden\n", symbol); fprintf(fout, "\t.previous\n"); fprintf(fout, "\n"); fprintf(fout, "\t.initbss %s%s\n", initprio, symbol); fprintf(fout, "%s:\n", symbol); fprintf(fout, "\t.zero\t%lu\n", bss); fprintf(fout, "\t.endobj\t%s,globl,hidden\n", symbol); fprintf(fout, "\t.previous\n"); fprintf(fout, "\n"); fprintf(fout, "\t.init.start %s%s\n", initprio, symbol); fprintf(fout, "\tpush\t%%rsi\n"); fprintf(fout, "\tmov\t$%u,%%edx\n", size); fprintf(fout, "\tcall\tlz4cpy\n"); if (misalign) { fprintf(fout, "\tlea\t%zu(%%rax),%%rdi\n", misalign); } else { fprintf(fout, "\tmov\t%%rax,%%rdi\n"); } fprintf(fout, "\tpop\t%%rsi\n"); fprintf(fout, "\tadd\t$%u,%%rsi\n", ROUNDUP(size, 8)); fprintf(fout, "\t.init.end %s%s\n", initprio, symbol); fprintf(fout, "\n"); fprintf(fout, "\t.initro %s%s\n", initprio, symbol); fprintf(fout, "%sLz4:\n", symbol); int col = 0; char16_t glyphs[COLS + 1]; for (unsigned i = 0; i < size; ++i) { unsigned char ch = data[i]; if (col == 0) { fprintf(fout, "\t.byte\t"); bzero(glyphs, sizeof(glyphs)); } /* TODO(jart): Fix Emacs */ glyphs[col] = kCp437[ch == '"' || ch == '#' ? '.' : ch]; if (col) fputc(',', fout); fprintf(fout, "0x%02x", ch); if (++col == COLS) { col = 0; fprintf(fout, "\t#%hs\n", glyphs); } } while (col++ != COLS) { fprintf(fout, ",0x00"); } fprintf(fout, "\n"); fprintf(fout, "\t.endobj\t%sLz4,globl,hidden\n", symbol); fprintf(fout, "\t.previous\n"); return fclose(fout); }
6,603
185
jart/cosmopolitan
false
cosmopolitan/tool/build/sha256sum.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/errno.h" #include "libc/fmt/itoa.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "third_party/getopt/getopt.h" #include "third_party/mbedtls/sha256.h" #define PROG "sha256sum" #define USAGE \ "\ Usage: " PROG " [-?hbctw] [PATH...]\n\ -h help\n\ -c check mode\n\ -b binary mode\n\ -t textual mode\n\ -w warning mode\n\ \n\ cosmopolitan " PROG " v1.0\n\ copyright 2022 justine alexandra roberts tunney\n\ notice licenses are embedded in the binary\n\ https://twitter.com/justinetunney\n\ https://github.com/jart\n\ \n\ This program is an Actually Portable Executable (APE) rewrite of the\n\ GNU coreutils sha256sum command. Our version is better because it goes\n\ 400% faster than coreutils if the Intel® SHA-NI™ ISA is available,\n\ otherwise this command goes 50% faster than coreutils. This executable\n\ will work consistently on Linux/Mac/Windows/FreeBSD/NetBSD/OpenBSD, so\n\ consider vendoring it in your repo to avoid platform portability toil.\n\ " static bool g_warn; static char g_mode; static bool g_check; static int g_mismatches; static void GetOpts(int argc, char *argv[]) { int opt; g_mode = ' '; while ((opt = getopt(argc, argv, "?hbctw")) != -1) { switch (opt) { case 'w': g_warn = true; break; case 'c': g_check = true; break; case 't': g_mode = ' '; break; case 'b': g_mode = '*'; break; case 'h': case '?': write(1, USAGE, sizeof(USAGE) - 1); exit(0); default: write(2, USAGE, sizeof(USAGE) - 1); exit(64); } } } static ssize_t Write(int fd, const char *s, ...) { va_list va; char buf[512]; buf[0] = 0; va_start(va, s); do { strlcat(buf, s, sizeof(buf)); } while ((s = va_arg(va, const char *))); va_end(va); return write(fd, buf, strlen(buf)); } static bool IsModeCharacter(char c) { switch (c) { case ' ': case '*': return true; default: return false; } } static bool IsSupportedPath(const char *path) { size_t i; for (i = 0;; ++i) { switch (path[i]) { case 0: if (i) return true; // fallthrough case '\r': case '\n': case '\\': Write(2, PROG, ": ", path, ": unsupported path\n", NULL); return false; default: break; } } } static bool GetDigest(const char *path, FILE *f, unsigned char digest[32]) { size_t got; unsigned char buf[512]; mbedtls_sha256_context ctx; mbedtls_sha256_init(&ctx); _unassert(!mbedtls_sha256_starts_ret(&ctx, false)); while ((got = fread(buf, 1, sizeof(buf), f))) { _unassert(!mbedtls_sha256_update_ret(&ctx, buf, got)); } if (ferror(f)) { Write(2, PROG, ": ", path, ": ", _strerdoc(errno), "\n", NULL); return false; } _unassert(!mbedtls_sha256_finish_ret(&ctx, digest)); mbedtls_sha256_free(&ctx); return true; } static bool ProduceDigest(const char *path, FILE *f) { char hexdigest[65]; char mode[2] = {g_mode}; unsigned char digest[32]; if (!IsSupportedPath(path)) return false; if (!GetDigest(path, f, digest)) return false; hexpcpy(hexdigest, digest, 32); Write(1, hexdigest, " ", mode, path, "\n", NULL); return true; } static bool CheckDigests(const char *path, FILE *f) { FILE *f2; bool k = true; int a, b, i, line; const char *path2, *status; unsigned char wantdigest[32], gotdigest[32]; char buf[64 + 2 + PATH_MAX + 1 + 1], *p; for (line = 0; fgets(buf, sizeof(buf), f); ++line) { if (!*_chomp(buf)) continue; for (p = buf, i = 0; i < 32; ++i) { if ((a = kHexToInt[*p++ & 255]) == -1) goto InvalidLine; if ((b = kHexToInt[*p++ & 255]) == -1) goto InvalidLine; wantdigest[i] = a << 4 | b; } if (*p++ != ' ') goto InvalidLine; if (!IsModeCharacter(*p++)) goto InvalidLine; path2 = p; if (!*path2) goto InvalidLine; if (!IsSupportedPath(path2)) continue; if ((f2 = fopen(path2, "rb"))) { if (GetDigest(path2, f2, gotdigest)) { if (!memcmp(wantdigest, gotdigest, 32)) { status = "OK"; } else { status = "FAILED"; ++g_mismatches; k = false; } Write(1, path2, ": ", status, "\n", NULL); } else { k = false; } fclose(f2); } else { Write(2, PROG, ": ", path2, ": ", _strerdoc(errno), "\n", NULL); k = false; } continue; InvalidLine: if (g_warn) { char linestr[12]; FormatInt32(linestr, line + 1); Write(2, PROG, ": ", path, ":", linestr, ": ", "improperly formatted checksum line", "\n", NULL); } } if (ferror(f)) { Write(2, PROG, ": ", path, ": ", _strerdoc(errno), "\n", NULL); k = false; } return k; } static bool Process(const char *path, FILE *f) { if (g_check) { return CheckDigests(path, f); } else { return ProduceDigest(path, f); } } int main(int argc, char *argv[]) { int i; FILE *f; bool k = true; GetOpts(argc, argv); if (optind == argc) { f = stdin; k &= Process("-", f); } else { for (i = optind; i < argc; ++i) { if ((f = fopen(argv[i], "rb"))) { k &= Process(argv[i], f); fclose(f); } else { Write(2, PROG, ": ", argv[i], ": ", _strerdoc(errno), "\n", NULL); k = false; } } } if (g_mismatches) { char ibuf[12]; FormatInt32(ibuf, g_mismatches); Write(2, PROG, ": WARNING: ", ibuf, " computed checksum did NOT match\n", NULL); } return !k; }
7,584
244
jart/cosmopolitan
false
cosmopolitan/tool/build/echo.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/stdio/stdio.h" #include "libc/str/str.h" int main(int argc, char *argv[]) { int i, j; FILE *stream = stdout; bool wantnewline = true; for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-n")) { wantnewline = false; } else if (!strcmp(argv[i], "-2")) { stream = stderr; } else { break; } } for (j = 0; i + j < argc; ++j) { if (j) fputc(' ', stream); fputs(argv[i + j], stream); } if (wantnewline) { fputc('\n', stream); } return 0; }
2,353
47
jart/cosmopolitan
false
cosmopolitan/tool/build/mv.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/stat.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/s.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #include "third_party/musl/ftw.h" #define USAGE \ " SRC... DST\n\ \n\ SYNOPSIS\n\ \n\ Moves Files\n\ \n\ FLAGS\n\ \n\ -?\n\ -h help\n\ -f force\n\ -r recursive\n\ \n" bool force; int striplen; bool recursive; const char *prog; char mkbuf[PATH_MAX]; char srcdir[PATH_MAX]; char dstdir[PATH_MAX]; char srcfile[PATH_MAX]; char dstfile[PATH_MAX]; char linkbuf[PATH_MAX]; void Mv(char *, char *); bool IsDirectory(const char *path) { int e; bool res; struct stat st; e = errno; res = stat(path, &st) != -1 && S_ISDIR(st.st_mode); errno = e; return res; } bool IsSymlink(const char *path) { int e; bool res; struct stat st; e = errno; res = fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && S_ISLNK(st.st_mode); errno = e; return res; } 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, "?hfrR")) != -1) { switch (opt) { case 'f': force = true; break; case 'r': case 'R': recursive = true; break; case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } int Visit(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { char *src; strcpy(srcfile, fpath); src = srcfile + striplen; strcpy(dstfile, dstdir); if (!_endswith(dstfile, "/")) { strcat(dstfile, "/"); } strcat(dstfile, src); strcpy(srcfile, fpath); switch (tflag) { case FTW_D: return 0; case FTW_F: case FTW_SL: case FTW_SLN: Mv(srcfile, dstfile); return 0; default: fputs(fpath, stderr); fputs(": can't handle file type\n", stderr); exit(1); } } char *Join(const char *a, const char *b) { size_t n, m; n = strlen(a); m = strlen(b); if (n + 1 + m + 1 > sizeof(dstfile)) { fputs("error: mv: path too long\n", stderr); exit(1); } stpcpy(stpcpy(stpcpy(dstfile, a), "/"), b); return dstfile; } void Mv(char *src, char *dst) { ssize_t rc; const char *s; if (strlen(src) + 1 > PATH_MAX) _Exit(2); if (strlen(dst) + 1 > PATH_MAX) _Exit(2); basename(src); basename(dst); if (IsDirectory(src)) { if (!recursive) { fputs(prog, stderr); fputs(": won't move directory without -r flag.\n", stderr); exit(1); } strcpy(dstdir, dst); if (IsDirectory(dst)) { strcpy(srcdir, src); basename(srcdir); striplen = 0; strcpy(srcdir, basename(src)); } else { strcpy(srcdir, src); basename(srcdir); striplen = strlen(srcdir); strcpy(srcdir, ""); } if (nftw(src, Visit, 20, 0) == -1) { fputs(prog, stderr); fputs(": nftw failed: ", stderr); fputs(_strerdoc(errno), stderr); fputs("\n", stderr); exit(1); } return; } if (IsDirectory(dst)) { dst = Join(dst, basename(src)); } if (!force && access(dst, W_OK) == -1 && errno != ENOENT) goto OnFail; strcpy(mkbuf, dst); if (makedirs(dirname(mkbuf), 0755) == -1) goto OnFail; if (IsSymlink(src)) { if ((rc = readlink(src, linkbuf, sizeof(linkbuf) - 1)) == -1) goto OnFail; linkbuf[rc] = 0; if (symlink(linkbuf, dst) == -1) goto OnFail; } else { if (rename(src, dst) == -1) goto OnFail; } return; OnFail: s = _strerdoc(errno); fputs(prog, stderr); fputs(": ", stderr); fputs(src, stderr); fputs(" ", stderr); fputs(dst, stderr); fputs(": ", stderr); fputs(s, stderr); fputs("\n", stderr); exit(1); } int main(int argc, char *argv[]) { int i; prog = argc > 0 ? argv[0] : "mv.com"; GetOpts(argc, argv); if (argc - optind < 2) PrintUsage(EX_USAGE, stderr); for (i = optind; i < argc - 1; ++i) { Mv(argv[i], argv[argc - 1]); } return 0; }
6,256
222
jart/cosmopolitan
false
cosmopolitan/tool/build/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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/stat.h" #include "libc/elf/elf.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.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/mem/arraylist2.internal.h" #include "libc/mem/copyfd.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.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/sysv/consts/s.h" #include "libc/x/x.h" #include "tool/build/lib/getargs.h" /** * @fileoverview System Five Static Archive Builder. * * GNU ar has a bug which causes it to take hundreds of milliseconds to * build archives like ntdll.a and several minutes for cosmopolitan.a. * This goes quadratically faster taking 1ms to do ntdll w/ hot cache. * * Compared to LLVM ar this tool goes 10x faster because it uses madvise * and copy_file_range which give us the optimal page cached file system * beahvior that a build environment needs. * * This tool also adds a feature: it ignores directory parameters. This * is important because good Makefiles on Linux will generally have the * directory be a .a prerequisite so archives rebuild on file deletion. * * @see https://www.unix.com/man-page/opensolaris/3head/ar.h/ */ struct Args { size_t i, n; char **p; }; struct String { size_t i, n; char *p; }; struct Ints { size_t i, n; int *p; }; struct Header { char name[16]; char date[12]; char uid[6]; char gid[6]; char mode[8]; char size[10]; char fmag[2]; }; static void *Realloc(void *p, size_t n) { void *q; if (!(q = realloc(p, n))) { fputs("error: ar: out of memory\n", stderr); exit(1); } return q; } static void *Malloc(size_t n) { return Realloc(0, n); } static void NewArgs(struct Args *l, size_t n) { l->i = 0; l->n = MAX(2, n); l->p = Malloc(l->n * sizeof(*l->p)); l->p[0] = 0; } static void NewInts(struct Ints *l, size_t n) { l->i = 0; l->n = MAX(2, n); l->p = Malloc(l->n * sizeof(*l->p)); l->p[0] = 0; } static void NewString(struct String *s, size_t n) { s->i = 0; s->n = MAX(2, n); s->p = Malloc(s->n * sizeof(*s->p)); s->p[0] = 0; } static void AppendInt(struct Ints *l, int i) { assert(l->n > 1); if (l->i + 1 >= l->n) { do { l->n += l->n >> 1; } while (l->i + 1 >= l->n); l->p = Realloc(l->p, l->n * sizeof(*l->p)); } l->p[l->i++] = i; l->p[l->i] = 0; } static void AppendArg(struct Args *l, char *s) { assert(l->n > 1); if (l->i + 1 >= l->n) { do { l->n += l->n >> 1; } while (l->i + 1 >= l->n); l->p = Realloc(l->p, l->n * sizeof(*l->p)); } l->p[l->i++] = s; l->p[l->i] = 0; } static void MakeHeader(struct Header *h, const char *name, int ref, int mode, int size) { size_t n; char ibuf[13], *p; memset(h, ' ', sizeof(*h)); n = strlen(name); memcpy(h->name, name, n); if (ref != -1) { FormatUint32(h->name + n, ref); } if (strcmp(name, "//") != 0) { h->date[0] = '0'; h->uid[0] = '0'; h->gid[0] = '0'; p = FormatOctal32(ibuf, mode & 0777, false); CHECK_LE(p - ibuf, sizeof(h->mode)); memcpy(h->mode, ibuf, p - ibuf); } h->fmag[0] = '`'; h->fmag[1] = '\n'; p = FormatUint32(ibuf, size); CHECK_LE(p - ibuf, sizeof(h->size)); memcpy(h->size, ibuf, p - ibuf); } int main(int argc, char *argv[]) { FILE *f; void *elf; char *line; char *strs; ssize_t rc; int *offsets; size_t wrote; size_t remain; struct stat *st; uint32_t outpos; Elf64_Sym *syms; const char *arg; struct Args args; uint64_t outsize; uint8_t *tablebuf; struct GetArgs ga; struct Ints modes; struct Ints names; struct Ints sizes; const char *reason; struct iovec iov[7]; const char *symname; const char *outpath; Elf64_Xword symcount; struct Ints symnames; struct String symbols; struct String filenames; struct Header *header1, *header2; int i, j, fd, err, name, outfd, tablebufsize; // TODO(jart): Delete this. if (argc == 2 && !strcmp(argv[1], "-n")) { exit(0); } // we only support one mode of operation, which is creating a new // deterministic archive. this tool is so fast that we don't need // database-like tools when editing static archives if (!(argc > 2 && strcmp(argv[1], "rcsD") == 0)) { fputs("usage: ", stderr); if (argc > 0) fputs(argv[0], stderr); fputs(" rcsD ARCHIVE FILE...", stderr); exit(EX_USAGE); } outpath = argv[2]; NewArgs(&args, 4); st = Malloc(sizeof(struct stat)); NewInts(&modes, 128); NewInts(&names, 128); NewInts(&sizes, 128); NewInts(&symnames, 1024); NewString(&symbols, 4096); NewString(&filenames, 1024); getargs_init(&ga, argv + 3); // load global symbols and populate page cache for (i = 0;; ++i) { TryAgain: if (!(arg = getargs_next(&ga))) break; if (_endswith(arg, "/")) goto TryAgain; if (_endswith(arg, ".pkg")) goto TryAgain; CHECK_NE(-1, stat(arg, st), "%s", arg); if (!st->st_size || S_ISDIR(st->st_mode)) goto TryAgain; CHECK_NE(-1, (fd = open(arg, O_RDONLY)), "%s", arg); CHECK_LT(st->st_size, 0x7ffff000); AppendArg(&args, xstrdup(arg)); AppendInt(&names, filenames.i); AppendInt(&sizes, st->st_size); AppendInt(&modes, st->st_mode); CONCAT(&filenames.p, &filenames.i, &filenames.n, basename(arg), strlen(basename(arg))); CONCAT(&filenames.p, &filenames.i, &filenames.n, "/\n", 2); CHECK_NE(MAP_FAILED, (elf = mmap(0, st->st_size, PROT_READ, MAP_PRIVATE, fd, 0))); CHECK(IsElf64Binary(elf, st->st_size), "%s", arg); CHECK_NOTNULL((strs = GetElfStringTable(elf, st->st_size))); CHECK_NOTNULL((syms = GetElfSymbolTable(elf, st->st_size, &symcount))); for (j = 0; j < symcount; ++j) { if (syms[j].st_shndx == SHN_UNDEF) continue; if (syms[j].st_other == STV_INTERNAL) continue; if (ELF64_ST_BIND(syms[j].st_info) == STB_LOCAL) continue; symname = GetElfString(elf, st->st_size, strs, syms[j].st_name); CONCAT(&symbols.p, &symbols.i, &symbols.n, symname, strlen(symname) + 1); AppendInt(&symnames, i); } CHECK_NE(-1, munmap(elf, st->st_size)); close(fd); } APPEND(&filenames.p, &filenames.i, &filenames.n, "\n"); // compute length of output archive outsize = 0; tablebufsize = 4 + symnames.i * 4; tablebuf = Malloc(tablebufsize); offsets = Malloc(args.i * 4); header1 = Malloc(sizeof(struct Header)); header2 = Malloc(sizeof(struct Header)); iov[0].iov_base = "!<arch>\n"; outsize += (iov[0].iov_len = 8); iov[1].iov_base = header1; outsize += (iov[1].iov_len = 60); iov[2].iov_base = tablebuf; outsize += (iov[2].iov_len = tablebufsize); iov[3].iov_base = symbols.p; outsize += (iov[3].iov_len = symbols.i); iov[4].iov_base = "\n"; outsize += (iov[4].iov_len = outsize & 1); iov[5].iov_base = header2; outsize += (iov[5].iov_len = 60); iov[6].iov_base = filenames.p; outsize += (iov[6].iov_len = filenames.i); for (i = 0; i < args.i; ++i) { outsize += outsize & 1; offsets[i] = outsize; outsize += 60; outsize += sizes.p[i]; } CHECK_LE(outsize, 0x7ffff000); // serialize metadata MakeHeader(header1, "/", -1, 0, tablebufsize + symbols.i); MakeHeader(header2, "//", -1, 0, filenames.i); WRITE32BE(tablebuf, symnames.i); for (i = 0; i < symnames.i; ++i) { WRITE32BE(tablebuf + 4 + i * 4, offsets[symnames.p[i]]); } // write output archive CHECK_NE(-1, (outfd = creat(outpath, 0644))); ftruncate(outfd, outsize); if ((outsize = writev(outfd, iov, ARRAYLEN(iov))) == -1) { reason = "writev1 failed"; goto fail; } for (i = 0; i < args.i; ++i) { if ((fd = open(args.p[i], O_RDONLY)) == -1) { reason = "open failed"; goto fail; } iov[0].iov_base = "\n"; outsize += (iov[0].iov_len = outsize & 1); iov[1].iov_base = header1; outsize += (iov[1].iov_len = 60); MakeHeader(header1, "/", names.p[i], modes.p[i], sizes.p[i]); if (writev(outfd, iov, 2) == -1) { reason = "writev2 failed"; goto fail; } outsize += (remain = sizes.p[i]); if (_copyfd(fd, outfd, remain) == -1) { reason = "copy_file_range failed"; goto fail; } close(fd); } close(outfd); for (i = 0; i < args.i; ++i) free(args.p[i]); getargs_destroy(&ga); free(filenames.p); free(symnames.p); free(symbols.p); free(tablebuf); free(modes.p); free(names.p); free(sizes.p); free(offsets); free(header1); free(header2); free(args.p); free(st); return 0; fail: err = errno; unlink(outpath); fputs("error: ar failed: ", stderr); fputs(reason, stderr); fputs(": ", stderr); fputs(strerror(err), stderr); fputs("\n", stderr); return 1; }
10,988
359
jart/cosmopolitan
false
cosmopolitan/tool/build/runitd.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/stat.h" #include "libc/calls/struct/timeval.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/nexgen32e/crc32.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/sock/struct/sockaddr.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/inaddr.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/sa.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/w.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "net/https/https.h" #include "third_party/getopt/getopt.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" #include "tool/build/runit.h" /** * @fileoverview Remote test runner daemon. * Delivers 10x latency improvement over SSH (100x if Debian defaults) * * Here's how it handles connections: * * 1. Receives atomically-written request header, comprised of: * * - 4 byte nbo magic = 0xFEEDABEEu * - 1 byte command = kRunitExecute * - 4 byte nbo name length in bytes, e.g. "test1" * - 4 byte nbo executable file length in bytes * - <name bytes> (no NUL terminator) * - <file bytes> (it's binary data) * * 2. Runs program, after verifying it came from the IP that spawned * this program via SSH. Be sure to only run this over a trusted * physically-wired network. To use this software on untrustworthy * networks, wrap it with stunnel and use your own CA. * * 3. Sends stdout/stderr fragments, potentially multiple times: * * - 4 byte nbo magic = 0xFEEDABEEu * - 1 byte command = kRunitStdout/Stderr * - 4 byte nbo byte length * - <chunk bytes> * * 4. Sends process exit code: * * - 4 byte nbo magic = 0xFEEDABEEu * - 1 byte command = kRunitExit * - 1 byte exit status */ #define DEATH_CLOCK_SECONDS 128 #define kLogFile "o/runitd.log" #define kLogMaxBytes (2 * 1000 * 1000) bool use_ftrace; bool use_strace; char *g_exepath; volatile bool g_interrupted; struct sockaddr_in g_servaddr; unsigned char g_buf[PAGESIZE]; bool g_daemonize, g_sendready; int g_timeout, g_bogusfd, g_servfd, g_clifd, g_exefd; void OnInterrupt(int sig) { g_interrupted = true; } void OnChildTerminated(int sig) { int ws, pid; sigset_t ss, oldss; sigfillset(&ss); sigdelset(&ss, SIGTERM); sigprocmask(SIG_BLOCK, &ss, &oldss); for (;;) { INFOF("waitpid"); if ((pid = waitpid(-1, &ws, WNOHANG)) != -1) { if (pid) { if (WIFEXITED(ws)) { DEBUGF("worker %d exited with %d", pid, WEXITSTATUS(ws)); } else { DEBUGF("worker %d terminated with %s", pid, strsignal(WTERMSIG(ws))); } } else { break; } } else { if (errno == EINTR) continue; if (errno == ECHILD) break; FATALF("waitpid failed in sigchld"); } } sigprocmask(SIG_SETMASK, &oldss, 0); } wontreturn void ShowUsage(FILE *f, int rc) { fprintf(f, "%s: %s %s\n", "Usage", program_invocation_name, "[-d] [-r] [-l LISTENIP] [-p PORT] [-t TIMEOUTMS]"); exit(rc); } void GetOpts(int argc, char *argv[]) { int opt; g_timeout = RUNITD_TIMEOUT_MS; g_servaddr.sin_family = AF_INET; g_servaddr.sin_port = htons(RUNITD_PORT); g_servaddr.sin_addr.s_addr = INADDR_ANY; while ((opt = getopt(argc, argv, "fqhvsdrl:p:t:w:")) != -1) { switch (opt) { case 'f': use_ftrace = true; break; case 's': use_strace = true; break; case 'q': --__log_level; break; case 'v': ++__log_level; break; case 'd': g_daemonize = true; break; case 'r': g_sendready = true; break; case 't': g_timeout = atoi(optarg); break; case 'p': CHECK_NE(0xFFFF, (g_servaddr.sin_port = htons(parseport(optarg)))); break; case 'l': CHECK_EQ(1, inet_pton(AF_INET, optarg, &g_servaddr.sin_addr)); break; case 'h': ShowUsage(stdout, EXIT_SUCCESS); unreachable; default: ShowUsage(stderr, EX_USAGE); unreachable; } } } dontdiscard char *DescribeAddress(struct sockaddr_in *addr) { char ip4buf[16]; return xasprintf("%s:%hu", inet_ntop(addr->sin_family, &addr->sin_addr.s_addr, ip4buf, sizeof(ip4buf)), ntohs(addr->sin_port)); } void StartTcpServer(void) { int yes = true; uint32_t asize; /* * TODO: How can we make close(serversocket) on Windows go fast? * That way we can put back SOCK_CLOEXEC. */ CHECK_NE(-1, (g_servfd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP))); struct timeval timeo = {30}; setsockopt(g_servfd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo)); setsockopt(g_servfd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo)); LOGIFNEG1(setsockopt(g_servfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes))); if (bind(g_servfd, (struct sockaddr *)&g_servaddr, sizeof(g_servaddr)) == -1) { FATALF("bind failed %m"); } CHECK_NE(-1, listen(g_servfd, 10)); asize = sizeof(g_servaddr); CHECK_NE(-1, getsockname(g_servfd, (struct sockaddr *)&g_servaddr, &asize)); INFOF("%s:%s", "listening on tcp", _gc(DescribeAddress(&g_servaddr))); if (g_sendready) { printf("ready %hu\n", ntohs(g_servaddr.sin_port)); fflush(stdout); fclose(stdout); dup2(g_bogusfd, stdout->fd); } } void SendExitMessage(int rc) { unsigned char msg[4 + 1 + 1]; msg[0 + 0] = (RUNITD_MAGIC & 0xff000000) >> 030; msg[0 + 1] = (RUNITD_MAGIC & 0x00ff0000) >> 020; msg[0 + 2] = (RUNITD_MAGIC & 0x0000ff00) >> 010; msg[0 + 3] = (RUNITD_MAGIC & 0x000000ff) >> 000; msg[4] = kRunitExit; msg[5] = rc; INFOF("mbedtls_ssl_write"); CHECK_EQ(sizeof(msg), mbedtls_ssl_write(&ezssl, msg, sizeof(msg))); CHECK_EQ(0, EzTlsFlush(&ezbio, 0, 0)); } void SendOutputFragmentMessage(enum RunitCommand kind, unsigned char *buf, size_t size) { ssize_t rc; size_t sent; unsigned char msg[4 + 1 + 4]; msg[0 + 0] = (RUNITD_MAGIC & 0xff000000) >> 030; msg[0 + 1] = (RUNITD_MAGIC & 0x00ff0000) >> 020; msg[0 + 2] = (RUNITD_MAGIC & 0x0000ff00) >> 010; msg[0 + 3] = (RUNITD_MAGIC & 0x000000ff) >> 000; msg[4 + 0] = kind; msg[5 + 0] = (size & 0xff000000) >> 030; msg[5 + 1] = (size & 0x00ff0000) >> 020; msg[5 + 2] = (size & 0x0000ff00) >> 010; msg[5 + 3] = (size & 0x000000ff) >> 000; INFOF("mbedtls_ssl_write"); CHECK_EQ(sizeof(msg), mbedtls_ssl_write(&ezssl, msg, sizeof(msg))); while (size) { CHECK_NE(-1, (rc = mbedtls_ssl_write(&ezssl, buf, size))); CHECK_LE((sent = (size_t)rc), size); size -= sent; buf += sent; } CHECK_EQ(0, EzTlsFlush(&ezbio, 0, 0)); } void Recv(void *output, size_t outputsize) { int rc; ssize_t tx, chunk, received, totalgot; static bool once; static int zstatus; static char buf[32768]; static z_stream zs; static struct { size_t off; size_t len; size_t cap; char *data; } rbuf; if (!once) { CHECK_EQ(Z_OK, inflateInit(&zs)); once = true; } totalgot = 0; for (;;) { if (rbuf.len >= outputsize) { tx = MIN(outputsize, rbuf.len); memcpy(output, rbuf.data + rbuf.off, outputsize); rbuf.len -= outputsize; rbuf.off += outputsize; // trim dymanic buffer once it empties if (!rbuf.len) { rbuf.off = 0; rbuf.cap = 4096; rbuf.data = realloc(rbuf.data, rbuf.cap); } return; } if (zstatus == Z_STREAM_END) { close(g_clifd); FATALF("recv zlib unexpected eof"); } // get another fixed-size data packet from network // pass along error conditions to caller // pass along eof condition to zlib received = mbedtls_ssl_read(&ezssl, buf, sizeof(buf)); if (!received) { close(g_clifd); TlsDie("got unexpected eof", received); } if (received < 0) { close(g_clifd); TlsDie("read failed", received); } totalgot += received; // decompress packet completely // into a dynamical size buffer zs.avail_in = received; zs.next_in = (unsigned char *)buf; CHECK_EQ(Z_OK, zstatus); do { // make sure we have a reasonable capacity for zlib output if (rbuf.cap - (rbuf.off + rbuf.len) < sizeof(buf)) { rbuf.cap += sizeof(buf); rbuf.data = realloc(rbuf.data, rbuf.cap); } // inflate packet, which naturally can be much larger // permit zlib no delay flushes that come from sender zs.next_out = (unsigned char *)rbuf.data + (rbuf.off + rbuf.len); zs.avail_out = chunk = rbuf.cap - (rbuf.off + rbuf.len); zstatus = inflate(&zs, Z_SYNC_FLUSH); CHECK_NE(Z_STREAM_ERROR, zstatus); switch (zstatus) { case Z_NEED_DICT: WARNF("tls recv Z_NEED_DICT %ld total %ld", received, totalgot); exit(1); case Z_DATA_ERROR: WARNF("tls recv Z_DATA_ERROR %ld total %ld", received, totalgot); exit(1); case Z_MEM_ERROR: WARNF("tls recv Z_MEM_ERROR %ld total %ld", received, totalgot); exit(1); case Z_BUF_ERROR: zstatus = Z_OK; // harmless? nothing for inflate to do break; // it probably just our wraparound eof default: rbuf.len += chunk - zs.avail_out; break; } } while (!zs.avail_out); } } void HandleClient(void) { const size_t kMaxNameSize = 128; const size_t kMaxFileSize = 10 * 1024 * 1024; uint32_t crc; ssize_t got, wrote; struct sockaddr_in addr; long double now, deadline; sigset_t chldmask, savemask; char *addrstr, *exename, *exe; unsigned char msg[4 + 1 + 4 + 4 + 4]; struct sigaction ignore, saveint, savequit; uint32_t addrsize, namesize, filesize, remaining; int rc, events, exitcode, wstatus, child, pipefds[2]; /* read request to run program */ addrsize = sizeof(addr); INFOF("accept"); do { g_clifd = accept4(g_servfd, (struct sockaddr *)&addr, &addrsize, SOCK_CLOEXEC); } while (g_clifd == -1 && errno == EAGAIN); CHECK_NE(-1, g_clifd); if (fork()) { close(g_clifd); return; } EzFd(g_clifd); INFOF("EzHandshake"); EzHandshake(); addrstr = _gc(DescribeAddress(&addr)); DEBUGF("%s %s %s", _gc(DescribeAddress(&g_servaddr)), "accepted", addrstr); Recv(msg, sizeof(msg)); CHECK_EQ(RUNITD_MAGIC, READ32BE(msg)); CHECK_EQ(kRunitExecute, msg[4]); namesize = READ32BE(msg + 5); filesize = READ32BE(msg + 9); crc = READ32BE(msg + 13); exename = _gc(calloc(1, namesize + 1)); Recv(exename, namesize); g_exepath = _gc(xasprintf("o/%d.%s", getpid(), basename(exename))); INFOF("%s asked we run %`'s (%,u bytes @ %`'s)", addrstr, exename, filesize, g_exepath); exe = malloc(filesize); Recv(exe, filesize); if (crc32_z(0, exe, filesize) != crc) { FATALF("%s crc mismatch! %`'s", addrstr, exename); } CHECK_NE(-1, (g_exefd = creat(g_exepath, 0700))); LOGIFNEG1(ftruncate(g_exefd, filesize)); INFOF("xwrite"); CHECK_NE(-1, xwrite(g_exefd, exe, filesize)); LOGIFNEG1(close(g_exefd)); /* run program, tee'ing stderr to both log and client */ DEBUGF("spawning %s", exename); 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); CHECK_NE(-1, pipe2(pipefds, O_CLOEXEC)); CHECK_NE(-1, (child = fork())); if (!child) { dup2(g_bogusfd, 0); dup2(pipefds[1], 1); dup2(pipefds[1], 2); sigaction(SIGINT, &(struct sigaction){0}, 0); sigaction(SIGQUIT, &(struct sigaction){0}, 0); sigprocmask(SIG_SETMASK, &savemask, 0); int i = 0; const char *exe; char *args[8] = {0}; if (!IsXnuSilicon()) { exe = g_exepath; } else { exe = "ape-m1.com"; args[i++] = exe; args[i++] = "-"; args[i++] = g_exepath; } args[i++] = g_exepath; if (use_strace) args[i++] = "--strace"; if (use_ftrace) args[i++] = "--ftrace"; execvp(exe, args); _Exit(127); } close(pipefds[1]); DEBUGF("communicating %s[%d]", exename, child); deadline = nowl() + DEATH_CLOCK_SECONDS; for (;;) { now = nowl(); if (now >= deadline) { WARNF("%s worker timed out", exename); LOGIFNEG1(kill(child, 9)); LOGIFNEG1(waitpid(child, 0, 0)); LOGIFNEG1(close(g_clifd)); LOGIFNEG1(close(pipefds[0])); LOGIFNEG1(unlink(g_exepath)); _exit(1); } struct pollfd fds[2]; fds[0].fd = g_clifd; fds[0].events = POLLIN; fds[1].fd = pipefds[0]; fds[1].events = POLLIN; INFOF("poll"); events = poll(fds, ARRAYLEN(fds), (deadline - now) * 1000); CHECK_NE(-1, events); // EINTR shouldn't be possible if (fds[0].revents) { if (!(fds[0].revents & POLLHUP)) { WARNF("%s got unexpected input event from client %#x", exename, fds[0].revents); } WARNF("%s client disconnected so killing worker %d", exename, child); LOGIFNEG1(kill(child, 9)); LOGIFNEG1(waitpid(child, 0, 0)); LOGIFNEG1(close(g_clifd)); LOGIFNEG1(close(pipefds[0])); LOGIFNEG1(unlink(g_exepath)); _exit(1); } INFOF("read"); got = read(pipefds[0], g_buf, sizeof(g_buf)); CHECK_NE(-1, got); // EINTR shouldn't be possible if (!got) { LOGIFNEG1(close(pipefds[0])); break; } fwrite(g_buf, got, 1, stderr); SendOutputFragmentMessage(kRunitStderr, g_buf, got); } INFOF("waitpid"); CHECK_NE(-1, waitpid(child, &wstatus, 0)); // EINTR shouldn't be possible if (WIFEXITED(wstatus)) { if (WEXITSTATUS(wstatus)) { WARNF("%s exited with %d", exename, WEXITSTATUS(wstatus)); } else { VERBOSEF("%s exited with %d", exename, WEXITSTATUS(wstatus)); } exitcode = WEXITSTATUS(wstatus); } else { WARNF("%s terminated with %s", exename, strsignal(WTERMSIG(wstatus))); exitcode = 128 + WTERMSIG(wstatus); } LOGIFNEG1(unlink(g_exepath)); SendExitMessage(exitcode); INFOF("mbedtls_ssl_close_notify"); mbedtls_ssl_close_notify(&ezssl); LOGIFNEG1(close(g_clifd)); _exit(0); } int Poll(void) { int i, wait, evcount; struct pollfd fds[1]; TryAgain: if (g_interrupted) return 0; fds[0].fd = g_servfd; fds[0].events = POLLIN | POLLERR | POLLHUP; wait = MIN(1000, g_timeout); evcount = poll(fds, ARRAYLEN(fds), wait); if (!evcount) g_timeout -= wait; if (evcount == -1 && errno == EINTR) goto TryAgain; CHECK_NE(-1, evcount); for (i = 0; i < evcount; ++i) { CHECK(fds[i].revents & POLLIN); HandleClient(); } /* manually do this because of nt */ while (waitpid(-1, NULL, WNOHANG) > 0) donothing; return evcount; } int Serve(void) { StartTcpServer(); sigaction(SIGINT, (&(struct sigaction){.sa_handler = OnInterrupt}), 0); sigaction(SIGCHLD, (&(struct sigaction){.sa_handler = OnChildTerminated, .sa_flags = SA_RESTART}), 0); for (;;) { if (!Poll() && (!g_timeout || g_interrupted)) break; } close(g_servfd); if (!g_timeout) { INFOF("timeout expired, shutting down"); } else { INFOF("got ctrl-c, shutting down"); } return 0; } void Daemonize(void) { struct stat st; if (fork() > 0) _exit(0); setsid(); if (fork() > 0) _exit(0); dup2(g_bogusfd, stdin->fd); if (!g_sendready) dup2(g_bogusfd, stdout->fd); freopen(kLogFile, "ae", stderr); if (fstat(fileno(stderr), &st) != -1 && st.st_size > kLogMaxBytes) { ftruncate(fileno(stderr), 0); } } int main(int argc, char *argv[]) { int i; SetupPresharedKeySsl(MBEDTLS_SSL_IS_SERVER, GetRunitPsk()); __log_level = kLogWarn; GetOpts(argc, argv); for (i = 3; i < 16; ++i) close(i); errno = 0; // poll()'ing /dev/null stdin file descriptor on xnu returns POLLNVAL?! if (IsWindows()) { CHECK_EQ(3, (g_bogusfd = open("/dev/null", O_RDONLY | O_CLOEXEC))); } else { CHECK_EQ(3, (g_bogusfd = open("/dev/zero", O_RDONLY | O_CLOEXEC))); } if (!isdirectory("o")) CHECK_NE(-1, mkdir("o", 0700)); if (g_daemonize) Daemonize(); return Serve(); }
18,914
587
jart/cosmopolitan
false
cosmopolitan/tool/build/printf.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/stdio/stdio.h" #include "libc/str/str.h" static bool isoctal(char c) { return '0' <= c && c <= '7'; } char *U(char *p) { int c, i = 0, j = 0; for (;;) { switch ((c = p[i++] & 255)) { case '\\': switch ((c = p[i++] & 255)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (isoctal(p[i])) { if (isoctal(p[i + 1])) { p[j++] = (c - '0') << 6 | (p[i] - '0') << 3 | (p[i + 1] - '0'); i += 2; continue; } else { p[j++] = (c - '0') << 3 | (p[i++] - '0'); continue; } } else { p[j++] = (c - '0'); continue; } case '\\': p[j++] = '\\'; continue; case 'a': p[j++] = '\a'; continue; case 'b': p[j++] = '\b'; continue; case 't': p[j++] = '\t'; continue; case 'f': p[j++] = '\f'; continue; case 'v': p[j++] = '\v'; continue; case 'e': p[j++] = '\e'; continue; case 'r': p[j++] = '\r'; continue; case 'n': p[j++] = '\n'; continue; case '"': p[j++] = '"'; continue; case '\'': p[j++] = '\''; continue; } // fallthrough default: p[j++] = c; break; case '\0': p[j] = 0; return p; } } } int main(int argc, char *argv[]) { switch (argc) { case 2: printf(U(argv[1])); return 0; case 3: printf(U(argv[1]), argv[2]); return 0; case 4: printf(U(argv[1]), argv[2], argv[3]); return 0; case 5: printf(U(argv[1]), argv[2], argv[3], argv[4]); return 0; case 6: printf(U(argv[1]), argv[2], argv[3], argv[4], argv[5]); return 0; case 7: printf(U(argv[1]), argv[2], argv[3], argv[4], argv[5], argv[6]); return 0; case 8: printf(U(argv[1]), argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]); return 0; default: if (argc > 0) { fprintf(stderr, "%s: %s format [arguments]\n", argv[0], argv[0]); } return 1; } }
4,347
128
jart/cosmopolitan
false
cosmopolitan/tool/build/rm.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/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" #define USAGE \ " FILE...\n\ \n\ SYNOPSIS\n\ \n\ Removes Files\n\ \n\ FLAGS\n\ \n\ -?\n\ -h help\n\ -f force\n\ \n" bool force; const char *prog; 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, "?hf")) != -1) { switch (opt) { case 'f': force = true; break; case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } void Remove(const char *path) { const char *s; if (!force && access(path, W_OK) == -1) goto OnFail; if (unlink(path) == -1) goto OnFail; return; OnFail: if (force && errno == ENOENT) return; s = _strerdoc(errno); fputs(prog, stderr); fputs(": cannot remove '", stderr); fputs(path, stderr); fputs("': ", stderr); fputs(s, stderr); fputs("\n", stderr); exit(1); } int main(int argc, char *argv[]) { int i; prog = argc > 0 ? argv[0] : "rm.com"; if (argc < 2) { fputs(prog, stderr); fputs(": missing operand\n" "Try 'rm -h' for more information.\n", stderr); exit(1); } GetOpts(argc, argv); for (i = optind; i < argc; ++i) { Remove(argv[i]); } }
3,447
104
jart/cosmopolitan
false
cosmopolitan/tool/build/build.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += TOOL_BUILD TOOL_BUILD_FILES := $(wildcard tool/build/*) TOOL_BUILD_SRCS = $(filter %.c,$(TOOL_BUILD_FILES)) TOOL_BUILD_HDRS = $(filter %.h,$(TOOL_BUILD_FILES)) TOOL_BUILD_CTESTS = $(filter %.ctest,$(TOOL_BUILD_FILES)) TOOL_BUILD_BINS = \ $(TOOL_BUILD_COMS) \ $(TOOL_BUILD_COMS:%=%.dbg) \ o/$(MODE)/tool/build/mkdir \ o/$(MODE)/tool/build/chmod \ o/$(MODE)/tool/build/cp \ o/$(MODE)/tool/build/mv \ o/$(MODE)/tool/build/echo \ o/$(MODE)/tool/build/false \ o/$(MODE)/tool/build/gzip \ o/$(MODE)/tool/build/printf \ o/$(MODE)/tool/build/dd TOOL_BUILD_CALCULATOR = o/$(MODE)/tool/build/calculator.com TOOL_BUILD_OBJS = \ $(TOOL_BUILD_SRCS:%.c=o/$(MODE)/%.o) TOOL_BUILD_COMS = \ $(TOOL_BUILD_SRCS:%.c=o/$(MODE)/%.com) TOOL_BUILD_CHECKS = \ $(TOOL_BUILD).pkg \ $(TOOL_BUILD_HDRS:%=o/$(MODE)/%.ok) \ $(TOOL_BUILD_CTESTS:%=o/$(MODE)/%.ok) TOOL_BUILD_DIRECTDEPS = \ DSP_CORE \ DSP_SCALE \ DSP_TTY \ LIBC_CALLS \ LIBC_DNS \ LIBC_ELF \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_KERNEL32 \ LIBC_NT_USER32 \ LIBC_NT_WS2_32 \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_THREAD \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_X \ LIBC_ZIPOS \ NET_HTTPS \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_GDTOA \ THIRD_PARTY_GETOPT \ THIRD_PARTY_MBEDTLS \ THIRD_PARTY_MUSL \ THIRD_PARTY_REGEX \ THIRD_PARTY_STB \ THIRD_PARTY_XED \ THIRD_PARTY_ZLIB \ THIRD_PARTY_ZLIB_GZ \ TOOL_BUILD_LIB TOOL_BUILD_DEPS := \ $(call uniq,$(foreach x,$(TOOL_BUILD_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/build/build.pkg: \ $(TOOL_BUILD_OBJS) \ $(foreach x,$(TOOL_BUILD_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/%.ctest.ok: \ %.ctest \ $(TOOL_BUILD_CALCULATOR) \ $(VM) @$(COMPILE) -AMKWIDES -wtT$@ $(VM) $(TOOL_BUILD_CALCULATOR) $< o/$(MODE)/tool/build/%.com.dbg: \ $(TOOL_BUILD_DEPS) \ o/$(MODE)/tool/build/build.pkg \ o/$(MODE)/tool/build/%.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/build/blinkenlights.com: \ o/$(MODE)/tool/build/blinkenlights.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) o/$(MODE)/tool/build/emulator.o: private \ OVERRIDE_COPTS += \ -fno-sanitize=pointer-overflow o/$(MODE)/tool/build/dso/sandbox.so.zip.o \ o/$(MODE)/tool/build/mkdir.zip.o \ o/$(MODE)/tool/build/chmod.zip.o \ o/$(MODE)/tool/build/cp.zip.o \ o/$(MODE)/tool/build/mv.zip.o \ o/$(MODE)/tool/build/false.zip.o \ o/$(MODE)/tool/build/false.com.zip.o \ o/$(MODE)/tool/build/echo.zip.o \ o/$(MODE)/tool/build/echo.com.zip.o \ o/$(MODE)/tool/build/cocmd.com.zip.o \ o/$(MODE)/tool/build/gzip.zip.o \ o/$(MODE)/tool/build/printf.zip.o \ o/$(MODE)/tool/build/dd.zip.o: private \ ZIPOBJ_FLAGS += \ -B # we need pic because: # so it can be an LD_PRELOAD payload o/$(MODE)/tool/build/dso/sandbox.o: private \ OVERRIDE_CFLAGS += \ -fPIC o/$(MODE)/tool/build/dso/sandbox.o: \ libc/calls/calls.h \ tool/build/dso/sandbox.c \ libc/calls/pledge.h \ libc/runtime/runtime.h \ libc/calls/pledge.internal.h \ libc/intrin/promises.internal.h \ tool/build/build.mk o/$(MODE)/tool/build/dso/sandbox.so: \ o/$(MODE)/tool/build/dso/sandbox.o \ o/$(MODE)/libc/calls/pledge-linux.o \ o/$(MODE)/libc/sysv/restorert.o @$(COMPILE) -ALINK.so \ $(CC) \ -s \ -shared \ -nostdlib \ -Wl,--gc-sections \ o/$(MODE)/tool/build/dso/sandbox.o \ o/$(MODE)/libc/calls/pledge-linux.o \ o/$(MODE)/libc/sysv/restorert.o \ $(OUTPUT_OPTION) o/$(MODE)/tool/build/pledge.com.dbg: \ $(TOOL_BUILD_DEPS) \ o/$(MODE)/tool/build/build.pkg \ o/$(MODE)/tool/build/dso/sandbox.so.zip.o \ o/$(MODE)/tool/build/pledge.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) .PHONY: o/$(MODE)/tool/build o/$(MODE)/tool/build: \ o/$(MODE)/tool/build/emucrt \ o/$(MODE)/tool/build/emubin \ o/$(MODE)/tool/build/lib \ $(TOOL_BUILD_BINS) \ $(TOOL_BUILD_CHECKS)
4,524
173
jart/cosmopolitan
false
cosmopolitan/tool/build/helpop.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/conv.h" #include "libc/intrin/safemacros.internal.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 "third_party/getopt/getopt.h" #define USAGE \ " [FLAGS] OPERAND..\n\ Decodes geek operand notation used by ref.x86asm.net\n\ \n\ Flags:\n\ -s succinct mode\n\ -b BITS sets 16/32/64 bit mode [default 64]\n\ -? shows this information\n\ \n\ Examples:\n\ o/tool/cpu/help-operand -b64 Evqp\n\ \n" int bits_; bool succinct_; void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void GetOpts(int argc, char *argv[]) { int opt; bits_ = 64; while ((opt = getopt(argc, argv, "?hbs")) != -1) { switch (opt) { case 's': succinct_ = true; break; case 'b': bits_ = atoi(optarg); break; case '?': case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } const struct Descriptors { const char prefix[8]; const char *succinct; const char *description; } kDescriptors[] = { {"AL", "AL", "AL register"}, {"CS", "CS", "CS register (code segment)"}, {"va", "?", "Word or doubleword, according to asz address-size attribute (only REP " "and LOOP families)."}, {"dqa", "?", "Doubleword or quadword, according to asz address-size attribute (only " "REP and LOOP families)."}, {"wa", "?", "Word, according to asz address-size attribute (only JCXZ instruction)."}, {"wo", "?", "Word, according to current operand size (e. g., MOVSW instruction)."}, {"ws", "?", "Word, according to current stack size (only PUSHF and POPF instructions " "in 64-bit mode)."}, {"da", "?", "Doubleword, according to asz address-size attribute (only JECXZ " "instruction)."}, {"do", "?", "Doubleword, according to current osz operand size (e. g., MOVSD " "instruction)."}, {"qa", "?", "Quadword, according to asz address-size attribute (only JRCXZ " "instruction)."}, {"qs", "64/16", "Quadword, according to current stack size via osz operand-size (only " "PUSHFQ and POPFQ instructions)."}, {"va", "16/32", "Word or doubleword sign extended to the size of the stack pointer (for " "example, PUSH (68))."}, {"vqp", "16/32/64", "Word or doubleword, depending on operand-size attribute, or " "quadword, promoted by REX.W in 64-bit mode."}, {"vs", "16/32", "Word or doubleword sign extended to the size of the stack pointer (for " "example, PUSH (68))."}, {"vds", "16/32", "Word or doubleword, depending on operand-size attribute, or doubleword, " "sign-extended to 64 bits for 64-bit operand size."}, {"vq", "64/16", "Quadword (default) or word if operand-size prefix is used (for " "example, PUSH (50))."}, {"EST", "STi", "A ModR/M byte follows the opcode and specifies the x87 FPU stack " "register."}, {"ES", "STi/m", "A ModR/M byte follows the opcode and specifies the operand. The " "operand is either a x87 FPU stack register or a memory address. If " "it is a memory address, the address is computed from a segment " "register and any of the following values: a base register, an " "index register, a scaling factor, or a displacement."}, {"SC", "", "Stack operand, used by instructions which either push an operand to the " "stack or pop an operand from the stack. Pop-like instructions are, for " "example, POP, RET, IRET, LEAVE. Push-like are, for example, PUSH, CALL, " "INT. No Operand type is provided along with this method because it " "depends on source/destination operand(s)."}, {"BA", "m", "Memory addressed by DS:EAX, or by rAX in 64-bit mode (only 0F01C8 " "MONITOR)."}, {"BB", "m", "Memory addressed by DS:eBX+AL, or by rBX+AL in 64-bit mode (only XLAT)."}, {"BD", "m", "Memory addressed by DS:eDI or by RDI (only 0FF7 MASKMOVQ and 660FF7 " "MASKMOVDQU)"}, {"A", "ptr", "Direct address. The instruction has no ModR/M byte; the address of the " "operand is encoded in the instruction; no base register, index register, " "or scaling factor can be applied (for example, far JMP (EA))."}, {"C", "CRn", "The reg field of the ModR/M byte selects a control register (only MOV " "(0F20, 0F22))."}, {"D", "DRn", "The reg field of the ModR/M byte selects a debug register (only MOV " "(0F21, 0F23))."}, {"I", "imm", "Immediate data. The operand value is encoded in subsequent bytes of the " "instruction."}, {"J", "rel", "The instruction contains a relative offset to be added to the " "instruction pointer register (for example, JMP (E9), LOOP))."}, {"E", "r/m", "A ModR/M byte follows the opcode and specifies the operand. The " "operand is either a general-purpose register or a memory address. " "If it is a memory address, the address is computed from a segment " "register and any of the following values: a base register, an index " "register, a scaling factor, or a displacement."}, {"G", "r", "The reg field of the ModR/M byte selects a general register (for " "example, AX (000))."}, {"H", "r", "The r/m field of the ModR/M byte always selects a general register, " "regardless of the mod field (for example, MOV (0F20))."}, {"M", "rm", "The ModR/M byte may refer only to memory: mod != 11bin (BOUND, LEA, " "CALLF, JMPF, LES, LDS, LSS, LFS, LGS, CMPXCHG8B, CMPXCHG16B, F20FF0 " "LDDQU)."}, {"N", "mm", "The R/M field of the ModR/M byte selects a packed quadword MMX " "technology register."}, {"O", "moffs", "The instruction has no ModR/M byte; the offset of the operand is coded " "as a word, double word or quad word (depending on address size " "attribute) in the instruction. No base register, index register, or " "scaling factor can be applied (only MOV (A0, A1, A2, A3))."}, {"P", "mm", "The reg field of the ModR/M byte selects a packed quadword MMX " "technology register."}, {"Q", "mm/m64", "A ModR/M byte follows the opcode and specifies the operand. The " "operand is either an MMX technology register or a memory address. " "If it is a memory address, the address is computed from a segment " "register and any of the following values: a base register, an index " "register, a scaling factor, and a displacement."}, {"R", "r", "The mod field of the ModR/M byte may refer only to a general " "register (only MOV (0F20-0F24, 0F26))."}, {"S", "Sreg", "The reg field of the ModR/M byte selects a segment register (only MOV " "(8C, 8E))."}, {"T", "TRn", "The reg field of the ModR/M byte selects a test register (only MOV " "(0F24, 0F26))."}, {"U", "xmm", "The R/M field of the ModR/M byte selects a 128-bit XMM register."}, {"sr", "32real", "Single-real. Only x87 FPU instructions (for example, FADD)."}, {"dr", "64real", "Double-real. Only x87 FPU instructions (for example, FADD)."}, {"er", "80real", "Extended-real. Only x87 FPU instructions (for example, FLD)."}, {"e", "14/28", "x87 FPU environment (for example, FSTENV)."}, {"V", "xmm", "The reg field of the ModR/M byte selects a 128-bit XMM register."}, {"W", "xmm/m", "A ModR/M byte follows the opcode and specifies the operand. The operand " "is either a 128-bit XMM register or a memory address. If it is a memory " "address, the address is computed from a segment register and any of the " "following values: a base register, an index register, a scaling factor, " "and a displacement"}, {"X", "m", "Memory addressed by the DS:eSI or by RSI (only MOVS, CMPS, OUTS, " "and LODS). In 64-bit mode, only 64-bit (RSI) and 32-bit (ESI) " "address sizes are supported. In non-64-bit modes, only 32-bit (ESI) " "and 16-bit (SI) address sizes are supported."}, {"Y", "m", "Memory addressed by the ES:eDI or by RDI (only MOVS, CMPS, INS, " "STOS, and SCAS). In 64-bit mode, only 64-bit (RDI) and 32-bit (EDI) " "address sizes are supported. In non-64-bit modes, only 32-bit (EDI) " "and 16-bit (DI) address sizes are supported. The implicit ES " "segment register cannot be overridden by a segment prefix."}, {"Z", "r", "The instruction has no ModR/M byte; the three least-significant " "bits of the opcode byte selects a general-purpose register."}, {"F", "-", "rFLAGS register."}, {"si", "32real", "Doubleword integer register (e. g., eax). (unused even by Intel?)"}, {"ss", "-", "Scalar element of a 128-bit packed single-precision floating data."}, {"stx", "512", "x87 FPU and SIMD state (FXSAVE and FXRSTOR)."}, {"st", "94/108", "x87 FPU state (for example, FSAVE)."}, {"s", "-", "6-byte pseudo-descriptor, or 10-byte pseudo-descriptor in 64-bit mode " "(for example, SGDT)."}, {"bcd", "80dec", "Packed-BCD. Only x87 FPU instructions (for example, FBLD)."}, {"bsq", "", "(Byte, sign-extended to 64 bits.)"}, {"bss", "8", "Byte, sign-extended to the size of the stack pointer (for example, PUSH " "(6A))."}, {"bs", "8", "Byte, sign-extended to the size of the destination operand."}, {"a", "16/32&16/32", "Two one-word operands in memory or two double-word operands in memory, " "depending on operand-size attribute (only BOUND)."}, {"b", "8", "Byte, regardless of operand-size attribute."}, {"c", "?", "Byte or word, depending on operand-size attribute. (unused even by " "Intel?)"}, {"dqp", "32/64", "Doubleword, or quadword, promoted by REX.W in 64-bit mode (for example, " "MOVSXD)."}, {"dq", "128", "Double-quadword, regardless of operand-size attribute (for example, " "CMPXCHG16B)."}, {"ds", "32", "Doubleword, sign-extended to 64 bits (for example, CALL (E8)."}, {"di", "32int", "Doubleword-integer. Only x87 FPU instructions (for example, FIADD)."}, {"d", "32", "Doubleword, regardless of operand-size attribute."}, {"qi", "64int", "Qword-integer. Only x87 FPU instructions (for example, FILD)."}, {"qp", "64", "Quadword, promoted by REX.W (for example, IRETQ)."}, {"q", "64", "Quadword, regardless of operand-size attribute (for example, CALL (FF " "/2))."}, {"v", "16/32", "Word or doubleword, depending on operand-size attribute (for example, " "INC (40), PUSH (50))."}, {"wi", "16int", "Word-integer. Only x87 FPU instructions (for example, FIADD)."}, {"w", "16", "Word, regardless of operand-size attribute (for example, ENTER)."}, {"pi", "-", "Quadword MMX technology data."}, {"psq", "-", "64-bit packed single-precision floating-point data."}, {"pd", "-", "128-bit packed double-precision floating-point data."}, {"ps", "-", "128-bit packed single-precision floating-point data."}, {"ptp", "16:16/32/64", "32-bit or 48-bit pointer, depending on operand-size attribute, or 80-bit " "far pointer, promoted by REX.W in 64-bit mode (for example, " "CALLF (FF /3))."}, {"p", "16:16/32", "32-bit or 48-bit pointer, depending on operand-size attribute (for " "example, CALLF (9A)."}, }; void HandleOperand(const char *op) { int i; bool found; while (*op) { found = false; for (i = 0; i < ARRAYLEN(kDescriptors); ++i) { if (_startswith(op, kDescriptors[i].prefix)) { found = true; op += strlen(kDescriptors[i].prefix); if (succinct_) { printf("%s ", kDescriptors[i].succinct); } else if (!isempty(kDescriptors[i].succinct) && strcmp(kDescriptors[i].succinct, "-") != 0 && strcmp(kDescriptors[i].succinct, "?") != 0) { printf("%s (%s): %s\n", kDescriptors[i].prefix, kDescriptors[i].succinct, kDescriptors[i].description); } else { printf("%s: %s\n", kDescriptors[i].prefix, kDescriptors[i].description); } break; } } if (!found) { printf("%c?", *op); if (succinct_) { printf(" "); } else { printf("\n"); } op++; } } printf("\n"); } int main(int argc, char *argv[]) { int i; GetOpts(argc, argv); for (i = optind; i < argc; ++i) { HandleOperand(argv[i]); } return 0; }
14,661
372
jart/cosmopolitan
false
cosmopolitan/tool/build/package.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/elf.h" #include "libc/elf/struct/shdr.h" #include "libc/elf/struct/sym.h" #include "libc/intrin/bswap.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "third_party/getopt/getopt.h" #include "third_party/xed/x86.h" #include "tool/build/lib/getargs.h" #include "tool/build/lib/persist.h" /** * @fileoverview Build Package Script. * * FIRST PURPOSE * * This script verifies the well-formedness of dependencies, e.g. * * o/tool/build/package.com \ * -o o/libc/stubs/stubs.pkg \ * o/libc/stubs/{a,b,...}.o * * o/tool/build/package.com \ * -o o/libc/nexgen32e/nexgen32e.pkg \ * -d o/libc/stubs/stubs.pkg \ * o/libc/nexgen32e/{a,b,...}.o * * We want the following: * * 1. FOO declares in FOO_DIRECTDEPS where its undefined symbols are. * 2. FOO_DIRECTDEPS is complete, so FOO ∪ FOO_DIRECTDEPS has no UNDEFs. * 3. FOO_DIRECTDEPS is non-transitive; thus this tool is incremental. * 4. Package relationships on a whole are acyclic. * * These rules help keep the structure of large codebases easy to * understand. More importantly, it allows us to further optimize * compiled objects very cheaply as the build progresses. */ #define PACKAGE_MAGIC bswap_32(0xBEEFBEEFu) #define PACKAGE_ABI 1 struct Packages { size_t i, n; struct Package { uint32_t magic; int32_t abi; uint32_t path; // pkg->strings.p[path] int64_t fd; // not persisted void *addr; // not persisted size_t size; // not persisted struct Strings { size_t i, n; char *p; // persisted as pkg+RVA } strings; // TODO(jart): interning? struct Objects { size_t i, n; struct Object { uint32_t path; // pkg->strings.p[path] unsigned mode; // not persisted struct Elf64_Ehdr *elf; // not persisted size_t size; // not persisted char *strs; // not persisted Elf64_Sym *syms; // not persisted Elf64_Xword symcount; // not persisted struct Sections { size_t i, n; struct Section { enum SectionKind { kUndef, kText, kData, kPiroRelo, kPiroData, kPiroBss, kBss, } kind; } * p; } sections; // not persisted } * p; // persisted as pkg+RVA } objects; struct Symbols { size_t i, n; struct Symbol { uint32_t name; // pkg->strings.p[name] enum SectionKind kind : 8; uint8_t bind_ : 4; uint8_t type : 4; uint16_t object; // pkg->objects.p[object] } * p; // persisted as pkg+RVA } symbols, undefs; // TODO(jart): hash undefs? } * *p; // persisted across multiple files }; int CompareSymbolName(const struct Symbol *a, const struct Symbol *b, const char *tab) { return strcmp(tab + a->name, tab + b->name); } struct Package *LoadPackage(const char *path) { int fd; ssize_t i; struct stat st; struct Package *pkg; CHECK(fileexists(path), "%s: %s: %s\n", "error", path, "not found"); CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_NE(MAP_FAILED, (pkg = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)), "path=%s", path); CHECK_NE(-1, close(fd)); CHECK_EQ(PACKAGE_MAGIC, pkg->magic, "corrupt package: %`'s", path); pkg->strings.p = (char *)((intptr_t)pkg->strings.p + (intptr_t)pkg); pkg->objects.p = (struct Object *)((intptr_t)pkg->objects.p + (intptr_t)pkg); pkg->symbols.p = (struct Symbol *)((intptr_t)pkg->symbols.p + (intptr_t)pkg); pkg->addr = pkg; pkg->size = st.st_size; CHECK_NE(-1, mprotect(pkg, st.st_size, PROT_READ)); return pkg; } void AddDependency(struct Packages *deps, const char *path) { struct Package *pkg; pkg = LoadPackage(path); CHECK_NE(-1, append(deps, &pkg)); } void WritePackage(struct Package *pkg) { CHECK_NE(0, PACKAGE_MAGIC); pkg->magic = PACKAGE_MAGIC; pkg->abi = PACKAGE_ABI; DEBUGF("%s has %,ld objects, %,ld symbols, and a %,ld byte string table", &pkg->strings.p[pkg->path], pkg->objects.i, pkg->symbols.i, pkg->strings.i); PersistObject( &pkg->strings.p[pkg->path], 64, &(struct ObjectParam){ sizeof(struct Package), pkg, &pkg->magic, &pkg->abi, (struct ObjectArrayParam[]){ {pkg->strings.i, sizeof(pkg->strings.p[0]), &pkg->strings.p}, {pkg->objects.i, sizeof(pkg->objects.p[0]), &pkg->objects.p}, {pkg->symbols.i, sizeof(pkg->symbols.p[0]), &pkg->symbols.p}, {0}, }, }); } void GetOpts(struct Package *pkg, struct Packages *deps, int argc, char *argv[]) { long i, si, opt; const char *arg; struct GetArgs ga; pkg->path = -1; while ((opt = getopt(argc, argv, "vho:d:")) != -1) { switch (opt) { case 'v': __log_level = kLogDebug; break; case 'o': pkg->path = concat(&pkg->strings, optarg, strlen(optarg) + 1); break; case 'd': AddDependency(deps, optarg); break; case 'h': exit(0); default: fprintf(stderr, "%s: %s [%s %s] [%s %s] %s\n", "Usage", program_invocation_name, "-o", "OUTPACKAGE", "-d", "DEPPACKAGE", "OBJECT..."); exit(1); } } CHECK_NE(-1, pkg->path, "no packages passed to package.com"); CHECK_LT(optind, argc, "no objects passed to package.com; " "is your foo.mk $(FOO_OBJS) glob broken?"); getargs_init(&ga, argv + optind); while ((arg = getargs_next(&ga))) { CHECK_NE(-1, (si = concat(&pkg->strings, arg, strlen(arg) + 1))); CHECK_NE(-1, append(&pkg->objects, (&(struct Object){si}))); } getargs_destroy(&ga); } void IndexSections(struct Object *obj) { size_t i; const char *name; const uint8_t *code; struct Section sect; const Elf64_Shdr *shdr; struct XedDecodedInst xedd; for (i = 0; i < obj->elf->e_shnum; ++i) { bzero(&sect, sizeof(sect)); CHECK_NOTNULL((shdr = GetElfSectionHeaderAddress(obj->elf, obj->size, i))); if (shdr->sh_type != SHT_NULL) { CHECK_NOTNULL((name = GetElfSectionName(obj->elf, obj->size, shdr))); if (_startswith(name, ".sort.")) name += 5; if ((strcmp(name, ".piro.relo") == 0 || _startswith(name, ".piro.relo.")) || (strcmp(name, ".data.rel.ro") == 0 || _startswith(name, ".data.rel.ro."))) { sect.kind = kPiroRelo; } else if (strcmp(name, ".piro.data") == 0 || _startswith(name, ".piro.data.")) { sect.kind = kPiroData; } else if (strcmp(name, ".piro.bss") == 0 || _startswith(name, ".piro.bss.")) { sect.kind = kPiroBss; } else if (strcmp(name, ".data") == 0 || _startswith(name, ".data.")) { sect.kind = kData; } else if (strcmp(name, ".bss") == 0 || _startswith(name, ".bss.")) { sect.kind = kBss; } else { sect.kind = kText; } } else { sect.kind = kUndef; /* should always and only be section #0 */ } CHECK_NE(-1, append(&obj->sections, &sect)); } } enum SectionKind ClassifySection(struct Object *obj, uint8_t type, Elf64_Section shndx) { if (type == STT_COMMON) return kBss; if (!obj->sections.i) return kText; return obj->sections.p[min(max(0, shndx), obj->sections.i - 1)].kind; } void LoadSymbols(struct Package *pkg, uint32_t object) { Elf64_Xword i; const char *name; struct Object *obj; struct Symbol symbol; obj = &pkg->objects.p[object]; symbol.object = object; for (i = 0; i < obj->symcount; ++i) { symbol.bind_ = ELF64_ST_BIND(obj->syms[i].st_info); symbol.type = ELF64_ST_TYPE(obj->syms[i].st_info); if (symbol.bind_ != STB_LOCAL && (symbol.type == STT_OBJECT || symbol.type == STT_FUNC || symbol.type == STT_COMMON || symbol.type == STT_NOTYPE)) { name = GetElfString(obj->elf, obj->size, obj->strs, obj->syms[i].st_name); DEBUGF("%s", name); if (strcmp(name, "_GLOBAL_OFFSET_TABLE_") != 0) { symbol.kind = ClassifySection(obj, symbol.type, obj->syms[i].st_shndx); CHECK_NE(-1, (symbol.name = concat(&pkg->strings, name, strlen(name) + 1))); CHECK_NE(-1, append(symbol.kind != kUndef ? &pkg->symbols : &pkg->undefs, &symbol)); } } } } void OpenObject(struct Package *pkg, struct Object *obj, int mode, int prot, int flags) { int fd; struct stat st; CHECK_NE(-1, (fd = open(&pkg->strings.p[obj->path], (obj->mode = mode))), "path=%`'s", &pkg->strings.p[obj->path]); CHECK_NE(-1, fstat(fd, &st)); CHECK_NE( MAP_FAILED, (obj->elf = mmap(NULL, (obj->size = st.st_size), prot, flags, fd, 0)), "path=%`'s", &pkg->strings.p[obj->path]); CHECK_NE(-1, close(fd)); CHECK(IsElf64Binary(obj->elf, obj->size), "path=%`'s", &pkg->strings.p[obj->path]); CHECK_NOTNULL((obj->strs = GetElfStringTable(obj->elf, obj->size)), "on %s", &pkg->strings.p[obj->path]); CHECK_NOTNULL( (obj->syms = GetElfSymbolTable(obj->elf, obj->size, &obj->symcount))); CHECK_NE(0, obj->symcount); IndexSections(obj); } void CloseObject(struct Object *obj) { CHECK_NE(-1, munmap(obj->elf, obj->size)); } void LoadObjects(struct Package *pkg) { size_t i; struct Object *obj; for (i = 0; i < pkg->objects.i; ++i) { obj = pkg->objects.p + i; OpenObject(pkg, obj, O_RDONLY, PROT_READ, MAP_SHARED); LoadSymbols(pkg, i); CloseObject(obj); } qsort_r(pkg->symbols.p, pkg->symbols.i, sizeof(*pkg->symbols.p), (void *)CompareSymbolName, pkg->strings.p); } struct Symbol *BisectSymbol(struct Package *pkg, const char *name) { int c; long m, l, r; l = 0; r = pkg->symbols.i - 1; while (l <= r) { m = (l + r) >> 1; c = strcmp(pkg->strings.p + pkg->symbols.p[m].name, name); if (c < 0) { l = m + 1; } else if (c > 0) { r = m - 1; } else { return pkg->symbols.p + m; } } return NULL; } bool FindSymbol(const char *name, struct Package *pkg, struct Packages *directdeps, struct Package **out_pkg, struct Symbol **out_sym) { size_t i, j; struct Symbol *sym; if ((sym = BisectSymbol(pkg, name))) { if (out_sym) *out_sym = sym; if (out_pkg) *out_pkg = pkg; return true; } for (i = 0; i < directdeps->i; ++i) { if ((sym = BisectSymbol(directdeps->p[i], name))) { if (out_sym) *out_sym = sym; if (out_pkg) *out_pkg = directdeps->p[i]; return true; } } return false; } void CheckStrictDeps(struct Package *pkg, struct Packages *deps) { size_t i, j; struct Package *dep; struct Symbol *undef; for (i = 0; i < pkg->undefs.i; ++i) { undef = &pkg->undefs.p[i]; if (undef->bind_ == STB_WEAK) continue; if (!FindSymbol(pkg->strings.p + undef->name, pkg, deps, NULL, NULL)) { fprintf(stderr, "%s: %`'s (%s) %s %s\n", "error", pkg->strings.p + undef->name, pkg->strings.p + pkg->objects.p[undef->object].path, "not defined by direct deps of", pkg->strings.p + pkg->path); for (j = 0; j < deps->i; ++j) { dep = deps->p[j]; fputc('\t', stderr); fputs(dep->strings.p + dep->path, stderr); fputc('\n', stderr); } exit(1); } } free(pkg->undefs.p); bzero(&pkg->undefs, sizeof(pkg->undefs)); } forceinline bool IsRipRelativeModrm(uint8_t modrm) { return (modrm & 0b11000111) == 0b00000101; } forceinline uint8_t ChangeRipToRbx(uint8_t modrm) { return (modrm & 0b00111000) | 0b10000011; } bool IsSymbolDirectlyReachable(struct Package *pkg, struct Packages *deps, const char *symbol) { return FindSymbol(symbol, pkg, deps, NULL, NULL); } void Package(int argc, char *argv[], struct Package *pkg, struct Packages *deps) { size_t i, j; GetOpts(pkg, deps, argc, argv); LoadObjects(pkg); CheckStrictDeps(pkg, deps); WritePackage(pkg); for (i = 0; i < deps->i; ++i) { CHECK_NE(-1, munmap(deps->p[i]->addr, deps->p[i]->size)); } for (i = 0; i < pkg->objects.i; ++i) { free(pkg->objects.p[i].sections.p); } free(pkg->strings.p); free(pkg->objects.p); free(pkg->symbols.p); free(deps->p); } int main(int argc, char *argv[]) { struct Package pkg; struct Packages deps; if (argc == 2 && !strcmp(argv[1], "-n")) exit(0); if (IsModeDbg()) ShowCrashReports(); bzero(&pkg, sizeof(pkg)); bzero(&deps, sizeof(deps)); Package(argc, argv, &pkg, &deps); return 0; }
15,170
436
jart/cosmopolitan
false
cosmopolitan/tool/build/chmod.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/dirent.h" #include "libc/errno.h" #include "libc/fmt/conv.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" #define USAGE \ " OCTAL DST...\n\ \n\ SYNOPSIS\n\ \n\ Changes File Mode Bits\n\ \n\ FLAGS\n\ \n\ -?\n\ -h help\n\ \n" const char *prog; 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, "?h")) != -1) { switch (opt) { case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } int main(int argc, char *argv[]) { int i, mode; char buf[PATH_MAX]; { printf("curdir %s\n", getcwd(buf, sizeof(buf))); printf("tmp:"); struct dirent *e; DIR *d; if ((d = opendir("tmp"))) { while ((e = readdir(d))) { printf(" %s", e->d_name); } closedir(d); } else { printf(" dir not found"); } printf("\n"); } { printf("curdir %s\n", getcwd(buf, sizeof(buf))); printf("bin:"); struct dirent *e; DIR *d; if ((d = opendir("bin"))) { while ((e = readdir(d))) { printf(" %s", e->d_name); } closedir(d); } else { printf(" dir not found"); } printf("\n"); } prog = argc > 0 ? argv[0] : "mv.com"; GetOpts(argc, argv); if (argc - optind < 2) { PrintUsage(EX_USAGE, stderr); } mode = strtol(argv[optind], 0, 8) & 07777; for (i = optind + 1; i < argc; ++i) { if (chmod(argv[i], mode) == -1) { const char *s = _strerdoc(errno); fputs(prog, stderr); fputs(": ", stderr); fputs(argv[i], stderr); fputs(": ", stderr); fputs(s, stderr); fputs("\n", stderr); exit(1); } } return 0; }
3,872
121
jart/cosmopolitan
false
cosmopolitan/tool/build/mkdir.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/errno.h" #include "libc/fmt/conv.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [-p] [-m MODE] DIR...\n\ Utility for creating directories.\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -m MODE Octal mode\n\ -p Make parent directories\n" const char *prog; wontreturn void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(prog, f); fputs(USAGE, f); exit(rc); } int main(int argc, char *argv[]) { int i, mode = 0755; int (*mkdirp)(const char *, unsigned) = mkdir; prog = argc > 0 ? argv[0] : "mkdir.com"; while ((i = getopt(argc, argv, "?hpm:")) != -1) { switch (i) { case 'p': mkdirp = makedirs; break; case 'm': mode = strtol(optarg, 0, 8); break; case '?': case 'h': PrintUsage(0, stdout); default: PrintUsage(EX_USAGE, stderr); } } if (optind == argc) { fputs(prog, stderr); fputs(": missing argument\n", stderr); fputs("Try '", stderr); fputs(prog, stderr); fputs(" -h' for more information.\n", stderr); exit(1); } for (i = optind; i < argc; ++i) { if (mkdirp(argv[i], mode) == -1) { fputs(prog, stderr); fputs(": cannot create directory '", stderr); fputs(argv[i], stderr); fputs("' ", stderr); fputs(_strerdoc(errno), stderr); fputc('\n', stderr); exit(1); } } return 0; }
2,375
83
jart/cosmopolitan
false
cosmopolitan/tool/build/pledge.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/pledge.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/landlock.h" #include "libc/calls/pledge.internal.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/sched_param.h" #include "libc/calls/struct/seccomp.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/sysinfo.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/calls/syscall_support-sysv.internal.h" #include "libc/dce.h" #include "libc/elf/def.h" #include "libc/elf/struct/ehdr.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/promises.internal.h" #include "libc/intrin/safemacros.internal.h" #include "libc/macros.internal.h" #include "libc/math.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/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ioprio.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/pr.h" #include "libc/sysv/consts/prio.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlim.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sched.h" #include "libc/sysv/errfuns.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" // MANUALLY TESTED BY RUNNING // // test/tool/build/pledge_test.sh // STATIC_YOINK("strerror_wr"); STATIC_YOINK("zip_uri_support"); #define USAGE \ "\ usage: pledge.com [-hnN] PROG ARGS...\n\ -h show help\n\ -g GID call setgid()\n\ -u UID call setuid()\n\ -c PATH call chroot()\n\ -v [PERM:]PATH call unveil(PATH, PERM[rwxc])\n\ -V disable unveiling (only pledge)\n\ -q disable stderr violation logging\n\ -k kill process rather than eperm'ing\n\ -n set maximum niceness\n\ -D don't drop capabilities\n\ -N don't normalize file descriptors\n\ -C SECS set cpu limit [default: inherited]\n\ -M BYTES set virtual memory limit [default: 4gb]\n\ -O FILES set file descriptor limit [default: 64]\n\ -P PROCS set process limit [default: preexisting + cpus]\n\ -F BYTES set individual file size limit [default: 4gb]\n\ -T pledge exits 0 if pledge() is supported by host system\n\ -T unveil exits 0 if unveil() is supported by host system\n\ -p PLEDGE may contain any of following separated by spaces\n\ - stdio: allow stdio and benign system calls\n\ - rpath: read-only path ops\n\ - wpath: write path ops\n\ - cpath: create path ops\n\ - dpath: create special files\n\ - chown: allows file ownership changes\n\ - flock: file locks\n\ - tty: terminal ioctls\n\ - recvfd: allow SCM_RIGHTS\n\ - sendfd: allow SCM_RIGHTS\n\ - fattr: allow changing some struct stat bits\n\ - inet: allow IPv4 and IPv6\n\ - unix: allow local sockets\n\ - id: allow setuid and friends\n\ - dns: allow dns and related files\n\ - proc: allow process and thread creation\n\ - exec: implied by default\n\ - prot_exec: allow creating executable memory\n\ - vminfo: allows /proc/stat, /proc/self/maps, etc.\n\ - tmppath: allows /tmp, $TMPPATH, lstat, unlink\n\ \n\ pledge.com v1.8\n\ copyright 2022 justine alexandra roberts tunney\n\ notice licenses are embedded in the binary\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 sandbox that's\n\ inspired by the design of openbsd's pledge() system call. Visit\n\ the https://justine.lol/pledge/ page for online documentation.\n\ \n\ " int g_gflag; int g_uflag; int g_kflag; int g_hflag; bool g_nice; bool g_qflag; bool isdynamic; bool g_noclose; long g_cpuquota; long g_fszquota; long g_nfdquota; long g_memquota; long g_proquota; long g_dontdrop; long g_dontunveil; const char *g_test; const char *g_chroot; const char *g_promises; char dsopath[PATH_MAX]; char tmppath[PATH_MAX]; struct { int n; char **p; } unveils; static void GetOpts(int argc, char *argv[]) { int opt; struct sysinfo si; g_promises = 0; g_nfdquota = 64; g_fszquota = 256 * 1000 * 1000; if (!sysinfo(&si)) { g_memquota = si.totalram; g_proquota = _getcpucount() + si.procs; } else { g_proquota = _getcpucount() * 100; g_memquota = 4L * 1024 * 1024 * 1024; } while ((opt = getopt(argc, argv, "hnqkNVT:p:u:g:c:C:D:P:M:F:O:v:")) != -1) { switch (opt) { case 'n': g_nice = true; break; case 'q': g_qflag = true; break; case 'k': g_kflag = true; break; case 'N': g_noclose = true; break; case 'D': g_dontdrop = true; break; case 'V': g_dontunveil = true; break; case 'T': g_test = optarg; break; case 'c': g_chroot = optarg; break; case 'g': g_gflag = atoi(optarg); break; case 'u': g_uflag = atoi(optarg); break; case 'C': g_cpuquota = atoi(optarg); break; case 'P': g_proquota = atoi(optarg); break; case 'O': g_nfdquota = atoi(optarg); break; case 'F': errno = 0; g_fszquota = sizetol(optarg, 1000); if (errno) { kprintf("error: invalid size: -F %s\n", optarg); exit(1); } break; case 'M': errno = 0; g_memquota = sizetol(optarg, 1024); if (errno) { kprintf("error: invalid size: -F %s\n", optarg); exit(1); } break; case 'p': if (g_promises) { g_promises = xstrcat(g_promises, ' ', optarg); } else { g_promises = optarg; } break; case 'v': unveils.p = realloc(unveils.p, ++unveils.n * sizeof(*unveils.p)); unveils.p[unveils.n - 1] = optarg; break; case 'h': case '?': write(1, USAGE, sizeof(USAGE) - 1); exit(0); default: write(2, USAGE, sizeof(USAGE) - 1); exit(64); } } if (!g_promises) { g_promises = "stdio rpath"; } } const char *prog; char pathbuf[PATH_MAX]; struct pollfd pfds[256]; static bool SupportsLandlock(void) { int e = errno; bool r = landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION) >= 0; errno = e; return r; } int GetPollMaxFds(void) { int n; struct rlimit rl; if (getrlimit(RLIMIT_NOFILE, &rl) != -1) { n = rl.rlim_cur; } else { n = 64; } return MIN(ARRAYLEN(pfds), MAX(3, n)); } void NormalizeFileDescriptors(void) { int e, i, n, fd; n = GetPollMaxFds(); e = errno; closefrom(3); // more secure if linux 5.9+ errno = e; for (i = 0; i < n; ++i) { pfds[i].fd = i; pfds[i].events = POLLIN; } if (poll(pfds, n, 0) == -1) { kprintf("error: poll() failed: %m\n"); exit(1); } for (i = 0; i < 3; ++i) { if (pfds[i].revents & POLLNVAL) { if ((fd = open("/dev/null", O_RDWR)) == -1) { kprintf("error: open(\"/dev/null\") failed: %m\n"); exit(2); } if (fd != i) { kprintf("error: open() is broken: %d vs. %d\n", fd, i); exit(3); } } } for (i = 3; i < n; ++i) { if (~pfds[i].revents & POLLNVAL) { if (close(pfds[i].fd) == -1) { kprintf("error: close(%d) failed: %m\n", pfds[i].fd); exit(4); } } } } int SetLimit(int r, long lo, long hi) { struct rlimit old; struct rlimit lim = {lo, hi}; if (r < 0 || r >= RLIM_NLIMITS) return 0; if (!setrlimit(r, &lim)) return 0; if (getrlimit(r, &old)) return -1; lim.rlim_cur = MIN(lim.rlim_cur, old.rlim_max); lim.rlim_max = MIN(lim.rlim_max, old.rlim_max); return setrlimit(r, &lim); } static int GetBaseCpuFreqMhz(void) { return KCPUIDS(16H, EAX) & 0x7fff; } int SetCpuLimit(int secs) { #ifdef __x86_64__ int mhz, lim; if (secs <= 0) return 0; if (!(mhz = GetBaseCpuFreqMhz())) return eopnotsupp(); lim = ceil(3100. / mhz * secs); return SetLimit(RLIMIT_CPU, lim, lim); #else return 0; #endif } bool PathExists(const char *path) { int err; struct stat st; if (path) { err = errno; if (!stat(path, &st)) { return true; } else { errno = err; return false; } } else { return false; } } void Unveil(const char *path, const char *perm) { if (unveil(path, perm) == -1) { kprintf("error: unveil(%#s, %#s) failed: %m\n", path, perm); _Exit(20); } } int UnveilIfExists(const char *path, const char *perm) { int err; if (path) { err = errno; if (unveil(path, perm) != -1) { return 0; } else if (errno == ENOENT) { errno = err; } else { kprintf("error: unveil(%#s, %#s) failed: %m\n", path, perm); _Exit(20); } } return -1; } void MakeProcessNice(void) { if (!g_nice) return; if (setpriority(PRIO_PROCESS, 0, 19) == -1) { kprintf("error: setpriority(PRIO_PROCESS, 0, 19) failed: %m\n"); exit(23); } if (ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)) == -1) { kprintf("error: ioprio_set() failed: %m\n"); exit(23); } struct sched_param p = {sched_get_priority_min(SCHED_IDLE)}; if (sched_setscheduler(0, SCHED_IDLE, &p) == -1) { kprintf("error: sched_setscheduler(SCHED_IDLE) failed: %m\n"); exit(23); } } void ApplyFilesystemPolicy(unsigned long ipromises) { const char *p; if (g_dontunveil) return; if (!SupportsLandlock()) return; Unveil(prog, "rx"); if (isdynamic) { Unveil(dsopath, "rx"); UnveilIfExists("/lib", "rx"); UnveilIfExists("/lib64", "rx"); UnveilIfExists("/usr/lib", "rx"); UnveilIfExists("/usr/lib64", "rx"); UnveilIfExists("/usr/local/lib", "rx"); UnveilIfExists("/usr/local/lib64", "rx"); UnveilIfExists("/etc/ld-musl-x86_64.path", "r"); UnveilIfExists("/etc/ld.so.conf", "r"); UnveilIfExists("/etc/ld.so.cache", "r"); UnveilIfExists("/etc/ld.so.conf.d", "r"); UnveilIfExists("/etc/ld.so.preload", "r"); } if (~ipromises & (1ul << PROMISE_STDIO)) { UnveilIfExists("/dev/fd", "r"); UnveilIfExists("/dev/log", "w"); UnveilIfExists("/dev/zero", "r"); UnveilIfExists("/dev/null", "rw"); UnveilIfExists("/dev/full", "rw"); UnveilIfExists("/dev/stdin", "rw"); UnveilIfExists("/dev/stdout", "rw"); UnveilIfExists("/dev/stderr", "rw"); UnveilIfExists("/dev/urandom", "r"); UnveilIfExists("/etc/localtime", "r"); UnveilIfExists("/proc/self/fd", "rw"); UnveilIfExists("/proc/self/stat", "r"); UnveilIfExists("/proc/self/status", "r"); UnveilIfExists("/usr/share/locale", "r"); UnveilIfExists("/proc/self/cmdline", "r"); UnveilIfExists("/usr/share/zoneinfo", "r"); UnveilIfExists("/proc/sys/kernel/version", "r"); UnveilIfExists("/usr/share/common-licenses", "r"); UnveilIfExists("/proc/sys/kernel/ngroups_max", "r"); UnveilIfExists("/proc/sys/kernel/cap_last_cap", "r"); UnveilIfExists("/proc/sys/vm/overcommit_memory", "r"); } if (~ipromises & (1ul << PROMISE_INET)) { UnveilIfExists("/etc/ssl/certs/ca-certificates.crt", "r"); } if (~ipromises & (1ul << PROMISE_RPATH)) { UnveilIfExists("/proc/filesystems", "r"); } if (~ipromises & (1ul << PROMISE_DNS)) { UnveilIfExists("/etc/hosts", "r"); UnveilIfExists("/etc/hostname", "r"); UnveilIfExists("/etc/services", "r"); UnveilIfExists("/etc/protocols", "r"); UnveilIfExists("/etc/resolv.conf", "r"); } if (~ipromises & (1ul << PROMISE_TTY)) { UnveilIfExists(ttyname(0), "rw"); UnveilIfExists("/dev/tty", "rw"); UnveilIfExists("/dev/console", "rw"); UnveilIfExists("/etc/terminfo", "r"); UnveilIfExists("/usr/lib/terminfo", "r"); UnveilIfExists("/usr/share/terminfo", "r"); } if (~ipromises & (1ul << PROMISE_PROT_EXEC)) { if (UnveilIfExists("/usr/bin/ape", "rx") == -1) { if ((p = getenv("TMPDIR"))) { UnveilIfExists(xjoinpaths(p, ".ape"), "rx"); } if ((p = getenv("HOME"))) { UnveilIfExists(xjoinpaths(p, ".ape"), "rx"); } } } if (~ipromises & (1ul << PROMISE_VMINFO)) { UnveilIfExists("/proc/stat", "r"); UnveilIfExists("/proc/meminfo", "r"); UnveilIfExists("/proc/cpuinfo", "r"); UnveilIfExists("/proc/diskstats", "r"); UnveilIfExists("/proc/self/maps", "r"); UnveilIfExists("/sys/devices/system/cpu", "r"); } if (~ipromises & (1ul << PROMISE_TMPPATH)) { UnveilIfExists("/tmp", "rwc"); UnveilIfExists(getenv("TMPPATH"), "rwc"); } for (int i = 0; i < unveils.n; ++i) { char *s, *t; const char *path; const char *perm; s = unveils.p[i]; if ((t = strchr(s, ':'))) { *t = 0; perm = s; path = t + 1; } else { perm = "r"; path = s; } UnveilIfExists(path, perm); } if (unveil(0, 0) == -1) { kprintf("error: unveil(0, 0) failed: %m\n"); _Exit(20); } } void DropCapabilities(void) { int e, i; for (e = errno, i = 0;; ++i) { if (prctl(PR_CAPBSET_DROP, i) == -1) { if (errno == EINVAL || errno == EPERM) { errno = e; break; } else { kprintf("error: prctl(PR_CAPBSET_DROP, %d) failed: %m\n", i); _Exit(25); } } } } 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; } int Extract(const char *from, const char *to, int mode) { int fdin, fdout; if ((fdin = open(from, O_RDONLY)) == -1) return -1; if ((fdout = creat(to, mode)) == -1) { close(fdin); return -1; } if (_copyfd(fdin, fdout, -1) == -1) { close(fdout); close(fdin); return -1; } return close(fdout) | close(fdin); } int main(int argc, char *argv[]) { const char *s; bool hasfunbits; int fdin, fdout; char buf[PATH_MAX]; int e, zipfd, memfd; int useruid, usergid; int owneruid, ownergid; int oldfsuid, oldfsgid; unsigned long ipromises; if (!IsLinux()) { kprintf("error: this program is only intended for linux\n"); exit(5); } // parse flags GetOpts(argc, argv); if (g_test) { if (!strcmp(g_test, "pledge")) { if (IsOpenbsd() || (IsLinux() && __is_linux_2_6_23())) { exit(0); } else { exit(1); } } if (!strcmp(g_test, "unveil")) { if (IsOpenbsd() || (IsLinux() && SupportsLandlock())) { exit(0); } else { exit(1); } } kprintf("error: unknown test: %s\n", g_test); exit(2); } if (optind == argc) { kprintf("error: too few args\n"); write(2, USAGE, sizeof(USAGE) - 1); exit(64); } if (!g_noclose) { NormalizeFileDescriptors(); } // set resource limits MakeProcessNice(); if (SetCpuLimit(g_cpuquota) == -1) { kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_CPU"); exit(1); } if (SetLimit(RLIMIT_FSIZE, g_fszquota, g_fszquota * 1.5) == -1) { kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_FSIZE"); exit(1); } if (SetLimit(RLIMIT_AS, g_memquota, g_memquota) == -1) { kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_AS"); exit(1); } if (SetLimit(RLIMIT_NPROC, g_proquota, g_proquota) == -1) { kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_NPROC"); exit(1); } // test for weird chmod bits usergid = getgid(); ownergid = getegid(); useruid = getuid(); owneruid = geteuid(); hasfunbits = usergid != ownergid || useruid != owneruid; if (hasfunbits) { setuid(owneruid); setgid(ownergid); } // some flags can't be allowed if binary has setuid bits if (hasfunbits) { if (g_uflag || g_gflag) { kprintf("error: setuid flags forbidden on setuid binaries\n"); _Exit(6); } } // check if user has permission to chroot directory if (hasfunbits && g_chroot) { oldfsuid = setfsuid(useruid); oldfsgid = setfsgid(usergid); if (access(g_chroot, R_OK) == -1) { kprintf("error: access(%#s) failed: %m\n", g_chroot); _Exit(7); } setfsuid(oldfsuid); setfsgid(oldfsgid); } // change root fs path if (g_chroot) { if (chdir(g_chroot) == -1) { kprintf("error: chdir(%#s) failed: %m\n", g_chroot); _Exit(8); } if (chroot(g_chroot) == -1) { kprintf("error: chroot(%#s) failed: %m\n", g_chroot); _Exit(9); } } // find program if (hasfunbits) { oldfsuid = setfsuid(useruid); oldfsgid = setfsgid(usergid); } if (!(prog = commandv(argv[optind], pathbuf, sizeof(pathbuf)))) { kprintf("error: command not found: %m\n", argv[optind]); _Exit(10); } if (hasfunbits) { setfsuid(oldfsuid); setfsgid(oldfsgid); } // figure out where we want the dso if (_IsDynamicExecutable(prog)) { isdynamic = true; if ((s = getenv("TMPDIR")) || // (s = getenv("HOME")) || // (s = ".")) { ksnprintf(dsopath, sizeof(dsopath), "%s/sandbox.so", s); if (!FileExistsAndIsNewerThan(dsopath, GetProgramExecutableName())) { ksnprintf(tmppath, sizeof(tmppath), "%s/sandbox.so.%d", s, getpid()); if (Extract("/zip/sandbox.so", tmppath, 0755) == -1) { kprintf("error: extract dso failed: %m\n"); exit(1); } if (rename(tmppath, dsopath) == -1) { kprintf("error: rename dso failed: %m\n"); exit(1); } } ksnprintf(buf, sizeof(buf), "LD_PRELOAD=%s", dsopath); putenv(buf); } } if (g_dontdrop) { if (hasfunbits) { kprintf("error: -D flag forbidden on setuid binaries\n"); _Exit(6); } } else { DropCapabilities(); } // set group id if (usergid != ownergid) { // setgid binaries must use the gid of the user that ran it if (setgid(usergid) == -1) { kprintf("error: setgid(%d) failed: %m\n", usergid); _Exit(11); } if (getgid() != usergid || getegid() != usergid) { kprintf("error: setgid() broken\n"); _Exit(12); } } else if (g_gflag) { // otherwise we trust the gid flag if (setgid(g_gflag) == -1) { kprintf("error: setgid(%d) failed: %m\n", g_gflag); _Exit(13); } if (getgid() != g_gflag || getegid() != g_gflag) { kprintf("error: setgid() broken\n"); _Exit(14); } } // set user id if (useruid != owneruid) { // setuid binaries must use the uid of the user that ran it if (setuid(useruid) == -1) { kprintf("error: setuid(%d) failed: %m\n", useruid); _Exit(15); } if (getuid() != useruid || geteuid() != useruid) { kprintf("error: setuid() broken\n"); _Exit(16); } } else if (g_uflag) { // otherwise we trust the uid flag if (setuid(g_uflag) == -1) { kprintf("error: setuid(%d) failed: %m\n", g_uflag); _Exit(17); } if (getuid() != g_uflag || geteuid() != g_uflag) { kprintf("error: setuid() broken\n"); _Exit(18); } } if (ParsePromises(g_promises, &ipromises) == -1) { kprintf("error: bad promises list: %s\n", g_promises); _Exit(21); } ApplyFilesystemPolicy(ipromises); // pledge.com uses the return eperm instead of killing the process // model. we do this becasue it's only possible to have sigsys print // crash messages if we're not pledging exec, which is what this tool // always has to do currently. if (g_kflag) { __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS; } else { __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; } // we need to be able to call execv and mmap the dso // it'll be pledged away once/if the dso gets loaded if (!(~ipromises & (1ul << PROMISE_EXEC))) { g_promises = xstrcat(g_promises, ' ', "exec"); if (!g_qflag) { // TODO(jart): Fix me. // __pledge_mode |= PLEDGE_STDERR_LOGGING; } } if (isdynamic) { g_promises = xstrcat(g_promises, ' ', "prot_exec"); } // pass arguments to pledge() inside the dso if (isdynamic) { ksnprintf(buf, sizeof(buf), "_PLEDGE=%ld,%ld", ~ipromises, __pledge_mode); putenv(buf); } if (SetLimit(RLIMIT_NOFILE, g_nfdquota, g_nfdquota) == -1) { kprintf("error: setrlimit(%s) failed: %m\n", "RLIMIT_NOFILE"); exit(1); } // apply sandbox if (pledge(g_promises, g_promises) == -1) { kprintf("error: pledge(%#s) failed: %m\n", g_promises); _Exit(19); } // launch program sys_execve(prog, argv + optind, environ); kprintf("%s: execve failed: %m\n", prog); return 127; }
23,095
809
jart/cosmopolitan
false
cosmopolitan/tool/build/unbundle.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/stat.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "libc/x/x.h" #include "third_party/musl/ftw.h" const char *prog; char tmpdir[PATH_MAX]; char binpath[PATH_MAX]; bool IsDirectory(const char *path) { int e; bool res; struct stat st; e = errno; res = stat(path, &st) != -1 && S_ISDIR(st.st_mode); errno = e; return res; } void Execute(char *argv[]) { int ws; if (!vfork()) { execv(argv[0], argv); _Exit(127); } wait(&ws); if (!WIFEXITED(ws) || WEXITSTATUS(ws)) { fputs(argv[0], stderr); fputs(": command failed\n", stderr); exit(1); } } int Visit(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { if (tflag == FTW_F && _endswith(fpath, ".gz")) { Execute((char *[]){"build/bootstrap/gzip.com", "-d", fpath, 0}); strcpy(binpath, fpath); binpath[strlen(binpath) - 3] = 0; chmod(binpath, 0755); } else if (tflag == FTW_F && _endswith(fpath, ".sym")) { strcpy(binpath, fpath); binpath[strlen(binpath) - 4] = 0; symlink(xslurp(fpath, 0), binpath); } return 0; } int main(int argc, char *argv[]) { if (!IsLinux()) return 0; prog = argc > 0 ? argv[0] : "unbundle.com"; if (IsDirectory("o/third_party/gcc")) return 0; makedirs("o/third_party", 0755); FormatInt32(stpcpy(tmpdir, "o/third_party/gcc."), getpid()); Execute( (char *[]){"build/bootstrap/cp.com", "-r", "third_party/gcc", tmpdir, 0}); if (nftw(tmpdir, Visit, 20, 0) == -1) { fputs(prog, stderr); fputs(": nftw failed: ", stderr); fputs(_strerdoc(errno), stderr); fputs("\n", stderr); exit(1); } rename(tmpdir, "o/third_party/gcc"); }
3,706
91
jart/cosmopolitan
false
cosmopolitan/tool/build/refactor.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/dirent.h" #include "libc/calls/struct/stat.h" #include "libc/fmt/fmt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/check.h" #include "libc/mem/alg.h" #include "libc/mem/gc.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/dt.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/x/x.h" /** * @fileoverview Pretty fast substring refactor tool. */ static const char kBefore[] = "\ │ Copyright 2020 Justine Alexandra Roberts Tunney │\n\ │ │\n\ │ This program is free software; you can redistribute it and/or modify │\n\ │ it under the terms of the GNU General Public License as published by │\n\ │ the Free Software Foundation; version 2 of the License. │\n\ │ │\n\ │ This program is distributed in the hope that it will be useful, but │\n\ │ WITHOUT ANY WARRANTY; without even the implied warranty of │\n\ │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU │\n\ │ General Public License for more details. │\n\ │ │\n\ │ You should have received a copy of the GNU General Public License │\n\ │ along with this program; if not, write to the Free Software │\n\ │ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA │\n\ │ 02110-1301 USA │\n\ "; const char kAfter[] = "\ │ Copyright 2020 Justine Alexandra Roberts Tunney │\n\ │ │\n\ │ Permission to use, copy, modify, and/or distribute this software for │\n\ │ any purpose with or without fee is hereby granted, provided that the │\n\ │ above copyright notice and this permission notice appear in all copies. │\n\ │ │\n\ │ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL │\n\ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │\n\ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │\n\ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │\n\ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │\n\ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │\n\ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │\n\ │ PERFORMANCE OF THIS SOFTWARE. │\n\ "; #if 0 static const char kBefore[] = "\ /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│"; const char kAfter[] = "\ /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│"; #endif void RefactorFile(const char *path) { int fd; struct stat st; size_t len, partlen, len1, len2; char *mem, *spot = NULL, *part1, *part2; CHECK_NE(-1, (fd = open(path, O_RDONLY))); CHECK_NE(-1, fstat(fd, &st)); len2 = 0; if ((len = st.st_size)) { CHECK_NE(MAP_FAILED, (mem = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0))); partlen = sizeof(kBefore) - 1; if ((spot = memmem(mem, len, kBefore, partlen))) { part1 = gc(xmalloc((len1 = spot - mem))); part2 = gc(xmalloc((len2 = len - partlen - (spot - mem)))); memcpy(part1, mem, len1); memcpy(part2, spot + partlen, len2); } CHECK_NE(-1, munmap(mem, len)); } CHECK_NE(-1, close(fd)); if (spot) { fprintf(stderr, "found! %s\n", path); CHECK_NE(-1, (fd = open(path, O_RDWR | O_TRUNC))); CHECK_EQ(len1, write(fd, part1, len1)); CHECK_EQ(sizeof(kAfter) - 1, write(fd, kAfter, sizeof(kAfter) - 1)); CHECK_EQ(len2, write(fd, part2, len2)); CHECK_NE(-1, close(fd)); } } void RefactorDir(const char *dpath) { DIR *dir; struct dirent *ent; char *path = gc(xmalloc(4096)); CHECK_NOTNULL(dir = opendir(firstnonnull(dpath, "."))); while ((ent = readdir(dir))) { if (_startswith(ent->d_name, ".")) continue; if (strcmp(ent->d_name, "o") == 0) continue; snprintf(path, 4096, "%s%s%s", dpath ? dpath : "", dpath ? "/" : "", ent->d_name); if (isdirectory(path)) { RefactorDir(path); } else if (isregularfile(path)) { RefactorFile(path); } } CHECK_NE(-1, closedir(dir)); } int main(int argc, char *argv[]) { RefactorDir(NULL); return 0; }
6,904
135
jart/cosmopolitan
false
cosmopolitan/tool/build/cp.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/copyfile.h" #include "libc/calls/struct/stat.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/mem/copyfd.internal.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/s.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #include "third_party/musl/ftw.h" #define USAGE \ " SRC... DST\n\ \n\ SYNOPSIS\n\ \n\ Copies Files\n\ \n\ FLAGS\n\ \n\ -?\n\ -h help\n\ -f force\n\ -r recursive\n\ -n no clobber\n\ -a preserve all\n\ -p preserve owner and timestamps\n\ \n" int flags; bool force; int striplen; bool recursive; const char *prog; char mkbuf[PATH_MAX]; char srcdir[PATH_MAX]; char dstdir[PATH_MAX]; char srcfile[PATH_MAX]; char dstfile[PATH_MAX]; char linkbuf[PATH_MAX]; void Cp(char *, char *); bool IsDirectory(const char *path) { int e; bool res; struct stat st; e = errno; res = stat(path, &st) != -1 && S_ISDIR(st.st_mode); errno = e; return res; } bool IsSymlink(const char *path) { int e; bool res; struct stat st; e = errno; res = fstatat(AT_FDCWD, path, &st, AT_SYMLINK_NOFOLLOW) != -1 && S_ISLNK(st.st_mode); errno = e; return res; } 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, "?hfnaprR")) != -1) { switch (opt) { case 'f': force = true; break; case 'r': case 'R': recursive = true; break; case 'n': flags |= COPYFILE_NOCLOBBER; break; case 'a': case 'p': flags |= COPYFILE_PRESERVE_OWNER; flags |= COPYFILE_PRESERVE_TIMESTAMPS; break; case 'h': case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } int Visit(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { char *src; strcpy(srcfile, fpath); src = srcfile + striplen; strcpy(dstfile, dstdir); if (!_endswith(dstfile, "/")) { strcat(dstfile, "/"); } strcat(dstfile, src); strcpy(srcfile, fpath); switch (tflag) { case FTW_D: return 0; case FTW_F: case FTW_SL: case FTW_SLN: Cp(srcfile, dstfile); return 0; default: fputs(fpath, stderr); fputs(": can't handle file type\n", stderr); exit(1); } } char *Join(const char *a, const char *b) { size_t n, m; n = strlen(a); m = strlen(b); if (n + 1 + m + 1 > sizeof(dstfile)) { fputs("error: cp: path too long\n", stderr); exit(1); } stpcpy(stpcpy(stpcpy(dstfile, a), "/"), b); return dstfile; } bool MovePreservingDestinationInode(const char *from, const char *to) { bool res; 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; } res = _copyfd(fdin, fdout, -1) != -1; close(fdin); close(fdout); return res; } void Cp(char *src, char *dst) { ssize_t rc; const char *s; if (strlen(src) + 1 > PATH_MAX) _Exit(2); if (strlen(dst) + 1 > PATH_MAX) _Exit(2); basename(src); basename(dst); if (IsDirectory(src)) { if (!recursive) { fputs(prog, stderr); fputs(": won't copy directory without -r flag.\n", stderr); exit(1); } strcpy(dstdir, dst); if (IsDirectory(dst)) { strcpy(srcdir, src); basename(srcdir); striplen = 0; strcpy(srcdir, basename(src)); } else { strcpy(srcdir, src); basename(srcdir); striplen = strlen(srcdir); strcpy(srcdir, ""); } if (nftw(src, Visit, 20, 0) == -1) { fputs(prog, stderr); fputs(": nftw failed: ", stderr); fputs(_strerdoc(errno), stderr); fputs("\n", stderr); exit(1); } return; } if (IsDirectory(dst)) { dst = Join(dst, basename(src)); } if (!force && access(dst, W_OK) == -1 && errno != ENOENT) goto OnFail; strcpy(mkbuf, dst); if (makedirs(dirname(mkbuf), 0755) == -1) goto OnFail; if (IsSymlink(src)) { if ((rc = readlink(src, linkbuf, sizeof(linkbuf) - 1)) == -1) goto OnFail; linkbuf[rc] = 0; if (symlink(linkbuf, dst) == -1) goto OnFail; } else { if (!MovePreservingDestinationInode(src, dst)) goto OnFail; } return; OnFail: s = _strerdoc(errno); fputs(prog, stderr); fputs(": ", stderr); fputs(src, stderr); fputs(" ", stderr); fputs(dst, stderr); fputs(": ", stderr); fputs(s, stderr); fputs("\n", stderr); exit(1); } int main(int argc, char *argv[]) { int i; prog = argc > 0 ? argv[0] : "cp.com"; GetOpts(argc, argv); if (argc - optind < 2) PrintUsage(EX_USAGE, stderr); for (i = optind; i < argc - 1; ++i) { Cp(argv[i], argv[argc - 1]); } return 0; }
7,072
255
jart/cosmopolitan
false
cosmopolitan/tool/build/ocat.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/itoa.h" #include "libc/mem/copyfd.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/o.h" #include "third_party/getopt/getopt.h" char buf[512]; static 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", 0); exit(rc); } int main(int argc, char *argv[]) { int i, opt; const char *outpath = "/dev/stdout"; while ((opt = getopt(argc, argv, "o:")) != -1) { switch (opt) { case 'o': outpath = optarg; break; default: return 1; } } int out = open(outpath, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (out == -1) SysExit(2, "open", outpath); for (i = optind; i < argc; ++i) { int in = open(argv[i], O_RDONLY); if (in == -1) SysExit(3, "open", argv[i]); for (;;) { ssize_t rc = read(in, buf, 512); if (rc == -1) SysExit(3, "read", argv[i]); if (!rc) break; ssize_t rc2 = write(out, buf, rc); if (rc2 != rc) SysExit(4, "write", outpath); } if (close(in) == -1) SysExit(5, "close", argv[i]); } if (close(out) == -1) SysExit(6, "close", outpath); }
3,434
80
jart/cosmopolitan
false
cosmopolitan/tool/build/calculator.ctest
# INTEGER 2 3 + 5 = assert 3 2 + 5 = assert 5 2 - 3 = assert 2 5 - -3 = assert 81 3 / 27 = assert 81 3 // 27 = assert 2 8 ** 256 = assert 17 10 % 7 = assert 17 10 fmod 7 = assert # FLOATING POINT .1 .2 + .3 - abs epsilon < assert pi sqrt pi sqrt * pi - abs epsilon < assert 3 2 / 1.5 = assert pi pi = assert pi cos -1 = assert pi 2 / sin 1 = assert 81 3 / 27 = assert inf isinf assert inf isnormal ! assert nan isnormal ! assert 1 0 / isnormal ! assert 0 signbit ! assert -.5 round -1 = assert -.5 floor -1 = assert -.5 rint dup 0 = assert signbit assert -.5 nearbyint dup 0 = assert signbit assert -.5 ceil dup 0 = assert signbit assert -.5 trunc dup 0 = assert signbit assert 0 0 / dup isnan assert signbit assert # is this right? 1 0 / dup isinf assert signbit ! assert # is this right? nan nan != assert # is this right? # -nan -nan != assert # is this right? inf inf = assert # is this right? -inf -inf = assert # is this right? # BIT ARITHMETIC -1 ~ 0 = assert 0 0x7fffffffffffffffffffffffffffffff - -0x7fffffffffffffffffffffffffffffff = assert 0b1010101 popcnt 4 = assert 0b1010101 0b0110101 ^ 0b1100000 = assert 0b1010101 0b0110101 | 0b1110101 = assert 0b1010101 0b0110101 & 0b0010101 = assert 0b1010101 1 >> 0b000101010 = assert 0b1010101 2 >> 0b000010101 = assert 0b1010101 1 << 0b010101010 = assert 0b1010101 2 << 0b101010100 = assert # BOOLEAN true assert false ! assert true ! ! assert true true && assert true false && ! assert false true && ! assert true false && ! assert false true && ! assert true true || assert false true || assert true false || assert false false || ! assert 4 5 < assert 5 4 < ! assert -5 4 < assert 5 5 < ! assert 5 5 <= assert 5 4 > assert 4 5 > ! assert 4 -5 > assert 5 5 > ! assert 5 5 >= assert # MISC 1 abs 1 = assert -1 abs 1 = assert -1 1 max 1 = assert 1 -1 max 1 = assert 1 2 max 2 = assert -1 1 min -1 = assert 1 -1 min -1 = assert 1 2 min 1 = assert rand64 rand64 rand64 rand64 != != && assert # HEX SIGN -0x80000000 -2147483648 = assert 0x80000000 2147483648 = assert 0x80000001 2147483649 = assert 0xffffffff 4294967295 = assert 0x100000000 4294967296 = assert -0x100000000 -4294967296 = assert
2,251
92
jart/cosmopolitan
false
cosmopolitan/tool/build/zipbase.c
#if 0 /*─────────────────────────────────────────────────────────────────╗ │ To the extent possible under law, Justine Tunney has waived │ │ all copyright and related or neighboring rights to this file, │ │ as it is written in the following disclaimers: │ │ • http://unlicense.org/ │ │ • http://creativecommons.org/publicdomain/zero/1.0/ │ ╚─────────────────────────────────────────────────────────────────*/ #endif #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/zip.h" int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: %s FOO.COM\n", argv[0]); fprintf(stderr, "prints lowest file offset (in decimal bytes) at which zip\n" "records exist within a .com, .com.dbg, or .zip file\n"); exit(1); } int fd = open(argv[1], O_RDONLY); if (fd == -1) { perror(argv[1]); exit(1); } size_t n; struct stat st; CHECK_EQ(0, fstat(fd, &st)); n = st.st_size; uint8_t *m; CHECK_NE(MAP_FAILED, (m = mmap(0, n, PROT_READ, MAP_PRIVATE, fd, 0))); uint8_t *b, *d, *p; if ((p = FindEmbeddedApe(m, n))) { b = p; n -= p - m; } else { b = m; } if (!(d = GetZipCdir(b, n))) { fprintf(stderr, "%s: couldn't locate central directory\n", argv[1]); exit(1); } size_t zsize = n; uint8_t *zmap = m; uint8_t *zbase = b; uint8_t *zcdir = d; DCHECK(IsZipCdir32(zbase, zsize, zcdir - zbase) || IsZipCdir64(zbase, zsize, zcdir - zbase)); uint64_t cf; uint64_t lf; uint64_t minzipoffset; n = GetZipCdirRecords(zcdir); minzipoffset = cf = GetZipCdirOffset(zcdir); for (; n--; cf += ZIP_CFILE_HDRSIZE(zbase + cf)) { CHECK_EQ(kZipCfileHdrMagic, ZIP_CFILE_MAGIC(zbase + cf)); lf = GetZipCfileOffset(zbase + cf); minzipoffset = MIN(minzipoffset, lf); } printf("%ld\n", (zbase + minzipoffset) - m); }
2,463
77
jart/cosmopolitan
false
cosmopolitan/tool/build/bigmul.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/assert.h" #include "libc/fmt/conv.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview cryptographic multiplication kernel generator */ void PrintMultiplyKernel(int n, int m) { bool cf, of; uint128_t x; bool *Rs, *Ra; int j, i, k1, k2, g; uint64_t *R, *H; printf("\ /**\n\ * Computes %d-bit product of %d-bit and %d-bit numbers.\n\ *\n\ * @param C receives %d quadword result\n\ * @param A is left hand side which must have %d quadwords\n\ * @param B is right hand side which must have %d quadwords\n\ * @note words are host endian while array is little endian\n\ * @mayalias\n\ */\n\ void Multiply%dx%d(uint64_t C[%d], const uint64_t A[%d], const uint64_t B[%d]) {\n\ static bool cf,of;\n\ uint64_t z,h,l;\n\ uint64_t ", (n + m) * 64, n * 64, m * 64, n + m, n, m, n, m, n + m, n, m); Rs = gc(calloc(sizeof(*Rs), n + m + 1)); Ra = gc(calloc(sizeof(*Ra), n + m + 1)); for (j = 0; j < n; ++j) { if (j) printf(", "); printf("H%d", j); } printf(";\n"); printf(" uint64_t "); for (j = 0; j < n + m; ++j) { if (j) printf(", "); printf("R%d", j); } printf(";\n"); for (j = 0; j < m; ++j) { (printf)("\ asm(\"xorl\\t%%k0,%%k0\" : \"=r\"(z), \"+m\"(cf), \"+m\"(of));\n", j); for (cf = of = i = 0; i < n; ++i) { if (!i) { if (!Rs[i + j] && !Rs[i + j + 1]) { assert(!cf); assert(!of); Rs[i + j + 0] = true; Rs[i + j + 1] = true; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(R%d), \"=r\"(R%d) : \"rm\"(A[%d]), \"d\"(B[%d]));\n", i + j + 1, i + j, i, j); } else if (!Rs[i + j + 1]) { of = true; assert(!cf); Ra[i + j + 0] = true; Rs[i + j + 1] = true; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(R%d), \"=r\"(l) : \"rm\"(A[%d]), \"d\"(B[%d]));\n\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(l));\n", i + j + 1, i, j, i + j); } else { cf = true; of = true; assert(Rs[i + j]); Ra[i + j + 0] = true; Ra[i + j + 1] = true; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(h), \"=r\"(l) : \"rm\"(A[%d]), \"d\"(B[%d]));\n\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(l));\n\ asm(\"adcx\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(cf) : \"r\"(h));\n", i, j, i + j, i + j + 1); } } else { assert(Rs[i + j]); if (!Rs[i + j + 1]) { if (cf) { of = true; cf = false; Ra[i + j + 0] = true; Rs[i + j + 1] = true; Ra[i + j + 1] = false; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(R%d), \"=r\"(l) : \"rm\"(A[%d]), \"d\"(B[%d]));\n\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(l));\n\ asm(\"adcx\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(cf) : \"r\"(z));\n", i + j + 1, i, j, i + j, i + j + 1); } else { of = true; Ra[i + j + 0] = true; Rs[i + j + 1] = true; Ra[i + j + 1] = false; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(R%d), \"=r\"(l) : \"rm\"(A[%d]), \"d\"(B[%d]));\n\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(l));\n", i + j + 1, i, j, i + j); } } else { of = true; cf = true; Ra[i + j + 0] = true; Ra[i + j + 1] = true; (printf)("\ asm(\"mulx\\t%%2,%%1,%%0\" : \"=r\"(h), \"=r\"(l) : \"rm\"(A[%d]), \"d\"(B[%d]));\n\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(l));\n\ asm(\"adcx\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(cf) : \"rm\"(h));\n", i, j, i + j, i + j + 1); } } } k1 = 0; if (of) { for (;; ++k1) { (printf)("\ asm(\"adox\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(of) : \"r\"(z));\n", i + j + k1); if (!Rs[i + j + k1]) { break; } if (!Ra[i + j + k1]) { break; } } } k2 = 0; if (cf) { for (;; ++k2) { (printf)("\ asm(\"adcx\\t%%2,%%0\" : \"+r\"(R%d), \"+m\"(cf) : \"r\"(z));\n", i + j + k2); if (!Rs[i + j + k2]) { break; } if (!Ra[i + j + k2]) { break; } } } for (g = 0; g < MAX(k1, k2); ++g) { Rs[i + j + g] = true; } } for (j = 0; j < n + m; ++j) { printf(" C[%d] = R%d;\n", j, j); } printf("}\n"); fflush(stdout); } int main(int argc, char *argv[]) { int n, m; if (argc != 3 || (n = atoi(argv[1])) <= 0 || (m = atoi(argv[2])) <= 0) { fprintf(stderr, "Usage: %s LHS-LIMBS RHS-LIMBS\n", argv[0]); return 1; } PrintMultiplyKernel(n, m); return 0; }
6,841
186
jart/cosmopolitan
false
cosmopolitan/tool/build/touch.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/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview Command for updating timestamps on files. */ int main(int argc, char *argv[]) { int i; const char *s, *prog; prog = argc > 0 ? argv[0] : "touch.com"; for (i = 1; i < argc; ++i) { if (touch(argv[i], 0666) == -1) { s = _strerdoc(errno); fputs(prog, stderr); fputs(": cannot touch '", stderr); fputs(argv[i], stderr); fputs("': ", stderr); fputs(s, stderr); fputs("\n", stderr); exit(1); } } return 0; }
2,473
47
jart/cosmopolitan
false
cosmopolitan/tool/build/dso/sandbox.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/pledge.h" #include "libc/calls/pledge.internal.h" #include "libc/intrin/promises.internal.h" #include "libc/runtime/runtime.h" /* * runs pledge at glibc executable load time, e.g. * strace -vff bash -c '_PLEDGE=4194303,0 LD_PRELOAD=$HOME/sandbox.so ls' */ _Hide uint8_t __privileged_start[1]; _Hide uint8_t __privileged_end[1]; __attribute__((__constructor__)) void init(void) { int c, i, j; const char *s; uint64_t arg[2] = {0}; s = getenv("_PLEDGE"); for (i = j = 0; i < 2; ++i) { while ((c = s[j] & 255)) { ++j; if ('0' <= c & c <= '9') { arg[i] *= 10; arg[i] += c - '0'; } else { break; } } } sys_pledge_linux(~arg[0], arg[1]); }
2,597
51
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/word.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/str/str.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/word.h" void SetMemoryShort(struct Machine *m, int64_t v, int16_t i) { void *p[2]; uint8_t b[2]; Write16(BeginStore(m, v, 2, p, b), i); EndStore(m, v, 2, p, b); } void SetMemoryInt(struct Machine *m, int64_t v, int32_t i) { void *p[2]; uint8_t b[4]; Write32(BeginStore(m, v, 4, p, b), i); EndStore(m, v, 4, p, b); } void SetMemoryLong(struct Machine *m, int64_t v, int64_t i) { void *p[2]; uint8_t b[8]; Write64(BeginStore(m, v, 8, p, b), i); EndStore(m, v, 8, p, b); } void SetMemoryFloat(struct Machine *m, int64_t v, float f) { void *p[2]; uint8_t b[4]; memcpy(BeginStore(m, v, 4, p, b), &f, 4); EndStore(m, v, 4, p, b); } void SetMemoryDouble(struct Machine *m, int64_t v, double f) { void *p[2]; uint8_t b[8]; memcpy(BeginStore(m, v, 8, p, b), &f, 8); EndStore(m, v, 8, p, b); } void SetMemoryLdbl(struct Machine *m, int64_t v, long double f) { void *p[2]; uint8_t b[10]; memcpy(BeginStore(m, v, 10, p, b), &f, 10); EndStore(m, v, 10, p, b); }
2,960
65
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/demangle.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/iovec.h" #include "libc/intrin/safemacros.internal.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "tool/build/lib/demangle.h" struct CxxFilt { int pid; int reader; int writer; } g_cxxfilt; void CloseCxxFilt(void) { close(g_cxxfilt.reader); close(g_cxxfilt.writer); g_cxxfilt.pid = -1; } void SpawnCxxFilt(void) { int pipefds[2][2]; const char *cxxfilt; char path[PATH_MAX]; cxxfilt = firstnonnull(emptytonull(getenv("CXXFILT")), "c++filt"); if (commandv(cxxfilt, path, sizeof(path))) { pipe2(pipefds[0], O_CLOEXEC); pipe2(pipefds[1], O_CLOEXEC); if (!(g_cxxfilt.pid = vfork())) { dup2(pipefds[1][0], 0); dup2(pipefds[0][1], 1); execv(path, (char *const[]){cxxfilt, NULL}); abort(); } g_cxxfilt.reader = pipefds[0][0]; g_cxxfilt.writer = pipefds[1][1]; atexit(CloseCxxFilt); } else { g_cxxfilt.pid = -1; } } char *CopySymbol(char *p, size_t pn, const char *s, size_t sn) { size_t extra; bool showdots, iscomplicated; assert(pn >= 1 + 3 + 1 + 1); iscomplicated = memchr(s, ' ', sn) || memchr(s, '(', sn); extra = 1; if (iscomplicated) extra += 2; if (sn + extra > pn) { sn = pn - extra - 3; showdots = true; } else { showdots = false; } if (iscomplicated) *p++ = '"'; p = mempcpy(p, s, sn); if (showdots) p = stpcpy(p, "..."); if (iscomplicated) *p++ = '"'; *p = '\0'; return p; } char *DemangleCxxFilt(char *p, size_t pn, const char *s, size_t sn) { ssize_t rc; size_t got; struct iovec iov[2]; static char buf[PAGESIZE]; if (!g_cxxfilt.pid) SpawnCxxFilt(); if (g_cxxfilt.pid == -1) return NULL; buf[0] = '\n'; iov[0].iov_base = s; iov[0].iov_len = sn; iov[1].iov_base = buf; iov[1].iov_len = 1; writev(g_cxxfilt.writer, iov, ARRAYLEN(iov)); if ((rc = read(g_cxxfilt.reader, buf, sizeof(buf))) != -1) { got = rc; if (got >= 2 && buf[got - 1] == '\n') { if (buf[got - 2] == '\r') --got; --got; return CopySymbol(p, pn, buf, got); } } CloseCxxFilt(); return NULL; } /** * Decrypts C++ symbol. * * Decoding these takes roughly the same lines of code as an entire * x86_64 disassembler. That's just for the GNU encoding scheme. So * what we'll do, is just offload this work to the c++filt program. */ char *Demangle(char *p, const char *symbol, size_t n) { char *r; size_t sn; sn = strlen(symbol); if (_startswith(symbol, "_Z")) { if ((r = DemangleCxxFilt(p, n, symbol, sn))) return r; } return CopySymbol(p, n, symbol, sn); }
4,478
123
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/interner.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/lib/interner.h" #include "libc/intrin/safemacros.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/crc32.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/x/x.h" #define kInitialItems 16 struct InternerObject { struct Interner pool; size_t i, n; struct InternerHash { unsigned hash; /* 0 means empty */ unsigned index; } * p; }; static void rehash(struct InternerObject *it) { size_t i, j, n, step; struct InternerHash *p; n = it->n; p = it->p; it->p = xcalloc((it->n <<= 1), sizeof(struct InternerHash)); for (i = 0; i < n; ++i) { if (!p[i].hash) continue; step = 0; do { j = (p[i].hash + step * ((step + 1) >> 1)) & (it->n - 1); step++; } while (it->p[j].hash); memcpy(&it->p[j], &p[i], sizeof(p[i])); } free(p); } /** * Creates new interner. */ struct Interner *newinterner(void) { struct InternerObject *it; it = xcalloc(1, sizeof(*it)); it->p = xcalloc((it->n = kInitialItems), sizeof(*it->p)); it->pool.p = xcalloc((it->pool.n = kInitialItems), sizeof(*it->pool.p)); return &it->pool; } /** * Destroys interner. */ void freeinterner(struct Interner *t) { struct InternerObject *it = (struct InternerObject *)t; if (it) { free(it->pool.p); free(it->p); free(it); } } /** * Returns number of unique items interned. */ size_t interncount(const struct Interner *t) { struct InternerObject *it = (struct InternerObject *)t; return it->i; } /** * Interns object. * * @return index into 𝑡→𝑝 holding equal item * @note use consistent size w/ non-string items */ size_t internobj(struct Interner *t, const void *data, size_t size) { char *p2; size_t n2; char *item; unsigned hash; struct InternerObject *it; size_t i, off, step, need, bytes; step = 0; item = data; it = (struct InternerObject *)t; hash = max(1, crc32c(0, data, size)); do { /* it is written that triangle probe halts iff i<n/2 && popcnt(n)==1 */ i = (hash + step * ((step + 1) >> 1)) & (it->n - 1); if (it->p[i].hash == hash && it->p[i].index + size <= it->pool.n && memcmp(item, &it->pool.p[it->p[i].index], size) == 0) { return it->p[i].index; } step++; } while (it->p[i].hash); if (++it->i == (it->n >> 1)) { rehash(it); step = 0; do { i = (hash + step * ((step + 1) >> 1)) & (it->n - 1); step++; } while (it->p[i].hash); } off = it->pool.i; if (__builtin_add_overflow(off, size, &need)) abort(); if (__builtin_add_overflow(need, 1, &need)) abort(); if (need > it->pool.n) { if (__builtin_add_overflow(it->pool.n, 1, &n2)) abort(); do { if (__builtin_add_overflow(n2, n2 >> 1, &n2)) abort(); } while (need > n2); if (__builtin_mul_overflow(n2, sizeof(*it->pool.p), &bytes)) abort(); if (!(p2 = realloc(it->pool.p, bytes))) abort(); it->pool.p = p2; it->pool.n = n2; } memcpy(it->pool.p + off, data, size); it->pool.p[off + size] = 0; it->p[i].hash = hash; it->p[i].index = off; it->pool.i += size; return off; } /** * Interns string. * * The NUL-terminated string 𝑠 is concatenated to the relocatable * double-NUL terminated string list 𝑡→𝑝 with de-duplication and * preservation of insertion order. * * @return index into 𝑡→𝑝 holding string equal to 𝑠 */ size_t intern(struct Interner *t, const char *s) { return internobj(t, s, strlen(s) + 1); } /** * Returns true if string is interned. */ bool isinterned(struct Interner *t, const char *s) { unsigned hash; size_t i, n, step; struct InternerObject *it; step = 0; n = strlen(s) + 1; hash = max(1, crc32c(0, s, n)); it = (struct InternerObject *)t; do { i = (hash + step * ((step + 1) >> 1)) & (it->n - 1); if (it->p[i].hash == hash && it->p[i].index + n <= it->pool.n && !memcmp(s, &it->pool.p[it->p[i].index], n)) { return true; } step++; } while (it->p[i].hash); return false; }
5,853
176
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/signal.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/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "tool/build/lib/bits.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/signal.h" #include "tool/build/lib/xlat.h" #define SIGCHLD_LINUX 17 #define SIGURG_LINUX 23 #define SIGWINCH_LINUX 28 void OpRestore(struct Machine *m) { union { struct fpstate_bits fp; struct ucontext_bits uc; } u; VirtualSendRead(m, &u.uc, m->siguc, sizeof(u.uc)); m->ip = Read64(u.uc.rip); m->flags = Read64(u.uc.eflags); memcpy(m->r8, u.uc.r8, 8); memcpy(m->r9, u.uc.r9, 8); memcpy(m->r10, u.uc.r10, 8); memcpy(m->r11, u.uc.r11, 8); memcpy(m->r12, u.uc.r12, 8); memcpy(m->r13, u.uc.r13, 8); memcpy(m->r14, u.uc.r14, 8); memcpy(m->r15, u.uc.r15, 8); memcpy(m->di, u.uc.rdi, 8); memcpy(m->si, u.uc.rsi, 8); memcpy(m->bp, u.uc.rbp, 8); memcpy(m->bx, u.uc.rbx, 8); memcpy(m->dx, u.uc.rdx, 8); memcpy(m->ax, u.uc.rax, 8); memcpy(m->cx, u.uc.rcx, 8); memcpy(m->sp, u.uc.rsp, 8); VirtualSendRead(m, &u.fp, m->sigfp, sizeof(u.fp)); m->fpu.cw = Read16(u.fp.cwd); m->fpu.sw = Read16(u.fp.swd); m->fpu.tw = Read16(u.fp.ftw); m->fpu.op = Read16(u.fp.fop); m->fpu.ip = Read64(u.fp.rip); m->fpu.dp = Read64(u.fp.rdp); memcpy(m->fpu.st, u.fp.st, 128); memcpy(m->xmm, u.fp.xmm, 256); m->sig = 0; } int DeliverSignal(struct Machine *m, int sig, int code) { uint64_t sp, siaddr; static struct siginfo_bits si; static struct fpstate_bits fp; static struct ucontext_bits uc; switch (Read64(m->sighand[sig - 1].handler)) { case 1: // SIG_IGN return 0; case 0: // SIG_DFL if (sig == SIGCHLD_LINUX || sig == SIGURG_LINUX || sig == SIGWINCH_LINUX) { return 0; } raise(sig); _exit(128 + sig); default: break; } Write32(si.si_signo, sig); Write32(si.si_code, code); memcpy(uc.r8, m->r8, 8); memcpy(uc.r9, m->r9, 8); memcpy(uc.r10, m->r10, 8); memcpy(uc.r11, m->r11, 8); memcpy(uc.r12, m->r12, 8); memcpy(uc.r13, m->r13, 8); memcpy(uc.r14, m->r14, 8); memcpy(uc.r15, m->r15, 8); memcpy(uc.rdi, m->di, 8); memcpy(uc.rsi, m->si, 8); memcpy(uc.rbp, m->bp, 8); memcpy(uc.rbx, m->bx, 8); memcpy(uc.rdx, m->dx, 8); memcpy(uc.rax, m->ax, 8); memcpy(uc.rcx, m->cx, 8); memcpy(uc.rsp, m->sp, 8); Write64(uc.rip, m->ip); Write64(uc.eflags, m->flags); Write16(fp.cwd, m->fpu.cw); Write16(fp.swd, m->fpu.sw); Write16(fp.ftw, m->fpu.tw); Write16(fp.fop, m->fpu.op); Write64(fp.rip, m->fpu.ip); Write64(fp.rdp, m->fpu.dp); memcpy(fp.st, m->fpu.st, 128); memcpy(fp.xmm, m->xmm, 256); sp = Read64(m->sp); sp = ROUNDDOWN(sp - sizeof(si), 16); VirtualRecvWrite(m, sp, &si, sizeof(si)); siaddr = sp; sp = ROUNDDOWN(sp - sizeof(fp), 16); VirtualRecvWrite(m, sp, &fp, sizeof(fp)); m->sigfp = sp; Write64(uc.fpstate, sp); sp = ROUNDDOWN(sp - sizeof(uc), 16); VirtualRecvWrite(m, sp, &uc, sizeof(uc)); m->siguc = sp; m->sig = sig; sp -= 8; VirtualRecvWrite(m, sp, m->sighand[sig - 1].restorer, 8); Write64(m->sp, sp); Write64(m->di, sig); Write64(m->si, siaddr); Write64(m->dx, m->siguc); m->ip = Read64(m->sighand[sig - 1].handler); return 0; } void EnqueueSignal(struct Machine *m, int sig, int code) { if (m->signals.n < ARRAYLEN(m->signals.p)) { m->signals.p[m->signals.n].code = UnXlatSicode(sig, code); m->signals.p[m->signals.n].sig = UnXlatSignal(sig); m->signals.n++; } } int ConsumeSignal(struct Machine *m) { int sig, code; sig = m->signals.p[m->signals.i].sig; code = m->signals.p[m->signals.i].code; if (!m->sig || ((sig != m->sig || (Read64(m->sighand[m->sig - 1].flags) & 0x40000000)) && !(Read64(m->sighand[m->sig - 1].mask) & (1ull << (m->sig - 1))))) { if (++m->signals.i == m->signals.n) m->signals.i = m->signals.n = 0; return DeliverSignal(m, sig, code); } return 0; } void TerminateSignal(struct Machine *m, int sig) { if (m->isfork) { _exit(28 + sig); } else { exit(128 + sig); } }
6,001
166
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/divmul.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/limits.h" #include "tool/build/lib/divmul.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/throw.h" struct Dubble { uint64_t lo; uint64_t hi; }; static inline struct Dubble DubbleNeg(struct Dubble x) { struct Dubble d; d.lo = -x.lo; d.hi = ~(x.hi - (x.lo - 1 > x.lo)); return d; } static inline struct Dubble DubbleShl(struct Dubble x) { struct Dubble d; d.lo = x.lo << 1; d.hi = x.hi << 1 | x.lo >> 63; return d; } static inline struct Dubble DubbleShr(struct Dubble x) { struct Dubble d; d.lo = x.lo >> 1 | x.hi << 63; d.hi = x.hi >> 1; return d; } static inline unsigned DubbleLte(struct Dubble a, struct Dubble b) { return a.hi == b.hi ? a.lo <= b.lo : a.hi <= b.hi; } static struct Dubble DubbleMul(uint64_t a, uint64_t b) { struct Dubble d; uint64_t x, y, t; x = (a & 0xffffffff) * (b & 0xffffffff); t = x >> 32; x &= 0xffffffff; t += (a >> 32) * (b & 0xffffffff); x += (t & 0xffffffff) << 32; y = t >> 32; t = x >> 32; x &= 0xffffffff; t += (b >> 32) * (a & 0xffffffff); x += (t & 0xffffffff) << 32; y += t >> 32; y += (a >> 32) * (b >> 32); d.lo = x; d.hi = y; return d; } static struct Dubble DubbleImul(uint64_t a, uint64_t b) { unsigned s, t; struct Dubble p; if ((s = a >> 63)) a = -a; if ((t = b >> 63)) b = -b; p = DubbleMul(a, b); return s ^ t ? DubbleNeg(p) : p; } static struct Dubble DubbleDiv(struct Dubble a, uint64_t b, uint64_t *r) { int n, c; uint64_t s; struct Dubble d, q, t; d.lo = b, d.hi = 0; q.lo = 0, q.hi = 0; for (n = 0; DubbleLte(d, a) && n < 128; ++n) { d = DubbleShl(d); } for (; n > 0; --n) { t = a; d = DubbleShr(d); q = DubbleShl(q); s = a.lo, a.lo -= d.lo + 0, c = a.lo > s; s = a.hi, a.hi -= d.hi + c, c = a.hi > s; if (c) { a = t; } else { q.lo++; } } *r = a.lo; return q; } static struct Dubble DubbleIdiv(struct Dubble a, uint64_t b, uint64_t *r) { unsigned s, t; struct Dubble q; if ((s = a.hi >> 63)) a = DubbleNeg(a); if ((t = b >> 63)) b = -b; q = DubbleDiv(a, b, r); if (s ^ t) q = DubbleNeg(q); if (s) *r = -*r; return q; } void OpDivAlAhAxEbSigned(struct Machine *m, uint32_t rde) { int8_t y, r; int16_t x, q; x = Read16(m->ax); y = Read8(GetModrmRegisterBytePointerRead(m, rde)); if (!y) ThrowDivideError(m); if (x == INT16_MIN) ThrowDivideError(m); q = x / y; r = x % y; if (q != (int8_t)q) ThrowDivideError(m); m->ax[0] = q & 0xff; m->ax[1] = r & 0xff; } void OpDivAlAhAxEbUnsigned(struct Machine *m, uint32_t rde) { uint8_t y, r; uint16_t x, q; x = Read16(m->ax); y = Read8(GetModrmRegisterBytePointerRead(m, rde)); if (!y) ThrowDivideError(m); q = x / y; r = x % y; if (q > 255) ThrowDivideError(m); m->ax[0] = q & 0xff; m->ax[1] = r & 0xff; } static void OpDivRdxRaxEvqpSigned64(struct Machine *m, uint32_t rde, uint8_t *p) { uint64_t d, r; struct Dubble q; q.lo = Read64(m->ax); q.hi = Read64(m->dx); d = Read64(p); if (!d) ThrowDivideError(m); if (!q.lo && q.hi == 0x8000000000000000) ThrowDivideError(m); q = DubbleIdiv(q, d, &r); if ((int64_t)q.lo < 0 && (int64_t)q.hi != -1) ThrowDivideError(m); if ((int64_t)q.lo >= 0 && q.hi) ThrowDivideError(m); Write64(m->ax, q.lo); Write64(m->dx, r); } static void OpDivRdxRaxEvqpSigned32(struct Machine *m, uint32_t rde, uint8_t *p) { int32_t y, r; int64_t x, q; x = (uint64_t)Read32(m->dx) << 32 | Read32(m->ax); y = Read32(p); if (!y) ThrowDivideError(m); if (x == INT64_MIN) ThrowDivideError(m); q = x / y; r = x % y; if (q != (int32_t)q) ThrowDivideError(m); Write64(m->ax, q & 0xffffffff); Write64(m->dx, r & 0xffffffff); } static void OpDivRdxRaxEvqpSigned16(struct Machine *m, uint32_t rde, uint8_t *p) { int16_t y, r; int32_t x, q; x = (uint32_t)Read16(m->dx) << 16 | Read16(m->ax); y = Read16(p); if (!y) ThrowDivideError(m); if (x == INT32_MIN) ThrowDivideError(m); q = x / y; r = x % y; if (q != (int16_t)q) ThrowDivideError(m); Write16(m->ax, q); Write16(m->dx, r); } static void OpDivRdxRaxEvqpUnsigned16(struct Machine *m, uint32_t rde, uint8_t *p) { uint16_t y, r; uint32_t x, q; x = (uint32_t)Read16(m->dx) << 16 | Read16(m->ax); y = Read16(p); if (!y) ThrowDivideError(m); q = x / y; r = x % y; if (q > 65535) ThrowDivideError(m); Write16(m->ax, q); Write16(m->dx, r); } static void OpDivRdxRaxEvqpUnsigned32(struct Machine *m, uint32_t rde, uint8_t *p) { uint32_t y, r; uint64_t x, q; x = (uint64_t)Read32(m->dx) << 32 | Read32(m->ax); y = Read32(p); if (!y) ThrowDivideError(m); q = x / y; r = x % y; if (q > 4294967295) ThrowDivideError(m); Write64(m->ax, q & 0xffffffff); Write64(m->dx, r & 0xffffffff); } static void OpDivRdxRaxEvqpUnsigned64(struct Machine *m, uint32_t rde, uint8_t *p) { uint64_t d, r; struct Dubble q; q.lo = Read64(m->ax); q.hi = Read64(m->dx); d = Read64(p); if (!d) ThrowDivideError(m); q = DubbleDiv(q, d, &r); if (q.hi) ThrowDivideError(m); Write64(m->ax, q.lo); Write64(m->dx, r); } void OpDivRdxRaxEvqpSigned(struct Machine *m, uint32_t rde) { uint8_t *p; p = GetModrmRegisterWordPointerReadOszRexw(m, rde); if (Rexw(rde)) { OpDivRdxRaxEvqpSigned64(m, rde, p); } else if (!Osz(rde)) { OpDivRdxRaxEvqpSigned32(m, rde, p); } else { OpDivRdxRaxEvqpSigned16(m, rde, p); } } void OpDivRdxRaxEvqpUnsigned(struct Machine *m, uint32_t rde) { uint8_t *p; p = GetModrmRegisterWordPointerReadOszRexw(m, rde); if (Rexw(rde)) { OpDivRdxRaxEvqpUnsigned64(m, rde, p); } else if (!Osz(rde)) { OpDivRdxRaxEvqpUnsigned32(m, rde, p); } else { OpDivRdxRaxEvqpUnsigned16(m, rde, p); } } void OpMulAxAlEbSigned(struct Machine *m, uint32_t rde) { int16_t ax; uint8_t *p; unsigned of; p = GetModrmRegisterBytePointerRead(m, rde); ax = (int8_t)Read8(m->ax) * (int8_t)Read8(p); of = ax != (int8_t)ax; m->flags = SetFlag(m->flags, FLAGS_CF, of); m->flags = SetFlag(m->flags, FLAGS_OF, of); Write16(m->ax, ax); } void OpMulAxAlEbUnsigned(struct Machine *m, uint32_t rde) { int ax; uint8_t *p; unsigned of; p = GetModrmRegisterBytePointerRead(m, rde); ax = Read8(m->ax) * Read8(p); of = ax != (uint8_t)ax; m->flags = SetFlag(m->flags, FLAGS_CF, of); m->flags = SetFlag(m->flags, FLAGS_OF, of); Write16(m->ax, ax); } void OpMulRdxRaxEvqpSigned(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned of; int32_t dxax; int64_t edxeax; struct Dubble rdxrax; p = GetModrmRegisterWordPointerReadOszRexw(m, rde); if (Rexw(rde)) { rdxrax = DubbleImul(Read64(m->ax), Read64(p)); of = !!(rdxrax.hi + (rdxrax.lo >> 63)); Write64(m->ax, rdxrax.lo); Write64(m->dx, rdxrax.hi); } else if (!Osz(rde)) { edxeax = (int64_t)(int32_t)Read32(m->ax) * (int32_t)Read32(p); of = edxeax != (int32_t)edxeax; Write64(m->ax, edxeax); Write64(m->dx, edxeax >> 32); } else { dxax = (int32_t)(int16_t)Read16(m->ax) * (int16_t)Read16(p); of = dxax != (int16_t)dxax; Write16(m->ax, dxax); Write16(m->dx, dxax >> 16); } m->flags = SetFlag(m->flags, FLAGS_CF, of); m->flags = SetFlag(m->flags, FLAGS_OF, of); } void OpMulRdxRaxEvqpUnsigned(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned of; uint32_t dxax; uint64_t edxeax; struct Dubble rdxrax; p = GetModrmRegisterWordPointerReadOszRexw(m, rde); if (Rexw(rde)) { rdxrax = DubbleMul(Read64(m->ax), Read64(p)); of = !!rdxrax.hi; Write64(m->ax, rdxrax.lo); Write64(m->dx, rdxrax.hi); } else if (!Osz(rde)) { edxeax = (uint64_t)Read32(m->ax) * Read32(p); of = (uint32_t)edxeax != edxeax; Write64(m->ax, edxeax); Write64(m->dx, edxeax >> 32); } else { dxax = (uint32_t)(uint16_t)Read16(m->ax) * (uint16_t)Read16(p); of = (uint16_t)dxax != dxax; Write16(m->ax, dxax); Write16(m->dx, dxax >> 16); } m->flags = SetFlag(m->flags, FLAGS_CF, of); m->flags = SetFlag(m->flags, FLAGS_OF, of); } static void AluImul(struct Machine *m, uint32_t rde, uint8_t *a, uint8_t *b) { unsigned of; if (Rexw(rde)) { struct Dubble p; p = DubbleImul(Read64(a), Read64(b)); of = !!(p.hi + (p.lo >> 63)); Write64(RegRexrReg(m, rde), p.lo); } else if (!Osz(rde)) { int64_t z; z = (int64_t)(int32_t)Read32(a) * (int32_t)Read32(b); of = z != (int32_t)z; Write64(RegRexrReg(m, rde), z & 0xffffffff); } else { int32_t z; z = (int32_t)(int16_t)Read16(a) * (int16_t)Read16(b); of = z != (int16_t)z; Write16(RegRexrReg(m, rde), z); } m->flags = SetFlag(m->flags, FLAGS_CF, of); m->flags = SetFlag(m->flags, FLAGS_OF, of); } void OpImulGvqpEvqp(struct Machine *m, uint32_t rde) { AluImul(m, rde, RegRexrReg(m, rde), GetModrmRegisterWordPointerReadOszRexw(m, rde)); } void OpImulGvqpEvqpImm(struct Machine *m, uint32_t rde) { uint8_t b[8]; Write64(b, m->xedd->op.uimm0); AluImul(m, rde, GetModrmRegisterWordPointerReadOszRexw(m, rde), b); }
11,171
370
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/disarg.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/itoa.h" #include "libc/intrin/bits.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "tool/build/lib/demangle.h" #include "tool/build/lib/dis.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/high.h" #include "tool/build/lib/modrm.h" static const char kRiz[2][4] = {"eiz", "riz"}; static const char kRip[2][4] = {"eip", "rip"}; static const char kSka[4][4] = {"", ",2", ",4", ",8"}; static const char kSeg[8][3] = {"es", "cs", "ss", "ds", "fs", "gs"}; static const char kCtl[8][4] = {"cr0", "wut", "cr2", "cr3", "cr4", "wut", "wut", "wut"}; static const char kBreg[2][2][8][5] = { {{"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}, {"al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil"}}, {{"wut", "wut", "wut", "wut", "wut", "wut", "wut", "wut"}, {"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b"}}, }; static const char kGreg[2][2][2][8][5] = { {{{"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}, {"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"}}, {{"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}, {"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"}}}, {{{"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}, {"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"}}, {{"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}, {"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"}}}, }; static int64_t RipRelative(struct Dis *d, int64_t i) { return d->addr + d->xedd->length + i; } static int64_t ZeroExtend(uint32_t rde, int64_t i) { switch (Mode(rde)) { case XED_MODE_REAL: return i & 0xffff; case XED_MODE_LEGACY: return i & 0xffffffff; default: return i; } } static int64_t Unrelative(uint32_t rde, int64_t i) { switch (Eamode(rde)) { case XED_MODE_REAL: return i & 0xffff; case XED_MODE_LEGACY: return i & 0xffffffff; default: return i; } } static int64_t GetSeg(struct Dis *d, uint32_t rde, unsigned char *s) { switch (Sego(rde) ? Sego(rde) : d->xedd->op.hint) { default: return Read64(s); case 1: return Read64(d->m->es); case 2: return Read64(d->m->cs); case 3: return Read64(d->m->ss); case 4: return Read64(d->m->ds); } } static const char *GetAddrReg(struct Dis *d, uint32_t rde, uint8_t x, uint8_t r) { return kGreg[Eamode(rde) == XED_MODE_REAL][Eamode(rde) == XED_MODE_LONG] [x & 1][r & 7]; } static char *DisRegister(char *p, const char *s) { p = HighStart(p, g_high.reg); *p++ = '%'; p = stpcpy(p, s); p = HighEnd(p); return p; } static char *DisComment(char *p, const char *s) { p = HighStart(p, g_high.comment); p = stpcpy(p, s); p = HighEnd(p); return p; } static char *DisRegisterByte(struct Dis *d, uint32_t rde, char *p, bool g, int r) { return DisRegister(p, kBreg[g][Rex(rde)][r]); } static char *DisRegisterWord(struct Dis *d, uint32_t rde, char *p, bool g, int r) { return DisRegister(p, kGreg[Osz(rde)][Rexw(rde)][g][r]); } static char *DisInt(char *p, int64_t x) { if (-15 <= x && x <= 15) { p = FormatInt64(p, x); } else if (x == INT64_MIN) { p = stpcpy(p, "-0x"); p += uint64toarray_radix16(INT64_MIN, p); } else if (x < 0 && -x < 0xFFFFFFFF) { p = stpcpy(p, "-0x"); p += uint64toarray_radix16(-x, p); } else { p = stpcpy(p, "0x"); p += uint64toarray_radix16(x, p); } return p; } static char *DisSymImpl(struct Dis *d, char *p, int64_t x, long sym) { int64_t addend; const char *name; addend = x - d->syms.p[sym].addr; name = d->syms.stab + d->syms.p[sym].name; p = Demangle(p, name, DIS_MAX_SYMBOL_LENGTH); if (addend) { *p++ = '+'; p = DisInt(p, addend); } return p; } static char *DisSym(struct Dis *d, char *p, int64_t value, int64_t addr) { long sym; if ((sym = DisFindSym(d, addr)) != -1 && d->syms.p[sym].name) { return DisSymImpl(d, p, addr, sym); } else { return DisInt(p, value); } } static char *DisSymLiteral(struct Dis *d, uint32_t rde, char *p, uint64_t addr, uint64_t ip) { *p++ = '$'; p = HighStart(p, g_high.literal); p = DisSym(d, p, addr, addr); p = HighEnd(p); return p; } static char *DisGvqp(struct Dis *d, uint32_t rde, char *p) { return DisRegisterWord(d, rde, p, Rexr(rde), ModrmReg(rde)); } static char *DisGdqp(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[0][Rexw(rde)][Rexr(rde)][ModrmReg(rde)]); } static char *DisGb(struct Dis *d, uint32_t rde, char *p) { return DisRegisterByte(d, rde, p, Rexr(rde), ModrmReg(rde)); } static char *DisSego(struct Dis *d, uint32_t rde, char *p) { int seg; seg = Sego(rde) ? Sego(rde) : d->xedd->op.hint; if (seg) { p = DisRegister(p, kSeg[seg - 1]); *p++ = ':'; } return p; } static bool IsRealModrmAbsolute(uint32_t rde) { return Eamode(rde) == XED_MODE_REAL && ModrmRm(rde) == 6 && !ModrmMod(rde); } static char *DisDisp(struct Dis *d, uint32_t rde, char *p) { bool rela; int64_t disp; if (ModrmMod(rde) == 0b01 || ModrmMod(rde) == 0b10 || IsRipRelative(rde) || IsRealModrmAbsolute(rde) || (Eamode(rde) != XED_MODE_REAL && ModrmMod(rde) == 0b00 && ModrmRm(rde) == 0b100 && SibBase(d->xedd) == 0b101)) { disp = d->xedd->op.disp; if (IsRipRelative(rde)) { if (Mode(rde) == XED_MODE_LONG) { disp = RipRelative(d, disp); rela = true; } else { disp = Unrelative(rde, disp); rela = false; } } else if (IsRealModrmAbsolute(rde)) { disp = Unrelative(rde, disp); rela = false; } else { rela = true; } p = DisSym(d, p, disp, disp); } return p; } static char *DisBis(struct Dis *d, uint32_t rde, char *p) { const char *base, *index, *scale; base = index = scale = NULL; if (Eamode(rde) != XED_MODE_REAL) { if (!SibExists(rde)) { DCHECK(!d->xedd->op.has_sib); if (IsRipRelative(rde)) { if (Mode(rde) == XED_MODE_LONG) { base = kRip[Eamode(rde) == XED_MODE_LONG]; } } else { base = GetAddrReg(d, rde, Rexb(rde), ModrmRm(rde)); } } else if (!SibIsAbsolute(d->xedd, rde)) { if (SibHasBase(d->xedd, rde)) { base = GetAddrReg(d, rde, Rexb(rde), SibBase(d->xedd)); } if (SibHasIndex(d->xedd)) { index = GetAddrReg(d, rde, Rexx(d->xedd), SibIndex(d->xedd)); } else if (d->xedd->op.scale) { index = kRiz[Eamode(rde) == XED_MODE_LONG]; } scale = kSka[d->xedd->op.scale]; } } else { switch (ModrmRm(rde)) { case 0: base = "bx"; index = "si"; break; case 1: base = "bx"; index = "di"; break; case 2: base = "bp"; index = "si"; break; case 3: base = "bp"; index = "di"; break; case 4: base = "si"; break; case 5: base = "di"; break; case 6: if (ModrmMod(rde)) base = "bp"; break; case 7: base = "bx"; break; default: unreachable; } } if (base || index) { *p++ = '('; if (base) { p = DisRegister(p, base); } if (index) { *p++ = ','; p = DisRegister(p, index); if (scale) { p = stpcpy(p, scale); } } *p++ = ')'; } *p = '\0'; return p; } static char *DisM(struct Dis *d, uint32_t rde, char *p) { p = DisSego(d, rde, p); p = DisDisp(d, rde, p); p = DisBis(d, rde, p); return p; } static char *DisRegMem(struct Dis *d, uint32_t rde, char *p, char *f(struct Dis *, uint32_t, char *)) { if (IsModrmRegister(rde)) { return f(d, rde, p); } else { return DisM(d, rde, p); } } static dontinline char *DisE(struct Dis *d, uint32_t rde, char *p, char *f(struct Dis *, uint32_t, char *, bool, int)) { if (IsModrmRegister(rde)) { return f(d, rde, p, Rexb(rde), ModrmRm(rde)); } else { return DisM(d, rde, p); } } static char *DisEb(struct Dis *d, uint32_t rde, char *p) { return DisE(d, rde, p, DisRegisterByte); } static char *DisEvqp(struct Dis *d, uint32_t rde, char *p) { return DisE(d, rde, p, DisRegisterWord); } static char *DisRv(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[Osz(rde)][0][Rexb(rde)][ModrmRm(rde)]); } static char *DisRvqp(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[Osz(rde)][Rexw(rde)][Rexb(rde)][ModrmRm(rde)]); } static char *DisRdqp(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[0][Rexw(rde)][Rexb(rde)][ModrmRm(rde)]); } static char *DisEdqp(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisRdqp); } static char *DisEv(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisRv); } static char *DisGvq(struct Dis *d, uint32_t rde, char *p, int r) { const char *s; if (Mode(rde) == XED_MODE_LONG) { s = kGreg[Osz(rde)][!Osz(rde)][Rexb(rde)][r]; } else { s = kGreg[Osz(rde)][0][Rexb(rde)][r]; } return DisRegister(p, s); } static char *DisZvq(struct Dis *d, uint32_t rde, char *p) { return DisGvq(d, rde, p, ModrmSrm(rde)); } static char *DisEvqReg(struct Dis *d, uint32_t rde, char *p) { return DisGvq(d, rde, p, ModrmRm(rde)); } static char *DisEvq(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisEvqReg); } static char *DisEdReg(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[0][0][Rexb(rde)][ModrmRm(rde)]); } static char *DisEd(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisEdReg); } static char *DisEqReg(struct Dis *d, uint32_t rde, char *p) { const char *r; if (Mode(rde) == XED_MODE_LONG) { r = kGreg[0][1][Rexb(rde)][ModrmRm(rde)]; } else { r = kGreg[Osz(rde)][0][Rexb(rde)][ModrmRm(rde)]; } return DisRegister(p, r); } static char *DisEq(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisEqReg); } static char *DisZvqp(struct Dis *d, uint32_t rde, char *p) { return DisRegisterWord(d, rde, p, Rexb(rde), ModrmSrm(rde)); } static char *DisZb(struct Dis *d, uint32_t rde, char *p) { return DisRegisterByte(d, rde, p, Rexb(rde), ModrmSrm(rde)); } static char *DisEax(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[Osz(rde)][0][0][0]); } static char *DisRax(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[Osz(rde)][Rexw(rde)][0][0]); } static char *DisRdx(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[Osz(rde)][Rexw(rde)][0][2]); } static char *DisPort(struct Dis *d, uint32_t rde, char *p) { *p++ = '('; p = DisRegister(p, kGreg[1][0][0][2]); *p++ = ')'; *p = '\0'; return p; } static char *DisCd(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kCtl[ModrmReg(rde)]); } static char *DisHd(struct Dis *d, uint32_t rde, char *p) { return DisRegister(p, kGreg[0][Mode(rde) == XED_MODE_LONG][0][ModrmRm(rde)]); } static char *DisImm(struct Dis *d, uint32_t rde, char *p) { return DisSymLiteral(d, rde, p, d->xedd->op.uimm0, ZeroExtend(rde, d->xedd->op.uimm0)); } static char *DisRvds(struct Dis *d, uint32_t rde, char *p) { return DisSymLiteral(d, rde, p, d->xedd->op.disp, d->xedd->op.disp); } static char *DisKpvds(struct Dis *d, uint32_t rde, char *p, uint64_t x) { *p++ = '$'; p = HighStart(p, g_high.literal); p = DisInt(p, x); p = HighEnd(p); return p; } static char *DisKvds(struct Dis *d, uint32_t rde, char *p) { return DisKpvds(d, rde, p, d->xedd->op.uimm0); } static char *DisPvds(struct Dis *d, uint32_t rde, char *p) { return DisKpvds(d, rde, p, d->xedd->op.disp & (Osz(rde) ? 0xffff : 0xffffffff)); } static char *DisOne(struct Dis *d, uint32_t rde, char *p) { *p++ = '$'; p = HighStart(p, g_high.literal); p = stpcpy(p, "1"); p = HighEnd(p); return p; } static char *DisJbs(struct Dis *d, uint32_t rde, char *p) { if (d->xedd->op.disp > 0) *p++ = '+'; p = FormatInt64(p, d->xedd->op.disp); return p; } static char *DisJb(struct Dis *d, uint32_t rde, char *p) { if (d->xedd->op.disp > 0) *p++ = '+'; p = FormatUint32(p, d->xedd->op.disp & 0xff); return p; } static char *DisJvds(struct Dis *d, uint32_t rde, char *p) { return DisSym(d, p, RipRelative(d, d->xedd->op.disp), RipRelative(d, d->xedd->op.disp) - Read64(d->m->cs)); } static char *DisAbs(struct Dis *d, uint32_t rde, char *p) { return DisSym(d, p, d->xedd->op.disp, d->xedd->op.disp); } static char *DisSw(struct Dis *d, uint32_t rde, char *p) { if (kSeg[ModrmReg(rde)][0]) p = DisRegister(p, kSeg[ModrmReg(rde)]); return p; } static char *DisSpecialAddr(struct Dis *d, uint32_t rde, char *p, int r) { *p++ = '('; p = DisRegister(p, GetAddrReg(d, rde, 0, r)); *p++ = ')'; *p = '\0'; return p; } static char *DisY(struct Dis *d, uint32_t rde, char *p) { return DisSpecialAddr(d, rde, p, 7); // es:di } static char *DisX(struct Dis *d, uint32_t rde, char *p) { p = DisSego(d, rde, p); return DisSpecialAddr(d, rde, p, 6); // ds:si } static char *DisBBb(struct Dis *d, uint32_t rde, char *p) { p = DisSego(d, rde, p); return DisSpecialAddr(d, rde, p, 3); // ds:bx } static char *DisXmm(struct Dis *d, uint32_t rde, char *p, const char *s, int reg) { p = HighStart(p, g_high.reg); *p++ = '%'; p = stpcpy(p, s); p = FormatUint32(p, reg); p = HighEnd(p); return p; } static char *DisNq(struct Dis *d, uint32_t rde, char *p) { return DisXmm(d, rde, p, "mm", ModrmRm(rde)); } static char *DisPq(struct Dis *d, uint32_t rde, char *p) { return DisXmm(d, rde, p, "mm", ModrmReg(rde)); } static char *DisUq(struct Dis *d, uint32_t rde, char *p) { return DisXmm(d, rde, p, "xmm", RexbRm(rde)); } static char *DisUdq(struct Dis *d, uint32_t rde, char *p) { return DisXmm(d, rde, p, "xmm", RexbRm(rde)); } static char *DisVdq(struct Dis *d, uint32_t rde, char *p) { return DisXmm(d, rde, p, "xmm", RexrReg(rde)); } static char *DisQq(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisNq); } static char *DisEst(struct Dis *d, uint32_t rde, char *p) { p = DisRegister(p, "st"); if (ModrmRm(rde) != 0) { *p++ = '('; *p++ = '0' + ModrmRm(rde); *p++ = ')'; *p = '\0'; } return p; } static char *DisEst1(struct Dis *d, uint32_t rde, char *p) { if (ModrmRm(rde) != 1) { p = DisEst(d, rde, p); } else { *p = '\0'; } return p; } static char *DisEssr(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisEst); } static char *DisWps(struct Dis *d, uint32_t rde, char *p) { return DisRegMem(d, rde, p, DisUdq); } #define DisEdr DisM #define DisEqp DisEq #define DisEsr DisM #define DisGv DisGvqp #define DisIb DisImm #define DisIbs DisImm #define DisIbss DisImm #define DisIvds DisImm #define DisIvqp DisImm #define DisIvs DisImm #define DisIw DisImm #define DisMdi DisM #define DisMdq DisM #define DisMdqp DisM #define DisMdr DisM #define DisMe DisM #define DisMer DisM #define DisMp DisM #define DisMps DisM #define DisMq DisM #define DisMqi DisM #define DisMs DisM #define DisMsr DisEssr #define DisMw DisM #define DisMwi DisM #define DisOb DisAbs #define DisOvqp DisAbs #define DisPpi DisPq #define DisQpi DisQq #define DisVpd DisVdq #define DisVps DisVdq #define DisVq DisVdq #define DisVsd DisVdq #define DisVss DisVdq #define DisWdq DisWps #define DisWpd DisWps #define DisWpsq DisWps #define DisWq DisWps #define DisWsd DisWps #define DisWss DisWps #define DisXb DisX #define DisXv DisX #define DisXvqp DisX #define DisYb DisY #define DisYv DisY #define DisYvqp DisY #define DisZv DisZvqp static const struct DisArg { char s[8]; char *(*f)(struct Dis *, uint32_t, char *); } kDisArgs[] = /* <sorted> */ { {"$1", DisOne}, // {"%Cd", DisCd}, // {"%Gb", DisGb}, // {"%Gdqp", DisGdqp}, // {"%Gv", DisGv}, // {"%Gvqp", DisGvqp}, // {"%Hd", DisHd}, // {"%Nq", DisNq}, // {"%Ppi", DisPpi}, // {"%Pq", DisPq}, // {"%Rdqp", DisRdqp}, // {"%Rvqp", DisRvqp}, // {"%Sw", DisSw}, // {"%Udq", DisUdq}, // {"%Uq", DisUq}, // {"%Vdq", DisVdq}, // {"%Vpd", DisVpd}, // {"%Vps", DisVps}, // {"%Vq", DisVq}, // {"%Vsd", DisVsd}, // {"%Vss", DisVss}, // {"%Zb", DisZb}, // {"%Zv", DisZv}, // {"%Zvq", DisZvq}, // {"%Zvqp", DisZvqp}, // {"%eAX", DisEax}, // {"%rAX", DisRax}, // {"%rDX", DisRdx}, // {"BBb", DisBBb}, // {"DX", DisPort}, // {"EST", DisEst}, // {"EST1", DisEst1}, // {"ESsr", DisEssr}, // {"Eb", DisEb}, // {"Ed", DisEd}, // {"Edqp", DisEdqp}, // {"Edr", DisEdr}, // {"Eq", DisEq}, // {"Eqp", DisEqp}, // {"Esr", DisEsr}, // {"Ev", DisEv}, // {"Evq", DisEvq}, // {"Evqp", DisEvqp}, // {"Ew", DisEvqp}, // {"Ib", DisIb}, // {"Ibs", DisIbs}, // {"Ibss", DisIbss}, // {"Ivds", DisIvds}, // {"Ivqp", DisIvqp}, // {"Ivs", DisIvs}, // {"Iw", DisIw}, // {"Jb", DisJb}, // {"Jbs", DisJbs}, // {"Jvds", DisJvds}, // {"Kvds", DisKvds}, // {"M", DisM}, // {"Mdi", DisMdi}, // {"Mdq", DisMdq}, // {"Mdqp", DisMdqp}, // {"Mdr", DisMdr}, // {"Me", DisMe}, // {"Mer", DisMer}, // {"Mp", DisMp}, // {"Mps", DisMps}, // {"Mq", DisMq}, // {"Mqi", DisMqi}, // {"Ms", DisMs}, // {"Msr", DisMsr}, // {"Mw", DisMw}, // {"Mwi", DisMwi}, // {"Ob", DisOb}, // {"Ovqp", DisOvqp}, // {"Pvds", DisPvds}, // {"Qpi", DisQpi}, // {"Qq", DisQq}, // {"Rvds", DisRvds}, // {"Wdq", DisWdq}, // {"Wpd", DisWpd}, // {"Wps", DisWps}, // {"Wpsq", DisWpsq}, // {"Wq", DisWq}, // {"Wsd", DisWsd}, // {"Wss", DisWss}, // {"Xb", DisXb}, // {"Xv", DisXv}, // {"Xvqp", DisXvqp}, // {"Yb", DisYb}, // {"Yv", DisYv}, // {"Yvqp", DisYvqp}, // }; char *DisArg(struct Dis *d, char *p, const char *s) { char k[8]; int m, l, r; l = 0; r = ARRAYLEN(kDisArgs) - 1; strncpy(k, s, 8); while (l <= r) { m = (l + r) >> 1; if (READ64BE(kDisArgs[m].s) < READ64BE(k)) { l = m + 1; } else if (READ64BE(kDisArgs[m].s) > READ64BE(k)) { r = m - 1; } else { return kDisArgs[m].f(d, d->xedd->op.rde, p); } } if (*s == '%') { p = DisRegister(p, s + 1); } else { p = stpcpy(p, s); } return p; }
21,077
748
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/sse.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/str/str.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/throw.h" static void MmxPor(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] |= y[i]; } } static void MmxPxor(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] ^= y[i]; } } static void MmxPsubb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] -= y[i]; } } static void MmxPaddb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] += y[i]; } } static void MmxPand(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] &= y[i]; } } static void MmxPandn(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = ~x[i] & y[i]; } } static void MmxPavgb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = (x[i] + y[i] + 1) >> 1; } } static void MmxPabsb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = ABS((int8_t)y[i]); } } static void MmxPminub(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MIN(x[i], y[i]); } } static void MmxPmaxub(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MAX(x[i], y[i]); } } static void MmxPaddusb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MIN(255, x[i] + y[i]); } } static void MmxPsubusb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MIN(255, MAX(0, x[i] - y[i])); } } static void MmxPcmpeqb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = -(x[i] == y[i]); } } static void MmxPcmpgtb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = -((int8_t)x[i] > (int8_t)y[i]); } } static void MmxPsubsb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MAX(-128, MIN(127, (int8_t)x[i] - (int8_t)y[i])); } } static void MmxPaddsb(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 8; ++i) { x[i] = MAX(-128, MIN(127, (int8_t)x[i] + (int8_t)y[i])); } } static void MmxPmulhrsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; int16_t a, b; for (i = 0; i < 4; ++i) { a = Read16(x + i * 2); b = Read16(y + i * 2); Write16(x + i * 2, (((a * b) >> 14) + 1) >> 1); } } static void MmxPmaddubsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MAX(-32768, MIN(32767, (x[i * 2 + 0] * (int8_t)y[i * 2 + 0] + x[i * 2 + 1] * (int8_t)y[i * 2 + 1])))); } } static void MmxPsraw(uint8_t x[8], unsigned k) { unsigned i; if (k > 15) k = 15; for (i = 0; i < 4; ++i) { Write16(x + i * 2, (int16_t)Read16(x + i * 2) >> k); } } static void MmxPsrad(uint8_t x[8], unsigned k) { unsigned i; if (k > 31) k = 31; for (i = 0; i < 2; ++i) { Write32(x + i * 4, (int32_t)Read32(x + i * 4) >> k); } } static void MmxPsrlw(uint8_t x[8], unsigned k) { unsigned i; if (k < 16) { for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) >> k); } } else { memset(x, 0, 8); } } static void MmxPsllw(uint8_t x[8], unsigned k) { unsigned i; if (k <= 15) { for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) << k); } } else { memset(x, 0, 8); } } static void MmxPsrld(uint8_t x[8], unsigned k) { unsigned i; if (k <= 31) { for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) >> k); } } else { memset(x, 0, 8); } } static void MmxPslld(uint8_t x[8], unsigned k) { unsigned i; if (k <= 31) { for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) << k); } } else { memset(x, 0, 8); } } static void MmxPsrlq(uint8_t x[8], unsigned k) { if (k <= 63) { Write64(x, Read64(x) >> k); } else { memset(x, 0, 8); } } static void MmxPsllq(uint8_t x[8], unsigned k) { if (k <= 63) { Write64(x, Read64(x) << k); } else { memset(x, 0, 8); } } static void MmxPslldq(uint8_t x[8], unsigned k) { unsigned i; uint8_t t[8]; if (k > 8) k = 8; for (i = 0; i < k; ++i) t[i] = 0; for (i = 0; i < 8 - k; ++i) t[k + i] = x[i]; memcpy(x, t, 8); } static void MmxPsrldq(uint8_t x[8], unsigned k) { uint8_t t[8]; if (k > 8) k = 8; memcpy(t, x + k, 8 - k); memset(t + (8 - k), 0, k); memcpy(x, t, 8); } static void MmxPalignr(uint8_t x[8], const uint8_t y[8], unsigned k) { uint8_t t[24]; memcpy(t, y, 8); memcpy(t + 8, x, 8); memset(t + 16, 0, 8); memcpy(x, t + MIN(k, 16), 8); } static void MmxPsubw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) - Read16(y + i * 2)); } } static void MmxPaddw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) + Read16(y + i * 2)); } } static void MmxPsubd(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) - Read32(y + i * 4)); } } static void MmxPaddd(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) + Read32(y + i * 4)); } } static void MmxPaddq(uint8_t x[8], const uint8_t y[8]) { Write64(x, Read64(x) + Read64(y)); } static void MmxPsubq(uint8_t x[8], const uint8_t y[8]) { Write64(x, Read64(x) - Read64(y)); } static void MmxPaddsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + i * 2) + (int16_t)Read16(y + i * 2))))); } } static void MmxPsubsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + i * 2) - (int16_t)Read16(y + i * 2))))); } } static void MmxPaddusw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MIN(65535, Read16(x + i * 2) + Read16(y + i * 2))); } } static void MmxPsubusw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MIN(65535, MAX(0, Read16(x + i * 2) - Read16(y + i * 2)))); } } static void MmxPminsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MIN((int16_t)Read16(x + i * 2), (int16_t)Read16(y + i * 2))); } } static void MmxPmaxsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, MAX((int16_t)Read16(x + i * 2), (int16_t)Read16(y + i * 2))); } } static void MmxPackuswb(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint8_t t[8]; for (i = 0; i < 4; ++i) { t[i + 0] = MIN(255, MAX(0, (int16_t)Read16(x + i * 2))); } for (i = 0; i < 4; ++i) { t[i + 4] = MIN(255, MAX(0, (int16_t)Read16(y + i * 2))); } memcpy(x, t, 8); } static void MmxPacksswb(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint8_t t[8]; for (i = 0; i < 4; ++i) { t[i + 0] = MAX(-128, MIN(127, (int16_t)Read16(x + i * 2))); } for (i = 0; i < 4; ++i) { t[i + 4] = MAX(-128, MIN(127, (int16_t)Read16(y + i * 2))); } memcpy(x, t, 8); } static void MmxPackssdw(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint8_t t[8]; for (i = 0; i < 2; ++i) { Write16(t + i * 2 + 0, MAX(-32768, MIN(32767, (int32_t)Read32(x + i * 4)))); } for (i = 0; i < 2; ++i) { Write16(t + i * 2 + 4, MAX(-32768, MIN(32767, (int32_t)Read32(y + i * 4)))); } memcpy(x, t, 8); } static void MmxPcmpgtw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, -((int16_t)Read16(x + i * 2) > (int16_t)Read16(y + i * 2))); } } static void MmxPcmpeqw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, -(Read16(x + i * 2) == Read16(y + i * 2))); } } static void MmxPcmpgtd(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, -((int32_t)Read32(x + i * 4) > (int32_t)Read32(y + i * 4))); } } static void MmxPcmpeqd(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, -(Read32(x + i * 4) == Read32(y + i * 4))); } } static void MmxPsrawv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k > 15) k = 15; for (i = 0; i < 4; ++i) { Write16(x + i * 2, (int16_t)Read16(x + i * 2) >> k); } } static void MmxPsradv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k > 31) k = 31; for (i = 0; i < 2; ++i) { Write32(x + i * 4, (int32_t)Read32(x + i * 4) >> k); } } static void MmxPsrlwv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k < 16) { for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) >> k); } } else { memset(x, 0, 8); } } static void MmxPsllwv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k < 16) { for (i = 0; i < 4; ++i) { Write16(x + i * 2, Read16(x + i * 2) << k); } } else { memset(x, 0, 8); } } static void MmxPsrldv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k < 32) { for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) >> k); } } else { memset(x, 0, 8); } } static void MmxPslldv(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint64_t k; k = Read64(y); if (k < 32) { for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) << k); } } else { memset(x, 0, 8); } } static void MmxPsrlqv(uint8_t x[8], const uint8_t y[8]) { uint64_t k; k = Read64(y); if (k < 64) { Write64(x, Read64(x) >> k); } else { memset(x, 0, 8); } } static void MmxPsllqv(uint8_t x[8], const uint8_t y[8]) { uint64_t k; k = Read64(y); if (k < 64) { Write64(x, Read64(x) << k); } else { memset(x, 0, 8); } } static void MmxPavgw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, (Read16(x + i * 2) + Read16(y + i * 2) + 1) >> 1); } } static void MmxPsadbw(uint8_t x[8], const uint8_t y[8]) { unsigned i, s, t; for (s = i = 0; i < 4; ++i) s += ABS(x[i] - y[i]); for (t = 0; i < 8; ++i) t += ABS(x[i] - y[i]); Write32(x + 0, s); Write32(x + 4, t); } static void MmxPmaddwd(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, ((int16_t)Read16(x + i * 4 + 0) * (int16_t)Read16(y + i * 4 + 0) + (int16_t)Read16(x + i * 4 + 2) * (int16_t)Read16(y + i * 4 + 2))); } } static void MmxPmulhuw(uint8_t x[8], const uint8_t y[8]) { uint32_t v; unsigned i; for (i = 0; i < 4; ++i) { v = Read16(x + i * 2); v *= Read16(y + i * 2); v >>= 16; Write16(x + i * 2, v); } } static void MmxPmulhw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, ((int16_t)Read16(x + i * 2) * (int16_t)Read16(y + i * 2)) >> 16); } } static void MmxPmuludq(uint8_t x[8], const uint8_t y[8]) { Write64(x, (uint64_t)Read32(x) * Read32(y)); } static void MmxPmullw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, (int16_t)Read16(x + i * 2) * (int16_t)Read16(y + i * 2)); } } static void MmxPmulld(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 2; ++i) { Write32(x + i * 4, Read32(x + i * 4) * Read32(y + i * 4)); } } static void MmxPshufb(uint8_t x[8], const uint8_t y[8]) { unsigned i; uint8_t t[8]; for (i = 0; i < 8; ++i) { t[i] = (y[i] & 128) ? 0 : x[y[i] & 7]; } memcpy(x, t, 8); } static void MmxPsignb(uint8_t x[8], const uint8_t y[8]) { int v; unsigned i; for (i = 0; i < 8; ++i) { v = (int8_t)y[i]; if (!v) { x[i] = 0; } else if (v < 0) { x[i] = -(int8_t)x[i]; } } } static void MmxPsignw(uint8_t x[8], const uint8_t y[8]) { int v; unsigned i; for (i = 0; i < 4; ++i) { v = (int16_t)Read16(y + i * 2); if (!v) { Write16(x + i * 2, 0); } else if (v < 0) { Write16(x + i * 2, -(int16_t)Read16(x + i * 2)); } } } static void MmxPsignd(uint8_t x[8], const uint8_t y[8]) { int32_t v; unsigned i; for (i = 0; i < 2; ++i) { v = Read32(y + i * 4); if (!v) { Write32(x + i * 4, 0); } else if (v < 0) { Write32(x + i * 4, -Read32(x + i * 4)); } } } static void MmxPabsw(uint8_t x[8], const uint8_t y[8]) { unsigned i; for (i = 0; i < 4; ++i) { Write16(x + i * 2, ABS((int16_t)Read16(y + i * 2))); } } static void MmxPabsd(uint8_t x[8], const uint8_t y[8]) { int32_t v; unsigned i; for (i = 0; i < 2; ++i) { v = Read32(y + i * 4); Write32(x + i * 4, v >= 0 ? v : -(uint32_t)v); } } static void MmxPhaddw(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write16(t + 0 * 2, Read16(x + 0 * 2) + Read16(x + 1 * 2)); Write16(t + 1 * 2, Read16(x + 2 * 2) + Read16(x + 3 * 2)); Write16(t + 2 * 2, Read16(y + 0 * 2) + Read16(y + 1 * 2)); Write16(t + 3 * 2, Read16(y + 2 * 2) + Read16(y + 3 * 2)); memcpy(x, t, 8); } static void MmxPhsubw(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write16(t + 0 * 2, Read16(x + 0 * 2) - Read16(x + 1 * 2)); Write16(t + 1 * 2, Read16(x + 2 * 2) - Read16(x + 3 * 2)); Write16(t + 2 * 2, Read16(y + 0 * 2) - Read16(y + 1 * 2)); Write16(t + 3 * 2, Read16(y + 2 * 2) - Read16(y + 3 * 2)); memcpy(x, t, 8); } static void MmxPhaddd(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write32(t + 0 * 4, Read32(x + 0 * 4) + Read32(x + 1 * 4)); Write32(t + 1 * 4, Read32(y + 0 * 4) + Read32(y + 1 * 4)); memcpy(x, t, 8); } static void MmxPhsubd(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write32(t + 0 * 4, Read32(x + 0 * 4) - Read32(x + 1 * 4)); Write32(t + 1 * 4, Read32(y + 0 * 4) - Read32(y + 1 * 4)); memcpy(x, t, 8); } static void MmxPhaddsw(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write16(t + 0 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 0 * 2) + (int16_t)Read16(x + 1 * 2))))); Write16(t + 1 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 2 * 2) + (int16_t)Read16(x + 3 * 2))))); Write16(t + 2 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 0 * 2) + (int16_t)Read16(y + 1 * 2))))); Write16(t + 3 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 2 * 2) + (int16_t)Read16(y + 3 * 2))))); memcpy(x, t, 8); } static void MmxPhsubsw(uint8_t x[8], const uint8_t y[8]) { uint8_t t[8]; Write16(t + 0 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 0 * 2) - (int16_t)Read16(x + 1 * 2))))); Write16(t + 1 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 2 * 2) - (int16_t)Read16(x + 3 * 2))))); Write16(t + 2 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 0 * 2) - (int16_t)Read16(x + 1 * 2))))); Write16(t + 3 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 2 * 2) - (int16_t)Read16(y + 3 * 2))))); memcpy(x, t, 8); } static void MmxPunpcklbw(uint8_t x[8], const uint8_t y[8]) { x[7] = y[3]; x[6] = x[3]; x[5] = y[2]; x[4] = x[2]; x[3] = y[1]; x[2] = x[1]; x[1] = y[0]; x[0] = x[0]; } static void MmxPunpckhbw(uint8_t x[8], const uint8_t y[8]) { x[0] = x[4]; x[1] = y[4]; x[2] = x[5]; x[3] = y[5]; x[4] = x[6]; x[5] = y[6]; x[6] = x[7]; x[7] = y[7]; } static void MmxPunpcklwd(uint8_t x[8], const uint8_t y[8]) { x[6] = y[2]; x[7] = y[3]; x[4] = x[2]; x[5] = x[3]; x[2] = y[0]; x[3] = y[1]; x[0] = x[0]; x[1] = x[1]; } static void MmxPunpckldq(uint8_t x[8], const uint8_t y[8]) { x[4] = y[0]; x[5] = y[1]; x[6] = y[2]; x[7] = y[3]; x[0] = x[0]; x[1] = x[1]; x[2] = x[2]; x[3] = x[3]; } static void MmxPunpckhwd(uint8_t x[8], const uint8_t y[8]) { x[0] = x[4]; x[1] = x[5]; x[2] = y[4]; x[3] = y[5]; x[4] = x[6]; x[5] = x[7]; x[6] = y[6]; x[7] = y[7]; } static void MmxPunpckhdq(uint8_t x[8], const uint8_t y[8]) { x[0] = x[4]; x[1] = x[5]; x[2] = x[6]; x[3] = x[7]; x[4] = y[4]; x[5] = y[5]; x[6] = y[6]; x[7] = y[7]; } static void MmxPunpcklqdq(uint8_t x[8], const uint8_t y[8]) { } static void MmxPunpckhqdq(uint8_t x[8], const uint8_t y[8]) { } static void SsePsubb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] -= y[i]; } } static void SsePaddb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] += y[i]; } } static void SsePor(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] |= y[i]; } } static void SsePxor(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] ^= y[i]; } } static void SsePand(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] &= y[i]; } } static void SsePandn(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = ~x[i] & y[i]; } } static void SsePcmpeqb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = -(x[i] == y[i]); } } static void SsePcmpgtb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = -((int8_t)x[i] > (int8_t)y[i]); } } static void SsePavgb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = (x[i] + y[i] + 1) >> 1; } } static void SsePabsb(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = ABS((int8_t)y[i]); } } static void SsePminub(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = MIN(x[i], y[i]); } } static void SsePmaxub(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 16; ++i) { x[i] = MAX(x[i], y[i]); } } static void SsePslldq(uint8_t x[16], unsigned k) { unsigned i; uint8_t t[16]; if (k > 16) k = 16; for (i = 0; i < k; ++i) t[i] = 0; for (i = 0; i < 16 - k; ++i) t[k + i] = x[i]; memcpy(x, t, 16); } static void SsePsrldq(uint8_t x[16], unsigned k) { uint8_t t[16]; if (k > 16) k = 16; memcpy(t, x + k, 16 - k); memset(t + (16 - k), 0, k); memcpy(x, t, 16); } static void SsePalignr(uint8_t x[16], const uint8_t y[16], unsigned k) { uint8_t t[48]; memcpy(t, y, 16); memcpy(t + 16, x, 16); memset(t + 32, 0, 16); memcpy(x, t + MIN(k, 32), 16); } static void SsePsubw(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 8; ++i) { Write16(x + i * 2, Read16(x + i * 2) - Read16(y + i * 2)); } } static void SsePaddw(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 8; ++i) { Write16(x + i * 2, Read16(x + i * 2) + Read16(y + i * 2)); } } static void SsePsubd(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 4; ++i) { Write32(x + i * 4, Read32(x + i * 4) - Read32(y + i * 4)); } } static void SsePaddd(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 4; ++i) { Write32(x + i * 4, Read32(x + i * 4) + Read32(y + i * 4)); } } static void SsePaddq(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 2; ++i) { Write64(x + i * 8, Read64(x + i * 8) + Read64(y + i * 8)); } } static void SsePsubq(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 2; ++i) { Write64(x + i * 8, Read64(x + i * 8) - Read64(y + i * 8)); } } static void SsePaddusw(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 8; ++i) { Write16(x + i * 2, MIN(65535, Read16(x + i * 2) + Read16(y + i * 2))); } } static void SsePackuswb(uint8_t x[16], const uint8_t y[16]) { unsigned i; uint8_t t[16]; for (i = 0; i < 8; ++i) { t[i + 0] = MIN(255, MAX(0, (int16_t)Read16(x + i * 2))); } for (i = 0; i < 8; ++i) { t[i + 8] = MIN(255, MAX(0, (int16_t)Read16(y + i * 2))); } memcpy(x, t, 16); } static void SsePacksswb(uint8_t x[16], const uint8_t y[16]) { unsigned i; uint8_t t[16]; for (i = 0; i < 8; ++i) { t[i + 0] = MAX(-128, MIN(127, (int16_t)Read16(x + i * 2))); } for (i = 0; i < 8; ++i) { t[i + 8] = MAX(-128, MIN(127, (int16_t)Read16(y + i * 2))); } memcpy(x, t, 16); } static void SsePackssdw(uint8_t x[16], const uint8_t y[16]) { unsigned i; uint8_t t[16]; for (i = 0; i < 4; ++i) { Write16(t + i * 2 + 0, MAX(-32768, MIN(32767, (int32_t)Read32(x + i * 4)))); } for (i = 0; i < 4; ++i) { Write16(t + i * 2 + 8, MAX(-32768, MIN(32767, (int32_t)Read32(y + i * 4)))); } memcpy(x, t, 16); } static void SsePsadbw(uint8_t x[16], const uint8_t y[16]) { unsigned i, s, t; for (s = i = 0; i < 8; ++i) s += ABS(x[i] - y[i]); for (t = 0; i < 16; ++i) t += ABS(x[i] - y[i]); Write64(x + 0, s); Write64(x + 8, t); } static void SsePmuludq(uint8_t x[16], const uint8_t y[16]) { unsigned i; for (i = 0; i < 2; ++i) { Write64(x + i * 8, (uint64_t)Read32(x + i * 8) * Read32(y + i * 8)); } } static void SsePshufb(uint8_t x[16], const uint8_t y[16]) { unsigned i; uint8_t t[16]; for (i = 0; i < 16; ++i) { t[i] = (y[i] & 128) ? 0 : x[y[i] & 15]; } memcpy(x, t, 16); } static void SsePhaddd(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write32(t + 0 * 4, Read32(x + 0 * 4) + Read32(x + 1 * 4)); Write32(t + 1 * 4, Read32(x + 2 * 4) + Read32(x + 3 * 4)); Write32(t + 2 * 4, Read32(y + 0 * 4) + Read32(y + 1 * 4)); Write32(t + 3 * 4, Read32(y + 2 * 4) + Read32(y + 3 * 4)); memcpy(x, t, 16); } static void SsePhsubd(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write32(t + 0 * 4, Read32(x + 0 * 4) - Read32(x + 1 * 4)); Write32(t + 1 * 4, Read32(x + 2 * 4) - Read32(x + 3 * 4)); Write32(t + 2 * 4, Read32(y + 0 * 4) - Read32(y + 1 * 4)); Write32(t + 3 * 4, Read32(y + 2 * 4) - Read32(y + 3 * 4)); memcpy(x, t, 16); } static void SsePhaddw(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write16(t + 0 * 2, Read16(x + 0 * 2) + Read16(x + 1 * 2)); Write16(t + 1 * 2, Read16(x + 2 * 2) + Read16(x + 3 * 2)); Write16(t + 2 * 2, Read16(x + 4 * 2) + Read16(x + 5 * 2)); Write16(t + 3 * 2, Read16(x + 6 * 2) + Read16(x + 7 * 2)); Write16(t + 4 * 2, Read16(y + 0 * 2) + Read16(y + 1 * 2)); Write16(t + 5 * 2, Read16(y + 2 * 2) + Read16(y + 3 * 2)); Write16(t + 6 * 2, Read16(y + 4 * 2) + Read16(y + 5 * 2)); Write16(t + 7 * 2, Read16(y + 6 * 2) + Read16(y + 7 * 2)); memcpy(x, t, 16); } static void SsePhsubw(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write16(t + 0 * 2, Read16(x + 0 * 2) - Read16(x + 1 * 2)); Write16(t + 1 * 2, Read16(x + 2 * 2) - Read16(x + 3 * 2)); Write16(t + 2 * 2, Read16(x + 4 * 2) - Read16(x + 5 * 2)); Write16(t + 3 * 2, Read16(x + 6 * 2) - Read16(x + 7 * 2)); Write16(t + 4 * 2, Read16(y + 0 * 2) - Read16(y + 1 * 2)); Write16(t + 5 * 2, Read16(y + 2 * 2) - Read16(y + 3 * 2)); Write16(t + 6 * 2, Read16(y + 4 * 2) - Read16(y + 5 * 2)); Write16(t + 7 * 2, Read16(y + 6 * 2) - Read16(y + 7 * 2)); memcpy(x, t, 16); } static void SsePhaddsw(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write16(t + 0 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 0 * 2) + (int16_t)Read16(x + 1 * 2))))); Write16(t + 1 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 2 * 2) + (int16_t)Read16(x + 3 * 2))))); Write16(t + 2 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 4 * 2) + (int16_t)Read16(x + 5 * 2))))); Write16(t + 3 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 6 * 2) + (int16_t)Read16(x + 7 * 2))))); Write16(t + 4 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 0 * 2) + (int16_t)Read16(y + 1 * 2))))); Write16(t + 5 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 2 * 2) + (int16_t)Read16(y + 3 * 2))))); Write16(t + 6 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 4 * 2) + (int16_t)Read16(y + 5 * 2))))); Write16(t + 7 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 6 * 2) + (int16_t)Read16(y + 7 * 2))))); memcpy(x, t, 16); } static void SsePhsubsw(uint8_t x[16], const uint8_t y[16]) { uint8_t t[16]; Write16(t + 0 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 0 * 2) - (int16_t)Read16(x + 1 * 2))))); Write16(t + 1 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 2 * 2) - (int16_t)Read16(x + 3 * 2))))); Write16(t + 2 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 4 * 2) - (int16_t)Read16(x + 5 * 2))))); Write16(t + 3 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(x + 6 * 2) - (int16_t)Read16(x + 7 * 2))))); Write16(t + 4 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 0 * 2) - (int16_t)Read16(y + 1 * 2))))); Write16(t + 5 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 2 * 2) - (int16_t)Read16(y + 3 * 2))))); Write16(t + 6 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 4 * 2) - (int16_t)Read16(y + 5 * 2))))); Write16(t + 7 * 2, MAX(-32768, MIN(32767, ((int16_t)Read16(y + 6 * 2) - (int16_t)Read16(y + 7 * 2))))); memcpy(x, t, 16); } static void SsePunpcklbw(uint8_t x[16], const uint8_t y[16]) { x[0xf] = y[0x7]; x[0xe] = x[0x7]; x[0xd] = y[0x6]; x[0xc] = x[0x6]; x[0xb] = y[0x5]; x[0xa] = x[0x5]; x[0x9] = y[0x4]; x[0x8] = x[0x4]; x[0x7] = y[0x3]; x[0x6] = x[0x3]; x[0x5] = y[0x2]; x[0x4] = x[0x2]; x[0x3] = y[0x1]; x[0x2] = x[0x1]; x[0x1] = y[0x0]; x[0x0] = x[0x0]; } static void SsePunpckhbw(uint8_t x[16], const uint8_t y[16]) { x[0x0] = x[0x8]; x[0x1] = y[0x8]; x[0x2] = x[0x9]; x[0x3] = y[0x9]; x[0x4] = x[0xa]; x[0x5] = y[0xa]; x[0x6] = x[0xb]; x[0x7] = y[0xb]; x[0x8] = x[0xc]; x[0x9] = y[0xc]; x[0xa] = x[0xd]; x[0xb] = y[0xd]; x[0xc] = x[0xe]; x[0xd] = y[0xe]; x[0xe] = x[0xf]; x[0xf] = y[0xf]; } static void SsePunpcklwd(uint8_t x[16], const uint8_t y[16]) { x[0xe] = y[0x6]; x[0xf] = y[0x7]; x[0xc] = x[0x6]; x[0xd] = x[0x7]; x[0xa] = y[0x4]; x[0xb] = y[0x5]; x[0x8] = x[0x4]; x[0x9] = x[0x5]; x[0x6] = y[0x2]; x[0x7] = y[0x3]; x[0x4] = x[0x2]; x[0x5] = x[0x3]; x[0x2] = y[0x0]; x[0x3] = y[0x1]; x[0x0] = x[0x0]; x[0x1] = x[0x1]; } static void SsePunpckldq(uint8_t x[16], const uint8_t y[16]) { x[0xc] = y[0x4]; x[0xd] = y[0x5]; x[0xe] = y[0x6]; x[0xf] = y[0x7]; x[0x8] = x[0x4]; x[0x9] = x[0x5]; x[0xa] = x[0x6]; x[0xb] = x[0x7]; x[0x4] = y[0x0]; x[0x5] = y[0x1]; x[0x6] = y[0x2]; x[0x7] = y[0x3]; x[0x0] = x[0x0]; x[0x1] = x[0x1]; x[0x2] = x[0x2]; x[0x3] = x[0x3]; } static void SsePunpckhwd(uint8_t x[16], const uint8_t y[16]) { x[0x0] = x[0x8]; x[0x1] = x[0x9]; x[0x2] = y[0x8]; x[0x3] = y[0x9]; x[0x4] = x[0xa]; x[0x5] = x[0xb]; x[0x6] = y[0xa]; x[0x7] = y[0xb]; x[0x8] = x[0xc]; x[0x9] = x[0xd]; x[0xa] = y[0xc]; x[0xb] = y[0xd]; x[0xc] = x[0xe]; x[0xd] = x[0xf]; x[0xe] = y[0xe]; x[0xf] = y[0xf]; } static void SsePunpckhdq(uint8_t x[16], const uint8_t y[16]) { x[0x0] = x[0x8]; x[0x1] = x[0x9]; x[0x2] = x[0xa]; x[0x3] = x[0xb]; x[0x4] = y[0x8]; x[0x5] = y[0x9]; x[0x6] = y[0xa]; x[0x7] = y[0xb]; x[0x8] = x[0xc]; x[0x9] = x[0xd]; x[0xa] = x[0xe]; x[0xb] = x[0xf]; x[0xc] = y[0xc]; x[0xd] = y[0xd]; x[0xe] = y[0xe]; x[0xf] = y[0xf]; } static void SsePunpcklqdq(uint8_t x[16], const uint8_t y[16]) { x[0x8] = y[0x0]; x[0x9] = y[0x1]; x[0xa] = y[0x2]; x[0xb] = y[0x3]; x[0xc] = y[0x4]; x[0xd] = y[0x5]; x[0xe] = y[0x6]; x[0xf] = y[0x7]; x[0x0] = x[0x0]; x[0x1] = x[0x1]; x[0x2] = x[0x2]; x[0x3] = x[0x3]; x[0x4] = x[0x4]; x[0x5] = x[0x5]; x[0x6] = x[0x6]; x[0x7] = x[0x7]; } static void SsePunpckhqdq(uint8_t x[16], const uint8_t y[16]) { x[0x0] = x[0x8]; x[0x1] = x[0x9]; x[0x2] = x[0xa]; x[0x3] = x[0xb]; x[0x4] = x[0xc]; x[0x5] = x[0xd]; x[0x6] = x[0xe]; x[0x7] = x[0xf]; x[0x8] = y[0x8]; x[0x9] = y[0x9]; x[0xa] = y[0xa]; x[0xb] = y[0xb]; x[0xc] = y[0xc]; x[0xd] = y[0xd]; x[0xe] = y[0xe]; x[0xf] = y[0xf]; } static void SsePsrlw(uint8_t x[16], unsigned k) { MmxPsrlw(x + 0, k); MmxPsrlw(x + 8, k); } static void SsePsraw(uint8_t x[16], unsigned k) { MmxPsraw(x + 0, k); MmxPsraw(x + 8, k); } static void SsePsllw(uint8_t x[16], unsigned k) { MmxPsllw(x + 0, k); MmxPsllw(x + 8, k); } static void SsePsrld(uint8_t x[16], unsigned k) { MmxPsrld(x + 0, k); MmxPsrld(x + 8, k); } static void SsePsrad(uint8_t x[16], unsigned k) { MmxPsrad(x + 0, k); MmxPsrad(x + 8, k); } static void SsePslld(uint8_t x[16], unsigned k) { MmxPslld(x + 0, k); MmxPslld(x + 8, k); } static void SsePsrlq(uint8_t x[16], unsigned k) { MmxPsrlq(x + 0, k); MmxPsrlq(x + 8, k); } static void SsePsllq(uint8_t x[16], unsigned k) { MmxPsllq(x + 0, k); MmxPsllq(x + 8, k); } static void SsePsubsb(uint8_t x[16], const uint8_t y[16]) { MmxPsubsb(x + 0, y + 0); MmxPsubsb(x + 8, y + 8); } static void SsePaddsb(uint8_t x[16], const uint8_t y[16]) { MmxPaddsb(x + 0, y + 0); MmxPaddsb(x + 8, y + 8); } static void SsePsubsw(uint8_t x[16], const uint8_t y[16]) { MmxPsubsw(x + 0, y + 0); MmxPsubsw(x + 8, y + 8); } static void SsePaddsw(uint8_t x[16], const uint8_t y[16]) { MmxPaddsw(x + 0, y + 0); MmxPaddsw(x + 8, y + 8); } static void SsePaddusb(uint8_t x[16], const uint8_t y[16]) { MmxPaddusb(x + 0, y + 0); MmxPaddusb(x + 8, y + 8); } static void SsePsubusb(uint8_t x[16], const uint8_t y[16]) { MmxPsubusb(x + 0, y + 0); MmxPsubusb(x + 8, y + 8); } static void SsePsubusw(uint8_t x[16], const uint8_t y[16]) { MmxPsubusw(x + 0, y + 0); MmxPsubusw(x + 8, y + 8); } static void SsePminsw(uint8_t x[16], const uint8_t y[16]) { MmxPminsw(x + 0, y + 0); MmxPminsw(x + 8, y + 8); } static void SsePmaxsw(uint8_t x[16], const uint8_t y[16]) { MmxPmaxsw(x + 0, y + 0); MmxPmaxsw(x + 8, y + 8); } static void SsePsignb(uint8_t x[16], const uint8_t y[16]) { MmxPsignb(x + 0, y + 0); MmxPsignb(x + 8, y + 8); } static void SsePsignw(uint8_t x[16], const uint8_t y[16]) { MmxPsignw(x + 0, y + 0); MmxPsignw(x + 8, y + 8); } static void SsePsignd(uint8_t x[16], const uint8_t y[16]) { MmxPsignd(x + 0, y + 0); MmxPsignd(x + 8, y + 8); } static void SsePmulhrsw(uint8_t x[16], const uint8_t y[16]) { MmxPmulhrsw(x + 0, y + 0); MmxPmulhrsw(x + 8, y + 8); } static void SsePabsw(uint8_t x[16], const uint8_t y[16]) { MmxPabsw(x + 0, y + 0); MmxPabsw(x + 8, y + 8); } static void SsePabsd(uint8_t x[16], const uint8_t y[16]) { MmxPabsd(x + 0, y + 0); MmxPabsd(x + 8, y + 8); } static void SsePcmpgtw(uint8_t x[16], const uint8_t y[16]) { MmxPcmpgtw(x + 0, y + 0); MmxPcmpgtw(x + 8, y + 8); } static void SsePcmpeqw(uint8_t x[16], const uint8_t y[16]) { MmxPcmpeqw(x + 0, y + 0); MmxPcmpeqw(x + 8, y + 8); } static void SsePcmpgtd(uint8_t x[16], const uint8_t y[16]) { MmxPcmpgtd(x + 0, y + 0); MmxPcmpgtd(x + 8, y + 8); } static void SsePcmpeqd(uint8_t x[16], const uint8_t y[16]) { MmxPcmpeqd(x + 0, y + 0); MmxPcmpeqd(x + 8, y + 8); } static void SsePsrawv(uint8_t x[16], const uint8_t y[16]) { MmxPsrawv(x + 0, y); MmxPsrawv(x + 8, y); } static void SsePsradv(uint8_t x[16], const uint8_t y[16]) { MmxPsradv(x + 0, y); MmxPsradv(x + 8, y); } static void SsePsrlwv(uint8_t x[16], const uint8_t y[16]) { MmxPsrlwv(x + 0, y); MmxPsrlwv(x + 8, y); } static void SsePsllwv(uint8_t x[16], const uint8_t y[16]) { MmxPsllwv(x + 0, y); MmxPsllwv(x + 8, y); } static void SsePsrldv(uint8_t x[16], const uint8_t y[16]) { MmxPsrldv(x + 0, y); MmxPsrldv(x + 8, y); } static void SsePslldv(uint8_t x[16], const uint8_t y[16]) { MmxPslldv(x + 0, y); MmxPslldv(x + 8, y); } static void SsePsrlqv(uint8_t x[16], const uint8_t y[16]) { MmxPsrlqv(x + 0, y); MmxPsrlqv(x + 8, y); } static void SsePsllqv(uint8_t x[16], const uint8_t y[16]) { MmxPsllqv(x + 0, y); MmxPsllqv(x + 8, y); } static void SsePavgw(uint8_t x[16], const uint8_t y[16]) { MmxPavgw(x + 0, y + 0); MmxPavgw(x + 8, y + 8); } static void SsePmaddwd(uint8_t x[16], const uint8_t y[16]) { MmxPmaddwd(x + 0, y + 0); MmxPmaddwd(x + 8, y + 8); } static void SsePmulhuw(uint8_t x[16], const uint8_t y[16]) { MmxPmulhuw(x + 0, y + 0); MmxPmulhuw(x + 8, y + 8); } static void SsePmulhw(uint8_t x[16], const uint8_t y[16]) { MmxPmulhw(x + 0, y + 0); MmxPmulhw(x + 8, y + 8); } static void SsePmullw(uint8_t x[16], const uint8_t y[16]) { MmxPmullw(x + 0, y + 0); MmxPmullw(x + 8, y + 8); } static void SsePmulld(uint8_t x[16], const uint8_t y[16]) { MmxPmulld(x + 0, y + 0); MmxPmulld(x + 8, y + 8); } static void SsePmaddubsw(uint8_t x[16], const uint8_t y[16]) { MmxPmaddubsw(x + 0, y + 0); MmxPmaddubsw(x + 8, y + 8); } static void OpPsb(struct Machine *m, uint32_t rde, void MmxKernel(uint8_t[8], unsigned), void SseKernel(uint8_t[16], unsigned)) { if (Osz(rde)) { SseKernel(XmmRexbRm(m, rde), m->xedd->op.uimm0); } else { MmxKernel(XmmRexbRm(m, rde), m->xedd->op.uimm0); } } void Op171(struct Machine *m, uint32_t rde) { switch (ModrmReg(rde)) { case 2: OpPsb(m, rde, MmxPsrlw, SsePsrlw); break; case 4: OpPsb(m, rde, MmxPsraw, SsePsraw); break; case 6: OpPsb(m, rde, MmxPsllw, SsePsllw); break; default: OpUd(m, rde); } } void Op172(struct Machine *m, uint32_t rde) { switch (ModrmReg(rde)) { case 2: OpPsb(m, rde, MmxPsrld, SsePsrld); break; case 4: OpPsb(m, rde, MmxPsrad, SsePsrad); break; case 6: OpPsb(m, rde, MmxPslld, SsePslld); break; default: OpUd(m, rde); } } void Op173(struct Machine *m, uint32_t rde) { switch (ModrmReg(rde)) { case 2: OpPsb(m, rde, MmxPsrlq, SsePsrlq); break; case 3: OpPsb(m, rde, MmxPsrldq, SsePsrldq); break; case 6: OpPsb(m, rde, MmxPsllq, SsePsllq); break; case 7: OpPsb(m, rde, MmxPslldq, SsePslldq); break; default: OpUd(m, rde); } } void OpSsePalignr(struct Machine *m, uint32_t rde) { if (Osz(rde)) { SsePalignr(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead16(m, rde), m->xedd->op.uimm0); } else { MmxPalignr(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead8(m, rde), m->xedd->op.uimm0); } } static void OpSse(struct Machine *m, uint32_t rde, void MmxKernel(uint8_t[8], const uint8_t[8]), void SseKernel(uint8_t[16], const uint8_t[16])) { if (Osz(rde)) { SseKernel(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead16(m, rde)); } else { MmxKernel(XmmRexrReg(m, rde), GetModrmRegisterXmmPointerRead8(m, rde)); } } /* clang-format off */ void OpSsePunpcklbw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpcklbw, SsePunpcklbw); } void OpSsePunpcklwd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpcklwd, SsePunpcklwd); } void OpSsePunpckldq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpckldq, SsePunpckldq); } void OpSsePacksswb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPacksswb, SsePacksswb); } void OpSsePcmpgtb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpgtb, SsePcmpgtb); } void OpSsePcmpgtw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpgtw, SsePcmpgtw); } void OpSsePcmpgtd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpgtd, SsePcmpgtd); } void OpSsePackuswb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPackuswb, SsePackuswb); } void OpSsePunpckhbw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpckhbw, SsePunpckhbw); } void OpSsePunpckhwd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpckhwd, SsePunpckhwd); } void OpSsePunpckhdq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpckhdq, SsePunpckhdq); } void OpSsePackssdw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPackssdw, SsePackssdw); } void OpSsePunpcklqdq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpcklqdq, SsePunpcklqdq); } void OpSsePunpckhqdq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPunpckhqdq, SsePunpckhqdq); } void OpSsePcmpeqb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpeqb, SsePcmpeqb); } void OpSsePcmpeqw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpeqw, SsePcmpeqw); } void OpSsePcmpeqd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPcmpeqd, SsePcmpeqd); } void OpSsePsrlwv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsrlwv, SsePsrlwv); } void OpSsePsrldv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsrldv, SsePsrldv); } void OpSsePsrlqv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsrlqv, SsePsrlqv); } void OpSsePaddq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddq, SsePaddq); } void OpSsePmullw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmullw, SsePmullw); } void OpSsePsubusb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubusb, SsePsubusb); } void OpSsePsubusw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubusw, SsePsubusw); } void OpSsePminub(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPminub, SsePminub); } void OpSsePand(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPand, SsePand); } void OpSsePaddusb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddusb, SsePaddusb); } void OpSsePaddusw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddusw, SsePaddusw); } void OpSsePmaxub(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmaxub, SsePmaxub); } void OpSsePandn(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPandn, SsePandn); } void OpSsePavgb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPavgb, SsePavgb); } void OpSsePsrawv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsrawv, SsePsrawv); } void OpSsePsradv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsradv, SsePsradv); } void OpSsePavgw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPavgw, SsePavgw); } void OpSsePmulhuw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmulhuw, SsePmulhuw); } void OpSsePmulhw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmulhw, SsePmulhw); } void OpSsePsubsb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubsb, SsePsubsb); } void OpSsePsubsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubsw, SsePsubsw); } void OpSsePminsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPminsw, SsePminsw); } void OpSsePor(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPor, SsePor); } void OpSsePaddsb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddsb, SsePaddsb); } void OpSsePaddsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddsw, SsePaddsw); } void OpSsePmaxsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmaxsw, SsePmaxsw); } void OpSsePxor(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPxor, SsePxor); } void OpSsePsllwv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsllwv, SsePsllwv); } void OpSsePslldv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPslldv, SsePslldv); } void OpSsePsllqv(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsllqv, SsePsllqv); } void OpSsePmuludq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmuludq, SsePmuludq); } void OpSsePmaddwd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmaddwd, SsePmaddwd); } void OpSsePsadbw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsadbw, SsePsadbw); } void OpSsePsubb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubb, SsePsubb); } void OpSsePsubw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubw, SsePsubw); } void OpSsePsubd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubd, SsePsubd); } void OpSsePsubq(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsubq, SsePsubq); } void OpSsePaddb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddb, SsePaddb); } void OpSsePaddw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddw, SsePaddw); } void OpSsePaddd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPaddd, SsePaddd); } void OpSsePshufb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPshufb, SsePshufb); } void OpSsePhaddw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhaddw, SsePhaddw); } void OpSsePhaddd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhaddd, SsePhaddd); } void OpSsePhaddsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhaddsw, SsePhaddsw); } void OpSsePmaddubsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmaddubsw, SsePmaddubsw); } void OpSsePhsubw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhsubw, SsePhsubw); } void OpSsePhsubd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhsubd, SsePhsubd); } void OpSsePhsubsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPhsubsw, SsePhsubsw); } void OpSsePsignb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsignb, SsePsignb); } void OpSsePsignw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsignw, SsePsignw); } void OpSsePsignd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPsignd, SsePsignd); } void OpSsePmulhrsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmulhrsw, SsePmulhrsw); } void OpSsePabsb(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPabsb, SsePabsb); } void OpSsePabsw(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPabsw, SsePabsw); } void OpSsePabsd(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPabsd, SsePabsd); } void OpSsePmulld(struct Machine *m, uint32_t rde) { OpSse(m, rde, MmxPmulld, SsePmulld); } /* clang-format on */
44,973
1,576
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/machine.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_MACHINE_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_MACHINE_H_ #include "libc/runtime/runtime.h" #include "third_party/xed/x86.h" #include "tool/build/lib/bits.h" #include "tool/build/lib/fds.h" #define kMachineHalt -1 #define kMachineDecodeError -2 #define kMachineUndefinedInstruction -3 #define kMachineSegmentationFault -4 #define kMachineExit -5 #define kMachineDivideError -6 #define kMachineFpuException -7 #define kMachineProtectionFault -8 #define kMachineSimdException -9 #define kMachineOverflow -10 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Machine { struct XedDecodedInst *xedd; uint64_t ip; uint8_t cs[8]; uint8_t ss[8]; uint64_t codevirt; uint8_t *codehost; uint32_t mode; uint32_t flags; uint32_t tlbindex; uint32_t stashsize; int64_t stashaddr; int64_t readaddr; int64_t writeaddr; uint32_t readsize; uint32_t writesize; union { uint8_t reg[16][8]; struct { uint8_t ax[8]; uint8_t cx[8]; uint8_t dx[8]; uint8_t bx[8]; uint8_t sp[8]; uint8_t bp[8]; uint8_t si[8]; uint8_t di[8]; uint8_t r8[8]; uint8_t r9[8]; uint8_t r10[8]; uint8_t r11[8]; uint8_t r12[8]; uint8_t r13[8]; uint8_t r14[8]; uint8_t r15[8]; }; }; struct MachineTlb { int64_t virt; uint64_t entry; } tlb[16]; struct MachineReal { size_t i, n; uint8_t *p; } real; uint64_t cr3; uint8_t xmm[16][16]; uint8_t es[8]; uint8_t ds[8]; uint8_t fs[8]; uint8_t gs[8]; struct MachineFpu { long double st[8]; union { uint32_t cw; struct { unsigned im : 1; // invalid operation mask unsigned dm : 1; // denormal operand mask unsigned zm : 1; // zero divide mask unsigned om : 1; // overflow mask unsigned um : 1; // underflow mask unsigned pm : 1; // precision mask unsigned _p1 : 2; // reserved unsigned pc : 2; // precision: 32,∅,64,80 unsigned rc : 2; // rounding: even,→-∞,→+∞,→0 }; }; union { uint32_t sw; struct { unsigned ie : 1; // invalid operation unsigned de : 1; // denormalized operand unsigned ze : 1; // zero divide unsigned oe : 1; // overflow unsigned ue : 1; // underflow unsigned pe : 1; // precision unsigned sf : 1; // stack fault unsigned es : 1; // exception summary status unsigned c0 : 1; // condition 0 unsigned c1 : 1; // condition 1 unsigned c2 : 1; // condition 2 unsigned sp : 3; // top stack unsigned c3 : 1; // condition 3 unsigned bf : 1; // busy flag }; }; int tw; int op; int64_t ip; int64_t dp; } fpu; struct MachineSse { union { uint32_t mxcsr; struct { unsigned ie : 1; // invalid operation flag unsigned de : 1; // denormal flag unsigned ze : 1; // divide by zero flag unsigned oe : 1; // overflow flag unsigned ue : 1; // underflow flag unsigned pe : 1; // precision flag unsigned daz : 1; // denormals are zeros unsigned im : 1; // invalid operation mask unsigned dm : 1; // denormal mask unsigned zm : 1; // divide by zero mask unsigned om : 1; // overflow mask unsigned um : 1; // underflow mask unsigned pm : 1; // precision mask unsigned rc : 2; // rounding control unsigned ftz : 1; // flush to zero }; }; } sse; uint64_t cr0; uint64_t cr2; uint64_t cr4; uint64_t gdt_base; uint64_t idt_base; uint16_t gdt_limit; uint16_t idt_limit; uint32_t mxcsr; struct MachineRealFree { uint64_t i; uint64_t n; struct MachineRealFree *next; } * realfree; struct FreeList { uint32_t i; void *p[6]; } freelist; struct MachineMemstat { int freed; int resizes; int reserved; int committed; int allocated; int reclaimed; int pagetables; } memstat; int64_t brk; int64_t bofram[2]; jmp_buf onhalt; int64_t faultaddr; bool dlab; bool isfork; bool ismetal; struct MachineFds fds; uint8_t stash[4096]; uint8_t icache[1024][40]; void (*onbinbase)(struct Machine *); void (*onlongbranch)(struct Machine *); void (*redraw)(void); struct sigaction_bits sighand[28]; uint8_t sigmask[8]; int sig; uint64_t siguc; uint64_t sigfp; struct { int i, n; struct { int sig; int code; } p[64]; } signals; } forcealign(64); struct Machine *NewMachine(void) dontdiscard; void FreeMachine(struct Machine *); void ResetMem(struct Machine *); void ResetCpu(struct Machine *); void ResetTlb(struct Machine *); void ResetInstructionCache(struct Machine *); void LoadInstruction(struct Machine *); void ExecuteInstruction(struct Machine *); long AllocateLinearPage(struct Machine *); long AllocateLinearPageRaw(struct Machine *); int ReserveReal(struct Machine *, size_t); int ReserveVirtual(struct Machine *, int64_t, size_t, uint64_t); char *FormatPml4t(struct Machine *) dontdiscard; int64_t FindVirtual(struct Machine *, int64_t, size_t); int FreeVirtual(struct Machine *, int64_t, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_MACHINE_H_ */
5,525
207
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/time.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/timespec.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/sock/sock.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/poll.h" #include "libc/time/time.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/time.h" /** * @fileoverview i am the timelorde */ void OpPause(struct Machine *m, uint32_t rde) { struct pollfd pf; static bool once, interactive; if (!once) { interactive = isatty(0); once = true; } pf.fd = 0; pf.events = POLLIN; poll(&pf, 1, 20); /* make spin loops less brutal */ } void OpRdtsc(struct Machine *m, uint32_t rde) { uint64_t c; struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); c = ts.tv_sec * 1000000000 + ts.tv_nsec; Write64(m->ax, (c >> 000) & 0xffffffff); Write64(m->dx, (c >> 040) & 0xffffffff); } static int64_t GetTscAux(struct Machine *m) { uint32_t core, node; core = 0; node = 0; return (node & 0xfff) << 12 | (core & 0xfff); } void OpRdtscp(struct Machine *m, uint32_t rde) { OpRdtsc(m, rde); Write64(m->cx, GetTscAux(m)); } void OpRdpid(struct Machine *m, uint32_t rde) { Write64(RegRexbRm(m, rde), GetTscAux(m)); }
3,069
70
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/psk.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PSK_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PSK_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void *GetRunitPsk(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PSK_H_ */
288
11
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/errnos.S
/*-*- mode:asm; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│ │vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" .macro .e local:req linux:req .globl \local .long \local-kLinuxErrnos .byte \linux .endm // Lookup table translating errnos between systems. // // @see libc/sysv/systemfive.S .rodata .balign 4 kLinuxErrnos: .e EPERM,1 .e ENOENT,2 .e ESRCH,3 .e EINTR,4 .e EIO,5 .e ENXIO,6 .e E2BIG,7 .e ENOEXEC,8 .e EBADF,9 .e ECHILD,10 .e EAGAIN,11 .e ENOMEM,12 .e EACCES,13 .e EFAULT,14 .e ENOTBLK,15 .e EBUSY,16 .e EEXIST,17 .e EXDEV,18 .e ENODEV,19 .e ENOTDIR,20 .e EISDIR,21 .e EINVAL,22 .e ENFILE,23 .e EMFILE,24 .e ENOTTY,25 .e ETXTBSY,26 .e EFBIG,27 .e ENOSPC,28 .e ESPIPE,29 .e EROFS,30 .e EMLINK,31 .e EPIPE,32 .e EDOM,33 .e ERANGE,34 .e EDEADLK,35 .e ENAMETOOLONG,36 .e ENOLCK,37 .e ENOSYS,38 .e ENOTEMPTY,39 .e ELOOP,40 .e ENOMSG,42 .e EIDRM,43 .e EUSERS,87 .e ENOTSOCK,88 .e EDESTADDRREQ,89 .e EMSGSIZE,90 .e EPROTOTYPE,91 .e ENOPROTOOPT,92 .e EPROTONOSUPPORT,93 .e ESOCKTNOSUPPORT,94 .e EOPNOTSUPP,95 .e EPFNOSUPPORT,96 .e EAFNOSUPPORT,97 .e EADDRINUSE,98 .e EADDRNOTAVAIL,99 .e EL2NSYNC,45 .e EL3HLT,46 .e EL3RST,47 .e ELNRNG,48 .e ETIME,62 .e ENONET,64 .e EREMOTE,66 .e EPROTO,71 .e EBADMSG,74 .e EOVERFLOW,75 .e EILSEQ,84 .e ERESTART,85 .e ENETDOWN,100 .e ENETUNREACH,101 .e ENETRESET,102 .e ECONNABORTED,103 .e ECONNRESET,104 .e ENOBUFS,105 .e EISCONN,106 .e ENOTCONN,107 .e ESHUTDOWN,108 .e ETOOMANYREFS,109 .e ETIMEDOUT,110 .e ECONNREFUSED,111 .e EHOSTDOWN,112 .e EHOSTUNREACH,113 .e EALREADY,114 .e EINPROGRESS,115 .e ESTALE,116 .e EDQUOT,122 .e ECANCELED,125 .e EOWNERDEAD,130 .e ENOTRECOVERABLE,131 .long 0 .byte 0 .endobj kLinuxErrnos,globl
3,518
124
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/throw.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_THROW_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_THROW_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpUd(struct Machine *, uint32_t) wontreturn; void HaltMachine(struct Machine *, int) wontreturn; void ThrowDivideError(struct Machine *) wontreturn; void ThrowSegmentationFault(struct Machine *, int64_t) wontreturn; void ThrowProtectionFault(struct Machine *) wontreturn; void OpHlt(struct Machine *, uint32_t) wontreturn; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_THROW_H_ */
633
17
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stats.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_STATS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_STATS_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern unsigned long taken; extern unsigned long ntaken; extern unsigned long opcount; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_STATS_H_ */
356
13
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/memory.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/nt/struct/importobjectheader.internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/runtime/pc.internal.h" #include "libc/str/str.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/throw.h" void SetReadAddr(struct Machine *m, int64_t addr, uint32_t size) { if (size) { m->readaddr = addr; m->readsize = size; } } void SetWriteAddr(struct Machine *m, int64_t addr, uint32_t size) { if (size) { m->writeaddr = addr; m->writesize = size; } } uint64_t HandlePageFault(struct Machine *m, int64_t virt, uint64_t entry, uint64_t table, unsigned index) { long page; if ((page = AllocateLinearPage(m)) != -1) { --m->memstat.reserved; if (entry & PAGE_GROD) { ReserveVirtual(m, virt - 4096, 4096, PAGE_GROD | PAGE_RSRV | (entry & (PAGE_XD | PAGE_U | PAGE_RW | PAGE_V))); } return (*(uint64_t *)(m->real.p + table + index * 8) = page | entry & ~(PAGE_TA | PAGE_IGN1)); } else { return 0; } } uint64_t FindPage(struct Machine *m, int64_t virt) { uint64_t table, entry; unsigned level, index, i; virt &= -4096; for (i = 0; i < ARRAYLEN(m->tlb); ++i) { if (m->tlb[i].virt == virt && (m->tlb[i].entry & 1)) { return m->tlb[i].entry; } } level = 39; entry = m->cr3; do { table = entry & PAGE_TA; CHECK_LT(table, m->real.n); index = (virt >> level) & 511; entry = *(uint64_t *)(m->real.p + table + index * 8); if (!(entry & 1)) return 0; } while ((level -= 9) >= 12); if ((entry & PAGE_RSRV) && (entry = HandlePageFault(m, virt, entry, table, index)) == -1) { return 0; } m->tlbindex = (m->tlbindex + 1) & (ARRAYLEN(m->tlb) - 1); m->tlb[m->tlbindex] = m->tlb[0]; m->tlb[0].virt = virt; m->tlb[0].entry = entry; return entry; } void *FindReal(struct Machine *m, int64_t virt) { uint64_t table, entry, page; unsigned skew, level, index, i; if ((m->mode & 3) != XED_MODE_REAL) { if (IsLegalPointer(virt)) { if (!(entry = FindPage(m, virt))) return NULL; return m->real.p + (entry & PAGE_TA) + (virt & 0xfff); } else { return NULL; } } else if (0 <= virt && virt + 0xfff < m->real.n) { return m->real.p + virt; } else { return NULL; } } void *ResolveAddress(struct Machine *m, int64_t v) { void *r; if ((r = FindReal(m, v))) return r; ThrowSegmentationFault(m, v); } void VirtualSet(struct Machine *m, int64_t v, char c, uint64_t n) { char *p; uint64_t k; k = 4096 - (v & 0xfff); while (n) { k = MIN(k, n); p = ResolveAddress(m, v); memset(p, c, k); n -= k; v += k; k = 4096; } } void VirtualCopy(struct Machine *m, int64_t v, char *r, uint64_t n, bool d) { char *p; uint64_t k; k = 4096 - (v & 0xfff); while (n) { k = MIN(k, n); p = ResolveAddress(m, v); if (d) { memcpy(r, p, k); } else { memcpy(p, r, k); } n -= k; r += k; v += k; k = 4096; } } void *VirtualSend(struct Machine *m, void *dst, int64_t src, uint64_t n) { VirtualCopy(m, src, dst, n, true); return dst; } void VirtualSendRead(struct Machine *m, void *dst, int64_t addr, uint64_t n) { VirtualSend(m, dst, addr, n); SetReadAddr(m, addr, n); } void VirtualRecv(struct Machine *m, int64_t dst, void *src, uint64_t n) { VirtualCopy(m, dst, src, n, false); } void VirtualRecvWrite(struct Machine *m, int64_t addr, void *src, uint64_t n) { VirtualRecv(m, addr, src, n); SetWriteAddr(m, addr, n); } void *ReserveAddress(struct Machine *m, int64_t v, size_t n) { void *r; DCHECK_LE(n, sizeof(m->stash)); if ((v & 0xfff) + n <= 4096) return ResolveAddress(m, v); m->stashaddr = v; m->stashsize = n; r = m->stash; VirtualSend(m, r, v, n); return r; } void *AccessRam(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *tmp, bool copy) { unsigned k; uint8_t *a, *b; DCHECK_LE(n, 4096); if ((v & 0xfff) + n <= 4096) return ResolveAddress(m, v); k = 4096; k -= v & 0xfff; DCHECK_LE(k, 4096); a = ResolveAddress(m, v); b = ResolveAddress(m, v + k); if (copy) { memcpy(tmp, a, k); memcpy(tmp + k, b, n - k); } p[0] = a; p[1] = b; return tmp; } void *Load(struct Machine *m, int64_t v, size_t n, uint8_t *b) { void *p[2]; SetReadAddr(m, v, n); return AccessRam(m, v, n, p, b, true); } void *BeginStore(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *b) { SetWriteAddr(m, v, n); return AccessRam(m, v, n, p, b, false); } void *BeginStoreNp(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *b) { if (!v) return NULL; return BeginStore(m, v, n, p, b); } void *BeginLoadStore(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *b) { SetWriteAddr(m, v, n); return AccessRam(m, v, n, p, b, true); } void EndStore(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *b) { uint8_t *a; unsigned k; DCHECK_LE(n, 4096); if ((v & 0xfff) + n <= 4096) return; k = 4096; k -= v & 0xfff; DCHECK_GT(k, n); DCHECK_NOTNULL(p[0]); DCHECK_NOTNULL(p[1]); memcpy(p[0], b, k); memcpy(p[1], b + k, n - k); } void EndStoreNp(struct Machine *m, int64_t v, size_t n, void *p[2], uint8_t *b) { if (v) EndStore(m, v, n, p, b); } void *LoadStr(struct Machine *m, int64_t addr) { size_t have; char *copy, *page, *p; have = 4096 - (addr & 0xfff); if (!addr) return NULL; if (!(page = FindReal(m, addr))) return NULL; if ((p = memchr(page, '\0', have))) { SetReadAddr(m, addr, p - page + 1); return page; } CHECK_LT(m->freelist.i, ARRAYLEN(m->freelist.p)); if (!(copy = malloc(have + 4096))) return NULL; memcpy(copy, page, have); for (;;) { if (!(page = FindReal(m, addr + have))) break; if ((p = memccpy(copy + have, page, '\0', 4096))) { SetReadAddr(m, addr, have + (p - (copy + have)) + 1); return (m->freelist.p[m->freelist.i++] = copy); } have += 4096; if (!(p = realloc(copy, have + 4096))) break; copy = p; } free(copy); return NULL; } void *LoadBuf(struct Machine *m, int64_t addr, size_t size) { size_t have, need; char *buf, *copy, *page; have = 4096 - (addr & 0xfff); if (!addr) return NULL; if (!(buf = FindReal(m, addr))) return NULL; if (size > have) { CHECK_LT(m->freelist.i, ARRAYLEN(m->freelist.p)); if (!(copy = malloc(size))) return NULL; buf = memcpy(copy, buf, have); do { need = MIN(4096, size - have); if ((page = FindReal(m, addr + have))) { memcpy(copy + have, page, need); have += need; } else { free(copy); return NULL; } } while (have < size); } SetReadAddr(m, addr, size); return buf; }
8,783
289
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pml4t.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PML4T_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PML4T_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define IsValidPage(x) ((x)&1) #define MaskPageAddr(x) ((x)&0x00007ffffffff000) #define UnmaskPageAddr(x) SignExtendAddr(MaskPageAddr(x)) #define SignExtendAddr(x) ((int64_t)((uint64_t)(x) << 16) >> 16) struct ContiguousMemoryRanges { size_t i, n; struct ContiguousMemoryRange { int64_t a; int64_t b; } * p; }; void FindContiguousMemoryRanges(struct Machine *, struct ContiguousMemoryRanges *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PML4T_H_ */
753
26
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/breakpoint.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/assert.h" #include "libc/log/log.h" #include "tool/build/lib/breakpoint.h" void PopBreakpoint(struct Breakpoints *bps) { if (bps->i) { --bps->i; } } ssize_t PushBreakpoint(struct Breakpoints *bps, struct Breakpoint *b) { int i; for (i = 0; i < bps->i; ++i) { if (bps->p[i].disable) { memcpy(&bps->p[i], b, sizeof(*b)); return i; } } return APPEND(&bps->p, &bps->i, &bps->n, b); } ssize_t IsAtBreakpoint(struct Breakpoints *bps, int64_t addr) { size_t i; for (i = bps->i; i--;) { if (bps->p[i].disable) continue; if (bps->p[i].addr == addr) { if (bps->p[i].oneshot) { bps->p[i].disable = true; if (i == bps->i - 1) { --bps->i; } } return i; } } return -1; }
2,661
57
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/abp.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ABP_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ABP_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) #define Abp8(x) ((uint8_t *)__builtin_assume_aligned(x, 8)) #define Abp16(x) ((uint8_t *)__builtin_assume_aligned(x, 16)) #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ABP_H_ */
344
10
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/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 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/bing.internal.h" #include "libc/fmt/itoa.h" #include "libc/intrin/tpenc.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "third_party/xed/x86.h" #include "tool/build/lib/demangle.h" #include "tool/build/lib/dis.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/high.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #define ADDRLEN 8 #define BYTELEN 11 #define PFIXLEN 4 #define NAMELEN 8 #define CODELEN 40 #define CODELIM 15 #define DATALIM 8 #define PIVOTOP pos_opcode static char *DisColumn(char *p2, char *p1, long need) { char *p; unsigned long have; DCHECK_GE(p2, p1); have = p2 - p1; p = p2; do { *p++ = ' '; } while (++have < need); *p = '\0'; return p; } static char *DisOctets(char *p, const uint8_t *d, size_t n) { size_t i; for (i = 0; i < n; ++i) { if (i) *p++ = ','; *p++ = '0'; *p++ = 'x'; *p++ = "0123456789abcdef"[(d[i] & 0xf0) >> 4]; *p++ = "0123456789abcdef"[(d[i] & 0x0f) >> 0]; } *p = '\0'; return p; } static char *DisByte(char *p, const uint8_t *d, size_t n) { p = HighStart(p, g_high.keyword); p = DisColumn(stpcpy(p, ".byte"), p, NAMELEN); p = HighEnd(p); p = DisOctets(p, d, n); return p; } static char *DisError(struct Dis *d, char *p) { p = DisColumn(DisByte(p, d->xedd->bytes, MIN(15, d->xedd->length)), p, CODELEN); p = HighStart(p, g_high.comment); *p++ = '#'; *p++ = ' '; p = stpcpy(p, IndexDoubleNulString(kXedErrorNames, d->xedd->op.error)); p = HighEnd(p); *p = '\0'; return p; } static char *DisAddr(struct Dis *d, char *p) { int64_t x = d->addr; if (0 <= x && x < 0x10fff0) { return p + uint64toarray_fixed16(x, p, 24); } else if (INT_MIN <= x && x <= INT_MAX) { return p + uint64toarray_fixed16(x, p, 32); } else { return p + uint64toarray_fixed16(x, p, 48); } } static char *DisRaw(struct Dis *d, char *p) { long i; int plen; if (0 <= d->addr && d->addr < 0x10fff0) { plen = 2; } else { plen = PFIXLEN; } for (i = 0; i < plen - MIN(plen, d->xedd->op.PIVOTOP); ++i) { *p++ = ' '; *p++ = ' '; } for (i = 0; i < MIN(15, d->xedd->length); ++i) { if (i == d->xedd->op.PIVOTOP) *p++ = ' '; *p++ = "0123456789abcdef"[(d->xedd->bytes[i] & 0xf0) >> 4]; *p++ = "0123456789abcdef"[(d->xedd->bytes[i] & 0x0f) >> 0]; } *p = '\0'; return p; } static char *DisCode(struct Dis *d, char *p) { char optspecbuf[128]; if (!d->xedd->op.error) { return DisInst(d, p, DisSpec(d->xedd, optspecbuf)); } else { return DisError(d, p); } } static char *DisLineCode(struct Dis *d, char *p) { int blen, plen; if (0 <= d->addr && d->addr < 0x10fff0) { plen = 2; blen = 6; } else { blen = BYTELEN; plen = PFIXLEN; } p = DisColumn(DisAddr(d, p), p, ADDRLEN); p = DisColumn(DisRaw(d, p), p, plen * 2 + 1 + blen * 2); p = DisCode(d, p); return p; } static char *DisLineData(struct Dis *d, char *p, const uint8_t *b, size_t n) { size_t i; uint64_t w; p = DisColumn(DisAddr(d, p), p, ADDRLEN); p = DisColumn(DisByte(p, b, n), p, 64); p = HighStart(p, g_high.comment); *p++ = '#'; *p++ = ' '; for (i = 0; i < n; ++i) { w = _tpenc(bing(b[i], 0)); do { *p++ = w; } while ((w >>= 8)); } p = HighEnd(p); *p = '\0'; return p; } static char *DisLabel(struct Dis *d, char *p, const char *name) { p = DisColumn(DisAddr(d, p), p, ADDRLEN); p = HighStart(p, g_high.label); p = Demangle(p, name, DIS_MAX_SYMBOL_LENGTH); p = HighEnd(p); *p++ = ':'; *p = '\0'; return p; } long DisFind(struct Dis *d, int64_t addr) { int l, r, m, i; l = 0; r = d->ops.i - 1; while (l <= r) { m = (l + r) >> 1; if (d->ops.p[m].addr < addr) { l = m + 1; } else if (d->ops.p[m].addr > addr) { r = m - 1; } else { return m; } } return -1; } static long DisAppendOpLines(struct Dis *d, struct Machine *m, int64_t addr) { void *r; int64_t ip; unsigned k; struct DisOp op; long i, n, symbol; uint8_t *p, b[15]; n = 15; ip = addr - Read64(m->cs); if ((symbol = DisFindSym(d, ip)) != -1) { if (d->syms.p[symbol].addr <= ip && ip < d->syms.p[symbol].addr + d->syms.p[symbol].size) { n = d->syms.p[symbol].size - (ip - d->syms.p[symbol].addr); } if (ip == d->syms.p[symbol].addr && d->syms.p[symbol].name) { op.addr = addr; op.size = 0; op.active = true; d->addr = addr; DisLabel(d, d->buf, d->syms.stab + d->syms.p[symbol].name); if (!(op.s = strdup(d->buf))) return -1; APPEND(&d->ops.p, &d->ops.i, &d->ops.n, &op); } } n = MAX(1, MIN(15, n)); if (!(r = FindReal(m, addr))) return -1; k = 0x1000 - (addr & 0xfff); if (n <= k) { p = r; } else { p = b; memcpy(b, r, k); if ((r = FindReal(m, addr + k))) { memcpy(b + k, r, n - k); } else { n = k; } } xed_decoded_inst_zero_set_mode(d->xedd, m->mode); xed_instruction_length_decode(d->xedd, p, n); d->xedd->op.rde = EncodeRde(d->xedd); n = d->xedd->op.error ? 1 : d->xedd->length; op.addr = addr; op.size = n; op.active = true; op.s = NULL; APPEND(&d->ops.p, &d->ops.i, &d->ops.n, &op); return n; } long Dis(struct Dis *d, struct Machine *m, uint64_t addr, uint64_t ip, int lines) { int64_t i, j, symbol; DisFreeOps(&d->ops); if ((symbol = DisFindSym(d, addr)) != -1 && (d->syms.p[symbol].addr < addr && addr < d->syms.p[symbol].addr + d->syms.p[symbol].size)) { for (i = d->syms.p[symbol].addr; i < addr; i += j) { if ((j = DisAppendOpLines(d, m, i)) == -1) return -1; } } for (i = 0; i < lines; ++i, addr += j) { if ((j = DisAppendOpLines(d, m, addr)) == -1) return -1; } return 0; } const char *DisGetLine(struct Dis *d, struct Machine *m, size_t i) { void *r[2]; uint8_t b[15]; if (i >= d->ops.i) return ""; if (d->ops.p[i].s) return d->ops.p[i].s; DCHECK_LE(d->ops.p[i].size, 15); xed_decoded_inst_zero_set_mode(d->xedd, m->mode); xed_instruction_length_decode( d->xedd, AccessRam(m, d->ops.p[i].addr, d->ops.p[i].size, r, b, true), d->ops.p[i].size); d->xedd->op.rde = EncodeRde(d->xedd); d->m = m; d->addr = d->ops.p[i].addr; CHECK_LT(DisLineCode(d, d->buf) - d->buf, sizeof(d->buf)); return d->buf; } void DisFreeOp(struct DisOp *o) { free(o->s); } void DisFreeOps(struct DisOps *ops) { long i; for (i = 0; i < ops->i; ++i) { DisFreeOp(&ops->p[i]); } free(ops->p); bzero(ops, sizeof(*ops)); } void DisFree(struct Dis *d) { long i; DisFreeOps(&d->ops); free(d->edges.p); free(d->loads.p); free(d->syms.p); bzero(d, sizeof(*d)); }
8,662
297
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/memory.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_MEMORY_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_MEMORY_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int RegisterMemory(struct Machine *, int64_t, void *, size_t); uint64_t FindPage(struct Machine *, int64_t); void *AccessRam(struct Machine *, int64_t, size_t, void *[2], uint8_t *, bool); void *BeginLoadStore(struct Machine *, int64_t, size_t, void *[2], uint8_t *); void *BeginStore(struct Machine *, int64_t, size_t, void *[2], uint8_t *); void *BeginStoreNp(struct Machine *, int64_t, size_t, void *[2], uint8_t *); void *FindReal(struct Machine *, int64_t); void *Load(struct Machine *, int64_t, size_t, uint8_t *); void *LoadBuf(struct Machine *, int64_t, size_t); void *LoadStr(struct Machine *, int64_t); void *MallocPage(void); void *RealAddress(struct Machine *, int64_t); void *ReserveAddress(struct Machine *, int64_t, size_t); void *ResolveAddress(struct Machine *, int64_t); void *VirtualSend(struct Machine *, void *, int64_t, uint64_t); void EndStore(struct Machine *, int64_t, size_t, void *[2], uint8_t *); void EndStoreNp(struct Machine *, int64_t, size_t, void *[2], uint8_t *); void ResetRam(struct Machine *); void SetReadAddr(struct Machine *, int64_t, uint32_t); void SetWriteAddr(struct Machine *, int64_t, uint32_t); void VirtualRecv(struct Machine *, int64_t, void *, uint64_t); void VirtualRecvWrite(struct Machine *, int64_t, void *, uint64_t); void VirtualSendRead(struct Machine *, void *, int64_t, uint64_t); void VirtualSet(struct Machine *, int64_t, char, uint64_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_MEMORY_H_ */
1,709
35
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ssefloat.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/str/str.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/fpu.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/pun.h" #include "tool/build/lib/ssefloat.h" #include "tool/build/lib/throw.h" static void pshufw(int16_t b[4], const int16_t a[4], int m) { int16_t t[4]; t[0] = a[(m & 0003) >> 0]; t[1] = a[(m & 0014) >> 2]; t[2] = a[(m & 0060) >> 4]; t[3] = a[(m & 0300) >> 6]; b[0] = t[0]; b[1] = t[1]; b[2] = t[2]; b[3] = t[3]; } static void pshufd(int32_t b[4], const int32_t a[4], int m) { int32_t t[4]; t[0] = a[(m & 0003) >> 0]; t[1] = a[(m & 0014) >> 2]; t[2] = a[(m & 0060) >> 4]; t[3] = a[(m & 0300) >> 6]; b[0] = t[0]; b[1] = t[1]; b[2] = t[2]; b[3] = t[3]; } static void pshuflw(int16_t b[8], const int16_t a[8], int m) { int16_t t[4]; t[0] = a[(m & 0003) >> 0]; t[1] = a[(m & 0014) >> 2]; t[2] = a[(m & 0060) >> 4]; t[3] = a[(m & 0300) >> 6]; b[0] = t[0]; b[1] = t[1]; b[2] = t[2]; b[3] = t[3]; b[4] = a[4]; b[5] = a[5]; b[6] = a[6]; b[7] = a[7]; } static void pshufhw(int16_t b[8], const int16_t a[8], int m) { int16_t t[4]; t[0] = a[4 + ((m & 0003) >> 0)]; t[1] = a[4 + ((m & 0014) >> 2)]; t[2] = a[4 + ((m & 0060) >> 4)]; t[3] = a[4 + ((m & 0300) >> 6)]; b[0] = a[0]; b[1] = a[1]; b[2] = a[2]; b[3] = a[3]; b[4] = t[0]; b[5] = t[1]; b[6] = t[2]; b[7] = t[3]; } void OpUnpcklpsd(struct Machine *m, uint32_t rde) { uint8_t *a, *b; a = XmmRexrReg(m, rde); b = GetModrmRegisterXmmPointerRead8(m, rde); if (Osz(rde)) { memcpy(a + 8, b, 8); } else { memcpy(a + 4 * 3, b + 4, 4); memcpy(a + 4 * 2, a + 4, 4); memcpy(a + 4 * 1, b + 0, 4); } } void OpUnpckhpsd(struct Machine *m, uint32_t rde) { uint8_t *a, *b; a = XmmRexrReg(m, rde); b = GetModrmRegisterXmmPointerRead16(m, rde); if (Osz(rde)) { memcpy(a + 0, b + 8, 8); memcpy(a + 8, b + 8, 8); } else { memcpy(a + 4 * 0, a + 4 * 2, 4); memcpy(a + 4 * 1, b + 4 * 2, 4); memcpy(a + 4 * 2, a + 4 * 3, 4); memcpy(a + 4 * 3, b + 4 * 3, 4); } } void OpPextrwGdqpUdqIb(struct Machine *m, uint32_t rde) { uint8_t i; i = m->xedd->op.uimm0; i &= Osz(rde) ? 7 : 3; Write16(RegRexrReg(m, rde), Read16(XmmRexbRm(m, rde) + i * 2)); } void OpPinsrwVdqEwIb(struct Machine *m, uint32_t rde) { uint8_t i; i = m->xedd->op.uimm0; i &= Osz(rde) ? 7 : 3; Write16(XmmRexrReg(m, rde) + i * 2, Read16(GetModrmRegisterWordPointerRead2(m, rde))); } void OpShuffle(struct Machine *m, uint32_t rde) { int16_t q16[4]; int16_t x16[8]; int32_t x32[4]; switch (Rep(rde) | Osz(rde)) { case 0: memcpy(q16, GetModrmRegisterXmmPointerRead8(m, rde), 8); pshufw(q16, q16, m->xedd->op.uimm0); memcpy(XmmRexrReg(m, rde), q16, 8); break; case 1: memcpy(x32, GetModrmRegisterXmmPointerRead16(m, rde), 16); pshufd(x32, x32, m->xedd->op.uimm0); memcpy(XmmRexrReg(m, rde), x32, 16); break; case 2: memcpy(x16, GetModrmRegisterXmmPointerRead16(m, rde), 16); pshuflw(x16, x16, m->xedd->op.uimm0); memcpy(XmmRexrReg(m, rde), x16, 16); break; case 3: memcpy(x16, GetModrmRegisterXmmPointerRead16(m, rde), 16); pshufhw(x16, x16, m->xedd->op.uimm0); memcpy(XmmRexrReg(m, rde), x16, 16); break; default: for (;;) (void)0; } } static void Shufps(struct Machine *m, uint32_t rde) { uint8_t *p; union FloatPun x[4], y[4], z[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); z[0].f = y[(m->xedd->op.uimm0 & 0003) >> 0].f; z[1].f = y[(m->xedd->op.uimm0 & 0014) >> 2].f; z[2].f = x[(m->xedd->op.uimm0 & 0060) >> 4].f; z[3].f = x[(m->xedd->op.uimm0 & 0300) >> 6].f; Write32(p + 0 * 4, z[0].i); Write32(p + 1 * 4, z[1].i); Write32(p + 2 * 4, z[2].i); Write32(p + 3 * 4, z[3].i); } static void Shufpd(struct Machine *m, uint32_t rde) { uint8_t *p; union DoublePun x[2], y[2], z[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 4); y[1].i = Read64(p + 1 * 4); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 4); x[1].i = Read64(p + 1 * 4); z[0].f = y[(m->xedd->op.uimm0 & 0001) >> 0].f; z[1].f = x[(m->xedd->op.uimm0 & 0002) >> 1].f; Write64(p + 0 * 4, z[0].i); Write64(p + 1 * 4, z[1].i); } void OpShufpsd(struct Machine *m, uint32_t rde) { if (Osz(rde)) { Shufpd(m, rde); } else { Shufps(m, rde); } } void OpSqrtpsd(struct Machine *m, uint32_t rde) { switch (Rep(rde) | Osz(rde)) { case 0: { int i; uint8_t *p; union FloatPun u[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); u[0].i = Read32(p + 0 * 4); u[1].i = Read32(p + 1 * 4); u[2].i = Read32(p + 2 * 4); u[3].i = Read32(p + 3 * 4); for (i = 0; i < 4; ++i) u[i].f = sqrtf(u[i].f); p = XmmRexrReg(m, rde); Write32(p + 0 * 4, u[0].i); Write32(p + 1 * 4, u[1].i); Write32(p + 2 * 4, u[2].i); Write32(p + 3 * 4, u[3].i); break; } case 1: { int i; uint8_t *p; union DoublePun u[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); u[0].i = Read32(p + 0 * 8); u[1].i = Read32(p + 1 * 8); for (i = 0; i < 2; ++i) u[i].f = sqrt(u[i].f); p = XmmRexrReg(m, rde); Write32(p + 0 * 8, u[0].i); Write32(p + 1 * 8, u[1].i); break; } case 2: { union DoublePun u; u.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); u.f = sqrt(u.f); Write64(XmmRexrReg(m, rde), u.i); break; } case 3: { union FloatPun u; u.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); u.f = sqrtf(u.f); Write32(XmmRexrReg(m, rde), u.i); break; } default: for (;;) (void)0; } } void OpRsqrtps(struct Machine *m, uint32_t rde) { if (Rep(rde) != 3) { int i; uint8_t *p; union FloatPun u[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); u[0].i = Read32(p + 0 * 4); u[1].i = Read32(p + 1 * 4); u[2].i = Read32(p + 2 * 4); u[3].i = Read32(p + 3 * 4); for (i = 0; i < 4; ++i) u[i].f = 1.f / sqrtf(u[i].f); p = XmmRexrReg(m, rde); Write32(p + 0 * 4, u[0].i); Write32(p + 1 * 4, u[1].i); Write32(p + 2 * 4, u[2].i); Write32(p + 3 * 4, u[3].i); } else { union FloatPun u; u.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); u.f = 1.f / sqrtf(u.f); Write32(XmmRexrReg(m, rde), u.i); } } void OpRcpps(struct Machine *m, uint32_t rde) { if (Rep(rde) != 3) { int i; uint8_t *p; union FloatPun u[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); u[0].i = Read32(p + 0 * 4); u[1].i = Read32(p + 1 * 4); u[2].i = Read32(p + 2 * 4); u[3].i = Read32(p + 3 * 4); for (i = 0; i < 4; ++i) u[i].f = 1.f / u[i].f; p = XmmRexrReg(m, rde); Write32(p + 0 * 4, u[0].i); Write32(p + 1 * 4, u[1].i); Write32(p + 2 * 4, u[2].i); Write32(p + 3 * 4, u[3].i); } else { union FloatPun u; u.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); u.f = 1.f / u.f; Write32(XmmRexrReg(m, rde), u.i); } } void OpComissVsWs(struct Machine *m, uint32_t rde) { uint8_t zf, cf, pf, ie; if (!Osz(rde)) { union FloatPun xf, yf; xf.i = Read32(XmmRexrReg(m, rde)); yf.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); if (!isnan(xf.f) && !isnan(yf.f)) { zf = xf.f == yf.f; cf = xf.f < yf.f; pf = false; ie = false; } else { zf = cf = pf = ie = true; } } else { union DoublePun xd, yd; xd.i = Read64(XmmRexrReg(m, rde)); yd.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); if (!isnan(xd.f) && !isnan(yd.f)) { zf = xd.f == yd.f; cf = xd.f < yd.f; pf = false; ie = false; } else { zf = cf = pf = ie = true; } } m->flags = SetFlag(m->flags, FLAGS_ZF, zf); m->flags = SetFlag(m->flags, FLAGS_PF, pf); m->flags = SetFlag(m->flags, FLAGS_CF, cf); m->flags = SetFlag(m->flags, FLAGS_SF, false); m->flags = SetFlag(m->flags, FLAGS_OF, false); if (m->xedd->op.opcode & 1) { m->mxcsr &= ~kMxcsrIe; if (ie) { m->mxcsr |= kMxcsrIe; if (!(m->mxcsr & kMxcsrIm)) { HaltMachine(m, kMachineSimdException); } } } } static inline void OpPsd(struct Machine *m, uint32_t rde, float fs(float x, float y), double fd(double x, double y)) { if (Rep(rde) == 2) { union DoublePun x, y; y.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); x.i = Read64(XmmRexrReg(m, rde)); x.f = fd(x.f, y.f); Write64(XmmRexrReg(m, rde), x.i); } else if (Rep(rde) == 3) { union FloatPun x, y; y.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); x.i = Read32(XmmRexrReg(m, rde)); x.f = fs(x.f, y.f); Write32(XmmRexrReg(m, rde), x.i); } else if (Osz(rde)) { uint8_t *p; union DoublePun x[2], y[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 8); y[1].i = Read64(p + 1 * 8); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 8); x[1].i = Read64(p + 1 * 8); x[0].f = fd(x[0].f, y[0].f); x[1].f = fd(x[1].f, y[1].f); Write64(p + 0 * 8, x[0].i); Write64(p + 1 * 8, x[1].i); } else { uint8_t *p; union FloatPun x[4], y[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); x[0].f = fs(x[0].f, y[0].f); x[1].f = fs(x[1].f, y[1].f); x[2].f = fs(x[2].f, y[2].f); x[3].f = fs(x[3].f, y[3].f); Write32(p + 0 * 4, x[0].i); Write32(p + 1 * 4, x[1].i); Write32(p + 2 * 4, x[2].i); Write32(p + 3 * 4, x[3].i); } } static inline float Adds(float x, float y) { return x + y; } static inline double Addd(double x, double y) { return x + y; } void OpAddpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Adds, Addd); } static inline float Subs(float x, float y) { return x - y; } static inline double Subd(double x, double y) { return x - y; } void OpSubpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Subs, Subd); } static inline float Muls(float x, float y) { return x * y; } static inline double Muld(double x, double y) { return x * y; } void OpMulpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Muls, Muld); } static inline float Divs(float x, float y) { return x / y; } static inline double Divd(double x, double y) { return x / y; } void OpDivpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Divs, Divd); } static inline float Mins(float x, float y) { return MIN(x, y); } static inline double Mind(double x, double y) { return MIN(x, y); } void OpMinpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Mins, Mind); } static inline float Maxs(float x, float y) { return MAX(x, y); } static inline double Maxd(double x, double y) { return MAX(x, y); } void OpMaxpsd(struct Machine *m, uint32_t rde) { OpPsd(m, rde, Maxs, Maxd); } static int Cmps(int imm, float x, float y) { switch (imm) { case 0: return x == y ? -1 : 0; case 1: return x < y ? -1 : 0; case 2: return x <= y ? -1 : 0; case 3: return isnan(x) || isnan(y) ? -1 : 0; case 4: return x != y ? -1 : 0; case 5: return x >= y ? -1 : 0; case 6: return x > y ? -1 : 0; case 7: return !(isnan(x) || isnan(y)) ? -1 : 0; default: return 0; } } static int32_t Cmpd(int imm, double x, double y) { switch (imm) { case 0: return x == y ? -1 : 0; case 1: return x < y ? -1 : 0; case 2: return x <= y ? -1 : 0; case 3: return isnan(x) || isnan(y) ? -1 : 0; case 4: return x != y ? -1 : 0; case 5: return x >= y ? -1 : 0; case 6: return x > y ? -1 : 0; case 7: return !(isnan(x) || isnan(y)) ? -1 : 0; default: return 0; } } void OpCmppsd(struct Machine *m, uint32_t rde) { int imm = m->xedd->op.uimm0; if (Rep(rde) == 2) { union DoublePun x, y; y.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); x.i = Read64(XmmRexrReg(m, rde)); x.f = Cmpd(imm, x.f, y.f); Write64(XmmRexrReg(m, rde), x.i); } else if (Rep(rde) == 3) { union FloatPun x, y; y.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); x.i = Read32(XmmRexrReg(m, rde)); x.f = Cmps(imm, x.f, y.f); Write32(XmmRexrReg(m, rde), x.i); } else if (Osz(rde)) { uint8_t *p; union DoublePun x[2], y[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 8); y[1].i = Read64(p + 1 * 8); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 8); x[1].i = Read64(p + 1 * 8); x[0].f = Cmpd(imm, x[0].f, y[0].f); x[1].f = Cmpd(imm, x[1].f, y[1].f); Write64(p + 0 * 8, x[0].i); Write64(p + 1 * 8, x[1].i); } else { uint8_t *p; union FloatPun x[4], y[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); x[0].f = Cmps(imm, x[0].f, y[0].f); x[1].f = Cmps(imm, x[1].f, y[1].f); x[2].f = Cmps(imm, x[2].f, y[2].f); x[3].f = Cmps(imm, x[3].f, y[3].f); Write32(p + 0 * 4, x[0].i); Write32(p + 1 * 4, x[1].i); Write32(p + 2 * 4, x[2].i); Write32(p + 3 * 4, x[3].i); } } void OpAndpsd(struct Machine *m, uint32_t rde) { uint64_t x[2], y[2]; memcpy(x, XmmRexrReg(m, rde), 16); memcpy(y, GetModrmRegisterXmmPointerRead16(m, rde), 16); x[0] &= y[0]; x[1] &= y[1]; memcpy(XmmRexrReg(m, rde), x, 16); } void OpAndnpsd(struct Machine *m, uint32_t rde) { uint64_t x[2], y[2]; memcpy(x, XmmRexrReg(m, rde), 16); memcpy(y, GetModrmRegisterXmmPointerRead16(m, rde), 16); x[0] = ~x[0] & y[0]; x[1] = ~x[1] & y[1]; memcpy(XmmRexrReg(m, rde), x, 16); } void OpOrpsd(struct Machine *m, uint32_t rde) { uint64_t x[2], y[2]; memcpy(x, XmmRexrReg(m, rde), 16); memcpy(y, GetModrmRegisterXmmPointerRead16(m, rde), 16); x[0] |= y[0]; x[1] |= y[1]; memcpy(XmmRexrReg(m, rde), x, 16); } void OpXorpsd(struct Machine *m, uint32_t rde) { uint64_t x[2], y[2]; memcpy(x, XmmRexrReg(m, rde), 16); memcpy(y, GetModrmRegisterXmmPointerRead16(m, rde), 16); x[0] ^= y[0]; x[1] ^= y[1]; memcpy(XmmRexrReg(m, rde), x, 16); } void OpHaddpsd(struct Machine *m, uint32_t rde) { uint8_t *p; if (Rep(rde) == 2) { union FloatPun x[4], y[4], z[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); z[0].f = x[0].f + x[1].f; z[1].f = x[2].f + x[3].f; z[2].f = y[0].f + y[1].f; z[3].f = y[2].f + y[3].f; Write32(p + 0 * 4, z[0].i); Write32(p + 1 * 4, z[1].i); Write32(p + 2 * 4, z[2].i); Write32(p + 3 * 4, z[3].i); } else if (Osz(rde)) { union DoublePun x[2], y[2], z[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 8); y[1].i = Read64(p + 1 * 8); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 8); x[1].i = Read64(p + 1 * 8); z[0].f = x[0].f + x[1].f; z[1].f = y[0].f + y[1].f; Write64(p + 0 * 8, z[0].i); Write64(p + 1 * 8, z[1].i); } else { OpUd(m, rde); } } void OpHsubpsd(struct Machine *m, uint32_t rde) { uint8_t *p; if (Rep(rde) == 2) { union FloatPun x[4], y[4], z[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); z[0].f = x[0].f - x[1].f; z[1].f = x[2].f - x[3].f; z[2].f = y[0].f - y[1].f; z[3].f = y[2].f - y[3].f; Write32(p + 0 * 4, z[0].i); Write32(p + 1 * 4, z[1].i); Write32(p + 2 * 4, z[2].i); Write32(p + 3 * 4, z[3].i); } else if (Osz(rde)) { union DoublePun x[2], y[2], z[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 8); y[1].i = Read64(p + 1 * 8); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 8); x[1].i = Read64(p + 1 * 8); z[0].f = x[0].f - x[1].f; z[1].f = y[0].f - y[1].f; Write64(p + 0 * 8, z[0].i); Write64(p + 1 * 8, z[1].i); } else { OpUd(m, rde); } } void OpAddsubpsd(struct Machine *m, uint32_t rde) { uint8_t *p; if (Rep(rde) == 2) { union FloatPun x[4], y[4], z[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read32(p + 0 * 4); y[1].i = Read32(p + 1 * 4); y[2].i = Read32(p + 2 * 4); y[3].i = Read32(p + 3 * 4); p = XmmRexrReg(m, rde); x[0].i = Read32(p + 0 * 4); x[1].i = Read32(p + 1 * 4); x[2].i = Read32(p + 2 * 4); x[3].i = Read32(p + 3 * 4); z[0].f = x[0].f - y[0].f; z[1].f = x[1].f + y[1].f; z[2].f = x[2].f - y[2].f; z[3].f = x[3].f + y[3].f; Write32(p + 0 * 4, z[0].i); Write32(p + 1 * 4, z[1].i); Write32(p + 2 * 4, z[2].i); Write32(p + 3 * 4, z[3].i); } else if (Osz(rde)) { union DoublePun x[2], y[2], z[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); y[0].i = Read64(p + 0 * 8); y[1].i = Read64(p + 1 * 8); p = XmmRexrReg(m, rde); x[0].i = Read64(p + 0 * 8); x[1].i = Read64(p + 1 * 8); z[0].f = x[0].f - y[0].f; z[1].f = x[1].f + y[1].f; Write64(p + 0 * 8, z[0].i); Write64(p + 1 * 8, z[1].i); } else { OpUd(m, rde); } }
20,382
720
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/endian.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ENDIAN_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ENDIAN_H_ static inline uint8_t Read8(const uint8_t *p) { return p[0]; } static inline void Write8(uint8_t *p, uint8_t v) { *p = v; } static inline uint16_t Read16(const uint8_t *p) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint16_t v; __builtin_memcpy(&v, p, sizeof(v)); return v; #else return p[1] << 8 | p[0]; #endif } static inline void Write16(uint8_t *p, uint16_t v) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ __builtin_memcpy(p, &v, sizeof(v)); #else p[0] = (0x00FF & v) >> 000; p[1] = (0xFF00 & v) >> 010; #endif } static inline uint32_t Read32(const uint8_t *p) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint32_t v; __builtin_memcpy(&v, p, sizeof(v)); return v; #else return ((uint32_t)p[0] << 000 | (uint32_t)p[1] << 010 | (uint32_t)p[2] << 020 | (uint32_t)p[3] << 030); #endif } static inline void Write32(uint8_t *p, uint32_t v) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ __builtin_memcpy(p, &v, sizeof(v)); #else p[0] = (0x000000FF & v) >> 000; p[1] = (0x0000FF00 & v) >> 010; p[2] = (0x00FF0000 & v) >> 020; p[3] = (0xFF000000 & v) >> 030; #endif } static inline uint64_t Read64(const uint8_t *p) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ uint64_t v; __builtin_memcpy(&v, p, sizeof(v)); return v; #else return ((uint64_t)p[0] << 000 | (uint64_t)p[1] << 010 | (uint64_t)p[2] << 020 | (uint64_t)p[3] << 030 | (uint64_t)p[4] << 040 | (uint64_t)p[5] << 050 | (uint64_t)p[6] << 060 | (uint64_t)p[7] << 070); #endif } static inline void Write64(uint8_t *p, uint64_t v) { #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ __builtin_memcpy(p, &v, sizeof(v)); #else p[0] = (0x00000000000000FF & v) >> 000; p[1] = (0x000000000000FF00 & v) >> 010; p[2] = (0x0000000000FF0000 & v) >> 020; p[3] = (0x00000000FF000000 & v) >> 030; p[4] = (0x000000FF00000000 & v) >> 040; p[5] = (0x0000FF0000000000 & v) >> 050; p[6] = (0x00FF000000000000 & v) >> 060; p[7] = (0xFF00000000000000 & v) >> 070; #endif } #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ENDIAN_H_ */
2,168
82
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/elfwriter_cargoculting.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 "tool/build/lib/elfwriter.h" void elfwriter_cargoculting(struct ElfWriter *elf) { elfwriter_startsection(elf, "", SHT_NULL, 0); elfwriter_finishsection(elf); elfwriter_startsection(elf, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR); elfwriter_finishsection(elf); elfwriter_startsection(elf, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE); elfwriter_finishsection(elf); elfwriter_startsection(elf, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE); elfwriter_finishsection(elf); }
2,364
32
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stack.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_STACK_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_STACK_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void Push(struct Machine *, uint32_t, uint64_t); uint64_t Pop(struct Machine *, uint32_t, uint16_t); void OpCallJvds(struct Machine *, uint32_t); void OpRet(struct Machine *, uint32_t); void OpRetf(struct Machine *, uint32_t); void OpLeave(struct Machine *, uint32_t); void OpCallEq(struct Machine *, uint32_t); void OpPopEvq(struct Machine *, uint32_t); void OpPopZvq(struct Machine *, uint32_t); void OpPushZvq(struct Machine *, uint32_t); void OpPushEvq(struct Machine *, uint32_t); void PopVq(struct Machine *, uint32_t); void PushVq(struct Machine *, uint32_t); void OpJmpEq(struct Machine *, uint32_t); void OpPusha(struct Machine *, uint32_t); void OpPopa(struct Machine *, uint32_t); void OpCallf(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_STACK_H_ */
1,039
28
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/elfwriter_zip.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/dos.h" #include "libc/fmt/conv.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/mem/gc.h" #include "libc/nexgen32e/crc32.h" #include "libc/nt/enum/fileflagandattributes.h" #include "libc/stdio/rand.h" #include "libc/str/str.h" #include "libc/sysv/consts/s.h" #include "libc/time/struct/tm.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "libc/zip.h" #include "net/http/http.h" #include "third_party/zlib/zlib.h" #include "tool/build/lib/elfwriter.h" #define ZIP_LOCALFILE_SECTION ".zip.2." #define ZIP_DIRECTORY_SECTION ".zip.4." static bool ShouldCompress(const char *name, size_t namesize, const unsigned char *data, size_t datasize, bool nocompress) { return !nocompress && datasize >= 64 && !IsNoCompressExt(name, namesize) && (datasize < 1000 || MeasureEntropy((void *)data, 1000) < 7); } static void GetDosLocalTime(int64_t utcunixts, uint16_t *out_time, uint16_t *out_date) { struct tm tm; CHECK_NOTNULL(localtime_r(&utcunixts, &tm)); *out_time = DOS_TIME(tm.tm_hour, tm.tm_min, tm.tm_sec); *out_date = DOS_DATE(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday + 1); } static int DetermineVersionNeededToExtract(int method) { if (method == kZipCompressionDeflate) { return kZipEra1993; } else { return kZipEra1989; } } static unsigned char *EmitZipLfileHdr(unsigned char *p, const void *name, size_t namesize, uint32_t crc, uint8_t era, uint16_t gflags, uint16_t method, uint16_t mtime, uint16_t mdate, size_t compsize, size_t uncompsize) { p = WRITE32LE(p, kZipLfileHdrMagic); *p++ = era; *p++ = kZipOsDos; p = WRITE16LE(p, gflags); p = WRITE16LE(p, method); p = WRITE16LE(p, mtime); p = WRITE16LE(p, mdate); p = WRITE32LE(p, crc); p = WRITE32LE(p, compsize); p = WRITE32LE(p, uncompsize); p = WRITE16LE(p, namesize); p = WRITE16LE(p, 0); /* extra */ return mempcpy(p, name, namesize); } static void EmitZipCdirHdr(unsigned char *p, const void *name, size_t namesize, uint32_t crc, uint8_t era, uint16_t gflags, uint16_t method, uint16_t mtime, uint16_t mdate, uint16_t iattrs, uint16_t dosmode, uint16_t unixmode, size_t compsize, size_t uncompsize, size_t commentsize, struct timespec mtim, struct timespec atim, struct timespec ctim) { uint64_t mt, at, ct; p = WRITE32LE(p, kZipCfileHdrMagic); *p++ = kZipCosmopolitanVersion; *p++ = kZipOsUnix; *p++ = era; *p++ = kZipOsDos; p = WRITE16LE(p, gflags); p = WRITE16LE(p, method); p = WRITE16LE(p, mtime); p = WRITE16LE(p, mdate); /* 16 */ p = WRITE32LE(p, crc); p = WRITE32LE(p, compsize); p = WRITE32LE(p, uncompsize); p = WRITE16LE(p, namesize); #define CFILE_HDR_SIZE (kZipCfileHdrMinSize + 36) p = WRITE16LE(p, 36); /* extra size */ /* 32 */ p = WRITE16LE(p, commentsize); p = WRITE16LE(p, 0); /* disk */ p = WRITE16LE(p, iattrs); p = WRITE16LE(p, dosmode); p = WRITE16LE(p, unixmode); p = WRITE32LE(p, 0); /* RELOCATE ME (kZipCfileOffsetOffset) */ /* 46 */ memcpy(p, name, namesize); p += namesize; p = WRITE16LE(p, kZipExtraNtfs); p = WRITE16LE(p, 32); p = WRITE32LE(p, 0); p = WRITE16LE(p, 1); p = WRITE16LE(p, 24); mt = TimeSpecToWindowsTime(mtim); at = TimeSpecToWindowsTime(atim); ct = TimeSpecToWindowsTime(ctim); p = WRITE64LE(p, mt); p = WRITE64LE(p, at); p = WRITE64LE(p, ct); } /** * Embeds zip file in elf object. */ void elfwriter_zip(struct ElfWriter *elf, const char *symbol, const char *name, size_t namesize, const void *data, size_t size, uint32_t mode, struct timespec mtim, struct timespec atim, struct timespec ctim, bool nocompress, uint64_t imagebase, size_t kZipCdirHdrLinkableSizeBootstrap) { z_stream zs; uint8_t era; uint32_t crc; unsigned char *lfile, *cfile; struct ElfWriterSymRef lfilesym; size_t lfilehdrsize, uncompsize, compsize, commentsize; uint16_t method, gflags, mtime, mdate, iattrs, dosmode; CHECK_NE(0, mtim.tv_sec); gflags = 0; iattrs = 0; compsize = size; uncompsize = size; CHECK_LE(uncompsize, UINT32_MAX); lfilehdrsize = kZipLfileHdrMinSize + namesize; crc = crc32_z(0, data, uncompsize); GetDosLocalTime(mtim.tv_sec, &mtime, &mdate); if (_isutf8(name, namesize)) gflags |= kZipGflagUtf8; if (S_ISREG(mode) && _istext(data, size)) { iattrs |= kZipIattrText; } commentsize = kZipCdirHdrLinkableSizeBootstrap - (CFILE_HDR_SIZE + namesize); dosmode = !(mode & 0200) ? kNtFileAttributeReadonly : 0; method = ShouldCompress(name, namesize, data, size, nocompress) ? kZipCompressionDeflate : kZipCompressionNone; /* emit embedded file content w/ pkzip local file header */ elfwriter_align(elf, 1, 0); elfwriter_startsection(elf, _gc(xasprintf("%s%s", ZIP_LOCALFILE_SECTION, name)), SHT_PROGBITS, SHF_ALLOC); if (method == kZipCompressionDeflate) { CHECK_EQ(Z_OK, deflateInit2(memset(&zs, 0, sizeof(zs)), Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)); zs.next_in = data; zs.avail_in = uncompsize; zs.next_out = ((lfile = elfwriter_reserve( elf, (lfilehdrsize + (zs.avail_out = compressBound(uncompsize))))) + lfilehdrsize); CHECK_EQ(Z_STREAM_END, deflate(&zs, Z_FINISH)); CHECK_EQ(Z_OK, deflateEnd(&zs)); if (zs.total_out < uncompsize) { compsize = zs.total_out; } else { method = kZipCompressionNone; } } else { lfile = elfwriter_reserve(elf, lfilehdrsize + uncompsize); } if (method == kZipCompressionNone) { memcpy(lfile + lfilehdrsize, data, uncompsize); } era = method ? kZipEra1993 : kZipEra1989; EmitZipLfileHdr(lfile, name, namesize, crc, era, gflags, method, mtime, mdate, compsize, uncompsize); elfwriter_commit(elf, lfilehdrsize + compsize); lfilesym = elfwriter_appendsym( elf, _gc(xasprintf("%s%s", "zip+lfile:", name)), ELF64_ST_INFO(STB_LOCAL, STT_OBJECT), STV_DEFAULT, 0, lfilehdrsize); elfwriter_appendsym(elf, symbol, ELF64_ST_INFO(STB_GLOBAL, STT_OBJECT), STV_DEFAULT, lfilehdrsize, compsize); elfwriter_finishsection(elf); /* emit central directory record */ elfwriter_align(elf, 1, 0); elfwriter_startsection(elf, _gc(xasprintf("%s%s", ZIP_DIRECTORY_SECTION, name)), SHT_PROGBITS, SHF_ALLOC); EmitZipCdirHdr( (cfile = elfwriter_reserve(elf, kZipCdirHdrLinkableSizeBootstrap)), name, namesize, crc, era, gflags, method, mtime, mdate, iattrs, dosmode, mode, compsize, uncompsize, commentsize, mtim, atim, ctim); elfwriter_appendsym(elf, _gc(xasprintf("%s%s", "zip+cdir:", name)), ELF64_ST_INFO(STB_LOCAL, STT_OBJECT), STV_DEFAULT, 0, kZipCdirHdrLinkableSizeBootstrap); elfwriter_appendrela(elf, kZipCfileOffsetOffset, lfilesym, elfwriter_relatype_abs32(elf), -imagebase); elfwriter_commit(elf, kZipCdirHdrLinkableSizeBootstrap); elfwriter_finishsection(elf); }
9,512
223
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/xmmtype.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_XMMTYPE_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_XMMTYPE_H_ #include "tool/build/lib/machine.h" #define kXmmIntegral 0 #define kXmmDouble 1 #define kXmmFloat 2 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct XmmType { uint8_t type[16]; uint8_t size[16]; }; void UpdateXmmType(struct Machine *, struct XmmType *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_XMMTYPE_H_ */
499
22
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ioports.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_IOPORTS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_IOPORTS_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ uint64_t OpIn(struct Machine *, uint16_t); void OpOut(struct Machine *, uint16_t, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_IOPORTS_H_ */
404
13
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/breg.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/lib/modrm.h" /** * Byte register offsets. * * for (i = 0; i < 2; ++i) { // rex * for (j = 0; j < 2; ++j) { // rexb, or rexr * for (k = 0; k < 8; ++k) { // reg, rm, or srm * kByteReg[i << 4 | j << 3 | k] = * i ? (j << 3 | k) * 8 : (k & 0b11) * 8 + ((k & 0b100) >> 2); * } * } * } */ const uint8_t kByteReg[32] = {0x00, 0x08, 0x10, 0x18, 0x01, 0x09, 0x11, 0x19, 0x00, 0x08, 0x10, 0x18, 0x01, 0x09, 0x11, 0x19, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78};
2,501
37
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cga.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_CGA_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_CGA_H_ #include "tool/build/lib/panel.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void DrawCga(struct Panel *, uint8_t[25][80][2]); size_t FormatCga(uint8_t, char[hasatleast 11]); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_CGA_H_ */
395
13
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/psk.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/log/check.h" #include "libc/mem/mem.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/o.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "tool/build/lib/psk.h" /** * Returns preshared key for runit testing infrastructure. */ void *GetRunitPsk(void) { int fd; char *r, *p; struct stat st; p = _gc(xasprintf("%s/.runit.psk", _gc(xhomedir()))); if (stat(p, &st) == -1 || st.st_size != 32) { fprintf(stderr, "need o//examples/getrandom.com -bn32 >~/.runit.psk\n"); exit(1); } CHECK_NOTNULL((r = malloc(32))); CHECK_NE(-1, (fd = open(p, O_RDONLY))); CHECK_EQ(32, read(fd, r, 32)); CHECK_NE(-1, close(fd)); return r; }
2,647
49
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/argv.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ARGV_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ARGV_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void LoadArgv(struct Machine *, const char *, char **, char **); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ARGV_H_ */
367
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/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/errno.h" #include "libc/str/str.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/ip.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/lock.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/msync.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/rusage.h" #include "libc/sysv/consts/sicode.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/sysv/consts/termios.h" #include "libc/sysv/consts/w.h" #include "libc/sysv/errfuns.h" #include "tool/build/lib/case.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/xlat.h" #define XLAT(x, y) CASE(x, return y) int XlatSignal(int x) { switch (x) { XLAT(1, SIGHUP); XLAT(2, SIGINT); XLAT(3, SIGQUIT); XLAT(4, SIGILL); XLAT(5, SIGTRAP); XLAT(6, SIGABRT); XLAT(7, SIGBUS); XLAT(8, SIGFPE); XLAT(9, SIGKILL); XLAT(10, SIGUSR1); XLAT(11, SIGSEGV); XLAT(12, SIGUSR2); XLAT(13, SIGPIPE); XLAT(14, SIGALRM); XLAT(15, SIGTERM); XLAT(17, SIGCHLD); XLAT(18, SIGCONT); XLAT(21, SIGTTIN); XLAT(22, SIGTTOU); XLAT(24, SIGXCPU); XLAT(25, SIGXFSZ); XLAT(26, SIGVTALRM); XLAT(27, SIGPROF); XLAT(28, SIGWINCH); XLAT(29, SIGIO); XLAT(19, SIGSTOP); XLAT(31, SIGSYS); XLAT(20, SIGTSTP); XLAT(23, SIGURG); default: return einval(); } } int UnXlatSignal(int x) { if (x == SIGHUP) return 1; if (x == SIGINT) return 2; if (x == SIGQUIT) return 3; if (x == SIGILL) return 4; if (x == SIGTRAP) return 5; if (x == SIGABRT) return 6; if (x == SIGBUS) return 7; if (x == SIGFPE) return 8; if (x == SIGKILL) return 9; if (x == SIGUSR1) return 10; if (x == SIGSEGV) return 11; if (x == SIGUSR2) return 12; if (x == SIGPIPE) return 13; if (x == SIGALRM) return 14; if (x == SIGTERM) return 15; if (x == SIGCHLD) return 17; if (x == SIGCONT) return 18; if (x == SIGTTIN) return 21; if (x == SIGTTOU) return 22; if (x == SIGXCPU) return 24; if (x == SIGXFSZ) return 25; if (x == SIGVTALRM) return 26; if (x == SIGPROF) return 27; if (x == SIGWINCH) return 28; if (x == SIGIO) return 29; if (x == SIGSTOP) return 19; if (x == SIGSYS) return 31; if (x == SIGTSTP) return 20; if (x == SIGURG) return 23; return 15; } int UnXlatSicode(int sig, int code) { if (code == SI_USER) return 0; if (code == SI_QUEUE) return -1; if (code == SI_TIMER) return -2; if (code == SI_TKILL) return -6; if (code == SI_MESGQ) return -3; if (code == SI_ASYNCIO) return -4; if (code == SI_ASYNCNL) return -60; if (code == SI_KERNEL) return 0x80; if (sig == SIGCHLD) { if (code == CLD_EXITED) return 1; if (code == CLD_KILLED) return 2; if (code == CLD_DUMPED) return 3; if (code == CLD_TRAPPED) return 4; if (code == CLD_STOPPED) return 5; if (code == CLD_CONTINUED) return 6; return -1; } if (sig == SIGTRAP) { if (code == TRAP_BRKPT) return 1; if (code == TRAP_TRACE) return 2; return -1; } if (sig == SIGSEGV) { if (code == SEGV_MAPERR) return 1; if (code == SEGV_ACCERR) return 2; return -1; } if (sig == SIGFPE) { if (code == FPE_INTDIV) return 1; if (code == FPE_INTOVF) return 2; if (code == FPE_FLTDIV) return 3; if (code == FPE_FLTOVF) return 4; if (code == FPE_FLTUND) return 5; if (code == FPE_FLTRES) return 6; if (code == FPE_FLTINV) return 7; if (code == FPE_FLTSUB) return 8; return -1; } if (sig == SIGILL) { if (code == ILL_ILLOPC) return 1; if (code == ILL_ILLOPN) return 2; if (code == ILL_ILLADR) return 3; if (code == ILL_ILLTRP) return 4; if (code == ILL_PRVOPC) return 5; if (code == ILL_PRVREG) return 6; if (code == ILL_COPROC) return 7; if (code == ILL_BADSTK) return 8; return -1; } if (sig == SIGBUS) { if (code == BUS_ADRALN) return 1; if (code == BUS_ADRERR) return 2; if (code == BUS_OBJERR) return 3; if (code == BUS_MCEERR_AR) return 4; if (code == BUS_MCEERR_AO) return 5; return -1; } if (sig == SIGIO) { if (code == POLL_IN) return 1; if (code == POLL_OUT) return 2; if (code == POLL_MSG) return 3; if (code == POLL_ERR) return 4; if (code == POLL_PRI) return 5; if (code == POLL_HUP) return 6; return -1; } return -1; } int XlatSig(int x) { switch (x) { XLAT(0, SIG_BLOCK); XLAT(1, SIG_UNBLOCK); XLAT(2, SIG_SETMASK); default: return einval(); } } int XlatRusage(int x) { switch (x) { XLAT(0, RUSAGE_SELF); XLAT(-1, RUSAGE_CHILDREN); XLAT(1, RUSAGE_THREAD); default: return einval(); } } int XlatSocketFamily(int x) { switch (x) { XLAT(0, AF_UNSPEC); XLAT(1, AF_UNIX); XLAT(2, AF_INET); default: errno = EPFNOSUPPORT; return -1; } } int UnXlatSocketFamily(int x) { switch (x) { XLAT(AF_UNSPEC, 0); XLAT(AF_UNIX, 1); XLAT(AF_INET, 2); default: return x; } } int XlatSocketType(int x) { switch (x) { XLAT(1, SOCK_STREAM); XLAT(2, SOCK_DGRAM); default: return einval(); } } int XlatSocketFlags(int flags) { unsigned res = 0; if (flags & 0x080000) res |= SOCK_CLOEXEC; if (flags & 0x000800) res |= SOCK_NONBLOCK; return res; } int XlatSocketProtocol(int x) { switch (x) { XLAT(0, 0); XLAT(6, IPPROTO_TCP); XLAT(17, IPPROTO_UDP); default: return einval(); } } int XlatSocketLevel(int level) { switch (level) { XLAT(0, SOL_IP); XLAT(1, SOL_SOCKET); XLAT(6, SOL_TCP); XLAT(17, SOL_UDP); default: return einval(); } } int XlatSocketOptname(int level, int optname) { if (level == SOL_SOCKET) { switch (optname) { XLAT(1, SO_DEBUG); XLAT(2, SO_REUSEADDR); XLAT(3, SO_TYPE); XLAT(4, SO_ERROR); XLAT(5, SO_DONTROUTE); XLAT(6, SO_BROADCAST); XLAT(7, SO_SNDBUF); XLAT(8, SO_RCVBUF); XLAT(9, SO_KEEPALIVE); XLAT(13, SO_LINGER); XLAT(15, SO_REUSEPORT); XLAT(18, SO_RCVLOWAT); XLAT(19, SO_SNDLOWAT); XLAT(30, SO_ACCEPTCONN); default: return einval(); } } if (level == SOL_TCP) { switch (optname) { XLAT(1, TCP_NODELAY); XLAT(2, TCP_MAXSEG); #if defined(TCP_CORK) XLAT(3, TCP_CORK); #elif defined(TCP_NOPUSH) XLAT(3, TCP_NOPUSH); #endif #ifdef TCP_KEEPIDLE XLAT(4, TCP_KEEPIDLE); #endif #ifdef TCP_KEEPINTVL XLAT(5, TCP_KEEPINTVL); #endif #ifdef TCP_KEEPCNT XLAT(6, TCP_KEEPCNT); #endif #ifdef TCP_SYNCNT XLAT(7, TCP_SYNCNT); #endif #ifdef TCP_WINDOW_CLAMP XLAT(10, TCP_WINDOW_CLAMP); #endif #ifdef TCP_FASTOPEN XLAT(23, TCP_FASTOPEN); #endif #ifdef TCP_QUICKACK XLAT(12, TCP_QUICKACK); #endif #ifdef TCP_NOTSENT_LOWAT XLAT(25, TCP_NOTSENT_LOWAT); #endif #ifdef TCP_SAVE_SYN XLAT(27, TCP_SAVE_SYN); #endif #ifdef TCP_FASTOPEN_CONNECT XLAT(30, TCP_FASTOPEN_CONNECT); #endif default: return einval(); } } if (level == SOL_IP) { switch (optname) { XLAT(1, IP_TOS); XLAT(2, IP_TTL); XLAT(3, IP_HDRINCL); XLAT(14, IP_MTU); default: return einval(); } } return einval(); } int XlatAccess(int x) { int r = F_OK; if (x & 1) r |= X_OK; if (x & 2) r |= W_OK; if (x & 4) r |= R_OK; return r; } int XlatLock(int x) { int r = 0; if (x & 1) r |= LOCK_SH; if (x & 2) r |= LOCK_EX; if (x & 4) r |= LOCK_NB; if (x & 8) r |= LOCK_UN; return r; } int XlatWait(int x) { int r = 0; if (x & 1) r |= WNOHANG; if (x & 2) r |= WUNTRACED; if (x & 8) r |= WCONTINUED; return r; } int XlatMapFlags(int x) { int r = 0; if (x & 1) r |= MAP_SHARED; if (x & 2) r |= MAP_PRIVATE; if (x & 16) r |= MAP_FIXED; if (x & 32) r |= MAP_ANONYMOUS; return r; } int XlatMsyncFlags(int x) { unsigned res = 0; if (x & 1) res |= MS_ASYNC; if (x & 2) res |= MS_INVALIDATE; if (x & 4) res |= MS_SYNC; return res; } int XlatClock(int x) { switch (x) { XLAT(0, CLOCK_REALTIME); XLAT(1, CLOCK_MONOTONIC); XLAT(2, CLOCK_PROCESS_CPUTIME_ID); #ifdef CLOCK_MONOTONIC_RAW XLAT(4, CLOCK_MONOTONIC_RAW); #endif default: return x; } } int XlatAtf(int x) { int res = 0; if (x & 0x0100) res |= AT_SYMLINK_NOFOLLOW; if (x & 0x0200) res |= AT_REMOVEDIR; if (x & 0x0400) res |= AT_SYMLINK_FOLLOW; if (x & 0x1000) res |= AT_EMPTY_PATH; return res; } int XlatOpenMode(int flags) { switch (flags & 3) { case 0: return O_RDONLY; case 1: return O_WRONLY; case 2: return O_RDWR; default: for (;;) (void)0; } } int XlatOpenFlags(int flags) { int res; res = XlatOpenMode(flags); if (flags & 0x00400) res |= O_APPEND; if (flags & 0x00040) res |= O_CREAT; if (flags & 0x00080) res |= O_EXCL; if (flags & 0x00200) res |= O_TRUNC; if (flags & 0x00800) res |= O_NDELAY; if (flags & 0x04000) res |= O_DIRECT; if (flags & 0x10000) res |= O_DIRECTORY; if (flags & 0x20000) res |= O_NOFOLLOW; if (flags & 0x80000) res |= O_CLOEXEC; if (flags & 0x00100) res |= O_NOCTTY; #ifdef O_ASYNC if (flags & 0x02000) res |= O_ASYNC; #endif #ifdef O_NOATIME if (flags & 0x40000) res |= O_NOATIME; #endif #ifdef O_DSYNC if (flags & 0x000001000) res |= O_DSYNC; #endif #ifdef O_SYNC if ((flags & 0x00101000) == 0x00101000) res |= O_SYNC; #endif return res; } int XlatFcntlCmd(int x) { switch (x) { XLAT(1, F_GETFD); XLAT(2, F_SETFD); XLAT(3, F_GETFL); XLAT(4, F_SETFL); default: return einval(); } } int XlatFcntlArg(int x) { switch (x) { XLAT(0, 0); XLAT(1, FD_CLOEXEC); XLAT(0x0800, O_NONBLOCK); default: return einval(); } } int XlatAdvice(int x) { switch (x) { XLAT(0, MADV_NORMAL); XLAT(1, MADV_RANDOM); XLAT(2, MADV_SEQUENTIAL); XLAT(3, MADV_WILLNEED); XLAT(4, MADV_DONTNEED); XLAT(8, MADV_FREE); XLAT(12, MADV_MERGEABLE); default: return einval(); } } void XlatSockaddrToHost(struct sockaddr_in *dst, const struct sockaddr_in_bits *src) { memset(dst, 0, sizeof(*dst)); dst->sin_family = XlatSocketFamily(Read16(src->sin_family)); dst->sin_port = src->sin_port; dst->sin_addr.s_addr = src->sin_addr; } void XlatSockaddrToLinux(struct sockaddr_in_bits *dst, const struct sockaddr_in *src) { memset(dst, 0, sizeof(*dst)); Write16(dst->sin_family, UnXlatSocketFamily(src->sin_family)); dst->sin_port = src->sin_port; dst->sin_addr = src->sin_addr.s_addr; } void XlatStatToLinux(struct stat_bits *dst, const struct stat *src) { Write64(dst->st_dev, src->st_dev); Write64(dst->st_ino, src->st_ino); Write64(dst->st_nlink, src->st_nlink); Write32(dst->st_mode, src->st_mode); Write32(dst->st_uid, src->st_uid); Write32(dst->st_gid, src->st_gid); Write32(dst->__pad, 0); Write64(dst->st_rdev, src->st_rdev); Write64(dst->st_size, src->st_size); Write64(dst->st_blksize, src->st_blksize); Write64(dst->st_blocks, src->st_blocks); Write64(dst->st_dev, src->st_dev); Write64(dst->st_atim.tv_sec, src->st_atim.tv_sec); Write64(dst->st_atim.tv_nsec, src->st_atim.tv_nsec); Write64(dst->st_mtim.tv_sec, src->st_mtim.tv_sec); Write64(dst->st_mtim.tv_nsec, src->st_mtim.tv_nsec); Write64(dst->st_ctim.tv_sec, src->st_ctim.tv_sec); Write64(dst->st_ctim.tv_nsec, src->st_ctim.tv_nsec); } void XlatRusageToLinux(struct rusage_bits *dst, const struct rusage *src) { Write64(dst->ru_utime.tv_sec, src->ru_utime.tv_sec); Write64(dst->ru_utime.tv_usec, src->ru_utime.tv_usec); Write64(dst->ru_stime.tv_sec, src->ru_stime.tv_sec); Write64(dst->ru_stime.tv_usec, src->ru_stime.tv_usec); Write64(dst->ru_maxrss, src->ru_maxrss); Write64(dst->ru_ixrss, src->ru_ixrss); Write64(dst->ru_idrss, src->ru_idrss); Write64(dst->ru_isrss, src->ru_isrss); Write64(dst->ru_minflt, src->ru_minflt); Write64(dst->ru_majflt, src->ru_majflt); Write64(dst->ru_nswap, src->ru_nswap); Write64(dst->ru_inblock, src->ru_inblock); Write64(dst->ru_oublock, src->ru_oublock); Write64(dst->ru_msgsnd, src->ru_msgsnd); Write64(dst->ru_msgrcv, src->ru_msgrcv); Write64(dst->ru_nsignals, src->ru_nsignals); Write64(dst->ru_nvcsw, src->ru_nvcsw); Write64(dst->ru_nivcsw, src->ru_nivcsw); } void XlatItimervalToLinux(struct itimerval_bits *dst, const struct itimerval *src) { Write64(dst->it_interval.tv_sec, src->it_interval.tv_sec); Write64(dst->it_interval.tv_usec, src->it_interval.tv_usec); Write64(dst->it_value.tv_sec, src->it_value.tv_sec); Write64(dst->it_value.tv_usec, src->it_value.tv_usec); } void XlatLinuxToItimerval(struct itimerval *dst, const struct itimerval_bits *src) { dst->it_interval.tv_sec = Read64(src->it_interval.tv_sec); dst->it_interval.tv_usec = Read64(src->it_interval.tv_usec); dst->it_value.tv_sec = Read64(src->it_value.tv_sec); dst->it_value.tv_usec = Read64(src->it_value.tv_usec); } void XlatWinsizeToLinux(struct winsize_bits *dst, const struct winsize *src) { memset(dst, 0, sizeof(*dst)); Write16(dst->ws_row, src->ws_row); Write16(dst->ws_col, src->ws_col); } void XlatSigsetToLinux(uint8_t dst[8], const sigset_t *src) { int i; uint64_t x; for (x = i = 0; i < 64; ++i) { if (sigismember(src, i + 1)) { x |= 1ull << i; } } Write64(dst, x); } void XlatLinuxToSigset(sigset_t *dst, const uint8_t src[8]) { int i; uint64_t x; x = Read64(src); sigemptyset(dst); for (i = 0; i < 64; ++i) { if ((1ull << i) & x) { sigaddset(dst, i + 1); } } } static int XlatTermiosCflag(int x) { int r = 0; if (x & 0x0001) r |= ISIG; if (x & 0x0040) r |= CSTOPB; if (x & 0x0080) r |= CREAD; if (x & 0x0100) r |= PARENB; if (x & 0x0200) r |= PARODD; if (x & 0x0400) r |= HUPCL; if (x & 0x0800) r |= CLOCAL; if ((x & 0x0030) == 0x0010) { r |= CS6; } else if ((x & 0x0030) == 0x0020) { r |= CS7; } else if ((x & 0x0030) == 0x0030) { r |= CS8; } return r; } static int UnXlatTermiosCflag(int x) { int r = 0; if (x & ISIG) r |= 0x0001; if (x & CSTOPB) r |= 0x0040; if (x & CREAD) r |= 0x0080; if (x & PARENB) r |= 0x0100; if (x & PARODD) r |= 0x0200; if (x & HUPCL) r |= 0x0400; if (x & CLOCAL) r |= 0x0800; if ((x & CSIZE) == CS5) { r |= 0x0000; } else if ((x & CSIZE) == CS6) { r |= 0x0010; } else if ((x & CSIZE) == CS7) { r |= 0x0020; } else if ((x & CSIZE) == CS8) { r |= 0x0030; } return r; } static int XlatTermiosLflag(int x) { int r = 0; if (x & 0x0001) r |= ISIG; if (x & 0x0002) r |= ICANON; if (x & 0x0008) r |= ECHO; if (x & 0x0010) r |= ECHOE; if (x & 0x0020) r |= ECHOK; if (x & 0x0040) r |= ECHONL; if (x & 0x0080) r |= NOFLSH; if (x & 0x0100) r |= TOSTOP; if (x & 0x8000) r |= IEXTEN; #ifdef ECHOCTL if (x & 0x0200) r |= ECHOCTL; #endif #ifdef ECHOPRT if (x & 0x0400) r |= ECHOPRT; #endif #ifdef ECHOKE if (x & 0x0800) r |= ECHOKE; #endif #ifdef FLUSHO if (x & 0x1000) r |= FLUSHO; #endif #ifdef PENDIN if (x & 0x4000) r |= PENDIN; #endif #ifdef XCASE if (x & 0x0004) r |= XCASE; #endif return r; } static int UnXlatTermiosLflag(int x) { int r = 0; if (x & ISIG) r |= 0x0001; if (x & ICANON) r |= 0x0002; if (x & ECHO) r |= 0x0008; if (x & ECHOE) r |= 0x0010; if (x & ECHOK) r |= 0x0020; if (x & ECHONL) r |= 0x0040; if (x & NOFLSH) r |= 0x0080; if (x & TOSTOP) r |= 0x0100; if (x & IEXTEN) r |= 0x8000; #ifdef ECHOCTL if (x & ECHOCTL) r |= 0x0200; #endif #ifdef ECHOPRT if (x & ECHOPRT) r |= 0x0400; #endif #ifdef ECHOKE if (x & ECHOKE) r |= 0x0800; #endif #ifdef FLUSHO if (x & FLUSHO) r |= 0x1000; #endif #ifdef PENDIN if (x & PENDIN) r |= 0x4000; #endif #ifdef XCASE if (x & XCASE) r |= 0x0004; #endif return r; } static int XlatTermiosIflag(int x) { int r = 0; if (x & 0x0001) r |= IGNBRK; if (x & 0x0002) r |= BRKINT; if (x & 0x0004) r |= IGNPAR; if (x & 0x0008) r |= PARMRK; if (x & 0x0010) r |= INPCK; if (x & 0x0020) r |= ISTRIP; if (x & 0x0040) r |= INLCR; if (x & 0x0080) r |= IGNCR; if (x & 0x0100) r |= ICRNL; if (x & 0x0400) r |= IXON; if (x & 0x0800) r |= IXANY; if (x & 0x1000) r |= IXOFF; #ifdef IMAXBEL if (x & 0x2000) r |= IMAXBEL; #endif #ifdef IUTF8 if (x & 0x4000) r |= IUTF8; #endif #ifdef IUCLC if (x & 0x0200) r |= IUCLC; #endif return r; } static int UnXlatTermiosIflag(int x) { int r = 0; if (x & IGNBRK) r |= 0x0001; if (x & BRKINT) r |= 0x0002; if (x & IGNPAR) r |= 0x0004; if (x & PARMRK) r |= 0x0008; if (x & INPCK) r |= 0x0010; if (x & ISTRIP) r |= 0x0020; if (x & INLCR) r |= 0x0040; if (x & IGNCR) r |= 0x0080; if (x & ICRNL) r |= 0x0100; if (x & IXON) r |= 0x0400; if (x & IXANY) r |= 0x0800; if (x & IXOFF) r |= 0x1000; #ifdef IMAXBEL if (x & IMAXBEL) r |= 0x2000; #endif #ifdef IUTF8 if (x & IUTF8) r |= 0x4000; #endif #ifdef IUCLC if (x & IUCLC) r |= 0x0200; #endif return r; } static int XlatTermiosOflag(int x) { int r = 0; if (x & 0x0001) r |= OPOST; #ifdef ONLCR if (x & 0x0004) r |= ONLCR; #endif #ifdef OCRNL if (x & 0x0008) r |= OCRNL; #endif #ifdef ONOCR if (x & 0x0010) r |= ONOCR; #endif #ifdef ONLRET if (x & 0x0020) r |= ONLRET; #endif #ifdef OFILL if (x & 0x0040) r |= OFILL; #endif #ifdef OFDEL if (x & 0x0080) r |= OFDEL; #endif #ifdef NLDLY if ((x & 0x0100) == 0x0000) { r |= NL0; } else if ((x & 0x0100) == 0x0100) { r |= NL1; #ifdef NL2 } else if ((x & 0x0100) == 0x0000) { r |= NL2; #endif #ifdef NL3 } else if ((x & 0x0100) == 0x0000) { r |= NL3; #endif } #endif #ifdef CRDLY if ((x & 0x0600) == 0x0000) { r |= CR0; } else if ((x & 0x0600) == 0x0200) { r |= CR1; } else if ((x & 0x0600) == 0x0400) { r |= CR2; } else if ((x & 0x0600) == 0x0600) { r |= CR3; } #endif #ifdef TABDLY if ((x & 0x1800) == 0x0000) { r |= TAB0; #ifdef TAB1 } else if ((x & 0x1800) == 0x0800) { r |= TAB1; #endif #ifdef TAB1 } else if ((x & 0x1800) == 0x1000) { r |= TAB2; #endif } else if ((x & 0x1800) == 0x1800) { r |= TAB3; } #endif #ifdef BSDLY if ((x & 0x2000) == 0x0000) { r |= BS0; } else if ((x & 0x2000) == 0x2000) { r |= BS1; } #endif #ifdef VTBDLY if ((x & 0x4000) == 0x0000) { r |= VT0; } else if ((x & 0x4000) == 0x4000) { r |= VT1; } #endif #ifdef FFBDLY if ((x & 0x8000) == 0x0000) { r |= FF0; } else if ((x & 0x8000) == 0x8000) { r |= FF1; } #endif #ifdef OLCUC if (x & 0x0002) r |= OLCUC; #endif return r; } static int UnXlatTermiosOflag(int x) { int r = 0; if (x & OPOST) r |= 0x0001; #ifdef ONLCR if (x & ONLCR) r |= 0x0004; #endif #ifdef OCRNL if (x & OCRNL) r |= 0x0008; #endif #ifdef ONOCR if (x & ONOCR) r |= 0x0010; #endif #ifdef ONLRET if (x & ONLRET) r |= 0x0020; #endif #ifdef OFILL if (x & OFILL) r |= 0x0040; #endif #ifdef OFDEL if (x & OFDEL) r |= 0x0080; #endif #ifdef NLDLY if ((x & NLDLY) == NL0) { r |= 0x0000; } else if ((x & NLDLY) == NL1) { r |= 0x0100; #ifdef NL2 } else if ((x & NLDLY) == NL2) { r |= 0x0000; #endif #ifdef NL3 } else if ((x & NLDLY) == NL3) { r |= 0x0000; #endif } #endif #ifdef CRDLY if ((x & CRDLY) == CR0) { r |= 0x0000; } else if ((x & CRDLY) == CR1) { r |= 0x0200; } else if ((x & CRDLY) == CR2) { r |= 0x0400; } else if ((x & CRDLY) == CR3) { r |= 0x0600; } #endif #ifdef TABDLY if ((x & TABDLY) == TAB0) { r |= 0x0000; #ifdef TAB1 } else if ((x & TABDLY) == TAB1) { r |= 0x0800; #endif #ifdef TAB2 } else if ((x & TABDLY) == TAB2) { r |= 0x1000; #endif } else if ((x & TABDLY) == TAB3) { r |= 0x1800; } #endif #ifdef BSDLY if ((x & BSDLY) == BS0) { r |= 0x0000; } else if ((x & BSDLY) == BS1) { r |= 0x2000; } #endif #ifdef VTDLY if ((x & VTDLY) == VT0) { r |= 0x0000; } else if ((x & VTDLY) == VT1) { r |= 0x4000; } #endif #ifdef FFDLY if ((x & FFDLY) == FF0) { r |= 0x0000; } else if ((x & FFDLY) == FF1) { r |= 0x8000; } #endif #ifdef OLCUC if (x & OLCUC) r |= 0x0002; #endif return r; } static void XlatTermiosCc(struct termios *dst, const struct termios_bits *src) { dst->c_cc[VINTR] = src->c_cc[0]; dst->c_cc[VQUIT] = src->c_cc[1]; dst->c_cc[VERASE] = src->c_cc[2]; dst->c_cc[VKILL] = src->c_cc[3]; dst->c_cc[VEOF] = src->c_cc[4]; dst->c_cc[VTIME] = src->c_cc[5]; dst->c_cc[VMIN] = src->c_cc[6]; dst->c_cc[VSTART] = src->c_cc[8]; dst->c_cc[VSTOP] = src->c_cc[9]; dst->c_cc[VSUSP] = src->c_cc[10]; dst->c_cc[VEOL] = src->c_cc[11]; #ifdef VSWTC dst->c_cc[VSWTC] = src->c_cc[7]; #endif #ifdef VREPRINT dst->c_cc[VREPRINT] = src->c_cc[12]; #endif #ifdef VDISCARD dst->c_cc[VDISCARD] = src->c_cc[13]; #endif #ifdef VWERASE dst->c_cc[VWERASE] = src->c_cc[14]; #endif #ifdef VLNEXT dst->c_cc[VLNEXT] = src->c_cc[15]; #endif #ifdef VEOL2 dst->c_cc[VEOL2] = src->c_cc[16]; #endif } static void UnXlatTermiosCc(struct termios_bits *dst, const struct termios *src) { dst->c_cc[0] = src->c_cc[VINTR]; dst->c_cc[1] = src->c_cc[VQUIT]; dst->c_cc[2] = src->c_cc[VERASE]; dst->c_cc[3] = src->c_cc[VKILL]; dst->c_cc[4] = src->c_cc[VEOF]; dst->c_cc[5] = src->c_cc[VTIME]; dst->c_cc[6] = src->c_cc[VMIN]; dst->c_cc[8] = src->c_cc[VSTART]; dst->c_cc[9] = src->c_cc[VSTOP]; dst->c_cc[10] = src->c_cc[VSUSP]; dst->c_cc[11] = src->c_cc[VEOL]; #ifdef VSWTC dst->c_cc[7] = src->c_cc[VSWTC]; #endif #ifdef VREPRINT dst->c_cc[12] = src->c_cc[VREPRINT]; #endif #ifdef VDISCARD dst->c_cc[13] = src->c_cc[VDISCARD]; #endif #ifdef VWERASE dst->c_cc[14] = src->c_cc[VWERASE]; #endif #ifdef VLNEXT dst->c_cc[15] = src->c_cc[VLNEXT]; #endif #ifdef VEOL2 dst->c_cc[16] = src->c_cc[VEOL2]; #endif } void XlatLinuxToTermios(struct termios *dst, const struct termios_bits *src) { memset(dst, 0, sizeof(*dst)); dst->c_iflag = XlatTermiosIflag(Read32(src->c_iflag)); dst->c_oflag = XlatTermiosOflag(Read32(src->c_oflag)); dst->c_cflag = XlatTermiosCflag(Read32(src->c_cflag)); dst->c_lflag = XlatTermiosLflag(Read32(src->c_lflag)); XlatTermiosCc(dst, src); } void XlatTermiosToLinux(struct termios_bits *dst, const struct termios *src) { memset(dst, 0, sizeof(*dst)); Write32(dst->c_iflag, UnXlatTermiosIflag(src->c_iflag)); Write32(dst->c_oflag, UnXlatTermiosOflag(src->c_oflag)); Write32(dst->c_cflag, UnXlatTermiosCflag(src->c_cflag)); Write32(dst->c_lflag, UnXlatTermiosLflag(src->c_lflag)); UnXlatTermiosCc(dst, src); }
24,815
1,003
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/panel.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/lib/panel.h" #include "libc/fmt/conv.h" #include "libc/intrin/bsr.h" #include "libc/intrin/safemacros.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "libc/str/unicode.h" #include "tool/build/lib/buffer.h" static int tpdecode(const char *s, wint_t *out) { uint32_t wc, cb, need, msb, j, i = 0; if ((wc = s[i++] & 255) == -1) return -1; while ((wc & 0300) == 0200) { if ((wc = s[i++] & 255) == -1) return -1; } if (!(0 <= wc && wc <= 0x7F)) { msb = wc < 252 ? _bsr(~wc & 0xff) : 1; need = 7 - msb; wc &= ((1u << msb) - 1) | 0003; for (j = 1; j < need; ++j) { if ((cb = s[i++] & 255) == -1) return -1; if ((cb & 0300) == 0200) { wc = wc << 6 | (cb & 077); } else { if (out) *out = 0xFFFD; return -1; } } } if (out) *out = wc; return i; } /** * Renders panel div flex boxen inside terminal display for tui. * * You can use all the UNICODE and ANSI escape sequences you want. * * @param fd is file descriptor * @param pn is number of panels * @param p is panel list in logically sorted order * @param tyn is terminal height in cells * @param txn is terminal width in cells * @return -1 w/ errno if an error happened * @see nblack's notcurses project too! */ ssize_t PrintPanels(int fd, long pn, struct Panel *p, long tyn, long txn) { wint_t wc; ssize_t rc; size_t wrote; struct Buffer b, *l; int x, y, i, j, width; enum { kUtf8, kAnsi, kAnsiCsi } state; bzero(&b, sizeof(b)); AppendStr(&b, "\e[H"); for (y = 0; y < tyn; ++y) { if (y) AppendFmt(&b, "\e[%dH", y + 1); for (x = i = 0; i < pn; ++i) { if (p[i].top <= y && y < p[i].bottom) { j = state = 0; l = &p[i].lines[y - p[i].top]; while (x < p[i].left) { AppendChar(&b, ' '); x += 1; } AppendFmt(&b, "\e[%d;%dH", y + 1, x + 1); // bsd utf-8 :( while (x < p[i].right || j < l->i) { wc = '\0'; width = 0; if (j < l->i) { wc = l->p[j]; switch (state) { case kUtf8: switch (wc & 0xff) { case '\e': state = kAnsi; ++j; break; default: j += abs(tpdecode(l->p + j, &wc)); if (x < p[i].right) { width = max(0, wcwidth(wc)); } else { wc = 0; } break; } break; case kAnsi: switch (wc & 0xff) { case '[': state = kAnsiCsi; ++j; break; case '@': case ']': case '^': case '_': case '\\': case 'A' ... 'Z': state = kUtf8; ++j; break; default: state = kUtf8; continue; } break; case kAnsiCsi: switch (wc & 0xff) { case ':': case ';': case '<': case '=': case '>': case '?': case '0' ... '9': ++j; break; case '`': case '~': case '^': case '@': case '[': case ']': case '{': case '}': case '_': case '|': case '\\': case 'A' ... 'Z': case 'a' ... 'z': state = kUtf8; ++j; break; default: state = kUtf8; continue; } break; default: unreachable; } if (x > p[i].right) { break; } } else if (x < p[i].right) { wc = ' '; width = 1; } if (wc) { x += width; AppendWide(&b, wc); } } } } } rc = WriteBuffer(&b, fd); free(b.p); return rc; }
6,344
181
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/high.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/itoa.h" #include "libc/str/str.h" #include "tool/build/lib/high.h" struct High g_high; char *HighStart(char *p, int h) { if (h) { p = stpcpy(p, "\e[38;5;"); p = FormatUint32(p, h); p = stpcpy(p, "m"); g_high.active = true; } return p; } char *HighEnd(char *p) { if (g_high.active) { p = stpcpy(p, "\e[39m"); g_high.active = false; } return p; }
2,239
42
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ssemov.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_SSEMOV_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_SSEMOV_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpLddquVdqMdq(struct Machine *, uint32_t); void OpMovntiMdqpGdqp(struct Machine *, uint32_t); void OpPmovmskbGdqpNqUdq(struct Machine *, uint32_t); void OpMaskMovDiXmmRegXmmRm(struct Machine *, uint32_t); void OpMovntdqaVdqMdq(struct Machine *, uint32_t); void OpMovWpsVps(struct Machine *, uint32_t); void OpMov0f28(struct Machine *, uint32_t); void OpMov0f6e(struct Machine *, uint32_t); void OpMov0f6f(struct Machine *, uint32_t); void OpMov0fE7(struct Machine *, uint32_t); void OpMov0f7e(struct Machine *, uint32_t); void OpMov0f7f(struct Machine *, uint32_t); void OpMov0f10(struct Machine *, uint32_t); void OpMov0f29(struct Machine *, uint32_t); void OpMov0f2b(struct Machine *, uint32_t); void OpMov0f12(struct Machine *, uint32_t); void OpMov0f13(struct Machine *, uint32_t); void OpMov0f16(struct Machine *, uint32_t); void OpMov0f17(struct Machine *, uint32_t); void OpMov0fD6(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_SSEMOV_H_ */
1,231
31
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/string.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/log/log.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "tool/build/lib/address.h" #include "tool/build/lib/alu.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/ioports.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/string.h" #include "tool/build/lib/throw.h" static uint64_t ReadInt(uint8_t p[8], unsigned long w) { switch (w) { case 0: return Read8(p); case 1: return Read16(p); case 2: return Read32(p); case 3: return Read64(p); default: unreachable; } } static void WriteInt(uint8_t p[8], uint64_t x, unsigned long w) { switch (w) { case 0: Write8(p, x); break; case 1: Write16(p, x); break; case 2: Write64(p, x & 0xffffffff); break; case 3: Write64(p, x); break; default: unreachable; } } static void AddDi(struct Machine *m, uint32_t rde, uint64_t x) { switch (Eamode(rde)) { case XED_MODE_LONG: Write64(m->di, Read64(m->di) + x); return; case XED_MODE_LEGACY: Write64(m->di, (Read32(m->di) + x) & 0xffffffff); return; case XED_MODE_REAL: Write16(m->di, Read16(m->di) + x); return; default: unreachable; } } static void AddSi(struct Machine *m, uint32_t rde, uint64_t x) { switch (Eamode(rde)) { case XED_MODE_LONG: Write64(m->si, Read64(m->si) + x); return; case XED_MODE_LEGACY: Write64(m->si, (Read32(m->si) + x) & 0xffffffff); return; case XED_MODE_REAL: Write16(m->si, Read16(m->si) + x); return; default: unreachable; } } static uint64_t ReadCx(struct Machine *m, uint32_t rde) { switch (Eamode(rde)) { case XED_MODE_LONG: return Read64(m->cx); case XED_MODE_LEGACY: return Read32(m->cx); case XED_MODE_REAL: return Read16(m->cx); default: unreachable; } } static uint64_t SubtractCx(struct Machine *m, uint32_t rde, uint64_t x) { uint64_t cx; cx = Read64(m->cx) - x; if (Eamode(rde) != XED_MODE_REAL) { if (Eamode(rde) == XED_MODE_LEGACY) { cx &= 0xffffffff; } Write64(m->cx, cx); } else { cx &= 0xffff; Write16(m->cx, cx); } return cx; } static void StringOp(struct Machine *m, uint32_t rde, int op) { bool stop; void *p[2]; unsigned n; int64_t sgn, v; uint8_t s[3][8]; stop = false; n = 1 << RegLog2(rde); sgn = GetFlag(m->flags, FLAGS_DF) ? -1 : 1; do { if (Rep(rde) && !ReadCx(m, rde)) break; switch (op) { case STRING_CMPS: kAlu[ALU_SUB][RegLog2(rde)]( ReadInt(Load(m, AddressSi(m, rde), n, s[2]), RegLog2(rde)), ReadInt(Load(m, AddressDi(m, rde), n, s[1]), RegLog2(rde)), &m->flags); AddDi(m, rde, sgn * n); AddSi(m, rde, sgn * n); stop = (Rep(rde) == 2 && GetFlag(m->flags, FLAGS_ZF)) || (Rep(rde) == 3 && !GetFlag(m->flags, FLAGS_ZF)); break; case STRING_MOVS: memcpy(BeginStore(m, (v = AddressDi(m, rde)), n, p, s[0]), Load(m, AddressSi(m, rde), n, s[1]), n); AddDi(m, rde, sgn * n); AddSi(m, rde, sgn * n); EndStore(m, v, n, p, s[0]); break; case STRING_STOS: memcpy(BeginStore(m, (v = AddressDi(m, rde)), n, p, s[0]), m->ax, n); AddDi(m, rde, sgn * n); EndStore(m, v, n, p, s[0]); break; case STRING_LODS: memcpy(m->ax, Load(m, AddressSi(m, rde), n, s[1]), n); AddSi(m, rde, sgn * n); break; case STRING_SCAS: kAlu[ALU_SUB][RegLog2(rde)]( ReadInt(Load(m, AddressDi(m, rde), n, s[1]), RegLog2(rde)), ReadInt(m->ax, RegLog2(rde)), &m->flags); AddDi(m, rde, sgn * n); stop = (Rep(rde) == 2 && GetFlag(m->flags, FLAGS_ZF)) || (Rep(rde) == 3 && !GetFlag(m->flags, FLAGS_ZF)); break; case STRING_OUTS: OpOut(m, Read16(m->dx), ReadInt(Load(m, AddressSi(m, rde), n, s[1]), RegLog2(rde))); AddSi(m, rde, sgn * n); break; case STRING_INS: WriteInt(BeginStore(m, (v = AddressDi(m, rde)), n, p, s[0]), OpIn(m, Read16(m->dx)), RegLog2(rde)); AddDi(m, rde, sgn * n); EndStore(m, v, n, p, s[0]); break; default: abort(); } if (Rep(rde)) { SubtractCx(m, rde, 1); } else { break; } } while (!stop); } static void RepMovsbEnhanced(struct Machine *m, uint32_t rde) { uint8_t *direal, *sireal; uint64_t diactual, siactual, cx; unsigned diremain, siremain, i, n; if ((cx = ReadCx(m, rde))) { do { diactual = AddressDi(m, rde); siactual = AddressSi(m, rde); SetWriteAddr(m, diactual, cx); SetReadAddr(m, siactual, cx); direal = ResolveAddress(m, diactual); sireal = ResolveAddress(m, siactual); diremain = 0x1000 - (diactual & 0xfff); siremain = 0x1000 - (siactual & 0xfff); n = MIN(cx, MIN(diremain, siremain)); if ((uintptr_t)direal <= (uintptr_t)sireal || (uintptr_t)direal >= (uintptr_t)sireal + n) { memcpy(direal, sireal, n); } else { for (i = 0; i < n; ++i) { direal[i] = sireal[i]; } } AddDi(m, rde, n); AddSi(m, rde, n); } while ((cx = SubtractCx(m, rde, n))); } } static void RepStosbEnhanced(struct Machine *m, uint32_t rde) { uint8_t *direal; unsigned diremain, n; uint64_t divirtual, diactual, cx; if ((cx = ReadCx(m, rde))) { do { diactual = AddressDi(m, rde); SetWriteAddr(m, diactual, cx); direal = ResolveAddress(m, diactual); diremain = 0x1000 - (diactual & 0xfff); n = MIN(cx, diremain); memset(direal, Read8(m->ax), n); AddDi(m, rde, n); } while ((cx = SubtractCx(m, rde, n))); } } void OpMovs(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_MOVS); } void OpCmps(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_CMPS); } void OpStos(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_STOS); } void OpLods(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_LODS); } void OpScas(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_SCAS); } void OpIns(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_INS); } void OpOuts(struct Machine *m, uint32_t rde) { StringOp(m, rde, STRING_OUTS); } void OpMovsb(struct Machine *m, uint32_t rde) { if (Rep(rde) && !GetFlag(m->flags, FLAGS_DF)) { RepMovsbEnhanced(m, rde); } else { OpMovs(m, rde); } } void OpStosb(struct Machine *m, uint32_t rde) { if (Rep(rde) && !GetFlag(m->flags, FLAGS_DF)) { RepStosbEnhanced(m, rde); } else { OpStos(m, rde); } }
8,810
286
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/disspec.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/str/str.h" #include "third_party/xed/x86.h" #include "tool/build/lib/case.h" #include "tool/build/lib/modrm.h" #define UNKNOWN "wut" #define RCASE(x, y) CASE(x, return y) static const char kFpuName[][8][8] = { {"fadd", "fmul", "fcom", "fcomp", "fsub", "fsubr", "fdiv", "fdivr"}, {"fchs", "fabs", UNKNOWN, UNKNOWN, "ftst", "fxam", UNKNOWN, UNKNOWN}, {"fld1", "fldl2t", "fldl2e", "fldpi", "fldlg2", "fldln2", "fldz"}, {"f2xm1", "fyl2x", "fptan", "fpatan", "fxtract", "fprem1", "fdecstp", "fincstp"}, {"fprem", "fyl2xp1", "fsqrt", "fsincos", "frndint", "fscale", "fsin", "fcos"}, {"fneni", "fndisi", "fnclex", "fninit", "fnsetpm"}, }; char *DisOpFpu1(struct XedDecodedInst *x, char *p, const char *extra) { stpcpy(stpcpy(p, kFpuName[0][ModrmReg(x->op.rde)]), extra); return p; } char *DisOp66(struct XedDecodedInst *x, char *p, const char *s, const char *a, const char *b) { stpcpy(stpcpy(p, s), !Osz(x->op.rde) ? a : b); return p; } char *DisOpVpsWpsVssWss(struct XedDecodedInst *x, char *p, const char *s) { return DisOp66(x, p, s, "ps %Vps Wps", "ss %Vss Wss"); } char *DisOpVpdWpdVpsWps(struct XedDecodedInst *x, char *p, const char *s) { return DisOp66(x, p, s, "ps %Vps Wps", "pd %Vpd Wpd"); } char *DisOpPqQqVdqWdq(struct XedDecodedInst *x, char *p, const char *s) { return DisOp66(x, p, s, " %Pq Qq", " %Vdq Wdq"); } char *DisOpPqQqIbVdqWdqIb(struct XedDecodedInst *x, char *p, const char *s) { return DisOp66(x, p, s, " %Pq Qq Ib", " %Vdq Wdq Ib"); } char *DisOpNqIbUdqIb(struct XedDecodedInst *x, char *p, const char *s) { return DisOp66(x, p, s, " %Nq Ib", " %Udq Ib"); } char *DisOpVpsWpsVssWssVpdWpdVsdWsd(struct XedDecodedInst *x, char *p, const char *s) { char *q = stpcpy(p, s); if (Rep(x->op.rde) == 3) { stpcpy(q, "ss %Vss Wss"); } else if (Rep(x->op.rde) == 2) { stpcpy(q, "sd %Vsd Wsd"); } else if (Osz(x->op.rde)) { stpcpy(q, "pd %Vpd Wpd"); } else { stpcpy(q, "ps %Vps Wps"); } return p; } const char *DisSpecFpu0(struct XedDecodedInst *x, int group) { const char *s; s = kFpuName[group][ModrmRm(x->op.rde)]; return *s ? s : UNKNOWN; } const char *DisSpecRegMem(struct XedDecodedInst *x, const char *a, const char *b) { if (IsModrmRegister(x->op.rde)) { return a; } else { return b; } } const char *DisSpecRegMemFpu0(struct XedDecodedInst *x, int group, const char *b) { return DisSpecRegMem(x, DisSpecFpu0(x, group), b); } const char *DisSpecMap0(struct XedDecodedInst *x, char *p) { switch (x->op.opcode & 0xff) { RCASE(0x00, "ALU Eb %Gb"); RCASE(0x01, "ALU Evqp %Gvqp"); RCASE(0x02, "ALU %Gb Eb"); RCASE(0x03, "ALU %Gvqp Evqp"); RCASE(0x04, "ALU %al Ib"); RCASE(0x05, "ALU %rAX Ivds"); RCASE(0x06, "push %es"); RCASE(0x07, "pop %es"); RCASE(0x08, "ALU Eb %Gb"); RCASE(0x09, "ALU Evqp %Gvqp"); RCASE(0x0a, "ALU %Gb Eb"); RCASE(0x0b, "ALU %Gvqp Evqp"); RCASE(0x0c, "ALU %al Ib"); RCASE(0x0d, "ALU %rAX Ivds"); RCASE(0x0e, "push %cs"); RCASE(0x0f, "pop %cs"); RCASE(0x10, "ALU Eb %Gb"); RCASE(0x11, "ALU Evqp %Gvqp"); RCASE(0x12, "ALU %Gb Eb"); RCASE(0x13, "ALU %Gvqp Evqp"); RCASE(0x14, "ALU %al Ib"); RCASE(0x15, "ALU %rAX Ivds"); RCASE(0x16, "push %ss"); RCASE(0x17, "pop %ss"); RCASE(0x18, "ALU Eb %Gb"); RCASE(0x19, "ALU Evqp %Gvqp"); RCASE(0x1a, "ALU %Gb Eb"); RCASE(0x1b, "ALU %Gvqp Evqp"); RCASE(0x1c, "ALU %al Ib"); RCASE(0x1d, "ALU %rAX Ivds"); RCASE(0x1e, "push %ds"); RCASE(0x1f, "pop %ds"); RCASE(0x20, "ALU Eb %Gb"); RCASE(0x21, "ALU Evqp %Gvqp"); RCASE(0x22, "ALU %Gb Eb"); RCASE(0x23, "ALU %Gvqp Evqp"); RCASE(0x24, "ALU %al Ib"); RCASE(0x25, "ALU %rAX Ivds"); RCASE(0x26, "push %es"); RCASE(0x27, "pop %es"); RCASE(0x28, "ALU Eb %Gb"); RCASE(0x29, "ALU Evqp %Gvqp"); RCASE(0x2a, "ALU %Gb Eb"); RCASE(0x2b, "ALU %Gvqp Evqp"); RCASE(0x2c, "ALU %al Ib"); RCASE(0x2d, "ALU %rAX Ivds"); RCASE(0x2F, "das"); RCASE(0x30, "ALU Eb %Gb"); RCASE(0x31, "ALU Evqp %Gvqp"); RCASE(0x32, "ALU %Gb Eb"); RCASE(0x33, "ALU %Gvqp Evqp"); RCASE(0x34, "ALU %al Ib"); RCASE(0x35, "ALU %rAX Ivds"); RCASE(0x37, "aaa"); RCASE(0x38, "ALU Eb %Gb"); RCASE(0x39, "ALU Evqp %Gvqp"); RCASE(0x3A, "ALU %Gb Eb"); RCASE(0x3B, "ALU %Gvqp Evqp"); RCASE(0x3C, "ALU %al Ib"); RCASE(0x3D, "ALU %rAX Ivds"); RCASE(0x3F, "aas"); RCASE(0x40 ... 0x47, "inc %Zv"); RCASE(0x48 ... 0x4f, "dec %Zv"); RCASE(0x50 ... 0x57, "push %Zvq"); RCASE(0x58 ... 0x5f, "pop %Zvq"); RCASE(0x60, "pusha"); RCASE(0x61, "popa"); RCASE(0x62, "bound"); RCASE(0x63, "movslLQ %Gdqp Ed"); RCASE(0x68, "pushWQ Ivs"); RCASE(0x69, "imul %Gvqp Evqp Ivds"); RCASE(0x6A, "pushWQ Ibss"); RCASE(0x6B, "imul %Gvqp Evqp Ibs"); RCASE(0x6C, "insb Yb DX"); RCASE(0x6D, "insWL Yv DX"); RCASE(0x6E, "outsb DX Xb"); RCASE(0x6F, "outsWL DX Xv"); RCASE(0x70 ... 0x7f, "jCC Jbs"); RCASE(0x80, "ALU2 Eb Ib"); RCASE(0x81, "ALU2 Evqp Ivds"); RCASE(0x82, "ALU2 Eb Ib"); RCASE(0x83, "ALU2 Evqp Ibs"); RCASE(0x84, "test Eb %Gb"); RCASE(0x85, "test %Gvqp Evqp"); RCASE(0x86, "xchg %Gb Eb"); RCASE(0x87, "xchg %Gvqp Evqp"); RCASE(0x88, "mov Eb %Gb"); RCASE(0x89, "mov Evqp %Gvqp"); RCASE(0x8A, "mov %Gb Eb"); RCASE(0x8B, "mov %Gvqp Evqp"); RCASE(0x8C, "mov Evqp %Sw"); RCASE(0x8D, "lea %Gvqp M"); RCASE(0x8E, "mov %Sw Evqp"); RCASE(0x90, "nop"); RCASE(0x91 ... 0x97, "xchg %Zvqp %rAX"); RCASE(0x98, "cwtl"); RCASE(0x99, "cltd"); RCASE(0x9A, "lcall Pvds Kvds"); RCASE(0x9B, "fwait"); RCASE(0x9C, "pushfWQ"); RCASE(0x9D, "popfWQ"); RCASE(0x9E, "sahf"); RCASE(0x9F, "lahf"); RCASE(0xA0, "movABS %al Ob"); RCASE(0xA1, "movABS %rAX Ovqp"); RCASE(0xA2, "movABS Ob %al"); RCASE(0xA3, "movABS Ovqp %rAX"); RCASE(0xA4, "movsb Yb Xb"); RCASE(0xA5, "movsWLQ Yvqp Xvqp"); RCASE(0xA6, "cmpsb Yb Xb"); RCASE(0xA7, "cmpsWLQ Yvqp Xvqp"); RCASE(0xA8, "test %al Ib"); RCASE(0xA9, "test %rAX Ivds"); RCASE(0xAA, "stosb Yb %al"); RCASE(0xAB, "stosWLQ Yvqp %rAX"); RCASE(0xAC, "lodsb %al Xb"); RCASE(0xAD, "lodsWLQ %rAX Xvqp"); RCASE(0xAE, "scasb %al Yb"); RCASE(0xAF, "scasWLQ %rAX Yvqp"); RCASE(0xB0 ... 0xb7, "mov %Zb Ib"); RCASE(0xB8 ... 0xbf, "movABS %Zvqp Ivqp"); RCASE(0xC0, "BIT Eb Ib"); RCASE(0xC1, "BIT Evqp Ib"); RCASE(0xC2, "ret Iw"); RCASE(0xC3, "ret"); RCASE(0xC4, "les %Gv Mp"); RCASE(0xC5, "lds %Gv Mp"); RCASE(0xC6, "mov Eb Ib"); RCASE(0xC7, "mov Evqp Ivds"); RCASE(0xC9, "leave"); RCASE(0xCA, "lret Iw"); RCASE(0xCB, "lret"); RCASE(0xCC, "int3"); RCASE(0xCD, "int Ib"); RCASE(0xCE, "into"); RCASE(0xCF, "iret"); RCASE(0xD0, "BIT Eb"); RCASE(0xD1, "BIT Evqp"); RCASE(0xD2, "BIT Evqp %cl"); RCASE(0xD3, "BIT Evqp %cl"); RCASE(0xD4, x->op.uimm0 == 0x0a ? "aam" : "aam Ib"); RCASE(0xD5, x->op.uimm0 == 0x0a ? "aad" : "aad Ib"); RCASE(0xD6, "salc"); RCASE(0xD7, "xlat BBb"); RCASE(0xE0, "loopne Jbs"); RCASE(0xE1, "loope Jbs"); RCASE(0xE2, "loop Jbs"); RCASE(0xE3, "jcxz Jbs"); RCASE(0xE4, "in %al Ib"); RCASE(0xE5, "in %eAX Ib"); RCASE(0xE6, "out Ib %al"); RCASE(0xE7, "out Ib %eAX"); RCASE(0xE8, "call Jvds"); RCASE(0xE9, "jmp Jvds"); RCASE(0xEA, "ljmp Rvds Kvds"); RCASE(0xEB, "jmp Jbs"); RCASE(0xEC, "in %al DX"); RCASE(0xED, "in %eAX DX"); RCASE(0xEE, "out DX %al"); RCASE(0xEF, "out DX %eAX"); RCASE(0xF1, "int1"); RCASE(0xF4, "hlt"); RCASE(0xF5, "cmc"); RCASE(0xF8, "clc"); RCASE(0xF9, "stc"); RCASE(0xFA, "cli"); RCASE(0xFB, "sti"); RCASE(0xFC, "cld"); RCASE(0xFD, "std"); case 0x8F: switch (ModrmReg(x->op.rde)) { RCASE(0, "popWQ Evq"); default: break; } break; case 0xD9: switch (ModrmReg(x->op.rde)) { RCASE(1, "fxch EST1"); RCASE(3, "fstps Msr %st"); RCASE(0, DisSpecRegMem(x, "fld EST", "flds Msr")); RCASE(2, DisSpecRegMem(x, "fnop", "fsts Msr %st")); RCASE(4, DisSpecRegMemFpu0(x, 1, "fldenv Me")); RCASE(5, DisSpecRegMemFpu0(x, 2, "fldcw Mw")); RCASE(6, DisSpecRegMemFpu0(x, 3, "fnstenv M")); RCASE(7, DisSpecRegMemFpu0(x, 4, "fnstcw Mw")); } break; case 0xDA: switch (ModrmReg(x->op.rde)) { RCASE(0, DisSpecRegMem(x, "fcmovb %st EST", "fiaddl Mdi")); RCASE(1, DisSpecRegMem(x, "fcmove %st EST", "fimull Mdi")); RCASE(2, DisSpecRegMem(x, "fcmovbe %st EST", "ficoml Mdi")); RCASE(3, DisSpecRegMem(x, "fcmovu %st EST", "ficompl Mdi")); RCASE(4, DisSpecRegMem(x, "fisubr Mdi", "fisubl Mdi")); RCASE(5, DisSpecRegMem(x, "fucompp", "fisubrl Mdi")); RCASE(6, DisSpecRegMem(x, "fidivl Mdi", "UNKNOWN")); RCASE(7, DisSpecRegMem(x, "fidivrl Mdi", "UNKNOWN")); } break; case 0xDB: switch (ModrmReg(x->op.rde)) { RCASE(0, DisSpecRegMem(x, "fcmovnb %st EST", "fildl Mdi")); RCASE(1, DisSpecRegMem(x, "fcmovne %st EST", "fisttpl Mdi")); RCASE(2, DisSpecRegMem(x, "fcmovnbe %st EST", "fistl Mdi")); RCASE(3, DisSpecRegMem(x, "fcmovnu %st EST", "fistpl Mdi")); RCASE(4, DisSpecFpu0(x, 5)); RCASE(5, DisSpecRegMem(x, "fucomi %st EST", "fldt Mer")); RCASE(6, DisSpecRegMem(x, "fcomi %st EST", UNKNOWN)); RCASE(7, DisSpecRegMem(x, UNKNOWN, "fstpt Mer")); } break; case 0xD8: return DisOpFpu1(x, p, !IsModrmRegister(x->op.rde) ? "s Msr" : " EST1"); case 0xDC: if (!IsModrmRegister(x->op.rde)) { return DisOpFpu1(x, p, "l Mdr"); } else { switch (ModrmReg(x->op.rde)) { RCASE(0, "fadd EST %st"); RCASE(1, "fmul EST %st"); RCASE(2, "fcom %st EST"); RCASE(3, "fcomp %st EST"); RCASE(4, "fsub EST %st"); RCASE(5, "fsubr EST %st"); RCASE(6, "fdiv EST %st"); RCASE(7, "fdivr EST %st"); } } break; case 0xDD: if (!IsModrmRegister(x->op.rde)) { switch (ModrmReg(x->op.rde)) { RCASE(0, "fldl Mdr"); RCASE(1, "fisttpll Mqi"); RCASE(2, "fstl Mdr"); RCASE(3, "fstpl Mdr"); RCASE(4, "frstor Mdr"); RCASE(6, "fnsave Mst"); RCASE(7, "fnstsw Mst"); } } else { switch (ModrmReg(x->op.rde)) { RCASE(0, "ffree EST"); RCASE(1, "fxch EST"); RCASE(2, "fst EST"); RCASE(3, "fstp EST"); RCASE(4, "fucom EST1"); RCASE(5, "fucomp EST1"); } } break; case 0xDE: if (!IsModrmRegister(x->op.rde)) { switch (ModrmReg(x->op.rde)) { RCASE(0, "fiadds Mwi"); RCASE(1, "fimuls Mwi"); RCASE(2, "ficoms Mwi"); RCASE(3, "ficomps Mwi"); RCASE(4, "fisubs Mwi"); RCASE(5, "fisubrs Mwi"); RCASE(6, "fidivs Mwi"); RCASE(7, "fidivrs Mwi"); } } else { switch (ModrmReg(x->op.rde)) { RCASE(0, "faddp EST1"); RCASE(1, "fmulp EST1"); RCASE(2, "fcomp EST1"); RCASE(3, "fcompp"); RCASE(4, "fsubp EST1"); RCASE(5, "fsubrp EST1"); RCASE(6, "fdivp EST1"); RCASE(7, "fdivrp EST1"); } } break; case 0xDF: if (!IsModrmRegister(x->op.rde)) { switch (ModrmReg(x->op.rde)) { RCASE(0, "filds Mwi"); RCASE(1, "fisttps Mwi"); RCASE(2, "fists Mwi"); RCASE(3, "fistps Mwi"); RCASE(4, "fbld"); RCASE(5, "fildll Mqi"); RCASE(6, "fbstp"); RCASE(7, "fistpll Mqi"); } } else { switch (ModrmReg(x->op.rde)) { RCASE(0, "ffreep EST"); RCASE(1, "fxch"); RCASE(2, "fstp EST"); RCASE(3, "fstp EST"); RCASE(4, "fnstsw"); RCASE(5, "fucomip EST"); RCASE(6, "fcomip EST"); } } break; case 0xF6: switch (ModrmReg(x->op.rde)) { RCASE(0, "test Eb Ib"); RCASE(1, "test Eb Ib"); RCASE(2, "not Eb"); RCASE(3, "neg Eb"); RCASE(4, "mulb Eb"); RCASE(5, "imulb Eb"); RCASE(6, "divb Eb"); RCASE(7, "idivb Eb"); } break; case 0xF7: switch (ModrmReg(x->op.rde)) { RCASE(0, "test Evqp Ivds"); RCASE(1, "test Evqp Ivds"); RCASE(2, "not Evqp"); RCASE(3, "neg Evqp"); RCASE(4, "mul Evqp"); RCASE(5, "imul Evqp"); RCASE(6, "div Evqp"); RCASE(7, "idiv Evqp"); } break; case 0xFE: switch (ModrmReg(x->op.rde)) { RCASE(0, "inc Eb"); RCASE(1, "dec Eb"); } break; case 0xFF: switch (ModrmReg(x->op.rde)) { RCASE(0, "inc Evqp"); RCASE(1, "dec Evqp"); RCASE(2, "CALL Eq"); RCASE(4, "JMP Eq"); RCASE(6, "pushWQ Evq"); } break; } return UNKNOWN; } const char *DisSpecMap1(struct XedDecodedInst *x, char *p) { bool isreg; isreg = IsModrmRegister(x->op.rde); switch (x->op.opcode & 0xff) { RCASE(0x02, "lar %Gvqp Ev"); RCASE(0x03, "lsl %Gvqp Ev"); RCASE(0x05, "syscall"); RCASE(0x0B, "ud2"); RCASE(0x0D, "nop Ev"); RCASE(0x18, "nop Ev"); RCASE(0x19, "nop Ev"); RCASE(0x1A, "nop Ev"); RCASE(0x1B, "nop Ev"); RCASE(0x1C, "nop Ev"); RCASE(0x1D, "nop Ev"); RCASE(0x20, "mov %Hd %Cd"); RCASE(0x22, "mov %Cd %Hd"); RCASE(0x28, "movapSD %Vps Wps"); RCASE(0x29, "movapSD Wps %Vps"); RCASE(0x2B, "movntpSD Mps %Vps"); RCASE(0x2E, Osz(x->op.rde) ? "ucomisd %Vsd Wsd" : "ucomiss %Vss Wss"); RCASE(0x2F, Osz(x->op.rde) ? "comisd %Vsd Wsd" : "comiss %Vss Wss"); RCASE(0x30, "wrmsr"); RCASE(0x31, "rdtsc"); RCASE(0x32, "rdmsr"); RCASE(0x33, "rdpmc"); RCASE(0x34, "sysenter"); RCASE(0x35, "sysexit"); RCASE(0x40 ... 0x4f, "cmovCC %Gvqp Evqp"); RCASE(0x52, DisOpVpsWpsVssWss(x, p, "rsqrt")); RCASE(0x53, DisOpVpsWpsVssWss(x, p, "rcp")); RCASE(0x54, DisOpVpdWpdVpsWps(x, p, "and")); RCASE(0x55, DisOpVpdWpdVpsWps(x, p, "andn")); RCASE(0x56, DisOpVpdWpdVpsWps(x, p, "or")); RCASE(0x57, DisOpVpdWpdVpsWps(x, p, "xor")); RCASE(0x58, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "add")); RCASE(0x59, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "mul")); RCASE(0x5C, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "sub")); RCASE(0x5D, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "min")); RCASE(0x5E, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "div")); RCASE(0x5F, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "max")); RCASE(0x60, DisOpPqQqVdqWdq(x, p, "punpcklbw")); RCASE(0x61, DisOpPqQqVdqWdq(x, p, "punpcklwd")); RCASE(0x62, DisOpPqQqVdqWdq(x, p, "punpckldq")); RCASE(0x63, DisOpPqQqVdqWdq(x, p, "packsswb")); RCASE(0x64, DisOpPqQqVdqWdq(x, p, "pcmpgtb")); RCASE(0x65, DisOpPqQqVdqWdq(x, p, "pcmpgtw")); RCASE(0x66, DisOpPqQqVdqWdq(x, p, "pcmpgtd")); RCASE(0x67, DisOpPqQqVdqWdq(x, p, "packuswb")); RCASE(0x68, DisOpPqQqVdqWdq(x, p, "punpckhbw")); RCASE(0x69, DisOpPqQqVdqWdq(x, p, "punpckhwd")); RCASE(0x6A, DisOpPqQqVdqWdq(x, p, "punpckhdq")); RCASE(0x6B, DisOpPqQqVdqWdq(x, p, "packssdw")); RCASE(0x6C, DisOpPqQqVdqWdq(x, p, "punpcklqdq")); RCASE(0x6D, DisOpPqQqVdqWdq(x, p, "punpckhqdq")); RCASE(0x74, DisOpPqQqVdqWdq(x, p, "pcmpeqb")); RCASE(0x75, DisOpPqQqVdqWdq(x, p, "pcmpeqw")); RCASE(0x76, DisOpPqQqVdqWdq(x, p, "pcmpeqd")); RCASE(0x77, "emms"); RCASE(0x80 ... 0x8f, "jCC Jvds"); RCASE(0x90 ... 0x9f, "setCC Jvds"); RCASE(0xA0, "push %fs"); RCASE(0xA1, "pop %fs"); RCASE(0xA2, "cpuid"); RCASE(0xA3, "bt Evqp %Gvqp"); RCASE(0xA4, "shld Evqp %Gvqp Ib"); RCASE(0xA5, "shld Evqp %Gvqp %cl"); RCASE(0xA8, "push %gs"); RCASE(0xA9, "pop %gs"); RCASE(0xAB, "bts Evqp %Gvqp"); RCASE(0xAC, "shrd Evqp %Gvqp Ib"); RCASE(0xAD, "shrd Evqp %Gvqp %cl"); RCASE(0xAF, "imul %Gvqp Evqp"); RCASE(0xB0, "cmpxchg Eb %Gb"); RCASE(0xB1, "cmpxchg Evqp %Gvqp"); RCASE(0xB3, "btr Evqp %Gvqp"); RCASE(0xB6, "movzbWLQ %Gvqp Eb"); RCASE(0xB7, "movzwWLQ %Gvqp Ew"); RCASE(0xB9, "ud %Gvqp Evqp"); RCASE(0xBB, "btc Evqp %Gvqp"); RCASE(0xBE, "movsbWLQ %Gvqp Eb"); RCASE(0xBF, "movswWLQ %Gvqp Ew"); RCASE(0xC0, "xadd Eb %Gb"); RCASE(0xC1, "xadd Evqp %Gvqp"); RCASE(0xC2, DisOpVpsWpsVssWssVpdWpdVsdWsd(x, p, "cmp")); RCASE(0xC3, "movnti Mdqp %Gdqp"); RCASE(0xC8 ... 0xCF, "bswap %Zvqp"); RCASE(0xD1, DisOpPqQqVdqWdq(x, p, "psrlw")); RCASE(0xD2, DisOpPqQqVdqWdq(x, p, "psrld")); RCASE(0xD3, DisOpPqQqVdqWdq(x, p, "psrlq")); RCASE(0xD4, DisOpPqQqVdqWdq(x, p, "paddq")); RCASE(0xD5, DisOpPqQqVdqWdq(x, p, "pmullw")); RCASE(0xD7, Osz(x->op.rde) ? "pmovmskb %Gdqp %Udq" : "pmovmskb %Gdqp %Nq"); RCASE(0xD8, DisOpPqQqVdqWdq(x, p, "psubusb")); RCASE(0xD9, DisOpPqQqVdqWdq(x, p, "psubusw")); RCASE(0xDA, DisOpPqQqVdqWdq(x, p, "pminub")); RCASE(0xDB, DisOpPqQqVdqWdq(x, p, "pand")); RCASE(0xDC, DisOpPqQqVdqWdq(x, p, "paddusb")); RCASE(0xDD, DisOpPqQqVdqWdq(x, p, "paddusw")); RCASE(0xDE, DisOpPqQqVdqWdq(x, p, "pmaxub")); RCASE(0xDF, DisOpPqQqVdqWdq(x, p, "pandn")); RCASE(0xE0, DisOpPqQqVdqWdq(x, p, "pavgb")); RCASE(0xE1, DisOpPqQqVdqWdq(x, p, "psrawv")); RCASE(0xE2, DisOpPqQqVdqWdq(x, p, "psradv")); RCASE(0xE3, DisOpPqQqVdqWdq(x, p, "pavgw")); RCASE(0xE4, DisOpPqQqVdqWdq(x, p, "pmulhuw")); RCASE(0xE5, DisOpPqQqVdqWdq(x, p, "pmulhw")); RCASE(0xE7, Osz(x->op.rde) ? "movntdq Mdq %Vdq" : "movntq Mq %Pq"); RCASE(0xE8, DisOpPqQqVdqWdq(x, p, "psubsb")); RCASE(0xE9, DisOpPqQqVdqWdq(x, p, "psubsw")); RCASE(0xEA, DisOpPqQqVdqWdq(x, p, "pminsw")); RCASE(0xEB, DisOpPqQqVdqWdq(x, p, "por")); RCASE(0xEC, DisOpPqQqVdqWdq(x, p, "paddsb")); RCASE(0xED, DisOpPqQqVdqWdq(x, p, "paddsw")); RCASE(0xEE, DisOpPqQqVdqWdq(x, p, "pmaxsw")); RCASE(0xEF, DisOpPqQqVdqWdq(x, p, "pxor")); RCASE(0xF0, "lddqu %Vdq Mdq"); RCASE(0xF1, DisOpPqQqVdqWdq(x, p, "psllwv")); RCASE(0xF2, DisOpPqQqVdqWdq(x, p, "pslldv")); RCASE(0xF3, DisOpPqQqVdqWdq(x, p, "psllqv")); RCASE(0xF4, DisOpPqQqVdqWdq(x, p, "pmuludq")); RCASE(0xF5, DisOpPqQqVdqWdq(x, p, "pmaddwd")); RCASE(0xF6, DisOpPqQqVdqWdq(x, p, "psadbw")); RCASE(0xF8, DisOpPqQqVdqWdq(x, p, "psubb")); RCASE(0xF9, DisOpPqQqVdqWdq(x, p, "psubw")); RCASE(0xFA, DisOpPqQqVdqWdq(x, p, "psubd")); RCASE(0xFB, DisOpPqQqVdqWdq(x, p, "psubq")); RCASE(0xFC, DisOpPqQqVdqWdq(x, p, "paddb")); RCASE(0xFD, DisOpPqQqVdqWdq(x, p, "paddw")); RCASE(0xFE, DisOpPqQqVdqWdq(x, p, "paddd")); RCASE(0xFF, "ud0 %Gvqp Evqp"); case 0xBC: if (Rep(x->op.rde) == 3) { return "tzcnt %Gvqp Evqp"; } else { return "bsf %Gvqp Evqp"; } case 0xBD: if (Rep(x->op.rde) == 3) { return "lzcnt %Gvqp Evqp"; } else { return "bsr %Gvqp Evqp"; } case 0x01: switch (ModrmReg(x->op.rde)) { case 0: if (!isreg) { return "sgdt Ms"; } else { switch (ModrmRm(x->op.rde)) { case 1: return "vmcall"; case 2: return "vmlaunch"; case 3: return "vmresume"; case 4: return "vmxoff"; default: return UNKNOWN; } } break; case 1: if (!isreg) { return "sidt Ms"; } else { switch (ModrmRm(x->op.rde)) { case 0: return "monitor"; case 1: return "mwait"; default: return UNKNOWN; } } break; case 2: if (!isreg) { return "lgdt Ms"; } else if (ModrmRm(x->op.rde) == 0) { return "xgetbv"; } else if (ModrmRm(x->op.rde) == 1) { return "xsetbv"; } else { return UNKNOWN; } break; case 3: if (!isreg) { return "lidt Ms"; } else { return UNKNOWN; } case 4: return "smsw Ew"; case 6: return "lmsw Ew"; case 7: if (!isreg) { return "invlpg M"; } else { switch (ModrmRm(x->op.rde)) { case 0: return "swapgs"; case 1: return "rdtscp"; default: return UNKNOWN; } } default: return UNKNOWN; } case 0x1F: if (ModrmMod(x->op.rde) == 1 && ModrmReg(x->op.rde) == 0 && ModrmRm(x->op.rde) == 0b101) { return "bofram Jb"; } else { return "nop Ev"; } break; case 0x70: switch (Rep(x->op.rde) | Osz(x->op.rde)) { RCASE(0, "pshufw %Pq Qq Ib"); RCASE(1, "pshufd %Vdq Wdq Ib"); RCASE(2, "pshuflw %Vdq Wdq Ib"); RCASE(3, "pshufhw %Vdq Wdq Ib"); } break; case 0x71: switch (ModrmReg(x->op.rde)) { RCASE(2, DisOpNqIbUdqIb(x, p, "psrlw")); RCASE(4, DisOpNqIbUdqIb(x, p, "psraw")); RCASE(6, DisOpNqIbUdqIb(x, p, "psllw")); } break; case 0x72: switch (ModrmReg(x->op.rde)) { RCASE(2, DisOpNqIbUdqIb(x, p, "psrld")); RCASE(4, DisOpNqIbUdqIb(x, p, "psrad")); RCASE(6, DisOpNqIbUdqIb(x, p, "pslld")); } break; case 0x73: switch (ModrmReg(x->op.rde)) { RCASE(2, DisOpNqIbUdqIb(x, p, "psrlq")); RCASE(3, DisOpNqIbUdqIb(x, p, "psrldq")); RCASE(6, DisOpNqIbUdqIb(x, p, "psllq")); RCASE(7, DisOpNqIbUdqIb(x, p, "pslldq")); } break; case 0xAE: switch (ModrmReg(x->op.rde)) { case 0: if (isreg) { return "rdfsbase %Rdqp"; } else { return "fxsave M"; } case 1: if (isreg) { return "rdgsbase %Rdqp"; } else { return "fxrstor M"; } case 2: if (isreg) { return "wrfsbase %Rdqp"; } else { return "ldmxcsr Md"; } case 3: if (isreg) { return "wrgsbase %Rdqp"; } else { return "stmxcsr Md"; } case 4: if (isreg) { return UNKNOWN; } else { return "xsave M %edx %eax"; } case 5: return "lfence"; case 6: return "mfence"; case 7: if (isreg && ModrmReg(x->op.rde) == 0b111) { return "sfence"; } else { return "clflush"; } } break; case 0xBA: switch (ModrmReg(x->op.rde)) { RCASE(4, "btWLQ Evqp Ib"); RCASE(5, "btsWLQ Evqp Ib"); RCASE(6, "btrWLQ Evqp Ib"); RCASE(7, "btcWLQ Evqp Ib"); } break; case 0x10: if (Rep(x->op.rde) == 3) { return "movss %Vss Wss"; } else if (Rep(x->op.rde) == 2) { return "movsd %Vsd Wsd"; } else if (Osz(x->op.rde)) { return "movupd %Vpd Wpd"; } else { return "movups %Vps Wps"; } break; case 0x11: if (Rep(x->op.rde) == 3) { return "movss Wss %Vss"; } else if (Rep(x->op.rde) == 2) { return "movsd Wsd %Vsd"; } else if (Osz(x->op.rde)) { return "movupd Wpd %Vpd"; } else { return "movups Wps %Vps"; } break; case 0xC4: if (!Osz(x->op.rde)) { if (isreg) { return "pinsrw %Pq %Rdqp Ib"; } else { return "pinsrw %Pq Mw Ib"; } } else { if (isreg) { return "pinsrw %Vdq %Rdqp Ib"; } else { return "pinsrw %Vdq Mw Ib"; } } break; case 0xC5: if (!Osz(x->op.rde)) { return "pextrw %Gdqp %Nq Ib"; } else { return "pextrw %Gdqp %Udq Ib"; } break; case 0xC6: if (!Osz(x->op.rde)) { return "shufps %Vps Wps Ib"; } else { return "shufpd %Vpd Wpd Ib"; } break; case 0xC7: switch (ModrmReg(x->op.rde)) { case 1: if (!isreg) { if (Rexw(x->op.rde)) { return "cmpxchg16b Mdq"; } else { return "cmpxchg8b Mq"; } } else { return UNKNOWN; } break; case 6: if (isreg) { return "rdrand %Rdqp"; } else { return UNKNOWN; } break; case 7: if (isreg) { if (Rep(x->op.rde) == 3) { return "rdpid %Rdqp"; } else { return "rdseed %Rdqp"; } } else { return UNKNOWN; } break; default: return UNKNOWN; } break; case 0xD6: if (Osz(x->op.rde)) { return "movq Wq %Vq"; } else if (Rep(x->op.rde) == 3) { return "movq2dq %Vdq %Nq"; } else if (Rep(x->op.rde) == 2) { return "movq2dq %Pq %Uq"; } break; case 0x12: switch (Rep(x->op.rde) | Osz(x->op.rde)) { case 0: if (isreg) { return "movhlps %Vq %Uq"; } else { return "movlps %Vq Mq"; } break; case 1: return "movlpd %Vq Mq"; case 2: return "movddup %Vq Wq"; case 3: return "movsldup %Vq Wq"; default: unreachable; } break; case 0x13: if (Osz(x->op.rde)) { return "movlpd Mq %Vq"; } else { return "movlps Mq %Vq"; } break; case 0x16: switch (Rep(x->op.rde) | Osz(x->op.rde)) { case 0: if (isreg) { return "movlhps %Vq %Uq"; } else { return "movhps %Vq Mq"; } break; case 1: return "movhpd %Vq Mq"; case 3: return "movshdup %Vq Wq"; default: break; } break; case 0x17: if (Osz(x->op.rde)) { return "movhpd Mq %Vq"; } else { return "movhps Mq %Vq"; } break; case 0x2A: if (Rep(x->op.rde) == 3) { return "cvtsi2ss %Vss Edqp"; } else if (Rep(x->op.rde) == 2) { return "cvtsi2sd %Vsd Edqp"; } else if (Osz(x->op.rde)) { return "cvtpi2pd %Vpd Qpi"; } else { return "cvtpi2ps %Vps Qpi"; } break; case 0x2C: if (Rep(x->op.rde) == 3) { return "cvttss2si %Gdqp Wss"; } else if (Rep(x->op.rde) == 2) { return "cvttsd2si %Gdqp Wsd"; } else if (Osz(x->op.rde)) { return "cvttpd2pi %Ppi Wpd"; } else { return "cvttps2pi %Ppi Wpsq"; } break; case 0x2D: if (Rep(x->op.rde) == 3) { return "cvtss2si %Gdqp Wss"; } else if (Rep(x->op.rde) == 2) { return "cvtsd2si %Gdqp Wsd"; } else if (Osz(x->op.rde)) { return "cvtpd2pi %Ppi Wpd"; } else { return "cvtps2pi %Ppi Wpsq"; } break; case 0x5a: if (Rep(x->op.rde) == 3) { return "cvtss2sd %Vsd Wss"; } else if (Rep(x->op.rde) == 2) { return "cvtsd2ss %Vss Wsd"; } else if (Osz(x->op.rde)) { return "cvtpd2ps %Vps Wpd"; } else { return "cvtps2pd %Vpd Wps"; } break; case 0x5b: if (Rep(x->op.rde) == 3) { return "cvttps2dq %Vdq Wps"; } else if (Osz(x->op.rde)) { return "cvtps2dq %Vdq Wps"; } else { return "cvtdq2ps %Vps Wdq"; } break; case 0x51: if (Rep(x->op.rde) == 3) { return "sqrtss %Vss Wss"; } else if (Rep(x->op.rde) == 2) { return "sqrtsd %Vsd Wsd"; } else if (Osz(x->op.rde)) { return "sqrtpd %Vpd Wpd"; } else { return "sqrtps %Vps Wps"; } break; case 0x6E: if (Osz(x->op.rde)) { if (Rexw(x->op.rde)) { return "movq %Vdq Eqp"; } else { return "movd %Vdq Ed"; } } else { if (Rexw(x->op.rde)) { return "movq %Pq Eqp"; } else { return "movd %Pq Ed"; } } break; case 0x6F: if (Rep(x->op.rde) == 3) { return "movdqu %Vdq Wdq"; } else if (Osz(x->op.rde)) { return "movdqa %Vdq Wdq"; } else { return "movq %Pq Qq"; } break; case 0x7E: if (Rep(x->op.rde) == 3) { return "movq %Vq Wq"; } else if (Osz(x->op.rde)) { if (Rexw(x->op.rde)) { return "movq Eqp %Vdq"; } else { return "movd Ed %Vdq"; } } else { if (Rexw(x->op.rde)) { return "movq Eqp %Pq"; } else { return "movd Ed %Pq"; } } break; case 0x7F: if (Rep(x->op.rde) == 3) { return "movdqu Wdq %Vdq"; } else if (Osz(x->op.rde)) { return "movdqa Wdq %Vdq"; } else { return "movq Qq %Pq"; } break; case 0xE6: if (Rep(x->op.rde) == 2) { return "cvtpd2dq %Vdq Wpd"; } else if (Osz(x->op.rde)) { return "cvttpd2dq %Vdq Wpd"; } else if (Rep(x->op.rde) == 3) { return "cvtdq2pd %Vpd Wdq"; } break; } return UNKNOWN; } const char *DisSpecMap2(struct XedDecodedInst *x, char *p) { switch (x->op.opcode & 0xff) { RCASE(0x00, DisOpPqQqVdqWdq(x, p, "pshufb")); RCASE(0x01, DisOpPqQqVdqWdq(x, p, "phaddw")); RCASE(0x02, DisOpPqQqVdqWdq(x, p, "phaddd")); RCASE(0x03, DisOpPqQqVdqWdq(x, p, "phaddsw")); RCASE(0x04, DisOpPqQqVdqWdq(x, p, "pmaddubsw")); RCASE(0x05, DisOpPqQqVdqWdq(x, p, "phsubw")); RCASE(0x06, DisOpPqQqVdqWdq(x, p, "phsubd")); RCASE(0x07, DisOpPqQqVdqWdq(x, p, "phsubsw")); RCASE(0x08, DisOpPqQqVdqWdq(x, p, "psignb")); RCASE(0x09, DisOpPqQqVdqWdq(x, p, "psignw")); RCASE(0x0A, DisOpPqQqVdqWdq(x, p, "psignd")); RCASE(0x0B, DisOpPqQqVdqWdq(x, p, "pmulhrsw")); RCASE(0x10, "pblendvb %Vdq Wdq"); RCASE(0x14, "blendvps Vps Wps"); RCASE(0x15, "blendvpd Vpd Wpd"); RCASE(0x17, "ptest %Vdq Wdq"); RCASE(0x1C, DisOpPqQqVdqWdq(x, p, "pabsb")); RCASE(0x1D, DisOpPqQqVdqWdq(x, p, "pabsw")); RCASE(0x1E, DisOpPqQqVdqWdq(x, p, "pabsd")); RCASE(0x20, "pmovsxbw %Vdq Mq"); RCASE(0x21, "pmovsxbd %Vdq Md"); RCASE(0x22, "pmovsxbq %Vdq Mw"); RCASE(0x23, "pmovsxwd %Vdq Mq"); RCASE(0x24, "pmovsxwq %Vdq Md"); RCASE(0x25, "pmovsxdq %Vdq Mq"); RCASE(0x28, "pmuldq %Vdq Wdq"); RCASE(0x29, "pcmpeqq %Vdq Wdq"); RCASE(0x2A, "movntdqa %Vdq Mdq"); RCASE(0x2B, "packusdw %Vdq Wdq"); RCASE(0x30, "pmovzxbw %Vdq Mq"); RCASE(0x31, "pmovzxbd %Vdq Md"); RCASE(0x32, "pmovzxbq %Vdq Mw"); RCASE(0x33, "pmovzxwd %Vdq Mq"); RCASE(0x34, "pmovzxwq %Vdq Md"); RCASE(0x35, "pmovzxdq %Vdq Mq"); RCASE(0x37, "pcmpgtq %Vdq Wdq"); RCASE(0x38, "pminsb %Vdq Wdq"); RCASE(0x39, "pminsd %Vdq Wdq"); RCASE(0x3A, "pminuw %Vdq Wdq"); RCASE(0x3B, "pminud %Vdq Wdq"); RCASE(0x3C, "pmaxsb %Vdq Wdq"); RCASE(0x3D, "pmaxsd %Vdq Wdq"); RCASE(0x3E, "pmaxuw %Vdq Wdq"); RCASE(0x3F, "pmaxud %Vdq Wdq"); RCASE(0x40, "pmulld %Vdq Wdq"); RCASE(0x41, "phminposuw %Vdq Wdq"); RCASE(0x80, "invept %Gq Mdq"); RCASE(0x81, "invvpid %Gq Mdq"); case 0xF0: if (Rep(x->op.rde) == 2) { return "crc32 %Gvqp Eb"; } else { return "movbe %Gvqp M"; } break; case 0xF1: if (Rep(x->op.rde) == 2) { return "crc32 %Gvqp Evqp"; } else { return "movbe M %Gvqp"; } break; default: return UNKNOWN; } } const char *DisSpecMap3(struct XedDecodedInst *x, char *p) { switch (x->op.opcode & 0xff) { RCASE(0x0F, DisOpPqQqIbVdqWdqIb(x, p, "palignr")); default: return UNKNOWN; } } const char *DisSpec(struct XedDecodedInst *x, char *p) { switch (x->op.map & 7) { case XED_ILD_MAP0: return DisSpecMap0(x, p); case XED_ILD_MAP1: return DisSpecMap1(x, p); case XED_ILD_MAP2: return DisSpecMap2(x, p); case XED_ILD_MAP3: return DisSpecMap3(x, p); default: return UNKNOWN; } }
34,960
1,117
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/loader.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/elf.h" #include "libc/elf/struct/phdr.h" #include "libc/intrin/bits.h" #include "libc/intrin/popcnt.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/runtime/pc.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/argv.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/loader.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" static void LoadElfLoadSegment(struct Machine *m, void *code, size_t codesize, Elf64_Phdr *phdr) { void *rbss; int64_t align, bsssize; int64_t felf, fstart, fend, vstart, vbss, vend; align = MAX(phdr->p_align, PAGESIZE); if (popcnt(align) != 1) align = 8; CHECK_EQ(0, (phdr->p_vaddr - phdr->p_offset) % align); felf = (int64_t)(intptr_t)code; vstart = ROUNDDOWN(phdr->p_vaddr, align); vbss = ROUNDUP(phdr->p_vaddr + phdr->p_filesz, align); vend = ROUNDUP(phdr->p_vaddr + phdr->p_memsz, align); fstart = felf + ROUNDDOWN(phdr->p_offset, align); fend = felf + phdr->p_offset + phdr->p_filesz; bsssize = vend - vbss; VERBOSEF("LOADELFLOADSEGMENT" " VSTART %#lx VBSS %#lx VEND %#lx" " FSTART %#lx FEND %#lx BSSSIZE %#lx", vstart, vbss, vend, fstart, fend, bsssize); m->brk = MAX(m->brk, vend); CHECK_GE(vend, vstart); CHECK_GE(fend, fstart); CHECK_LE(felf, fstart); CHECK_GE(vstart, -0x800000000000); CHECK_LE(vend, 0x800000000000); CHECK_GE(vend - vstart, fstart - fend); CHECK_LE(phdr->p_filesz, phdr->p_memsz); CHECK_EQ(felf + phdr->p_offset - fstart, phdr->p_vaddr - vstart); CHECK_NE(-1, ReserveVirtual(m, vstart, fend - fstart, PAGE_V | PAGE_RW | PAGE_U | PAGE_RSRV)); VirtualRecv(m, vstart, (void *)fstart, fend - fstart); if (bsssize) CHECK_NE(-1, ReserveVirtual(m, vbss, bsssize, PAGE_V | PAGE_RW | PAGE_U | PAGE_RSRV)); if (phdr->p_memsz - phdr->p_filesz > bsssize) { VirtualSet(m, phdr->p_vaddr + phdr->p_filesz, 0, phdr->p_memsz - phdr->p_filesz - bsssize); } } static void LoadElf(struct Machine *m, struct Elf *elf) { unsigned i; Elf64_Phdr *phdr; m->ip = elf->base = 0x400000 /* elf->ehdr->e_entry */; VERBOSEF("LOADELF ENTRY %012lx", m->ip); for (i = 0; i < elf->ehdr->e_phnum; ++i) { phdr = GetElfSegmentHeaderAddress(elf->ehdr, elf->size, i); switch (phdr->p_type) { case PT_LOAD: elf->base = MIN(elf->base, phdr->p_vaddr); LoadElfLoadSegment(m, elf->ehdr, elf->size, phdr); break; default: break; } } } static void LoadBin(struct Machine *m, intptr_t base, const char *prog, void *code, size_t codesize) { Elf64_Phdr phdr = { .p_type = PT_LOAD, .p_flags = PF_X | PF_R | PF_W, .p_offset = 0, .p_vaddr = base, .p_paddr = base, .p_filesz = codesize, .p_memsz = ROUNDUP(codesize + FRAMESIZE, BIGPAGESIZE), .p_align = PAGESIZE, }; LoadElfLoadSegment(m, code, codesize, &phdr); m->ip = base; } static void BootProgram(struct Machine *m, struct Elf *elf, size_t codesize) { m->ip = 0x7c00; elf->base = 0x7c00; CHECK_NE(-1, ReserveReal(m, 0x00f00000)); bzero(m->real.p, 0x00f00000); Write16(m->real.p + 0x400, 0x3F8); Write16(m->real.p + 0x40E, 0xb0000 >> 4); Write16(m->real.p + 0x413, 0xb0000 / 1024); Write16(m->real.p + 0x44A, 80); Write64(m->cs, 0); Write64(m->dx, 0); memcpy(m->real.p + 0x7c00, elf->map, 512); if (memcmp(elf->map, "\177ELF", 4) == 0) { elf->ehdr = (void *)elf->map; elf->size = codesize; elf->base = elf->ehdr->e_entry; } else { elf->base = 0x7c00; elf->ehdr = NULL; elf->size = 0; } } static int GetElfHeader(char ehdr[hasatleast 64], const char *prog, 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 { WARNF("%s: ape printf elf header too long\n", prog); return -1; } } if (i != 64) { WARNF("%s: ape printf elf header too short\n", prog); return -1; } if (READ32LE(ehdr) != READ32LE("\177ELF")) { WARNF("%s: ape printf elf header didn't have elf magic\n", prog); return -1; } return 0; } WARNF("%s: printf statement not found in first 4096 bytes\n", prog); return -1; } void LoadProgram(struct Machine *m, const char *prog, char **args, char **vars, struct Elf *elf) { int fd; ssize_t rc; int64_t sp; char ehdr[64]; struct stat st; size_t i, mappedsize; DCHECK_NOTNULL(prog); elf->prog = prog; if ((fd = open(prog, O_RDONLY)) == -1 || (fstat(fd, &st) == -1 || !st.st_size)) { fputs(prog, stderr); fputs(": not found\n", stderr); exit(1); } elf->mapsize = st.st_size; CHECK_NE(MAP_FAILED, (elf->map = mmap(NULL, elf->mapsize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0))); CHECK_NE(-1, close(fd)); ResetCpu(m); if ((m->mode & 3) == XED_MODE_REAL) { BootProgram(m, elf, elf->mapsize); } else { sp = 0x800000000000; Write64(m->sp, sp); m->cr3 = AllocateLinearPage(m); CHECK_NE(-1, ReserveVirtual(m, sp - 0x800000, 0x800000, PAGE_V | PAGE_RW | PAGE_U | PAGE_RSRV)); LoadArgv(m, prog, args, vars); if (memcmp(elf->map, "\177ELF", 4) == 0) { elf->ehdr = (void *)elf->map; elf->size = elf->mapsize; LoadElf(m, elf); } else if (READ64LE(elf->map) == READ64LE("MZqFpD='") && !GetElfHeader(ehdr, prog, elf->map)) { memcpy(elf->map, ehdr, 64); elf->ehdr = (void *)elf->map; elf->size = elf->mapsize; LoadElf(m, elf); } else { elf->base = IMAGE_BASE_VIRTUAL; elf->ehdr = NULL; elf->size = 0; LoadBin(m, elf->base, prog, elf->map, elf->mapsize); } } }
8,490
228
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/elfwriter.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ELFWRITER_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ELFWRITER_H_ #include "libc/calls/struct/timespec.h" #include "libc/elf/struct/ehdr.h" #include "libc/elf/struct/rela.h" #include "libc/elf/struct/shdr.h" #include "libc/elf/struct/sym.h" #include "tool/build/lib/interner.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct ElfWriterSyms { size_t i, n; Elf64_Sym *p; }; enum ElfWriterSymOrder { kElfWriterSymSection, kElfWriterSymLocal, kElfWriterSymGlobal }; struct ElfWriterSymRef { int slg; uint32_t sym; }; struct ElfWriterRela { uint64_t offset; struct ElfWriterSymRef symkey; uint32_t type; int64_t addend; }; struct ElfWriter { char *path; int fd; void *map; size_t mapsize; size_t wrote; size_t entsize; size_t addralign; struct Elf64_Ehdr *ehdr; struct { size_t i, n; Elf64_Shdr *p; } shdrs[1]; struct ElfWriterSyms syms[3][1]; struct { size_t i, j, n; struct ElfWriterRela *p; } relas[1]; struct Interner *strtab; struct Interner *shstrtab; }; struct ElfWriter *elfwriter_open(const char *, int) dontdiscard; void elfwriter_cargoculting(struct ElfWriter *); void elfwriter_close(struct ElfWriter *); void elfwriter_align(struct ElfWriter *, size_t, size_t); size_t elfwriter_startsection(struct ElfWriter *, const char *, int, int); void *elfwriter_reserve(struct ElfWriter *, size_t); void elfwriter_commit(struct ElfWriter *, size_t); void elfwriter_finishsection(struct ElfWriter *); void elfwriter_appendrela(struct ElfWriter *, uint64_t, struct ElfWriterSymRef, uint32_t, int64_t); uint32_t elfwriter_relatype_abs32(const struct ElfWriter *); struct ElfWriterSymRef elfwriter_linksym(struct ElfWriter *, const char *, int, int); struct ElfWriterSymRef elfwriter_appendsym(struct ElfWriter *, const char *, int, int, size_t, size_t); void elfwriter_yoink(struct ElfWriter *, const char *, int); void elfwriter_setsection(struct ElfWriter *, struct ElfWriterSymRef, uint16_t); void elfwriter_zip(struct ElfWriter *, const char *, const char *, size_t, const void *, size_t, uint32_t, struct timespec, struct timespec, struct timespec, bool, uint64_t, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ELFWRITER_H_ */
2,470
81
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/bcd.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/lib/alu.h" #include "tool/build/lib/bcd.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/throw.h" relegated void OpDas(struct Machine *m, uint32_t rde) { uint8_t al, af, cf; af = cf = 0; al = m->ax[0]; if ((al & 0x0f) > 9 || GetFlag(m->flags, FLAGS_AF)) { cf = m->ax[0] < 6 || GetFlag(m->flags, FLAGS_CF); m->ax[0] -= 0x06; af = 1; } if (al > 0x99 || GetFlag(m->flags, FLAGS_CF)) { m->ax[0] -= 0x60; cf = 1; } AluFlags8(m->ax[0], af, &m->flags, 0, cf); } relegated void OpAaa(struct Machine *m, uint32_t rde) { uint8_t af, cf; af = cf = 0; if ((m->ax[0] & 0x0f) > 9 || GetFlag(m->flags, FLAGS_AF)) { cf = m->ax[0] < 6 || GetFlag(m->flags, FLAGS_CF); Write16(m->ax, Read16(m->ax) + 0x106); af = cf = 1; } m->ax[0] &= 0x0f; AluFlags8(m->ax[0], af, &m->flags, 0, cf); } relegated void OpAas(struct Machine *m, uint32_t rde) { uint8_t af, cf; af = cf = 0; if ((m->ax[0] & 0x0f) > 9 || GetFlag(m->flags, FLAGS_AF)) { cf = m->ax[0] < 6 || GetFlag(m->flags, FLAGS_CF); Write16(m->ax, Read16(m->ax) - 0x106); af = cf = 1; } m->ax[0] &= 0x0f; AluFlags8(m->ax[0], af, &m->flags, 0, cf); } relegated void OpAam(struct Machine *m, uint32_t rde) { uint8_t i = m->xedd->op.uimm0; if (!i) ThrowDivideError(m); m->ax[1] = m->ax[0] / i; m->ax[0] = m->ax[0] % i; AluFlags8(m->ax[0], 0, &m->flags, 0, 0); } relegated void OpAad(struct Machine *m, uint32_t rde) { uint8_t i = m->xedd->op.uimm0; Write16(m->ax, (m->ax[1] * i + m->ax[0]) & 0xff); AluFlags8(m->ax[0], 0, &m->flags, 0, 0); }
3,478
78
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stripcomponents.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/stripcomponents.h" /** * Strips leading directory components. * * The basename is never stripped. */ char *StripComponents(const char *path, int n) { const char *p; while (n-- > 0) { for (p = path; *p; ++p) { if (*p == '/') { path = p + 1; break; } } } return (char *)path; }
2,186
38
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/ldbl.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/macros.internal.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/ldbl.h" #include "tool/build/lib/pun.h" uint8_t *SerializeLdbl(uint8_t b[10], double f) { int e; union DoublePun u = {f}; e = (u.i >> 52) & 0x7ff; if (!e) { e = 0; } else if (e == 0x7ff) { e = 0x7fff; } else { e -= 0x3ff; e += 0x3fff; } Write16(b + 8, e | u.i >> 63 << 15); Write64(b, (u.i & 0x000fffffffffffff) << 11 | (uint64_t) !!u.f << 63); return b; } double DeserializeLdbl(const uint8_t b[10]) { union DoublePun u; u.i = (uint64_t)(MAX(-1023, MIN(1024, ((Read16(b + 8) & 0x7fff) - 0x3fff))) + 1023) << 52 | ((Read64(b) & 0x7fffffffffffffff) + (1 << (11 - 1))) >> 11 | (uint64_t)(b[9] >> 7) << 63; return u.f; }
2,639
50
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/debug.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/elf.h" #include "libc/log/check.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/x.h" #include "tool/build/lib/loader.h" void LoadDebugSymbols(struct Elf *elf) { int fd; size_t n; void *elfmap; struct stat st; const char *path; if (elf->ehdr && GetElfSymbolTable(elf->ehdr, elf->size, &n) && n) return; DCHECK_NOTNULL(elf->prog); if ((fd = open(xstrcat(elf->prog, ".dbg"), O_RDONLY)) != -1) { if (fstat(fd, &st) != -1 && (elfmap = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != MAP_FAILED) { elf->ehdr = elfmap; elf->size = st.st_size; } close(fd); } }
2,654
48
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/persist.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/iovec.h" #include "libc/intrin/bsr.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/sock/sock.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/x/x.h" #include "tool/build/lib/persist.h" static bool IsWithin(size_t sz1, void *vp1, size_t sz2, void *vp2) { char *p1 = vp1, *p2 = vp2; return p1 >= p2 && p1 + sz1 <= p2 + sz2; } static bool IsOverlapping(void *vx1, void *vy1, void *vx2, void *vy2) { char *x1 = vx1, *y1 = vy1, *x2 = vx2, *y2 = vy2; return (x1 >= x2 && x1 <= y2) || (y1 >= x2 && y1 <= y2); } static bool IsOverlappingIov(struct iovec *a, struct iovec *b) { char *ap = a->iov_base, *bp = b->iov_base; return IsOverlapping(ap, ap + a->iov_len, bp, bp + b->iov_len); } /** * Writes struct w/ dynamic arrays to mappable file, e.g. * * PersistObject(path, 64, &(struct ObjectParam){ * sizeof(*o), o, &o->magic, &o->abi, * &(struct ObjectArrayParam){ * {&o->a1.i, sizeof(o->a1.p[0]), &o->a1.p}, * {&o->a2.i, sizeof(o->a2.p[0]), &o->a2.p}, * {0}, * }}); * * @param obj->magic needs to be unique for struct * @param obj->abi monotonically tracks breaking changes * @param obj->arrays needs sentinel with item size of zero * @note non-recursive i.e. array elements can't have pointers * @see MapObject() */ void PersistObject(const char *path, size_t align, const struct ObjectParam *obj) { const char *pad; struct iovec *iov; int i, n, fd, iovlen; long len, size, bytes, filesize; unsigned char *hdr, *p1, *p2, **pp; intptr_t arrayptroffset, arraydataoffset; filesize = 0; DCHECK_GE(align, 1); CHECK_GT(*obj->magic, 0); CHECK_GT(*obj->abi, 0); CHECK(IsWithin(sizeof(*obj->magic), obj->magic, obj->size, obj->p)); CHECK(IsWithin(sizeof(*obj->abi), obj->abi, obj->size, obj->p)); for (n = i = 0; obj->arrays[i].size; ++i) ++n; iovlen = (n + 1) * 2; pad = _gc(xcalloc(align, 1)); hdr = _gc(xmalloc(obj->size)); iov = _gc(xcalloc(iovlen, sizeof(*iov))); bytes = obj->size; iov[0].iov_base = memcpy(hdr, obj->p, obj->size); iov[0].iov_len = bytes; iov[1].iov_base = pad; iov[1].iov_len = ROUNDUP(bytes, align) - bytes; filesize += ROUNDUP(bytes, align); for (i = 0; i < n; ++i) { pp = obj->arrays[i].pp; len = obj->arrays[i].len; size = obj->arrays[i].size; if (!*pp || !len) continue; p1 = obj->p; p2 = obj->arrays[i].pp; arrayptroffset = p2 - p1; arraydataoffset = filesize; CHECK((!len || _bsrl(len) + _bsrl(size) < 31), "path=%s i=%d len=%,lu size=%,lu", path, i, len, size); CHECK(IsWithin(sizeof(void *), pp, obj->size, obj->p)); CHECK(!IsOverlapping(pp, pp + sizeof(void *), obj->magic, obj->magic + sizeof(*obj->magic))); CHECK(!IsOverlapping(pp, pp + sizeof(void *), obj->abi, obj->abi + sizeof(*obj->abi))); memcpy(hdr + arrayptroffset, &arraydataoffset, sizeof(intptr_t)); CHECK_LT(filesize + arraydataoffset, 0x7ffff000); bytes = len * size; iov[(i + 1) * 2 + 0].iov_base = *pp; iov[(i + 1) * 2 + 0].iov_len = bytes; iov[(i + 1) * 2 + 1].iov_base = pad; iov[(i + 1) * 2 + 1].iov_len = ROUNDUP(bytes, align) - bytes; filesize += ROUNDUP(bytes, align); CHECK(!IsOverlappingIov(&iov[(i + 0) * 2], &iov[(i + 1) * 2]), "iov[%d]={%#p,%#x}, iov[%d]={%#p,%#x} path=%s", (i + 0) * 2, iov[(i + 0) * 2].iov_base, iov[(i + 0) * 2].iov_len, (i + 1) * 2, iov[(i + 1) * 2].iov_base, iov[(i + 1) * 2].iov_len, path); } CHECK_NE(-1, (fd = creat(path, 0644)), "%s", path); CHECK_EQ(filesize, writev(fd, iov, iovlen)); CHECK_NE(-1, close(fd)); }
5,647
121
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/case.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_CASE_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_CASE_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) #define CASE(OP, CODE) \ case OP: \ CODE; \ break #define CASR(OP, CODE) \ case OP: \ CODE; \ return #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_CASE_H_ */
396
17
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pun.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PUN_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PUN_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ union FloatPun { float f; uint32_t i; }; union DoublePun { double f; uint64_t i; }; union FloatVectorPun { union FloatPun u[4]; float f[4]; }; union DoubleVectorPun { union DoublePun u[2]; double f[2]; }; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PUN_H_ */
487
29
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/stripcomponents.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_STRIPCOMPONENTS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_STRIPCOMPONENTS_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ char *StripComponents(const char *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_STRIPCOMPONENTS_H_ */
341
11
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/divmul.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_DIVMUL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_DIVMUL_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpDivAlAhAxEbSigned(struct Machine *, uint32_t); void OpDivAlAhAxEbUnsigned(struct Machine *, uint32_t); void OpDivRdxRaxEvqpSigned(struct Machine *, uint32_t); void OpDivRdxRaxEvqpUnsigned(struct Machine *, uint32_t); void OpImulGvqpEvqp(struct Machine *, uint32_t); void OpImulGvqpEvqpImm(struct Machine *, uint32_t); void OpMulAxAlEbSigned(struct Machine *, uint32_t); void OpMulAxAlEbUnsigned(struct Machine *, uint32_t); void OpMulRdxRaxEvqpSigned(struct Machine *, uint32_t); void OpMulRdxRaxEvqpUnsigned(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_DIVMUL_H_ */
853
21
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/flags.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_FLAGS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_FLAGS_H_ #include "tool/build/lib/machine.h" #define FLAGS_CF 0 #define FLAGS_VF 1 #define FLAGS_PF 2 #define FLAGS_F1 3 #define FLAGS_AF 4 #define FLAGS_KF 5 #define FLAGS_ZF 6 #define FLAGS_SF 7 #define FLAGS_TF 8 #define FLAGS_IF 9 #define FLAGS_DF 10 #define FLAGS_OF 11 #define FLAGS_IOPL 12 #define FLAGS_NT 14 #define FLAGS_F0 15 #define FLAGS_RF 16 #define FLAGS_VM 17 #define FLAGS_AC 18 #define FLAGS_VIF 19 #define FLAGS_VIP 20 #define FLAGS_ID 21 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define GetLazyParityBool(f) GetParity((f) >> 24) #define SetLazyParityByte(f, x) (((f) & ~0xFF000000u) | ((x)&0xFFu) << 24) #define GetFlag(FLAGS, BIT) \ ({ \ autotype(FLAGS) Flags = (FLAGS); \ typeof(Flags) IsSet; \ switch (BIT) { \ case FLAGS_PF: \ IsSet = GetLazyParityBool(Flags); \ break; \ default: \ IsSet = (Flags >> (BIT)) & 1; \ break; \ } \ IsSet; \ }) #define SetFlag(FLAGS, BIT, VAL) \ ({ \ autotype(FLAGS) Flags = (FLAGS); \ typeof(Flags) Val = (VAL); \ typeof(Flags) One = 1; \ switch (BIT) { \ case FLAGS_PF: \ Flags = SetLazyParityByte(Flags, !Val); \ break; \ default: \ Flags = (Flags & ~(One << (BIT))) | Val << (BIT); \ break; \ } \ Flags; \ }) bool GetParity(uint8_t); uint64_t ExportFlags(uint64_t); void ImportFlags(struct Machine *, uint64_t); int64_t AluFlags(uint64_t, uint32_t, uint32_t *, uint32_t, uint32_t, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_FLAGS_H_ */
2,495
72
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/dis.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_DIS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_DIS_H_ #include "third_party/xed/x86.h" #include "tool/build/lib/loader.h" #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define DIS_MAX_SYMBOL_LENGTH 32 struct Dis { struct DisOps { size_t i, n; struct DisOp { int64_t addr; uint8_t size; bool active; char *s; } * p; } ops; struct DisLoads { size_t i, n; struct DisLoad { int64_t addr; uint64_t size; bool istext; } * p; } loads; struct DisSyms { size_t i, n; struct DisSym { int64_t addr; int unique; int size; int name; char rank; bool iscode; bool isabs; } * p; const char *stab; } syms; struct DisEdges { size_t i, n; struct DisEdge { int64_t src; int64_t dst; } * p; } edges; struct XedDecodedInst xedd[1]; struct Machine *m; /* for the segment registers */ uint64_t addr; /* current effective address */ char buf[512]; }; extern bool g_disisprog_disable; long Dis(struct Dis *, struct Machine *, uint64_t, uint64_t, int); long DisFind(struct Dis *, int64_t); void DisFree(struct Dis *); void DisFreeOp(struct DisOp *); void DisFreeOps(struct DisOps *); void DisLoadElf(struct Dis *, struct Elf *); long DisFindSym(struct Dis *, int64_t); long DisFindSymByName(struct Dis *, const char *); bool DisIsText(struct Dis *, int64_t); bool DisIsProg(struct Dis *, int64_t); char *DisInst(struct Dis *, char *, const char *); char *DisArg(struct Dis *, char *, const char *); const char *DisSpec(struct XedDecodedInst *, char *); const char *DisGetLine(struct Dis *, struct Machine *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_DIS_H_ */
1,868
75
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/clmul.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_CLMUL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_CLMUL_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpSsePclmulqdq(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_CLMUL_H_ */
354
12
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/buffer.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_BUFFER_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_BUFFER_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Buffer { unsigned i, n; char *p; }; void AppendChar(struct Buffer *, char); void AppendData(struct Buffer *, char *, unsigned); void AppendStr(struct Buffer *, const char *); void AppendWide(struct Buffer *, wint_t); int AppendFmt(struct Buffer *, const char *, ...); ssize_t WriteBuffer(struct Buffer *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_BUFFER_H_ */
595
21
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/disinst.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/str/str.h" #include "tool/build/lib/dis.h" #include "tool/build/lib/high.h" #include "tool/build/lib/modrm.h" static const char kJcxz[3][6] = {"jcxz", "jecxz", "jrcxz"}; static const char kAluOp[8][4] = {"add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"}; static const char kBitOp[8][4] = {"rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"}; static const char kCc[16][3] = {"o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"}; static bool IsProbablyByteOp(struct XedDecodedInst *x) { return !(x->op.opcode & 1); } static int IsRepOpcode(struct Dis *d) { switch (d->xedd->op.opcode & ~1) { case 0x6C: // INS return 1; case 0x6E: // OUTS return 1; case 0xA4: // MOVS return 1; case 0xAA: // STOS return 1; case 0xAC: // LODS return 1; case 0xA6: // CMPS return 2; case 0xAE: // SCAS return 2; default: return 0; } } static char *DisRepPrefix(struct Dis *d, char *p) { const char *s; if (Rep(d->xedd->op.rde) && d->xedd->op.map == XED_ILD_MAP0) { switch (IsRepOpcode(d)) { case 0: break; case 1: p = stpcpy(p, "rep "); break; case 2: p = stpcpy(p, Rep(d->xedd->op.rde) == 2 ? "repnz " : "repz "); break; default: break; } } return p; } static char *DisBranchTaken(struct Dis *d, char *p) { switch (d->xedd->op.hint) { case XED_HINT_NTAKEN: return stpcpy(p, ",pn"); case XED_HINT_TAKEN: return stpcpy(p, ",pt"); default: return p; } } static char *DisName(struct Dis *d, char *bp, const char *name, bool ambiguous) { char *p, *np; uint32_t rde; bool notbyte, notlong, wantsuffix, wantsuffixsd; p = bp; rde = d->xedd->op.rde; if (d->xedd->op.lock) p = stpcpy(p, "lock "); p = DisRepPrefix(d, p); if (strcmp(name, "BIT") == 0) { p = stpcpy(p, kBitOp[ModrmReg(rde)]); } else if (strcmp(name, "nop") == 0 && d->xedd->op.rep) { p = stpcpy(p, "pause"); } else if (strcmp(name, "CALL") == 0) { p = stpcpy(p, "call"); } else if (strcmp(name, "JMP") == 0) { p = stpcpy(p, "jmp"); } else if (strcmp(name, "jcxz") == 0) { p = stpcpy(p, kJcxz[Eamode(rde)]); p = DisBranchTaken(d, p); } else if (strcmp(name, "loop") == 0 || strcmp(name, "loope") == 0 || strcmp(name, "loopne") == 0) { p = stpcpy(p, name); if (Eamode(rde) != Mode(rde)) { *p++ = "wl"[Eamode(rde)]; *p = '\0'; } p = DisBranchTaken(d, p); } else if (strcmp(name, "cwtl") == 0) { if (Osz(rde)) name = "cbtw"; if (Rexw(rde)) name = "cltq"; p = stpcpy(p, name); } else if (strcmp(name, "cltd") == 0) { if (Osz(rde)) name = "cwtd"; if (Rexw(rde)) name = "cqto"; p = stpcpy(p, name); } else { notbyte = false; notlong = false; wantsuffix = false; wantsuffixsd = false; for (np = name; *np && (islower(*np) || isdigit(*np)); ++np) { *p++ = *np; } if (strcmp(name, "ALU") == 0) { p = stpcpy(p, kAluOp[(d->xedd->op.opcode & 070) >> 3]); } else if (strcmp(name, "ALU2") == 0) { p = stpcpy(p, kAluOp[ModrmReg(rde)]); } else if (strcmp(np, "WLQ") == 0) { notbyte = true; wantsuffix = true; } else if (strcmp(np, "CC") == 0) { p = stpcpy(p, kCc[d->xedd->op.opcode & 15]); p = DisBranchTaken(d, p); } else if (strcmp(np, "WQ") == 0) { notbyte = true; notlong = Eamode(rde) != XED_MODE_REAL; wantsuffix = true; } else if (strcmp(np, "LQ") == 0 || strcmp(np, "WL") == 0) { notbyte = true; wantsuffix = true; } else if (strcmp(np, "SD") == 0) { notbyte = true; wantsuffixsd = true; } else if (strcmp(np, "ABS") == 0) { if (Rexw(rde)) p = stpcpy(p, "abs"); } if (wantsuffixsd) { if (Osz(rde)) { *p++ = 'd'; } else { *p++ = 's'; } } else if (wantsuffix || (ambiguous && !_startswith(name, "f") && !_startswith(name, "set"))) { if (Osz(rde)) { if (ambiguous || Mode(rde) != XED_MODE_REAL) { *p++ = 'w'; } } else if (Rexw(rde)) { *p++ = 'q'; } else if (ambiguous && !notbyte && IsProbablyByteOp(d->xedd)) { *p++ = 'b'; } else if (!notlong) { *p++ = 'l'; } } } *p++ = ' '; while (p - bp < 8) *p++ = ' '; *p = '\0'; return p; } /** * Disassembles instruction based on string spec. * @see DisSpec() */ char *DisInst(struct Dis *d, char *p, const char *spec) { long i, n; char sbuf[64]; char args[4][256]; char *s, *name, *state; bool hasarg, hasmodrm, hasregister, hasmemory; CHECK_EQ(0, (int)d->xedd->op.error); DCHECK_LT(strlen(spec), 128); hasarg = false; hasmodrm = d->xedd->op.has_modrm; hasmemory = hasmodrm && !IsModrmRegister(d->xedd->op.rde); hasregister = hasmodrm && IsModrmRegister(d->xedd->op.rde); name = strtok_r(strcpy(sbuf, spec), " ", &state); for (n = 0; (s = strtok_r(NULL, " ", &state)); ++n) { hasarg = true; hasregister |= *s == '%'; hasmemory |= *s == 'O'; CHECK_LT(DisArg(d, args[n], s) - args[n], sizeof(args[n])); } p = HighStart(p, g_high.keyword); p = DisName(d, p, name, hasarg && !hasregister && hasmemory); p = HighEnd(p); for (i = 0; i < n; ++i) { if (i && args[n - i][0]) { *p++ = ','; } p = stpcpy(p, args[n - i - 1]); } return p; }
7,475
216
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pty.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PTY_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PTY_H_ #include "tool/build/lib/buffer.h" #define kPtyFg 0x0001 #define kPtyBg 0x0002 #define kPtyBold 0x0004 #define kPtyFlip 0x0008 #define kPtyFaint 0x0010 #define kPtyUnder 0x0020 #define kPtyDunder 0x0040 #define kPtyTrue 0x0080 #define kPtyBlink 0x0100 #define kPtyItalic 0x0200 #define kPtyFraktur 0x0400 #define kPtyStrike 0x0800 #define kPtyConceal 0x1000 #define kPtyBell 0x001 #define kPtyRedzone 0x002 #define kPtyNocursor 0x004 #define kPtyBlinkcursor 0x008 #define kPtyNocanon 0x010 #define kPtyNoecho 0x020 #define kPtyNoopost 0x040 #define kPtyLed1 0x080 #define kPtyLed2 0x100 #define kPtyLed3 0x200 #define kPtyLed4 0x400 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Pty { int y; int x; int yn; int xn; uint32_t u8; uint32_t n8; uint32_t pr; uint32_t fg; uint32_t bg; uint32_t conf; uint32_t save; uint32_t *wcs; uint32_t *prs; uint32_t *fgs; uint32_t *bgs; wchar_t *xlat; enum PtyState { kPtyAscii, kPtyUtf8, kPtyEsc, kPtyCsi, } state; struct PtyEsc { unsigned i; char s[64]; } esc; struct PtyInput { size_t i, n; char *p; } input; }; void FreePty(struct Pty *); struct Pty *NewPty(void) dontdiscard; void PtyResize(struct Pty *, int, int); ssize_t PtyRead(struct Pty *, void *, size_t); ssize_t PtyWrite(struct Pty *, const void *, size_t); ssize_t PtyWriteInput(struct Pty *, const void *, size_t); int PtyAppendLine(struct Pty *, struct Buffer *, unsigned); void PtyFullReset(struct Pty *); void PtyMemmove(struct Pty *, long, long, long); void PtyErase(struct Pty *, long, long); void PtySetY(struct Pty *, int); void PtySetX(struct Pty *, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PTY_H_ */
1,950
83
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cvt.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/str/str.h" #include "tool/build/lib/cvt.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/fpu.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/pun.h" #include "tool/build/lib/throw.h" #define kOpCvt0f2a 0 #define kOpCvtt0f2c 4 #define kOpCvt0f2d 8 #define kOpCvt0f5a 12 #define kOpCvt0f5b 16 #define kOpCvt0fE6 20 static double SseRoundDouble(struct Machine *m, double x) { switch ((m->mxcsr & kMxcsrRc) >> 13) { case 0: return rint(x); case 1: return floor(x); case 2: return ceil(x); case 3: return trunc(x); default: for (;;) (void)0; } } static void OpGdqpWssCvttss2si(struct Machine *m, uint32_t rde) { int64_t n; union FloatPun f; f.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); n = f.f; if (!Rexw(rde)) n &= 0xffffffff; Write64(RegRexrReg(m, rde), n); } static void OpGdqpWsdCvttsd2si(struct Machine *m, uint32_t rde) { int64_t n; union DoublePun d; d.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); n = d.f; if (!Rexw(rde)) n &= 0xffffffff; Write64(RegRexrReg(m, rde), n); } static void OpGdqpWssCvtss2si(struct Machine *m, uint32_t rde) { int64_t n; union FloatPun f; f.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); n = rintf(f.f); if (!Rexw(rde)) n &= 0xffffffff; Write64(RegRexrReg(m, rde), n); } static void OpGdqpWsdCvtsd2si(struct Machine *m, uint32_t rde) { int64_t n; union DoublePun d; d.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); n = SseRoundDouble(m, d.f); if (!Rexw(rde)) n &= 0xffffffff; Write64(RegRexrReg(m, rde), n); } static void OpVssEdqpCvtsi2ss(struct Machine *m, uint32_t rde) { union FloatPun f; if (Rexw(rde)) { int64_t n; n = Read64(GetModrmRegisterWordPointerRead8(m, rde)); f.f = n; Write32(XmmRexrReg(m, rde), f.i); } else { int32_t n; n = Read32(GetModrmRegisterWordPointerRead4(m, rde)); f.f = n; Write32(XmmRexrReg(m, rde), f.i); } } static void OpVsdEdqpCvtsi2sd(struct Machine *m, uint32_t rde) { union DoublePun d; if (Rexw(rde)) { int64_t n; n = Read64(GetModrmRegisterWordPointerRead8(m, rde)); d.f = n; Write64(XmmRexrReg(m, rde), d.i); } else { int32_t n; n = Read32(GetModrmRegisterWordPointerRead4(m, rde)); d.f = n; Write64(XmmRexrReg(m, rde), d.i); } } static void OpVpsQpiCvtpi2ps(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t i[2]; union FloatPun f[2]; p = GetModrmRegisterMmPointerRead8(m, rde); i[0] = Read32(p + 0); i[1] = Read32(p + 4); f[0].f = i[0]; f[1].f = i[1]; Write32(XmmRexrReg(m, rde) + 0, f[0].i); Write32(XmmRexrReg(m, rde) + 4, f[1].i); } static void OpVpdQpiCvtpi2pd(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[2]; union DoublePun f[2]; p = GetModrmRegisterMmPointerRead8(m, rde); n[0] = Read32(p + 0); n[1] = Read32(p + 4); f[0].f = n[0]; f[1].f = n[1]; Write64(XmmRexrReg(m, rde) + 0, f[0].i); Write64(XmmRexrReg(m, rde) + 8, f[1].i); } static void OpPpiWpsqCvtps2pi(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned i; int32_t n[2]; union FloatPun f[2]; p = GetModrmRegisterXmmPointerRead8(m, rde); f[0].i = Read32(p + 0 * 4); f[1].i = Read32(p + 1 * 4); switch ((m->mxcsr & kMxcsrRc) >> 13) { case 0: for (i = 0; i < 2; ++i) n[i] = rintf(f[i].f); break; case 1: for (i = 0; i < 2; ++i) n[i] = floorf(f[i].f); break; case 2: for (i = 0; i < 2; ++i) n[i] = ceilf(f[i].f); break; case 3: for (i = 0; i < 2; ++i) n[i] = truncf(f[i].f); break; default: for (;;) (void)0; } Write32(MmReg(m, rde) + 0, n[0]); Write32(MmReg(m, rde) + 4, n[1]); } static void OpPpiWpsqCvttps2pi(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[2]; union FloatPun f[2]; p = GetModrmRegisterXmmPointerRead8(m, rde); f[0].i = Read32(p + 0); f[1].i = Read32(p + 4); n[0] = f[0].f; n[1] = f[1].f; Write32(MmReg(m, rde) + 0, n[0]); Write32(MmReg(m, rde) + 4, n[1]); } static void OpPpiWpdCvtpd2pi(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned i; int32_t n[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); d[0].i = Read64(p + 0); d[1].i = Read64(p + 8); for (i = 0; i < 2; ++i) n[i] = SseRoundDouble(m, d[i].f); Write32(MmReg(m, rde) + 0, n[0]); Write32(MmReg(m, rde) + 4, n[1]); } static void OpPpiWpdCvttpd2pi(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); d[0].i = Read64(p + 0); d[1].i = Read64(p + 8); n[0] = d[0].f; n[1] = d[1].f; Write32(MmReg(m, rde) + 0, n[0]); Write32(MmReg(m, rde) + 4, n[1]); } static void OpVpdWpsCvtps2pd(struct Machine *m, uint32_t rde) { uint8_t *p; union FloatPun f[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead8(m, rde); f[0].i = Read32(p + 0); f[1].i = Read32(p + 4); d[0].f = f[0].f; d[1].f = f[1].f; Write64(XmmRexrReg(m, rde) + 0, d[0].i); Write64(XmmRexrReg(m, rde) + 8, d[1].i); } static void OpVpsWpdCvtpd2ps(struct Machine *m, uint32_t rde) { uint8_t *p; union FloatPun f[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); d[0].i = Read64(p + 0); d[1].i = Read64(p + 8); f[0].f = d[0].f; f[1].f = d[1].f; Write32(XmmRexrReg(m, rde) + 0, f[0].i); Write32(XmmRexrReg(m, rde) + 4, f[1].i); } static void OpVssWsdCvtsd2ss(struct Machine *m, uint32_t rde) { union FloatPun f; union DoublePun d; d.i = Read64(GetModrmRegisterXmmPointerRead8(m, rde)); f.f = d.f; Write32(XmmRexrReg(m, rde), f.i); } static void OpVsdWssCvtss2sd(struct Machine *m, uint32_t rde) { union FloatPun f; union DoublePun d; f.i = Read32(GetModrmRegisterXmmPointerRead4(m, rde)); d.f = f.f; Write64(XmmRexrReg(m, rde), d.i); } static void OpVpsWdqCvtdq2ps(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[4]; union FloatPun f[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); n[0] = Read32(p + 0 * 4); n[1] = Read32(p + 1 * 4); n[2] = Read32(p + 2 * 4); n[3] = Read32(p + 3 * 4); f[0].f = n[0]; f[1].f = n[1]; f[2].f = n[2]; f[3].f = n[3]; Write32(XmmRexrReg(m, rde) + 0 * 4, f[0].i); Write32(XmmRexrReg(m, rde) + 1 * 4, f[1].i); Write32(XmmRexrReg(m, rde) + 2 * 4, f[2].i); Write32(XmmRexrReg(m, rde) + 3 * 4, f[3].i); } static void OpVpdWdqCvtdq2pd(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead8(m, rde); n[0] = Read32(p + 0 * 4); n[1] = Read32(p + 1 * 4); d[0].f = n[0]; d[1].f = n[1]; Write64(XmmRexrReg(m, rde) + 0, d[0].i); Write64(XmmRexrReg(m, rde) + 8, d[1].i); } static void OpVdqWpsCvttps2dq(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[4]; union FloatPun f[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); f[0].i = Read32(p + 0 * 4); f[1].i = Read32(p + 1 * 4); f[2].i = Read32(p + 2 * 4); f[3].i = Read32(p + 3 * 4); n[0] = f[0].f; n[1] = f[1].f; n[2] = f[2].f; n[3] = f[3].f; Write32(XmmRexrReg(m, rde) + 0 * 4, n[0]); Write32(XmmRexrReg(m, rde) + 1 * 4, n[1]); Write32(XmmRexrReg(m, rde) + 2 * 4, n[2]); Write32(XmmRexrReg(m, rde) + 3 * 4, n[3]); } static void OpVdqWpsCvtps2dq(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned i; int32_t n[4]; union FloatPun f[4]; p = GetModrmRegisterXmmPointerRead16(m, rde); f[0].i = Read32(p + 0 * 4); f[1].i = Read32(p + 1 * 4); f[2].i = Read32(p + 2 * 4); f[3].i = Read32(p + 3 * 4); switch ((m->mxcsr & kMxcsrRc) >> 13) { case 0: for (i = 0; i < 4; ++i) n[i] = rintf(f[i].f); break; case 1: for (i = 0; i < 4; ++i) n[i] = floorf(f[i].f); break; case 2: for (i = 0; i < 4; ++i) n[i] = ceilf(f[i].f); break; case 3: for (i = 0; i < 4; ++i) n[i] = truncf(f[i].f); break; default: for (;;) (void)0; } Write32(XmmRexrReg(m, rde) + 0 * 4, n[0]); Write32(XmmRexrReg(m, rde) + 1 * 4, n[1]); Write32(XmmRexrReg(m, rde) + 2 * 4, n[2]); Write32(XmmRexrReg(m, rde) + 3 * 4, n[3]); } static void OpVdqWpdCvttpd2dq(struct Machine *m, uint32_t rde) { uint8_t *p; int32_t n[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); d[0].i = Read64(p + 0); d[1].i = Read64(p + 8); n[0] = d[0].f; n[1] = d[1].f; Write32(XmmRexrReg(m, rde) + 0, n[0]); Write32(XmmRexrReg(m, rde) + 4, n[1]); } static void OpVdqWpdCvtpd2dq(struct Machine *m, uint32_t rde) { uint8_t *p; unsigned i; int32_t n[2]; union DoublePun d[2]; p = GetModrmRegisterXmmPointerRead16(m, rde); d[0].i = Read64(p + 0); d[1].i = Read64(p + 8); for (i = 0; i < 2; ++i) n[i] = SseRoundDouble(m, d[i].f); Write32(XmmRexrReg(m, rde) + 0, n[0]); Write32(XmmRexrReg(m, rde) + 4, n[1]); } static void OpCvt(struct Machine *m, uint32_t rde, unsigned long op) { switch (op | Rep(rde) | Osz(rde)) { case kOpCvt0f2a + 0: OpVpsQpiCvtpi2ps(m, rde); break; case kOpCvt0f2a + 1: OpVpdQpiCvtpi2pd(m, rde); break; case kOpCvt0f2a + 2: OpVsdEdqpCvtsi2sd(m, rde); break; case kOpCvt0f2a + 3: OpVssEdqpCvtsi2ss(m, rde); break; case kOpCvtt0f2c + 0: OpPpiWpsqCvttps2pi(m, rde); break; case kOpCvtt0f2c + 1: OpPpiWpdCvttpd2pi(m, rde); break; case kOpCvtt0f2c + 2: OpGdqpWsdCvttsd2si(m, rde); break; case kOpCvtt0f2c + 3: OpGdqpWssCvttss2si(m, rde); break; case kOpCvt0f2d + 0: OpPpiWpsqCvtps2pi(m, rde); break; case kOpCvt0f2d + 1: OpPpiWpdCvtpd2pi(m, rde); break; case kOpCvt0f2d + 2: OpGdqpWsdCvtsd2si(m, rde); break; case kOpCvt0f2d + 3: OpGdqpWssCvtss2si(m, rde); break; case kOpCvt0f5a + 0: OpVpdWpsCvtps2pd(m, rde); break; case kOpCvt0f5a + 1: OpVpsWpdCvtpd2ps(m, rde); break; case kOpCvt0f5a + 2: OpVssWsdCvtsd2ss(m, rde); break; case kOpCvt0f5a + 3: OpVsdWssCvtss2sd(m, rde); break; case kOpCvt0f5b + 0: OpVpsWdqCvtdq2ps(m, rde); break; case kOpCvt0f5b + 1: OpVdqWpsCvtps2dq(m, rde); break; case kOpCvt0f5b + 3: OpVdqWpsCvttps2dq(m, rde); break; case kOpCvt0fE6 + 1: OpVdqWpdCvtpd2dq(m, rde); break; case kOpCvt0fE6 + 2: OpVdqWpdCvttpd2dq(m, rde); break; case kOpCvt0fE6 + 3: OpVpdWdqCvtdq2pd(m, rde); break; default: OpUd(m, rde); } } void OpCvt0f2a(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvt0f2a); } void OpCvtt0f2c(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvtt0f2c); } void OpCvt0f2d(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvt0f2d); } void OpCvt0f5a(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvt0f5a); } void OpCvt0f5b(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvt0f5b); } void OpCvt0fE6(struct Machine *m, uint32_t rde) { OpCvt(m, rde, kOpCvt0fE6); }
13,066
459
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/interner.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_INTERNER_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_INTERNER_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Interner { size_t i; /* byte size of 𝑝 */ size_t n; /* byte capacity of 𝑝 */ char *p; /* will relocate */ }; struct Interner *newinterner(void) returnsnonnull paramsnonnull(); void freeinterner(struct Interner *); size_t interncount(const struct Interner *) paramsnonnull(); size_t internobj(struct Interner *, const void *, size_t) paramsnonnull(); size_t intern(struct Interner *, const char *) paramsnonnull(); bool isinterned(struct Interner *, const char *) paramsnonnull(); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_INTERNER_H_ */
779
22
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/alu.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 "tool/build/lib/alu.h" #include "tool/build/lib/flags.h" const aluop_f kAlu[12][4] = { {Add8, Add16, Add32, Add64}, {Or8, Or16, Or32, Or64}, {Adc8, Adc16, Adc32, Adc64}, {Sbb8, Sbb16, Sbb32, Sbb64}, {And8, And16, And32, And64}, {Sub8, Sub16, Sub32, Sub64}, {Xor8, Xor16, Xor32, Xor64}, {Sub8, Sub16, Sub32, Sub64}, {Not8, Not16, Not32, Not64}, {Neg8, Neg16, Neg32, Neg64}, {Inc8, Inc16, Inc32, Inc64}, {Dec8, Dec16, Dec32, Dec64}, }; const aluop_f kBsu[8][4] = { {Rol8, Rol16, Rol32, Rol64}, {Ror8, Ror16, Ror32, Ror64}, {Rcl8, Rcl16, Rcl32, Rcl64}, {Rcr8, Rcr16, Rcr32, Rcr64}, {Shl8, Shl16, Shl32, Shl64}, {Shr8, Shr16, Shr32, Shr64}, {Shl8, Shl16, Shl32, Shl64}, {Sar8, Sar16, Sar32, Sar64}, }; int64_t AluFlags8(uint8_t z, uint32_t af, uint32_t *f, uint32_t of, uint32_t cf) { return AluFlags(z, af, f, of, cf, z >> 7); } int64_t AluFlags32(uint32_t z, uint32_t af, uint32_t *f, uint32_t of, uint32_t cf) { return AluFlags(z, af, f, of, cf, z >> 31); } int64_t Xor32(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags32(x ^ y, 0, f, 0, 0); } int64_t Sub32(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint32_t x, y, z; x = x64; y = y64; z = x - y; cf = x < z; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ y)) >> 31; return AluFlags32(z, af, f, of, cf); } int64_t AluFlags64(uint64_t z, uint32_t af, uint32_t *f, uint32_t of, uint32_t cf) { return AluFlags(z, af, f, of, cf, z >> 63); } int64_t Sub64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z; bool cf, of, af; z = x - y; cf = x < z; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ y)) >> 63; return AluFlags64(z, af, f, of, cf); } int64_t Xor8(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags8(x ^ y, 0, f, 0, 0); } int64_t Xor64(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags64(x ^ y, 0, f, 0, 0); } int64_t Or8(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags8(x | y, 0, f, 0, 0); } int64_t Or32(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags32(x | y, 0, f, 0, 0); } int64_t Or64(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags64(x | y, 0, f, 0, 0); } int64_t And8(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags8(x & y, 0, f, 0, 0); } int64_t And32(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags32(x & y, 0, f, 0, 0); } int64_t And64(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags64(x & y, 0, f, 0, 0); } int64_t Sub8(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint8_t x, y, z; x = x64; y = y64; z = x - y; cf = x < z; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ y)) >> 7; return AluFlags8(z, af, f, of, cf); } int64_t Add8(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint8_t x, y, z; x = x64; y = y64; z = x + y; cf = z < y; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ y)) >> 7; return AluFlags8(z, af, f, of, cf); } int64_t Add32(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint32_t x, y, z; x = x64; y = y64; z = x + y; cf = z < y; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ y)) >> 31; return AluFlags32(z, af, f, of, cf); } int64_t Add64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z; bool cf, of, af; z = x + y; cf = z < y; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ y)) >> 63; return AluFlags64(z, af, f, of, cf); } int64_t Adc8(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint8_t x, y, z, t; x = x64; y = y64; t = x + GetFlag(*f, FLAGS_CF); z = t + y; cf = (t < x) | (z < y); of = ((z ^ x) & (z ^ y)) >> 7; af = ((t & 15) < (x & 15)) | ((z & 15) < (y & 15)); return AluFlags8(z, af, f, of, cf); } int64_t Adc32(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint32_t x, y, z, t; x = x64; y = y64; t = x + GetFlag(*f, FLAGS_CF); z = t + y; cf = (t < x) | (z < y); of = ((z ^ x) & (z ^ y)) >> 31; af = ((t & 15) < (x & 15)) | ((z & 15) < (y & 15)); return AluFlags32(z, af, f, of, cf); } int64_t Adc64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z, t; bool cf, of, af; t = x + GetFlag(*f, FLAGS_CF); z = t + y; cf = (t < x) | (z < y); of = ((z ^ x) & (z ^ y)) >> 63; af = ((t & 15) < (x & 15)) | ((z & 15) < (y & 15)); return AluFlags64(z, af, f, of, cf); } int64_t Sbb8(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint8_t x, y, z, t; x = x64; y = y64; t = x - GetFlag(*f, FLAGS_CF); z = t - y; cf = (x < t) | (t < z); of = ((z ^ x) & (x ^ y)) >> 7; af = ((x & 15) < (t & 15)) | ((t & 15) < (z & 15)); return AluFlags8(z, af, f, of, cf); } int64_t Sbb32(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint32_t x, y, z, t; x = x64; y = y64; t = x - GetFlag(*f, FLAGS_CF); z = t - y; cf = (x < t) | (t < z); of = ((z ^ x) & (x ^ y)) >> 31; af = ((x & 15) < (t & 15)) | ((t & 15) < (z & 15)); return AluFlags32(z, af, f, of, cf); } int64_t Sbb64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z, t; bool cf, of, af; t = x - GetFlag(*f, FLAGS_CF); z = t - y; cf = (x < t) | (t < z); of = ((z ^ x) & (x ^ y)) >> 63; af = ((x & 15) < (t & 15)) | ((t & 15) < (z & 15)); return AluFlags64(z, af, f, of, cf); } int64_t Not8(uint64_t x, uint64_t y, uint32_t *f) { return ~x & 0xFF; } int64_t Not32(uint64_t x, uint64_t y, uint32_t *f) { return ~x & 0xFFFFFFFF; } int64_t Not64(uint64_t x, uint64_t y, uint32_t *f) { return ~x & 0xFFFFFFFFFFFFFFFF; } int64_t Neg8(uint64_t x64, uint64_t y, uint32_t *f) { uint8_t x; bool cf, of, af; x = x64; af = cf = !!x; of = x == 0x80; x = ~x + 1; return AluFlags8(x, af, f, of, cf); } int64_t Neg32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x; bool cf, of, af; x = x64; af = cf = !!x; of = x == 0x80000000; x = ~x + 1; return AluFlags32(x, af, f, of, cf); } int64_t Neg64(uint64_t x64, uint64_t y, uint32_t *f) { uint64_t x; bool cf, of, af; x = x64; af = cf = !!x; of = x == 0x8000000000000000; x = ~x + 1; return AluFlags64(x, af, f, of, cf); } static int64_t BumpFlags(uint64_t x, uint32_t af, uint32_t *f, uint32_t of, uint32_t sf) { return AluFlags(x, af, f, of, GetFlag(*f, FLAGS_CF), sf); } int64_t Dec32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, z, of, sf, af; x = x64; z = x - 1; sf = z >> 31; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ 1)) >> 31; return BumpFlags(z, af, f, of, sf); } int64_t Inc32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, z, of, sf, af; x = x64; z = x + 1; sf = z >> 31; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ 1)) >> 31; return BumpFlags(z, af, f, of, sf); } int64_t Inc64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z; uint32_t of, sf, af; z = x + 1; sf = z >> 63; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ 1)) >> 63; return BumpFlags(z, af, f, of, sf); } int64_t Dec64(uint64_t x, uint64_t y, uint32_t *f) { uint64_t z; uint32_t of, sf, af; z = x - 1; sf = z >> 63; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ 1)) >> 63; return BumpFlags(z, af, f, of, sf); } int64_t Inc8(uint64_t x64, uint64_t y, uint32_t *f) { uint8_t x, z; uint32_t of, sf, af; x = x64; z = x + 1; sf = z >> 7; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ 1)) >> 7; return BumpFlags(z, af, f, of, sf); } int64_t Dec8(uint64_t x64, uint64_t y, uint32_t *f) { uint8_t x, z; uint32_t of, sf, af; x = x64; z = x - 1; sf = z >> 7; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ 1)) >> 7; return BumpFlags(z, af, f, of, sf); } int64_t Shr8(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xff; if ((y &= 31)) { cf = (x >> (y - 1)) & 1; x >>= y; return AluFlags8(x, 0, f, ((x << 1) ^ x) >> 7, cf); } else { return x; } } int64_t Shr32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t cf, x = x64; if ((y &= 31)) { cf = (x >> (y - 1)) & 1; x >>= y; return AluFlags32(x, 0, f, ((x << 1) ^ x) >> 31, cf); } else { return x; } } int64_t Shr64(uint64_t x, uint64_t y, uint32_t *f) { uint32_t cf; if ((y &= 63)) { cf = (x >> (y - 1)) & 1; x >>= y; return AluFlags64(x, 0, f, ((x << 1) ^ x) >> 63, cf); } else { return x; } } int64_t Shl8(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xff; if ((y &= 31)) { cf = (x >> ((8 - y) & 31)) & 1; x = (x << y) & 0xff; return AluFlags8(x, 0, f, (x >> 7) ^ cf, cf); } else { return x; } } int64_t Shl32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t cf, x = x64; if ((y &= 31)) { cf = (x >> (32 - y)) & 1; x <<= y; return AluFlags32(x, 0, f, (x >> 31) ^ cf, cf); } else { return x; } } int64_t Shl64(uint64_t x, uint64_t y, uint32_t *f) { uint32_t cf; if ((y &= 63)) { cf = (x >> (64 - y)) & 1; x <<= y; return AluFlags64(x, 0, f, (x >> 63) ^ cf, cf); } else { return x; } } int64_t Sar8(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xff; if ((y &= 31)) { cf = ((int32_t)(int8_t)x >> (y - 1)) & 1; x = ((int32_t)(int8_t)x >> y) & 0xff; return AluFlags8(x, 0, f, 0, cf); } else { return x; } } int64_t Sar32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t cf, x = x64; if ((y &= 31)) { cf = ((int32_t)x >> (y - 1)) & 1; x = (int32_t)x >> y; return AluFlags32(x, 0, f, 0, cf); } else { return x; } } int64_t Sar64(uint64_t x, uint64_t y, uint32_t *f) { uint32_t cf; if ((y &= 63)) { cf = ((int64_t)x >> (y - 1)) & 1; x = (int64_t)x >> y; return AluFlags64(x, 0, f, 0, cf); } else { return x; } } static int64_t RotateFlags(uint64_t x, uint32_t cf, uint32_t *f, uint32_t of) { *f &= ~(1u << FLAGS_CF | 1u << FLAGS_OF); *f |= cf << FLAGS_CF | of << FLAGS_OF; return x; } int64_t Rol32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x = x64; if ((y &= 31)) { x = x << y | x >> (32 - y); return RotateFlags(x, x & 1, f, ((x >> 31) ^ x) & 1); } else { return x; } } int64_t Rol64(uint64_t x, uint64_t y, uint32_t *f) { if ((y &= 63)) { x = x << y | x >> (64 - y); return RotateFlags(x, x & 1, f, ((x >> 63) ^ x) & 1); } else { return x; } } int64_t Ror32(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x = x64; if ((y &= 31)) { x = x >> y | x << (32 - y); return RotateFlags(x, x >> 31, f, ((x >> 31) ^ (x >> 30)) & 1); } else { return x; } } int64_t Ror64(uint64_t x, uint64_t y, uint32_t *f) { if ((y &= 63)) { x = x >> y | x << (64 - y); return RotateFlags(x, x >> 63, f, ((x >> 63) ^ (x >> 62)) & 1); } else { return x; } } int64_t Rol8(uint64_t x64, uint64_t y, uint32_t *f) { uint8_t x = x64; if (y & 31) { if ((y &= 7)) x = x << y | x >> (8 - y); return RotateFlags(x, x & 1, f, ((x >> 7) ^ x) & 1); } else { return x; } } int64_t Ror8(uint64_t x64, uint64_t y, uint32_t *f) { uint8_t x = x64; if (y & 31) { if ((y &= 7)) x = x >> y | x << (8 - y); return RotateFlags(x, x >> 7, f, ((x >> 7) ^ (x >> 6)) & 1); } else { return x; } } static int64_t Rcr(uint64_t x, uint64_t y, uint32_t *f, uint64_t xm, uint64_t k) { uint64_t cf; uint32_t ct; x &= xm; if (y) { cf = GetFlag(*f, FLAGS_CF); ct = (x >> (y - 1)) & 1; if (y == 1) { x = (x >> 1 | cf << (k - 1)) & xm; } else { x = (x >> y | cf << (k - y) | x << (k + 1 - y)) & xm; } return RotateFlags(x, ct, f, (((x << 1) ^ x) >> (k - 1)) & 1); } else { return x; } } int64_t Rcr8(uint64_t x, uint64_t y, uint32_t *f) { return Rcr(x, (y & 31) % 9, f, 0xff, 8); } int64_t Rcr16(uint64_t x, uint64_t y, uint32_t *f) { return Rcr(x, (y & 31) % 17, f, 0xffff, 16); } int64_t Rcr32(uint64_t x, uint64_t y, uint32_t *f) { return Rcr(x, y & 31, f, 0xffffffff, 32); } int64_t Rcr64(uint64_t x, uint64_t y, uint32_t *f) { return Rcr(x, y & 63, f, 0xffffffffffffffff, 64); } static int64_t Rcl(uint64_t x, uint64_t y, uint32_t *f, uint64_t xm, uint64_t k) { uint64_t cf; uint32_t ct; x &= xm; if (y) { cf = GetFlag(*f, FLAGS_CF); ct = (x >> (k - y)) & 1; if (y == 1) { x = (x << 1 | cf) & xm; } else { x = (x << y | cf << (y - 1) | x >> (k + 1 - y)) & xm; } return RotateFlags(x, ct, f, ct ^ ((x >> (k - 1)) & 1)); } else { return x; } } int64_t Rcl8(uint64_t x, uint64_t y, uint32_t *f) { return Rcl(x, (y & 31) % 9, f, 0xff, 8); } int64_t Rcl16(uint64_t x, uint64_t y, uint32_t *f) { return Rcl(x, (y & 31) % 17, f, 0xffff, 16); } int64_t Rcl32(uint64_t x, uint64_t y, uint32_t *f) { return Rcl(x, y & 31, f, 0xffffffff, 32); } int64_t Rcl64(uint64_t x, uint64_t y, uint32_t *f) { return Rcl(x, y & 63, f, 0xffffffffffffffff, 64); } uint64_t BsuDoubleShift(int w, uint64_t x, uint64_t y, uint8_t b, bool isright, uint32_t *f) { bool cf, of; uint64_t s, k, m, z; k = 8; k <<= w; s = 1; s <<= k - 1; m = s | s - 1; b &= w == 3 ? 63 : 31; x &= m; if (b) { if (isright) { z = x >> b | y << (k - b); cf = (x >> (b - 1)) & 1; of = b == 1 && (z & s) != (x & s); } else { z = x << b | y >> (k - b); cf = (x >> (k - b)) & 1; of = b == 1 && (z & s) != (x & s); } x = z; x &= m; return AluFlags(x, 0, f, of, cf, !!(x & s)); } else { return x; } } int64_t AluFlags16(uint16_t z, uint32_t af, uint32_t *f, uint32_t of, uint32_t cf) { return AluFlags(z, af, f, of, cf, z >> 15); } int64_t Xor16(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags16(x ^ y, 0, f, 0, 0); } int64_t Or16(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags16(x | y, 0, f, 0, 0); } int64_t And16(uint64_t x, uint64_t y, uint32_t *f) { return AluFlags16(x & y, 0, f, 0, 0); } int64_t Sub16(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint16_t x, y, z; x = x64; y = y64; z = x - y; cf = x < z; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ y)) >> 15; return AluFlags16(z, af, f, of, cf); } int64_t Add16(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint16_t x, y, z; x = x64; y = y64; z = x + y; cf = z < y; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ y)) >> 15; return AluFlags16(z, af, f, of, cf); } int64_t Adc16(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint16_t x, y, z, t; x = x64; y = y64; t = x + GetFlag(*f, FLAGS_CF); z = t + y; cf = (t < x) | (z < y); of = ((z ^ x) & (z ^ y)) >> 15; af = ((t & 15) < (x & 15)) | ((z & 15) < (y & 15)); return AluFlags16(z, af, f, of, cf); } int64_t Sbb16(uint64_t x64, uint64_t y64, uint32_t *f) { bool cf, of, af; uint16_t x, y, z, t; x = x64; y = y64; t = x - GetFlag(*f, FLAGS_CF); z = t - y; cf = (x < t) | (t < z); of = ((z ^ x) & (x ^ y)) >> 15; af = ((x & 15) < (t & 15)) | ((t & 15) < (z & 15)); return AluFlags16(z, af, f, of, cf); } int64_t Not16(uint64_t x, uint64_t y, uint32_t *f) { return ~x & 0xFFFF; } int64_t Neg16(uint64_t x64, uint64_t y, uint32_t *f) { uint16_t x; bool cf, of, af; x = x64; af = cf = !!x; of = x == 0x8000; x = ~x + 1; return AluFlags16(x, af, f, of, cf); } int64_t Inc16(uint64_t x64, uint64_t y, uint32_t *f) { uint16_t x, z; uint32_t of, sf, af; x = x64; z = x + 1; sf = z >> 15; af = (z & 15) < (y & 15); of = ((z ^ x) & (z ^ 1)) >> 15; return BumpFlags(z, af, f, of, sf); } int64_t Dec16(uint64_t x64, uint64_t y, uint32_t *f) { uint16_t x, z; uint32_t of, sf, af; x = x64; z = x - 1; sf = z >> 15; af = (x & 15) < (z & 15); of = ((z ^ x) & (x ^ 1)) >> 15; return BumpFlags(z, af, f, of, sf); } int64_t Shr16(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xffff; if ((y &= 31)) { cf = (x >> (y - 1)) & 1; x >>= y; return AluFlags16(x, 0, f, ((x << 1) ^ x) >> 15, cf); } else { return x; } } int64_t Shl16(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xffff; if ((y &= 31)) { cf = (x >> ((16 - y) & 31)) & 1; x = (x << y) & 0xffff; return AluFlags16(x, 0, f, (x >> 15) ^ cf, cf); } else { return x; } } int64_t Sar16(uint64_t x64, uint64_t y, uint32_t *f) { uint32_t x, cf; x = x64 & 0xffff; if ((y &= 31)) { cf = ((int32_t)(int16_t)x >> (y - 1)) & 1; x = ((int32_t)(int16_t)x >> y) & 0xffff; return AluFlags16(x, 0, f, 0, cf); } else { return x; } } int64_t Rol16(uint64_t x64, uint64_t y, uint32_t *f) { uint16_t x = x64; if (y & 31) { if ((y &= 15)) x = x << y | x >> (16 - y); return RotateFlags(x, x & 1, f, ((x >> 15) ^ x) & 1); } else { return x; } } int64_t Ror16(uint64_t x64, uint64_t y, uint32_t *f) { uint16_t x = x64; if (y & 31) { if ((y &= 15)) x = x >> y | x << (16 - y); return RotateFlags(x, x >> 15, f, ((x >> 15) ^ (x >> 14)) & 1); } else { return x; } }
19,056
764
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cga.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/itoa.h" #include "libc/macros.internal.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "tool/build/lib/buffer.h" #include "tool/build/lib/cga.h" /* blk blu grn cyn red mag yel wht */ static const uint8_t kCgaToAnsi[16] = {30, 34, 32, 36, 31, 35, 33, 37, 90, 94, 92, 96, 91, 95, 93, 97}; size_t FormatCga(uint8_t bgfg, char buf[hasatleast 11]) { char *p = buf; *p++ = '\e'; *p++ = '['; p = FormatUint32(p, kCgaToAnsi[(bgfg & 0xF0) >> 4] + 10); *p++ = ';'; p = FormatUint32(p, kCgaToAnsi[bgfg & 0x0F]); *p++ = 'm'; *p = '\0'; return p - buf; } void DrawCga(struct Panel *p, uint8_t v[25][80][2]) { char buf[11]; unsigned y, x, n, a; n = MIN(25, p->bottom - p->top); for (y = 0; y < n; ++y) { a = -1; for (x = 0; x < 80; ++x) { if (v[y][x][1] != a) { AppendData(&p->lines[y], buf, FormatCga((a = v[y][x][1]), buf)); } AppendWide(&p->lines[y], kCp437[v[y][x][0]]); } AppendStr(&p->lines[y], "\e[0m"); } }
2,929
57
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/reset.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/macros.internal.h" #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/machine.h" #define LDBL 3 #define RINT 0 static void ResetFpu(struct Machine *m) { long i; long double fval; fval = -NAN; m->fpu.sw = 0; m->fpu.tw = -1; m->fpu.cw = 0; m->fpu.im = true; m->fpu.dm = true; m->fpu.zm = true; m->fpu.om = true; m->fpu.um = true; m->fpu.pm = true; m->fpu.pc = LDBL; m->fpu.rc = RINT; for (i = 0; i < ARRAYLEN(m->fpu.st); ++i) { memcpy(&m->fpu.st[i], &fval, sizeof(fval)); } } static void ResetSse(struct Machine *m) { m->sse.mxcsr = 0; m->sse.daz = false; m->sse.im = true; m->sse.dm = true; m->sse.zm = true; m->sse.om = true; m->sse.um = true; m->sse.pm = true; m->sse.rc = RINT; m->sse.ftz = false; bzero(m->xmm, sizeof(m->xmm)); } void ResetInstructionCache(struct Machine *m) { memset(m->icache, -1, sizeof(m->icache)); } void ResetCpu(struct Machine *m) { m->faultaddr = 0; m->stashsize = 0; m->stashaddr = 0; m->writeaddr = 0; m->readaddr = 0; m->writesize = 0; m->readsize = 0; m->flags = SetFlag(m->flags, FLAGS_DF, false); m->flags = SetFlag(m->flags, FLAGS_CF, false); m->flags = SetFlag(m->flags, FLAGS_ZF, false); m->flags = SetFlag(m->flags, FLAGS_SF, false); m->flags = SetFlag(m->flags, FLAGS_IF, true); m->flags = SetFlag(m->flags, FLAGS_F1, true); m->flags = SetFlag(m->flags, FLAGS_F0, false); m->flags = SetFlag(m->flags, FLAGS_IOPL, 3); bzero(m->reg, sizeof(m->reg)); bzero(m->bofram, sizeof(m->bofram)); bzero(&m->freelist, sizeof(m->freelist)); ResetSse(m); ResetFpu(m); } void ResetTlb(struct Machine *m) { m->tlbindex = 0; bzero(m->tlb, sizeof(m->tlb)); m->codevirt = 0; m->codehost = 0; }
3,691
97
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/panel.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_PANEL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_PANEL_H_ #include "tool/build/lib/buffer.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Panel { int top; int bottom; int left; int right; struct Buffer *lines; size_t n; }; ssize_t PrintPanels(int, long, struct Panel *, long, long); void PrintMessageBox(int, const char *, long, long); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_PANEL_H_ */
522
22
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/op101.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/op101.h" #include "tool/build/lib/throw.h" #include "tool/build/lib/time.h" static void StoreDescriptorTable(struct Machine *m, uint32_t rde, uint16_t limit, uint64_t base) { uint64_t l; l = ComputeAddress(m, rde); if (l + 10 <= m->real.n) { Write16(m->real.p + l, limit); if (Rexw(rde)) { Write64(m->real.p + l + 2, base); SetWriteAddr(m, l, 10); } else if (!Osz(rde)) { Write32(m->real.p + l + 2, base); SetWriteAddr(m, l, 6); } else { Write16(m->real.p + l + 2, base); SetWriteAddr(m, l, 4); } } else { ThrowSegmentationFault(m, l); } } static void LoadDescriptorTable(struct Machine *m, uint32_t rde, uint16_t *out_limit, uint64_t *out_base) { uint16_t limit; uint64_t l, base; l = ComputeAddress(m, rde); if (l + 10 <= m->real.n) { limit = Read16(m->real.p + l); if (Rexw(rde)) { base = Read64(m->real.p + l + 2) & 0x00ffffff; SetReadAddr(m, l, 10); } else if (!Osz(rde)) { base = Read32(m->real.p + l + 2); SetReadAddr(m, l, 6); } else { base = Read16(m->real.p + l + 2); SetReadAddr(m, l, 4); } if (base + limit <= m->real.n) { *out_limit = limit; *out_base = base; } else { ThrowProtectionFault(m); } } else { ThrowSegmentationFault(m, l); } } static void SgdtMs(struct Machine *m, uint32_t rde) { StoreDescriptorTable(m, rde, m->gdt_limit, m->gdt_base); } static void LgdtMs(struct Machine *m, uint32_t rde) { LoadDescriptorTable(m, rde, &m->gdt_limit, &m->gdt_base); INFOF("set gdt %p lim %,d", m->gdt_base, m->gdt_limit); } static void SidtMs(struct Machine *m, uint32_t rde) { StoreDescriptorTable(m, rde, m->idt_limit, m->idt_base); } static void LidtMs(struct Machine *m, uint32_t rde) { LoadDescriptorTable(m, rde, &m->idt_limit, &m->idt_base); INFOF("set idt %p lim %,d", m->idt_base, m->idt_limit); } static void Monitor(struct Machine *m, uint32_t rde) { } static void Mwait(struct Machine *m, uint32_t rde) { } static void Swapgs(struct Machine *m, uint32_t rde) { } static void Vmcall(struct Machine *m, uint32_t rde) { } static void Vmlaunch(struct Machine *m, uint32_t rde) { } static void Vmresume(struct Machine *m, uint32_t rde) { } static void Vmxoff(struct Machine *m, uint32_t rde) { } static void InvlpgM(struct Machine *m, uint32_t rde) { ResetTlb(m); } static void Smsw(struct Machine *m, uint32_t rde, bool ismem) { if (ismem) { Write16(GetModrmRegisterWordPointerWrite2(m, rde), m->cr0); } else if (Rexw(rde)) { Write64(RegRexrReg(m, rde), m->cr0); } else if (!Osz(rde)) { Write64(RegRexrReg(m, rde), m->cr0 & 0xffffffff); } else { Write16(RegRexrReg(m, rde), m->cr0); } } static void Lmsw(struct Machine *m, uint32_t rde) { m->cr0 = Read16(GetModrmRegisterWordPointerRead2(m, rde)); } void Op101(struct Machine *m, uint32_t rde) { bool ismem; ismem = !IsModrmRegister(rde); switch (ModrmReg(rde)) { case 0: if (ismem) { SgdtMs(m, rde); } else { switch (ModrmRm(rde)) { case 1: Vmcall(m, rde); break; case 2: Vmlaunch(m, rde); break; case 3: Vmresume(m, rde); break; case 4: Vmxoff(m, rde); break; default: OpUd(m, rde); } } break; case 1: if (ismem) { SidtMs(m, rde); } else { switch (ModrmRm(rde)) { case 0: Monitor(m, rde); break; case 1: Mwait(m, rde); break; default: OpUd(m, rde); } } break; case 2: if (ismem) { LgdtMs(m, rde); } else { OpUd(m, rde); } break; case 3: if (ismem) { LidtMs(m, rde); } else { OpUd(m, rde); } break; case 4: Smsw(m, rde, ismem); break; case 6: Lmsw(m, rde); break; case 7: if (ismem) { InvlpgM(m, rde); } else { switch (ModrmRm(rde)) { case 0: Swapgs(m, rde); break; case 1: OpRdtscp(m, rde); break; default: OpUd(m, rde); } } break; default: OpUd(m, rde); } }
6,449
217
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/alu.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_ALU_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_ALU_H_ #include "tool/build/lib/machine.h" #define ALU_ADD 0 #define ALU_OR 1 #define ALU_ADC 2 #define ALU_SBB 3 #define ALU_AND 4 #define ALU_SUB 5 #define ALU_XOR 6 #define ALU_CMP 7 #define ALU_NOT 8 #define ALU_NEG 9 #define ALU_INC 10 #define ALU_DEC 11 #define BSU_ROL 0 #define BSU_ROR 1 #define BSU_RCL 2 #define BSU_RCR 3 #define BSU_SHL 4 #define BSU_SHR 5 #define BSU_SAL 6 #define BSU_SAR 7 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef int64_t (*aluop_f)(uint64_t, uint64_t, uint32_t *); extern const aluop_f kAlu[12][4]; extern const aluop_f kBsu[8][4]; int64_t Xor8(uint64_t, uint64_t, uint32_t *); int64_t Xor16(uint64_t, uint64_t, uint32_t *); int64_t Xor32(uint64_t, uint64_t, uint32_t *); int64_t Xor64(uint64_t, uint64_t, uint32_t *); int64_t Or8(uint64_t, uint64_t, uint32_t *); int64_t Or16(uint64_t, uint64_t, uint32_t *); int64_t Or32(uint64_t, uint64_t, uint32_t *); int64_t Or64(uint64_t, uint64_t, uint32_t *); int64_t And8(uint64_t, uint64_t, uint32_t *); int64_t And16(uint64_t, uint64_t, uint32_t *); int64_t And32(uint64_t, uint64_t, uint32_t *); int64_t And64(uint64_t, uint64_t, uint32_t *); int64_t Sub8(uint64_t, uint64_t, uint32_t *); int64_t Sbb8(uint64_t, uint64_t, uint32_t *); int64_t Sub16(uint64_t, uint64_t, uint32_t *); int64_t Sbb16(uint64_t, uint64_t, uint32_t *); int64_t Sub32(uint64_t, uint64_t, uint32_t *); int64_t Sbb32(uint64_t, uint64_t, uint32_t *); int64_t Sub64(uint64_t, uint64_t, uint32_t *); int64_t Sbb64(uint64_t, uint64_t, uint32_t *); int64_t Add8(uint64_t, uint64_t, uint32_t *); int64_t Adc8(uint64_t, uint64_t, uint32_t *); int64_t Add16(uint64_t, uint64_t, uint32_t *); int64_t Adc16(uint64_t, uint64_t, uint32_t *); int64_t Add32(uint64_t, uint64_t, uint32_t *); int64_t Adc32(uint64_t, uint64_t, uint32_t *); int64_t Add64(uint64_t, uint64_t, uint32_t *); int64_t Adc64(uint64_t, uint64_t, uint32_t *); int64_t Not8(uint64_t, uint64_t, uint32_t *); int64_t Not16(uint64_t, uint64_t, uint32_t *); int64_t Not32(uint64_t, uint64_t, uint32_t *); int64_t Not64(uint64_t, uint64_t, uint32_t *); int64_t Neg8(uint64_t, uint64_t, uint32_t *); int64_t Neg16(uint64_t, uint64_t, uint32_t *); int64_t Neg32(uint64_t, uint64_t, uint32_t *); int64_t Neg64(uint64_t, uint64_t, uint32_t *); int64_t Inc8(uint64_t, uint64_t, uint32_t *); int64_t Inc16(uint64_t, uint64_t, uint32_t *); int64_t Inc32(uint64_t, uint64_t, uint32_t *); int64_t Inc64(uint64_t, uint64_t, uint32_t *); int64_t Dec8(uint64_t, uint64_t, uint32_t *); int64_t Dec16(uint64_t, uint64_t, uint32_t *); int64_t Dec32(uint64_t, uint64_t, uint32_t *); int64_t Dec64(uint64_t, uint64_t, uint32_t *); int64_t Shr8(uint64_t, uint64_t, uint32_t *); int64_t Shr16(uint64_t, uint64_t, uint32_t *); int64_t Shr32(uint64_t, uint64_t, uint32_t *); int64_t Shr64(uint64_t, uint64_t, uint32_t *); int64_t Shl8(uint64_t, uint64_t, uint32_t *); int64_t Shl16(uint64_t, uint64_t, uint32_t *); int64_t Shl32(uint64_t, uint64_t, uint32_t *); int64_t Shl64(uint64_t, uint64_t, uint32_t *); int64_t Sar8(uint64_t, uint64_t, uint32_t *); int64_t Sar16(uint64_t, uint64_t, uint32_t *); int64_t Sar32(uint64_t, uint64_t, uint32_t *); int64_t Sar64(uint64_t, uint64_t, uint32_t *); int64_t Rol8(uint64_t, uint64_t, uint32_t *); int64_t Rol16(uint64_t, uint64_t, uint32_t *); int64_t Rol32(uint64_t, uint64_t, uint32_t *); int64_t Rol64(uint64_t, uint64_t, uint32_t *); int64_t Ror8(uint64_t, uint64_t, uint32_t *); int64_t Ror16(uint64_t, uint64_t, uint32_t *); int64_t Ror32(uint64_t, uint64_t, uint32_t *); int64_t Ror64(uint64_t, uint64_t, uint32_t *); int64_t Rcr8(uint64_t, uint64_t, uint32_t *); int64_t Rcr16(uint64_t, uint64_t, uint32_t *); int64_t Rcr32(uint64_t, uint64_t, uint32_t *); int64_t Rcr64(uint64_t, uint64_t, uint32_t *); int64_t Rcl8(uint64_t, uint64_t, uint32_t *); int64_t Rcl16(uint64_t, uint64_t, uint32_t *); int64_t Rcl32(uint64_t, uint64_t, uint32_t *); int64_t Rcl64(uint64_t, uint64_t, uint32_t *); uint64_t BsuDoubleShift(int, uint64_t, uint64_t, uint8_t, bool, uint32_t *); int64_t AluFlags8(uint8_t, uint32_t, uint32_t *, uint32_t, uint32_t); int64_t AluFlags16(uint16_t, uint32_t, uint32_t *, uint32_t, uint32_t); int64_t AluFlags32(uint32_t, uint32_t, uint32_t *, uint32_t, uint32_t); int64_t AluFlags64(uint64_t, uint32_t, uint32_t *, uint32_t, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_ALU_H_ */
4,521
119
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/eztls.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/iovec.h" #include "libc/errno.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/sysv/consts/sig.h" #include "libc/x/x.h" #include "libc/x/xsigaction.h" #include "net/https/https.h" #include "third_party/mbedtls/net_sockets.h" #include "third_party/mbedtls/ssl.h" #include "tool/build/lib/eztls.h" struct EzTlsBio ezbio; mbedtls_ssl_config ezconf; mbedtls_ssl_context ezssl; mbedtls_ctr_drbg_context ezrng; static ssize_t EzWritevAll(int fd, struct iovec *iov, int iovlen) { int i; ssize_t rc; size_t wrote, total; i = 0; total = 0; do { if (i) { while (i < iovlen && !iov[i].iov_len) ++i; if (i == iovlen) break; } if ((rc = writev(fd, iov + i, iovlen - i)) != -1) { wrote = rc; total += wrote; do { if (wrote >= iov[i].iov_len) { wrote -= iov[i++].iov_len; } else { iov[i].iov_base = (char *)iov[i].iov_base + wrote; iov[i].iov_len -= wrote; wrote = 0; } } while (wrote); } else { WARNF("writev() failed %m"); if (errno != EINTR) { return total ? total : -1; } } } while (i < iovlen); return total; } int EzTlsFlush(struct EzTlsBio *bio, const unsigned char *buf, size_t len) { struct iovec v[2]; if (len || bio->c > 0) { v[0].iov_base = bio->u; v[0].iov_len = MAX(0, bio->c); v[1].iov_base = buf; v[1].iov_len = len; if (EzWritevAll(bio->fd, v, 2) != -1) { if (bio->c > 0) bio->c = 0; } else if (errno == EAGAIN) { return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { WARNF("EzTlsSend error %s", strerror(errno)); return MBEDTLS_ERR_NET_SEND_FAILED; } } return 0; } static int EzTlsSend(void *ctx, const unsigned char *buf, size_t len) { int rc; struct iovec v[2]; struct EzTlsBio *bio = ctx; if (bio->c >= 0 && bio->c + len <= sizeof(bio->u)) { memcpy(bio->u + bio->c, buf, len); bio->c += len; return len; } if ((rc = EzTlsFlush(bio, buf, len)) < 0) return rc; return len; } static int EzTlsRecvImpl(void *ctx, unsigned char *p, size_t n, uint32_t o) { int r; ssize_t s; struct iovec v[2]; struct EzTlsBio *bio = ctx; if ((r = EzTlsFlush(bio, 0, 0)) < 0) return r; if (bio->a < bio->b) { r = MIN(n, bio->b - bio->a); memcpy(p, bio->t + bio->a, r); if ((bio->a += r) == bio->b) bio->a = bio->b = 0; return r; } v[0].iov_base = p; v[0].iov_len = n; v[1].iov_base = bio->t; v[1].iov_len = sizeof(bio->t); while ((r = readv(bio->fd, v, 2)) == -1) { WARNF("tls read() error %s", strerror(errno)); if (errno == EINTR) { return MBEDTLS_ERR_SSL_WANT_READ; } else if (errno == EAGAIN) { return MBEDTLS_ERR_SSL_TIMEOUT; } else if (errno == EPIPE || errno == ECONNRESET || errno == ENETRESET) { return MBEDTLS_ERR_NET_CONN_RESET; } else { return MBEDTLS_ERR_NET_RECV_FAILED; } } if (r > n) bio->b = r - n; return MIN(n, r); } static int EzTlsRecv(void *ctx, unsigned char *buf, size_t len, uint32_t tmo) { return EzTlsRecvImpl(ctx, buf, len, tmo); } void EzFd(int fd) { mbedtls_ssl_session_reset(&ezssl); mbedtls_platform_zeroize(&ezbio, sizeof(ezbio)); ezbio.fd = fd; } void EzHandshake(void) { int rc; while ((rc = mbedtls_ssl_handshake(&ezssl))) { if (rc != MBEDTLS_ERR_SSL_WANT_READ) { TlsDie("handshake failed", rc); } } while ((rc = EzTlsFlush(&ezbio, 0, 0))) { if (rc != MBEDTLS_ERR_SSL_WANT_READ) { TlsDie("handshake flush failed", rc); } } } int EzHandshake2(void) { int rc; while ((rc = mbedtls_ssl_handshake(&ezssl))) { if (rc == MBEDTLS_ERR_NET_CONN_RESET) { return rc; } else if (rc != MBEDTLS_ERR_SSL_WANT_READ) { TlsDie("handshake failed", rc); } } while ((rc = EzTlsFlush(&ezbio, 0, 0))) { if (rc == MBEDTLS_ERR_NET_CONN_RESET) { return rc; } else if (rc != MBEDTLS_ERR_SSL_WANT_READ) { TlsDie("handshake flush failed", rc); } } return 0; } void EzInitialize(void) { xsigaction(SIGPIPE, SIG_IGN, 0, 0, 0); ezconf.disable_compression = 1; /* TODO(jart): Why does it behave weirdly? */ InitializeRng(&ezrng); } void EzSetup(char psk[32]) { int rc; mbedtls_ssl_conf_rng(&ezconf, mbedtls_ctr_drbg_random, &ezrng); if ((rc = mbedtls_ssl_conf_psk(&ezconf, psk, 32, "runit", 5)) || (rc = mbedtls_ssl_setup(&ezssl, &ezconf))) { TlsDie("EzSetup", rc); } mbedtls_ssl_set_bio(&ezssl, &ezbio, EzTlsSend, 0, EzTlsRecv); }
6,536
194
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/fpu.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_FPU_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_FPU_H_ #include "tool/build/lib/machine.h" #define kFpuTagValid 0b00 #define kFpuTagZero 0b01 #define kFpuTagSpecial 0b10 #define kFpuTagEmpty 0b11 #define kFpuCwIm 0x0001 /* invalid operation mask */ #define kFpuCwDm 0x0002 /* denormal operand mask */ #define kFpuCwZm 0x0004 /* zero divide mask */ #define kFpuCwOm 0x0008 /* overflow mask */ #define kFpuCwUm 0x0010 /* underflow mask */ #define kFpuCwPm 0x0020 /* precision mask */ #define kFpuCwPc 0x0300 /* precision: 32,∅,64,80 */ #define kFpuCwRc 0x0c00 /* rounding: even,→-∞,→+∞,→0 */ #define kFpuSwIe 0x0001 /* invalid operation */ #define kFpuSwDe 0x0002 /* denormalized operand */ #define kFpuSwZe 0x0004 /* zero divide */ #define kFpuSwOe 0x0008 /* overflow */ #define kFpuSwUe 0x0010 /* underflow */ #define kFpuSwPe 0x0020 /* precision */ #define kFpuSwSf 0x0040 /* stack fault */ #define kFpuSwEs 0x0080 /* exception summary status */ #define kFpuSwC0 0x0100 /* condition 0 */ #define kFpuSwC1 0x0200 /* condition 1 */ #define kFpuSwC2 0x0400 /* condition 2 */ #define kFpuSwSp 0x3800 /* top stack */ #define kFpuSwC3 0x4000 /* condition 3 */ #define kFpuSwBf 0x8000 /* busy flag */ #define kMxcsrIe 0x0001 /* invalid operation flag */ #define kMxcsrDe 0x0002 /* denormal flag */ #define kMxcsrZe 0x0004 /* divide by zero flag */ #define kMxcsrOe 0x0008 /* overflow flag */ #define kMxcsrUe 0x0010 /* underflow flag */ #define kMxcsrPe 0x0020 /* precision flag */ #define kMxcsrDaz 0x0040 /* denormals are zeros */ #define kMxcsrIm 0x0080 /* invalid operation mask */ #define kMxcsrDm 0x0100 /* denormal mask */ #define kMxcsrZm 0x0200 /* divide by zero mask */ #define kMxcsrOm 0x0400 /* overflow mask */ #define kMxcsrUm 0x0800 /* underflow mask */ #define kMxcsrPm 0x1000 /* precision mask */ #define kMxcsrRc 0x6000 /* rounding control */ #define kMxcsrFtz 0x8000 /* flush to zero */ #define FpuSt(m, i) ((m)->fpu.st + (((i) + ((m->fpu.sw & kFpuSwSp) >> 11)) & 7)) #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ double FpuPop(struct Machine *); int FpuGetTag(struct Machine *, unsigned); void FpuPush(struct Machine *, double); void FpuSetTag(struct Machine *, unsigned, unsigned); void OpFinit(struct Machine *); void OpFpu(struct Machine *, uint32_t); void OpFwait(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_FPU_H_ */
2,511
66
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/javadown.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_JAVADOWN_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_JAVADOWN_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct JavadownTag { char *tag; char *text; }; struct JavadownTags { size_t n; struct JavadownTag * p; }; struct Javadown { bool isfileoverview; char *title; char *text; struct JavadownTags tags; }; struct Javadown *ParseJavadown(const char *, size_t); void FreeJavadown(struct Javadown *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_JAVADOWN_H_ */
588
29
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/pml4t.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 "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/pml4t.h" static void AppendContiguousMemoryRange(struct ContiguousMemoryRanges *ranges, int64_t a, int64_t b) { APPEND(&ranges->p, &ranges->i, &ranges->n, (&(struct ContiguousMemoryRange){a, b})); } static void FindContiguousMemoryRangesImpl( struct Machine *m, struct ContiguousMemoryRanges *ranges, int64_t addr, unsigned level, int64_t pt, int64_t a, int64_t b) { int64_t i, page, entry; for (i = a; i < b; ++i) { entry = Read64(m->real.p + pt + i * 8); if (!(entry & 1)) continue; entry &= 0x7ffffffff000; page = (int64_t)((uint64_t)(addr | i << level) << 16) >> 16; if (level == 12) { if (ranges->i && page == ranges->p[ranges->i - 1].b) { ranges->p[ranges->i - 1].b += 0x1000; } else { AppendContiguousMemoryRange(ranges, page, page + 0x1000); } } else if (entry + 512 * 8 <= m->real.n) { FindContiguousMemoryRangesImpl(m, ranges, page, level - 9, entry, 0, 512); } } } void FindContiguousMemoryRanges(struct Machine *m, struct ContiguousMemoryRanges *ranges) { uint64_t cr3; ranges->i = 0; if ((m->mode & 3) == XED_MODE_LONG) { cr3 = m->cr3 & 0x7ffffffff000; FindContiguousMemoryRangesImpl(m, ranges, 0, 39, cr3, 256, 512); FindContiguousMemoryRangesImpl(m, ranges, 0, 39, cr3, 0, 256); } else { AppendContiguousMemoryRange(ranges, 0, m->real.n); } }
3,426
63
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/elfwriter.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/lib/elfwriter.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/elf/def.h" #include "libc/log/check.h" #include "libc/mem/arraylist2.internal.h" #include "libc/mem/gc.h" #include "libc/runtime/memtrack.internal.h" #include "libc/stdalign.internal.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 "libc/x/xasprintf.h" static const Elf64_Ehdr kObjHeader = { .e_ident = {ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3, ELFCLASS64, ELFDATA2LSB, 1, ELFOSABI_NONE}, .e_type = ET_REL, .e_machine = EM_NEXGEN32E, .e_version = 1, .e_ehsize = sizeof(Elf64_Ehdr), .e_shentsize = sizeof(Elf64_Shdr), }; static size_t AppendSection(struct ElfWriter *elf, const char *name, int sh_type, int sh_flags) { ssize_t section = APPEND(&elf->shdrs->p, &elf->shdrs->i, &elf->shdrs->n, (&(Elf64_Shdr){.sh_type = sh_type, .sh_flags = sh_flags, .sh_entsize = elf->entsize, .sh_addralign = elf->addralign, .sh_offset = sh_type != SHT_NULL ? elf->wrote : 0, .sh_name = intern(elf->shstrtab, name)})); CHECK_NE(-1, section); return section; } static size_t FinishSection(struct ElfWriter *elf) { size_t section = elf->shdrs->i - 1; elf->shdrs->p[section].sh_size = elf->wrote - elf->shdrs->p[section].sh_offset; return section; } static struct ElfWriterSymRef AppendSymbol(struct ElfWriter *elf, const char *name, int st_info, int st_other, size_t st_value, size_t st_size, size_t st_shndx, enum ElfWriterSymOrder slg) { ssize_t sym = APPEND(&elf->syms[slg]->p, &elf->syms[slg]->i, &elf->syms[slg]->n, (&(Elf64_Sym){.st_info = st_info, .st_size = st_size, .st_value = st_value, .st_other = st_other, .st_name = intern(elf->strtab, name), .st_shndx = st_shndx})); CHECK_NE(-1, sym); return (struct ElfWriterSymRef){.slg = slg, .sym = sym}; } static void MakeRelaSection(struct ElfWriter *elf, size_t section) { size_t shdr, size; size = (elf->relas->i - elf->relas->j) * sizeof(Elf64_Rela); elfwriter_align(elf, alignof(Elf64_Rela), sizeof(Elf64_Rela)); shdr = elfwriter_startsection( elf, _gc(xasprintf("%s%s", ".rela", &elf->shstrtab->p[elf->shdrs->p[section].sh_name])), SHT_RELA, SHF_INFO_LINK); elf->shdrs->p[shdr].sh_info = section; elfwriter_reserve(elf, size); elfwriter_commit(elf, size); FinishSection(elf); elf->relas->j = elf->relas->i; } static void WriteRelaSections(struct ElfWriter *elf, size_t symtab) { uint32_t sym; size_t i, j, k; Elf64_Rela *rela; for (j = 0, i = 0; i < elf->shdrs->i; ++i) { if (elf->shdrs->p[i].sh_type == SHT_RELA) { elf->shdrs->p[i].sh_link = symtab; for (rela = (Elf64_Rela *)((char *)elf->map + elf->shdrs->p[i].sh_offset); rela < (Elf64_Rela *)((char *)elf->map + (elf->shdrs->p[i].sh_offset + elf->shdrs->p[i].sh_size)); rela++, j++) { sym = elf->relas->p[j].symkey.sym; for (k = 0; k < elf->relas->p[j].symkey.slg; ++k) { sym += elf->syms[k]->i; } rela->r_offset = elf->relas->p[j].offset; rela->r_info = ELF64_R_INFO(sym, elf->relas->p[j].type); rela->r_addend = elf->relas->p[j].addend; } } } assert(j == elf->relas->i); } static size_t FlushStrtab(struct ElfWriter *elf, const char *name, struct Interner *strtab) { size_t size = strtab->i * sizeof(strtab->p[0]); elfwriter_align(elf, 1, 0); AppendSection(elf, name, SHT_STRTAB, 0); mempcpy(elfwriter_reserve(elf, size), strtab->p, size); elfwriter_commit(elf, size); return FinishSection(elf); } static void FlushTables(struct ElfWriter *elf) { size_t i, size, symtab; elfwriter_align(elf, alignof(Elf64_Sym), sizeof(Elf64_Sym)); symtab = AppendSection(elf, ".symtab", SHT_SYMTAB, 0); for (i = 0; i < ARRAYLEN(elf->syms); ++i) { size = elf->syms[i]->i * sizeof(Elf64_Sym); if (size) { memcpy(elfwriter_reserve(elf, size), elf->syms[i]->p, size); } elfwriter_commit(elf, size); } FinishSection(elf); elf->shdrs->p[symtab].sh_link = FlushStrtab(elf, ".strtab", elf->strtab); elf->ehdr->e_shstrndx = FlushStrtab(elf, ".shstrtab", elf->shstrtab); WriteRelaSections(elf, symtab); size = elf->shdrs->i * sizeof(elf->shdrs->p[0]); elfwriter_align(elf, alignof(Elf64_Shdr), sizeof(elf->shdrs->p[0])); elf->ehdr->e_shoff = elf->wrote; elf->ehdr->e_shnum = elf->shdrs->i; elf->shdrs->p[symtab].sh_info = elf->syms[kElfWriterSymSection]->i + elf->syms[kElfWriterSymLocal]->i; mempcpy(elfwriter_reserve(elf, size), elf->shdrs->p, size); elfwriter_commit(elf, size); } struct ElfWriter *elfwriter_open(const char *path, int mode) { struct ElfWriter *elf; CHECK_NOTNULL((elf = calloc(1, sizeof(struct ElfWriter)))); CHECK_NOTNULL((elf->path = strdup(path))); CHECK_NE(-1, (elf->fd = open(elf->path, O_CREAT | O_TRUNC | O_RDWR, mode))); CHECK_NE(-1, ftruncate(elf->fd, (elf->mapsize = FRAMESIZE))); CHECK_NE(MAP_FAILED, (elf->map = mmap((void *)(intptr_t)kFixedmapStart, elf->mapsize, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, elf->fd, 0))); elf->ehdr = memcpy(elf->map, &kObjHeader, (elf->wrote = sizeof(kObjHeader))); if (strstr(path, "/aarch64")) { elf->ehdr->e_machine = EM_AARCH64; } else if (strstr(path, "/powerpc64")) { elf->ehdr->e_machine = EM_PPC64; } else if (strstr(path, "/riscv")) { elf->ehdr->e_machine = EM_RISCV; } else if (strstr(path, "/s390")) { elf->ehdr->e_machine = EM_S390; } elf->strtab = newinterner(); elf->shstrtab = newinterner(); intern(elf->strtab, ""); intern(elf->shstrtab, ""); intern(elf->shstrtab, ".shstrtab"); return elf; } void elfwriter_close(struct ElfWriter *elf) { size_t i; FlushTables(elf); CHECK_NE(-1, msync(elf->map, elf->wrote, MS_ASYNC)); CHECK_NE(-1, munmap(elf->map, elf->mapsize)); CHECK_NE(-1, ftruncate(elf->fd, elf->wrote)); CHECK_NE(-1, close(elf->fd)); freeinterner(elf->shstrtab); freeinterner(elf->strtab); free(elf->shdrs->p); free(elf->relas->p); free(elf->path); for (i = 0; i < ARRAYLEN(elf->syms); ++i) { free(elf->syms[i]->p); } free(elf); } void elfwriter_align(struct ElfWriter *elf, size_t addralign, size_t entsize) { elf->entsize = entsize; elf->addralign = addralign; elf->wrote = ROUNDUP(elf->wrote, addralign); } size_t elfwriter_startsection(struct ElfWriter *elf, const char *name, int sh_type, int sh_flags) { size_t shdr = AppendSection(elf, name, sh_type, sh_flags); AppendSymbol(elf, "", sh_type != SHT_NULL ? ELF64_ST_INFO(STB_LOCAL, STT_SECTION) : ELF64_ST_INFO(STB_LOCAL, STT_NOTYPE), STV_DEFAULT, 0, 0, shdr, kElfWriterSymSection); return shdr; } void *elfwriter_reserve(struct ElfWriter *elf, size_t size) { size_t need, greed; need = elf->wrote + size; greed = elf->mapsize; if (need > greed) { do { greed = greed + (greed >> 1); } while (need > greed); greed = ROUNDUP(greed, FRAMESIZE); CHECK_NE(-1, ftruncate(elf->fd, greed)); CHECK_NE(MAP_FAILED, mmap((char *)elf->map + elf->mapsize, greed - elf->mapsize, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, elf->fd, elf->mapsize)); elf->mapsize = greed; } return (char *)elf->map + elf->wrote; } void elfwriter_commit(struct ElfWriter *elf, size_t size) { elf->wrote += size; } void elfwriter_finishsection(struct ElfWriter *elf) { size_t section = FinishSection(elf); if (elf->relas->j < elf->relas->i) MakeRelaSection(elf, section); } /** * Appends symbol. * * This function should be called between elfwriter_startsection() and * elfwriter_finishsection(). If that's not possible, then this can be * called after elfwriter_open() and then elfwriter_setsection() can be * called later to fix-up the section id. */ struct ElfWriterSymRef elfwriter_appendsym(struct ElfWriter *elf, const char *name, int st_info, int st_other, size_t st_value, size_t st_size) { return AppendSymbol( elf, name, st_info, st_other, st_value, st_size, elf->shdrs->i - 1, ELF64_ST_BIND(st_info) == STB_LOCAL ? kElfWriterSymLocal : kElfWriterSymGlobal); } void elfwriter_setsection(struct ElfWriter *elf, struct ElfWriterSymRef sym, uint16_t st_shndx) { elf->syms[sym.slg]->p[sym.sym].st_shndx = st_shndx; } struct ElfWriterSymRef elfwriter_linksym(struct ElfWriter *elf, const char *name, int st_info, int st_other) { return AppendSymbol(elf, name, st_info, st_other, 0, 0, 0, kElfWriterSymGlobal); } void elfwriter_appendrela(struct ElfWriter *elf, uint64_t r_offset, struct ElfWriterSymRef symkey, uint32_t type, int64_t r_addend) { CHECK_NE(-1, APPEND(&elf->relas->p, &elf->relas->i, &elf->relas->n, (&(struct ElfWriterRela){.type = type, .symkey = symkey, .offset = r_offset, .addend = r_addend}))); } uint32_t elfwriter_relatype_abs32(const struct ElfWriter *elf) { switch (elf->ehdr->e_machine) { case EM_NEXGEN32E: return R_X86_64_32; case EM_AARCH64: return R_AARCH64_ABS32; case EM_PPC64: return R_PPC64_ADDR32; case EM_RISCV: return R_RISCV_32; case EM_S390: return R_390_32; default: notpossible; } }
12,398
303
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/fpu.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/math.h" #include "libc/nt/struct/importobjectheader.internal.h" #include "libc/str/str.h" #include "tool/build/lib/case.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/flags.h" #include "tool/build/lib/fpu.h" #include "tool/build/lib/ldbl.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/pun.h" #include "tool/build/lib/throw.h" #define FPUREG 0 #define MEMORY 1 #define DISP(x, y, z) ((7 & (x)) << 4 | (y) << 3 | (z)) static void OnFpuStackOverflow(struct Machine *m) { m->fpu.sw |= kFpuSwIe | kFpuSwC1 | kFpuSwSf; } static double OnFpuStackUnderflow(struct Machine *m) { m->fpu.sw |= kFpuSwIe | kFpuSwSf; m->fpu.sw &= ~kFpuSwC1; return -NAN; } static double St(struct Machine *m, int i) { if (FpuGetTag(m, i) == kFpuTagEmpty) OnFpuStackUnderflow(m); return *FpuSt(m, i); } static double St0(struct Machine *m) { return St(m, 0); } static double St1(struct Machine *m) { return St(m, 1); } static double StRm(struct Machine *m) { return St(m, ModrmRm(m->xedd->op.rde)); } static void FpuClearRoundup(struct Machine *m) { m->fpu.sw &= ~kFpuSwC1; } static void FpuClearOutOfRangeIndicator(struct Machine *m) { m->fpu.sw &= ~kFpuSwC2; } static void FpuSetSt0(struct Machine *m, double x) { *FpuSt(m, 0) = x; } static void FpuSetStRm(struct Machine *m, double x) { *FpuSt(m, ModrmRm(m->xedd->op.rde)) = x; } static void FpuSetStPop(struct Machine *m, int i, double x) { *FpuSt(m, i) = x; FpuPop(m); } static void FpuSetStRmPop(struct Machine *m, double x) { FpuSetStPop(m, ModrmRm(m->xedd->op.rde), x); } static int16_t FpuGetMemoryShort(struct Machine *m) { uint8_t b[2]; return Read16(Load(m, m->fpu.dp, 2, b)); } static int32_t FpuGetMemoryInt(struct Machine *m) { uint8_t b[4]; return Read32(Load(m, m->fpu.dp, 4, b)); } static int64_t FpuGetMemoryLong(struct Machine *m) { uint8_t b[8]; return Read64(Load(m, m->fpu.dp, 8, b)); } static float FpuGetMemoryFloat(struct Machine *m) { union FloatPun u; u.i = FpuGetMemoryInt(m); return u.f; } static double FpuGetMemoryDouble(struct Machine *m) { union DoublePun u; u.i = FpuGetMemoryLong(m); return u.f; } static void FpuSetMemoryShort(struct Machine *m, int16_t i) { void *p[2]; uint8_t b[2]; Write16(BeginStore(m, m->fpu.dp, 2, p, b), i); EndStore(m, m->fpu.dp, 2, p, b); } static void FpuSetMemoryInt(struct Machine *m, int32_t i) { void *p[2]; uint8_t b[4]; Write32(BeginStore(m, m->fpu.dp, 4, p, b), i); EndStore(m, m->fpu.dp, 4, p, b); } static void FpuSetMemoryLong(struct Machine *m, int64_t i) { void *p[2]; uint8_t b[8]; Write64(BeginStore(m, m->fpu.dp, 8, p, b), i); EndStore(m, m->fpu.dp, 8, p, b); } static void FpuSetMemoryFloat(struct Machine *m, float f) { union FloatPun u = {f}; FpuSetMemoryInt(m, u.i); } static void FpuSetMemoryDouble(struct Machine *m, double f) { union DoublePun u = {f}; FpuSetMemoryLong(m, u.i); } static double FpuGetMemoryLdbl(struct Machine *m) { uint8_t b[10]; return DeserializeLdbl(Load(m, m->fpu.dp, 10, b)); } static void FpuSetMemoryLdbl(struct Machine *m, double f) { void *p[2]; uint8_t b[10], t[10]; SerializeLdbl(b, f); memcpy(BeginStore(m, m->fpu.dp, 10, p, t), b, 10); EndStore(m, m->fpu.dp, 10, p, t); } static double f2xm1(double x) { return exp2(x) - 1; } static double fyl2x(double x, double y) { return y * log2(x); } static double fyl2xp1(double x, double y) { return y * log2(x + 1); } static double fscale(double significand, double exponent) { if (isunordered(significand, exponent)) return NAN; return ldexp(significand, exponent); } static double x87remainder(double x, double y, uint32_t *sw, double rem(double, double), double rnd(double)) { int s; long q; double r; s = 0; r = rem(x, y); q = rnd(x / y); s &= ~kFpuSwC2; /* ty libm */ if (q & 1) s |= kFpuSwC1; if (q & 2) s |= kFpuSwC3; if (q & 4) s |= kFpuSwC0; if (sw) *sw = s | (*sw & ~(kFpuSwC0 | kFpuSwC1 | kFpuSwC2 | kFpuSwC3)); return r; } static double fprem(double dividend, double modulus, uint32_t *sw) { return x87remainder(dividend, modulus, sw, fmod, trunc); } static double fprem1(double dividend, double modulus, uint32_t *sw) { return x87remainder(dividend, modulus, sw, remainder, rint); } static double FpuAdd(struct Machine *m, double x, double y) { if (!isunordered(x, y)) { switch (isinf(y) << 1 | isinf(x)) { case 0: return x + y; case 1: return x; case 2: return y; case 3: if (signbit(x) == signbit(y)) { return x; } else { m->fpu.sw |= kFpuSwIe; return copysign(NAN, x); } default: for (;;) (void)0; } } else { return NAN; } } static double FpuSub(struct Machine *m, double x, double y) { if (!isunordered(x, y)) { switch (isinf(y) << 1 | isinf(x)) { case 0: return x - y; case 1: return -x; case 2: return y; case 3: if (signbit(x) == signbit(y)) { m->fpu.sw |= kFpuSwIe; return copysign(NAN, x); } else { return y; } default: for (;;) (void)0; } } else { return NAN; } } static double FpuMul(struct Machine *m, double x, double y) { if (!isunordered(x, y)) { if (!((isinf(x) && !y) || (isinf(y) && !x))) { return x * y; } else { m->fpu.sw |= kFpuSwIe; return -NAN; } } else { return NAN; } } static double FpuDiv(struct Machine *m, double x, double y) { if (!isunordered(x, y)) { if (x || y) { if (y) { return x / y; } else { m->fpu.sw |= kFpuSwZe; return copysign(INFINITY, x); } } else { m->fpu.sw |= kFpuSwIe; return copysign(NAN, x); } } else { return NAN; } } static double FpuRound(struct Machine *m, double x) { switch ((m->fpu.cw & kFpuCwRc) >> 10) { case 0: return rint(x); case 1: return floor(x); case 2: return ceil(x); case 3: return trunc(x); default: for (;;) (void)0; } } static void FpuCompare(struct Machine *m, double y) { double x = St0(m); m->fpu.sw &= ~(kFpuSwC0 | kFpuSwC1 | kFpuSwC2 | kFpuSwC3); if (!isunordered(x, y)) { if (x < y) m->fpu.sw |= kFpuSwC0; if (x == y) m->fpu.sw |= kFpuSwC3; } else { m->fpu.sw |= kFpuSwC0 | kFpuSwC2 | kFpuSwC3 | kFpuSwIe; } } static void OpFxam(struct Machine *m) { double x; x = *FpuSt(m, 0); m->fpu.sw &= ~(kFpuSwC0 | kFpuSwC1 | kFpuSwC2 | kFpuSwC3); if (signbit(x)) m->fpu.sw |= kFpuSwC1; if (FpuGetTag(m, 0) == kFpuTagEmpty) { m->fpu.sw |= kFpuSwC0 | kFpuSwC3; } else { switch (fpclassify(x)) { case FP_NAN: m->fpu.sw |= kFpuSwC0; break; case FP_INFINITE: m->fpu.sw |= kFpuSwC0 | kFpuSwC2; break; case FP_ZERO: m->fpu.sw |= kFpuSwC3; break; case FP_SUBNORMAL: m->fpu.sw |= kFpuSwC2 | kFpuSwC3; break; case FP_NORMAL: m->fpu.sw |= kFpuSwC2; break; default: for (;;) (void)0; } } } static void OpFtst(struct Machine *m) { FpuCompare(m, 0); } static void OpFcmovb(struct Machine *m) { if (GetFlag(m->flags, FLAGS_CF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmove(struct Machine *m) { if (GetFlag(m->flags, FLAGS_ZF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovbe(struct Machine *m) { if (GetFlag(m->flags, FLAGS_CF) || GetFlag(m->flags, FLAGS_ZF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovu(struct Machine *m) { if (GetFlag(m->flags, FLAGS_PF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovnb(struct Machine *m) { if (!GetFlag(m->flags, FLAGS_CF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovne(struct Machine *m) { if (!GetFlag(m->flags, FLAGS_ZF)) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovnbe(struct Machine *m) { if (!(GetFlag(m->flags, FLAGS_CF) || GetFlag(m->flags, FLAGS_ZF))) { FpuSetSt0(m, StRm(m)); } } static void OpFcmovnu(struct Machine *m) { if (!GetFlag(m->flags, FLAGS_PF)) { FpuSetSt0(m, StRm(m)); } } static void OpFchs(struct Machine *m) { FpuSetSt0(m, -St0(m)); } static void OpFabs(struct Machine *m) { FpuSetSt0(m, fabs(St0(m))); } static void OpF2xm1(struct Machine *m) { FpuSetSt0(m, f2xm1(St0(m))); } static void OpFyl2x(struct Machine *m) { FpuSetStPop(m, 1, fyl2x(St0(m), St1(m))); } static void OpFyl2xp1(struct Machine *m) { FpuSetStPop(m, 1, fyl2xp1(St0(m), St1(m))); } static void OpFcos(struct Machine *m) { FpuClearOutOfRangeIndicator(m); FpuSetSt0(m, cos(St0(m))); } static void OpFsin(struct Machine *m) { FpuClearOutOfRangeIndicator(m); FpuSetSt0(m, sin(St0(m))); } static void OpFptan(struct Machine *m) { FpuClearOutOfRangeIndicator(m); FpuSetSt0(m, tan(St0(m))); FpuPush(m, 1); } static void OpFsincos(struct Machine *m) { double tsin, tcos; FpuClearOutOfRangeIndicator(m); tsin = sin(St0(m)); tcos = cos(St0(m)); FpuSetSt0(m, tsin); FpuPush(m, tcos); } static void OpFpatan(struct Machine *m) { FpuClearRoundup(m); FpuSetStPop(m, 1, atan2(St1(m), St0(m))); } static void OpFcom(struct Machine *m) { FpuCompare(m, StRm(m)); } static void OpFcomp(struct Machine *m) { FpuCompare(m, StRm(m)); FpuPop(m); } static void OpFaddStEst(struct Machine *m) { FpuSetSt0(m, FpuAdd(m, St0(m), StRm(m))); } static void OpFmulStEst(struct Machine *m) { FpuSetSt0(m, FpuMul(m, St0(m), StRm(m))); } static void OpFsubStEst(struct Machine *m) { FpuSetSt0(m, FpuSub(m, St0(m), StRm(m))); } static void OpFsubrStEst(struct Machine *m) { FpuSetSt0(m, FpuSub(m, StRm(m), St0(m))); } static void OpFdivStEst(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, St0(m), StRm(m))); } static void OpFdivrStEst(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, StRm(m), St0(m))); } static void OpFaddEstSt(struct Machine *m) { FpuSetStRm(m, FpuAdd(m, StRm(m), St0(m))); } static void OpFmulEstSt(struct Machine *m) { FpuSetStRm(m, FpuMul(m, StRm(m), St0(m))); } static void OpFsubEstSt(struct Machine *m) { FpuSetStRm(m, FpuSub(m, St0(m), StRm(m))); } static void OpFsubrEstSt(struct Machine *m) { FpuSetStRm(m, FpuSub(m, StRm(m), St0(m))); } static void OpFdivEstSt(struct Machine *m) { FpuSetStRm(m, FpuDiv(m, StRm(m), St0(m))); } static void OpFdivrEstSt(struct Machine *m) { FpuSetStRm(m, FpuDiv(m, St0(m), StRm(m))); } static void OpFaddp(struct Machine *m) { FpuSetStRmPop(m, FpuAdd(m, St0(m), StRm(m))); } static void OpFmulp(struct Machine *m) { FpuSetStRmPop(m, FpuMul(m, St0(m), StRm(m))); } static void OpFcompp(struct Machine *m) { OpFcomp(m); FpuPop(m); } static void OpFsubp(struct Machine *m) { FpuSetStRmPop(m, FpuSub(m, St0(m), StRm(m))); } static void OpFsubrp(struct Machine *m) { FpuSetStPop(m, 1, FpuSub(m, StRm(m), St0(m))); } static void OpFdivp(struct Machine *m) { FpuSetStRmPop(m, FpuDiv(m, St0(m), StRm(m))); } static void OpFdivrp(struct Machine *m) { FpuSetStRmPop(m, FpuDiv(m, StRm(m), St0(m))); } static void OpFadds(struct Machine *m) { FpuSetSt0(m, FpuAdd(m, St0(m), FpuGetMemoryFloat(m))); } static void OpFmuls(struct Machine *m) { FpuSetSt0(m, FpuMul(m, St0(m), FpuGetMemoryFloat(m))); } static void OpFcoms(struct Machine *m) { FpuCompare(m, FpuGetMemoryFloat(m)); } static void OpFcomps(struct Machine *m) { OpFcoms(m); FpuPop(m); } static void OpFsubs(struct Machine *m) { FpuSetSt0(m, FpuSub(m, St0(m), FpuGetMemoryFloat(m))); } static void OpFsubrs(struct Machine *m) { FpuSetSt0(m, FpuSub(m, FpuGetMemoryFloat(m), St0(m))); } static void OpFdivs(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, St0(m), FpuGetMemoryFloat(m))); } static void OpFdivrs(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, FpuGetMemoryFloat(m), St0(m))); } static void OpFaddl(struct Machine *m) { FpuSetSt0(m, FpuAdd(m, St0(m), FpuGetMemoryDouble(m))); } static void OpFmull(struct Machine *m) { FpuSetSt0(m, FpuMul(m, St0(m), FpuGetMemoryDouble(m))); } static void OpFcoml(struct Machine *m) { FpuCompare(m, FpuGetMemoryDouble(m)); } static void OpFcompl(struct Machine *m) { FpuCompare(m, FpuGetMemoryDouble(m)); FpuPop(m); } static void OpFsubl(struct Machine *m) { FpuSetSt0(m, FpuSub(m, St0(m), FpuGetMemoryDouble(m))); } static void OpFsubrl(struct Machine *m) { FpuSetSt0(m, FpuSub(m, FpuGetMemoryDouble(m), St0(m))); } static void OpFdivl(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, St0(m), FpuGetMemoryDouble(m))); } static void OpFdivrl(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, FpuGetMemoryDouble(m), St0(m))); } static void OpFiaddl(struct Machine *m) { FpuSetSt0(m, FpuAdd(m, St0(m), FpuGetMemoryInt(m))); } static void OpFimull(struct Machine *m) { FpuSetSt0(m, FpuMul(m, St0(m), FpuGetMemoryInt(m))); } static void OpFicoml(struct Machine *m) { FpuCompare(m, FpuGetMemoryInt(m)); } static void OpFicompl(struct Machine *m) { OpFicoml(m); FpuPop(m); } static void OpFisubl(struct Machine *m) { FpuSetSt0(m, FpuSub(m, St0(m), FpuGetMemoryInt(m))); } static void OpFisubrl(struct Machine *m) { FpuSetSt0(m, FpuSub(m, FpuGetMemoryInt(m), St0(m))); } static void OpFidivl(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, St0(m), FpuGetMemoryInt(m))); } static void OpFidivrl(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, FpuGetMemoryInt(m), St0(m))); } static void OpFiadds(struct Machine *m) { FpuSetSt0(m, FpuAdd(m, St0(m), FpuGetMemoryShort(m))); } static void OpFimuls(struct Machine *m) { FpuSetSt0(m, FpuMul(m, St0(m), FpuGetMemoryShort(m))); } static void OpFicoms(struct Machine *m) { FpuCompare(m, FpuGetMemoryShort(m)); } static void OpFicomps(struct Machine *m) { OpFicoms(m); FpuPop(m); } static void OpFisubs(struct Machine *m) { FpuSetSt0(m, FpuSub(m, St0(m), FpuGetMemoryShort(m))); } static void OpFisubrs(struct Machine *m) { FpuSetSt0(m, FpuSub(m, FpuGetMemoryShort(m), St0(m))); } static void OpFidivs(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, St0(m), FpuGetMemoryShort(m))); } static void OpFidivrs(struct Machine *m) { FpuSetSt0(m, FpuDiv(m, FpuGetMemoryShort(m), St0(m))); } static void OpFsqrt(struct Machine *m) { FpuClearRoundup(m); FpuSetSt0(m, sqrt(St0(m))); } static void OpFrndint(struct Machine *m) { FpuSetSt0(m, FpuRound(m, St0(m))); } static void OpFscale(struct Machine *m) { FpuClearRoundup(m); FpuSetSt0(m, fscale(St0(m), St1(m))); } static void OpFprem(struct Machine *m) { FpuSetSt0(m, fprem(St0(m), St1(m), &m->fpu.sw)); } static void OpFprem1(struct Machine *m) { FpuSetSt0(m, fprem1(St0(m), St1(m), &m->fpu.sw)); } static void OpFdecstp(struct Machine *m) { m->fpu.sw = (m->fpu.sw & ~kFpuSwSp) | ((m->fpu.sw - (1 << 11)) & kFpuSwSp); } static void OpFincstp(struct Machine *m) { m->fpu.sw = (m->fpu.sw & ~kFpuSwSp) | ((m->fpu.sw + (1 << 11)) & kFpuSwSp); } static void OpFxtract(struct Machine *m) { double x = St0(m); FpuSetSt0(m, logb(x)); FpuPush(m, ldexp(x, -ilogb(x))); } static void OpFld(struct Machine *m) { FpuPush(m, StRm(m)); } static void OpFlds(struct Machine *m) { FpuPush(m, FpuGetMemoryFloat(m)); } static void OpFsts(struct Machine *m) { FpuSetMemoryFloat(m, St0(m)); } static void OpFstps(struct Machine *m) { OpFsts(m); FpuPop(m); } static void OpFstpt(struct Machine *m) { FpuSetMemoryLdbl(m, FpuPop(m)); } static void OpFstl(struct Machine *m) { FpuSetMemoryDouble(m, St0(m)); } static void OpFstpl(struct Machine *m) { OpFstl(m); FpuPop(m); } static void OpFst(struct Machine *m) { FpuSetStRm(m, St0(m)); } static void OpFstp(struct Machine *m) { FpuSetStRmPop(m, St0(m)); } static void OpFxch(struct Machine *m) { double t = StRm(m); FpuSetStRm(m, St0(m)); FpuSetSt0(m, t); } static void OpFldcw(struct Machine *m) { m->fpu.cw = FpuGetMemoryShort(m); } static void OpFldt(struct Machine *m) { FpuPush(m, FpuGetMemoryLdbl(m)); } static void OpFldl(struct Machine *m) { FpuPush(m, FpuGetMemoryDouble(m)); } static double Fld1(void) { return 1; } static double Fldl2t(void) { return 0xd.49a784bcd1b8afep-2L; /* log₂10 */ } static double Fldl2e(void) { return 0xb.8aa3b295c17f0bcp-3L; /* log₂𝑒 */ } static double Fldpi(void) { return 0x1.921fb54442d1846ap+1L; /* π */ } static double Fldlg2(void) { return 0x9.a209a84fbcff799p-5L; /* log₁₀2 */ } static double Fldln2(void) { return 0xb.17217f7d1cf79acp-4L; /* logₑ2 */ } static double Fldz(void) { return 0; } static void OpFldConstant(struct Machine *m) { double x; switch (ModrmRm(m->xedd->op.rde)) { CASE(0, x = Fld1()); CASE(1, x = Fldl2t()); CASE(2, x = Fldl2e()); CASE(3, x = Fldpi()); CASE(4, x = Fldlg2()); CASE(5, x = Fldln2()); CASE(6, x = Fldz()); default: OpUd(m, m->xedd->op.rde); } FpuPush(m, x); } static void OpFstcw(struct Machine *m) { FpuSetMemoryShort(m, m->fpu.cw); } static void OpFilds(struct Machine *m) { FpuPush(m, FpuGetMemoryShort(m)); } static void OpFildl(struct Machine *m) { FpuPush(m, FpuGetMemoryInt(m)); } static void OpFildll(struct Machine *m) { FpuPush(m, FpuGetMemoryLong(m)); } static void OpFisttpl(struct Machine *m) { FpuSetMemoryInt(m, FpuPop(m)); } static void OpFisttpll(struct Machine *m) { FpuSetMemoryLong(m, FpuPop(m)); } static void OpFisttps(struct Machine *m) { FpuSetMemoryShort(m, FpuPop(m)); } static void OpFists(struct Machine *m) { FpuSetMemoryShort(m, FpuRound(m, St0(m))); } static void OpFistl(struct Machine *m) { FpuSetMemoryInt(m, FpuRound(m, St0(m))); } static void OpFistll(struct Machine *m) { FpuSetMemoryLong(m, FpuRound(m, St0(m))); } static void OpFistpl(struct Machine *m) { OpFistl(m); FpuPop(m); } static void OpFistpll(struct Machine *m) { OpFistll(m); FpuPop(m); } static void OpFistps(struct Machine *m) { OpFists(m); FpuPop(m); } static void OpFcomi(struct Machine *m) { double x, y; x = St0(m); y = StRm(m); if (!isunordered(x, y)) { m->flags = SetFlag(m->flags, FLAGS_ZF, x == y); m->flags = SetFlag(m->flags, FLAGS_CF, x < y); m->flags = SetFlag(m->flags, FLAGS_PF, false); } else { m->fpu.sw |= kFpuSwIe; m->flags = SetFlag(m->flags, FLAGS_ZF, true); m->flags = SetFlag(m->flags, FLAGS_CF, true); m->flags = SetFlag(m->flags, FLAGS_PF, true); } } static void OpFucom(struct Machine *m) { FpuCompare(m, StRm(m)); } static void OpFucomp(struct Machine *m) { FpuCompare(m, StRm(m)); FpuPop(m); } static void OpFcomip(struct Machine *m) { OpFcomi(m); FpuPop(m); } static void OpFucomi(struct Machine *m) { OpFcomi(m); } static void OpFucomip(struct Machine *m) { OpFcomip(m); } static void OpFfree(struct Machine *m) { FpuSetTag(m, ModrmRm(m->xedd->op.rde), kFpuTagEmpty); } static void OpFfreep(struct Machine *m) { if (ModrmRm(m->xedd->op.rde)) OpFfree(m); FpuPop(m); } static void OpFstswMw(struct Machine *m) { FpuSetMemoryShort(m, m->fpu.sw); } static void OpFstswAx(struct Machine *m) { Write16(m->ax, m->fpu.sw); } static void SetFpuEnv(struct Machine *m, uint8_t p[28]) { Write16(p + 0, m->fpu.cw); Write16(p + 4, m->fpu.sw); Write16(p + 8, m->fpu.tw); Write64(p + 12, m->fpu.ip); Write16(p + 18, m->fpu.op); Write64(p + 20, m->fpu.dp); } static void GetFpuEnv(struct Machine *m, uint8_t p[28]) { m->fpu.cw = Read16(p + 0); m->fpu.sw = Read16(p + 4); m->fpu.tw = Read16(p + 8); } static void OpFstenv(struct Machine *m) { void *p[2]; uint8_t b[28]; SetFpuEnv(m, BeginStore(m, m->fpu.dp, sizeof(b), p, b)); EndStore(m, m->fpu.dp, sizeof(b), p, b); } static void OpFldenv(struct Machine *m) { uint8_t b[28]; GetFpuEnv(m, Load(m, m->fpu.dp, sizeof(b), b)); } static void OpFsave(struct Machine *m) { int i; void *p[2]; uint8_t *a, b[108], t[16]; a = BeginStore(m, m->fpu.dp, sizeof(b), p, b); SetFpuEnv(m, a); memset(t, 0, sizeof(t)); for (i = 0; i < 8; ++i) { SerializeLdbl(a + 28 + i * 10, *FpuSt(m, i)); } EndStore(m, m->fpu.dp, sizeof(b), p, b); OpFinit(m); } static void OpFrstor(struct Machine *m) { int i; uint8_t *a, b[108]; a = Load(m, m->fpu.dp, sizeof(b), b); GetFpuEnv(m, a); for (i = 0; i < 8; ++i) { *FpuSt(m, i) = DeserializeLdbl(a + 28 + i * 10); } } static void OpFnclex(struct Machine *m) { m->fpu.sw &= ~(kFpuSwIe | kFpuSwDe | kFpuSwZe | kFpuSwOe | kFpuSwUe | kFpuSwPe | kFpuSwEs | kFpuSwSf | kFpuSwBf); } static void OpFnop(struct Machine *m) { /* do nothing */ } void OpFinit(struct Machine *m) { m->fpu.cw = 0x037f; m->fpu.sw = 0; m->fpu.tw = -1; } void OpFwait(struct Machine *m, uint32_t rde) { int sw, cw; sw = m->fpu.sw; cw = m->fpu.cw; if (((sw & kFpuSwIe) && !(cw & kFpuCwIm)) || ((sw & kFpuSwDe) && !(cw & kFpuCwDm)) || ((sw & kFpuSwZe) && !(cw & kFpuCwZm)) || ((sw & kFpuSwOe) && !(cw & kFpuCwOm)) || ((sw & kFpuSwUe) && !(cw & kFpuCwUm)) || ((sw & kFpuSwPe) && !(cw & kFpuCwPm)) || ((sw & kFpuSwSf) && !(cw & kFpuCwIm))) { HaltMachine(m, kMachineFpuException); } } int FpuGetTag(struct Machine *m, unsigned i) { unsigned t; t = m->fpu.tw; i += (m->fpu.sw & kFpuSwSp) >> 11; i &= 7; i *= 2; t &= 3 << i; t >>= i; return t; } void FpuSetTag(struct Machine *m, unsigned i, unsigned t) { i += (m->fpu.sw & kFpuSwSp) >> 11; t &= 3; i &= 7; i *= 2; m->fpu.tw &= ~(3 << i); m->fpu.tw |= t << i; } void FpuPush(struct Machine *m, double x) { if (FpuGetTag(m, -1) != kFpuTagEmpty) OnFpuStackOverflow(m); m->fpu.sw = (m->fpu.sw & ~kFpuSwSp) | ((m->fpu.sw - (1 << 11)) & kFpuSwSp); *FpuSt(m, 0) = x; FpuSetTag(m, 0, kFpuTagValid); } double FpuPop(struct Machine *m) { double x; if (FpuGetTag(m, 0) != kFpuTagEmpty) { x = *FpuSt(m, 0); FpuSetTag(m, 0, kFpuTagEmpty); } else { x = OnFpuStackUnderflow(m); } m->fpu.sw = (m->fpu.sw & ~kFpuSwSp) | ((m->fpu.sw + (1 << 11)) & kFpuSwSp); return x; } void OpFpu(struct Machine *m, uint32_t rde) { unsigned op; bool ismemory; op = m->xedd->op.opcode & 7; ismemory = ModrmMod(rde) != 3; m->fpu.ip = m->ip - m->xedd->length; m->fpu.op = op << 8 | ModrmMod(rde) << 6 | ModrmReg(rde) << 3 | ModrmRm(rde); m->fpu.dp = ismemory ? ComputeAddress(m, rde) : 0; switch (DISP(op, ismemory, ModrmReg(rde))) { CASE(DISP(0xD8, FPUREG, 0), OpFaddStEst(m)); CASE(DISP(0xD8, FPUREG, 1), OpFmulStEst(m)); CASE(DISP(0xD8, FPUREG, 2), OpFcom(m)); CASE(DISP(0xD8, FPUREG, 3), OpFcomp(m)); CASE(DISP(0xD8, FPUREG, 4), OpFsubStEst(m)); CASE(DISP(0xD8, FPUREG, 5), OpFsubrStEst(m)); CASE(DISP(0xD8, FPUREG, 6), OpFdivStEst(m)); CASE(DISP(0xD8, FPUREG, 7), OpFdivrStEst(m)); CASE(DISP(0xD8, MEMORY, 0), OpFadds(m)); CASE(DISP(0xD8, MEMORY, 1), OpFmuls(m)); CASE(DISP(0xD8, MEMORY, 2), OpFcoms(m)); CASE(DISP(0xD8, MEMORY, 3), OpFcomps(m)); CASE(DISP(0xD8, MEMORY, 4), OpFsubs(m)); CASE(DISP(0xD8, MEMORY, 5), OpFsubrs(m)); CASE(DISP(0xD8, MEMORY, 6), OpFdivs(m)); CASE(DISP(0xD8, MEMORY, 7), OpFdivrs(m)); CASE(DISP(0xD9, FPUREG, 0), OpFld(m)); CASE(DISP(0xD9, FPUREG, 1), OpFxch(m)); CASE(DISP(0xD9, FPUREG, 2), OpFnop(m)); CASE(DISP(0xD9, FPUREG, 3), OpFstp(m)); CASE(DISP(0xD9, FPUREG, 5), OpFldConstant(m)); CASE(DISP(0xD9, MEMORY, 0), OpFlds(m)); CASE(DISP(0xD9, MEMORY, 2), OpFsts(m)); CASE(DISP(0xD9, MEMORY, 3), OpFstps(m)); CASE(DISP(0xD9, MEMORY, 4), OpFldenv(m)); CASE(DISP(0xD9, MEMORY, 5), OpFldcw(m)); CASE(DISP(0xD9, MEMORY, 6), OpFstenv(m)); CASE(DISP(0xD9, MEMORY, 7), OpFstcw(m)); CASE(DISP(0xDA, FPUREG, 0), OpFcmovb(m)); CASE(DISP(0xDA, FPUREG, 1), OpFcmove(m)); CASE(DISP(0xDA, FPUREG, 2), OpFcmovbe(m)); CASE(DISP(0xDA, FPUREG, 3), OpFcmovu(m)); CASE(DISP(0xDA, MEMORY, 0), OpFiaddl(m)); CASE(DISP(0xDA, MEMORY, 1), OpFimull(m)); CASE(DISP(0xDA, MEMORY, 2), OpFicoml(m)); CASE(DISP(0xDA, MEMORY, 3), OpFicompl(m)); CASE(DISP(0xDA, MEMORY, 4), OpFisubl(m)); CASE(DISP(0xDA, MEMORY, 5), OpFisubrl(m)); CASE(DISP(0xDA, MEMORY, 6), OpFidivl(m)); CASE(DISP(0xDA, MEMORY, 7), OpFidivrl(m)); CASE(DISP(0xDB, FPUREG, 0), OpFcmovnb(m)); CASE(DISP(0xDB, FPUREG, 1), OpFcmovne(m)); CASE(DISP(0xDB, FPUREG, 2), OpFcmovnbe(m)); CASE(DISP(0xDB, FPUREG, 3), OpFcmovnu(m)); CASE(DISP(0xDB, FPUREG, 5), OpFucomi(m)); CASE(DISP(0xDB, FPUREG, 6), OpFcomi(m)); CASE(DISP(0xDB, MEMORY, 0), OpFildl(m)); CASE(DISP(0xDB, MEMORY, 1), OpFisttpl(m)); CASE(DISP(0xDB, MEMORY, 2), OpFistl(m)); CASE(DISP(0xDB, MEMORY, 3), OpFistpl(m)); CASE(DISP(0xDB, MEMORY, 5), OpFldt(m)); CASE(DISP(0xDB, MEMORY, 7), OpFstpt(m)); CASE(DISP(0xDC, FPUREG, 0), OpFaddEstSt(m)); CASE(DISP(0xDC, FPUREG, 1), OpFmulEstSt(m)); CASE(DISP(0xDC, FPUREG, 2), OpFcom(m)); CASE(DISP(0xDC, FPUREG, 3), OpFcomp(m)); CASE(DISP(0xDC, FPUREG, 4), OpFsubEstSt(m)); CASE(DISP(0xDC, FPUREG, 5), OpFsubrEstSt(m)); CASE(DISP(0xDC, FPUREG, 6), OpFdivEstSt(m)); CASE(DISP(0xDC, FPUREG, 7), OpFdivrEstSt(m)); CASE(DISP(0xDC, MEMORY, 0), OpFaddl(m)); CASE(DISP(0xDC, MEMORY, 1), OpFmull(m)); CASE(DISP(0xDC, MEMORY, 2), OpFcoml(m)); CASE(DISP(0xDC, MEMORY, 3), OpFcompl(m)); CASE(DISP(0xDC, MEMORY, 4), OpFsubl(m)); CASE(DISP(0xDC, MEMORY, 5), OpFsubrl(m)); CASE(DISP(0xDC, MEMORY, 6), OpFdivl(m)); CASE(DISP(0xDC, MEMORY, 7), OpFdivrl(m)); CASE(DISP(0xDD, FPUREG, 0), OpFfree(m)); CASE(DISP(0xDD, FPUREG, 1), OpFxch(m)); CASE(DISP(0xDD, FPUREG, 2), OpFst(m)); CASE(DISP(0xDD, FPUREG, 3), OpFstp(m)); CASE(DISP(0xDD, FPUREG, 4), OpFucom(m)); CASE(DISP(0xDD, FPUREG, 5), OpFucomp(m)); CASE(DISP(0xDD, MEMORY, 0), OpFldl(m)); CASE(DISP(0xDD, MEMORY, 1), OpFisttpll(m)); CASE(DISP(0xDD, MEMORY, 2), OpFstl(m)); CASE(DISP(0xDD, MEMORY, 3), OpFstpl(m)); CASE(DISP(0xDD, MEMORY, 4), OpFrstor(m)); CASE(DISP(0xDD, MEMORY, 6), OpFsave(m)); CASE(DISP(0xDD, MEMORY, 7), OpFstswMw(m)); CASE(DISP(0xDE, FPUREG, 0), OpFaddp(m)); CASE(DISP(0xDE, FPUREG, 1), OpFmulp(m)); CASE(DISP(0xDE, FPUREG, 2), OpFcomp(m)); CASE(DISP(0xDE, FPUREG, 3), OpFcompp(m)); CASE(DISP(0xDE, FPUREG, 4), OpFsubp(m)); CASE(DISP(0xDE, FPUREG, 5), OpFsubrp(m)); CASE(DISP(0xDE, FPUREG, 6), OpFdivp(m)); CASE(DISP(0xDE, FPUREG, 7), OpFdivrp(m)); CASE(DISP(0xDE, MEMORY, 0), OpFiadds(m)); CASE(DISP(0xDE, MEMORY, 1), OpFimuls(m)); CASE(DISP(0xDE, MEMORY, 2), OpFicoms(m)); CASE(DISP(0xDE, MEMORY, 3), OpFicomps(m)); CASE(DISP(0xDE, MEMORY, 4), OpFisubs(m)); CASE(DISP(0xDE, MEMORY, 5), OpFisubrs(m)); CASE(DISP(0xDE, MEMORY, 6), OpFidivs(m)); CASE(DISP(0xDE, MEMORY, 7), OpFidivrs(m)); CASE(DISP(0xDF, FPUREG, 0), OpFfreep(m)); CASE(DISP(0xDF, FPUREG, 1), OpFxch(m)); CASE(DISP(0xDF, FPUREG, 2), OpFstp(m)); CASE(DISP(0xDF, FPUREG, 3), OpFstp(m)); CASE(DISP(0xDF, FPUREG, 4), OpFstswAx(m)); CASE(DISP(0xDF, FPUREG, 5), OpFucomip(m)); CASE(DISP(0xDF, FPUREG, 6), OpFcomip(m)); CASE(DISP(0xDF, MEMORY, 0), OpFilds(m)); CASE(DISP(0xDF, MEMORY, 1), OpFisttps(m)); CASE(DISP(0xDF, MEMORY, 2), OpFists(m)); CASE(DISP(0xDF, MEMORY, 3), OpFistps(m)); CASE(DISP(0xDF, MEMORY, 5), OpFildll(m)); CASE(DISP(0xDF, MEMORY, 7), OpFistpll(m)); case DISP(0xD9, FPUREG, 4): switch (ModrmRm(rde)) { CASE(0, OpFchs(m)); CASE(1, OpFabs(m)); CASE(4, OpFtst(m)); CASE(5, OpFxam(m)); default: OpUd(m, rde); } break; case DISP(0xD9, FPUREG, 6): switch (ModrmRm(rde)) { CASE(0, OpF2xm1(m)); CASE(1, OpFyl2x(m)); CASE(2, OpFptan(m)); CASE(3, OpFpatan(m)); CASE(4, OpFxtract(m)); CASE(5, OpFprem1(m)); CASE(6, OpFdecstp(m)); CASE(7, OpFincstp(m)); default: for (;;) (void)0; } break; case DISP(0xD9, FPUREG, 7): switch (ModrmRm(rde)) { CASE(0, OpFprem(m)); CASE(1, OpFyl2xp1(m)); CASE(2, OpFsqrt(m)); CASE(3, OpFsincos(m)); CASE(4, OpFrndint(m)); CASE(5, OpFscale(m)); CASE(6, OpFsin(m)); CASE(7, OpFcos(m)); default: for (;;) (void)0; } break; case DISP(0xDb, FPUREG, 4): switch (ModrmRm(rde)) { CASE(2, OpFnclex(m)); CASE(3, OpFinit(m)); default: OpUd(m, rde); } break; default: OpUd(m, rde); } }
30,546
1,191
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/modrm.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "third_party/xed/x86.h" #include "tool/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/machine.h" #include "tool/build/lib/memory.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/throw.h" /** * Compactly represents important parts of xed ild result. */ uint32_t EncodeRde(struct XedDecodedInst *x) { uint8_t kWordLog2[2][2][2] = {{{2, 3}, {1, 3}}, {{0, 0}, {0, 0}}}; uint32_t osz = x->op.osz ^ x->op.realmode; return kWordLog2[~x->op.opcode & 1][osz][x->op.rexw] << 28 | x->op.mode << 26 | kXedEamode[x->op.asz][x->op.mode] << 24 | (uint32_t)x->op.rep << 30 | x->op.mod << 22 | x->op.asz << 17 | x->op.seg_ovd << 18 | x->op.rexw << 6 | osz << 5 | (x->op.rex << 4 | x->op.rexb << 3 | x->op.srm) << 12 | (x->op.rex << 4 | x->op.rexb << 3 | x->op.rm) << 7 | (x->op.rex << 4 | x->op.rexr << 3 | x->op.reg); } struct AddrSeg LoadEffectiveAddress(const struct Machine *m, uint32_t rde) { uint8_t *s = m->ds; uint64_t i = m->xedd->op.disp; DCHECK(!IsModrmRegister(rde)); if (Eamode(rde) != XED_MODE_REAL) { if (!SibExists(rde)) { if (IsRipRelative(rde)) { if (Mode(rde) == XED_MODE_LONG) { i += m->ip; } } else { i += Read64(RegRexbRm(m, rde)); if (RexbRm(rde) == 4 || RexbRm(rde) == 5) { s = m->ss; } } } else { if (SibHasBase(m->xedd, rde)) { i += Read64(RegRexbBase(m, rde)); if (RexbBase(m, rde) == 4 || RexbBase(m, rde) == 5) { s = m->ss; } } if (SibHasIndex(m->xedd)) { i += Read64(RegRexxIndex(m)) << m->xedd->op.scale; } } if (Eamode(rde) == XED_MODE_LEGACY) { i &= 0xffffffff; } } else { switch (ModrmRm(rde)) { case 0: i += Read16(m->bx); i += Read16(m->si); break; case 1: i += Read16(m->bx); i += Read16(m->di); break; case 2: s = m->ss; i += Read16(m->bp); i += Read16(m->si); break; case 3: s = m->ss; i += Read16(m->bp); i += Read16(m->di); break; case 4: i += Read16(m->si); break; case 5: i += Read16(m->di); break; case 6: if (ModrmMod(rde)) { s = m->ss; i += Read16(m->bp); } break; case 7: i += Read16(m->bx); break; default: unreachable; } i &= 0xffff; } return (struct AddrSeg){i, s}; } int64_t ComputeAddress(const struct Machine *m, uint32_t rde) { struct AddrSeg ea; ea = LoadEffectiveAddress(m, rde); return AddSegment(m, rde, ea.addr, ea.seg); } void *ComputeReserveAddressRead(struct Machine *m, uint32_t rde, size_t n) { int64_t v; v = ComputeAddress(m, rde); SetReadAddr(m, v, n); return ReserveAddress(m, v, n); } void *ComputeReserveAddressRead1(struct Machine *m, uint32_t rde) { return ComputeReserveAddressRead(m, rde, 1); } void *ComputeReserveAddressRead4(struct Machine *m, uint32_t rde) { return ComputeReserveAddressRead(m, rde, 4); } void *ComputeReserveAddressRead8(struct Machine *m, uint32_t rde) { return ComputeReserveAddressRead(m, rde, 8); } void *ComputeReserveAddressWrite(struct Machine *m, uint32_t rde, size_t n) { int64_t v; v = ComputeAddress(m, rde); SetWriteAddr(m, v, n); return ReserveAddress(m, v, n); } void *ComputeReserveAddressWrite1(struct Machine *m, uint32_t rde) { return ComputeReserveAddressWrite(m, rde, 1); } void *ComputeReserveAddressWrite4(struct Machine *m, uint32_t rde) { return ComputeReserveAddressWrite(m, rde, 4); } void *ComputeReserveAddressWrite8(struct Machine *m, uint32_t rde) { return ComputeReserveAddressWrite(m, rde, 8); } uint8_t *GetModrmRegisterMmPointerRead(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return MmRm(m, rde); } else { return ComputeReserveAddressRead(m, rde, n); } } uint8_t *GetModrmRegisterMmPointerRead8(struct Machine *m, uint32_t rde) { return GetModrmRegisterMmPointerRead(m, rde, 8); } uint8_t *GetModrmRegisterMmPointerWrite(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return MmRm(m, rde); } else { return ComputeReserveAddressWrite(m, rde, n); } } uint8_t *GetModrmRegisterMmPointerWrite8(struct Machine *m, uint32_t rde) { return GetModrmRegisterMmPointerWrite(m, rde, 8); } uint8_t *GetModrmRegisterBytePointerRead(struct Machine *m, uint32_t rde) { int64_t v; if (IsModrmRegister(rde)) { return ByteRexbRm(m, rde); } else { return ComputeReserveAddressRead1(m, rde); } } uint8_t *GetModrmRegisterBytePointerWrite(struct Machine *m, uint32_t rde) { int64_t v; if (IsModrmRegister(rde)) { return ByteRexbRm(m, rde); } else { return ComputeReserveAddressWrite1(m, rde); } } uint8_t *GetModrmRegisterWordPointerRead(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return RegRexbRm(m, rde); } else { return ComputeReserveAddressRead(m, rde, n); } } uint8_t *GetModrmRegisterWordPointerRead2(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerRead(m, rde, 2); } uint8_t *GetModrmRegisterWordPointerRead4(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerRead(m, rde, 4); } uint8_t *GetModrmRegisterWordPointerRead8(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerRead(m, rde, 8); } uint8_t *GetModrmRegisterWordPointerReadOsz(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { return GetModrmRegisterWordPointerRead8(m, rde); } else { return GetModrmRegisterWordPointerRead2(m, rde); } } uint8_t *GetModrmRegisterWordPointerReadOszRexw(struct Machine *m, uint32_t rde) { if (Rexw(rde)) { return GetModrmRegisterWordPointerRead8(m, rde); } else if (!Osz(rde)) { return GetModrmRegisterWordPointerRead4(m, rde); } else { return GetModrmRegisterWordPointerRead2(m, rde); } } uint8_t *GetModrmRegisterWordPointerWrite(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return RegRexbRm(m, rde); } else { return ComputeReserveAddressWrite(m, rde, n); } } uint8_t *GetModrmRegisterWordPointerWrite2(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerWrite(m, rde, 2); } uint8_t *GetModrmRegisterWordPointerWrite4(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerWrite(m, rde, 4); } uint8_t *GetModrmRegisterWordPointerWrite8(struct Machine *m, uint32_t rde) { return GetModrmRegisterWordPointerWrite(m, rde, 8); } uint8_t *GetModrmRegisterWordPointerWriteOszRexw(struct Machine *m, uint32_t rde) { if (Rexw(rde)) { return GetModrmRegisterWordPointerWrite(m, rde, 8); } else if (!Osz(rde)) { return GetModrmRegisterWordPointerWrite(m, rde, 4); } else { return GetModrmRegisterWordPointerWrite(m, rde, 2); } } uint8_t *GetModrmRegisterWordPointerWriteOsz(struct Machine *m, uint32_t rde) { if (!Osz(rde)) { return GetModrmRegisterWordPointerWrite(m, rde, 8); } else { return GetModrmRegisterWordPointerWrite(m, rde, 2); } } uint8_t *GetModrmRegisterXmmPointerRead(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return XmmRexbRm(m, rde); } else { return ComputeReserveAddressRead(m, rde, n); } } uint8_t *GetModrmRegisterXmmPointerRead4(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerRead(m, rde, 4); } uint8_t *GetModrmRegisterXmmPointerRead8(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerRead(m, rde, 8); } uint8_t *GetModrmRegisterXmmPointerRead16(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerRead(m, rde, 16); } uint8_t *GetModrmRegisterXmmPointerWrite(struct Machine *m, uint32_t rde, size_t n) { if (IsModrmRegister(rde)) { return XmmRexbRm(m, rde); } else { return ComputeReserveAddressWrite(m, rde, n); } } uint8_t *GetModrmRegisterXmmPointerWrite4(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerWrite(m, rde, 4); } uint8_t *GetModrmRegisterXmmPointerWrite8(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerWrite(m, rde, 8); } uint8_t *GetModrmRegisterXmmPointerWrite16(struct Machine *m, uint32_t rde) { return GetModrmRegisterXmmPointerWrite(m, rde, 16); }
10,667
325
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/signal.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_SIGNAL_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_SIGNAL_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpRestore(struct Machine *); void TerminateSignal(struct Machine *, int); int DeliverSignal(struct Machine *, int, int); int ConsumeSignal(struct Machine *); void EnqueueSignal(struct Machine *, int, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_SIGNAL_H_ */
519
16
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/fds.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/mem/mem.h" #include "tool/build/lib/fds.h" int MachineFdAdd(struct MachineFds *mf) { int fd; struct MachineFdClosed *closed; if ((closed = mf->closed)) { fd = closed->fd; mf->closed = closed->next; free(closed); } else { fd = mf->i; if (mf->i++ == mf->n) { mf->n = mf->i + (mf->i >> 1); mf->p = realloc(mf->p, mf->n * sizeof(*mf->p)); } } return fd; } void MachineFdRemove(struct MachineFds *mf, int fd) { struct MachineFdClosed *closed; mf->p[fd].cb = NULL; if ((closed = malloc(sizeof(struct MachineFdClosed)))) { closed->fd = fd; closed->next = mf->closed; mf->closed = closed; } }
2,534
49
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/cvt.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_CVT_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_CVT_H_ #include "tool/build/lib/machine.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void OpCvt0f2a(struct Machine *, uint32_t); void OpCvtt0f2c(struct Machine *, uint32_t); void OpCvt0f2d(struct Machine *, uint32_t); void OpCvt0f5a(struct Machine *, uint32_t); void OpCvt0f5b(struct Machine *, uint32_t); void OpCvt0fE6(struct Machine *, uint32_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_CVT_H_ */
564
17
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/address.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/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/modrm.h" #include "tool/build/lib/throw.h" uint64_t AddressOb(struct Machine *m, uint32_t rde) { return AddSegment(m, rde, m->xedd->op.disp, m->ds); } uint8_t *GetSegment(struct Machine *m, uint32_t rde, int s) { switch (s & 7) { case 0: return m->es; case 1: return m->cs; case 2: return m->ss; case 3: return m->ds; case 4: return m->fs; case 5: return m->gs; case 6: case 7: OpUd(m, rde); default: unreachable; } } uint64_t AddSegment(struct Machine *m, uint32_t rde, uint64_t i, uint8_t s[8]) { if (!Sego(rde)) { return i + Read64(s); } else { return i + Read64(GetSegment(m, rde, Sego(rde) - 1)); } } uint64_t DataSegment(struct Machine *m, uint32_t rde, uint64_t i) { return AddSegment(m, rde, i, m->ds); } uint64_t AddressSi(struct Machine *m, uint32_t rde) { switch (Eamode(rde)) { case XED_MODE_LONG: return DataSegment(m, rde, Read64(m->si)); case XED_MODE_REAL: return DataSegment(m, rde, Read16(m->si)); case XED_MODE_LEGACY: return DataSegment(m, rde, Read32(m->si)); default: unreachable; } } uint64_t AddressDi(struct Machine *m, uint32_t rde) { uint64_t i = Read64(m->es); switch (Eamode(rde)) { case XED_MODE_LONG: return i + Read64(m->di); case XED_MODE_REAL: return i + Read16(m->di); case XED_MODE_LEGACY: return i + Read32(m->di); default: unreachable; } }
3,445
89
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/flags.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/lib/flags.h" bool GetParity(uint8_t b) { b ^= b >> 4; b ^= b >> 2; b ^= b >> 1; return ~b & 1; } void ImportFlags(struct Machine *m, uint64_t flags) { uint64_t old, mask = 0; mask |= 1u << FLAGS_CF; mask |= 1u << FLAGS_PF; mask |= 1u << FLAGS_AF; mask |= 1u << FLAGS_ZF; mask |= 1u << FLAGS_SF; mask |= 1u << FLAGS_TF; mask |= 1u << FLAGS_IF; mask |= 1u << FLAGS_DF; mask |= 1u << FLAGS_OF; mask |= 1u << FLAGS_NT; mask |= 1u << FLAGS_AC; mask |= 1u << FLAGS_ID; m->flags = (flags & mask) | (m->flags & ~mask); m->flags = SetFlag(m->flags, FLAGS_RF, false); m->flags = SetLazyParityByte(m->flags, !((m->flags >> FLAGS_PF) & 1)); } uint64_t ExportFlags(uint64_t flags) { flags = SetFlag(flags, FLAGS_IOPL, 3); flags = SetFlag(flags, FLAGS_F1, true); flags = SetFlag(flags, FLAGS_F0, false); flags = flags & ~(1ull << FLAGS_PF); flags |= GetLazyParityBool(flags) << FLAGS_PF; return flags; } int64_t AluFlags(uint64_t x, uint32_t af, uint32_t *f, uint32_t of, uint32_t cf, uint32_t sf) { *f &= ~(1u << FLAGS_CF | 1u << FLAGS_ZF | 1u << FLAGS_SF | 1u << FLAGS_OF | 1u << FLAGS_AF | 0xFF000000u); *f |= sf << FLAGS_SF | cf << FLAGS_CF | !x << FLAGS_ZF | of << FLAGS_OF | af << FLAGS_AF | (x & 0xFF) << 24; return x; }
3,168
64
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/throw.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/gc.internal.h" #include "libc/nexgen32e/vendor.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "tool/build/lib/address.h" #include "tool/build/lib/endian.h" #include "tool/build/lib/throw.h" static bool IsHaltingInitialized(struct Machine *m) { jmp_buf zb; bzero(zb, sizeof(zb)); return memcmp(m->onhalt, zb, sizeof(m->onhalt)) != 0; } void HaltMachine(struct Machine *m, int code) { CHECK(IsHaltingInitialized(m)); _gclongjmp(m->onhalt, code); } void ThrowDivideError(struct Machine *m) { HaltMachine(m, kMachineDivideError); } void ThrowSegmentationFault(struct Machine *m, int64_t va) { m->faultaddr = va; if (m->xedd) m->ip -= m->xedd->length; WARNF("%s%s ADDR %012lx IP %012lx AX %lx CX %lx DX %lx BX %lx SP %lx " "BP %lx SI %lx DI %lx R8 %lx R9 %lx R10 %lx R11 %lx R12 %lx R13 %lx " "R14 %lx R15 %lx", "SEGMENTATION FAULT", IsGenuineBlink() ? " SIMULATED" : "", va, m->ip, Read64(m->ax), Read64(m->cx), Read64(m->dx), Read64(m->bx), Read64(m->sp), Read64(m->bp), Read64(m->si), Read64(m->di), Read64(m->r8), Read64(m->r9), Read64(m->r10), Read64(m->r11), Read64(m->r12), Read64(m->r13), Read64(m->r14), Read64(m->r15)); HaltMachine(m, kMachineSegmentationFault); } void ThrowProtectionFault(struct Machine *m) { HaltMachine(m, kMachineProtectionFault); } void OpUd(struct Machine *m, uint32_t rde) { if (m->xedd) m->ip -= m->xedd->length; HaltMachine(m, kMachineUndefinedInstruction); } void OpHlt(struct Machine *m, uint32_t rde) { HaltMachine(m, kMachineHalt); }
3,504
70
jart/cosmopolitan
false
cosmopolitan/tool/build/lib/getargs.h
#ifndef COSMOPOLITAN_TOOL_BUILD_LIB_GETARGS_H_ #define COSMOPOLITAN_TOOL_BUILD_LIB_GETARGS_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct GetArgs { size_t i, j; char **args; char *path; char *map; size_t mapsize; }; void getargs_init(struct GetArgs *, char **); const char *getargs_next(struct GetArgs *); void getargs_destroy(struct GetArgs *); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_BUILD_LIB_GETARGS_H_ */
501
21
jart/cosmopolitan
false