README
RADIANT RISC-V EMULATOR

A RISC-V RV64I emulator with an x86-64 JIT compiler, interactive TUI
debugger, and headless execution mode. Part of the Radiant project.

Supports the RV64I base integer instruction set and the M (multiply/divide)
extension. Machine mode adds the A extension, Zicsr and Zifencei.

BUILDING

    $ make

  Requires `clang`, `lld`, `pkg-config`, and the BLAKE3 C library
  (`libblake3`). The binary is written to `bin/emulator`.

INSTALLATION

    $ make install

  Installed as `~/bin/emulator` by default. Can be overridden via the `PREFIX`
  variable.

USAGE

  Interactive (TUI):

    $ bin/emulator <program.bin>

  Headless:

    $ bin/emulator -run <program.bin> [<option>..]

  The emulator loads two image formats. The native format of current
  compilers has a 48-byte little-endian header followed by the bytes of
  three segments placed at their own addresses:

    0   "RADIANCE"
    8   code address (u64), size (u32)
    20  read-only data address (u64), size (u32)
    32  read-write data address (u64), size (u32), zero-filled tail (u32)
    48  code, read-only data and read-write data bytes

  Execution starts at the code address. Code and read-only data occupy
  exactly their size. Read-write data is followed by its zero-filled tail.
  Each segment must lie inside the memory of the mode, and the file must be
  exactly 48 plus the three sizes. Nothing else is checked.

  Images of older compilers also load in hosted mode, so that programs from
  every release run unchanged. The format is recognized by its magic bytes:

    "RAD0" version 1   Section sizes and fixed load addresses: read-only data
                       at 0x00010000, then text, then read-write data at
                       0x00FFFFF0. See image_rad0.c.
    no magic           The file is the text. Optional sidecar files
                       `<program>.ro.data` and `<program>.rw.data` hold the
                       data, at the same addresses. See image_raw.c.

  Machine mode loads only the native format. Each format is loaded by its own
  file, image_native.c, image_rad0.c and image_raw.c.

  A `<program>.debug` sidecar may be used for source locations.


OPTIONS

    -run                    Run headless (no TUI).
    -debug                  Load debug info for source-level diagnostics.
    -machine                Run RV64IMA M/U machine images, always headless.
                            Disables hosted calls, JIT, stack guards and TUI.
    -harts=N                Enable 1..8 independent machine harts (default 1).
    -irq=N                  Inject one PLIC edge on source 1..31, excluding 10.
    -irq-at=N               Virtual tick of the one-shot edge (default 0).
    -no-jit                 Disable the JIT compiler; interpret only.
    -memory-size=KB         Physical memory size in KB (default 128 MB).
    -data-size=KB           Data memory size in KB.
    -stack-size=KB          Stack size in KB (default 256 KB).
    -no-guard-stack         Disable stack guard zones (enabled by default, 16 bytes).
    -no-validate            Disable memory bounds checking.
    -trace                  Enable instruction tracing.
    -trace-instructions     Print each instruction during headless tracing.
    -trace-depth=N          Number of trace entries to display on fault.
    -max-steps=N            Maximum steps before timeout in headless mode.
    -count-instructions     Print instruction count on exit.
    -watch=ADDR             Set a memory watchpoint at ADDR.
    -watch-size=BYTES       Size of watched region (default 4).
    -watch-arm-pc=ADDR      Only trigger watchpoint after reaching ADDR.
    -watch-zero-only        Only trigger on zero-value stores.
    -watch-skip=N           Skip the first N watchpoint hits.
    -watch-backtrace        Print backtrace on watchpoint hit.
    -watch-bt-depth=N       Backtrace depth (default 8).

