emulator: Replace Linux system calls with a host ABI

f36eb5cf235517cfdd38b5825fea20e549970ac3de00ea2ee837cebdc54226e9
Hosted programs used Linux system call numbers, and openat passed
the guest's Linux flag values straight to the host open(), which is
wrong on hosts with other flag values. Guests could not list
directories or start other programs.

Hosted programs now call a Radiance host ABI from 0x400: exit, read,
write, open, close, stat, makeDir, remove, rename, listDir, spawn,
wait and waitAny. Paths are pointer and length, and errors are host
neutral codes. The Linux-numbered calls are removed; the tag
linux-abi marks the last version with them.

spawn runs another image on this emulator, in hosted or machine
mode, with its own sizes, step budget and output files. The child
reports whether it exited, hit its step limit or faulted, with its
full exit status, through a private pipe. Children still running
are terminated when the parent exits.

All host operations go through host.h, implemented for POSIX hosts
in host_posix.c. machine_run reports timeouts through its config.

Assisted-by: Claude:sonnet-5.5
Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent 4db56f55
Makefile +2 -2
12 12
           -Wmissing-field-initializers \
13 13
           -fno-common -fstack-protector-all \
14 14
           -mcmodel=medium \
15 15
           -march=native -flto
16 16
LDFLAGS := -fuse-ld=lld -Wl,-z,stack-size=33554432
17 -
EMULATOR_SRCS  := emulator.c jit.c riscv/debug.c io.c riscv.c \
17 +
EMULATOR_SRCS  := emulator.c host_posix.c jit.c riscv/debug.c io.c riscv.c \
18 18
                 machine.c machine_cpu.c machine_csr.c machine_devices.c machine_fdt.c
19 19
20 20
default: bin/emulator
21 21
22 -
bin/emulator: $(EMULATOR_SRCS) jit.h muldiv.h color.h types.h io.h riscv.h riscv/debug.h machine.h machine_internal.h
22 +
bin/emulator: $(EMULATOR_SRCS) jit.h muldiv.h color.h types.h io.h host.h riscv.h riscv/debug.h machine.h machine_internal.h
23 23
	@echo "cc    emulator => $@"
24 24
	@mkdir -p bin
25 25
	@$(CC) $(CFLAGS) $(LDFLAGS) $(EMULATOR_SRCS) -o $@
26 26
27 27
install: bin/emulator
README +44 -1
57 57
OPTIONS
58 58
59 59
    -run                    Run headless (no TUI).
60 60
    -debug                  Load debug info for source-level diagnostics.
61 61
    -machine                Run RV64IMA M/U machine images, always headless.
62 -
                            Disables host ecalls, JIT, stack guards and TUI.
62 +
                            Disables hosted calls, JIT, stack guards and TUI.
63 63
    -harts=N                Enable 1..8 independent machine harts (default 1).
64 64
    -irq=N                  Inject one PLIC edge on source 1..31, excluding 10.
65 65
    -irq-at=N               Virtual tick of the one-shot edge (default 0).
66 66
    -no-jit                 Disable the JIT compiler; interpret only.
67 67
    -memory-size=KB         Physical memory size in KB (default 128 MB).
80 80
    -watch-zero-only        Only trigger on zero-value stores.
81 81
    -watch-skip=N           Skip the first N watchpoint hits.
82 82
    -watch-backtrace        Print backtrace on watchpoint hit.
83 83
    -watch-bt-depth=N       Backtrace depth (default 8).
84 84
85 +
HOSTED SYSTEM CALLS
86 +
87 +
  Hosted programs call the emulator with `ecall`: the call number in a7,
88 +
  arguments in a0..a3 and the result in a0. A negative result is an error
89 +
  code. Memory is little-endian. Paths are (pointer, length) pairs without a
90 +
  terminating zero. A range outside guest memory faults the guest.
91 +
92 +
    0x400  exit(status)                       Does not return.
93 +
    0x401  read(fd, ptr, len)                 Bytes read, zero at end of file.
94 +
    0x402  write(fd, ptr, len)                Bytes written.
95 +
    0x403  open(path, len, mode)              Mode 0 reads; mode 1 creates or
96 +
                                              truncates for writing.
97 +
    0x404  close(fd)                          Descriptors 0..2 stay open.
98 +
    0x405  stat(path, len, out)               Writes size (u64), kind (u32:
99 +
                                              1 file, 2 directory, 3 other)
100 +
                                              and u32 padding.
101 +
    0x406  makeDir(path, len)
102 +
    0x407  remove(path, len)                  A file or an empty directory.
103 +
    0x408  rename(from, flen, to, tlen)
104 +
    0x409  listDir(path, len, buf, blen)      Names, each followed by a zero
105 +
                                              byte, without "." and "..".
106 +
    0x40A  spawn(spec)                        Runs an RV64 image in a child
107 +
                                              emulator; returns a child handle.
108 +
    0x40B  wait(child, out)                   Writes the outcome (kind u32:
109 +
                                              0 exited, 1 step limit, 2 fault;
110 +
                                              code i32).
111 +
    0x40C  waitAny(out)                       Returns the handle that ended.
112 +
113 +
  Errors: -1 NotFound, -2 Exists, -3 Denied, -4 NotEmpty, -5 Invalid (also
114 +
  any other call number), -6 TooLarge, -7 Limit, -8 Io.
115 +
116 +
  `spawn` takes a 128-byte record with the image path, the arguments, the
117 +
  destinations of standard output and error, the mode (hosted or machine),
118 +
  the machine and memory sizes, and the step budget. The child runs this
119 +
  executable again with the matching options; its standard input is empty.
120 +
  At most 64 children run at once. The children still running when the guest
121 +
  ends are terminated. A child reports how it ended through the internal
122 +
  option `-outcome-fd=N`, which is not meant to be passed by hand.
123 +
124 +
  The full specification is `.ai/decisions/2026-10-28-host-abi` in the
125 +
  Radiance repository. Everything that touches the host operating system is
126 +
  behind `host.h`; `host_posix.c` implements it for Linux and macOS.
127 +
85 128
MEMORY LAYOUT
86 129
87 130
    0x00010000                 Read-only data
88 131
    Program base               Program text (instructions)
89 132
    0x00FFFFF0                 Read-write data
emulator.c +434 -126
8 8
#include <sys/ioctl.h>
9 9
#include <termios.h>
10 10
#include <unistd.h>
11 11
12 12
#include "color.h"
13 +
#include "host.h"
13 14
#include "io.h"
14 15
#include "jit.h"
15 16
#include "machine.h"
16 17
#include "muldiv.h"
17 18
#include "riscv.h"
242 243
    u32  watch_backtrace_depth;
243 244
    bool validate_memory;
244 245
    bool count_instructions;
245 246
    bool jit_disabled;
246 247
    bool machine_mode;
248 +
    int  outcome_fd; /* Internal: descriptor for the outcome record, or -1. */
247 249
};
248 250
249 251
/* Global emulator options. */
250 252
static struct emulator_options g_opts = {
251 253
    .stack_guard              = true,
268 270
    .watch_backtrace_depth    = 8,
269 271
    .validate_memory          = true,
270 272
    .count_instructions       = false,
271 273
    .jit_disabled             = false,
272 274
    .machine_mode             = false,
275 +
    .outcome_fd               = -1,
273 276
};
274 277
275 278
/* Machine-only options are kept separate from hosted CPU and debugger state. */
276 279
static struct machine_config machine_options = { .hart_count = 1 };
277 280
850 853
        if (strcmp(arg, "-count-instructions") == 0) {
851 854
            g_opts.count_instructions = true;
852 855
            argi++;
853 856
            continue;
854 857
        }
858 +
        if (strncmp(arg, "-outcome-fd=", 12) == 0) {
859 +
            u32 fd;
860 +
            if (!parse_u32(arg + 12, "outcome descriptor", 10, &fd) ||
861 +
                fd > INT_MAX)
862 +
                return false;
863 +
            g_opts.outcome_fd = (int)fd;
864 +
            argi++;
865 +
            continue;
866 +
        }
