# Run, test, and debug firmware with sim

`sim` runs a firmware ELF on a simulated chip, in virtual time, with no hardware. This page
covers installation, a first run, checking a result, boards and peers, several machines,
and debugging with evidence. For a worked example with source and captured output,
follow the [STM32 simulation tutorial](/stm32-simulator).

Commands were checked against **sim 0.8.11 (build 0e3e0a82)** on November 5, 2026.
This page is adapted from that release's bundled guide. For the exact options your
installed version supports, run `sim docs show cli` or `sim <MCU> run --help`.

## Documentation for engineers and agents

The CLI bundles Markdown documentation inside the executable. It does **not**
install an editor-specific agent skill. An agent with terminal access can read the
same version-matched instructions as an engineer:

```sh
sim docs list
sim docs show guide
sim docs show troubleshooting
sim docs show record
sim docs show cli
```

These commands need neither a login nor Python. `sim docs path` writes the bundled
pages to `~/.sim/docs` when missing or from another version and prints that directory.
`sim docs install` refreshes the files explicitly; `sim update` refreshes them too.
The [Markdown version of this page](/docs/guide.md) is available to web-reading agents.
See [debugging with evidence](#debugging-with-evidence) for the investigation procedure.

## 1. Install and sign in

```sh
curl -fsSL https://simantic.com/install | sh     # installs sim to ~/.local/bin, then offers `sim login`
sim login                                        # browser sign-in; saves ~/.sim_id
sim version
```

- Downloads need no account. Community includes 100 runs a week, resetting Monday at 00:00 UTC; Developer and Enterprise keys have no run limit.
- A simulation run needs network access to validate your Simantic account. `sim models` lists built-in targets offline.
- `sim` needs CPython 3.12 or newer on the machine (`python3` or `python` on `PATH`, or set
  `SIMANTIC_PYTHON_DLL` to the path of its shared library). It is used for scripted peers.
- `sim update` installs the latest release and refreshes these docs. `sim update --check` only reports.
- `sim telemetry` shows whether usage stats are collected.

## 2. Pick a chip and run

```sh
sim models                                # the chips this sim runs, with their status
sim STM32H753II run --elf fw.elf --ascii --timeout 3
```

`run` builds the chip, loads the ELF (or Intel HEX), runs it for `--timeout` seconds of virtual
time (default 15), and prints every UART's output. `--ascii` prints text instead of hex bytes;
`--only-messages` drops the timestamp and UART name; `--output <file>` writes to a file.

```
[0.063234s] (uart5) [00:00:00.019,000] <wrn> stm32_sdmmc: Failed to configure pins for sleep (-2).
[0.894868s] (usart1) GDS usart1 echo endurosat_obc
```

`[t]` is instruction-precise virtual time. Warnings and the run summary go to stderr.

Models have a status: `modeled`, `incomplete` (runs, with a warning) or `not-modeled` (`run`
cannot simulate it). `sim models --show-incomplete --show-unmodeled` lists all three.

### Chips with a boot ROM

Some chips run code from a mask ROM before your firmware: it maps flash, sets up the CPU and
jumps to a second-stage bootloader or straight to the image.

| Chip | Boot ROM in `sim` | What to run |
| --- | --- | --- |
| RP2040, RP2350 | Built in | The flash image or ELF with its boot2 (pico-sdk's default output). An ELF whose entry is in SRAM starts directly, as a debug probe starts it. |
| ESP32, ESP32-S3, ESP32-C3 | Built in: Espressif's ROM for ESP32 v3.0, S3 v0.x and C3 v0.3 (the ROMs Espressif's QEMU ships). `ESP32_ROM` / `ESP32S3_ROM` / `ESP32C3_ROM`, or `rom:` in a scenario, point at another full ROM ELF | The app ELF from `idf.py build` or Arduino, left in its build directory: `sim` lays out flash as `idf.py flash` would, with the bootloader and partition table that build wrote beside it (`bootloader/bootloader.bin` + `partition_table/partition-table.bin`, or Arduino's `<sketch>.ino.bootloader.bin` + `.partitions.bin`) and the app at its partition. A merged flash image (`idf.py merge-bin`) also works. |
| ESP32-C5, ESP32-C6, ESP32-P4 | Not shipped | An image ELF that carries the ROM segment. |

```sh
idf.py build
sim ESP32-S3-WROOM-1-N16R8 run --elf build/hello_world.elf --ascii --timeout 3
```

Arduino: `arduino-cli compile -b esp32:esp32:esp32s3 --output-dir out Blink`, then
`sim ESP32-S3 run --elf out/Blink.ino.elf --ascii`. Console output on native USB (`USB_CDC_ON_BOOT`) needs
`--usb-cdc-console usb_otg`.

## 3. Turn a run into a check

```sh
sim STM32H753II run --elf fw.elf --ascii --timeout 3 \
    --expect "boot ok" --expect-absent "ASSERT"
```

- `--expect TEXT` exits 1 unless the UART output contains `TEXT`; `--expect-absent TEXT` exits 1 if it does. Both repeat.
- A Cortex-M fault (HardFault, MemManage, BusFault, UsageFault) or lockup fails the run at its end.
  `--on-fault stop` stops at the first one and exits 3 (one machine only); `--on-fault continue` does not fail.
- Unmapped accesses in a chip's recorded peripheral map fault by default. `--no-trap-unmapped`
  reads 0 and drops writes there instead. `--trap-unmapped` also faults outside the recorded map,
  where the simulator cannot distinguish reserved space from an unmodeled block.
- SIGINT or SIGTERM stops a run early, flushes output and exits 130 or 143 without checking `--expect`.

## 4. Boards and peers

A chip alone has no board around it. A **board file** (`--board <file>`) lists the parts on the
chip's buses: sensors, memories, other chips, the HSE crystal. A part that is not the chip is a
**peer**, usually a short Python script. A `file:` path inside a board file is read relative to
the directory you run `sim` from.

```sh
sim STM32H753II check --elf fw.elf --board obc.board     # builds and wires it, fails on any problem
sim STM32H753II run   --elf fw.elf --board obc.board --ascii
```

`check` fails on an unknown key, a model this sim has not ported (`skipped model:`), a bad pin
or an unwired peer. A run prints the same problems as warnings; `--fail-on-skipped-models`
makes a skipped model fail the run. A peer callback that raises does not stop the run: the first
traceback of each callback prints, and the run exits 1 at the end with
`error: N peer callbacks raised (...)`, even if the firmware passed. A peer that injects a fault
returns bad data instead of raising.

A board file is only the parts around the chip; the chip itself comes from `sim <MCU>`.

## 5. Several machines

A scenario file wires machines together over media (CAN, Ethernet, UART, Wi-Fi). Machines advance in
lockstep, one slice (the quantum) each in turn, so a multi-chip run is deterministic. The quantum is
10 us when the scenario declares a medium and 100 us otherwise; `quantum:` (seconds) sets it.


```yaml
machines:
  nodea: { mcu: STM32F407VG, elf: fw.elf }
  nodeb: { mcu: STM32F407VG, elf: fw.elf }
media:
  - type: can
    connect: [nodea.can1, nodeb.can1]
```

```sh
sim run --scenario two-node.yaml --ascii     # console lines are prefixed [nodea], [nodeb]
sim graph --scenario two-node.yaml           # the system as a Mermaid flowchart
```

A machine's `elf:` and `overlay:` paths resolve relative to the scenario file. Keys that reach the
host (`gateway:`, `forward:`, `bridge:`, `HostNetwork`) force real-time pacing and make the run depend
on your machine and network: use them to demo or debug, not to gate a build. A scripted peer or a
two-firmware medium stays deterministic.

### Choosing `quantum:`

Traffic between machines (a frame, a byte, a pin level, anything a Python peer relays from one
machine to another) can arrive up to one quantum late. A larger quantum runs faster, but **it must not
be longer than the shortest real latency of any link between machines**, or replies arrive after
they should have. The run stays repeatable, so nothing fails loudly: the firmware takes a timeout or
retry path it would not take on hardware.

- Find the shortest link: the smallest delay any medium, wire or relaying peer adds between two
  machines. A radio peer that holds frames for 20 ms allows up to 20 ms; a BLE link, which answers
  within about 150 us, does not.
- Pins wired between machines (`nets:`) and peers that relay with no delay have no latency. Leave the
  default.
- `sim` does not check this for you. A quantum longer than a link's latency is accepted and gives
  wrong results.
- When unsure, keep the default. A smaller quantum is always correct, only slower.
- A scenario that declares any medium runs at 10 us (BLE and 802.15.4 need it) unless it sets
  `quantum:`. Every machine pays a fixed cost per quantum, so that is 10x the work of the 100 us
  default, with or without traffic: two Teensy 4.1 on Ethernet cost 255 G host instructions for 2 s
  of virtual time at 10 us and 92 G at `quantum: 0.0001`, the same as the boards run alone. The run
  prints "cpu by machine, quantum N us" at the end; a total far above the machines run alone is this.
- If a quantum change alters a result, the larger value was too large.

## 6. See what firmware is doing without halting it

| Question | Flag |
| --- | --- |
| Is it running at all? | `--progress` prints virtual time, instructions, PC and the last peripheral touched every 2 s of wall time, and says STALL when nothing advanced |
| Did it reach a function, and with what arguments? | `--trace-symbol <name\|0xADDR>` (r0-r3 and virtual time, on every hit) |
| Which interrupts fire, when? | `--trace-interrupts` |
| Who touches this variable or register? | `--trace-memory <sym\|0xADDR[:len]>` |
| Was an update lost across thread/interrupt or interrupt contexts? | `--race <sym\|0xADDR[:len]>`; RTOS threads share one context, so this does not detect races between them |
| Does the bug depend on interrupt timing? | `--irq-jitter 2us --seed 7` (same seed, same run) |

Function traces and interrupt/memory traces go to standard output. With
`--output uart.txt`, UART goes to that file and you can capture the trace separately:

```sh
sim STM32F401RE run --elf fw.elf --timeout 1 --ascii --output uart.txt \
  --trace-symbol main > calls.txt
```

`--trace-out edges.jsonl` records GPIO pad edges. It is not a combined event log
or a function-call trace. Use `--record` for a directory of structured evidence.

`--gdb <port>` serves a GDB stub, halted at reset. Use it only on a single machine and not for timing-dependent
work: a halt changes the run.

## 7. Keep the evidence

```sh
sim STM32H753II run --elf fw.elf --timeout 3 --record out/
grep -h '"kind":"fault"' out/fault.jsonl | head
sim trail claim out/ --type hypothesis "The worker is waiting for a transfer-complete interrupt"
```

`sim trail claim <dir> --type <hypothesis|action|finding|conclusion> [--cite <seq>]... <text>` appends to
`trail.jsonl`. `--cite` takes the `seq` of the record that shows it; a finding or conclusion with no
`--cite` is recorded as uncorroborated.

`--record <dir>` writes the run's UART lines, GPIO edges, interrupts, faults, context switches, frames and
usage as JSONL, plus `runs.jsonl` describing the run. Read `runs.jsonl` first: its `not_recorded` field names
streams that were not watched. `sim docs show record` has the file-by-file table and recipes.
A finding must cite sequence numbers you actually inspected; do not copy a sequence number
from an example or treat a missing record as proof that an unwatched event never happened.

## Debugging with evidence

Start with a specific expected result and an observation that contradicts it.
A boot banner or a successful simulator exit does not establish that the firmware works.
The firmware, chip model, peer script, and test setup are all possible sources of a failure.

1. **Check the setup.** Record `sim version`, the target, ELF hash, board/scenario files,
   and inputs. Run `sim <MCU> check --elf fw.elf --board device.board` when a board is present.
   Read warnings and model status before calling a hang a firmware bug.
2. **Record a short baseline.** Use `--record` and keep the original firmware unchanged.
   Inspect `runs.jsonl`, including `not_recorded`, then UART, faults, and the scheduler timeline.
3. **Choose the next observation.** Trace a function if the question is whether it was
   reached; watch memory if the question is who changed a value. Use the table below.
4. **State and test a hypothesis.** Change one cause or input, then repeat the same result
   check. Compare the original and changed runs. A longer timeout alone does not explain a hang.
5. **Check the explanation.** Function entry does not prove return, lock ownership, or
   successful completion. Combine traces with source and the firmware's completion condition.
   A simulator mismatch can require a model or testbench fix rather than a firmware change.
6. **Keep a regression and its negative control.** Make the fixed run pass an explicit check
   and verify that the deliberately broken run fails it. Cite the records behind the conclusion.

| Question | Next observation | What it does not establish |
| --- | --- | --- |
| Did startup reach the expected function? | `--trace-symbol` with an unstripped ELF | That the function returned successfully |
| Are workers running or blocked? | `switch.jsonl` and `usage.jsonl` from `--record` | Which mutex each owns without additional evidence |
| Is an interrupt arriving? | `--trace-interrupts`, or recorded `isr.jsonl` | That the handler consumed the right data; CPU-raised faults are in `fault.jsonl` |
| Who changes a flag or buffer? | `--trace-memory` on its ELF symbol or address | All other memory accesses or every possible schedule |
| Did the simulated pin change? | `--trace-out` or recorded `gpio.jsonl` | Voltage, signal integrity, or electrical timing on a physical board |
| Did firmware fault? | stderr and recorded `fault.jsonl` | That firmware rather than a missing or incorrect model caused it |

Prefer non-halting observations for timing-sensitive failures. A breakpoint changes the
execution being investigated. For a source-level logic question, use `--gdb` deliberately
and keep that experiment separate from the non-halting baseline.

The [STM32 deadlock walkthrough](/stm32-simulator#3-trace-the-calls-that-explain-the-hang)
applies this procedure to a failing and fixed Zephyr program with published traces.

## 8. Reproducible and fast

- Two runs of the same ELF, board and flags print byte-identical output. A difference means a host-reaching
  key (section 5), `--real-time`, or a peer script that reads the clock or random numbers.
- The jit block tier is on by default; `--no-jit` (or `PYRITE_JIT=0`) runs the plain interpreter, the reference.
  If the two disagree, that is a sim bug: report it with `--record` from both.

## 9. Know the limits

- A model is evidence for the silicon revision it was checked on, not for the whole part family. Check the
  chip's status with `sim models` and the board file's header for its assumptions.
- A part with no model is skipped with a `skipped model:` line, and firmware that waits on it will wait.
  Check the model status before you read a hang as a firmware bug.