HOSTED SYSTEM CALLS

  Hosted programs call the emulator with `ecall`: the call number in a7,
  arguments in a0..a3 and the result in a0. A negative result is an error
  code. Memory is little-endian. Paths are (pointer, length) pairs without a
  terminating zero. A range outside guest memory faults the guest.

    0x400  exit(status)                       Does not return.
    0x401  read(fd, ptr, len)                 Bytes read, zero at end of file.
    0x402  write(fd, ptr, len)                Bytes written.
    0x403  open(path, len, mode)              Mode 0 reads; mode 1 creates or
                                              truncates for writing.
    0x404  close(fd)                          Descriptors 0..2 stay open.
    0x405  stat(path, len, out)               Writes size (u64), kind (u32:
                                              1 file, 2 directory, 3 other)
                                              and u32 padding.
    0x406  makeDir(path, len)
    0x407  remove(path, len)                  A file or an empty directory.
    0x408  rename(from, flen, to, tlen)
    0x409  listDir(path, len, buf, blen)      Names, each followed by a zero
                                              byte, without "." and "..".
    0x40A  spawn(spec)                        Runs an RV64 image in a child
                                              emulator; returns a child handle.
    0x40B  wait(child, out)                   Writes the outcome (kind u32:
                                              0 exited, 1 step limit, 2 fault;
                                              code i32).
    0x40C  waitAny(out)                       Returns the handle that ended.
    0x40D  exchange(left, llen, right, rlen)  Atomically swaps two existing
                                              entries on the same filesystem.

  Errors: -1 NotFound, -2 Exists, -3 Denied, -4 NotEmpty, -5 Invalid (also
  any other call number from 0x400), -6 TooLarge, -7 Limit, -8 Io.

  `spawn` takes a 128-byte record with the image path, the arguments, the
  destinations of standard output and error, the mode (hosted or machine),
  the machine and memory sizes, and the step budget. The child runs this
  executable again with the matching options; its standard input is empty.
  At most 64 children run at once. The children still running when the guest
  ends are terminated. A child reports how it ended through the internal
  option `-outcome-fd=N`, which is not meant to be passed by hand.

  The full specification is `.ai/decisions/2026-10-28-host-abi` in the
  Radiance repository. Everything that touches the host operating system is
  behind `host.h`; `host_posix.c` implements it for Linux and macOS.

LINUX SYSTEM CALLS

  Programs built before the host ABI, up to October 2026, call the emulator
  with Linux RV64 numbers. They run unchanged: numbers below 0x400 are Linux
  calls and numbers from 0x400 are host calls, in the same run. See
  abi_linux.c.

    56  openat(dirfd, path, flags)   Zero-terminated path; `dirfd` is ignored.
                                     Flags O_RDONLY, or O_WRONLY | O_CREAT |
                                     O_TRUNC. Returns a descriptor or -1.
    57  close(fd)                    Zero, or -1.
    63  read(fd, ptr, len)           Bytes read; zero on failure.
    64  write(fd, ptr, len)          Bytes written; zero on failure.
    93  exit(status)                 Does not return.

  Any other number returns -38 (ENOSYS).

MEMORY LAYOUT

    0x00010000                 Read-only data
    Program base               Program text (instructions)
    0x00FFFFF0                 Read-write data
    Memory top - stack size    Stack
    Memory top                 Top of memory

ARCHITECTURE

  The emulator operates in two execution modes:

    Interpreter    Steps through instructions one at a time. Used for the
                   TUI debugger, ecalls, ebreak, and as a fallback.

    JIT            Translates basic blocks of RV64I instructions to native
                   x86-64 machine code. Blocks are compiled on first
                   encounter and cached (16 MB code cache, up to 256K
                   blocks). Falls back to the interpreter for system
                   calls and faults.

  The TUI debugger supports single-stepping, reverse execution (via
  snapshots), register and stack inspection, and memory watchpoints.

