Kern
On this page

M2: freestanding runtime design

Status: design, not implemented. M0 supplies the 32-bit data model, target and capability checks; M1 supplies the pinned external assembler/linker, board descriptions and QEMU runner. M2 supplies the minimal no-OS runtime. M3 supplies general MMIO and interrupt declarations; M6 supplies cooperative tasks. No libc, OS, constructors, implicit heap, scheduler or background initialization is required. Runtime helpers and their data are linked only when referenced. Existing hosted behavior must remain unchanged.

Verified: Cortex-M3 runtime probe

On the M1 toolchain (Homebrew clang/LLD 23.1.6, QEMU 11.1.3, Arm GNU size 2.44.0.20250616), run:

export PATH="/opt/homebrew/opt/llvm/bin:/opt/homebrew/bin:$PATH"
sh scripts/mcu/runtime-probe.sh
# PASS: Cortex-M3 runtime probe

The script compiles separate normal and deliberate-trap images using clang's integrated assembler and LLD, and checks the complete QEMU semihosting output and process status: runtime ok\n / 0 and runtime trap\n / 1, respectively. Both runs have a 10-second timeout. Reset masks interrupts, sets MSP, poisons the probe RAM to make missing initialization observable, copies .data bytewise, clears .bss bytewise, and calls C main. The normal path checks a distinctive initialized word, all 4,097 B of BSS and a recursive call to depth six. The vector table and default halt handler are probe-specific; this is not compiler-generated runtime code.

To reproduce the normal image size (the runner itself removes its temporary files):

clang --target=arm-none-eabi -mcpu=cortex-m3 -mthumb -c scripts/mcu/runtime/startup.S -o /tmp/runtime-startup.o
clang --target=arm-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -fno-builtin -fno-stack-protector -Os -c scripts/mcu/runtime/probe.c -o /tmp/runtime-probe.o
ld.lld -T scripts/mcu/runtime/mps2-an385.ld /tmp/runtime-startup.o /tmp/runtime-probe.o -o /tmp/runtime-probe.elf
arm-none-eabi-size -A /tmp/runtime-probe.elf

The measured .text is 278 B, .data 4 B, .bss 4,097 B; .vectors is 192 B and .ARM.exidx is 16 B. This .text includes probe checks, semihosting and strings, so it is not a startup-only or incremental feature budget. The .data VMA is 0x20000000, load address 0x1e8; there are no undefined symbols. The 1 KiB stack reservation is a linker assertion, not included in .bss.

This does not verify interrupts, SysTick, physical boards, language-generated trap metadata, static stack proof, or the other planned runtime features.

Verified on RV32

On Homebrew clang/LLD 23.1.6 and QEMU 11.1.3, with LLVM llvm-size, run:

export PATH="/opt/homebrew/opt/llvm/bin:/opt/homebrew/bin:$PATH"
sh scripts/mcu/runtime-probe-rv32.sh
# PASS: RV32 runtime probe

The runner builds normal and deliberate illegal-instruction images for RV32IMAC plus Zicsr on QEMU virt without firmware. It checks the complete UART0 output and process status, respectively runtime ok\n / 0 and runtime trap\n / 1, with a 10-second timeout per run. Reset masks machine interrupts, initializes gp without linker relaxation and a 16-byte-aligned sp, installs the aligned mtvec entry, poisons the destination, copies .data, clears .bss, and calls the shared C probe. The checks cover a distinctive initialized word, all 4,097 B of BSS and a recursive chain to depth six. The illegal instruction enters the non-returning trap veneer and hook; the hook uses the QEMU test device to report failure. As a negative check, separately omitting the copy or zero loop caused runtime trap\n / 1 in each case.

The normal ELF measured 526 B .text, 4 B .data, 4,097 B .bss, and 14 B .trap; there is no .vectors section. .text includes the checks, UART code and strings, so it is not a startup-only budget. The data VMA is 0x80400000, its distinct load address is 0x80000220, and there are no undefined symbols. The 1 KiB stack reservation is a linker assertion, not part of .bss. Both IMAGE and RAM are regions of QEMU RAM: this models a separate load image but does not test physical flash or a real boot ROM.

This is a handwritten probe, not compiler-generated runtime. It does not verify machine interrupts or return from traps, nested faults in the hook, timer/clock support, physical UART or boards, language trap metadata, a static stack bound, or the other planned runtime features. The assembly veneer assumes an intact stack and uses a probe-specific non-returning hook; a production fault policy needs its own validation.

Memory and linker contract

