> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# XMOS xsim

> Run an XMOS application in the xsim simulator, check its output, trace instructions, drive pins, and run test cases in parallel.

Use xsim to run an XMOS `.xe` application without an xTAG or a physical board. Results describe the simulated target. They don't establish real-board electrical behavior or hardware timing.

After [setup](#set-up-the-simulator), you can:

* Run the application and check its console output. See [Run and check output](#run-and-check-output).
* See which instructions ran and which functions ran most. See [Record an instruction trace](#record-an-instruction-trace).
* Watch pins change and force their levels. See [Watch and drive pins](#watch-and-drive-pins).
* Read or patch target memory. See [Read and write simulated memory](#read-and-write-simulated-memory).
* Run a test gate of many independent cases at once. See [Run test cases in parallel](#run-test-cases-in-parallel).
* Set breakpoints and step. See [XMOS debugging](/docs/debug-mode/xmos-debugging.md), with the simulator as the target.

## Set up the simulator

1. Install XMOS XTC Tools and build your `.xe`. Simulated runs need `xsim`. Simulator debugging also uses `xgdbserver` and `xgdb`.
2. Make sure Inlay can find XTC Tools. It checks your `PATH`, `XMOS_TOOL_PATH`, and the standard install folder. For any other location, set `INLAY_XTC_PATH` to the XTC root or its `bin` folder in the environment that launches Inlay. See [Where Inlay finds XTC Tools](/docs/debug-mode/xmos-debugging.md#where-inlay-finds-xtc-tools).
3. Select the simulator in `.inlay/xmos.json`:

   ```json .inlay/xmos.json theme={"theme":"css-variables"}
   {
     "xe": "bin/app.xe",
     "target": "simulator"
   }
   ```

   Replace `bin/app.xe` with your project-relative `.xe` path.
4. Ask Inlay to check simulator readiness before you start. The simulator is ready only when Inlay finds both `xsim` and its own xsim plugin, which is built into Inlay. Finding XTC Tools alone isn't enough.

### Project settings

These keys in `.inlay/xmos.json` control simulated runs:

| Key | Default | Effect |
| - | - | - |
| `xe` | Newest `.xe` | The `.xe` to run, relative to the project. If it's unset or the file doesn't exist, Inlay uses the newest `.xe` in the project. |
| `target` | None | `simulator` uses xsim even when an xTAG is attached. |
| `xscope` | `"auto"` | `true` starts a realtime xSCOPE server. `false` turns xSCOPE off. `"auto"` uses offline xSCOPE in the simulator. |
| `sim.args` | `[]` | Extra xsim arguments for every simulated run. |
| `sim.pins` | `[]` | Pins to sample for the **Sim IO** tab. |
| `sim.sampleMhz` | `25` | Pin sampling rate, in MHz. |
| `sim.vcd` | `false` | Also writes `ports.vcd` for `tile[0]`. |
| `sim.jobs` | Automatic | Parallel runs for a test batch, from 1 to 64. See [Set the number of parallel runs](#set-the-number-of-parallel-runs). |

If the file has an unknown key or an invalid value, such as `sim.jobs` above 64, Inlay ignores the whole file and uses the defaults.

Don't put paths that contain spaces in `sim.args`. When you [debug under the simulator](/docs/debug-mode/xmos-debugging.md), such a path doesn't reach xsim intact, and Inlay drops `--max-cycles` because the debugger never stops on it.

## Run and check output

Ask Inlay to run the application and wait for a message your firmware prints:

```text theme={"theme":"css-variables"}
Run bin/app.xe in xsim, using the simulator selection in .inlay/xmos.json.
Wait up to 10 seconds for BOOT_OK, show the console output, and stop the
simulation. Do not use the connected physical board.
```

Replace `BOOT_OK` with a message your firmware emits. For a repeatable check, save a [hardware script](/docs/debug-mode/hardware-scripts.md) such as `.inlay/hardware/sim_boot.py`:

```python .inlay/hardware/sim_boot.py theme={"theme":"css-variables"}
xsim.start(xe="bin/app.xe")
xsim.wait_for_output(text="BOOT_OK", timeout_seconds=10)
print(xsim.console_log(max_chars=4000))
xsim.stop()
```

Ask Inlay to run it, or run `inlay script sim_boot.py` from the project directory. If the message doesn't appear in time, the script raises `TimeoutError` with `xsim console did not emit expected output`. Check the console and the simulator state before you assume a firmware defect.

With the default `"xscope": "auto"`, the simulator starts with offline xSCOPE, which needs an image built with `-fxscope`. For a plain image, call `xsim.start(xe="bin/app.xe", xscope=False)`, or set `"xscope": false` in `.inlay/xmos.json`.

Scripts can use these helpers:

| Helper | What it does |
| - | - |
| `xsim.start(xe=None, args=None, start_paused=False, xscope=None, timeout_seconds=30)` | Starts the simulation. A running simulation with exactly the same image and settings is reused; otherwise Inlay stops it and starts a new one. `args`, `pins`, `sample_mhz`, and `vcd` override the matching `sim.*` settings for this run. |
| `xsim.wait_for_output(text=None, pattern=None, timeout_seconds=15)` | Waits for console text or a regular expression. It also matches output printed before the call. |
| `xsim.console_log(max_chars=None)` | Returns the most recent console output, up to the last 64 KiB. |
| `xsim.suspend()`, `xsim.resume()` | Pauses and resumes the simulation. |
| `xsim.restart(xe=None)` | Reloads the simulation, optionally with another `.xe`. |
| `xsim.status()` | Reports the simulation state. |
| `xsim.stop()` | Stops the simulation. |

When the script ends, Inlay stops a simulation that the script started. It doesn't stop a simulation the script reused.

After a simulation ends, its full console log is in `.inlay/artifacts/xsim/<session>/`, with `ports.vcd` when `sim.vcd` is on and `xscope.xmt` from offline xSCOPE.

A Serial Monitor tab can also show the simulated application's output. Choose the **XMOS xsim (simulator)** port; see [xSCOPE](/docs/debug-mode/xscope.md).

For breakpoints, stepping, tiles, registers, or stack frames, use [XMOS debugging](/docs/debug-mode/xmos-debugging.md) with `simulator=True`. Starting a debugger replaces a standalone simulation that's already running. While the debugger owns the simulator, `xsim.start()` fails until you stop the debug session. To find where a workload spends its time, see [Profile a session](/docs/supported-hardware/xmos.md#profile-a-session).

## Record an instruction trace

An instruction trace records every retired instruction with its tile, logical core, PC, symbol, and tile-clock cycle. xsim names the symbols from the `.xe`, so you don't need a separate ELF.

Start the trace before the simulation. If a simulation is already running without tracing, the trace fails with `the running simulation was started without instruction tracing`. Stop that simulation and start the trace first.

The trace starts the simulator with offline xSCOPE, so build the image with `-fxscope`. Without it, the run can fail with `Unable to find __sodFlag`. Add `-g` when you want source-line results.

### From the Trace tab

1. Run **Inlay: Open Inlay Monitor**, select **+**, and choose **Trace**.
2. Open the source settings at the left of the Trace toolbar. In **Source**, choose the entry that ends in **XMOS xsim (simulator)**.
3. Open the capture settings next to it, which show **xSCOPE records**, and set **Capture** to **Instruction trace**.
4. Optional: change **Keep**, the number of recent instructions to keep. The default is 1,000,000.
5. Select **Record**. Select **Stop** when the interval you need is complete.

The trace uses the `.xe` selected in a Serial Monitor tab's **App (.xe)** or set as `xe` in `.inlay/xmos.json`. The result opens in the **Instructions** view, and you can watch it fill while it records.

### From chat or a script

```text theme={"theme":"css-variables"}
Record an xsim instruction trace for bin/app.xe. Retain the latest 100000
instructions, stop after a short boot run, and summarize the active tiles,
logical cores, and functions. Show the result in the Trace tab.
```

In a hardware script, call `xsim.trace_start()` and `xsim.trace_stop()`. See [Analyze the capture from Python](#analyze-the-capture-from-python).

### Limits

* The instruction limit is a rolling window across all tiles and cores. Older instructions are dropped as newer ones arrive. Execution doesn't stop at the limit.
* A recording stops on its own after 10 minutes of wall-clock time.
* Boot-ROM instructions aren't traced. In a script, pass `rom=True` to `xsim.trace_start()` to include them.
* Stopping a trace also stops a simulation that the trace started. A simulation that was already running keeps running.

Cycle values count the simulated tile clock. Convert them to time only with that tile's simulated clock frequency. They aren't host time or a measurement of a physical board.

## Analyze the capture from Python

`xsim.trace_start()` returns a session ID. A [hardware script](/docs/debug-mode/hardware-scripts.md) can query that session while it records or after `xsim.trace_stop()`:

```python .inlay/hardware/trace_bench.py theme={"theme":"css-variables"}
session = xsim.trace_start(max_instructions=200_000)
xsim.wait_for_output("BENCH_DONE", timeout_seconds=30)
xsim.trace_stop()

print(xsim.trace_summary(session))
page = xsim.trace_instructions(session, tile=0, after_index=-1, limit=1000)
print(xsim.trace_hotspots(session, group_by="line", tile=0, limit=50))
```

| Query | Returns |
| - | - |
| `xsim.trace_summary(session)` | Instruction counts and cycle span for each tile and logical core. |
| `xsim.trace_instructions(session, after_index=None, limit=1000)` | One page of retained instructions, oldest first. `limit` can be up to 10,000. |
| `xsim.trace_hotspots(session, group_by="function", limit=50)` | The most-executed functions, source lines (`"line"`), or addresses (`"address"`). `limit` can be up to 10,000. |

All three accept these filters:

* `tile` and `core` limit the result to one tile or logical core.
* `start_cycle` and `end_cycle` limit it to a cycle range, including the start and excluding the end. A cycle range needs `tile`, because each tile has its own clock.

To page through instructions, pass the returned `next_after_index` as `after_index` in the next call. Pages stay stable while the window rolls. If `cursor_evicted` is true, the instructions you asked for have already left the window. `window_truncated` means the trace holds only the tail of the run.

Hotspots count retained instructions. Instructions without a function or source line are counted separately as `unresolved_count`, so the total doesn't change silently.

Each new trace keeps its own copy of the `.xe`, so line-level hotspots still resolve after you rebuild. A trace that joined a simulation that was already running, or a trace from an earlier Inlay version, can't resolve source lines and reports that.

## Watch and drive pins

Use the **Sim IO** tab to watch simulated pins change and to force their levels while the simulation runs.

1. Run **Inlay: Open Inlay Monitor**, select **+**, and choose **Sim IO**.
2. Start a simulation. Until one runs, the tab shows **Start an xsim simulation to see GPIO activity.**
3. Search for pins, pick the ones you want, and select **Show *N* lanes** to add them.
4. Use **H**, **L**, and **R** on a lane to force the pin high, force it low, or release it.

To sample the same pins every time, list them in `sim.pins` in `.inlay/xmos.json`.

From a hardware script, use these helpers:

| Helper | What it does |
| - | - |
| `xsim.pins(pattern=None)` | Lists the simulated pins, optionally filtered. |
| `xsim.sample_pin(pin)` | Reads a pin's current level. |
| `xsim.force_pin(pin, high=True)` | Forces a pin high or low. |
| `xsim.release_pin(pin)` | Releases a forced pin. |

## Read and write simulated memory

Scripts can read and write target memory with `xsim.read_memory(tile, address, length)` and `xsim.write_memory(tile, address, data)`.

xsim fills memory that nothing has written with `0xBADDF00D`. The program image doesn't load until the simulation runs, so before that, the whole program area reads as this fill.

* `xsim.read_memory` warns when it reads the fill.
* `xsim.write_memory` refuses to write there, because loading the image would overwrite the write.

To write program memory, do one of the following:

* Resume the simulation first, for example with `xsim.resume()` and then `xsim.wait_for_output()`.
* Write at a debugger breakpoint.
* Patch the image with `write_memory` in [`xsim.run_batch`](#run-test-cases-in-parallel).

If the program is already running and hasn't used that memory yet, pass `force=True`.

## Run test cases in parallel

Use `xsim.run_batch` from a [hardware script](/docs/debug-mode/hardware-scripts.md) for a test gate with independent cases, such as one run per stimulus, vector set, parameter set, or seed. Inlay starts a separate xsim for each run, runs several at once, and waits for all of them. One failing case doesn't stop the others.

To debug a failing case with breakpoints or traces, reproduce it on its own with `xsim.start()` or [XMOS debugging](/docs/debug-mode/xmos-debugging.md).

A batch runs alongside the simulation that `xsim.start()` manages. It doesn't use or disturb that simulation, the **Sim IO** tab, or the **Trace** tab. Stopping the script cancels the batch.

```python .inlay/hardware/limiter_gate.py theme={"theme":"css-variables"}
import os

cases = ["silence", "impulse", "tone_1k_m20", "tone_1k_m3"]
runs = [
    {
        "name": name,
        "files": {"stim.raw": f"tests/stimuli/{name}.raw"},
        "args": ["stim.raw"],
    }
    for name in cases
]

batch = xsim.run_batch(
    runs=runs,
    xe="bin/test/app_limiter_test.xe",
    name="limiter",
    done_pattern=r"TEST DONE",
    fail_pattern=r"TEST FAIL",
    read_memory=[{"symbol": "capture", "length": 4 * 4800, "save_as": "capture.bin"}],
    timeout_seconds=600,
)
print(batch["jobs"], batch["jobs_reason"], batch["counts"])

for run in batch["runs"]:
    print(run["name"], run["status"], run["ended_by"], f"{run['duration_s']:.0f} s")
    if run["status"] == "passed":
        with open(os.path.join(run["dir"], "capture.bin"), "rb") as f:
            capture = f.read()  # compare with your reference model
    else:
        print(run["console_tail"][-400:])
```

Each run is a dict with a `name` that's unique in the batch, ignoring case. Names use letters, digits, `.`, `_`, and `-`, start with a letter or digit, and are up to 80 characters long. A batch can hold up to 1,000 runs. The batch's own `name` follows the same rules, up to 40 characters.

Keyword options apply to every run that doesn't set them. `defaults=` sets the same options as a dict. A run can also set its own `xe`.

| Option | Effect |
| - | - |
| `args` | Program arguments, passed with `xsim --args`. Build the image with `-fcmdline-buffer-bytes=N`, for example `256`. Otherwise `argc` is 0. |
| `files` | `{"name": "project/path"}` copies project files into the run directory. The firmware's `fopen` resolves relative paths against the run directory, so files the firmware writes stay with the run. |
| `sim_args`, `max_cycles` | Extra xsim arguments, applied after `sim.args`, and a cycle limit. |
| `timeout_seconds` | Wall-clock limit for each run. The default is 1800 seconds. |
| `done_pattern`, `fail_pattern` | Console regular expressions that end the run as passed or failed. |
| `done_memory` | `{"symbol": "test_done", "nonzero": True}` or `"equals": n`, with optional `tile`, `offset`, and `poll_ms` (default `1000`). Use `address` instead of `symbol` for a raw address. |
| `write_memory` | `[{"symbol": "stim", "file": "path"}]` or `"data": [...]`, with optional `tile` and `offset`. Each run's program starts with the data already in place; your `.xe` isn't changed. |
| `read_memory` | `[{"symbol": "capture", "length": n, "save_as": "capture.bin"}]`, with optional `tile` and `offset`. Needs `done_pattern` or `done_memory`. Inlay saves the bytes in the run directory after the done condition matches. Each read is limited to 1 MiB. |
| `xscope` | `"off"`, `"offline"` (writes `xscope.xmt`), or `"realtime"` (writes probe records and prints to `xscope.jsonl`). Needs an image built with `-fxscope`. |
| `uploads` | Host-to-target data for `xscope_data_from_host`, as `[{"file": "path"}]` or `"data": [...]`, with `delay_ms`. Needs `xscope="realtime"`. |
| `pins`, `force_pins`, `sample_mhz`, `vcd` | Sample package pins into `pins.jsonl`, force levels such as `{"X0D49": "high"}`, set the sampling rate (up to 600 MHz), and write `ports.vcd`. |

Startup zeroes `.bss`, so Inlay refuses a `write_memory` target there and reports the run as `error`. Give the variable an initializer, such as `int32_t stim[N] = {1};`, to place it in `.data`.

### How a run ends

Each run reports a `status` of `passed`, `failed`, `max_cycles`, `timeout`, `cancelled`, or `error`. `ended_by` names the condition that ended it:

* **Exit code:** a single-tile C `main` return value becomes the xsim exit code. `0` is `passed`. Any other value is `failed`.
* **`done_pattern` or `done_memory`:** the run is `passed`. Multi-tile and RTOS images can't call `exit()`, so end them this way. Keep the program running after the marker, for example in an idle loop, so `read_memory` can read the buffer.
* **`fail_pattern`:** the run is `failed`.
* **`max_cycles` or `timeout_seconds`:** the run reports `max_cycles` or `timeout`.

When `done_pattern` or `done_memory` is set, a run that exits before the condition matches is `failed`, and Inlay skips its `read_memory`. If the program exits after the done condition matches but before Inlay reads memory, the run reports `error`. Keep the program running after the marker.

`passed` means the run ended as specified, not that its output is correct. Compare each run's output with your reference.

`keep_going=False` cancels the remaining runs after the first one that doesn't pass. `check=True` raises `RuntimeError` if any run didn't pass.

Each run writes its files to `.inlay/artifacts/xsim-batch/<batch>/<name>/`, returned as `dir`. The directory holds the staged files, `console.log`, `result.json`, memory dumps, and any xSCOPE, pin, or VCD output. The batch result includes `batch_id`, `batch_dir`, `jobs`, `jobs_reason`, `all_passed`, `counts`, `duration_s`, and `runs`.

### Set the number of parallel runs

By default, Inlay runs one fewer job than the number of performance cores on Apple silicon, or one fewer than the available CPUs elsewhere. Free memory also caps that count. The count never exceeds the number of runs.

To override it, use one of these, in order of precedence. Each accepts 1 to 64:

1. `jobs=` on `xsim.run_batch`.
2. `sim.jobs` in `.inlay/xmos.json`:

```json .inlay/xmos.json theme={"theme":"css-variables"}
{
  "xe": "bin/app.xe",
  "target": "simulator",
  "sim": { "jobs": 4 }
}
```

`jobs_reason` in the result reports which setting applied.

### Keep cases short

xsim runs hundreds of times slower than real time, so one simulated second can take many minutes. Each run also slows down when several run at once. Time one short run of your image first, then set `timeout_seconds` from that estimate with margin.

Split a gate into many short cases instead of one long one. Give each case the shortest stimulus that proves it, and get coverage from more cases that run in parallel.

Ask Inlay to run batch scripts in the background. A foreground hardware-script run stops after 60 seconds by default, and Inlay can raise that to at most 10 minutes. The time limit doesn't apply to a background run. From a terminal, `inlay script` accepts `--timeout <ms>` for a longer limit.

## Troubleshoot

* **No `.xe` found:** build the project and correct `xe` in `.inlay/xmos.json`.
* **`xsim not found`:** install XMOS XTC Tools, or point `INLAY_XTC_PATH` or `XMOS_TOOL_PATH` at the installation.
* **`the Inlay xsim plugin is not available for this platform`:** the plugin is part of Inlay, not XTC Tools, and this copy of Inlay has no plugin or couldn't unpack it. Update Inlay, then ask it to check simulator readiness again.
* **`… path contains whitespace`:** xsim can't take file paths with spaces, and Inlay keeps the simulator's working files under your user folder. This affects user folders whose names contain a space. Set `INLAY_APP_DIR` to a folder whose path has no spaces, in the environment that starts Inlay, then start it again.
* **`the simulator is owned by the debugger session`:** stop the XMOS debug session before you start a standalone simulation.
* **The output wait times out:** check the console, whether the simulation is paused or running, and the expected message. Increase the wait only when the firmware needs longer.
* **`Unable to find __sodFlag`:** the image wasn't built with `-fxscope`. Rebuild with it, or start a plain image with `xscope=False`.
* **`the running simulation was started without instruction tracing`:** stop the running simulation and start the trace before the next run.
* **The beginning of the trace is missing:** record a shorter interval or raise the instruction limit.
* **`xsim.write_memory refused`:** the image isn't loaded yet. See [Read and write simulated memory](#read-and-write-simulated-memory).
* **A simulation exits at its cycle limit:** check the extra simulator arguments. A standalone run with `--max-cycles` exits when it reaches the limit, which proves only that the limit was reached.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.