MACHINE PLATFORM

  Machine execution is a separate RV64IMA + Zicsr + Zifencei interpreter, without
  floating point, compressed instructions, page translation or PMP. Each hart
  has independent registers, privilege, CSRs, traps, WFI and LR/SC reservation.
  Harts are selected round-robin; one instruction or trap boundary advances
  shared mtime by one tick. RAM and MMIO are strongly ordered, AMOs indivisible,
  and every overlapping store invalidates LR reservations. FENCE ordering is
  inherent; FENCE.I observes uncached instruction fetches.

  WFI sleeps until a locally enabled interrupt is pending, independently of the
  global MIE bit. It never exits the emulator. When all harts sleep, virtual time
  jumps to the next timer/input event or -max-steps deadline; idle ticks count
  toward this bound. External, software, then timer is the M interrupt priority.
  mtvec supports direct and vectored interrupts. Synchronous U faults trap to M.

  Physical devices (all other aperture offsets/widths fault):

    0x02000000..0x02010000  CLINT: MSIP words at +4*hart; mtimecmp at
                            +0x4000+8*hart; mtime at +0xbff8. Timers accept
                            aligned 32-bit halves or 64-bit accesses.
    0x0c000000..0x10000000  PLIC: 31 sources, priorities 0..7 at +4*source,
                            pending at +0x1000, enable at +0x2000+0x80*hart,
                            threshold/claim/complete at +0x200000+0x1000*hart
                            and +4. Every register is 32-bit. M context=hart.
    0x10000000..0x10001000  Transmit-only 16550 UART: byte registers THR +0
                            (stdout), IER +1 (only THRE, bit 1), IIR +2 and
                            LSR +5 (read only, always ready). Source 10 on the
                            PLIC is the level-sensitive THRE interrupt.
    0x10001000..0x10002000  Finish: 32-bit register at +0, writable in M and
                            U. Write 0x5555 for success, 0xNNNN3333 for
                            failure. Other writes fault. Reads return zero.

  RAM is [0x80000000,0x80000000+memory-size), above every device aperture.
  Naturally aligned fetches/loads/stores are checked even with -no-validate.
  The hosted stack and frame-pointer checks do not apply. Instructions may
  execute anywhere in RAM, including admitted images outside the original text.
  U stores to the original text and rodata are rejected as an optional ROM
  defense, not memory isolation.

  Boot and FDT:

    Every hart starts at the loaded text entry in M mode. a0 and mhartid are its
    zero-based ID; a1 is the FDT address, 0x80800000. sp is the 16-byte aligned
    top of RAM minus hart*stack-size. Each full stack is reserved; all other
    registers start zero. -stack-size applies independently to every hart.

    FDT v17 is stored in the fixed 64 KiB reservation [0x80800000,0x80810000).
    Image or stack overlap with this reservation is rejected. The memory node
    starts at 0x80000000. CPU interrupt-controller phandles are hart+1;
    the PLIC phandle is 0x100. CLINT extended pairs are (hart+1,3),(hart+1,7);
    PLIC contexts are ordered (hart+1,11). UART interrupt-parent is 0x100.
    The timebase is 10 MHz. The finish compatible string is "radiant,finish".

    /chosen has radiance,kernel-entry (u64), radiance,kernel-text,
    radiance,kernel-rodata, radiance,kernel-rwdata, radiance,fdt-reservation
    (each address-u64,size-u64), and radiance,kernel-stacks (one such pair per
    hart). Exact loaded sections, every initial stack, FDT storage and full
    MMIO apertures appear in both the reservation map and reserved-memory
    no-map nodes. Empty loaded sections have size zero in /chosen and are
    omitted from reservations.

  -trace prints hart-tagged instructions and traps. -count-instructions reports
  retired instructions separately from elapsed virtual ticks. Hosted source
  debugging and watchpoints are rejected in machine mode. Process results are
  0 for explicit success, 1 for guest failure, and 2 for timeout/configuration or
  host UART output failure. No host time, stdin polling or host threads affect
  guest execution. This is not a cycle-accurate model of UART wire timing.

  The platform is exercised by the Radiance test suite (`make test` in the
  Radiance repository, with `RAD_EMULATOR` set to this binary).

LICENSE

  Licensed under the MIT License,
  Copyright (c) 2025-2026 Radiant Computer (https://radiant.computer)