A board profile supplies physical FLASH and RAM origins and lengths, vector alignment and interrupt count, stack size, heap size (default 0), task stack sizes (default none), and optional clock and debug device. These values are board-specific; QEMU RAM addresses must come from its chosen machine, not this example. The layout is:

FLASH low: .vectors | .text | .rodata | .data load image :high
RAM   low: .data | .bss | optional heap | task stacks | unused | main stack :high

For example, an STM32F103-like profile (64 KiB flash, 20 KiB RAM) can generate this GNU ld/LLD script. The example uses an 8-byte heap/stack alignment and 1 KiB main stack; the board must choose adequate values. .vectors is retained even under section GC. .data has distinct run and load addresses; NOLOAD storage has no flash image. Task stack sizes include required alignment padding. No stack guard hardware is assumed.

ENTRY(_start)
MEMORY {
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 64K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 20K
}
__heap_size = 0;                 /* profile-generated; multiple of 8 */
__task_stacks_size = 0;          /* profile-generated; multiple of 8 */
__main_stack_size = 1K;          /* profile-generated; multiple of 8 */
SECTIONS {
  .vectors ORIGIN(FLASH) : ALIGN(128) {
    __vectors_start = .; KEEP(*(.vectors)) __vectors_end = .;
  } > FLASH
  .text : ALIGN(4) { *(.text .text.*) } > FLASH
  .rodata : ALIGN(4) { *(.rodata .rodata.*) } > FLASH
  .data : ALIGN(8) {
    __data_start = .; *(.data .data.*) . = ALIGN(8); __data_end = .;
  } > RAM AT> FLASH
  __data_load = LOADADDR(.data);
  .bss (NOLOAD) : ALIGN(8) {
    __bss_start = .; *(.bss .bss.* COMMON) . = ALIGN(8); __bss_end = .;
  } > RAM
  .heap (NOLOAD) : ALIGN(8) {
    __heap_start = .; . += __heap_size; __heap_end = .;
  } > RAM
  .task_stacks (NOLOAD) : ALIGN(8) {
    __task_stacks_start = .; . += __task_stacks_size; __task_stacks_end = .;
  } > RAM
  __main_stack_top = (ORIGIN(RAM) + LENGTH(RAM)) & ~7;
  __main_stack_bottom = __main_stack_top - __main_stack_size;
  ASSERT(__task_stacks_end <= __main_stack_bottom, "RAM overflow: stack collision")
  ASSERT((__heap_size & 7) == 0 && (__task_stacks_size & 7) == 0 &&
         (__main_stack_size & 7) == 0, "unaligned reservation")
}

The generator must reject arithmetic overflow, invalid sizes, and a vector address/alignment unsupported by the board. Reserve main-stack RAM in the memory report even though it is expressed by symbols; include .data in both flash load size and RAM use. The example's 128-byte vector alignment is a minimum illustration, not sufficient for every vector count or device. A board with a bootloader must specify its actual vector address and any required VTOR setup. Generate named subranges within the task stack pool at M6; each stack is statically bounded and disjoint. RV32 uses an analogous script but its boot entry and trap section are board/boot-contract specific, not an ARM vector table.

Reset and traps

On Cortex-M, the table starts with __main_stack_top, then the Thumb-addressed reset handler _start; the remaining architectural exception entries are NMI, HardFault, MemManage, BusFault, UsageFault, four reserved zero entries, SVCall, DebugMonitor, one reserved zero, PendSV and SysTick, followed by the board's external IRQ entries. Reserved entries are zero; unused implemented exceptions/IRQs point to a minimal non-returning default handler. The device profile supplies the number and ordering of external IRQs. Stack pointer is loaded by the core from vector word zero, before the reset handler executes. An alternate bootloader entry must explicitly establish MSP and vector routing to meet the same contract.

kern emits _start, the table and relocations, using the M1 external toolchain. Reset enters with interrupts disabled or masks them immediately, copies [__data_load, __data_load + (__data_end - __data_start)) to [__data_start, __data_end), and zeros [__bss_start, __bss_end); byte-safe loops handle empty ranges and tails. If the profile explicitly enables the M4F FPU, configure CP10/CP11 and execute the required barriers before any FP instruction. M3 and the initial M4 profile use no FPU. Initialize only requested devices (e.g. SysTick) after memory is ready; unmask interrupts only when handlers and state are valid. Call the compiler's normal main ABI, then invoke a board exit hook or halt forever. QEMU test profiles may use semihosting exit; physical boards default to a halt loop. No implicit allocator initialization is needed when heap is absent.