855 867
        if (strcmp(arg, "-no-jit") == 0) {
856 868
            g_opts.jit_disabled = true;
857 869
            argi++;
858 870
            continue;
859 871
        }
1274 1286
    trace_reset();
1275 1287
    guest_fd_table_init();
1276 1288
    cpu_reset(cpu);
1277 1289
}
1278 1290
1279 -
/* Open a file via the openat syscall (56). */
1280 -
static i32 ecall_openat(u32 pathname_addr, i32 flags) {
1281 -
    if (pathname_addr >= g_opts.memory_size)
1282 -
        return -1;
1283 -
1284 -
    /* Find the null terminator to validate the string is in bounds. */
1285 -
    u32 path_end = pathname_addr;
1286 -
    while (path_end < g_opts.memory_size && memory[path_end] != 0)
1287 -
        path_end++;
1288 -
    if (path_end >= g_opts.memory_size)
1289 -
        return -1;
1290 -
1291 -
    i32 host_fd = open((const char *)&memory[pathname_addr], flags, 0644);
1292 -
    if (host_fd < 0)
1293 -
        return -1;
1294 -
1295 -
    i32 guest_fd = guest_fd_table_add(host_fd);
1296 -
    if (guest_fd < 0) {
1297 -
        close(host_fd);
1298 -
        return -1;
1299 -
    }
1300 -
    return guest_fd;
1301 -
}
1302 -
1303 -
/* Close a file descriptor via the close syscall (57). */
1304 -
static i32 ecall_close(i32 guest_fd) {
1305 -
    /* Don't close standard streams. */
1306 -
    if (guest_fd < 3)
1307 -
        return 0;
1308 -
1309 -
    i32 host_fd = guest_fd_table_get(guest_fd);
1310 -
    if (host_fd >= 0) {
1311 -
        i32 result = close(host_fd);
1312 -
        guest_fd_table_remove(guest_fd);
1313 -
        return result;
1314 -
    }
1315 -
    return -1;
1316 -
}
1317 -
1318 1291
/* Decode a little-endian word without relying on host alignment. */
1319 1292
static u32 decode_u32_le(const u8 *bytes) {
1320 1293
    return (u32)bytes[0] | ((u32)bytes[1] << 8) | ((u32)bytes[2] << 16) |
1321 1294
           ((u32)bytes[3] << 24);
1322 1295
}
1690 1663
1691 1664
    cpu->programsize = program_bytes / sizeof(instr_t);
1692 1665
    cpu->pc          = program_base;
1693 1666
}
1694 1667
1668 +
/* Hosted system calls. The call number is in a7, arguments in a0..a3 and the
1669 +
 * result in a0; a negative result is an error code. See README. */
1670 +
#define ECALL_EXIT     0x400
1671 +
#define ECALL_READ     0x401
1672 +
#define ECALL_WRITE    0x402
1673 +
#define ECALL_OPEN     0x403
1674 +
#define ECALL_CLOSE    0x404
1675 +
#define ECALL_STAT     0x405
1676 +
#define ECALL_MAKE_DIR 0x406
1677 +
#define ECALL_REMOVE   0x407
1678 +
#define ECALL_RENAME   0x408
1679 +
#define ECALL_LIST_DIR 0x409
1680 +
#define ECALL_SPAWN    0x40A
1681 +
#define ECALL_WAIT     0x40B
1682 +
#define ECALL_WAIT_ANY 0x40C
1683 +
1684 +
/* Result of a call that faulted the guest: a0 is left unchanged. */
1685 +
#define ECALL_FAULTED INT64_MIN
1686 +
1687 +
/* Size of the guest records exchanged with the host. */
1688 +
#define SLICE_SIZE   16
1689 +
#define STAT_SIZE    16
1690 +
#define OUTCOME_SIZE 8
1691 +
#define SPAWN_SIZE   128
1692 +
1693 +
/* Spawn record values. */
1694 +
#define SPAWN_MODE_MACHINE 1
1695 +
#define SPAWN_OUT_FILE     2
1696 +
#define SPAWN_FLAG_INHERIT 1
1697 +
1698 +
/* Return true if the guest range [addr, addr + len) lies in guest memory. */
1699 +
static bool guest_range(u64 addr, u64 len) {
1700 +
    return addr <= g_opts.memory_size && len <= g_opts.memory_size - addr;
1701 +
}
1702 +
1703 +
/* Check a guest range, faulting the guest if it is out of bounds. */
1704 +
static bool ecall_range(
1705 +
    struct cpu *cpu, u32 pc, const char *call, u64 addr, u64 len
1706 +
) {
1707 +
    if (guest_range(addr, len))
1708 +
        return true;
1709 +
    printf(
1710 +
        "sys_%s out of bounds: addr=%016llx len=%llu\n",
1711 +
        call,
1712 +
        (unsigned long long)addr,
1713 +
        (unsigned long long)len
1714 +
    );
1715 +
    cpu->running = false;
1716 +
    emit_fault_diagnostics(cpu, pc);
1717 +
    return false;
1718 +
}
1719 +
1720 +
/* Store a little-endian integer of `size` bytes into guest memory. */
1721 +
static void encode_le(u8 *bytes, u64 value, u32 size) {
1722 +
    for (u32 i = 0; i < size; i++)
1723 +
        bytes[i] = (u8)(value >> (8 * i));
1724 +
}
1725 +
1726 +
/* Copy the guest string of `len` bytes at `addr` into `out`, which holds
1727 +
 * HOST_PATH_MAX bytes, and terminate it. Returns 0, `HOST_E_INVALID` for an
1728 +
 * embedded zero byte or a path that is too long, or `ECALL_FAULTED` after
1729 +
 * faulting the guest. */
1730 +
static i64 guest_path(
1731 +
    struct cpu *cpu, u32 pc, const char *call, u64 addr, u64 len, char *out
1732 +
) {
1733 +
    if (!ecall_range(cpu, pc, call, addr, len))
1734 +
        return ECALL_FAULTED;
1735 +
    if (len >= HOST_PATH_MAX || memchr(&memory[addr], 0, len))
1736 +
        return HOST_E_INVALID;
1737 +
    memcpy(out, &memory[addr], len);
1738 +
    out[len] = '\0';
1739 +
    return 0;
1740 +
}
1741 +
1742 +
/* Open a file and give it a guest descriptor. */
1743 +
static i64 ecall_open(const char *path, u64 mode) {
1744 +
    if (mode > 1)
1745 +
        return HOST_E_INVALID;
1746 +
    i64 host_fd = mode ? host_open_write(path) : host_open_read(path);
1747 +
    if (host_fd < 0)
1748 +
        return host_fd;
1749 +
    int guest_fd = guest_fd_table_add((int)host_fd);
1750 +
    if (guest_fd < 0) {
1751 +
        host_close((int)host_fd);
1752 +
        return HOST_E_LIMIT;
1753 +
    }
1754 +
    return guest_fd;
1755 +
}
1756 +
1757 +
/* Close a guest descriptor. The standard streams cannot be closed. */
1758 +
static i64 ecall_close(u64 guest_fd) {
1759 +
    if (guest_fd < 3 || guest_fd >= MAX_OPEN_FILES)
1760 +
        return HOST_E_INVALID;
1761 +
    int host_fd = guest_fd_table_get((int)guest_fd);
1762 +
    if (host_fd < 0)
1763 +
        return HOST_E_INVALID;
1764 +
    guest_fd_table_remove((int)guest_fd);
1765 +
    return host_close(host_fd) < 0 ? HOST_E_IO : 0;
1766 +
}
1767 +
1768 +
/* Read or write guest memory through a guest descriptor. */
1769 +
static i64 ecall_transfer(
1770 +
    struct cpu *cpu, u32 pc, bool write, u64 guest_fd, u64 addr, u64 len
1771 +
) {
1772 +
    if (!ecall_range(cpu, pc, write ? "write" : "read", addr, len))
1773 +
        return ECALL_FAULTED;
1774 +
    int host_fd =
1775 +
        guest_fd < MAX_OPEN_FILES ? guest_fd_table_get((int)guest_fd) : -1;
1776 +
    if (host_fd < 0)
1777 +
        return HOST_E_INVALID;
1778 +
    if (len == 0)
1779 +
        return 0;
1780 +
    return write ? host_write(host_fd, &memory[addr], (u32)len)
1781 +
                 : host_read(host_fd, &memory[addr], (u32)len);
1782 +
}
1783 +
1784 +
/* Describe a path into a guest Stat record. */
1785 +
static i64 ecall_stat(
1786 +
    struct cpu *cpu, u32 pc, u64 path_addr, u64 path_len, u64 out
1787 +
) {
1788 +
    char path[HOST_PATH_MAX];
1789 +
    i64  rc = guest_path(cpu, pc, "stat", path_addr, path_len, path);
1790 +
    if (rc)
1791 +
        return rc;
1792 +
    if (!ecall_range(cpu, pc, "stat", out, STAT_SIZE))
1793 +
        return ECALL_FAULTED;
1794 +
    struct host_stat st;
1795 +
    rc = host_stat(path, &st);
1796 +
    if (rc < 0)
1797 +
        return rc;
1798 +
    encode_le(&memory[out], st.size, 8);
1799 +
    encode_le(&memory[out + 8], st.kind, 4);
1800 +
    encode_le(&memory[out + 12], 0, 4);
1801 +
    return 0;
1802 +
}
1803 +
1804 +
/* List a directory into a guest buffer. */
1805 +
static i64 ecall_list_dir(
1806 +
    struct cpu *cpu, u32 pc, u64 path_addr, u64 path_len, u64 buf, u64 buf_len
1807 +
) {
1808 +
    char path[HOST_PATH_MAX];
1809 +
    i64  rc = guest_path(cpu, pc, "listDir", path_addr, path_len, path);
1810 +
    if (rc)
1811 +
        return rc;
1812 +
    if (!ecall_range(cpu, pc, "listDir", buf, buf_len))
1813 +
        return ECALL_FAULTED;
1814 +
    return host_list_dir(path, &memory[buf], (u32)buf_len);
1815 +
}
1816 +
1817 +
/* Wait for one child, or for any child when `any` is set, and store its
1818 +
 * outcome record in guest memory. */