RV32 _start follows the board's reset/boot contract, initializes sp and any ABI-required gp before generated code, sets mtvec to an aligned machine trap entry, performs the same data/BSS initialization, then calls main. It must not assume ARM vectors, SysTick, address zero, or a universal QEMU firmware. Board setup defines interrupt controller and timer access. Machine faults and unhandled interrupts enter a small assembly veneer that preserves the state needed by the ABI and calls the non-returning hook; interrupts explicitly handled by a board are dispatched separately.

One board-overridable, non-returning ABI is kern_trap_hook(kind: u32, file_id: u32, line: u32). It must be safe with interrupts masked, without allocation or locks; it may write a bounded numeric record to configured semihosting or polled UART, then halt. The default is halt alone; do not execute a semihosting breakpoint on hardware unless enabled. Exception veneers use reserved kind values and file/line zero when there is no source site. Trap within the hook goes directly to halt, avoiding recursive logging. An optional file-id map belongs in host-side debug artifacts, not mandatory flash strings; stable IDs within one build identify source files.

Today stage0 src/gen/stmt.rs creates line stubs and src/gen.rs emits kind/file stubs feeding the hosted kern_trap; self-hosted compiler/src/backend/data.kn emits per-site message stubs. For none, both backends instead pass numeric kind, file ID and the full line in target ABI registers and tail-branch to the hook, with no formatted message or syscall. Preserve the existing kind mapping: 0 overflow, 1 bounds, 2 assert, 3 division, 4 cast, 5 precondition, 6 postcondition. New runtime/hardware kinds need reserved documented values. Avoid the current AArch64 line truncation pattern in the new backend. Bounds/arena failures must retain the originating call site's identity, including across nested calls; do not rely on a single mutable global trap site.

Time and sleep

Clock is an explicit capability, absent unless a board supplies a valid monotonic timer, frequency and handler. On Cortex-M, configure SysTick for a 1 ms tick only when clock_ns or sleep_ms is reachable; validate reload in the 24-bit range and exact or documented rounded frequency. The handler increments a static u64 millisecond counter. On this 32-bit core read it in a short critical section that saves and restores the previous interrupt mask; never blindly enable interrupts. Return ticks * 1_000_000 as u64 nanoseconds, with 1 ms resolution (not nanosecond precision); specify modulo-u64 overflow. This is monotonic provided ticks are serviced without losing wraps. SysTick has a single pending bit: the board must bound interrupt masking and higher-priority handler time below a tick, or use a free-running hardware counter that can account for missed periods. Do not claim accurate elapsed time through prolonged masking or deep sleep that stops the timer.

sleep_ms(0) returns immediately. For nonzero durations compute an overflow-safe deadline or elapsed difference, and wait until elapsed ticks reach the requested duration; return true only on completion. Perform the check and low-power wait with the architecture's race-free interrupt protocol: mask, recheck, execute WFI while the enabled timer can become pending, restore the saved mask, then loop; document/test the target's WFI semantics. If called with interrupts already masked, from an ISR, or with a stopped/unavailable clock, fail deterministically rather than hang. Account for spurious wakeups. Tick quantization means at least the requested duration requires rounding the deadline up relative to the current tick phase, or a sub-tick counter; define the selected policy in tests. No polling loop that consumes CPU is the default.

RV32 has no SysTick: a board timer adapter provides equivalent monotonic ticks, interrupt acknowledgment/rearming and a race-free wfi protocol using the platform's machine timer/interrupt controller. Read split timer registers using the board-specified stable high/low/high sequence where applicable, and avoid torn compare writes. If the selected QEMU machine lacks a usable timer adapter, clock tests are skipped as unsupported and the capability is rejected, not silently emulated with an ARM register.

Explicit memory allocation

Default heap is zero and alloc is a compile-time capability error. With a declared nonzero heap, the linker-reserved byte region is managed by a first-fit free list ordered by address. Use 8-byte alignment (or the target ABI's larger required alignment); align the region inward and round each requested block up with checked arithmetic. A block has an aligned size/allocated-state header; free blocks also hold a next pointer in their payload. Enforce a minimum split size sufficient for that metadata, otherwise consume the whole block. Free validates a legitimate live allocation in checked builds, reinserts in address order and coalesces adjacent blocks. Search is bounded by the number of blocks in the fixed heap, but fragmentation can still make a request fail with enough total free bytes. Heap metadata and alignment padding count against the declared RAM budget. Initialize the free list explicitly at reset only when heap capability is used, after BSS initialization.

alloc[T](n) checks multiplication and rounding overflow, returns a zero-filled owned slice as specified today, and frees through the same provider on ownership release. Zero-size allocations have a documented canonical empty representation and consume no block. Because existing alloc is not fallible, exhaustion and invalid size trap through the single hook; no null slice masquerades as success. A future fallible API can return an error explicitly. Allocator calls are disallowed in interrupt context; protect shared task access with a bounded critical section or enforce single-owner access, and never hide allocation in output or time helpers.

A caller-buffer arena is independent of the heap: construct it explicitly from a mutable borrowed byte buffer, recording base, capacity and cursor. Each allocation aligns the absolute address, checks addition, multiplication and capacity, then advances the cursor and zeroes the returned bytes where required by language semantics. No per-object header or free list is needed; reset/release invalidates all arena borrows/handles under the ownership rules. Exhaustion traps at the caller site under the existing non-fallible API. Alignment padding counts against capacity; construction and allocation never allocate a backing buffer. Existing hosted arena creation calls kern_alloc, so a buffer-backed API and corresponding ownership rules are prerequisite work, not a claim about current behavior.

Static stack proof

After lowering and register allocation, each backend records the maximum actual frame for every function: saved registers, spills, locals, outgoing argument area, ABI alignment and compiler-generated temporaries. Include runtime helpers, assembly veneers and ABI call overhead; do not sum mutually exclusive branches. Construct the reachable direct call graph after monomorphization, include every possible indirect target or reject an unresolved edge, then compute frame(f) + max(edge overhead + chain(callee)) in reverse topological order. Reject reachable recursive strongly connected components in the MCU profile, including mutual recursion; no budget-based escape is in M2. External functions require a declared, verified stack bound or cause an error. Dynamic stack allocations and unknown calls are rejected.

The check belongs after final frame layout and call lowering, before successful link/report, in both stage0 and self-hosted builds. Compare main's maximum chain plus worst permitted nested exception/interrupt frames and handler chains, alignment and a board-specified safety margin against __main_stack_size. Include hardware exception stacking and optional FPU extended frames when enabled, plus software-saved registers. For M6 perform the same calculation per task stack and account separately for interrupt use of MSP/architecture-specific stacks. Report the chain and all assumptions; if interrupt nesting or external stack use is unbounded, reject the proof rather than claim safety. Static analysis is an upper bound only under those explicit assumptions; linker assertions independently prevent RAM reservations overlapping.

Capabilities and I/O

Pure arithmetic, control flow, fixed/static memory when M0/M3 deliver it, checked operations and caller-buffer arenas require no OS capability. print/numeric printing require an explicitly selected debug-output capability and a board-provided polled UART or semihosting sink; no default filesystem, stdout descriptor or hidden output buffer exists. With no sink, programs not using output still link; using print is rejected at compile time. Trap halt needs no sink. clock_ms, clock_ns and sleep_ms require clock; alloc requires a declared heap. Board UART and semihosting are explicit debug sinks, not general file APIs.

The M0 capability checker rejects write_file, read_file, directory operations and file metadata without a file capability, and spawn_process, wait/status/stop and process APIs without a process capability, with E170-E179 diagnostics naming the missing capability and source site. Environment, executable path, current directory, hosted image/JIT and OS services likewise require their own explicitly supported capability; no syscall-shaped stubs or silent success on none. No file/process provider is part of M2. Capability checking follows reachable code and generated helpers consistently in both compilers, before link; the board cannot grant a capability for which no provider exists. Runtime emission must not accidentally pull hosted mmap, syscall, libc or allocator code through a helper.

Implementation sequence and QEMU acceptance

  1. M0/M1 prerequisite: 32-bit ABI, target/profile and capabilities; external toolchain and per-board script. Add a minimal M3 and RV32 image/runner with explicit machine, memory map, semihosting and timeouts. The QEMU machine's actual boot ROM and reset addresses must be verified; do not substitute the illustrative linker addresses above.
  2. Startup/trap: add target-specific modules under src/gen/ and compiler/src/runtime_thumb/ and compiler/src/runtime_rv32/; dispatch from src/gen.rs, src/gen/runtime.rs, src/gen/support.rs and compiler/src/runtime/emit.kn. Adjust src/gen/stmt.rs and compiler/src/backend/data.kn for numeric trap ABI. Keep hosted templates unchanged. Add board/linker-script generation at the M1 toolchain boundary. src/elf.rs and compiler/src/elf/ are unchanged for M1 external linking; M5 must add 32-bit ELF machine/entry/sections and relocations rather than treating current hosted _start writer as MCU-ready.
  3. Memory and clock: add optional freestanding allocator and caller-buffer arena lowering alongside src/gen/arena.rs and matching self-hosted runtime modules, target-specific clock/ISR code alongside src/gen/system.rs and compiler/src/runtime_extra/, plus capability checking and stack reporting in both compiler pipelines. Emit each feature only if reachable. Integrate M3 interrupt declarations when available; M2 owns its private timer veneer.
  4. Deferred M6: task pool, context switch and per-task stack proof; do not add a scheduler to M2. Track M4 size optimization and M5 direct encoding separately.

tests/embedded/ and tests/run_embedded.sh should build with the pinned M1 toolchain and run with bounded QEMU timeouts, exercising both stage0 and self-hosted compilers where supported. Acceptance is planned, not evidence of current implementation:

  • M3 and RV32: sentinel initialized .data, zeroed .bss, aligned stack and main invocation; inspect ELF section VMA/LMA, vector/entry, linker map, absence of undefined libc/syscalls, and semihosting exit. Deliberately overflow RAM and expect link failure.
  • Trigger every language trap and assert exact kind/file/line, including large line values and arena call sites; default unhandled fault halts. Check no sink or heap code appears in a minimal image.
  • M3 SysTick and RV32 board timer: monotonic reads across a 32-bit counter carry, sleep zero and nonzero, spurious interrupt wake, no lost check-to-WFI wake, and masked/ISR rejection. Test timer unavailability as a compile-time rejection; make wrap and long masking assumptions explicit.
  • Heap-zero rejects alloc; heap-enabled test checks zero fill, alignment, split/coalesce, exhaustion, overflow, fragmentation and reuse. Caller-buffer arena checks misaligned buffers, exact fit, exhaustion and reset/lifetime checks without heap symbols.
  • Direct and mutual recursion, unknown external stack use, undersized main stack and unauthorized file/process/clock/output fail with source diagnostics. An acyclic nested-call case reports a conservative chain including an interrupt allowance.
  • With linker GC and a pinned toolchain, compare map/section sizes against feature budgets and require no unrelated feature symbols. QEMU semihosting validates functional paths, not physical UART, real interrupt latency, low-power current or hardware qualification.

Runtime text budgets and decisions

Proposed initial incremental maximum .text bytes, measured as the difference between otherwise identical linked minimal programs with/without the feature, same board, pinned toolchain, size flags and GC. They are design gates to validate and calibrate on both architectures, not measured results; report per architecture. Include generated veneers and compiler runtime helpers attributable to the feature; report vector/rodata separately and RAM reservations separately. Shared code is attributed once and also reported as a combined image so marginal numbers cannot hide growth.

FeatureIncremental .text ceilingScope
trap256 Bnumeric stub and halt hook; UART formatting excluded
clock and sleep512 Btick handler, atomic read and WFI sleep; board timer setup included
caller-buffer arena256 Balignment, bounds and reset; no backing storage
cooperative tasks (M6)1,024 Bscheduler and context switch, excluding task bodies and stacks
optional heap512 Bfirst-fit, coalescing, zero fill and failure path

Also gate base startup at 256 B and debug sink separately at 512 B; vectors and .data load image count toward total flash even though excluded from .text ceilings. Gate total flash/RAM against the board and EMBEDDED.md example budgets. If a measured implementation exceeds a proposed ceiling, investigate and explicitly revise the budget with evidence; never silently disable a feature or its safety checks.

Open decisions, with recommendations:

  • Clock precision: start with 1 ms SysTick and conservative sleep rounding; use a free-running timer when masked time or sub-millisecond precision matters. Specify RV32 timer per board.
  • Heap policy: retain a zero default and non-fallible alloc trap semantics; add fallible allocation only as a separate explicit API. Select a finite heap and forbid ISR use.
  • Arena API: introduce a caller-buffer constructor with borrow-checked lifetime; retain hosted heap-backed construction as an explicit separate provider.
  • Stack policy: reject recursion and unknown bounds for MCU v1; consider an explicit recursion budget only with a sound enforcement mechanism later.
  • Trap delivery: numeric hook plus halt by default, opt-in semihosting for CI and UART for boards; make file maps host artifacts.
  • Tasks: reserve zero bytes until M6 and defer scheduler and its budget proof; M2 remains single-threaded apart from declared interrupts.
  • FPU: off for M4F initially. Enabling it requires explicit board opt-in, ABI agreement and extended exception-stack accounting.

Source: M2-RUNTIME.md in the repository.