1819 +
static i64 ecall_wait(struct cpu *cpu, u32 pc, bool any, u64 child, u64 out) {
1820 +
    if (!ecall_range(cpu, pc, any ? "waitAny" : "wait", out, OUTCOME_SIZE))
1821 +
        return ECALL_FAULTED;
1822 +
    struct host_outcome outcome = { 0, 0 };
1823 +
    /* Handles beyond the table are unknown whatever their width. */
1824 +
    i64 rc =
1825 +
        any ? host_wait_any(&outcome)
1826 +
            : host_wait(child >= HOST_MAX_CHILDREN ? -1 : (i64)child, &outcome);
1827 +
    if (rc < 0)
1828 +
        return rc;
1829 +
    encode_le(&memory[out], outcome.kind, 4);
1830 +
    encode_le(&memory[out + 4], (u32)outcome.code, 4);
1831 +
    return any ? rc : 0;
1832 +
}
1833 +
1834 +
/* Format a numeric emulator option into `buf` and return it. */
1835 +
static char *format_option(char *buf, const char *name, u64 value) {
1836 +
    snprintf(buf, 48, "%s%llu", name, (unsigned long long)value);
1837 +
    return buf;
1838 +
}
1839 +
1840 +
/* Decode a spawn record at `spec` and start the child emulator. */
1841 +
static i64 ecall_spawn(struct cpu *cpu, u32 pc, u64 spec) {
1842 +
    if (!ecall_range(cpu, pc, "spawn", spec, SPAWN_SIZE))
1843 +
        return ECALL_FAULTED;
1844 +
1845 +
    const u8 *rec       = &memory[spec];
1846 +
    u64       image_ptr = decode_u64_le(rec);
1847 +
    u32       image_len = decode_u32_le(rec + 8);
1848 +
    u64       args_ptr  = decode_u64_le(rec + 16);
1849 +
    u32       args_len  = decode_u32_le(rec + 24);
1850 +
    u32       out_kind  = decode_u32_le(rec + 32);
1851 +
    u32       err_kind  = decode_u32_le(rec + 36);
1852 +
    u32       mode      = decode_u32_le(rec + 72);
1853 +
    u32       flags     = decode_u32_le(rec + 112);
1854 +
1855 +
    if (decode_u64_le(rec + 120) != 0 || mode > SPAWN_MODE_MACHINE ||
1856 +
        out_kind > SPAWN_OUT_FILE || err_kind > SPAWN_OUT_FILE ||
1857 +
        (flags & ~(u32)SPAWN_FLAG_INHERIT) != 0)
1858 +
        return HOST_E_INVALID;
1859 +
1860 +
    char image[HOST_PATH_MAX];
1861 +
    char out_path[HOST_PATH_MAX];
1862 +
    char err_path[HOST_PATH_MAX];
1863 +
    i64  rc = guest_path(cpu, pc, "spawn", image_ptr, image_len, image);
1864 +
    if (rc)
1865 +
        return rc;
1866 +
    if (out_kind == SPAWN_OUT_FILE) {
1867 +
        rc = guest_path(
1868 +
            cpu,
1869 +
            pc,
1870 +
            "spawn",
1871 +
            decode_u64_le(rec + 40),
1872 +
            decode_u32_le(rec + 48),
1873 +
            out_path
1874 +
        );
1875 +
        if (rc)
1876 +
            return rc;
1877 +
    }
1878 +
    if (err_kind == SPAWN_OUT_FILE) {
1879 +
        rc = guest_path(
1880 +
            cpu,
1881 +
            pc,
1882 +
            "spawn",
1883 +
            decode_u64_le(rec + 56),
1884 +
            decode_u32_le(rec + 64),
1885 +
            err_path
1886 +
        );
1887 +
        if (rc)
1888 +
            return rc;
1889 +
    }
1890 +
1891 +
    /* Validate the argument slices and measure their bytes. */
1892 +
    if (!ecall_range(cpu, pc, "spawn", args_ptr, (u64)args_len * SLICE_SIZE))
1893 +
        return ECALL_FAULTED;
1894 +
    u64 pool_size = 0;
1895 +
    for (u32 i = 0; i < args_len; i++) {
1896 +
        const u8 *slice = &memory[args_ptr + (u64)i * SLICE_SIZE];
1897 +
        u64       ptr   = decode_u64_le(slice);
1898 +
        u32       len   = decode_u32_le(slice + 8);
1899 +
        if (!ecall_range(cpu, pc, "spawn", ptr, len))
1900 +
            return ECALL_FAULTED;
1901 +
        if (memchr(&memory[ptr], 0, len))
1902 +
            return HOST_E_INVALID;
1903 +
        pool_size += (u64)len + 1;
1904 +
    }
1905 +
1906 +
    /* Memory sizes are in KB. With `inherit`, zero sizes take the parent's. */
1907 +
    u64 memory_kb = decode_u32_le(rec + 80);
1908 +
    u64 data_kb   = decode_u32_le(rec + 84);
1909 +
    u64 stack_kb  = decode_u32_le(rec + 88);
1910 +
    if (flags & SPAWN_FLAG_INHERIT) {
1911 +
        if (!memory_kb)
1912 +
            memory_kb = g_opts.memory_size / 1024;
1913 +
        if (!data_kb)
1914 +
            data_kb = g_opts.data_memory_size / 1024;
1915 +
        if (!stack_kb)
1916 +
            stack_kb = g_opts.stack_size / 1024;
1917 +
    }
1918 +
    const struct {
1919 +
        const char *name;
1920 +
        u64         value;
1921 +
    } options[] = {
1922 +
        { "-harts=", decode_u32_le(rec + 76) },
1923 +
        { "-memory-size=", memory_kb },
1924 +
        { "-data-size=", data_kb },
1925 +
        { "-stack-size=", stack_kb },
1926 +
        { "-irq=", decode_u32_le(rec + 92) },
1927 +
        { "-irq-at=", decode_u64_le(rec + 96) },
1928 +
        { "-max-steps=", decode_u64_le(rec + 104) },
1929 +
    };
1930 +
1931 +
    /* The program name, emulator options, "--", the image and the guest
1932 +
     * arguments, which follow the image unchanged. */
1933 +
    enum { OPTION_COUNT = 7, FIXED_MAX = OPTION_COUNT + 5 };
1934 +
    char  numbers[OPTION_COUNT + 1][48];
1935 +
    char *fixed[FIXED_MAX];
1936 +
    int   nfixed   = 0;
1937 +
    int   nnumbers = 0;
1938 +
1939 +
    fixed[nfixed++] = "emulator";
1940 +
    fixed[nfixed++] = "-run";
1941 +
    if (mode == SPAWN_MODE_MACHINE)
1942 +
        fixed[nfixed++] = "-machine";
1943 +
    for (usize i = 0; i < sizeof options / sizeof options[0]; i++) {
1944 +
        if (options[i].value)
1945 +
            fixed[nfixed++] = format_option(
1946 +
                numbers[nnumbers++], options[i].name, options[i].value
1947 +
            );
1948 +
    }
1949 +
    fixed[nfixed++] =
1950 +
        format_option(numbers[nnumbers++], "-outcome-fd=", HOST_OUTCOME_FD);
1951 +
    fixed[nfixed++] = "--";
1952 +
1953 +
    char **argv = malloc(((usize)nfixed + 2 + args_len) * sizeof *argv);
1954 +
    char  *pool = malloc(pool_size ? pool_size : 1);
1955 +
    if (!argv || !pool) {
1956 +
        free(argv);
1957 +
        free(pool);
1958 +
        return HOST_E_IO;
1959 +
    }
1960 +
    int n = 0;
1961 +
    for (int i = 0; i < nfixed; i++)
1962 +
        argv[n++] = fixed[i];
1963 +
    argv[n++] = image;
1964 +
1965 +
    char *next = pool;
1966 +
    for (u32 i = 0; i < args_len; i++) {
1967 +
        const u8 *slice = &memory[args_ptr + (u64)i * SLICE_SIZE];
1968 +
        u64       ptr   = decode_u64_le(slice);
1969 +
        u32       len   = decode_u32_le(slice + 8);
1970 +
        memcpy(next, &memory[ptr], len);
1971 +
        next[len]  = '\0';
1972 +
        argv[n++]  = next;
1973 +
        next      += len + 1;
1974 +
    }
1975 +
    argv[n] = NULL;
1976 +
1977 +
    struct host_spawn req = {
1978 +
        .argv     = argv,
1979 +
        .out_kind = out_kind,
1980 +
        .out_path = out_path,
1981 +
        .err_kind = err_kind,
1982 +
        .err_path = err_path,
1983 +
    };
1984 +
    /* One path for both streams is opened once and shared. */
1985 +
    if (out_kind == SPAWN_OUT_FILE && err_kind == SPAWN_OUT_FILE &&
1986 +
        strcmp(out_path, err_path) == 0)
1987 +
        req.err_kind = HOST_OUT_MERGE;
1988 +
1989 +
    fflush(NULL);
1990 +
    rc = host_spawn(&req);
1991 +
    free(argv);
1992 +
    free(pool);
1993 +
    return rc;
1994 +
}
1995 +
1996 +
/* Run the host call selected by a7 and store its result in a0. */
1997 +
static void ecall_dispatch(struct cpu *cpu, u32 pc) {
1998 +
    u64  call = cpu->regs[A7];
1999 +
    u64  a0 = cpu->regs[A0], a1 = cpu->regs[A1];
2000 +
    u64  a2 = cpu->regs[A2], a3 = cpu->regs[A3];
2001 +
    i64  rc;
2002 +
    char path[HOST_PATH_MAX];
2003 +
    char other[HOST_PATH_MAX];
2004 +
2005 +
    switch (call) {
2006 +
    case ECALL_EXIT:
2007 +
        /* The status is already in a0. */
2008 +
        cpu->running = false;
2009 +
        return;
2010 +
    case ECALL_READ:
2011 +
    case ECALL_WRITE:
2012 +
        rc = ecall_transfer(cpu, pc, call == ECALL_WRITE, a0, a1, a2);
2013 +
        break;
2014 +
    case ECALL_OPEN:
2015 +
        rc = guest_path(cpu, pc, "open", a0, a1, path);
2016 +
        if (!rc)
2017 +
            rc = ecall_open(path, a2);
2018 +
        break;
2019 +
    case ECALL_CLOSE:
2020 +
        rc = ecall_close(a0);
2021 +
        break;
2022 +
    case ECALL_STAT:
2023 +
        rc = ecall_stat(cpu, pc, a0, a1, a2);
2024 +
        break;
2025 +
    case ECALL_MAKE_DIR:
2026 +
        rc = guest_path(cpu, pc, "makeDir", a0, a1, path);
2027 +
        if (!rc)
2028 +
            rc = host_make_dir(path);
2029 +
        break;
2030 +
    case ECALL_REMOVE:
2031 +
        rc = guest_path(cpu, pc, "remove", a0, a1, path);
2032 +
        if (!rc)
2033 +
            rc = host_remove(path);
2034 +
        break;
2035 +
    case ECALL_RENAME:
2036 +
        rc = guest_path(cpu, pc, "rename", a0, a1, path);
2037 +
        if (!rc)
2038 +
            rc = guest_path(cpu, pc, "rename", a2, a3, other);
2039 +
        if (!rc)
2040 +
            rc = host_rename(path, other);
2041 +
        break;
2042 +
    case ECALL_LIST_DIR:
2043 +
        rc = ecall_list_dir(cpu, pc, a0, a1, a2, a3);
2044 +
        break;
2045 +
    case ECALL_SPAWN:
2046 +
        rc = ecall_spawn(cpu, pc, a0);
2047 +
        break;
2048 +
    case ECALL_WAIT:
2049 +
        rc = ecall_wait(cpu, pc, false, a0, a1);
2050 +
        break;
2051 +
    case ECALL_WAIT_ANY:
2052 +
        rc = ecall_wait(cpu, pc, true, 0, a0);
2053 +
        break;
2054 +
    default:
2055 +
        rc = HOST_E_INVALID;
2056 +
        break;
2057 +
    }
2058 +
    /* A fault has already stopped the guest; leave its registers alone. */
2059 +
    if (rc != ECALL_FAULTED)
2060 +
        cpu->regs[A0] = (u64)rc;
2061 +
}
2062 +
1695 2063
/* Execute a single instruction. */
1696 2064
static void cpu_execute(struct cpu *cpu, enum display display, bool headless) {
1697 2065
    if (cpu_out_of_bounds(cpu)) {
1698 2066
        cpu->running = false;
1699 2067
        emit_fault_diagnostics(cpu, cpu->pc);
2231 2599
2232 2600
    case OP_SYSTEM: {
2233 2601
        u32 funct12 = ins.i.imm_11_0;
2234 2602
2235 2603
        if (funct12 == 0) {
2236 -
            u32 syscall_num = (u32)cpu->regs[A7];
2237 -
2238 -
            switch (syscall_num) {
2239 -
            case 64: { /* write. */
2240 -
                int guest_fd = (int)cpu->regs[A0];
2241 -
                u64 addr     = cpu->regs[A1];
2242 -
                u64 count    = cpu->regs[A2];
2243 -
2244 -
                if (addr + count > g_opts.memory_size ||
2245 -
                    addr > (u64)g_opts.memory_size) {
2246 -
                    printf(
2247 -
                        "sys_write out of bounds: addr=%016llx len=%llu\n",
2248 -
                        (unsigned long long)addr,
2249 -
                        (unsigned long long)count
2250 -
                    );
2251 -
                    cpu->running = false;
2252 -
                    emit_fault_diagnostics(cpu, executed_pc);
2253 -
                    break;
2254 -
                }
2255 -
                ssize_t written = 0;
2256 -
                int     host_fd = guest_fd_table_get(guest_fd);
2257 -
2258 -
                if (host_fd >= 0 && count > 0) {
2259 -
                    written = write(host_fd, &memory[(u32)addr], (u32)count);
2260 -
                    if (written < 0) {
2261 -
                        written = 0;
2262 -
                    }
2263 -
                }
2264 -
                cpu->regs[A0] = (u64)written;
2265 -
                break;
2266 -
            }
2267 -
            case 63: { /* read. */
2268 -
                int guest_fd = (int)cpu->regs[A0];
2269 -
                u64 addr     = cpu->regs[A1];
2270 -
                u64 count    = cpu->regs[A2];
2271 -
2272 -
                if (addr + count > g_opts.memory_size ||
2273 -
                    addr > (u64)g_opts.memory_size) {
2274 -
                    printf(
2275 -
                        "sys_read out of bounds: addr=%016llx len=%llu\n",
2276 -
                        (unsigned long long)addr,
2277 -
                        (unsigned long long)count
2278 -
                    );
2279 -
                    cpu->running = false;
2280 -
                    emit_fault_diagnostics(cpu, executed_pc);
2281 -
                    break;
2282 -
                }
2283 -
                ssize_t read_bytes = 0;
2284 -
                int     host_fd    = guest_fd_table_get(guest_fd);
2285 -
2286 -
                if (host_fd >= 0 && count > 0) {
2287 -
                    read_bytes = read(host_fd, &memory[(u32)addr], (u32)count);
2288 -
                    if (read_bytes < 0) {
2289 -
                        read_bytes = 0;
2290 -
                    }
2291 -
                }
2292 -
                cpu->regs[A0] = (u64)read_bytes;
2293 -
                break;
2294 -
            }
2295 -
            case 93: { /* exit. */
2296 -
                cpu->running = false;
2297 -
                break;
2298 -
            }
2299 -
            case 56: { /* openat. */
2300 -
                u64 pathname_addr = cpu->regs[A1];
2301 -
                i32 flags         = (i32)cpu->regs[A2];
2302 -
                if (pathname_addr > (u64)g_opts.memory_size) {
2303 -
                    cpu->regs[A0] = (u64)(i64)(i32)-1;
2304 -
                    break;
2305 -
                }
2306 -
                cpu->regs[A0] =
2307 -
                    (u64)(i64)(i32)ecall_openat((u32)pathname_addr, flags);
2308 -
                break;
2309 -
            }
2310 -
            case 57: { /* close. */
2311 -
                i32 guest_fd  = (i32)cpu->regs[A0];
2312 -
                cpu->regs[A0] = (u64)(i64)ecall_close(guest_fd);
2313 -
                break;
2314 -
            }
2315 -
            default:
2316 -
                cpu->regs[A0] = (u32)syscall_num;
2317 -
                break;
2318 -
            }
2604 +
            ecall_dispatch(cpu, executed_pc);
2319 2605
        } else if (funct12 == 1) {
2320 2606
            /* Look up source location for this EBREAK.  PC in the debug
2321 2607
             * file is relative to program start, so subtract base. */
2322 2608
            u32                 relative_pc = executed_pc - program_base;
2323 2609
            struct debug_entry *entry       = debug_lookup(relative_pc);
2606 2892
/* Restore terminal settings. */
2607 2893
static void term_restore(struct termios *old) {
2608 2894
    tcsetattr(STDIN_FILENO, TCSANOW, old);
2609 2895
}
2610 2896
2897 +
/* Report the outcome to a parent emulator, if one asked for it with
2898 +
 * -outcome-fd, and return the process exit status. Children still running
2899 +
 * are terminated at exit. */
2900 +
static int finish(u32 kind, i32 code, int status) {
2901 +
    if (g_opts.outcome_fd >= 0) {
2902 +
        struct host_outcome outcome = { kind, code };
2903 +
        host_report_outcome(g_opts.outcome_fd, &outcome);
2904 +
    }
2905 +
    return status;
2906 +
}
2907 +
2611 2908
int main(int argc, char *argv[]) {
2612 2909
    struct cpu        cpu;
2613 2910
    enum display      display = DISPLAY_DEC;
2614 2911
    struct cli_config cli     = { 0 };
2615 2912
2616 2913
    if (!parse_cli_args(argc, argv, &cli))
2617 2914
        return 1;
2618 2915
2619 2916
    bool headless = cli.headless;
2620 2917
2918 +
    host_init();
2919 +
2621 2920
    g_opts.trace_headless = headless;
2622 2921
2623 2922
    cpu_init(&cpu);
2624 2923
    program_init(&cpu, cli.program_path);
2625 2924
    if (g_opts.machine_mode) {
2628 2927
        machine_options.stack_size  = g_opts.stack_size;
2629 2928
        machine_options.max_steps   = g_opts.headless_max_steps;
2630 2929
        machine_options.trace =
2631 2930
            g_opts.trace_enabled || g_opts.trace_print_instructions;
2632 2931
        machine_options.count_instructions = g_opts.count_instructions;
2633 -
        return machine_run(&machine_options);
2932 +
        bool timed_out                     = false;
2933 +
        machine_options.timed_out          = &timed_out;
2934 +
        int status                         = machine_run(&machine_options);
2935 +
        return finish(
2936 +
            timed_out ? HOST_OUTCOME_STEPS : HOST_OUTCOME_EXITED,
2937 +
            timed_out ? 0 : status,
2938 +
            status
2939 +
        );
2634 2940
    }
2635 2941
    int    prog_argc = argc - cli.arg_index;
2636 2942
    char **prog_argv = &argv[cli.arg_index];
2637 2943
    prepare_env(&cpu, prog_argc, prog_argv);
2638 2944
2713 3019
            fprintf(
2714 3020
                stderr,
2715 3021
                "program did not terminate within %zu steps\n",
2716 3022
                (size_t)max_steps
2717 3023
            );
2718 -
            return -1;
3024 +
            return finish(HOST_OUTCOME_STEPS, 0, -1);
2719 3025
        }
2720 3026
        if (cpu.faulted) {
2721 3027
            fprintf(stderr, "program terminated due to runtime fault\n");
2722 -
            return -1;
3028 +
            return finish(HOST_OUTCOME_FAULT, 0, -1);
2723 3029
        }
2724 3030
        if (g_opts.count_instructions) {
2725 3031
            fprintf(
2726 3032
                stderr,
2727 3033
                "Processed %llu instructions\n",
2728 3034
                (unsigned long long)steps
2729 3035
            );
2730 3036
        }
2731 -
        return (int)cpu.regs[A0];
3037 +
        return finish(
3038 +
            HOST_OUTCOME_EXITED, (i32)cpu.regs[A0], (int)cpu.regs[A0]
3039 +
        );
2732 3040
    }
2733 3041
    struct termios oldterm;
2734 3042
    term_init(&oldterm);
2735 3043
    snapshot_init(&cpu);
2736 3044
host.h added +137 -0
1 +
/* Host platform layer for the hosted system call ABI.
2 +
 *
3 +
 * Every operation that touches the host operating system on behalf of a
4 +
 * guest goes through this interface. The emulator decodes guest memory and
5 +
 * calls these functions; it never calls host file or process functions for
6 +
 * guest requests itself. A port to another host implements this header.
7 +
 *
8 +
 * Fallible functions return a value >= 0 on success, or a negative `HOST_E_*`
9 +
 * code, which equals the error code of the guest ABI. Paths are NUL-terminated
10 +
 * host strings. Files are identified by small host descriptors; the emulator
11 +
 * maps guest descriptors onto them. */
12 +
#ifndef HOST_H
13 +
#define HOST_H
14 +
15 +
#include "types.h"
16 +
17 +
/* Longest path accepted from a guest, including the terminating zero. */
18 +
#define HOST_PATH_MAX 4096
19 +
20 +
/* Error codes, shared with the guest ABI. */
21 +
#define HOST_E_NOT_FOUND -1 /* No such file, directory or child. */
22 +
#define HOST_E_EXISTS    -2 /* The path already exists. */
23 +
#define HOST_E_DENIED    -3 /* The host refused access. */
24 +
#define HOST_E_NOT_EMPTY -4 /* The directory is not empty. */
25 +
#define HOST_E_INVALID   -5 /* Bad argument, mode, path or call. */
26 +
#define HOST_E_TOO_LARGE -6 /* The output buffer is too small. */
27 +
#define HOST_E_LIMIT     -7 /* Too many open files or running children. */
28 +
#define HOST_E_IO        -8 /* Any other host failure. */
29 +
30 +
/* Kind of a file system object, as reported by `host_stat`. */
31 +
enum host_kind {
32 +
    HOST_KIND_FILE  = 1,
33 +
    HOST_KIND_DIR   = 2,
34 +
    HOST_KIND_OTHER = 3,
35 +
};
36 +
37 +
/* File metadata. */
38 +
struct host_stat {
39 +
    u64 size; /* Size in bytes, zero for directories. */
40 +
    u32 kind; /* One of `enum host_kind`. */
41 +
};
42 +
43 +
/* Where a child's standard output or error goes. */
44 +
enum host_output {
45 +
    HOST_OUT_INHERIT = 0, /* Share the emulator's stream. */
46 +
    HOST_OUT_DISCARD = 1, /* Write to the null device. */
47 +
    HOST_OUT_FILE    = 2, /* Create or truncate a file. */
48 +
    HOST_OUT_MERGE   = 3, /* Standard error only: share standard output. */
49 +
};
50 +
51 +
/* How a child ended, as reported by the child emulator itself. */
52 +
enum host_outcome_kind {
53 +
    HOST_OUTCOME_EXITED = 0, /* The guest exited; `code` is its status. */
54 +
    HOST_OUTCOME_STEPS  = 1, /* The step budget ran out. */
55 +
    HOST_OUTCOME_FAULT  = 2, /* A runtime fault, or the child crashed. */
56 +
};
57 +
58 +
/* Final state of a child. */
59 +
struct host_outcome {
60 +
    u32 kind; /* One of `enum host_outcome_kind`. */
61 +
    i32 code; /* Exit status when exited, otherwise zero. */
62 +
};
63 +
64 +
/* Request to start a child emulator process. */
65 +
struct host_spawn {
66 +
    char *const *argv;    /* Emulator options and guest arguments after the
67 +
                           * program name, NULL terminated. The program
68 +
                           * name argv[0] is filled in by the host layer. */
69 +
    u32         out_kind; /* `host_output` for standard output. */
70 +
    const char *out_path; /* File for `HOST_OUT_FILE`. */
71 +
    u32         err_kind; /* `host_output` for standard error. */
72 +
    const char *err_path; /* File for `HOST_OUT_FILE`. */
73 +
};
74 +
75 +
/* Descriptor number on which a child receives its outcome pipe. The parent
76 +
 * passes it to the child as `-outcome-fd=N`. */
77 +
#define HOST_OUTCOME_FD 3
78 +
79 +
/* Maximum number of children that can be running at once. */
80 +
#define HOST_MAX_CHILDREN 64
81 +
82 +
/* Open an existing file for reading. The descriptor is not inherited by
83 +
 * children. Returns the descriptor. */
84 +
i64 host_open_read(const char *path);
85 +
86 +
/* Create or truncate a file for writing with permissions 0644, subject to
87 +
 * the host umask. Returns the descriptor. */
88 +
i64 host_open_write(const char *path);
89 +
90 +
/* Read up to `len` bytes. Returns the count, zero at end of file. */
91 +
i64 host_read(int fd, void *buf, u32 len);
92 +
93 +
/* Write up to `len` bytes. Returns the count written. */
94 +
i64 host_write(int fd, const void *buf, u32 len);
95 +
96 +
/* Close a descriptor returned by one of the open functions. */
97 +
i64 host_close(int fd);
98 +
99 +
/* Describe the object at `path`. */
100 +
i64 host_stat(const char *path, struct host_stat *out);
101 +
102 +
/* Create one directory level. */
103 +
i64 host_make_dir(const char *path);
104 +
105 +
/* Remove a file or an empty directory. */
106 +
i64 host_remove(const char *path);
107 +
108 +
/* Rename a file or directory, replacing an existing file. */
109 +
i64 host_rename(const char *from, const char *to);
110 +
111 +
/* List a directory into `buf`: each entry name followed by a zero byte,
112 +
 * excluding "." and "..", in host order. Returns the byte count, or
113 +
 * `HOST_E_TOO_LARGE` if `cap` bytes are not enough. */
114 +
i64 host_list_dir(const char *path, u8 *buf, u32 cap);
115 +
116 +
/* Start a child emulator, running this emulator's own executable with the
117 +
 * given request. The child reports its outcome through a private pipe, and
118 +
 * its standard input is the null device. Returns a child handle. */
119 +
i64 host_spawn(const struct host_spawn *spec);
120 +
121 +
/* Wait for one child to end and store its outcome. The handle is released.
122 +
 * `HOST_E_NOT_FOUND` for an unknown handle. */
123 +
i64 host_wait(i64 child, struct host_outcome *out);
124 +
125 +
/* Wait for any running child. Returns its handle, and releases it.
126 +
 * `HOST_E_NOT_FOUND` when no child is running. */
127 +
i64 host_wait_any(struct host_outcome *out);
128 +
129 +
/* Arrange for every child that has not been waited for to be terminated
130 +
 * and reaped when this process exits or is asked to terminate. */
131 +
void host_init(void);
132 +
133 +
/* Write the outcome record for this process to `fd`, as the child side of
134 +
 * `host_spawn`. The record is 8 bytes: kind and code, little-endian. */
135 +
void host_report_outcome(int fd, const struct host_outcome *outcome);
136 +
137 +
#endif /* HOST_H */
host_posix.c added +406 -0
1 +
/* POSIX implementation of the host platform layer. */
2 +
#define _POSIX_C_SOURCE 200809L
3 +
4 +
#include <dirent.h>
5 +
#include <errno.h>
6 +
#include <fcntl.h>
7 +
#include <signal.h>
8 +
#include <spawn.h>
9 +
#include <stdio.h>
10 +
#include <stdlib.h>
11 +
#include <string.h>
12 +
#include <sys/stat.h>
13 +
#include <sys/types.h>
14 +
#include <sys/wait.h>
15 +
#include <unistd.h>
16 +
17 +
#ifdef __APPLE__
18 +
#include <mach-o/dyld.h>
19 +
#endif
20 +
21 +
#include "host.h"
22 +
23 +
extern char **environ;
24 +
25 +
/* Smallest descriptor number given to internal pipes, so that they never
26 +
 * collide with the descriptors a child is given. */
27 +
#define PIPE_FD_MIN 10
28 +
29 +
/* Null device used for discarded output and empty input. */
30 +
#define NULL_DEVICE "/dev/null"
31 +
32 +
/* A running child: its process and the read end of its outcome pipe. */
33 +
struct child {
34 +
    bool  used;
35 +
    pid_t pid;
36 +
    int   outcome_fd;
37 +
};
38 +
39 +
/* Table of children that have not been waited for. */
40 +
static struct child children[HOST_MAX_CHILDREN];
41 +
42 +
/* Map a host errno value to a guest ABI error code. This is the only place
43 +
 * where host error numbers are interpreted. */
44 +
static i64 host_error(int err) {
45 +
    switch (err) {
46 +
    case ENOENT:
47 +
    case ENOTDIR:
48 +
        return HOST_E_NOT_FOUND;
49 +
    case EEXIST:
50 +
        return HOST_E_EXISTS;
51 +
    case EACCES:
52 +
    case EPERM:
53 +
    case EROFS:
54 +
        return HOST_E_DENIED;
55 +
    case ENOTEMPTY:
56 +
        return HOST_E_NOT_EMPTY;
57 +
    case EINVAL:
58 +
    case EBADF:
59 +
    case ENAMETOOLONG:
60 +
        return HOST_E_INVALID;
61 +
    case EMFILE:
62 +
    case ENFILE:
63 +
        return HOST_E_LIMIT;
64 +
    default:
65 +
        return HOST_E_IO;
66 +
    }
67 +
}
68 +
69 +
/* Return a negative error code for the current `errno`. */
70 +
static i64 fail(void) {
71 +
    return host_error(errno);
72 +
}
73 +
74 +
/* Open a file and make sure children do not inherit it. */
75 +
static i64 open_file(const char *path, int flags) {
76 +
    int fd = open(path, flags | O_CLOEXEC, 0644);
77 +
    return fd < 0 ? fail() : fd;
78 +
}
79 +
80 +
i64 host_open_read(const char *path) {
81 +
    return open_file(path, O_RDONLY);
82 +
}
83 +
84 +
i64 host_open_write(const char *path) {
85 +
    return open_file(path, O_WRONLY | O_CREAT | O_TRUNC);
86 +
}
87 +
88 +
i64 host_read(int fd, void *buf, u32 len) {
89 +
    ssize_t n;
90 +
    do {
91 +
        n = read(fd, buf, len);
92 +
    } while (n < 0 && errno == EINTR);
93 +
    return n < 0 ? fail() : n;
94 +
}
95 +
96 +
i64 host_write(int fd, const void *buf, u32 len) {
97 +
    ssize_t n;
98 +
    do {
99 +
        n = write(fd, buf, len);
100 +
    } while (n < 0 && errno == EINTR);
101 +
    return n < 0 ? fail() : n;
102 +
}
103 +
104 +
i64 host_close(int fd) {
105 +
    return close(fd) < 0 ? fail() : 0;
106 +
}
107 +
108 +
i64 host_stat(const char *path, struct host_stat *out) {
109 +
    struct stat st;
110 +
    if (stat(path, &st) < 0)
111 +
        return fail();
112 +
    if (S_ISREG(st.st_mode)) {
113 +
        out->kind = HOST_KIND_FILE;
114 +
        out->size = (u64)st.st_size;
115 +
    } else if (S_ISDIR(st.st_mode)) {
116 +
        out->kind = HOST_KIND_DIR;
117 +
        out->size = 0;
118 +
    } else {
119 +
        out->kind = HOST_KIND_OTHER;
120 +
        out->size = 0;
121 +
    }
122 +
    return 0;
123 +
}
124 +
125 +
i64 host_make_dir(const char *path) {
126 +
    return mkdir(path, 0755) < 0 ? fail() : 0;
127 +
}
128 +
129 +
i64 host_remove(const char *path) {
130 +
    struct stat st;
131 +
    if (lstat(path, &st) < 0)
132 +
        return fail();
133 +
    /* Do not follow a symbolic link to a directory: remove the link. */
134 +
    int rc = S_ISDIR(st.st_mode) ? rmdir(path) : unlink(path);
135 +
    return rc < 0 ? fail() : 0;
136 +
}
137 +
138 +
i64 host_rename(const char *from, const char *to) {
139 +
    return rename(from, to) < 0 ? fail() : 0;
140 +
}
141 +
142 +
i64 host_list_dir(const char *path, u8 *buf, u32 cap) {
143 +
    DIR *dir = opendir(path);
144 +
    if (!dir)
145 +
        return fail();
146 +
147 +
    u64 used = 0;
148 +
    for (;;) {
149 +
        errno                  = 0;
150 +
        const struct dirent *e = readdir(dir);
151 +
        if (!e) {
152 +
            int err = errno;
153 +
            closedir(dir);
154 +
            return err ? host_error(err) : (i64)used;
155 +
        }
156 +
        if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
157 +
            continue;
158 +
        u64 size = (u64)strlen(e->d_name) + 1;
159 +
        if (size > cap - used) {
160 +
            closedir(dir);
161 +
            return HOST_E_TOO_LARGE;
162 +
        }
163 +
        memcpy(buf + used, e->d_name, size);
164 +
        used += size;
165 +
    }
166 +
}
167 +
168 +
/* Resolve the path of the running emulator executable into `buf`. */
169 +
static bool self_path(char *buf, usize cap) {
170 +
#ifdef __APPLE__
171 +
    uint32_t size = (uint32_t)cap;
172 +
    return _NSGetExecutablePath(buf, &size) == 0;
173 +
#else
174 +
    ssize_t n = readlink("/proc/self/exe", buf, cap - 1);
175 +
    if (n <= 0)
176 +
        return false;
177 +
    buf[n] = '\0';
178 +
    return true;
179 +
#endif
180 +
}
181 +
182 +
/* Move a descriptor to a number of at least PIPE_FD_MIN, closing the old
183 +
 * one. The new descriptor is close-on-exec. Returns -1 on failure. */
184 +
static int move_high(int fd) {
185 +
    int high = fcntl(fd, F_DUPFD_CLOEXEC, PIPE_FD_MIN);
186 +
    int err  = errno;
187 +
    close(fd);
188 +
    errno = err;
189 +
    return high;
190 +
}
191 +
192 +
/* Create the outcome pipe. Both ends are close-on-exec, so only the
193 +
 * child that is explicitly given the write end holds it. */
194 +
static bool outcome_pipe(int ends[2]) {
195 +
    int raw[2];
196 +
    if (pipe(raw) < 0)
197 +
        return false;
198 +
    ends[0] = move_high(raw[0]);
199 +
    if (ends[0] < 0) {
200 +
        close(raw[1]);
201 +
        return false;
202 +
    }
203 +
    ends[1] = move_high(raw[1]);
204 +
    if (ends[1] < 0) {
205 +
        close(ends[0]);
206 +
        return false;
207 +
    }
208 +
    return true;
209 +
}
210 +
211 +
/* Add the actions that connect one child output stream. */
212 +
static int output_actions(
213 +
    posix_spawn_file_actions_t *fa, int target, u32 kind, const char *path
214 +
) {
215 +
    switch (kind) {
216 +
    case HOST_OUT_INHERIT:
217 +
        return 0;
218 +
    case HOST_OUT_DISCARD:
219 +
        return posix_spawn_file_actions_addopen(
220 +
            fa, target, NULL_DEVICE, O_WRONLY, 0
221 +
        );
222 +
    case HOST_OUT_FILE:
223 +
        return posix_spawn_file_actions_addopen(
224 +
            fa, target, path, O_WRONLY | O_CREAT | O_TRUNC, 0644
225 +
        );
226 +
    case HOST_OUT_MERGE:
227 +
        return posix_spawn_file_actions_adddup2(fa, STDOUT_FILENO, target);
228 +
    default:
229 +
        return EINVAL;
230 +
    }
231 +
}
232 +
233 +
/* Build the file actions of a child. */
234 +
static int spawn_actions(
235 +
    posix_spawn_file_actions_t *fa, const struct host_spawn *spec, int out_fd
236 +
) {
237 +
    int rc = posix_spawn_file_actions_addopen(
238 +
        fa, STDIN_FILENO, NULL_DEVICE, O_RDONLY, 0
239 +
    );
240 +
    if (!rc)
241 +
        rc = posix_spawn_file_actions_adddup2(fa, out_fd, HOST_OUTCOME_FD);
242 +
    if (!rc)
243 +
        rc = output_actions(fa, STDOUT_FILENO, spec->out_kind, spec->out_path);
244 +
    if (!rc)
245 +
        rc = output_actions(fa, STDERR_FILENO, spec->err_kind, spec->err_path);
246 +
    return rc;
247 +
}
248 +
249 +
i64 host_spawn(const struct host_spawn *spec) {
250 +
    static char exe[HOST_PATH_MAX];
251 +
252 +
    int slot = 0;
253 +
    while (slot < HOST_MAX_CHILDREN && children[slot].used)
254 +
        slot++;
255 +
    if (slot == HOST_MAX_CHILDREN)
256 +
        return HOST_E_LIMIT;
257 +
    if (!exe[0] && !self_path(exe, sizeof exe))
258 +
        return HOST_E_IO;
259 +
    if (spec->out_kind == HOST_OUT_MERGE)
260 +
        return HOST_E_INVALID;
261 +
262 +
    /* Replace the program name in a copy of the argument vector. */
263 +
    usize argc = 0;
264 +
    while (spec->argv[argc])
265 +
        argc++;
266 +
    char **argv = malloc((argc + 1) * sizeof *argv);
267 +
    if (!argv)
268 +
        return HOST_E_IO;
269 +
    memcpy(argv, spec->argv, (argc + 1) * sizeof *argv);
270 +
    argv[0] = exe;
271 +
272 +
    int ends[2];
273 +
    if (!outcome_pipe(ends)) {
274 +
        i64 err = fail();
275 +
        free(argv);
276 +
        return err;
277 +
    }
278 +
279 +
    posix_spawn_file_actions_t fa;
280 +
    int                        rc  = posix_spawn_file_actions_init(&fa);
281 +
    pid_t                      pid = 0;
282 +
    if (!rc) {
283 +
        rc = spawn_actions(&fa, spec, ends[1]);
284 +
        if (!rc)
285 +
            rc = posix_spawn(&pid, exe, &fa, NULL, argv, environ);
286 +
        posix_spawn_file_actions_destroy(&fa);
287 +
    }
288 +
    free(argv);
289 +
    close(ends[1]);
290 +
    if (rc) {
291 +
        close(ends[0]);
292 +
        return host_error(rc);
293 +
    }
294 +
    children[slot] = (struct child){ true, pid, ends[0] };
295 +
    return slot;
296 +
}
297 +
298 +
/* Read the outcome record of an ended child and release its slot. A child
299 +
 * that did not leave a complete record is reported as a fault. */
300 +
static void collect(struct child *c, struct host_outcome *out) {
301 +
    u8  rec[8];
302 +
    u32 got = 0;
303 +
    while (got < sizeof rec) {
304 +
        ssize_t n = read(c->outcome_fd, rec + got, sizeof rec - got);
305 +
        if (n < 0 && errno == EINTR)
306 +
            continue;
307 +
        if (n <= 0)
308 +
            break;
309 +
        got += (u32)n;
310 +
    }
311 +
    if (got == sizeof rec) {
312 +
        out->kind = (u32)rec[0] | (u32)rec[1] << 8 | (u32)rec[2] << 16 |
313 +
                    (u32)rec[3] << 24;
314 +
        out->code = (i32)((u32)rec[4] | (u32)rec[5] << 8 | (u32)rec[6] << 16 |
315 +
                          (u32)rec[7] << 24);
316 +
        if (out->kind > HOST_OUTCOME_FAULT)
317 +
            out->kind = HOST_OUTCOME_FAULT, out->code = 0;
318 +
    } else {
319 +
        out->kind = HOST_OUTCOME_FAULT;
320 +
        out->code = 0;
321 +
    }
322 +
    close(c->outcome_fd);
323 +
    c->used = false;
324 +
}
325 +
326 +
/* Wait for a specific process, retrying when interrupted. */
327 +
static void reap(pid_t pid) {
328 +
    int status;
329 +
    while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
330 +
        ;
331 +
}
332 +
333 +
i64 host_wait(i64 child, struct host_outcome *out) {
334 +
    if (child < 0 || child >= HOST_MAX_CHILDREN || !children[child].used)
335 +
        return HOST_E_NOT_FOUND;
336 +
    reap(children[child].pid);
337 +
    collect(&children[child], out);
338 +
    return 0;
339 +
}
340 +
341 +
i64 host_wait_any(struct host_outcome *out) {
342 +
    bool any = false;
343 +
    for (int i = 0; i < HOST_MAX_CHILDREN; i++)
344 +
        any |= children[i].used;
345 +
    if (!any)
346 +
        return HOST_E_NOT_FOUND;
347 +
348 +
    /* The emulator starts no other processes, so any ended child is ours. */
349 +
    for (;;) {
350 +
        int   status;
351 +
        pid_t pid = waitpid(-1, &status, 0);
352 +
        if (pid < 0) {
353 +
            if (errno == EINTR)
354 +
                continue;
355 +
            return fail();
356 +
        }
357 +
        for (int i = 0; i < HOST_MAX_CHILDREN; i++) {
358 +
            if (children[i].used && children[i].pid == pid) {
359 +
                collect(&children[i], out);
360 +
                return i;
361 +
            }
362 +
        }
363 +
    }
364 +
}
365 +
366 +
/* Terminate and reap every child that has not been waited for. Only
367 +
 * async-signal-safe functions are used, so this runs from a handler. */
368 +
static void terminate_children(void) {
369 +
    for (int i = 0; i < HOST_MAX_CHILDREN; i++) {
370 +
        if (!children[i].used)
371 +
            continue;
372 +
        kill(children[i].pid, SIGTERM);
373 +
        reap(children[i].pid);
374 +
        close(children[i].outcome_fd);
375 +
        children[i].used = false;
376 +
    }
377 +
}
378 +
379 +
/* Terminate the children, then end the process as the signal would. */
380 +
static void on_terminate(int sig) {
381 +
    terminate_children();
382 +
    _exit(128 + sig);
383 +
}
384 +
385 +
void host_init(void) {
386 +
    atexit(terminate_children);
387 +
    signal(SIGTERM, on_terminate);
388 +
}
389 +
390 +
void host_report_outcome(int fd, const struct host_outcome *outcome) {
391 +
    u8  rec[8];
392 +
    u32 code = (u32)outcome->code;
393 +
    for (int i = 0; i < 4; i++) {
394 +
        rec[i]     = (u8)(outcome->kind >> (8 * i));
395 +
        rec[4 + i] = (u8)(code >> (8 * i));
396 +
    }
397 +
    u32 sent = 0;
398 +
    while (sent < sizeof rec) {
399 +
        ssize_t n = write(fd, rec + sent, sizeof rec - sent);
400 +
        if (n < 0 && errno == EINTR)
401 +
            continue;
402 +
        if (n <= 0)
403 +
            return;
404 +
        sent += (u32)n;
405 +
    }
406 +
}
machine.c +2 -0
101 101
            m.retired,
102 102
            config->hart_count,
103 103
            m.ticks
104 104
        );
105 105
    if (!m.finished) {
106 +
        if (config->timed_out)
107 +
            *config->timed_out = true;
106 108
        fprintf(
107 109
            stderr,
108 110
            "machine timed out after %llu ticks (%llu instructions)\n",
109 111
            m.ticks,
110 112
            m.retired
machine.h +9 -7
22 22
    u32                    memory_size; /* RAM byte count. */
23 23
    u64                    entry;       /* Initial PC for every hart. */
24 24
    struct machine_section text;        /* Loaded executable section. */
25 25
    struct machine_section rodata;      /* Loaded immutable data section. */
26 26
    struct machine_section rwdata; /* Loaded initialized writable section. */
27 -
    u32  stack_size;         /* Bytes reserved per hart; multiple of 16. */
28 -
    u32  hart_count;         /* Number of enabled harts, 1 through 8. */
29 -
    u64  max_steps;          /* Virtual ticks, including skipped idle time. */
30 -
    u32  irq_source;         /* One-shot PLIC edge source, 0 disables. */
31 -
    u64  irq_at;             /* Virtual tick of the one-shot edge. */
32 -
    bool trace;              /* Print hart-tagged instructions and traps. */
33 -
    bool count_instructions; /* Report actual retired instructions. */
27 +
    u32   stack_size;         /* Bytes reserved per hart; multiple of 16. */
28 +
    u32   hart_count;         /* Number of enabled harts, 1 through 8. */
29 +
    u64   max_steps;          /* Virtual ticks, including skipped idle time. */
30 +
    u32   irq_source;         /* One-shot PLIC edge source, 0 disables. */
31 +
    u64   irq_at;             /* Virtual tick of the one-shot edge. */
32 +
    bool  trace;              /* Print hart-tagged instructions and traps. */
33 +
    bool  count_instructions; /* Report actual retired instructions. */
34 +
    bool *timed_out; /* Optional out: set when the tick limit ended the run. */
34 35
};
35 36
36 37
/* Run the machine until a finish write or the tick limit. Returns 0 when the
37 38
 * guest writes the success value to the finish register, 1 when it writes a
38 39
 * failure value, and 2 for an invalid layout, UART output failure or timeout.
40 +
 * A timeout is also reported through `timed_out`, when it is not NULL.
39 41
 * Machine execution never enters the hosted JIT, debugger, or syscall
40 42
 * runtime. */
41 43
int machine_run(const struct machine_config *config);
42 44
43 45
#endif /* MACHINE_H */