Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Skip to content
BoardRunner

FastDyn

Firmware execution you can shape

FastDyn brings firmware execution, peripheral behavior, runtime instrumentation, and physical simulation into one configurable experiment. Load a firmware image, describe its machine and environment, and decide where to observe or intervene. The same framework can change a function argument, inspect an RTOS, replay peripheral interactions, connect a controller to a vehicle model, or drive a fuzzing campaign.

The execution engine combines a patched QEMU with a native FastDyn plugin. A Python frontend prepares the experiment from TOML or a public API. Host analysis resolves information before execution; runtime plugins and device models supply behavior while the guest runs. The result is a reusable place to investigate embedded software without rebuilding an entire physical test setup for each question.

Start with your first experiment, or use Choose a workflow to find the right entry point.

What makes FastDyn useful

Shape execution at the point that matters

A modifier can change a register or memory value at a chosen guest program counter. A virtual instruction can invoke a named native behavior there. These rules live alongside the experiment configuration, so the minimal example changes the argument received by a real firmware function while preserving the firmware image and its original addresses.

This is useful for supplying missing platform behavior, skipping a known initialization dependency, injecting a fault, collecting evidence, or making a narrow experiment repeatable. The instrumentation chapter explains the different costs and contracts of virtuals, modifiers, and the existing inline-I/O path.

Give each device the environment it needs

Use a compiled C model for a peripheral, connect an access to a physical board through a debug probe, or replay an interaction trace. A permissive stub helps bring up an early experiment; an explicit model provides the state and side effects needed for meaningful execution. These options share FastDyn's device-dispatch infrastructure, allowing the model boundary to evolve as the experiment matures.

Device models explains the available mechanisms. Writing a model walks through the ABI and model build workflow.

Move beyond boot success

Function counts, argument traces, variable observations, RTOS activity, object-bound checks, MMIO observations, and coverage expose what the firmware actually does. Host preprocessors can install instrumentation across an image rather than requiring a long manual list of addresses.

The shared host-analysis API supplies reusable image, symbol, DWARF, decoding, and RTOS facts. Individual plugins retain the policy that decides what to instrument.

Close the loop with physics

FastDyn can execute controller firmware against a physical model and feed the resulting sensor values back to the controller. Its FMI 3 path loads the FMU into the execution process; the core plant does not require a separate simulator process. Vehicle profiles, mission helpers, telemetry, and optional viewers turn that capability into practical experiments.

Read Physics and FMUs, then Flight controllers. The branch previews cover newer INAV and PX4 work with the exact revisions and evidence levels that apply to each.

Scale experiments and grow the framework

Use fastdyn swarm for independent workers, and FastDyn as a secondary simulator when an external controller grants guest execution time. Add explicit communication and plant coupling when the experiment contains interacting firmware instances. Multiple firmwares explains these arrangements. The Tempo chapter covers the companion scheduler's implemented federation compiler, typed routing, and mock-participant examples.

Extensions can use the Python run API, a preparation plugin, a native runtime plugin, a peripheral model, or a physics adapter. The system model helps choose the smallest appropriate extension point.

Optimize captured native code

Supercache retains native translations across runs. The Supercache optimizer, implemented on the separately pinned scopt branch, imports captured translations and metadata for offline optimization. Its workflows include profile-guided layout, cross-block transformations, state-synchronization reduction, and checked native helper inlining. The chapter explains the matching runtime, pass-specific requirements, artifact validation, and reproducible fixture path.

Optimize firmware with explicit contracts

FirmBOLT works on the firmware ELF through an extended BOLT pipeline. Its firmbolt branch includes a direct Cortex-M/Thumb backend, typed reference handling, instruction origins, and checks that keep the default Cortex-M output within the firmware's existing memory layout. The chapter explains the optimization passes, strict and relaxed timing contracts, qualification commands, and the evidence needed before using a changed image in an experiment.

A small first taste

After installation, run this from the FastDyn source checkout:

fastdyn -q run -c configs/minimal.toml -o out/first-run

The bundled configuration changes a function argument to 3, prints the observed register value, and ends the run at the scheduler entry. It provides a short, concrete check of the entire path from configuration to guest execution. The tutorial shows how to change the argument again and inspect the generated rules.

How to read this book

Your goalStart here
Run a firmware experimentInstallation, first run, configuration
Understand the machinerySystem model, execution pipeline
Observe or modify behaviorVirtuals and modifiers, introspection, tracing and sanitizers
Supply hardware behaviorDevice models, hardware and traces
Run a controller against a plantPhysics and FMUs, flight controllers
Build an analysis or downstream toolPython API, virtual plugins, host analysis
Work with advanced execution mechanismsSupercache, inline device modeling, experimental automatic MMIO, JIT patcher, hot-path optimizations
Optimize saved native translationsSupercache optimizer
Optimize the firmware ELFFirmBOLT
Control simulation progress and study coordinationFastDyn as a secondary simulator, Tempo

Contact

For questions about FastDyn, feedback on this book, or collaboration, contact Arslan Khan at arslankhan@psu.edu.

To contribute documentation, see the contribution guide.

Revision and evidence

This edition was refreshed on 18 November 2026, adding the Supercache optimizer at FastDyn scopt revision 124699d with QEMU 934890e, and FirmBOLT at firmbolt revision b14f14c. Core chapters retain the FastDyn baseline f9666d7. The JIT patcher and manual inline lab are pinned to 5b8bf3d. Automatic MMIO, hot-path optimizations, and the secondary-simulator workflow are reviewed at main e44dca2. The Tempo chapter records the implemented scheduler and compiler at its separate source revision. The Supercache optimizer records its branch implementation and matching runtime; the cache-reuse chapter retains its own frontend/backend recipe. FirmBOLT records its extended BOLT implementation and firmware acceptance path separately. Each source guide records its implementation evidence; reviewing one feature at a newer revision does not revalidate every older chapter. The book covers implemented capabilities and their current limits.

The book was checked against source, configuration examples, and test programs. It is not a new measurement campaign. See the capability status and testing guide for the scope of an experiment and the evidence to retain.

FastDyn itself is distributed under Apache-2.0; bundled firmware and dependencies retain their own licenses. See the source repository's LICENSE and NOTICE.

Source guide

Choose a workflow

A productive FastDyn experiment starts with a question that has a visible result. Booting a new image, measuring a function, validating a sensor interaction, and testing a controller against a plant require different amounts of environment modeling. Start with the smallest setup that answers the question, then add fidelity where it changes the result.

Find your starting point

QuestionStarting pointObservable result
Can I run FastDyn and change guest state?configs/minimal.tomlChanged argument printed by the firmware hook; automatic termination
Which functions execute?configs/function_counter.tomlFunction-entry counts written on shutdown
What arguments reach selected functions?configs/function_tracer.tomlSelected entry arguments and decoded values
Which RTOS tasks run?configs/introspection/freertos.tomlTask/activity records and configured monitor
Does a memory object stay within its modeled bounds?ObjectSan example configurationsReports at instrumented candidate accesses
How should an unmapped peripheral respond?An Elder C modelExplicit register and device-state behavior
Can I compare against a real peripheral?Passthrough or twintraceProbe-backed interactions or a replay record
Does a controller behave correctly in a scenario?An appropriate flight-controller/FMU configurationSensor/controller/actuator progress and a scenario outcome
How do I repeat many independent trials?fastdyn loop or fastdyn swarmSeparate trial or worker artifacts
How do I optimize a saved native translation cache?Supercache optimizer on its pinned scopt branchA validated candidate artifact or an explicit rejection, followed by workload-specific comparison
How do I optimize the firmware ELF itself?FirmBOLT on its pinned firmbolt branchAn image produced by the extended BOLT pipeline, with checked layout, reference, origin, and observation contracts
Can an external controller pace firmware execution?FastDyn as a secondary simulatorQMP time grants, observed stops, and reported guest time
How do I synchronize several firmware instances?Multiple firmwares and the lockstep utilityGuests paused at common time boundaries; connections are experiment-specific
How does typed routing and scheduling work in Tempo?Tempo's mock federationCompiled connections, participant progress, routed values, and trace records

The configuration examples are entry points, not interchangeable board descriptions. Their addresses, firmware images, register conventions, and optional dependencies belong to the named experiment.

New to FastDyn

Install the native build, run the first experiment, and inspect the generated virtuals.txt and modifiers.txt. Change one modifier, repeat the run, and check the observed value. This short loop teaches the operating model before adding device synthesis, a physical board, or physics.

Next, run an introspection or function-counting configuration. These examples demonstrate the second important pattern: a host preprocessor derives many runtime hooks from one small plugin table. You can read the resulting artifacts to understand exactly what was installed.

Bringing your own firmware

Prefer an ELF with symbols and, for layout-dependent analyses, DWARF. A raw image can still be executed when you know its load map and architecture, but missing metadata changes what the preparation stage can resolve automatically.

The ELF configuration generator is a useful first pass:

./fastdyn-env/bin/python tools/elf2config/elf_to_config.py firmware.elf   --output configs/my_firmware.toml

This command belongs to the FastDyn source checkout and assumes firmware.elf is your input. Review the generated CPU, memory, vector-table, and platform assumptions before running it. The tool's legacy generated QEMU path may point at a sibling checkout; use the executable built for your installation as described in installation.

An ELF supplies facts about an image. It does not fully describe the physical board, peripheral state machines, startup side effects, or available RAM. Treat inferred defaults as decisions to review. Configuration explains the fields and their path-resolution rules.

Choosing where to intervene

Use a modifier for an operation expressible by the current register/memory rule language. Use a virtual callback when the intervention needs native behavior, such as reading a model or recording a structured event. Use a device model when the firmware should exercise a peripheral interface repeatedly with meaningful state and side effects.

Use a run preprocessor when hook selection depends on the firmware. It can resolve symbols, inspect layouts, or select a family of sites once, then serialize a runtime plan. Use the Python run API when building an experiment driver or another tool around FastDyn. These choices can be combined; each addresses a different boundary.

For controller experiments, choose a sensor boundary intentionally. Injecting at a high-level sensor publication exercises the downstream controller but bypasses the physical device driver. Modeling SPI or I2C transactions exercises more of the driver path and requires more peripheral detail. Record that choice alongside the scenario.

Define completion before launching

Choose a termination event, a maximum run budget where the workflow provides one, and a result to inspect. Examples include reaching a function, writing a final counter file, satisfying a mission condition, or reporting a replay mismatch. A console that keeps running is not by itself evidence of correct execution.

For every new target, retain the firmware digest, configuration, generated hooks, model versions, and observed result. This makes the next run a comparison rather than a reconstruction of the setup.

Source guide

Install FastDyn

The shortest path to the bundled firmware example is a Linux source build of FastDyn and its patched QEMU. Add physical-board access, device-model libraries, or Modelica compilation when your experiment needs them. The documented host baseline is Ubuntu 24.04; the repository also provides a Docker image with a broader Gazebo and fuzzing stack.

These instructions use the FastDyn repository root as the working directory. The core tutorials describe commit f9666d7f518c373e89831d8e14a6371a27fe6436. Advanced chapters identify newer or separate runtime revisions: follow the checkout instructions in JIT patcher, inline device modeling, experimental automatic MMIO, hot-path optimizations, or Supercache when using those workflows.

Build the basic runtime

Clone the repository:

git clone https://github.com/boardrunner2049/FastDyn.git
cd FastDyn
git checkout --detach f9666d7f518c373e89831d8e14a6371a27fe6436

The detached checkout pins the snapshot used by these core tutorials. When working on a newer branch, consult that revision's documentation for changes to the examples and build inputs. In particular, main e44dca2 expects five ordered QEMU patches (icount, fragments, MMIO, MMIO saved-PC, constant-PC chaining), while this historical core tutorial predates those extra interfaces.

Install the Ubuntu build dependencies:

sudo apt-get update
sudo apt-get install -y \
  build-essential cmake git meson ninja-build pkg-config python3-venv \
  libglib2.0-dev libcjson-dev libpixman-1-dev libfdt-dev zlib1g-dev flex bison

Build the runtime and activate its Python environment:

source ./setup.sh --build-qemu --skip-optifuzz

This creates fastdyn-env/, installs the Python requirements and editable FastDyn package, initializes the required submodules, applies FastDyn's compatibility patch to its QEMU fork, and builds build/libfastdyn.so. The resulting plugin includes device models, the physics engine, FMI v3 support, and flight-controller adapters. --skip-optifuzz omits the Banquo dependency checkout used by the mission-level fuzzer; it does not remove the firmware runtime.

The default setup builds qemu-system-arm with the arm-softmmu target. FastDyn also contains RISC-V and x86 configuration presets, but this command does not build their QEMU executables. Those targets need a compatible patched QEMU build for their architecture. Architecture support for individual plugins must also be checked separately.

Verify the installed entry point, then run the first experiment:

fastdyn --help
fastdyn run --help
fastdyn -q run -c configs/minimal.toml -o out/first-run

In a new shell, activate the existing environment instead of repeating setup:

source fastdyn-env/bin/activate

Add capabilities as needed

CapabilitySetupWhat it provides
Physical board accessInstall libstlink-dev libusb-1.0-0-dev, then use --build-libhw together with --build-qemuHardware access through libhw for passthrough and trace recording
LibVIO device modelssource ./setup.sh --build-libvio --skip-optifuzzLibVIO installed under out/libvio/install, automatically found by build-model
Modelica and FMI v3 campaignssource ./setup.sh --build-qemu --with-rumocaPinned Rumoca and model sources, FMU generation, and the Banquo checkout used by OptiFuzz
Legacy Gazebo pathsource ./setup.sh --build-gazebo after building QEMU and installing Gazebo HarmonicGazebo/Courbet libraries and a plugin configured for them
SUNDIALS solverInstall libsundials-dev, then build with SUNDIALS=true plus the other required flagsOptional FMU solver support

Installing libhw alone does not rebuild an existing plugin. Include --build-qemu when you want setup to rebuild FastDyn with newly available libhw support. Rust/Cargo is needed for Rumoca, OptiFuzz, and the LibAFL backend; it is not needed for the minimal firmware walkthrough.

Rebuild without losing your build choices

After editing C sources, preserve the configured feature set with:

ninja -C build

The repository's make target removes and recreates the build directory. Every optional feature defaults to false unless explicitly supplied. For example, this chooses device models and the LibAFL backend:

make DEV=true LIBFUZZ=true

Include PHY=true FMU=true FLIGHT_CONTROLLERS=true when that rebuilt plugin must also retain the vehicle and FMU path:

make DEV=true LIBFUZZ=true PHY=true FMU=true FLIGHT_CONTROLLERS=true

LIBPY=true is documented as currently failing to build. Use the supported native virtual and host preprocessing interfaces for extensions.

Docker alternative

The checked-in Dockerfile builds patched QEMU, libhw, LibAFL, and Gazebo/Courbet. Initialize the sources copied into the image first:

git submodule update --init --depth 1 \
  third_party/common/qemu third_party/common/libhw \
  third_party/common/cmsis-svd-data \
  third_party/courbet_deps/mavlink_headers \
  third_party/courbet_deps/ardupilot_gazebo \
  third_party/courbet_deps/SITL_Models
docker build -t fastdyn .
docker run --rm -it fastdyn

The container starts in /workspace/FastDyn with fastdyn available. Its current build does not enable FMU=true or build Rumoca. Use the native FMU setup above for the maintained Modelica vehicle walkthroughs, or deliberately extend the image for that capability.

Choose the QEMU that matches your plugin

An explicit [Machine].qemu_path takes precedence. Without it, FastDyn checks FASTDYN_QEMU, the build metadata beside the plugin, then qemu-system-<arch> on PATH. A stock QEMU executable is not a substitute for the FastDyn fork and required compatibility patch.

Setup can use an already built sibling checkout at ../qemu; it reports that choice. To explicitly select another source checkout, use --qemu-root PATH. For a new external checkout, combine --clone-qemu --build-qemu. Existing sources are preserved rather than reset to a different branch.

Source guide

Your first experiment

In this walkthrough, FastDyn runs a bundled FreeRTOS firmware, changes a function argument at a chosen instruction, prints the value the callee receives, and stops at the scheduler entry. It demonstrates the central workflow: describe the experiment around the firmware, then execute it through the patched translator and runtime.

No board, device model library, FMU, or separate firmware compilation is required. Complete installation, activate fastdyn-env, and run from the FastDyn repository root.

Run the bundled configuration

fastdyn -q run -c configs/minimal.toml -o out/first-run

The configuration selects the bundled tests/sample_binaries/RTOS/RTOSDemo.axf, the generic cortexm machine, and a Cortex-M3 CPU. Its hooks are specific to that ELF. It exits by itself when execution reaches vTaskStartScheduler().

The key observable output is:

Reg 0:0x00000003

A [BENCH][minimal] record also reports elapsed time and the run terminates. Numeric timings depend on the host and build; a particular duration is not the pass criterion. The meaningful checks are the modified argument, the benchmark-end event, and a successful exit.

Understand what happened

The firmware's main() normally calls vStartLEDFlashTasks(1). Four configuration entries turn that behavior into a small experiment:

Trigger in this ELFActionWhat it demonstrates
0x08003972benchmark_startBegin a host-side timing interval at main()
0x0800397er0 <- 3Set the argument register before the call
0x080068b0printreg, argument 0Observe the value received at the callee entry
0x08001940benchmark_end, label minimalReport timing and stop at scheduler entry

These are the actual entries in configs/minimal.toml:

[[CPU.cpu0.virtuals]]
at = "0x08003972"
instruction = "benchmark_start"

[[CPU.cpu0.modifiers]]
at = "0x0800397e"
patch = "r0 <- 3"

[[CPU.cpu0.virtuals]]
at = "0x080068b0"
instruction = "printreg"
args = ["0"]

[[CPU.cpu0.virtuals]]
at = "0x08001940"
instruction = "benchmark_end"
args = ["minimal"]

The modifier changes execution state at the selected PC. The virtual instructions invoke named FastDyn actions there. The ELF file is unchanged, so the firmware retains its original addresses and symbols. These mechanisms have different runtime implementations, described in virtuals and modifiers.

The example uses ARM's r0 argument convention because its firmware is Cortex-M. The experiment structure is general; register names, ABI assumptions, and hook locations must match the selected architecture and binary.

Make one visible change

Copy the configuration into the repository root:

cp configs/minimal.toml first-experiment.toml

In first-experiment.toml, change the modifier to:

patch = "r0 <- 7"

Leave the rest of the existing modifier table in place, then run:

fastdyn -q run -c first-experiment.toml -o out/first-run-seven

The expected register line becomes Reg 0:0x00000007. This is a simple regression check for the relationship between configuration, trigger location, and guest state. Recompiling the firmware may move those locations, so do not carry the addresses into another ELF without resolving them again.

Inspect the run record

FastDyn writes the resolved rules to:

  • out/first-run/virtuals/virtuals.txt
  • out/first-run/virtuals/modifiers.txt

The default timing configuration also records fastdyn_timing.jsonl. Summarize it with:

fastdyn timing-summary out/first-run/fastdyn_timing.jsonl

Other outputs depend on enabled features. For example, QEMU instruction logging is disabled in the minimal configuration, so this run does not promise a populated qemu.log. Peripheral tracing, coverage, and plugin-specific artifacts appear when those features are enabled.

A new run replaces an existing work directory unless --persist-work-dir is supplied. Give each experiment its own path when you want to compare results. The minimal fixture also names fixed RAM files and a fixed QMP socket under /tmp; run this walkthrough serially. The multiple-firmware chapter explains isolation for concurrent workers.

Move to a longer-running example

To inspect a running RTOS and its activity monitor:

fastdyn run -c configs/introspection/freertos.toml -o out/freertos-introspection

The configured monitor is at http://127.0.0.1:8765/. Stop this example with Ctrl-C when finished. FastDyn requests a normal QEMU shutdown before escalating after its configured timeout, allowing runtime plugins to write their results.

The bundled minimal configuration intentionally allocates roomy emulated RAM. Its 512M main bank is a test configuration choice, not a statement about the physical RAM capacity of a Cortex-M3 microcontroller.

Source guide

Configure a firmware

A FastDyn TOML file is the experiment's executable description. It identifies the guest CPU and firmware, maps memory, routes peripheral accesses, and selects the instrumentation and optional physics required by the experiment. Start from a working profile close to your target, then make the assumptions explicit.

The full key reference is in configuration reference. This chapter explains the decisions in the order a new target usually needs them.

Start from the ELF or the starter

For an ELF with usable metadata, generate a draft:

./fastdyn-env/bin/python tools/elf2config/elf_to_config.py build/my_firmware.elf \
  --output configs/my_firmware.toml

Replace build/my_firmware.elf with your actual image. The tool extracts architecture, entry point, loadable writable ranges, and available Cortex-M, MCU, or RTOS hints. It produces a starting configuration for review. An ELF alone does not establish the complete board memory map or the behavior of its peripherals.

Alternatively, copy the small starter:

cp configs/bare_bones.toml my_firmware.toml

The starter intentionally names firmware.elf as a placeholder. Update it before launching.

Use the built-in discovery commands while editing:

fastdyn help platforms
fastdyn help machine
fastdyn help memory
fastdyn help firmware
fastdyn help device-models
fastdyn help plugins

On an interactive terminal, these commands offer choices and emit TOML fragments. --no-browse requests plain output. The SVD platform browser needs the catalog initialized by setup.

Describe the machine and CPU separately

[Machine] contains run-wide controls. [[CPU.cpu0]] selects the QEMU architecture, machine model, CPU model, firmware, and native FastDyn plugin. For example, this fragment describes a Cortex-M target; it is not a complete runnable configuration:

[Machine]
platform = "STM32F429"
display = "none"
monitor_port = 0
log_options = "none"

[[CPU.cpu0]]
arch = "arm"
machine = "cortexm"
cpu = "cortex-m4"
binary = "firmware.elf"
init_nsvtor = "0x08000000"

The CPU model must match the ISA and optional features used by the image. init_nsvtor is a Cortex-M vector-table setting; it is not a portable entry-point option for RISC-V or x86. Use the corresponding shipped architecture configuration as the starting point for those targets.

The SVD platform supplies peripheral and interrupt metadata. It does not generate a functioning peripheral implementation. generic-cortexm permits a Cortex-M experiment without an exact SVD match.

A single QEMU run can contain homogeneous CPUs, meaning the same architecture, CPU model, machine model, and firmware. Different firmware images belong in separate instances with explicit coordination, as covered in multiple firmwares.

Map memory from evidence

Define [Memory.main] first. Additional banks use array-table syntax such as [[Memory.ram1]]:

[Memory.main]
id = "ram0"
base_address = "0x20000000"
memory_size = "256K"
backend = "file"
share = true

This fragment lets FastDyn place the backing file inside the run directory. Use the target's actual map when validating memory behavior. Oversized RAM can conceal invalid accesses or missing memory regions.

backend may be file, ram, or memfd. File-backed memory can be inspected by host tools. Reusing an external RAM file can retain data between runs; select [Machine].reset_memory_files = true when the experiment requires it to be cleared before launch.

The generic Cortex-M machine supports additional RAM mapping properties. Other QEMU board models own their address layout, so creating a backend object alone does not give every board arbitrary remapping.

Route peripheral accesses

A device model registration names an available handler. A device table assigns address ranges and enables handlers for them:

[Device.Models.classic]

[Device.peripheral_window]
ranges = [["0x40000000", "0x5fffffff"]]
description = "Initial peripheral routing for this target."

[[Device.peripheral_window.handlers]]
model = "classic"
enabled = true

This is a configuration example, not a complete hardware model. Replace broad fallback routing with the models required by the firmware's behavior. If different regions require different models, give them separate device tables. A run with no peripheral handling can omit [Device] entirely.

For Cortex-M interrupts, numeric values are CPU exception numbers, so a device IRQ number has the architectural exception offset added. SVD interrupt names can be resolved for you. The reference explains the accepted list syntax and model-specific options.

Add only the instrumentation you need

Use a virtual for a named runtime action, a modifier for a guest state update at a PC, or a run-wide plugin for generated instrumentation. Plugin settings live under the CPU:

[CPU.cpu0.plugins.variable_watch]
enabled = true
variable = "motor_state.temperature"
access = "write"

This illustrative watch requires that variable to exist and be resolvable in your firmware. Each plugin defines its own prerequisites. Start with one observable result, such as an entry count or a known variable write, before combining multiple analyses.

Keep paths and run records predictable

Firmware, hardware-trace, model-library, and Python endpoint paths are checked relative to the configuration directory first. If the referenced file is absent there, the existing current-directory behavior remains. External plugin source paths are always resolved against the configuration directory. Helper working directories and FMU source paths use repository-root rules. These are different interfaces; do not assume every TOML string shares one path resolver.

Run from the repository root while bringing up a new profile:

fastdyn run -c configs/my_firmware.toml -o out/my-firmware-bringup

Inspect the generated rules, native logs, and first useful guest behavior. The initial success criterion should be concrete: reaching a known function, servicing one device transaction, advancing both RTOS tasks, or producing a valid sensor update. Reaching the entry point alone does not validate the whole board model.

Source guide

The system model

FastDyn is an execution engine for firmware experiments. Its inputs describe both the guest and the world visible to that guest. Its outputs describe what happened during the run. The framework makes those inputs and observations explicit enough to reuse them across analyses, target adaptations, and larger experiment drivers.

The main components

flowchart TD
    A["Experiment: TOML or Python"] --> B["Preparation and shared analysis"]
    B --> C["Rules, models, and artifacts"]
    C --> D["Patched QEMU and native FastDyn"]
    D --> E["Firmware execution"]
    E --> F["Peripheral models"]
    E --> G["Instrumentation plugins"]
    E --> H["Controller and physics adapter"]
    F --> E
    H --> I["In-process FMU"]
    I --> H
    G --> J["Observations and run results"]
    E --> J

The experiment description identifies a machine, CPU, firmware image, memory map, and optional features. Host preparation resolves information such as a function address or a structure member offset before QEMU starts. The native plugin then applies the resulting plan through QEMU's execution and translation hooks.

The execution pipeline describes the ordering in detail. This chapter explains why the components are separate and how to reason about the whole experiment.

The guest and its environment

The guest is the firmware running on the selected emulated CPU and machine. Its instructions, registers, address space, exceptions, and software state belong to that execution environment. The host is the machine running FastDyn and its models. A host pointer, a guest address, and an offset within a peripheral register bank are different values, even if they share an integer representation.

Peripheral models implement the interactions a firmware access encounters. Depending on the experiment, a device may be represented by a C state machine, a trace, a physical-board connection, or an existing QEMU device. A controller adapter may instead bridge a higher-level data boundary, such as a sensor sample or actuator output.

The chosen boundary determines what the run can establish. A correctly flying firmware slice can provide evidence about its executed control path while leaving bypassed hardware initialization untested. A register-level model can exercise a driver but still depend on the accuracy of its device semantics. FastDyn supplies the execution and integration mechanisms; the experiment author selects and records the abstraction.

Preparation and execution have different jobs

Preparation is a good place for expensive or repeated information recovery: reading an ELF, resolving aliases, inspecting DWARF, locating functions, selecting instrumentation points, validating layouts, and building an FMU when needed. The shared analysis session lets several preprocessors reuse immutable facts from the same image.

Execution is a good place for work that depends on live state: servicing an MMIO access, reading registers, updating device state, recording an interrupt event, or advancing the plant at the configured time boundary. Keeping image analysis out of hot callbacks makes plugins easier to understand and avoids repeating work on every guest event.

ConcernOwner
Parse and launch the experimentGeneric Python frontend and run API
Recover reusable firmware factsfastdyn.host and target-aware analysis helpers
Decide which functions or accesses matter to one featureThat feature's host preprocessor
Execute a virtual callback or observation hookThat feature's native runtime
Implement device registers and side effectsDevice model
Convert controller values and layouts to the plant contractFlight-controller or world adapter
Evolve physical stateSelected physics backend and model
Select campaign goals, policies, and result interpretationExperiment driver or downstream tool

The ownership rule prevents a feature from turning the core into a collection of target-specific cases. A new firmware can usually be adapted through configuration, profiles, and plugins while preserving the generic runner.

Time is part of the model

FastDyn experiments may observe host elapsed time, guest virtual time, executed-instruction progress, and a physical model's simulation time. These clocks answer different questions. Host timing measures cost. Guest time drives firmware-visible timeouts and scheduling. Physics time determines the plant's state evolution.

A model step must follow the experiment's chosen synchronization contract. Making the host faster should not silently change a controller's simulated sensor cadence. Conversely, a guest instruction budget is not a measurement of a physical processor's cycle timing. Read physics timing and performance measurement before comparing rates.

Artifacts are the boundary between stages

Prepared rules, schemas, manifests, and compiled models make the run inspectable. Runtime plugins write their observations under their artifact namespace. Experiment drivers can retain those products alongside the firmware and configuration to explain both what was requested and what was observed.

This structure supports three styles of work: a small hand-written experiment, a preparation plugin that derives instrumentation automatically, and a downstream system that repeatedly drives FastDyn through its API. They share the engine while making different decisions about the experiment.

Source guide

The execution pipeline

FastDyn turns a description of an experiment into an executable firmware environment. The same run can combine a firmware image, peripheral models, instruction-triggered interventions, observation plugins, and a physics backend. The central design choice is to prepare as much information as possible on the host, then give the native execution engine a compact description of what to do.

This creates three useful places to work: configuration describes the experiment; host preparation resolves firmware facts and builds instrumentation; execution runs the guest and applies the prepared behavior. A feature can use one or several of these stages without becoming a special case in the command-line frontend.

From a configuration to an experiment

flowchart TD
    A["TOML or Python run request"] --> B["Machine and CPU configuration"]
    B --> C["Enabled run preprocessors"]
    C --> D["Shared firmware analysis"]
    D --> E["Generated rules and artifacts"]
    B --> F["User virtuals and modifiers"]
    E --> G["Resolve and validate virtual rules"]
    F --> G
    G --> H["Patched QEMU and FastDyn plugin"]
    H --> I["Guest execution"]
    I --> J["Peripheral and physics interactions"]
    I --> K["Observations and interventions"]
    J --> I
    K --> L["Run artifacts"]

The Python run API and CLI share the run machinery. Configuration parsing builds the machine, CPU, memory, device, and plugin settings. The frontend prepares the work directory, optional FMU inputs, and other run resources before launching QEMU.

An enabled run preprocessor receives its own configuration table and a RunContext. It can query the firmware, write a schema or manifest, and return generated virtual instructions. Function Counter, for example, selects ELF function entries and generates one hook per selected entry. Introspection determines RTOS hooks and prepares a schema for the native walker.

FastDyn combines these generated hooks with explicit user rules and rules loaded through existing_config_path. It resolves trigger addresses, performs any per-virtual preparation, checks declared capabilities, and rejects conflicting virtual callbacks at a PC. Identical virtual rules are deduplicated. Modifiers have a separate serialization path and exact-line deduplication.

The resulting rule files are runtime inputs, not edits to the firmware:

Location under the work directoryRole
virtuals/virtuals.txtPrepared trigger PCs, callback names, and argument strings
virtuals/modifiers.txtPrepared inline state-update rules
virtual-artifacts/Data produced by individual virtual preprocessors
run-artifacts/<plugin>/Run-plugin schemas, manifests, observations, and final results

Native plugins resolve their own artifact names through the runtime SDK. A plugin therefore does not need to add a QEMU command-line option for each generated file.

What happens during translation

QEMU translates guest instructions into host-executable code in translation blocks. FastDyn's block-translation callback inspects the guest instruction addresses in a block and installs the configured instrumentation at matching PCs.

Virtual instructions and modifiers use two common execution mechanisms:

MechanismInstalled during translationAction when the guest reaches the PC
Virtual instructionAn instruction execution callbackInvoke the registered native C behavior
ModifierA specialized inline operation in the patched QEMU pathUpdate the configured register or memory state

The translation callback prepares instrumentation; it does not execute a firmware event merely because a block was translated. The installed action runs when the translated guest instruction executes, including subsequent executions of a cached block. This distinction matters for loops, counters, interrupts, and timing experiments.

The native core registers instrumentation in the following order within its instruction loop: coverage/register logging, a virtual callback, specialized inline I/O, modifiers, and legacy detours. This describes the current implementation's registration order. It is not a substitute for checking the semantics of overlapping interventions, especially interventions that change control flow.

Manual and automatic inline I/O

FastDyn already contains a specialized path that associates a known guest PC with an inline I/O load or store. [Machine].finline selects a user-supplied access-map file; the frontend forwards that path to the native parser. Each parsed record contains a PC, read/write direction, device name, offset, and register. The translation callback then installs QEMU_PLUGIN_INLINE_LOAD_IO or QEMU_PLUGIN_INLINE_STORE_IO.

This manual implementation addresses a global gpio_memory[0x400] buffer. The record's device name is parsed but does not choose a separate device backing block in this path. An inline hook executes before the original instruction; replacing an MMIO operation also requires a separately validated control-flow action that suppresses that original access. The inline device modeling chapter explains the backend semantics and a manual lab pinned to 5b8bf3d.

Revision e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576 adds experimental automatic MMIO optimization through the mmio_opt run plugin. Model compilation produces a bounded operation descriptor, while host preparation discovers candidate firmware loads through shared constant propagation. The runtime reads that plan during plugin initialization and defers instance binding until after dev_init, before guest translation. It then registers typed replacements against each resolved elder instance's live allocation. This uses the public post-device-init lifecycle and runtime SDK and the optimizer's native binder.

The patched Cortex-M translator emits the model expression as one arm of the original scalar load, with a live address guard and MPU fallback. It does not use the manual array or a PC-skipping modifier. The initial host gate requires a single Cortex-M CPU and disables substitution for its declared incompatible capabilities. Automatic MMIO optimization documents conservative effect admission, model ABI 2, original-fault fallback, and observer-safe execution; the host gate and QEMU patch define the implemented scope.

Other translated hot paths

The same current QEMU patch series also adds two independent execution-path optimizations. The ordinary MMIO exporter supplies a scalar saved PC directly to version-2 device callbacks, avoiding the old allocating register-read path; this does not optimize or bypass the device model. An eligible constant ARM32-PC modifier uses QEMU's direct TB chaining instead of the general PC-modifier exit, with conservative fallback when chaining is unsafe. Neither feature changes the TOML rule grammar, and neither makes a particular arbitrary firmware faster by itself. See Hot-path optimization contracts.

Runtime models and observations

During ordinary peripheral execution, device dispatch handles the configured accesses. Runtime plugins may observe MMIO after dispatch, react to guest IRQ events, inspect translated blocks, or install prepared PC callbacks. An optimized access that bypasses dispatch has a different observation boundary, covered in the automatic-MMIO chapter. Physics integration exchanges actuator commands and simulated state through its selected backend. These interfaces allow a model, a tracer, and an experiment controller to coexist while retaining distinct responsibilities.

Results remain in the work directory. Some artifacts, such as Introspection's activity log, are updated during execution. Others, such as Function Counter's final sorted totals, depend on normal shutdown callbacks. Stop a run cleanly when its result contract includes exit-time output.

Architecture is a property of each layer

The execution framework is not synonymous with Cortex-M. FastDyn exposes register/ABI headers for ARM32, Cortex-M, AArch64, RV64, and x86-64, and the source includes architecture-specific configurations and adapters. Individual analyses have their own scope: the shared instruction decoder, VariableWatch's candidate analysis, and ObjectSan's planner currently require ARM Thumb/M-profile.

Select the guest architecture, machine, CPU, instruction mode, and plugin together. An execution backend supporting an architecture does not imply that every analysis or peripheral model supports it.

Source guide

Architecture and portability

FastDyn's architecture spans more than Cortex-M. Its machine configuration and native SDK include multiple guest targets, while some of its most developed examples and analyses use ARM microcontrollers. Portability is therefore a property of a particular combination of execution backend, firmware, plugin, and model.

Four questions to ask

  1. Is the appropriate patched QEMU target built?
  2. Does the selected machine provide the execution environment needed by the image?
  3. Do the enabled analyses and runtime plugins support the guest's ISA, mode, widths, and ABI?
  4. Does the environment model implement the boundary this experiment uses?

Answer all four before moving a configuration between architectures. A register-name mapping cannot by itself port a Cortex-M interrupt model or a Thumb-specific instruction analysis.

Current source coverage

LayerEvidence in the inspected revisionPractical interpretation
Default build and shortest tutorialsarm-softmmu, Cortex-M fixturesThe native quick start is centered on ARM microcontroller examples
Additional guest configurationsconfigs/riscv_64.toml, configs/intel_x86_64.tomlTarget templates exist; they require their own binaries, paths, and matching QEMU builds
Native architecture helpersARM32, ARMv7-M, AArch64, RV64, x86-64 headersRuntime plugins can select explicit register and ABI definitions
Function entry tracingARM32, AArch64, RV64, System V AMD64 layoutsThe tracer has explicit entry-argument layouts rather than one universal register scheme
Shared instruction decoderARM with thumb-mclassUnsupported combinations raise a target error
VariableWatch and ObjectSan planningCurrent shared Thumb/M-profile analysisThese plugins do not become portable solely by changing arch
Experimental automatic MMIO at a38af40Single-CPU Cortex-M Thumb with little-endian scalar loadsRequires its matching QEMU patch and audited model; see automatic MMIO for eligibility and correctness limits
RTOS introspectionSix adapters with different discovery and runtime behaviorUse the adapter-specific contract and demonstrated fixture, not a blanket architecture claim
Device and interrupt infrastructureSeveral current windows and IRQ paths are M-profile-specificReview these paths when adapting a different machine

The target templates are not a claim that every example has been executed on every architecture. The capability status records what each category means in this book.

Guest state needs its actual width

The native SDK provides virtual_read_register_bytes() and virtual_write_register_bytes() for complete target-register representations. Its 32-bit convenience operations remain useful when a register or value is actually 32 bits. A portable plugin must not truncate an RV64 or x86-64 pointer simply because the original example used uint32_t.

Use the selected architecture header for register identifiers and argument conventions. Account for byte order, stack alignment, return-value layout, and registers that have special write semantics. Cortex-M's link-register and Thumb conventions are local target rules, not the definition of a FastDyn virtual instruction.

Guest addresses also differ from host pointers. Use the runtime memory APIs to access guest memory and the model API's supplied instance state to access host-side device state. A shared backing block needs an explicit mapping; it is not established by casting an address.

Host platforms and dependencies

The documented source installation targets Ubuntu 24.04. The FMI package/runtime code handles Linux host binaries for x86-64 and AArch64. This describes that subsystem's packaging capability; it is not a tested claim that every FastDyn dependency, optional backend, and board probe works on every host.

The default setup builds the ARM QEMU executable. When using another guest, select the corresponding patched QEMU build target and executable. A system QEMU that lacks FastDyn's extensions is not a drop-in substitute. Keep the firmware compiler, guest architecture, QEMU target, native plugin, and host FMU binary identities distinct in your experiment record.

Designing portable extensions

Keep generic policy separate from architecture mechanics. A host analysis can return an address or a candidate access description; an architecture adapter supplies decoding, ABI rules, and instruction effects. A runtime plugin can share its event logic while using target-specific state-access helpers.

The JIT patcher, reviewed at the newer main revision 5b8bf3d, follows this rule: one byte-fragment registration contract with explicit ISA, mode, and instruction order, backed by target-specific admission and decoding. Its translation insertion design explains how original guest addresses remain stable. This interface is not defined around one microcontroller family.

Source guide

FastDyn and its ecosystem

FastDyn supplies execution and experiment integration. Several related tools supply models, recover information, or automate workflows around it. Keeping those responsibilities explicit makes the system easier to extend: a model synthesis tool can improve without becoming part of the QEMU plugin, and a new plant model can serve more than one simulator consumer.

Current boundaries

ComponentRole around FastDynBoundary to preserve
FastDynConfigure, prepare, execute, instrument, and collect a firmware experimentGeneric execution and extension APIs
Patched QEMUGuest CPU/machine execution and the translation hooks FastDyn requiresPin the expected fork and patch
LibVIOReusable bus, DMA, signal, and host-I/O primitives used by device modelsPeripheral-model implementation library
libhwAccess a physical target through supported debug-probe backendsHardware connection and transactions
BoardRunnerLearn and verify peripheral models from hardware evidenceDownstream model-generation workflow
PhantomSmithAutomate firmware rehosting using the execution engineDownstream orchestration and target adaptation
RumocaCompile Modelica models used in the maintained FMI pathModel compilation and generated artifacts
TempoCompile typed federations and coordinate participant time, routing, and synchronizationSeparate native scheduler; the reviewed revision supplies mock participants
raw2elf and worldOptional neighboring tooling for image preparation and physical-world integrationTheir own repositories and explicitly configured adapters

The FastDyn source README documents BoardRunner, LibVIO, and PhantomSmith as separate projects. The implementation also pins optional dependencies and tools in .gitmodules. Their presence does not mean every dependency is required to run the minimal example.

A model-to-execution workflow

A peripheral model may be hand-written or generated by a downstream tool. FastDyn compiles or loads the resulting library and routes the configured accesses to it. The execution engine cares about the model's ABI and behavior, not how its author produced it.

Likewise, a firmware-analysis tool can use the Python API to prepare and run an experiment, then inspect artifacts. It should call the public runner rather than maintain another implementation of configuration parsing, work-directory management, FMU preparation, and helper-process cleanup.

This separation is useful for research. Two synthesis strategies can be compared against the same execution machinery. A new instrumentation technique can use the same peripheral models. A physics-backed scenario can combine an established controller profile with a different plant while retaining the experiment's timing and data contracts.

Physical models and the firmware boundary

FastDyn's physics integration includes Modelica files, pinned Rumoca integration, controller adapters, and an FMI runtime. A physical model supplies state and observations; the configured firmware adapter determines how those values reach the guest. Use the FMU chapter for the executable workflow and its versioned prerequisites.

The in-process FMU design allows a model to run inside the QEMU process. An optional viewer, telemetry bridge, or mission helper is a separate component with its own configuration and lifecycle.

External pacing and Tempo

FastDyn as a secondary simulator exposes execution budgets through patched QEMU's QMP interface. An external controller grants virtual time and observes stops; its data-exchange policy and any connections between guests remain explicit parts of the experiment.

Tempo implements a separate native scheduler, federation compiler, typed routing, and Python/TOML configuration. Its reviewed revision runs mock participants and contains no FastDyn or FMI adapter. The chapter's working examples exercise those shipped mocks.

Where a contribution belongs

Put behavior used by one feature in that feature's host/runtime package. Put shared immutable firmware facts in the host-analysis API when multiple consumers need them. Keep live simulator samples and feature-specific policy with the owning adapter or plugin.

Put model synthesis, agentic orchestration, or another downstream application's decisions in its own project. The FastDyn core should not need a special branch for a downstream tool name. Register extensions through the preparation, runtime, model, or backend interfaces.

These rules are more than directory organization: they preserve the ability to combine independent tools without duplicating the execution engine.

Source guide

Virtual instructions and modifiers

FastDyn lets an experiment change what happens at a chosen guest program counter without rebuilding the firmware. A virtual instruction invokes a named native action. A modifier requests a direct register or memory assignment through the patched QEMU inline path. These are useful for injecting inputs, observing function arguments, supplying initialization behavior, raising interrupts, and redirecting selected execution paths.

The trigger is a guest instruction address. A rule has no effect until that instruction executes. Use addresses and symbols from the exact firmware image being run.

Start with the bundled example

After building FastDyn and its patched QEMU, run from the repository root:

fastdyn -q run -c configs/minimal.toml -o fastdyn-minimal

The bundled configuration modifies an argument before a function call, prints the argument inside the callee, and ends the run at the scheduler startup point:

[[CPU.cpu0.modifiers]]
at = "0x0800397e"
patch = "r0 <- 3"

[[CPU.cpu0.virtuals]]
at = "0x080068b0"
instruction = "printreg"
args = ["0"]

[[CPU.cpu0.virtuals]]
at = "0x08001940"
instruction = "benchmark_end"
args = ["minimal"]

The observable result is register 0 containing 0x00000003, followed by a benchmark result tagged minimal. The elapsed time is machine-dependent; the important functional observation is that the callee receives the configured argument. The firmware file itself remains unchanged.

Choose a mechanism

Desired behaviorMechanism
Assign a fixed input value at an instructionModifier
Redirect a specific execution pathPC modifier, using the target's explicit PC name
Raise an IRQ, start a timer, or load a payloadExisting virtual instruction
Perform custom native workRuntime callback plus Python VirtualDefinition
Derive many hooks from firmware analysisRun preprocessor that emits virtual rules

Both mechanisms are installed during translation and take effect during execution. A virtual uses a C callback. A modifier uses specialized inline update operations. This is a mechanism distinction, not a universal performance result: actual overhead depends on what is instrumented and how often it executes.

Virtual configuration

Virtual entries live under a CPU's virtuals array. args is optional and contains string tokens. FastDyn prepares and joins the tokens into the argument string received by the callback. A symbol or symbol+offset can identify a trigger when the firmware provides the required symbols.

This fragment illustrates interrupt injection; replace the address with a suitable instruction in your image:

[[CPU.cpu0.virtuals]]
at = "0x08001234"
instruction = "raise_periodic_irq"
args = ["15,1000000"]

Here 15 is the exception vector and 1000000 is the period in nanoseconds. The trigger PC is neither the interrupt vector nor the period. Numeric interrupt arguments are passed through as exception vectors. The Cortex-M preparation adapter can resolve supported symbolic SVD IRQ names.

Core callback catalog

NameArgument shapeBehavior
raiseirqIRQ vectorRaise the configured IRQ
pulseirqIRQ vectorPulse the configured IRQ
raise_periodic_irqirq[,period_ns]Register a periodic interrupt
updatememaddress:r|w:length:byte,...Read or write guest memory; both forms require the byte-list parser field
randstateComma-separated register numbers or addressesRandomize selected state; avoid using it for the PC
printregRegister numberPrint a register
debug_logMessageEmit a diagnostic with CPU and virtual-time information
benchmark_startNoneStart a host monotonic-time region
bench_tickNoneIncrement that benchmark's tick counter
benchmark_endOptional tagReport elapsed time and terminate QEMU
timer_startIgnoredStart the legacy fixed-period virtual-clock timer
start_budgetingIgnoredEnter plugin budget waiting
dyninstaddress:fileLoad a host file's bytes into guest memory
dyninst_libELF fileLoad an ELF through the QEMU plugin API
dumploglogger-index:fileWrite an internal logger buffer

dyninst is a runtime memory-loading operation. The newer JIT patcher instead registers guest instruction bytes during plugin initialization and emits admitted fragments through the translator without writing those bytes into guest memory. Explore the virtual and modifier catalog with fastdyn help virtuals --no-browse and fastdyn help modifiers --no-browse; the fragment API is a native runtime SDK facility.

Modifier grammar

Use patch = "target <- value". The parser also accepts =, :=, and ->, but <- is the canonical spelling.

FormInterpretation
rN or xNNumeric register slot
[rN] or [xN]Memory through a register-held pointer
0xADDRESS on the leftAbsolute guest-memory target
Decimal or hexadecimal integer on the rightImmediate value
Register or register dereference on the rightSource operand, where the target backend implements the form
rip, rspExplicit x86-64 inline-register aliases
riscv_pc, pc32Explicit RISC-V PC slot

Use r15/r13 for ARM32 PC/SP, rip/rsp for x86-64, and riscv_pc with the appropriate xN registers for RV64. The generic pc alias currently resolves to slot 32 in the native parser, while sp resolves to 13. They are not portable architecture selectors. Modifier slots also belong to the inline backend's convention; do not assume they equal every runtime SDK register index.

The current absolute-memory target path warns and skips an address greater than 0x40000000. It should therefore not be presented as a general MMIO-write facility. Memory access widths and supported operand combinations follow the patched backend; this syntax is not an arbitrary typed expression language.

Composition and troubleshooting

Host preparation allows one distinct virtual callback at a trigger PC. Identical rules collapse; different rules at the same PC produce a conflict naming their origins. Function Counter and Function Tracer, for example, may both select the same function entry. Narrow their selections or run separate experiments.

Modifiers may coexist with a virtual, but overlapping updates need deliberate semantics. The current native registration order is logging, virtual callback, inline I/O, modifiers, then legacy detours. Avoid treating file order as a callback-composition API.

For an unexpected result, inspect virtuals/virtuals.txt and virtuals/modifiers.txt in the work directory, confirm the instruction is reached, and check the architecture-specific register mapping. An instruction may overwrite a value you assigned immediately before it; select the hook location according to the intended data flow.

Legacy manual inline I/O

[Machine].finline accepts a user-supplied static access-map file. The frontend forwards its path to the native parser; this path consumes an already prepared table and does not itself run the MMIO discovery helper. A schematic record is:

0x08001234 R gpioa 0x10 0x0

The five fields are hexadecimal PC, direction, device label, hexadecimal offset, and hexadecimal register slot. Direction accepts R/READ and W/WRITE, case-insensitively. The first matching record for a PC is used. The table has no transaction-width field; admitted register and access semantics belong to the patched backend.

This manual translation path uses the offset into a single 1 KiB gpio_memory buffer and does not select a backing region from the device label. Keep every access within that buffer: the native table reader does not bounds-check the offset. The hook runs before the original instruction; it does not suppress that instruction by itself. The inline device modeling chapter explains the backend's transfer width, an explicit same-site PC modifier for skipping the original MMIO, and the required control-flow checks in a lab pinned to 5b8bf3d.

Fixed-PC modifier chaining (ARM32)

With the updated five-patch QEMU backend at e44dca2, an eligible unconditional immediate assignment to the ARM32 PC is automatically lowered to QEMU's direct translated-block exit rather than the general modifier callback exit. The TOML syntax is unchanged:

[[CPU.cpu0.modifiers]]
at = "0x08001234"
patch = "r15 <- 0x08001000"

The source and absolute destination must be on the same guest page, align with A32 or Thumb mode, and have a usable outgoing QEMU chaining slot. IT/ECI/ICI, single-step, conflicting fragments/callbacks, and state-dependent targets retain the legacy behavior. AArch64 register 15 is not a PC alias. Disable promotion for comparison with FASTDYN_CONST_PC_CHAIN=0; use FASTDYN_CONST_PC_CHAIN_TRACE=1 for translation-time reasons, not a per-hit counter. The runtime retains the original PC value, suffix and instruction accounting; on PC-relative alias mismatch it takes the legacy general exit. See Hot-path optimization contracts for the precise constraints, regression command, and bounded benchmark.

Experimental automatic MMIO

Revision e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576 adds the mmio_opt run plugin. It combines model-operation metadata with discovered Cortex-M Thumb access sites, binds reads to initialized elder instances, and registers guarded replacements through the native runtime SDK. The runtime module and QEMU patch implement this separate path.

The current extractor declines unsafe effects, aliases and predicates; the native fast arm preserves alignment faults and uses ordinary dispatch when an MMIO observer is active (including later registrations). A successful fast arm replaces the original scalar read directly; it needs no manual PC-skipping modifier. The host compatibility gate disables automatic substitution when finline is active. Use Automatic MMIO optimization for configuration, the shipped demonstration, and the bounded admission and evidence requirements; arbitrary device models are not proven equivalent.

Source guide

RTOS introspection and the activity monitor

FastDyn can turn an opaque firmware run into a view of tasks, scheduler activity, and kernel resources. Its introspection plugin combines host-side symbol and layout analysis with native callbacks, then records structured events that a browser monitor can display while the guest executes.

This is useful when the firmware is running but its behavior is difficult to explain. You can ask which task is active, whether synchronization objects are being used, and where execution stops producing scheduler events. The same event log remains available after the run, so observations do not disappear with the browser window.

Run a complete example

After building FastDyn and patched QEMU, run from the repository root:

fastdyn run -c configs/introspection/freertos.toml \
  -o fastdyn-introspection-demo

This configuration uses a committed FreeRTOS ELF with debug information and enables the local activity monitor. Open the URL printed by the plugin, normally http://127.0.0.1:8765/. Let the firmware execute, inspect the task and resource panels, then stop the run with Ctrl-C.

The reusable outputs are:

Artifact under run-artifacts/introspection/Purpose
schema.txtPrepared symbols and supported kernel layouts consumed by the native adapter
activity.jsonlOne structured event per line, recorded during execution

The generated PC hooks are also visible in the run's virtuals/virtuals.txt. Looking at the schema and generated hooks explains what the plugin can observe for this particular firmware build.

Enable it in your configuration

Add the following tables to a suitable CPU configuration:

[CPU.cpu0.plugins.introspection]
enabled = true

[CPU.cpu0.plugins.introspection.activity_monitor]
enabled = true
host = "127.0.0.1"
port = 8765
open_browser = true

The nested monitor table belongs to the plugin. No extra FastDyn CLI flag or introspection-specific QEMU argument is required. Omit the monitor table, or set activity_monitor = false in the parent table, to collect the activity artifact without launching the browser service. The service binds to loopback by default and shuts down with the run.

A firmware needs enough retained symbols for the adapter to identify relevant hooks. DWARF supplies layout details for supported task and resource fields. An optimized-away API cannot be instrumented by its absent symbol, and missing type information limits the fields the runtime can decode.

Supported RTOS families

The repository provides directly runnable configurations for six RTOS families. These examples use committed debug-symbol fixtures; they do not require cloning and building every RTOS before trying the monitor.

RTOSExample configurationMonitor portMain observation approach
FreeRTOSconfigs/introspection/freertos.toml8765Dedicated native task walker, creation/switch events, queue-backed resource classification
ChibiOSconfigs/introspection/chibios.toml8766Dedicated native task walker and task/resource hooks
Zephyrconfigs/introspection/zephyr.toml8767Selected architecture switch hook, schema-backed current-thread fields, resource hooks
ThreadXconfigs/introspection/threadx.toml8768Scheduler/lifecycle events and current-thread pointer when available
RT-Threadconfigs/introspection/rtthread.toml8769Scheduler/lifecycle events and schema-backed current-thread lookup
NuttXconfigs/introspection/nuttx.toml8770Supported scheduler transition hook with decoded destination-task metadata

For example:

fastdyn run -c configs/introspection/zephyr.toml -o fastdyn-zephyr

The adapters intentionally differ in depth. FreeRTOS and ChibiOS have bespoke task walkers. The other adapters use event hooks and schema-backed fields instead of assuming a universal private task-list layout. A scheduler event is not automatically a complete task switch, and observing a resource operation is not automatically evidence that the operation succeeded.

All six adapters declare semaphore, mutex, and timer hooks where those APIs exist. Zephyr, ThreadX, and RT-Thread also include message-queue and event-flag operations; ChibiOS includes mailbox operations. The actual emitted set depends on symbols present in the selected image. FreeRTOS uses its schema to distinguish several resource kinds implemented through queues.

Read the monitor correctly

The overview identifies the latest active task when a task_switch event supplies one. Task and kernel-resource panels let you filter the stream by a stable object identity. The object viewer keeps a selected object in view while later events refresh its captured fields, such as priority, scheduler state, semaphore count, or timeout metadata.

Two visualizations answer different questions:

  • Event rate shows recorded events across simulated time. A quiet interval means no relevant events were recorded; it is not a host-utilization measurement.
  • Task CPU ownership estimates guest time between recorded task-switch events. Its accuracy depends on observing those switches and identifying the task. It is not a hardware performance counter or a complete RTOS accounting facility.

The event artifact uses time_ns from QEMU's virtual timer. Optional fields include rtos, event, task identity/name, priority, task state, and adapter-provided decoded fields. Missing fields remain absent rather than being filled with invented values.

For a stalled-looking run, first compare the monitor with the artifact. A populated log with no new events points to a different investigation than a missing or empty file. The guest might be polling a device, waiting for an interrupt, or running code outside the installed hooks. Combine this view with function tracing and variable watches to localize the behavior.

Architecture and build scope

Zephyr's host adapter contains switch-symbol selections for several architecture families, including Cortex-M, ARM A/R, AArch64, RISC-V, and selected others. The appropriate symbol differs by port; the adapter does not guess a universal Zephyr switch function. Some ports deliberately have no selected switch hook.

That selection table is not an end-to-end portability guarantee. The committed demonstration path is Cortex-M, and native introspection still contains 32-bit pointer/layout assumptions. The NuttX switch callback explicitly follows ARM AAPCS argument placement. Validate the native pointer width, calling convention, schema, and callback semantics before claiming introspection coverage for another target.

How to extend the feature

The host preprocessor identifies the RTOS, resolves hooks, emits a schema, and returns declarative virtual rules. The native adapter consumes that schema and appends events. The browser renders generic event fields, so adding a useful decoded field normally belongs in the adapter rather than the UI.

Use shared host analysis for symbols and layouts, but keep RTOS hook selection and runtime interpretation in the introspection plugin. Test detection, generated hooks, schema contents, and live callback behavior as separate boundaries. This keeps a newly recognized RTOS from being mistaken for a fully implemented runtime adapter.

Source guide

Tracing, watches, and selected-object checking

FastDyn's observation plugins let you choose the abstraction that matches the question. Function Counter summarizes activity. Function Tracer records entry arguments. VariableWatch follows a source variable or address range. ObjectSan tracks the identity and lifetime of selected objects as pointers move through execution.

Each feature prepares its firmware-specific information before QEMU starts and writes results under its own run-artifacts/<plugin>/ directory. This gives you inspectable manifests as well as runtime output.

QuestionPluginPrimary result
Which selected functions execute, and how often?function_countercounts.tsv
What arguments reach a selected function?function_tracertrace.tsv
Which actual accesses touch this variable or field?variable_watchevents.tsv
Does a selected object's pointer escape its bounds or survive its lifetime?object_sanitizerviolations.tsv

Count function entries

Run the bundled example from the repository root after building FastDyn:

fastdyn run -c configs/function_counter.toml -o fastdyn-function-counter

Stop it with Ctrl-C so the native shutdown callback can write final counts. functions.tsv records installed entry hooks; counts.tsv reports calls, sorted by decreasing count, including selected functions that were never observed.

For your own image, narrow the selection:

[CPU.cpu0.plugins.function_counter]
enabled = true
include = ["main", "sensor_*"]
exclude = ["sensor_busy_poll"]
max_functions = 128

Patterns are shell-style symbol-name globs. The preprocessor uses defined executable function symbols, chooses one name for aliases at an address, and normalizes ARM Thumb function addresses when appropriate. It fails when the selection is empty or exceeds the configured limit. The maximum supported selection is 4096 functions.

These are entry counts, not inclusive execution time. An inlined function without an independent entry is not represented as an ordinary call hook.

Trace arguments at function entry

Function Tracer augments the same selection pattern with a DWARF-derived argument schema:

fastdyn run -c configs/function_tracer.toml -o fastdyn-function-tracer

Its output includes functions.tsv, arguments.tsv, trace.tsv, and final counts.tsv. Each trace record contains the reported guest instruction count, entry PC, function name, and rendered arguments. The schema records how selected values should be obtained from registers or the caller's stack.

The trace's icount field comes from FastDyn's native counter. At this revision, the block-execution hook that advances that counter is installed for TwinTrace modes, so a default run can report zero throughout. Do not interpret zero as an absence of execution or use this field as exact instruction-retirement accounting.

[CPU.cpu0.plugins.function_tracer]
enabled = true
include = ["my_api_*"]
max_functions = 64
max_events = 10000

The implementation contains entry-ABI layouts for ARM32/AAPCS, AArch64, RV64, and System V AMD64. It recognizes bounded scalar, pointer, array, and structure descriptions, including up to eight direct scalar or pointer fields of a structure. It does not evaluate arbitrary DWARF locations, dereference arbitrary pointers, decode nested aggregates, or implement every aggregate-classification rule of those ABIs. Treat it as a bounded entry tracer and inspect arguments.tsv when an argument matters to your experiment.

The default event cap is 100000; zero removes the cap. Restricting function selection is usually more useful than capturing an enormous trace of frequent internal calls.

Function Counter and Function Tracer can select the same PCs. The virtual dispatcher accepts one distinct callback per PC, so use separate runs or disjoint selections when their hooks overlap.

Watch a source variable or raw range

VariableWatch resolves a fixed-address global or structure-member path:

[CPU.cpu0.plugins.variable_watch]
enabled = true
variable = "motor_state.temperature"
access = "write"
changes_only = true

It uses the field's actual address and size. An access to an adjacent field does not match unless its byte range overlaps the watched range. Runtime matching considers partial overlap and actual direction, rather than comparing only the starting address.

For an address-based watch, replace variable with address and a positive size:

[CPU.cpu0.plugins.variable_watch]
enabled = true
address = "0x20001420"
size = 4
access = "read_write"

Use exactly one selection form. Address selection needs no DWARF variable lookup. It is a raw address-range mode, not a claim of arbitrary flat-binary support: the shipped example still loads an ELF, and the candidate planner reads executable ELF sections. The included examples are:

fastdyn run -c configs/variable_watch.toml -o fastdyn-variable-watch
fastdyn run -c configs/variable_watch_raw.toml -o fastdyn-variable-watch-raw

watch.tsv records the normalized target, candidate_accesses.tsv records conservative candidate PCs, and events.tsv records matched runtime accesses. Events include the PC, containing function, direction, actual address/width, and watched bytes. Byte values retain target byte order. changes_only suppresses unchanged writes in the TSV output; native subscribers still receive matching filtered accesses.

The current candidate planner and runtime target ARM Thumb/Cortex-M. The planner retains uncertain indirect accesses rather than discarding them because static pointer recovery failed.

Track a selected object's identity

ObjectSan instruments selected objects and tracks provenance through supported operations. A static selection can name an object or all fixed-address globals of a supported DWARF type:

[CPU.cpu0.plugins.object_sanitizer]
enabled = true
object = "packet_buf"

For a dynamic allocation, selection can identify a direct allocation call by caller and one-based ordinal:

[CPU.cpu0.plugins.object_sanitizer]
enabled = true
function = "create_packet"
allocation = 1
allocator_model = "freertos"

The included normalized allocator models cover libc, FreeRTOS, Zephyr, NuttX, RT-Thread, ChibiOS, and ThreadX. Custom allocation/free APIs can be described in the plugin's allocators array. These models normalize events; they do not imply full support for every allocator calling pattern.

At a selected allocation, the runtime creates an object identity from the returned pointer. Freeing it marks that identity FREED. If a numerical address is reused, the new allocation gets a new identity, allowing stale pointers to remain distinguishable. Pointer arithmetic retains a selected object's provenance, so an access beyond its bounds can still be associated with the original object.

Run the purpose-built examples:

fastdyn run -c configs/object_sanitizer_static_oob.toml -o fastdyn-objectsan-static
fastdyn run -c configs/object_sanitizer_dynamic_oob.toml -o fastdyn-objectsan-dynamic

Inspect objects.tsv, object_events.tsv, allocation_sites.tsv, instructions.tsv, and violations.tsv under run-artifacts/object_sanitizer/. The violation reasons are spatial-overflow, use-after-free, and unknown-provenance. The last is an uncertainty report, not a confirmed safe access or necessarily a concrete memory bug.

This is selected-object checking with an ARM Thumb/M-profile planner and supported provenance operations. It is not complete memory-safety verification. Inferred allocation-type selection, indirect allocator calls, and proof-based relevance pruning remain outside the implemented selection contract.

Source guide

Device models

FastDyn lets you choose a peripheral implementation independently of the firmware image. A UART can be served by a native C model, another peripheral can remain attached to real hardware, and a recorded interaction can be replayed later. The configuration names the address ranges, interrupts, and handler used for each device. The firmware continues to issue its normal loads and stores.

This is useful during incremental rehosting. You can replace one hardware dependency at a time, retain the rest of a working environment, and reuse the resulting model across firmware that targets the same peripheral. A register model belongs to the device; a hook at a firmware function belongs to that firmware's execution configuration.

Choose a handler

HandlerWhat the current implementation doesUse it for
elderLoads a C shared library exporting the versioned fastdyn_model descriptor; creates a separate state object for each configured deviceReusable, stateful peripheral models
passthroughForwards reads and writes through a libhw probe session and coordinates interrupts with the boardKeeping a physical peripheral in a rehosted execution
twintraceRecords hardware-backed interactions or replays a prepared MMIO/interrupt tapeReproducing a recorded interaction and comparing model behavior
classicProvides a built-in callback implementation whose current reads return zero and writes do nothingA permissive bring-up stub or a starting point for a built-in handler

elder is the normal extension point for new models. Its library can be hand-written or produced by a model-generation workflow. FastDyn loads the same ABI in either case. BoardRunner's learning and verification workflow is a separate producer of these libraries.

The classic label describes the callback route, not a catalog of complete peripherals. Do not select it expecting a UART, timer, or DMA controller to acquire realistic behavior automatically.

Describe one device

The following is a device-table fragment to add to an otherwise complete machine configuration after building the referenced model:

[Device.Models.elder]

[Device.usart2]
ranges = [["0x40004400", "0x400047FF"]]
irq = ["USART2"]
pty = "usart2"

[[Device.usart2.handlers]]
model = "elder"
enabled = true
scroll = "build/models/stm32_usart.so"

Address-range ends are inclusive. A handler receives the absolute address, access width, and guest program counter. The model converts the address to an offset relative to the relevant range. Device-specific settings such as pty become the model's JSON configuration; FastDyn removes its own routing fields before calling the model.

Named IRQs require the selected platform's interrupt map. On Cortex-M, numeric entries are exception numbers, so an external interrupt numbered IRQn is represented as IRQn + 16. This is an architecture-specific convention, not a rule to transplant to another interrupt controller. Lists can contain individual numbers, names, or two-element ranges. The former string syntax such as "0-20:21-25" is rejected.

What happens on an access

The patched QEMU exposes an I/O interception interface to FastDyn. The dispatcher associates the address with a configured handler, invokes its read or write callback, and notifies registered MMIO observers. An elder handler then selects the device instance and invokes that instance's model callback. Reads return a value to the emulated execution; writes update model state or trigger the model's chosen effects.

The dispatcher also receives interrupt-entry and interrupt-return notifications. Elder forwards those notifications only to instances whose configured IRQ list contains the interrupt. These callbacks observe servicing; a model that needs to assert an interrupt must explicitly use the supported QEMU interrupt API.

Current dispatch supports dynamic 64-bit ranges and a handler-name route for generic PCIe devices, in addition to the legacy address-region lookup tables. That is broader than a single Cortex-M memory map. Individual model implementations and IRQ mechanisms still need to match the selected target.

Compose devices with explicit ownership

Prefer one enabled owner for each MMIO range. In the current dynamic-range path, matching is first-match and registration prepends entries. Overlapping ranges therefore depend on registration order; a configuration is not a general priority-controlled fallback chain. A read_priority field should not be treated as a portable composition contract.

For mixed hardware and software experiments, partition the peripherals or address regions deliberately. The parser rejects a device that enables both passthrough and twintrace, because both are hardware-capable handlers. The same principle applies to FIFOs, clear-on-write registers, and other operations that must happen once.

FastDyn retains useful boundaries for extension:

ConcernOwner
Firmware instruction executionQEMU and the FastDyn runtime
Address-to-device selectionFastDyn device dispatcher
Register semantics and peripheral stateThe selected model
Reusable buses, DMA, signals, and host I/O helpersLibVIO, when used by the model
Physical transfer functions and plant stateThe connected physics model

This separation lets a new peripheral library improve many firmware experiments without introducing firmware-specific logic into the central dispatcher.

Continue

Build an elder library in Writing a device model, or connect a board and record a trace in Hardware and trace replay. For selected access sites, inline device modeling explains the specialized translation path, its current backing-state limitations, and the checks needed before replacing an ordinary device access.

Source guide

Writing a device model

An elder model is a shared library with a small, explicit interface: initialize a device instance, read a register, write a register, and optionally observe interrupt entry and return. The library is loaded into the emulator process. No separate model server is required.

The current interface is model ABI version 2, defined in <fastdyn/device_model.h>. Start from this header and the shipped tests/models/elder_echo.c example. The loader rejects an incompatible ABI, a missing descriptor, or missing required callbacks at startup.

Build the supplied example

After the normal FastDyn setup has installed the Python command, compiler dependencies, and patched QEMU headers, run these commands from the repository root:

fastdyn build-model tests/models/elder_echo.c -o build/models --no-vio

The result is build/models/elder_echo.so. The command detects dependencies and compile-command changes, so a subsequent invocation can reuse an up-to-date build. If compilation fails, it removes the model's stale output instead of leaving an old library available to a later run.

The shipped echo model has a useful test contract:

OffsetMeaning
0x00Writable data register, initialized from the model's reset setting
0x04Count of interrupt-entry notifications received by this instance
0x08Count of interrupt-return notifications received by this instance
Last byte of the configured rangeReads as 0xAA, exercising the inclusive range boundary

To bind it, add this fragment to a complete firmware configuration that actually accesses the chosen range:

[Device.Models.elder]

[Device.echo]
ranges = [["0x40000000", "0x4000000F"]]
reset = 7

[[Device.echo.handlers]]
model = "elder"
enabled = true
scroll = "build/models/elder_echo.so"

The fragment does not create firmware traffic. A guest must read or write the range to exercise it. The echo model is an ABI example, not a substitute for the real register semantics of a device at that address.

Implement the descriptor

These are the exact callback shapes accepted by the public header. This interface excerpt shows how the functions are registered; supply their definitions in your model:

#include <fastdyn/device_model.h>

static void *my_init(const FdDevice *dev,
                     const char *config_json,
                     const FdHost *host);
static uint64_t my_read(void *opaque, hwaddr addr,
                        unsigned size, uint64_t pc);
static void my_write(void *opaque, hwaddr addr, uint64_t value,
                     unsigned size, uint64_t pc);

const FdModel fastdyn_model = {
    FASTDYN_MODEL_ABI_FIELDS,
    .init = my_init,
    .read = my_read,
    .write = my_write,
};

FASTDYN_MODEL_ABI_FIELDS supplies the interface version and descriptor size. Required members are init, read, and write. Optional interrupt and serve members both have signature void callback(void *opaque, int irq).

FdDevice provides the instance's name, ranges, and IRQs. Its ranges use base plus size, even though TOML uses inclusive start/end pairs. FdHost currently provides the logging service. The model header also includes declarations for the patched QEMU host APIs; include the FastDyn header rather than independently selecting a potentially incompatible QEMU header.

Keep state per instance

Allocate a state object in init and return it. FastDyn passes that object back as opaque on every callback. This allows one UART library to serve UART2 and UART3 without sharing FIFOs or configuration accidentally.

Return NULL when the configuration cannot be supported. Preserve or copy values you need from config_json and host during initialization; their API contract guarantees their validity only for that call. The FdDevice description remains valid until unload. ABI v2 has no model teardown callback, so plan ownership around the current process lifetime rather than inventing a destructor interface.

Handle access width explicitly. A one-byte write to a data register need not mean the same thing as a four-byte write, and read-to-clear or write-one-to-clear behavior needs deliberate implementation. Keep unsupported accesses diagnosable with host->log and include the address, size, and guest PC when that context helps explain a failure.

Reuse LibVIO

LibVIO supplies reusable I/O mechanisms, including buses, signals, DMA support, and host endpoints. It is useful when a model needs those facilities; a small register-only model can build without it, as the echo example does.

Prepare the pinned dependency with:

source ./setup.sh --build-libvio
fastdyn build-model models/ -o build/models -r -j 8

The second command assumes your models/ directory exists. FastDyn looks for LibVIO through its prepared build or pkg-config vio, and the model includes <vio/vio.h> when using it. Elder routes LibVIO logging into the same FastDyn log when the library exposes its logger setter. Use the LibVIO API from the pinned dependency for bus operations; FastDyn's FdModel contract remains the surrounding peripheral interface.

For a model implemented across multiple source files:

fastdyn build-model --name spi4 models/spi4.c models/spi4_dma.c -o build/models

That command produces one spi4.so. Without --name, each input C file is a separate model. Review duplicate output names before combining directories.

Experimental extraction at a38af40

FastDyn a38af408451394ea2f41be1e9cf1e96bc46c370f adds optional automatic MMIO metadata generation. This is a later addition to the core f9666d7 model workflow above. Follow the automatic MMIO setup to build that revision with its matching patched QEMU and plugin before using it.

With Clang 18 or a compatible clang available, run from the FastDyn repository root:

fastdyn build-model --mmio-opt --no-vio \
  tests/models/elder_echo.c -o build/mmio-models

The outputs are build/mmio-models/elder_echo.so and build/mmio-models/elder_echo.mmio.json. The library retains its ordinary fastdyn_model callbacks and embeds a generated fastdyn_mmio_model operation table. The JSON report exposes the extracted operations for inspection; the runtime consumes the embedded table. Clang is required for this extraction option, while ordinary model builds retain their existing compiler selection.

The extractor currently accepts one C source per model, so the multi-source --name example above does not apply with --mmio-opt. Configure the generated library as the normal elder scroll, then extend the existing CPU configuration with this fragment:

[CPU.cpu0.plugins.mmio_opt]
enabled = true

The first execution path targets a single Cortex-M CPU. This is experimental: an accepted operation is not a proof that it preserves the original callback. Use an explicitly audited model, inspect its build and installation reports, and compare against ordinary execution. The complete workflow and reviewed limitations explain the extractor and guest-semantics boundaries. Leaving the plugin disabled keeps the same library usable through its ordinary elder callbacks.

Validate behavior at the boundary

A useful model check exercises reset state, width-sensitive reads and writes, boundary addresses, per-instance isolation, and interrupt ordering. Then run the target firmware path that motivated the model and compare its I/O against a recorded trace or known hardware behavior. Successful loading establishes ABI compatibility; successful firmware progress establishes only the behavior exercised by that run.

Source guide

Hardware and trace replay

FastDyn supports a practical progression from a board-dependent experiment to a reusable software model: execute firmware in QEMU, forward selected peripheral accesses to hardware, capture the resulting interaction, and replay it without asking the physical device for every response. A learned or hand-written elder model can then replace that peripheral while the rest of the experiment remains recognizable.

Two handlers implement the hardware and recording paths. passthrough forwards accesses through libhw. twintrace uses the same hardware mechanism for recording and a binary event tape for replay. Both share a process-level probe-session implementation, which centralizes probe ownership and interrupt coordination.

Prepare the hardware path

Build libhw with the normal setup command:

source ./setup.sh --build-qemu --build-libhw

A live run also needs a compatible board, debug probe, libhw backend, board-side monitor arrangement, and a firmware/configuration pair prepared for that target. The mere presence of a probe is not sufficient to make an arbitrary board a passthrough backend.

This is a routing fragment, to merge with that complete configuration:

[Device.Models.passthrough]
backend = "stlink"

[Device.physical_uart]
ranges = [["0x40004400", "0x400047FF"]]
irq = [54]

[[Device.physical_uart.handlers]]
model = "passthrough"
enabled = true

The interrupt value is a Cortex-M example: USART2's external IRQ 38 corresponds to exception 54 on the relevant STM32 target. Replace the address and IRQ with the actual peripheral description for your platform.

The current shared hardware session supports 1-byte and 4-byte transfers. It handles temporary halted-board conditions with a bounded retry loop, and resumes the board when its captured interrupt is served. Passthrough's current initialization registers IRQs from its first configured device only. Keep that constraint visible when constructing a multi-peripheral hardware configuration; do not assume all listed device interrupts are forwarded.

Record a tape

Change the selected device handler to twintrace, declare its backend, and set the existing CPU entry's recording mode:

# In the existing [[CPU.cpu0]] entry:
twintrace = "record"

# In the device section:
[Device.Models.twintrace]
backend = "stlink"

[Device.physical_uart]
ranges = [["0x40004400", "0x400047FF"]]
irq = [54]

[[Device.physical_uart.handlers]]
model = "twintrace"
enabled = true

This is a configuration edit, not a second CPU declaration. Disable the old passthrough handler on that same device. FastDyn rejects a configuration that enables both hardware-capable handlers for one device.

Recording writes MMIO information and interrupt notifications through FastDyn's I/O log. Retain the resulting io.log with the exact firmware image, configuration, model routing, and execution inputs. The event format carries instruction counts, program counters, addresses, values, sizes, and event types. Those fields make later divergence diagnosable.

Replay without the board

In the existing CPU entry, select replay and point at the captured text trace:

twintrace = "replay"
hardware_trace = "captures/reference/io.log"

Keep twintrace enabled for the devices replay should serve. During run preparation, the launcher converts the text trace into <work-dir>/replay_bin.ttbin, verifies it, and passes it to the native replay handler. Replay is available even when FastDyn was built without libhw. A run that still routes other devices through passthrough continues to require hardware for those devices.

FastDyn supports two useful arrangements:

ArrangementRoutingTape preparation
All-trace replayThe recorded peripheral interaction is served by twintrace; no passthrough handler remains enabledConvert the full recorded event stream
Target-only replaySelected devices use twintrace while others retain passthroughFilter by the replay devices' address ranges and IRQs

Filtering follows the current routing, rather than trusting a record-time handler label. That lets a trace captured under one arrangement support a later experiment that isolates a particular peripheral.

Interpret a replay failure

The replay handler consumes an ordered stream. It checks event type, address, access width, and write value under its current defaults; strict PC checking is disabled. Interrupt-taken and interrupt-served events are also checked. Cortex-M SysTick, exception 15, is excluded from this tape path.

On divergence, the diagnostic prints the current record index, expected event, and observed access. Start with the first mismatch. A changed firmware binary, a different initialization path, or an incorrect peripheral range can explain a mismatch long before the final visible failure.

A trace describes a recorded behavior. It does not generalize to every input sequence or every possible hardware state. Use replay for reproduction and controlled comparisons, then use a stateful elder model when the experiment needs behavior beyond the captured path. Instruction-count alignment helps coordinate the trace, but it does not establish cycle accuracy against the physical MCU.

Source guide

Physics and FMUs

FastDyn can execute a controller's firmware and its physical environment in one simulation. Firmware produces actuator commands, a plant model evolves, and the resulting sensor values return to the firmware. The maintained vehicle path loads an FMI 3 Co-Simulation FMU directly into the FastDyn QEMU plugin. The physics calculation needs no separate simulator process.

That arrangement is useful for control-software analysis: the executable being studied remains the target firmware, while the environment can be inspected, parameterized, and changed. Optional MAVLink helpers and viewers provide automation and visualization without owning the plant's state.

flowchart TD
  F["Firmware controller"] -->|"Actuator commands"| A["FastDyn firmware adapter"]
  A -->|"PWM inputs"| P["In-process FMI 3 plant"]
  P -->|"Sensor outputs"| A
  A -->|"Firmware data structures"| F
  T["QEMU virtual clock"] -->|"Advance before timer IRQ"| P

Build and select a plant

After completing Installation, run from the FastDyn repository root:

source ./setup.sh --build-qemu --with-rumoca
fastdyn run -c configs/copter462.toml

The setup prepares the pinned compiler and emulator dependencies. The configuration selects FastDyn.Copter; auto_build = true builds its FMU when needed. The same mechanism serves the Rover and Plane configurations described in Flight controllers.

This excerpt is already present in the copter configuration:

[FMU]
active = "quadrotor"
auto_build = true

[FMU.models.quadrotor]
model = "FastDyn.Copter"
model_file = "modelica/FastDyn/Copter.mo"
source_roots = ["third_party/common/modelica_models"]
output = "out/fmi3/Copter"
build = true
release = false

active selects a named entry. fastdyn run -c <config> --fmu <name> selects another entry for one run. To generate the artifact without launching the firmware, use:

python3 utils/build_fmi3_fmu.py --config configs/copter462.toml --fmu quadrotor

Keep the compiler revision, source models, and generated artifact together when recording an experiment. A successful export establishes that a model compiled, not that its parameters match a physical vehicle.

Keep model ownership clear

COMPOSE/CP Models owns the reusable physical models and the shared vehicle-interface direction. FastDyn owns delivery to firmware, guest execution, firmware-specific adapters, and experiment orchestration. A change to a sensor's physical behavior belongs in the model layer; a change to how a particular firmware consumes that reading belongs in its adapter.

The documented main snapshot still contains FastDyn-specific wrapper models under modelica/FastDyn/ and uses the pinned modelica_models dependency for base dynamics. It also contains FIRE composition profiles, where physics_composition.py invokes the external model composer and records compilation provenance. These are concrete existing integration paths; adopting a newer shared COMPOSE interface requires matching its exporter and FastDyn adapter together.

The P0/P1/P2 FIRE profiles expose different propulsion models. Use their manifests and validation records to determine the fidelity and compiler support of the selected profile. A profile filename alone is not evidence of a validated flight or of support for every vehicle geometry.

The runtime contract

The Python launcher prepares the FMU and derives the native library, instantiation token, resources, and value references from that same package. This avoids combining a new binary with stale metadata. Current package loading supports Linux hosts on x86_64 and aarch64; the host architecture is distinct from the architecture of the guest firmware.

The native backend loads the shared library with dlopen, creates the FMI 3 instance, sets parameters and initial inputs, and calls fmi3DoStep during execution. Its current vehicle contract includes these named variables:

VariablesMeaning in the maintained copter wrapper
pwmFour actuator command values
accel, gyroBody FRD acceleration in m/s² and angular velocity in rad/s
magBody FRD magnetic field in gauss
gps, vel_ned, yaw_degLatitude/longitude/altitude, NED velocity, and yaw
baro_altitude_m, baro_pressure_pa, baro_temperature_c, baro_climb_rate_mpsBarometric outputs
lat0, lon0, ground_alt_wgs84, earth_radius_mGeodetic-origin parameters

The launcher requires these names and configured parameter references. The runtime still assumes their expected types and shapes. It is a vehicle adapter, not an unrestricted importer for every FMI variable type.

Two implementation details matter when choosing experiments. The current backend accepts four PWM channels; do not infer a complete six-motor path from the presence of a hexa configuration. Its IMU callback fills the 17-element firmware batch using the current acceleration and gyro readings, so those slots are not 17 independently sampled historical observations.

Time and fidelity

The maintained ArduPilot configuration uses:

[Machine]
icount = { shift = 5, sleep = false, align = false }
timer_irq_period_ns = 1000000

At each periodic IRQ, FastDyn asks the FMU to advance to QEMU's current virtual time before delivering the interrupt. Actuator writes update staged inputs. The native backend limits each internal step request to 2 ms, subdividing a larger advance. With the configured 1 ms tick, the normal advance interval is already smaller.

Keep three quantities distinct: host execution time, QEMU virtual time, and the plant's integration interval. Changing the board tick changes what the firmware observes. Changing icount.shift changes the relationship between guest instruction execution and virtual time. Neither supplies cycle-accurate timing for a physical MCU.

Model validation should therefore check units, frame conventions, actuator ordering, initial conditions, and convergence as the integration interval changes. Also distinguish datasheet-derived parameters, calibrated parameters, and behavior validated against measurements. The supplied copter's motor lag, ground contact, and sensor biases are explicit model choices that can be studied and refined.

Extending the backend

phy_backend_t in virtuals/physics/phy.h defines the current native interface. Implement its applicable sensor, actuator, lifecycle, and advance_simulation callbacks, then register the backend in phy.c. Use the header rather than copying older prose signatures. Gazebo remains an alternative path for existing experiments; the in-process FMU path is the starting point for new vehicle work.

See Branch previews for newer integration work that is separate from this documented main revision.

Source guide

Flight controllers

The flight-controller examples put several FastDyn capabilities together: execution of embedded firmware, virtual instructions and modifiers, physical feedback, host automation, and observability. Courbet supplies firmware-specific bindings and mission assets. The native physics backend supplies sensor and actuator operations. The ordinary FastDyn configuration ties them into a run.

This chapter covers the main revision recorded by the book. Newer PX4 and INAV work appears in Branch previews.

Choose a starting configuration

ConfigurationGuest and physical pathDefault automation
configs/copter462.tomlArduCopter 4.6.2 with FastDyn.Copter FMUMAVProxy/MAVCesium and copter mission helper
configs/rover462.tomlArduRover 4.6.2 with FastDyn.Rover FMUMAVProxy/MAVCesium and telemetry health check
configs/plane462.tomlArduPlane 4.6.2 with FastDyn.Plane FMUMAVProxy/MAVCesium and telemetry health check
configs/px4_fmu_v6c_fire_p2.tomlPX4 FMUv6C ARM/NuttX bridge with a FIRE P2 plantGuest boot commands, MAVProxy/MAVCesium, and PX4 mission helper

The first three use the maintained Rumoca setup described in Physics and FMUs. The PX4 P2 profile additionally requires its configured FIRE model/compiler dependencies and a successfully generated P2 FMU.

Run each command from the FastDyn repository root:

source ./setup.sh --build-qemu --with-rumoca
fastdyn run -c configs/copter462.toml -o out/copter-demo

The first run may build the selected FMU. Look for the FMU backend-loading message, the configured periodic IRQ, and the MAVCesium address. The default copter mission starts near the configured KLAF/Purdue origin, uploads the mission, monitors flight, and ends after the landing workflow completes. Mission progress is the useful outcome to inspect; the mere appearance of a map does not establish a successful run.

For the other maintained ArduPilot examples:

fastdyn run -c configs/rover462.toml -o out/rover-demo
fastdyn run -c configs/plane462.toml -o out/plane-demo

Run these sequentially with their default ports, or use Multiple firmware instances for isolated parallel launches.

Understand the firmware boundary

The target CPU executes the embedded firmware image. FastDyn's hooks adapt selected hardware-facing operations to the host environment and physics backend. In the ArduPilot path, this includes sensor data delivery, actuator output, timing, storage, and communication support at selected firmware entry points.

That boundary preserves useful controller and scheduler behavior while avoiding the need to emulate every peripheral before an experiment can start. It also determines what a result covers: an adapter that supplies data at a driver boundary does not exercise the skipped SPI or I²C register transactions. Select an MMIO model when those transactions are the subject of the experiment.

Binding files are specific to the executable and its calling conventions. Replacing an ELF without regenerating and reviewing those bindings can redirect a hook into unrelated code. The common generator supports the supplied ArduCopter, ArduPlane, and PX4 profiles:

fastdyn-env/bin/python virtuals/physics/flight_controllers/courbet/prepare_execution_configuration.py \
  --profile virtuals/physics/flight_controllers/courbet/ardupilot/copter462/profile.toml

The generator resolves symbols, compiles virtual/modifier rules, validates the profile, and writes virtuals.txt, modifiers.txt, and firmware.sha256. Failed validation preserves prior output. ArduPilot profiles pin the supplied ELF digest where their rules retain absolute addresses; PX4 additionally checks the structure layouts and instructions consumed by its bridge. Hook selection and native callback behavior remain authored decisions.

PX4 on the embedded target

The generic Rumoca setup does not initialize the additional FIRE model submodule or fetch its portable Modelica Standard Library and FMI headers. Prepare those inputs and build the plant first:

git submodule update --init third_party/courbet_deps/fire_modelica_models
python utils/setup_fire_toolchain.py
python utils/build_fmi3_fmu.py \
  --config configs/px4_fmu_v6c_fire_p2.toml --fmu quad_p2

The build should print Generated FMU: on success. The configuration also points to the model repository's compiler-limitations record; resolve any plant-build failure before diagnosing guest firmware. The generator and build commands are separate checks from successful closed-loop execution.

With the P2 FMU available, launch:

fastdyn run -c configs/px4_fmu_v6c_fire_p2.toml -o out/px4-demo

The configuration executes the supplied ARM ELF on Cortex-M7 and initializes modules through boot.nsh. The bridge replaces selected sensor publications with FMU readings while real uORB distribution, NuttX scheduling, sensor processing, EKF2, and control code execute. Actuator outputs feed the plant. TELEM1 UART bytes are forwarded through UDP to MAVProxy and the host mission helper.

The mission helper checks telemetry and estimator readiness, requests mission mode and normal arming, starts the mission, and monitors landing/disarming. FASTDYN_PX4_READY means the boot-command sequence was delivered; it does not establish estimator readiness or a completed mission.

For diagnosis without host mission helpers:

fastdyn run -c configs/px4_fmu_v6c_fire_p2.toml --no-run-processes

Guest module initialization still runs. For an uninitialized NuttX console, explicitly clear the guest boot setting as well:

FASTDYN_BRIDGE_BOOT= fastdyn run -c configs/px4_fmu_v6c_fire_p2.toml --no-run-processes

The profile is a firmware bridge, not a complete Pixhawk6C peripheral model. Its sensor injection uses PX4's simulation publication path; SIH *_groundtruth topics therefore do not represent FMU ground truth. Small deterministic sensor dither prevents repeated ideal readings from triggering stale-sensor detection, but it is not a calibrated noise model. The current geodetic adapter also supplies equal MSL and ellipsoid altitudes because this plant has no geoid model.

Observe and customize a run

The default viewer is http://127.0.0.1:5000/mavcesium/. Its telemetry reflects the flight stack's reported position and attitude. Map assets may require network access. Use the console, mission log, and raw physical outputs alongside the viewer when diagnosing disagreement.

Configuration parameters control the initial location, mass/inertia, motor response, and sensor biases supported by the selected model. FASTDYN_PARAM_FILE and FASTDYN_MISSION_FILE select alternative files where the configuration uses those overrides. Keep the mission's origin, expected altitude convention, actuator ordering, and plant's initial state consistent.

For a concrete smoke check after setup:

FASTDYN_COURBET_CONFIG=configs/rover462.toml \
  tests/integration/courbet_fmu_vehicle_smoke.sh

tests/integration/courbet_mission_smoke.sh

The first checks a vehicle launch and telemetry path; the second exercises the copter mission. PX4 has separate bridge and mission checks under courbet/tests/. These checks establish integration properties in the simulator. Physical fidelity requires calibration and comparisons appropriate to the claim being made.

Source guide

World models

The world plugin connects firmware-visible actions to FMI 3 physical models. A firmware function can drive a physical input, another can sample a physical output, and FastDyn advances the model to the guest's current time before either action. The bundled example connects a GPIO-like output to an RLC circuit and returns capacitor voltage through an analog-input hook.

The model supplies physical behavior. FastDyn supplies the bridge to guest execution. This provides a small, concrete way to study how firmware responds to a changing environment before building an entire vehicle experiment.

Build the optional runtime

The plugin uses the tools/world submodule, which is optional and requires access to its repository. Its native component is included only when Meson finds both the world header and tools/world/build/libworld_model.so. A configuration can be parsed even when the native component was omitted, so build order matters.

After the normal FastDyn installation, run from the repository root. The firmware build also requires the Arm bare-metal compiler arm-none-eabi-gcc:

git submodule update --init --checkout tools/world
python3 -m venv tools/world/venv
tools/world/venv/bin/pip install -e tools/world
cmake -S tools/world -B tools/world/build -DWM_BUILD_TESTS=ON
cmake --build tools/world/build
cmake --build tools/world/build --target rlc_fmu
tests/firmwares/world_rlc_gpio/build.sh

Reconfigure the existing FastDyn build after the world library exists, preserving the options selected during your original setup:

meson setup --reconfigure build
ninja -C build
export LD_LIBRARY_PATH="$PWD/tools/world/build:$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fastdyn run -c configs/world_rlc_gpio.toml -o out/world-rlc

The firmware prints capacitor-voltage samples while it alternates the input level. Expect charging while the pin is high and discharging while it is low. It runs continuously; stop it with Ctrl-C. The trace and runtime log are under out/world-rlc/run-artifacts/world/.

Connect a physical endpoint

The existing example declares one FMU and gives its variables stable local names:

[CPU.cpu0.plugins.world]
enabled = true
step_ns = 100000

[CPU.cpu0.plugins.world.models.rlc]
path = "tools/world/examples/rlc/out/RLC.fmu"

[CPU.cpu0.plugins.world.models.rlc.parameters]
resistance = 10.0
inductance = 0.01
capacitance = 0.001

[CPU.cpu0.plugins.world.endpoints]
supply = { target = "rlc.voltage", direction = "in" }
vcap = { target = "rlc.output_voltage", direction = "out" }

FMU paths in this plugin resolve against the working directory. Running from the FastDyn root keeps the supplied paths valid. Endpoint targets use <model>.<variable>, where the variable belongs to the FMU's metadata.

The pin rules bind those endpoints to firmware functions:

[[CPU.cpu0.plugins.world.pins]]
at = "world_gpio_write"
kind = "digital_out"
endpoint = "supply"
register = "r0"
low = 0.0
high = 3.3

[[CPU.cpu0.plugins.world.pins]]
at = "world_adc_read"
kind = "analog_in"
endpoint = "vcap"
register = "r0"
scale = 1000.0

A digital output maps zero and nonzero register values to the configured physical levels. An analog input multiplies the physical output by scale and writes an integer to the guest register. Here, volts become millivolts. Choose a range and scale representable by the 32-bit register conversion; this is not a floating-point guest-return interface.

The supplied firmware exposes short stub functions so the hook's register effects survive the return. When adapting a real function, inspect its calling convention and remaining instructions. A later instruction that overwrites the register will overwrite the injected result too.

Preparation and execution

The Python preprocessor validates model, endpoint, and pin tables; resolves named triggers through the shared ELF analysis; and rejects conflicting pin addresses. It emits world.manifest plus ordinary FastDyn virtual rules. The native plugin constructs the world, resolves endpoint handles once, and registers world_digital_out and world_analog_in callbacks.

This uses FastDyn's regular extension mechanism. Model-specific parsing stays in the plugin, while the core handles virtual dispatch and artifact delivery. Multiple FMUs can be declared in the same world, with model connections passed to the world runtime. Their physical composition remains separate from connecting multiple firmware instances.

Advance on access

Before a pin callback reads or changes an endpoint, it advances the world to virtual_guest_time_ns. Repeated accesses at the same guest timestamp do no additional integration work. For an output change, the elapsed interval is integrated under the previous value, then the new value takes effect.

step_ns controls the world's communication quantum. The numerical consequence depends on the FMU: the bundled RLC implementation performs an integration step at that scale, while another FMU may substep internally. Check convergence when changing the quantum; a visually plausible waveform can still contain integration error.

Advance-on-access also defines an important boundary. A guest sleeping until a physics-generated interrupt cannot cause physics to advance through an access that has not happened. Such an integration needs an explicit periodic or event-driven advance mechanism. The RLC example does not claim to provide that autonomous interrupt scheduler.

Inspect the world

The observer plots trace artifacts and displays runtime events. To use the prepared observer example:

fastdyn run -c configs/world_rlc_observer_master.toml -o out/world-observer

Open the printed observer URL, normally http://127.0.0.1:8770. The observer is read-only: it does not advance the physical world. Its display is a rolling trace window, so increasing the display horizon and changing the integration quantum have different purposes.

The slave variant starts the guest paused so an external master can grant time:

# Terminal 1
fastdyn run -c configs/world_rlc_observer_slave.toml -o out/world-observer-slave

# Terminal 2
python3 utils/fastdyn_cosim.py /tmp/fastdyn-observer.qmp --slice-ms 5 --slices 40

See Multiple firmware instances for the budget protocol.

Current contract

The pin adapter currently accepts ARM register names and scalar Float64 endpoints. It does not implement an ADC's complete register map, DMA behavior, or peripheral interrupt logic; an elder model can supply those layers when needed. It also lacks coordinated guest-and-world snapshot restoration, so a guest-only in-process fuzzing reset cannot restore a consistent physical experiment. The documented world runtime rejects early-return/event-mode FMUs; use the pinned exporter/runtime contract for this optional path.

Source guide

Multiple firmware instances

FastDyn provides two complementary ways to run several firmware instances. fastdyn swarm launches isolated workers for parallel experiments. The co-simulation utilities let an external master grant virtual time to individual guests and synchronize their observation boundaries. Together, these give experiments a path from independent repetitions to explicitly coordinated systems.

Choose the mechanism according to the experiment:

GoalStarting mechanismWhat you supply
Repeat a mission or fuzzing workload concurrentlyfastdyn swarmConfigured workload, parameters, inputs, and result analysis
Advance a guest in controlled virtual-time slicesBudgetMaster or fastdyn_cosim.pySlice schedule and any external model
Keep several guests at common boundariescosim_lockstep.pyBase slave configuration and time quantum
Model communicating devices or firmware sharing a plantA master plus explicit device/transport connectionsCommunication semantics, exchange policy, and shared state ownership

The existing lockstep example synchronizes time. It does not automatically connect UARTs, radios, buses, or actuators between its guests. The Advanced chapter FastDyn as a secondary simulator gives the complete setup and QMP lifecycle at e44dca2. Tempo covers a separate scheduler and its implemented mock-participant workflows.

Launch an isolated campaign

After preparing the selected firmware and FMU, inspect a worker plan without launching QEMU:

fastdyn swarm -c configs/copter462.toml -n 2 \
  -o out/swarm/copter --base-port 15000 --dry-run

Remove --dry-run to launch it:

fastdyn swarm -c configs/copter462.toml -n 2 \
  -o out/swarm/copter --base-port 15000

The supervisor assigns separate work directories, QMP sockets, RAM backing files, logs, and standard service ports. With the default stride of 20, worker 0's MAVCesium address is http://127.0.0.1:15003/mavcesium/, and worker 1's is http://127.0.0.1:15023/mavcesium/. Logs appear in out/swarm/copter/logs/worker-000.log, worker-001.log, and so forth.

The port assignment for worker index i starts at base_port + i * port_stride:

OffsetService
+0QEMU monitor
+1, +2Firmware and GCS MAVLink endpoints
+3MAVCesium
+4, +5Optional Rumoca HTTP and WebSocket endpoints
+6GDB

The supervisor checks those ports before launch. A custom helper or device model must likewise avoid hardcoded shared files and endpoints. Standard worker isolation does not automatically rewrite every resource created by application-specific code.

Drive one guest as a slave

The shipped slave example uses the RLC world model. Complete the secondary simulator setup, including its pinned backend and world build, before using these commands. Its key machine settings are:

[Machine]
qmp_socket = "/tmp/fastdyn-cosim.qmp"
stop_on_start = true
icount = { shift = 5, sleep = false, align = false }
exact_budget_stop = true

Start the guest and its master in separate terminals:

# Terminal 1
fastdyn run -c configs/cosim_slave.toml -o out/cosim

# Terminal 2
python3 utils/fastdyn_cosim.py /tmp/fastdyn-cosim.qmp --exact --slice-ms 20 --slices 6

The guest starts paused. The master grants slices and reports the virtual time actually reached. A pending slice is asynchronous: the immediate response to run-for is an acknowledgment of the grant, not evidence that execution has finished.

Respect the budget protocol

The patched QEMU provides three relevant commands:

QMP commandMeaning
run-for with budget in nanosecondsAdd a positive duration to the maintained cumulative execution deadline and resume
query-budgetRead totalbudget, actual currenttime, and whether exact mode is enabled
set-budget-mode with exactSelect the stopping mode for the current run

The master waits for the STOP event after each grant, then queries the budget. If a guest terminates instead, the master must handle shutdown rather than waiting indefinitely for a pause.

In the default stopping mode, the guest can stop beyond the deadline, and the backend can adjust its maintained deadline when it detects exhaustion after that time. Read both the deadline and actual reached time after each stop. The CLI's --exact, or BudgetMaster(..., exact_stop=True), actively selects synchronous stopping through QMP. At e44dca2, the native enabling call for exact_budget_stop = true is commented out; the configuration field alone is insufficient. Exact stopping is a synchronization property of the emulator, subject to its instruction-time granularity, not a hardware-cycle accuracy guarantee.

For a custom Python master, this is runnable from the repository root while the guest above is waiting:

PYTHONPATH=utils python3 - <<'PY'
from fastdyn_cosim import BudgetMaster

with BudgetMaster("/tmp/fastdyn-cosim.qmp", exact_stop=True) as guest:
    for _ in range(10):
        reached_ns = guest.run_slice(1_000_000)
        print(reached_ns, guest.budget_ns, guest.status)
PY

The client also separates grant() from wait_for_slice(), allowing a master to grant every participant before waiting for any of them.

Synchronize several guests

The supplied example derives unique QMP sockets, RAM files, and output directories from its base slave configuration:

python3 utils/cosim_lockstep.py \
  --instances 2 --slice-ms 0.5 --slices 40 --exact \
  --work-dir out/lockstep

It launches through the standard fastdyn-env/bin/fastdyn installation, grants each guest the same interval, waits for every guest to stop, and reports their time spread. In exact mode, the expected outcome is agreement at the boundaries. The utility is an example for the supplied single-RAM-file configuration; its config rewriting is not a general scheduler for arbitrary machine layouts.

To create a coupled experiment, add the exchange logic at that barrier: collect outputs, apply the shared physical or communication model, and publish the next inputs before granting more time. Define whether messages produced during an interval become visible immediately or only at the next boundary, who owns the shared state, and how faults or a terminated participant affect the run. Those choices determine the experiment's causality.

The budget interface is monotonic and does not provide rewind. Likewise, restoring guest memory alone does not restore an external plant or message queue. Preserve the full state needed by the experiment or restart its participants consistently between trials.

Verify the chosen property

The repository provides tests/integration/courbet_swarm_smoke.sh for parallel vehicle launches and tests/integration/run_cosim_slave_smoke.sh for budget stops and lockstep. At e44dca2, the latter's exact-mode stage relies on the inactive configuration-only switch; use the explicit QMP selection shown above for a controlled run. See the secondary chapter's validation limits for what was checked. A successful swarm check establishes launch isolation; a successful budget check establishes synchronization. Communication correctness and physical fidelity require checks for the connections and models in the experiment.

Source guide

Branch previews: INAV and PX4

Two development branches extend the flight-controller examples beyond this book's main revision. Both execute embedded board firmware and connect it to an FMU loaded inside the FastDyn/QEMU process. The controller, scheduler, and physical feedback can run together without a separate physics server.

Use the matching source revision for the commands below. These features and results should not be assumed to exist on the core chapters' f9666d7 baseline; a later main-branch merge also needs its own source and validation review.

PreviewReviewed FastDyn revisionFocus
INAV3910be12b82443efe8abb75ef89aa02f5ef047f4MATEKF405 firmware, receiver input, sensor conversion, takeoff and receiver-loss checks
PX40e13b73986a66270a6d8452b2c0147af7b874d29Five explicit FMUv6C version profiles, autonomous missions, and optional persistent translation caching

The reported outcomes below come from the pinned repository's validation records and test definitions. They were reviewed for this book; the book-writing process did not rerun the flight demonstrations.

Use a separate checkout for each preview so its build products and generated bindings stay with its source revision. For INAV:

git clone --branch codex/inav-fmu-integration \
  https://github.com/boardrunner2049/FastDyn.git FastDyn-inav
cd FastDyn-inav
git checkout --detach 3910be12b82443efe8abb75ef89aa02f5ef047f4

For PX4, from the parent directory where you keep checkouts:

git clone --branch px4-v1.17-firmware-slicing \
  https://github.com/boardrunner2049/FastDyn.git FastDyn-px4
cd FastDyn-px4
git checkout --detach 0e13b73986a66270a6d8452b2c0147af7b874d29

The setup commands in each section run inside its corresponding checkout.

INAV: a complete path from receiver to plant

The INAV profile runs Cortex-M4 firmware for MATEKF405 against FastDyn.Copter. Its source declares version 10.0.0, at upstream commit d0c611e040887940226c9536bc84a3795ef9e800. The version record identifies this as development source, not a verified 10.0.0 release tag.

This firmware requires the supplied source compatibility patch. It enables a 16 KiB RAM settings store, simulated GPS and other sensor interfaces, MSP receiver input, and an AUX1 arm switch. It also marks ideal simulated accelerometer and compass values as calibrated. Settings reset each run. The normal gyro calibration, estimator, filtering, PID, and motor mixer still execute.

The MPU6500 path is especially useful: the bridge provides device identity and raw sensor bursts, then lets INAV's actual MPU driver perform alignment and filtering. It compensates for the board's 180-degree sensor mounting and converts the FMU's FRD values into the driver's raw counts. Other selected board initialization and bus operations are bypassed by firmware-specific hooks. This boundary supports controller experiments without requiring a complete STM32 peripheral model.

Run the profile

From the root of the INAV revision, with the usual native build dependencies installed:

source ./setup.sh --build-qemu --with-rumoca --skip-optifuzz
python utils/setup_fire_toolchain.py
fastdyn run -c configs/inav_matekf405.toml -o inav-fastdyn_work

Rumoca requires its pinned nightly Rust toolchain, rustfmt, and the libudev development files. The toolchain helper supplies pinned FMI headers for packaging. The run builds or uses the Copter FMU and advances it every millisecond of QEMU virtual time. INAV configures its own SysTick; this FMU timer does not inject a second one.

In another terminal on the same host, send receiver frames:

python virtuals/physics/flight_controllers/inav/send_rc.py \
  --arm --throttle 1500 --duration 30

The helper first sends disarmed input, then arms and raises throttle. The receiver endpoint is fixed at 127.0.0.1:14590, so run one such profile at a time. Its packet is FDRC followed by eight little-endian unsigned 16-bit PWM values: AETR, then AUX1 through AUX4. Values must be 900–2100 microseconds; AUX1 at 1700–2100 requests arming. Stopping frames exercises INAV's receiver timeout and failsafe.

What the checks establish

python -m pytest -q tests/integration/test_inav_fmu_smoke.py

# After building out/fmi3/Copter/FastDyn_Copter.fmu:
FASTDYN_RUN_INAV_COPTER=1 \
  python -m pytest -q tests/integration/test_inav_fmu_smoke.py

The default integration check boots the real firmware against a deterministic test FMU. It inspects calibrated and filtered sensor values, GPS fix, and the initialized mixer; rejects an oversized receiver packet; arms through receiver input; and confirms that throttle reaches the FMU motor input.

The optional Copter check uses the actual plant. It requires normal receiver arming, a climb greater than one metre, receiver-loss failsafe, and all four motor commands returning to at most 1000 microseconds. The version record reports that this check was rerun after fixing the firmware's 64-bit microsecond return convention.

These checks establish a useful closed feedback loop and a specific failure response. Sustained flight stability, all-axis response, mission upload, telemetry interfaces, and physical sensor calibration are not established by this profile. Each rebuilt ELF also needs its own symbol/layout review and checksum; absolute hook addresses are not portable.

PX4: one board, five explicit firmware profiles

The PX4 branch runs unmodified ARM/NuttX ELFs built from official source tags, with symbols and DWARF retained. Runtime slicing bypasses selected unavailable hardware operations and bridges selected firmware data boundaries. NuttX scheduling, uORB, EKF2, commander, navigation, control, and MAVLink continue to execute in the guest.

Sensor samples enter at uORB publication, above the physical SPI/I²C sensor drivers. PX4's simulation publishers own sample scheduling and metadata; the bridge replaces selected numeric fields with FMU values. Actuator publications drive the P2 plant. This makes the profile useful for flight-stack behavior while leaving physical driver transactions outside its coverage.

The pinned version-sweep record distinguishes successful boot/sensor/motor checks from complete autonomous missions:

PX4 versionProfile directory under courbet/px4/Recorded result
v1.13.3fmu_v6c_v1_13Boot, sensors, and motor output; mission develops a compass-calibration error
v1.14.4fmu_v6c_v1_14Boot, sensors, and motor output; navigation failure during horizontal flight leads to failsafe landing
v1.15.4fmu_v6c_v1_15Autonomous mission, landing, and disarm
v1.16.2fmu_v6c_v1_16Autonomous mission, landing, and disarm
v1.17.0fmu_v6cAutonomous mission, landing, and disarm; default in this revision

Version handling includes real ABI differences. Older GPS topics contain scaled integers; later ones use doubles, with further structure changes in v1.17. The generator checks each ELF's DWARF and HRT instruction pattern before producing its bindings. A successful v1.17 run therefore does not automatically qualify another binary.

Run and inspect a mission

Prepare the native build and FIRE P2 dependencies described in Flight controllers, then use the selected revision's wrapper:

virtuals/physics/flight_controllers/courbet/px4/fmu_v6c_v1_16/run.sh

# Run separately for the default v1.17.0 profile:
virtuals/physics/flight_controllers/courbet/px4/fmu_v6c/run.sh

Each wrapper validates its bindings, builds the plugin, derives a temporary version-specific TOML, and launches the common machine and plant. The generator requires Python-enabled GDB and pyelftools. Wait for mission progress through normal arming, takeoff, waypoints, landing, and disarm. The viewer at http://127.0.0.1:5000/mavcesium/ provides position and attitude; FASTDYN_PX4_READY alone only confirms that boot commands were delivered.

After a successful P2 FMU build, run the stronger check:

fastdyn-env/bin/python \
  virtuals/physics/flight_controllers/courbet/tests/smoke_px4_mission.py \
  --version 1.17.0

It retains console output, viewer messages, and summary.json under out/px4-mission-*. Success requires the actual mission to finish landed and disarmed, at least 10 metres of relative altitude, 5 metres of horizontal movement, 50 attitude samples, a working viewer, and a successful process exit. This test uses --no-build-fmu internally, so it needs the plant built beforehand.

QEMU virtual time drives the FMU and PX4 HRT service; NuttX SysTick remains separate. Deterministic sensor dither avoids stale-sample detection but does not supply calibrated noise. SIH ground-truth topics describe SIH's internal plant, not this FMU, and the current altitude adapter has no geoid correction. Preserve these distinctions when comparing simulated and measured flight data.

Optional persistent translation caching

The reviewed PX4 revision also adds FastDyn configuration support for the QEMU fork's persistent TCG cache:

[Machine]
supercache = "../cache/firmware.sc"
supercache_flat = false

The preview's pinned QEMU submodule does not contain Supercache. The advanced Supercache chapter pairs this frontend with the separately pinned QEMU implementation and gives the complete build and cold/warm workflow. Begin with normal mode; flat mode additionally requires immutable executable guest memory and its documented address-span limits.

The cache path is relative to the TOML. FastDyn records effective configuration, generated instrumentation, and native input identities in an adjacent manifest, and discards stale caches when those inputs change. Large native files use path, size, and modification time rather than a complete content digest. Use a trusted filesystem and separate cache files for independent workers.

This optional mode requires ASLR to be disabled for the launched process, as documented by that revision. Treat it as a measured optimization for a particular workload; the branch's existence does not establish a universal acceleration factor.

Source guide

Debugging and observability

FastDyn exposes both sides of a firmware experiment: the guest's execution and the host machinery that makes the run possible. Use the smallest observation that answers the immediate question. A register print can establish that a hook fired; an RTOS activity record can establish that scheduling progressed; an FMU heartbeat can establish that firmware and physics are exchanging data.

All commands below assume an activated FastDyn environment and the FastDyn repository root. Paths such as configs/target.toml refer to your reviewed target configuration.

Start with the run record

Assign a distinct work directory before debugging:

fastdyn run -c configs/minimal.toml -o out/debug-minimal

The generated virtuals/virtuals.txt and virtuals/modifiers.txt show the addresses and operations actually handed to the native runtime. These are the first place to look when a symbolic trigger or preprocessing-generated hook does not behave as expected.

Other useful artifacts depend on the enabled features:

ArtifactWhat it answers
run-artifacts/<plugin>/What did host preprocessing discover and generate?
io.logWhich peripheral transactions did device handling observe?
qemu.logWhat did the selected QEMU -d logging categories report?
fastdyn_timing.jsonlWhich instrumented host phases ran, and how long did they take?
bbl.txt, optionally edges.txtWhat cumulative coverage did the enabled coverage implementation record?
Plugin result filesWhat functions, accesses, tasks, or violations did that plugin observe?

An absent file may mean the feature was disabled, the build lacks it, or the run never reached its initialization point. The minimal configuration uses log_options = "none", so it does not request instruction logs.

Control host and native logs

Global logging options precede the subcommand:

fastdyn -v run -c configs/minimal.toml -o out/debug-minimal
fastdyn --log-level fastdyn.targets=DEBUG run -c configs/minimal.toml -o out/debug-target
fastdyn --log-level fastdyn.native=DEBUG run -c configs/minimal.toml -o out/debug-native

-v selects debug output and -q selects warnings and errors; they are mutually exclusive. Repeat --log-level to adjust multiple logger namespaces. FASTDYN_LOG_LEVEL supplies the default when no CLI level is selected.

To retain Python-side logs, use a file outside the work directory that the runner may replace:

mkdir -p out/logs
fastdyn --log-file out/logs/minimal-python.log \
  run -c configs/minimal.toml -o out/debug-minimal

The file records Python debug messages regardless of the console threshold. Native plugin output is written by QEMU directly and is not copied into that Python log file. Capture both process streams when you need the complete launch transcript:

fastdyn run -c configs/minimal.toml -o out/debug-minimal \
  > out/logs/minimal-console.log 2>&1

Native debug statements additionally require a build with DEBUG_PRINT=true.

Attach GDB to a known point

For a target you have configured, edit its existing [Machine] table:

[Machine]
enable_gdb = true
gdb_port = 1234
stop_on_start = true
launch_gdb = false
print_command = true

This is a settings fragment, not a complete configuration. stop_on_start pauses before execution; the firmware will appear idle until the debugger continues it. In another terminal, load the exact ELF and attach. For the bundled minimal target:

gdb-multiarch tests/sample_binaries/RTOS/RTOSDemo.axf
target remote :1234
break main
continue
info registers

Keep symbol files synchronized with the loaded binary. If a trigger was taken from another build, a valid-looking address can silently observe a different instruction. The generated rules, disassembly, and current PC give complementary checks.

monitor_port controls the textual QEMU monitor; qmp_socket controls its machine-readable QMP interface. They are distinct from GDB. Setting monitor_port = 0 disables the default TCP monitor. The default QMP socket is made run-specific, but a manually configured fixed socket remains your responsibility when launching concurrent runs.

Inspect through Ghidra

The repository supplies a custom GDB launcher under decompilers/ghidra/ for inspecting an executing target through Ghidra's debugger. Load the project corresponding to the exact guest image and verify its address mapping before attaching. The pinned integration note identifies the launcher to replace; adapt that integration to your installed Ghidra layout rather than assuming every version uses the same path.

Move from instructions to behavior

A complete instruction trace is often unnecessary. Choose an observer with the right scope:

  • FunctionCounter identifies frequently reached functions.
  • FunctionTracer records function-entry activity selected by its preprocessing.
  • VariableWatch observes selected data accesses.
  • RTOS introspection produces task and scheduling records and can serve the activity monitor.
  • ObjectSan checks supported object-boundary conditions in its instrumented target.

Their prerequisites and example configurations are covered in tracing and sanitizers and RTOS introspection. A source name alone is insufficient if the plugin needs DWARF information that the image does not contain.

Diagnose the first failing layer

SymptomFocused next check
Executable or plugin not foundInspect the logged QEMU selection, plugin path, build metadata, and active environment.
Boot stalls immediatelyVerify CPU features, vector/entry settings, ELF identity, and mapped writable memory.
CPU waits at the first instructionCheck stop_on_start and continue through GDB.
Peripheral polling never finishesInspect the status-register model, relevant interrupt delivery, and expected side effects.
A hook never runsResolve its PC in this ELF, then inspect generated rules and control flow.
Vehicle run exits earlyInspect FMU initialization and the exit status of helpers marked terminate_run_on_exit.
A second run behaves differentlyCheck external RAM backing, plugin state, input files, and helper lifecycle.

FastDyn sends SIGINT to QEMU on an orderly stop and waits up to exit_timeout_ms, default 5000 ms, before killing it. Prefer that path when collecting plugin exit artifacts. fastdyn loop restarts runtime failures, which is useful for campaigns but can obscure a single failing launch; use run while diagnosing the cause.

Source guide

Fuzzing firmware and physical behavior

FastDyn lets a fuzzing campaign choose the execution boundary that matters: a parser, a persistent task loop, a device input path, or an entire vehicle mission. Execution controls, input injection, coverage, snapshots, and the physics backend supply different parts of that experiment.

The current tree contains two main workflows. Native LibAFL/AFLNet integration drives repeated firmware input processing. OptiFuzz/CP-Explore mutates parameters and evaluates mission behavior through the ArduPilot and FMU path. They use different execution boundaries and feedback; select one according to the property being investigated.

Choose a campaign boundary

WorkflowInput and boundaryMain feedback
Firmware loop or handlerRegisters, memory, streams, and modeled device inputs around chosen PCsCoverage, configured assertions, crashes, timeouts
Stateful protocolSequences of messages through an AFLNet-compatible target harnessProtocol feedback and firmware execution outcomes
Vehicle missionParameter mutations applied through mission helpers to firmware plus a plantPhysical traces, temporal properties, mission outcomes, optional coverage

A useful harness begins after the required initialization and ends after one meaningful input has been processed. That avoids repeatedly paying for unrelated boot work while retaining the state required by the selected behavior.

Task-loop fuzzing

Embedded tasks often run forever. FastDyn's existing virtuals and modifiers can select an iteration boundary, redirect execution, arrange inputs, and return to a repeatable point. The native fuzzer supplies snapshot and synchronization callbacks; the schema layer can install those callbacks from JSON.

For a task or loop, the practical workflow is:

  1. Establish a working execution path to the relevant code.
  2. Identify the state it needs, including globals, stack, queue state, and peripheral inputs.
  3. Choose snapshot and completion PCs, with all normal exits covered.
  4. Inject the inputs that the loop consumes, then collect outcomes after one iteration.
  5. Replay interesting inputs and check whether the resulting state is feasible for the real system.

The implemented controls support task-focused execution with explicitly selected boundaries and state. They do not automatically discover every task, derive its complete dependencies, or isolate arbitrary firmware loops. Binary loop and MMIO analyses can provide evidence; the harness still needs validation against the selected firmware.

Coverage PCs are logged from translated code into a circular buffer and drained by a tracer thread. That keeps the event producer in the translated path and supports an in-process LibAFL consumer. The current buffer and synchronization implementation should not be described as a proven lossless logger for arbitrary producer rates. Coverage identifies execution progress; it is not by itself a complete record of every instruction or scheduling event.

Build the native input backend

After the basic source setup, use a plugin built with the appropriate backend. LibAFL requires Rust/Cargo:

make DEV=true LIBFUZZ=true

make recreates the build directory, so include the other required feature flags if this same plugin must retain physics or hardware support. AFLNET=true selects the modified AFLNet integration and requires the corresponding external build at aflnet_path. Do not enable both input backends in one build without first resolving their shared backend interface.

Enable a schema-driven LibAFL campaign in the target's existing machine table:

[Machine]
fuzzing = true
coverage = true
fuzzing_schema = "schema.json"

coverage = true alone is observation mode: fuzzing = false avoids starting the input backend. The plugin must still include the coverage implementation needed by that experiment. The default basic build does not include the LibAFL coverage writer.

Describe structured inputs in JSON

The following is a schematic ARM32 harness, not a runnable profile for the bundled firmware. Replace all PCs and the destination with locations verified in your target:

{
  "flow": {
    "snap": { "at": "0x08002000" },
    "sync": [
      { "at": "0x08002080", "resume": "0x08002000" }
    ]
  },
  "fields": [
    {
      "name": "mode",
      "location": "reg(0)",
      "type": "uint",
      "size": 1
    },
    {
      "name": "payload",
      "location": "0x20001000",
      "type": "data",
      "size": 16
    }
  ]
}

flow.snap establishes the per-input boundary. Each entry in the nonempty flow.sync array ends an iteration and supplies the resume PC. An optional flow.state provides a longer-lived initialization snapshot. Direct fields are injected at the snapshot unless assigned to a hook.

The schema has four top-level sections: flow, fields, streams, and hooks. Its loader rejects unknown or duplicate properties and inconsistent references. reg(N) is the register-destination form. A location such as r2 + 4 is a memory address computed from register 2. Ordinary pointer dereferences are little-endian 32-bit reads in the current implementation.

Fields support integer, float, and raw data types, constants, numeric ranges, and selected integer values. Computed length and checksum fields preserve message structure. Streams deliver a sequence incrementally, such as bytes returned by a UART function; hooks select where those bytes are injected. A checksum can cover previously emitted stream bytes, so protocol order matters.

The current register and snapshot machinery includes ARM32 and Cortex-M assumptions. Validate support before applying this harness to another architecture. A snapshot also needs the relevant mutable state: restoring selected guest memory does not automatically rewind every external service, physical board, or arbitrary device-model state.

Run a mission-level campaign

For the maintained FMU workflow, from the FastDyn repository root:

source ./setup.sh --build-qemu --with-rumoca
cd virtuals/fuzzer/libafl_phi
FASTDYN_OPTIFUZZ_SMOKE=1 FASTDYN_OPTIFUZZ_DRY_RUN=1 \
  cargo run --bin baby_fuzzer

The dry run checks command wiring without launching QEMU. It still requires the Rust dependencies. To run the default copter campaign from that crate directory:

cargo run --bin baby_fuzzer

The default backend is fmuv3 and the default configuration is configs/copter462.toml. Per-execution artifacts go under out/optifuzz/execution-<n> in the FastDyn work tree. Mission helpers receive the mutation file through FASTDYN_OPTIFUZZ_MUTATION_BIN and apply the named parameters. Physical-property handling lives in the crate's observer code and stl_formulas.txt.

Select another vehicle using FASTDYN_OPTIFUZZ_VEHICLE and FASTDYN_OPTIFUZZ_CONFIG. FASTDYN_OPTIFUZZ_SWARM_INSTANCES=2 or greater launches isolated workers through fastdyn swarm. This scales campaigns; it does not connect the vehicles into one physical world. Enable FASTDYN_OPTIFUZZ_COVERAGE=1 only with a compatible coverage-enabled plugin.

Interpret a finding

Retain the exact firmware, configuration, schema, model versions, input, and property definition. First replay the failure under the same harness. Then minimize the input and determine whether the state or event sequence is reachable under the intended device, protocol, and physics constraints. Direct register or memory mutation can expose a real bug while also allowing states that a deployed device could never produce.

A mission-property violation and a memory-safety crash are different results. Report the violated property, observed trace, and reproduction boundary rather than treating every negative robustness score as a firmware crash.

Source guide

Measure and improve performance

FastDyn provides several mechanisms that can reduce avoidable work: shared host-analysis sessions, prepared runtime artifacts, inline modifier operations, in-process model execution, incremental model builds, and parallel independent campaigns. Their value depends on the workload. Measure the complete experiment as well as the boundary being optimized.

This chapter describes a measurement workflow. It does not claim a universal speedup or report a new benchmark result.

Name the quantity first

QuantityWhat it answersWhat it does not establish
Host wall-clock durationHow long the experiment costs on this hostGuest-realistic execution timing
Preparation phase durationTime spent parsing, analyzing, building, and launchingSteady-state callback cost
Guest virtual timeTime visible to modeled firmware eventsPhysical CPU cycle accuracy
Explicit co-simulation budget/progressHow much scheduled guest work was admittedUniversal hardware instruction timing
Plant simulation timeHow far the physical scenario evolvedHost performance
Completed trials per secondCampaign throughput at the defined completion conditionEquivalent trial behavior by itself

The native virtual_icount() helper is a separate implementation detail. In the inspected main revision it returns FastDyn's internal counter, whose increment callback is enabled with twintrace; it may remain zero in ordinary runs. Do not substitute it for the co-simulation protocol's progress accounting or assume every trace's icount field is a universal retired-instruction count.

Start with phase timing

Add or adjust the existing profiling table in an experiment configuration:

[Run.profiling]
timing = true
timing_echo = true
python = false
perf = "off"
fmu = true

Run the configuration with a dedicated work directory, then summarize its event log:

fastdyn timing-summary out/experiment/fastdyn_timing.jsonl

The filename above assumes that the experiment used -o out/experiment. Timing records include phase names, durations, process identities, and status. The runner records preparation and execution phases; optional components contribute their own events. JSONL fields such as duration_s, time_monotonic_s, and time_wall_s are in seconds. The native guest-time API and scheduling fields ending in _ns use nanoseconds.

Phase intervals may nest or overlap across processes. Adding every reported duration can double-count work. Use the enclosing run interval for end-to-end cost and the component intervals to explain it. Report failures and early exits separately from successfully completed experiments.

Profile a specific remaining bottleneck

To inspect Python helper scripts and QEMU on a compatible Linux host, use:

[Run.profiling]
timing = true
python = true
perf = "record"
perf_frequency_hz = 99
fmu = true

The Python wrapper uses cProfile for supported script commands. QEMU profiling uses Linux perf when it is available and permitted. Profile outputs live under the run's profiles/ directory. Read the actual filenames reported by the run before opening them with pstats or perf report.

Profilers themselves affect cost. Use them to locate work, then repeat the measurement with the selected production instrumentation settings. Enabling Python profiling does not magically profile native code, and a perf request that cannot run is not a captured profile.

Compare equivalent work

Before timing two variants, establish that both reach the same completion condition with equivalent relevant behavior. A variant that returns sooner because it skipped a controller update or stopped on an error is not a speedup.

Keep the following fixed unless the experiment explicitly studies them: firmware and compiler build, QEMU and FastDyn revisions, machine configuration, model implementation, initial state, inputs, virtual-time policy, enabled observations, and termination rule. Keep host configuration and worker concurrency in the record as well.

Use separate trials for cold preparation and warm/incremental work. An FMU build or a first model compilation can dominate an initial run; a later run that reuses artifacts answers a different question. Measure both when both matter to users.

For each comparison, report the baseline and variant durations and the chosen summary across repeated successful runs. Define the arithmetic explicitly:

speedup = baseline_duration / variant_duration
overhead_percent = 100 * (variant_duration / baseline_duration - 1)

The comparison is meaningful only for the stated baseline. Comparing a full environment against a permissive stub also changes behavior and fidelity, which must be explained separately.

Where to look for improvement

Repeated analysis. Reuse the run-scoped host-analysis session rather than reopening the ELF and rebuilding the same indexes in each preprocessor. Keep feature-specific planning outside the shared fact services.

High-frequency callbacks. Count how often an event occurs and how much work its handler performs. A small cost in a polling loop may dominate a larger initialization operation. Inline device modeling covers the legacy manual finline path in a lab pinned to 5b8bf3d; the JIT patcher covers admitted register-only guest instruction fragments. Automatic MMIO optimization covers the experimental mmio_opt implementation reviewed at e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576, including its separate correctness limits.

For the automatic path, retain discovery.json and installation.json along with phase timings. The native report distinguishes prepared and registered sites from fast and fallback execution counts. Registration alone does not establish that a site used the fast arm. The integration script compares its specific million-read workload with substitution enabled and disabled; it is a workload-specific demonstration, not a general equivalence or speed guarantee.

That comparison also changes observation volume: the fast arm bypasses ordinary device dispatch, per-access logging, and MMIO observer notification. Report the reduction in dispatch and logging work together, and decide whether the experiment requires those observations before comparing durations. Current code declines read substitutions when an observer is active and uses a live guard for observers registered after translation; the fast path without observers still skips ordinary per-access logging.

Saved MMIO PC and fixed-PC redirect hot paths. The current main revision passes a scalar saved_pc through the QEMU MMIO exporter instead of allocating a register-value buffer on every ordinary MMIO callback. A separate ARM32 optimization chains a strictly eligible r15 <- immediate modifier directly to another translated block. These optimize different vCPU paths and do not require automatic MMIO substitution. See Hot-path optimization contracts for the exact architecture contracts, disabling switch, test commands, and source-recorded measurements. Its 1.1169× ordinary-MMIO and 2.565× redirect-loop median ratios come from different bounded workloads, not general firmware throughput measurements.

Repeated translation. Supercache covers persistence and reuse of translated code in the separate backend that implements it. Distinguish a cold cache population run, a subsequent reuse run, and the complete experiment duration. Keep firmware, backend, plugin, machine, and instrumentation identities fixed; inspect cache compatibility and invalidation before attributing a timing difference to reuse.

Offline native-code optimization. The Supercache optimizer operates on a captured snapshot on the scopt branch. Measure pass-specific benefits against the same unoptimized warm cache: identity output is the no-change control, while accepted layout, cross-block, state-sync, and host-inline artifacts have distinct contracts. Keep capture, profiling, optimization, and validation costs separate from the final timed run. A published artifact or accepted inline site establishes a completed transformation; measured throughput still needs a successful matched workload and equivalent observations.

Firmware binary optimization. FirmBOLT applies an extended BOLT pipeline to the firmware ELF and checks which emitted bodies can be published under the selected firmware contract. Record whether the policy preserves modeled guest instruction count or explicitly relaxes it. Count installed bodies and changed bytes separately from timing results, and compare the same completed work and ordered observations. Its recorded Cortex-M publication checks and x86-64 application measurements exercise different targets; one cannot establish the other's performance.

Observation volume. Function traces, register logs, MMIO observations, and detailed QEMU logs can materially change throughput and output volume. Select the evidence the experiment needs. The current finite logging buffer and drain thread do not establish universal lossless observation under arbitrary load.

Physics and communication. Separate FMU stepping cost from adapter conversion, telemetry, viewers, and mission helpers. An embedded FMU removes a simulator-process boundary from that path, but does not eliminate physical-model computation.

Campaign scaling. Measure completed valid trials as worker count changes. Workers need isolated memory, files, sockets, and ports. More processes can contend for CPU, storage, or a shared external service rather than improve throughput.

A useful result record

Retain the exact experiment inputs, success criterion, timing log, optional profile, number of successful and failed trials, baseline definition, and raw durations. For a translation optimization, also retain functional equivalence checks and the fraction of accesses or instructions that actually used the optimized path.

This record connects an implementation choice to a reproducible result. It is also more useful to the next developer than an isolated claim that a particular run was fast.

Source guide

Testing and reproducibility

A FastDyn experiment has several independently testable layers: configuration, host analysis, native instrumentation, device behavior, firmware progress, and physical outcomes. A good validation plan checks the layer changed by the work and one observable result at the next boundary.

The commands in this chapter are repository-provided validation paths. Their presence establishes what the repository is designed to test; it is not a claim that every test passed on every host or that this book's preparation reran the full QEMU and vehicle suite.

Run the Python unit suite

From the FastDyn repository root, after setup:

source fastdyn-env/bin/activate
PYTHONPATH=src python -m pytest tests/unit/ -v

The suite covers configuration defaults and paths, model builds, CLI behavior, run orchestration, external plugins, shared host analysis, introspection, FMU handling, swarm plans, and other host components. It uses mocked external boundaries where appropriate. Passing these tests does not establish that a physical peripheral model or firmware mission is correct.

Use a focused test while iterating:

PYTHONPATH=src python -m pytest tests/unit/test_config_paths.py -v
PYTHONPATH=src python -m pytest tests/unit/test_virtual_preprocessing.py -v

A useful test should verify observable behavior or a contract: for example, whether two symbolic hooks resolve to a collision, whether a stale model library is removed after compilation failure, or whether workers receive distinct ports. Merely restating a helper's implementation does not improve confidence in the experiment.

Check the full minimal execution path

After building patched QEMU and build/libfastdyn.so:

fastdyn -q run -c configs/minimal.toml -o out/validation/minimal

Require the register result Reg 0:0x00000003, a [BENCH][minimal] record, and a successful exit. This exercises the configuration-to-QEMU path, a modifier, native virtual actions, and guest execution. It does not exercise active peripheral models, a complete RTOS workload, or physics.

At main e44dca2, the push/PR workflow also builds the five-QEMU-target matrix and runs the automatic MMIO six-case regression, fragment architecture and public-SDK smokes, constant-PC chaining smoke, the unit suite, the minimal run, and bundled FreeRTOS introspection. This exact CI run reports success. CI's tested QEMU environment is not a physical board or an FMU mission.

Validate new hot-path optimizations

Build from the reviewed main snapshot using the maintained source ./setup.sh --build-qemu --qemu-targets arm-softmmu,aarch64-softmmu,x86_64-softmmu,riscv32-softmmu,riscv64-softmmu command; the build must contain all five ordered QEMU patches. Then run:

tests/integration/run_fastdyn_mmio_opt.sh
tests/integration/run_fastdyn_mmio_pc_equivalence.sh
tests/integration/run_fastdyn_constant_pc.sh

The MMIO optimizer runner compares six baseline/optimized firmware outcomes, effects, aligned/unaligned fault behavior, selectors, and observer counts; FASTDYN_MMIO_ARTIFACTS=/absolute/new/directory retains a complete evidence tree. The saved-PC equivalence runner checks legacy register values against the scalar exporter across the documented target profiles; it is not the timed benchmark. The constant-PC runner checks A32/Thumb legacy equivalence, generated operations, and a live QEMU TB link, without timing thresholds. The hot-path chapter distinguishes the separate optional performance runners and their prerequisites.

Validate introspection against real guest execution

The bundled smoke test uses a committed debug-symbol FreeRTOS image and checks RTOS detection, generated hooks, a schema symbol, and live task activity:

FASTDYN_QEMU_BIN="$PWD/third_party/common/qemu/build/qemu-system-arm" \
  tests/integration/run_bundled_freertos_introspection_smoke.sh

The explicit environment setting matches a normal pinned-submodule build. The script's own fallback uses the older sibling checkout at ../qemu, so set the path when your layout differs. The script also accepts FASTDYN_BIN and FASTDYN_PLUGIN_LIB for alternate builds.

The upstream RTOS smoke scripts build additional fixtures and therefore have extra compiler and network requirements. For example:

FASTDYN_QEMU_BIN="$PWD/third_party/common/qemu/build/qemu-system-arm" \
  tests/integration/run_freertos_introspection_smoke.sh

Other scripts cover ThreadX, RT-Thread, ChibiOS, NuttX, and Zephyr. Inspect each script's prerequisites rather than assuming that a committed ELF and a rebuild-from-upstream test are equivalent. The STM32F429I LED fixture additionally checks that two task-owned counters advance, giving a behavioral scheduling check.

Test raw-image and ELF paths deliberately

tests/raw/README.md records how to regenerate flat images from the RTOS ELF fixtures and gives their load addresses. A raw image preserves bytes but discards ELF architecture, load-region, symbol, and DWARF metadata. Use raw images to test the explicitly supported numeric-address paths; retain the source ELF for tests that require symbolic triggers, type information, or RTOS discovery. The source map links the fixture guide.

Validate a vehicle in stages

Prepare the maintained FMI v3 stack first:

source ./setup.sh --build-qemu --with-rumoca

A vehicle launch smoke checks FMU loading, clock integration, the board tick, heartbeat, and telemetry. For a rover:

FASTDYN_COURBET_CONFIG=configs/rover462.toml \
FASTDYN_COURBET_LABEL=ardurover \
  tests/integration/courbet_fmu_vehicle_smoke.sh

A full copter mission adds stronger requirements:

tests/integration/courbet_mission_smoke.sh

That script checks mission upload, arming, sufficient climb, mission progression, and landing. A successful launch is a weaker result than successful mission completion. Neither establishes physical fidelity without a separate comparison to the intended system and measurements.

For concurrency, first inspect the plan without launching firmware:

fastdyn swarm -c configs/copter462.toml -n 2 \
  -o out/validation/swarm-plan --base-port 18000 --dry-run

Then use tests/integration/courbet_swarm_smoke.sh for actual workers. The manually triggered Courbet Mission workflow contains these broader vehicle, OptiFuzz wiring, and swarm checks. Its configuration is useful evidence of test scope; consult actual CI results when reporting a pass.

Preserve the experiment inputs

Before comparing two executions, record enough information to reconstruct both:

RecordWhy it matters
FastDyn commit and local diffLocal instrumentation changes alter the experiment.
Submodule revisions and QEMU patch stateThe translator, libraries, compiler, and models are separate dependencies.
Firmware hash and symbol-file identityTrigger PCs and debug metadata are binary-specific.
Complete TOML and enabled build featuresA config cannot enable a feature absent from the native build.
Device-model sources or binaries and hashesDevice behavior is part of the executed system.
FMU package, parameters, timing, and initial statePhysics results depend on more than the firmware image.
Fuzzer input or seed and property definitionA finding needs a reproducible input and an explicit oracle.
Helper commands and relevant environment overridesPorts, mutation files, and runtime selection can change behavior.
Result files, process exit statuses, and logsA silent early exit can otherwise resemble success.

Record relevant values rather than dumping the entire environment, which may contain unrelated credentials. Useful local commands include git rev-parse HEAD, git diff, git submodule status, and sha256sum on the actual experiment artifacts.

Keep state and timing comparisons controlled

A fresh work directory does not clear an external RAM file named by the configuration. When a clean boot is required, use fresh backing paths or the explicit reset_memory_files option. Similarly, a guest snapshot does not automatically reset host services or a physical board.

Hold logging, tracing, solver settings, input sequence, and stopping criteria constant when measuring performance. Report what was timed: host setup, guest execution, an entire mission, or multiple independent workers. Instruction-counted simulation time and elapsed host time answer different questions. Preserve both when interpreting a controller's behavior or claiming throughput.

Source guide

The Python API

Use the Python API when FastDyn is one part of a larger workflow: a campaign driver, a model-generation system, a target-analysis tool, or a notebook that prepares and runs experiments. The public runner gives these callers the same orchestration as fastdyn run, including configuration validation, work-directory setup, optional FMU building, helper-process lifecycle, and QEMU execution.

Run the examples in the activated FastDyn environment from the FastDyn source checkout unless another location is stated. They require the same native build as the corresponding CLI command.

Run a configuration

The smallest program uses run_config():

import fastdyn

results = fastdyn.run_config(
    "configs/minimal.toml",
    work_dir="out/python-first-run",
)

for result in results:
    print(result.machine_name, result.exit_code, result.work_dir)

The call blocks until execution finishes. The minimal example terminates itself; a long-running firmware needs the stop behavior appropriate to its experiment. The return value is a list of RunResult objects, one per machine processed by the runner.

Result fieldMeaning
machine_nameRunner identity, such as machine0
exit_codeExit status returned by the run machinery
work_dirResolved path containing the run artifacts

The current runner iterates its machines sequentially. Receiving a list of results does not make this API a parallel multi-firmware scheduler. Use the campaign and co-simulation facilities for those execution arrangements.

Control preparation explicitly

load() prepares a session without starting its machines:

import fastdyn

session = fastdyn.load(
    "configs/minimal.toml",
    work_dir="out/prepared-run",
    build_fmu=False,
    run_processes=False,
)

results = session.run()

In this example the configuration does not require an FMU or helper process, so both options are appropriate. For a scenario that needs them, leave their defaults enabled or supply equivalent prepared resources intentionally.

load() is not a side-effect-free parser. It validates the configuration, prepares the work directory, configures measurement, and may build an FMU. Session.run() starts the configured helpers and parses the machine configuration before execution. A session is a preparation/lifecycle object, not a guest snapshot or an isolated repeated-trial reset mechanism.

Options shared by the run entry points

ParameterDefaultPurpose
work_dir"fastdyn_work"Location for generated rules and results
svdBuilt-in catalog locationOverride the SVD source
persist_work_dirFalseKeep an existing work directory instead of replacing it
fmuNoneSelect an FMU name where the configuration supports selection
build_fmuTrueAllow configured automatic FMU preparation
run_processesTrueStart configured helper processes
validateTrueValidate configuration before preparing the run directory
reportModule loggerReceive preparation status messages

Choose a dedicated output directory. With the default persist_work_dir=False, an existing directory at that path is replaced. Persisting files is different from resetting guest RAM, device state, or plant state; the experiment must define each of those separately.

run_config() also accepts adjust and phase_name. Session.run() accepts adjust. The adjustment callback receives the parsed Fastdyn handle before a machine starts, allowing an application to change machine objects without writing a temporary TOML. Keep target-specific changes in the application or adapter, and preserve the same validation assumptions as the equivalent configuration.

Handle errors at the application boundary

Preparation failures may raise fastdyn.RunError; an unexpected QEMU exit can raise QemuExitError from fastdyn.targets.qemu_target. Configuration and analysis failures have their own specific exception classes. Do not treat an empty output file or a partial set of artifacts as a successful experiment merely because a process was launched.

A downstream application should attach the configuration, output directory, and failure context to its own result record. It can then distinguish a setup failure, a terminated run, a detected property violation, and an ordinary successful result.

FastDyn library code uses Python logging. Configure application logging at your entry point. This keeps the engine usable inside a larger program without taking over its log handlers.

Build models programmatically

The public model builder accepts source files, directories, or named groups of source files. This example builds the supplied ABI demonstration without LibVIO:

import fastdyn

report = fastdyn.build_models(
    ["tests/models/elder_echo.c"],
    out_dir="build/models",
    vio=False,
)

print(report.summary())
if not report.ok:
    for model in report.results:
        if model.status == "failed":
            print(model.name, model.first_error)
    raise RuntimeError("Device model build failed")

BuildReport exposes per-model results, a summary, and to_dict() for machine-readable reporting. Builds are incremental, include dependency tracking, and remove stale outputs on failure. The model chapter describes the ABI and CLI equivalents.

For a model spread across several files, construct fastdyn.Model(name, sources) and pass it to build_models(). This declares one shared-library output instead of treating every C file as an independent model.

Construct a machine directly

The lower-level builder is available through fastdyn.fastdyn.Fastdyn. It can create machines, CPUs, memories, devices, model handlers, virtual instructions, and modifiers. The repository contains two useful examples:

./fastdyn-env/bin/python configs/python_api/example.py
./fastdyn-env/bin/python configs/python_api/stm32f429i-disc0.py

The first is a non-running API tour with illustrative addresses. The second builds and runs the bundled FreeRTOS machine and remains active until stopped. Do not treat the tour's mixed addresses as one executable firmware setup.

Prefer run_config() for a downstream tool whose inputs are already TOML. Use the builder when constructing the machine itself is the application's job. In either case, call the API directly rather than spawning another fastdyn CLI process and recreating its orchestration.

Source guide

Write a virtual or run plugin

A FastDyn plugin can analyze firmware before launch, generate instrumentation, and execute native behavior while the guest runs. The frontend discovers registered features generically, so a new plugin can bring its configuration, preparation, runtime callbacks, and artifacts without adding a feature-specific command-line path.

Start with the smallest extension that expresses the behavior:

NeedExtension
A fixed register or memory assignmentA configured modifier
An action at a selected PCNative callback and VirtualDefinition
An action requiring prepared arguments or filesCallback, VirtualDefinition, and per-virtual prepare()
Firmware-wide selection or setupRunDefinition and run prepare(); native callbacks as needed
Observation of MMIO or translation eventsNative runtime hook, optionally configured by a run preprocessor

Try the complete external-plugin example

The repository includes tests/plugins/mmio_count/, an out-of-tree example that counts MMIO accesses and translated blocks. After building FastDyn, compile its native half from the repository root:

fastdyn build-model --pkg fastdyn \
  tests/plugins/mmio_count/runtime/mmio_count.c \
  -o tests/plugins/mmio_count/runtime/
cp configs/function_counter.toml configs/mmio-counter-demo.toml

Append these tables/settings to the copied configuration:

[CPU.cpu0.plugins.mmio_count]
enabled = true
source = "../tests/plugins/mmio_count"
label = "demo"

The source path is relative to the configuration file, so the .. above moves from configs/ to the repository root. Run it normally:

fastdyn run -c configs/mmio-counter-demo.toml -o fastdyn-mmio-counter

Let the example run briefly, then stop it with Ctrl-C. On orderly exit, the plugin writes run-artifacts/mmio_count/counts.txt, separating handled/unhandled reads and writes and reporting translated-block count. The copied configuration also enables Function Counter; the MMIO observer adds no competing function-entry callback. A translated-block count measures translation events, not how often cached blocks execute.

This example demonstrates the full handoff: the host validates label and writes settings.txt; the runtime resolves that artifact, registers observers, and writes final output. It needs no new core branch for mmio_count.

Host preparation contract

Both in-tree and external plugins use the same folder convention:

Path inside the plugin folderRole
host/preprocessor.pySelf-register Python definitions
runtime/<name>.cOptional native runtime implementation
runtime/*.soBuilt native libraries for an external plugin
meson.buildIn-tree native build integration, when applicable

VirtualDefinition registers a callback name, optional preparation object, required runtime capabilities, and optional ConfigurationHelp. Its preparation method receives VirtualContext plus argument tokens and returns VirtualPrepareResult(args, artifacts).

RunDefinition registers a plugin name, a preparation object, an enablement predicate, and optional help metadata. Its preparation method receives RunContext and returns RunPrepareResult(virtuals, artifacts, cleanup).

A run plugin reads its own [CPU.cpuN.plugins.<name>] table through ctx.settings. Use ctx.analysis for reusable firmware facts, ctx.plugin_artifact_path() for run-plugin artifacts, and ctx.logger for diagnostics. Each returned cleanup callback releases resources started by preparation, such as a local observer service. Per-virtual preparation has its separate ctx.artifact_path() allocator.

User-facing definitions should include ConfigurationHelp(description, toml, documentation) so the generic help browser can discover them. Internal callbacks generated by a run plugin can omit public help. Raise VirtualPreparationError with the relevant table/key when a setting is invalid.

Native registration and lifetime

A native callback has this signature:

static void entry_probe_hit(unsigned int cpu_index, void *userdata);

For a PC-triggered virtual, userdata is the prepared argument string. Validate it in C even if host preparation already checked it. Register the callback through virtual_register_callback(ctx, "entry_probe_hit", entry_probe_hit) in the plugin initializer.

Choose the descriptor that matches how the code is built:

/* Built into libfastdyn.so: */
VIRTUAL_PLUGIN("entry_probe", entry_probe_initialize);
/* Built as an external runtime/*.so: */
FASTDYN_EXTERNAL_PLUGIN("entry_probe", entry_probe_initialize);

These are alternative declarations, not two declarations for the same library. In-tree features add their native source through their own Meson file and the feature subdirectory list, then rebuild libfastdyn.so. External features export the descriptor and link the SDK using fastdyn build-model --pkg fastdyn.

FastDyn initializes built-in runtime modules after the generic callback registry and artifact root are ready. External libraries load afterward. The supplied VirtualContext remains valid for the plugin lifetime and may be retained. A built-in runtime module should use its prepared artifact to determine whether its feature was configured for the run.

The external loader checks descriptor presence, ABI version/size, plugin-name collisions, initializer failure, and linkage against the running FastDyn library. Python loading also requires the folder's preprocessor to register the name used by its configuration table. Keep that name stable and consistent across both halves.

Native SDK reference

Runtime modules include fastdyn_runtime.h. They use the public wrapper APIs instead of accessing frontend arguments or core global state.

API groupOperations
Lifecycle/outputvirtual_register_callback, virtual_artifact_path, virtual_register_exit, virtual_log
Execution statevirtual_pc, virtual_sp, virtual_icount, virtual_guest_time_ns
Registersvirtual_read_register_bytes, virtual_write_register_bytes; 32-bit convenience forms virtual_read_register, virtual_write_register
Memory/IRQsvirtual_read_memory, virtual_write_memory, virtual_raise_irq
Observersvirtual_register_irq_hook, virtual_register_mmio_observer, virtual_register_tb_translation_hook
Runtime-derived instrumentationvirtual_register_rule, virtual_register_update, virtual_register_gated_modifier
Experiment integrationvirtual_set_actuator_pwm, virtual_wait_for_trace_drain

Use full register-byte operations when a value is wider than 32 bits. Register bytes use target byte order. Include exactly one matching fastdyn/arch/ ABI header for register constants and conveniences such as VIRTUAL_FIRST_ARG and VIRTUAL_RETURN_VALUE. Available headers cover ARM32, Cortex-M, AArch64, RV64, and x86-64; the x86-64 ABI conveniences describe System V AMD64.

virtual_icount() exposes the native plugin counter, not a universal retirement counter. Its updating block-execution hook is currently enabled with TwinTrace modes; other runs can observe zero. QEMU's co-simulation budget accounting is a separate mechanism.

An MMIO observer receives VirtualMmioAccess: PC, address, value, size, direction, handled status, and whether the address is in FastDyn's MMIO routing window. It runs after device dispatch, on the vCPU thread, in registration order. Keep this path cheap and distinguish an unhandled access from a device returning zero.

A translation hook receives QEMU's block object for inspection/instrumentation. Translation is not a guest execution event. Install runtime-derived rules before the relevant blocks are translated; the registration APIs do not advertise automatic invalidation of previously cached translations. A gated modifier checks the provided flag during guest execution, so the flag's storage must remain valid.

Addition at a38af40: bind initialized device state

FastDyn a38af408451394ea2f41be1e9cf1e96bc46c370f adds two native extension points used by the experimental automatic MMIO plugin. They require that revision's runtime SDK and matching patched QEMU; they are additions to the core f9666d7 interfaces described above.

APIContract
virtual_register_post_device_init(ctx, callback)Register initialization that runs after successful dev_init and before guest translation, when device instances exist
virtual_register_mmio_replacement(ctx, replacement, out_hook_id)Submit a typed FastDynMmioReplacement through the runtime SDK during that initialization phase

The MMIO plugin illustrates the division of work: host preparation writes a candidate plan; native initialization loads it and registers post-device-init work; the later callback resolves an elder instance and its live opaque allocation before submitting a replacement. Registration returns success or failure, and the plugin records installed and declined sites in its report.

This lifecycle is useful whenever preparation can identify a site but binding needs initialized device state. Keep the state allocation valid for the lifetime of its generated accesses. The typed registration interface does not prove that an extracted expression preserves model behavior or all guest fault semantics; follow the automatic MMIO chapter's reviewed scope and validation requirements.

Ownership and validation

Keep feature-specific selection, schema formats, and runtime interpretation in the plugin. Move a helper to virtuals/utils/ only when multiple current plugins need it. Generic capabilities belong in the runtime SDK or frontend through a separate, reusable interface.

Inspect generated artifacts and rules before diagnosing runtime behavior. Exercise preparation errors and callback conflicts with focused unit tests, then use a small firmware integration case for native execution. A complete plugin contribution documents its settings, prerequisites, output, and target assumptions alongside its implementation.

Source guide

Reusable host analysis

fastdyn.host gives plugins and standalone tools a common way to inspect firmware before execution. It supplies image bytes, symbols, function ranges, supported DWARF queries, instruction facts, address resolution, and shared RTOS marker data. Multiple preprocessors examining the same image can reuse this work instead of loading and interpreting the ELF independently.

The API shares facts. A plugin still decides what to instrument, what a result means, and how its runtime manifest should look. Function Counter selects functions; ObjectSan selects objects and allocation sites; Courbet validates its firmware-specific hooks. Sharing the underlying symbol and image services does not move those policies into the generic frontend.

Open a standalone session

With FastDyn's Python environment activated, this example reads the bundled Zephyr ELF from the repository root:

from fastdyn.host import AnalysisSession

with AnalysisSession.open(
    "tests/binaries/rtos/zephyr.elf",
    architecture="arm",
    instruction_mode="thumb-mclass",
) as analysis:
    for function in list(analysis.symbols.function_ranges())[:5]:
        print(
            function.name,
            hex(function.start),
            function.size,
            function.range_provenance,
        )

Opening a session resolves the path but does not immediately parse ELF or DWARF. Services are loaded when requested. A context manager closes the session's resources at the end.

During normal FastDyn preparation, use RunContext.analysis or VirtualContext.analysis. FastDyn manages a run-scoped pool keyed by the resolved firmware path, architecture, and instruction mode. Repeated requests for that image/target reuse the session, and cleanup closes the pool after plugin cleanup callbacks.

Service reference

ServiceUseful operationsResult contract
analysis.imageread(address, size), read_bytes(address, size)Load-segment reads, with optional file/zero-fill provenance
analysis.symbolsall(), find(), lookup()Defined symbols with target-aware code addresses
analysis.symbolsfunction_ranges(), containing_function(address)Function extents with explicit or inferred provenance
analysis.dwarfglobal_variable(path) and supported type/member queriesFixed-address globals and constant layouts; unknown information remains explicit
analysis.decoderinstructions(address, size), return_sites(start, size)Cached instruction facts for the supported decoder target
resolve_address(token, symbols)Numeric values and symbol+/-offsetShared address-expression primitive
RTOS_SIGNATURES, RTOS_HINT_MARKERS, identify_rtos()Shared markers and strong-signature detectionReusable evidence with separate consumer thresholds

At the core f9666d7 baseline, LoopFinder, next_pcs, and mmiofinder retain their specialized APIs. The later constant-propagation addition below changes where mmiofinder obtains its candidates.

Addition at a38af40: known-address candidates

FastDyn a38af408451394ea2f41be1e9cf1e96bc46c370f adds analysis.constant_propagation.memory_accesses(). It returns a cached tuple of immutable KnownMemoryAccess records. Use a checkout and Python environment containing that revision for this example; the core installation walkthrough's f9666d7 snapshot predates this property.

from fastdyn.host import AnalysisSession

with AnalysisSession.open(
    "tests/binaries/rtos/zephyr.elf",
    architecture="arm",
    instruction_mode="thumb-mclass",
) as analysis:
    for access in analysis.constant_propagation.memory_accesses()[:10]:
        print(
            hex(access.pc),
            hex(access.address),
            access.direction,
            access.transfer_size,
            access.instruction_size,
        )

Run from the FastDyn repository root. This prints up to ten recovered candidates; the addresses and count depend on the image. No result means that the pass recovered no candidate, not that the firmware performs no memory accesses.

Record fieldMeaning
pcAddress of the decoded instruction
instruction_sizeEncoded instruction length in bytes
transfer_sizeMemory transfer width in bytes
directionread or write
arch, instructionArchitecture label and decoded instruction text
base_register, addressBase-register name and recovered effective address
noteAnalysis detail, such as the displacement

The compatibility property size means instruction_size, not transfer width. Keeping those dimensions separate matters for a two-byte Thumb instruction that performs a four-byte load.

The service does not decide whether an address is MMIO. At this revision, binary.mmiofinder.find_mmio_accesses() filters the shared analysis by supplied address ranges, and the experimental automatic MMIO plugin uses the same facts through ctx.analysis before applying its own device policy.

Treat these addresses as candidates, not formal proofs. The reviewed pass has limitations in control-flow merging, instruction propagation, and discovery across executable sections. It can retain an incorrect candidate or miss an access. A consumer must validate the instruction and any assumptions required by its action; a missing candidate does not establish that a memory region is unused. The automatic MMIO chapter explains the runtime guards and the remaining equivalence limits of that particular consumer.

Symbols: distinguish code from data

Use a function symbol's code_address for a hook and an object symbol's address for a data access. In an ARM thumb-mclass session, function addresses are normalized to remove the Thumb state bit. Odd data addresses remain odd, and address zero remains a valid value.

lookup() is deliberately singular. It raises SymbolNotFoundError for a missing symbol and AmbiguousSymbolError when distinct definitions remain. Use find() for a plural query or qualify a lookup by kind/address. Selecting the first result silently would conceal a choice that belongs to the consumer.

Some ELF functions have zero size. The index can infer their extent from the next function or the end of the same executable section. Check range_provenance before treating such an extent as authoritative compiler information.

Image bytes and layout evidence

analysis.image.read() returns both bytes and provenance. Reads can be file, zero-fill, or mixed. A load segment's zero-filled tail is available only within that segment's memory extent. A read does not continue into unrelated file data merely because the requested address fits a numerical range.

This matters when validating an instruction: zero-filled memory is useful for representing a segment, but it is not evidence that an instruction encoding existed in the file. Consumers that require original instruction bytes should require source == "file". Invalid, truncated, unmapped, or overflowing requests raise ImageAddressError.

DWARF support is similarly bounded. The API follows qualifiers and typedefs, resolves fixed DW_OP_addr globals and nested constant member paths, and handles supported constant member-offset encodings. It does not evaluate arbitrary expressions, dynamic locations, location lists, or bit-field layouts. Unknown sizes are represented as unknown, not guessed as four bytes.

Courbet's richer GDB-based C++ layout verification remains specialized. A narrower shared query is not a behavior-equivalent replacement for that workflow.

Instruction decoding has an explicit target

The current shared decoder accepts architecture="arm" with instruction_mode="thumb-mclass". Unsupported combinations raise UnsupportedTargetError. Its instruction records include address, size, mnemonic, operands, memory-transfer information, direct targets when recognized, and recognized return forms.

Image, symbol, and DWARF services can serve other compatible ELF targets without invoking this decoder. Select properties that match the actual image; the architecture family arm alone is not a request to treat every image as Cortex-M.

ObjectSan keeps operand-specific propagation logic local while using shared decoding. VariableWatch and ObjectSan reuse conservative candidate-memory-access analysis. Unresolved pointer flow remains a candidate rather than becoming evidence of irrelevance.

Use it inside a plugin

The following is a prepare() method excerpt for a registered run preprocessor. It discovers a function through the shared service and returns a plugin-owned hook:

from fastdyn.machine import VirtualInstruction
from fastdyn.virtual_preprocessing import RunPrepareResult


def prepare(self, ctx):
    function = ctx.analysis.symbols.lookup("main", kind="function")
    manifest = ctx.plugin_artifact_path("entry.tsv")
    manifest.write_text(
        f"0x{function.code_address:x}\t{function.name}\n",
        encoding="utf-8",
    )
    return RunPrepareResult(
        virtuals=[VirtualInstruction(
            at=function.code_address,
            instruction="entry_probe_hit",
            args=[],
        )],
        artifacts=[manifest],
    )

The plugin must separately register and implement entry_probe_hit; see writing plugins. The shared session never stores this mutable hook plan.

Reuse extends into physics, with clear ownership

The same principle applies beyond firmware ELF analysis:

Reused behaviorCurrent ownerWhat stays specialized
modelDescription.xml metadata parsingfastdyn.fmu_metadata.parse_model_description()Required vehicle variables, packaging/extraction policy, model execution, and physics state
Coverage block and growth parsingutils/coverage_helpers.pyPlotting, report formats, and presentation
Common ELF reads and symbols used by Courbetfastdyn.host, with compatibility adaptersFirmware profiles, target ABI validation, live GDB queries, and hook policy
Device description lookupExisting SVD/configuration helpersConfiguration-generation choices and model behavior

The FMU metadata parser returns FMI version, a validated model identifier when available, an instantiation token, and variable/value-reference metadata. It is a domain-local shared parser, not a reason to import FMI, Gazebo, or physics state into fastdyn.host.

Session lifetime and errors

A session treats its image as immutable. It does not poll or hash the file to notice replacements. Open a new session after rebuilding the firmware; do not reuse stale analysis indexes. Runtime mutations to guest memory are not updates to the host image's cached facts.

Public analysis errors derive from HostAnalysisError, including ImageAddressError, SymbolNotFoundError, AmbiguousSymbolError, DwarfQueryError, and UnsupportedTargetError. Handle these at the consumer boundary with the configuration key or requested analysis in the diagnostic.

Host-model layout service at e44dca2

The automatic-MMIO model extractor also uses the separately imported fastdyn.host.llvm_layout.gep_offsets() service, backed by libLLVM's C API. It parses constant GEP indices against the actual LLVM module data layout and returns unknown rather than guessing an offset if that proof is unavailable. This is an analysis of the host-compiled device-model IR, not a new generic ELF-firmware decoder; ordinary AnalysisSession users do not need libLLVM until the model-layout service is used. The optimized shared library links the same analyzed IR used to derive the metadata, avoiding mismatched __PIC__/__OPTIMIZE__ conditionals.

See the implementation at e44dca2 and the automatic MMIO contract.

Source guide

Supercache: retain native translations across runs

Supercache saves QEMU's generated native code so that a later process can reuse compatible translations. It targets repeated execution of the same firmware, such as a campaign that starts the same boot path many times. The reusable artifact is translated host code and its translation-block records. Guest RAM, device state, timers, and the state of FastDyn's plugins still belong to the new run.

This is an implemented development-branch capability with a separate QEMU prerequisite. It is not enabled by the current main-branch build.

For offline transformations of captured native code, continue to the Supercache optimizer. That chapter reviews FastDyn scopt at 124699d and QEMU 934890e, including capture metadata, profile-guided layout, cross-block optimization, and host inlining. It provides its own matching build and artifact requirements. The earlier frontend/backend pair below is the cache-reuse recipe reviewed by this chapter.

Choose the matching revisions

ComponentReviewed revisionSupercache capability
FastDyn maina38af40No supercache or supercache_flat frontend configuration
QEMU submodule pinned by that main revision and the PX4 preview99b54836Does not contain the persistent-cache implementation
FastDyn px4-v1.17-firmware-slicing preview0e13b739Configuration fields, input manifest, invalidation, and unit tests
QEMU fastdyn development revision12f5e688Persistent native translations, plugin callback reconstruction, and optional flat lookup

The workflow below deliberately combines the last two revisions. Following the preview's default submodule build alone still selects the older backend. Main's ordered QEMU patch series, including guest-instruction fragments and automatic MMIO replacement, is a different build path and is not qualified by this example. The automatic MMIO implementation does not establish compatibility with this Supercache combination.

Build the advanced runtime

Use an x86-64 Linux host and the native dependencies from Install FastDyn. This restriction describes the host executing cached native code; the example guest is ARM Cortex-M3. The backend is implemented for system emulation and does not provide this cache for user-mode emulation or other host architectures.

Start in the directory where you keep source checkouts. Choose a new external QEMU directory: setup intentionally preserves an existing checkout and will not switch it merely because --qemu-ref changes.

git clone --branch px4-v1.17-firmware-slicing \
  https://github.com/boardrunner2049/FastDyn.git FastDyn-supercache
cd FastDyn-supercache
git checkout --detach 0e13b73986a66270a6d8452b2c0147af7b874d29

source ./setup.sh --clone-qemu --build-qemu --skip-optifuzz \
  --qemu-root ../qemu-supercache-12f5e688 \
  --qemu-repo https://github.com/boardrunner2049/qemu.git \
  --qemu-ref 12f5e68807650822d3edb7e1073f524e0262bec7

This setup path builds qemu-system-arm with plugin support and builds build/libfastdyn.so against the selected QEMU. There is no separate FastDyn SUPERCACHE=true build switch. The preview's setup applies its icount/plugin compatibility patch before compiling.

Validation level: the setup flags and both implementations were inspected, and git apply --check succeeded for the preview's compatibility patch against the exact QEMU 12f5e688 target files. This documentation update did not compile this combination or execute the firmware with it. Patch applicability establishes a concrete build path, not a measured runtime result.

Run the bundled fixture cold, then warm

Continue from the FastDyn-supercache checkout with its environment active. Copy the shipped FreeRTOS example beside the original:

cp configs/minimal.toml configs/minimal-supercache.toml

In the copy's existing [Machine] table, enable the following settings. Do not add a second [Machine] table. The fixture already contains commented Supercache fields that can be edited:

supercache = "../cache/minimal.sc"
supercache_flat = false
print_command = true

The cache output path is resolved relative to the TOML, so this example writes cache/minimal.sc under the checkout. supercache_flat must be a TOML boolean; setting it to true requires a nonempty supercache path. A cache path cannot contain a comma or NUL because it becomes a QEMU accelerator option.

Select the exact executable and run:

export FASTDYN_QEMU="$PWD/../qemu-supercache-12f5e688/build/qemu-system-arm"

setarch "$(uname -m)" -R \
  fastdyn run -c configs/minimal-supercache.toml -o out/supercache-minimal

The copied fixture leaves [Machine].qemu_path unset, allowing FASTDYN_QEMU to select this build. An explicit qemu_path would take precedence.

The setarch invocation disables address-space randomization for this process and its children. Cached machine code contains process addresses, and this backend checks that the caller has already selected stable addresses. QEMU does not change the process personality or restart itself. A host that refuses this launch mode cannot run the documented Supercache workflow.

The fixture changes the argument to vStartLEDFlashTasks from 1 to 3, prints register 0 at that function, and ends at vTaskStartScheduler through benchmark_end. A successful cold and warm run should preserve those observations. The printed QEMU command should contain an accelerator argument shaped like this, with an absolute path:

-accel tcg,supercache=/absolute/path/FastDyn-supercache/cache/minimal.sc

Run the identical command again without editing the configuration, rebuilding binaries, or changing instrumentation. The first run records the translations it reaches; the next run can restore them and append translations for newly reached paths.

Two files serve different purposes:

FilePurpose
cache/minimal.scQEMU's native code and translation records
cache/minimal.sc.fastdyn.jsonFastDyn's fingerprint and the inputs used to compute it

The backend defaults to a 2 GiB translation-code capacity when Supercache is enabled. The file is sparse, with metadata after the code area, so logical file size and allocated disk space differ. The presence of these files demonstrates that the path was configured; it is not a cache-hit statistic.

What happens on a lookup

Ordinary QEMU lookup remains the first step. On a miss, Supercache considers a stored translation using the guest PC, code-segment base, first physical code address, target flags, and compilation flags. For PC-relative translation blocks, the PC component is normalized according to QEMU's CF_PCREL convention.

Before activating a stored block, the backend checks the second code-page mapping when present and hashes the current guest instruction bytes. A match permits it to reconstruct the process-local TranslationBlock, reset native jump links, and make the cached code available. The normal mode restores QEMU's interval-tree and page/hash-table bookkeeping so ordinary invalidation machinery can find the block.

FastDyn instrumentation is already present in the saved native code. QEMU therefore reruns plugin translation callbacks to rebuild their runtime metadata, without generating replacement TCG operations. A warm run can still perform translation-time plugin work; Supercache does not promise to eliminate every preprocessing or callback cost. Custom plugins must initialize the data that their cached instrumentation references. Replaying these callbacks is not serialization of arbitrary host objects, and extensions need cold-versus-warm behavioral checks.

Two layers decide whether reuse is valid

FastDyn owns the experiment's identity. Before launching QEMU, it computes a SHA-256 fingerprint over a versioned, deterministically serialized input description:

Input classIncluded examplesIdentity used
Effective settingsPlatform, CPU definitions, initial vector address, effective icount, log options, machine globals, scalar plugin options, flat modeValues in the manifest payload
Configuration and generated filesSource TOML, device description, virtuals, modifiers, fuzzing schema, snapshot extra ranges, inline-I/O map when present, preprocessing artifactsFile contents hashed with SHA-256, plus size
Native and firmware artifactsQEMU, FastDyn plugin, firmware/kernel, drive, BIOS, FMU library, external virtual librariesAbsolute path, size, and nanosecond modification time

Changed inputs invalidate an existing .sc file. A missing or unreadable FastDyn manifest also causes the existing cache to be discarded. An unchanged manifest is kept without rewriting it. The native-file strategy assumes a trusted filesystem: replacing a binary while preserving its path, size, and timestamp defeats that cheap identity. An extension that depends on additional generated inputs should register those artifacts with preprocessing rather than leave them outside the fingerprint.

QEMU then checks its own compatibility. The header records the cache format, code-buffer size, runtime signature, host page size, target page bits, and TranslationBlock structure size. The runtime signature incorporates executable mappings and backing-file metadata. Reuse also requires the stored code-buffer address to be available and the generated prologue layout to agree. Incompatible headers start a fresh cache; an unavailable required address or incompatible prologue can stop startup. Per-block guest-byte checks are a further condition, not a substitute for FastDyn's instrumentation fingerprint.

This is a local executable build artifact. Keep it with the exact runtime and workload that produced it; it is not a portable firmware cache for distribution across machines or arbitrary plugins.

Flat mode and lifecycle limits

Start with supercache_flat = false. Set it to true only for an experiment whose executable guest memory remains immutable for the entire run. Restored flat-mode blocks bypass the normal interval tree, page lists, and QEMU hash table. That shortcut removes bookkeeping that writable executable code and self-modifying firmware need.

The backend chooses its index from the span of cached guest PCs, not the ELF file's byte size:

Cached PC spanFlat index
Up to 32 MiBDirect index, with one 32-bit slot per byte of span
More than 32 MiB, up to 512 MiBPaged index with compact per-page lookup tables
More than 512 MiBRejected in flat mode; use normal mode

Both modes force single-threaded TCG. split-wx=on is incompatible. QEMU takes a nonblocking exclusive lock on the cache file; use a separate cache path and work directory for each worker, and avoid sharing a cache between concurrent FastDyn launches that could invalidate it before QEMU acquires the lock.

Each newly translated block persists its native bytes and a committed record, then updates the header. Normal process exit synchronizes the file. Record checksums and bounds checks allow invalid records to be ignored, but the implementation does not establish a general crash-consistent snapshot guarantee.

A QEMU translation flush preserves the persistent allocation state and makes cached blocks eligible for lazy validation and relinking. Cache capacity is not managed as an eviction queue: exhaustion terminates with a diagnostic while preserving cached translations. The reviewed FastDyn frontend exposes the cache path and flat flag, not a TOML cache-capacity setting. Stop users of the cache before removing its .sc file and companion manifest to force a fresh population.

Measure the optimization you need

Use the correctness and completion criteria from Performance and benchmarking. Compare at least three conditions on the same builds and firmware: caching disabled, caching enabled with an empty cache, and repeated launches with a populated cache. Keep execution inputs and instrumentation constant within each condition. Switching flat mode changes the fingerprint and requires a new warmup.

Measure full launch-to-completion wall time separately from the fixture's benchmark_start/benchmark_end interval. Startup, preprocessing, native-code restoration, metadata reconstruction, and file writes may fall outside a selected guest interval. A tiny fixture proves the workflow more readily than it predicts the benefit for a long boot sequence.

Record host and guest architecture, both source revisions, plugin build options, completion condition, cache mode, cache capacity, repetition count, and timing distribution. Check that cold and warm runs reach the same guest outputs and end state. Keep the cache and manifest unchanged between warm samples; avoid rebuilding or touching tracked native artifacts between them. This backend does not expose a FastDyn cache-hit counter, so neither a populated file nor a shorter isolated sample establishes a hit rate or a universal speedup.

The preview includes six frontend unit tests covering unchanged-input reuse, flat-option generation, instrumentation changes, scalar plugin-option changes, native-plugin rebuilds, and an existing cache without a manifest. They were inspected for this chapter, not executed here. They verify invalidation policy; they do not by themselves qualify cached native execution, a custom plugin, or a complete flight mission.

Source guide

Supercache optimizer

scopt optimizes native code that QEMU has already translated and saved in a Supercache. It can improve the arrangement of translation blocks, specialize selected connections between them, remove proved-dead state stores, and inline supported host helper calls. The firmware ELF remains the input to FastDyn; the optimizer produces a separately validated native-cache artifact.

For optimization of instructions in the firmware ELF, see FirmBOLT. That separately pinned branch extends BOLT with a Cortex-M/Thumb backend and firmware publication checks. The two tools operate at different stages: FirmBOLT prepares a firmware image; scopt prepares a saved host translation cache.

This chapter covers FastDyn's scopt branch at 124699db203aae581735b4bdfb82e9b949332405, paired with QEMU 934890ed5119ef70da69276991d921573f23ed4f. That backend includes capture, profiling, and the v5/v6 loader support needed by these workflows. The earlier Supercache chapter explains persistence and cache identity, but its historical build recipe does not produce the metadata required here. Use the matching source and backend for this chapter's lab. Source lock

What the optimizer works on

A saved block contains host machine instructions, references to runtime helpers, links to other blocks, and information used to recover guest state. Moving or rewriting those instructions requires more than a disassembler.

InputWhat it establishes
.sc cacheNative code arena and translation-block records. The current backend writes v5; its loader also accepts the v6 guarded-slot format.
.scm captureInstruction extents, native references, literal-pool uses, call provenance, guest instruction boundaries, recovery metadata, and runtime mappings.
.qprof and merged Profile v1Software counts collected from the unoptimized baseline, with explicit phases and input sets.
ExecutionBundle and RuntimeIdentityThe firmware, configuration, runtime binaries, and admission facts to which the snapshot belongs.
EnvLayout and helper effectsExact executable-bound descriptions used when a transformation reasons about QEMU state or helper behavior.

Import combines these inputs into an immutable snapshot. A block's identity includes its translation context, rather than only its guest address. Different cached versions of the same guest block remain distinguishable. Passes propose edits against that snapshot, and the manager tracks which analyses become stale when code, metadata, or layout changes. The linker checks placement and displacement constraints before the artifact is validated and published. Contracts, pass framework

flowchart TD
    C["Cache, capture, and identities"] --> S["Immutable snapshot"]
    P["Training profile"] --> O["Selected passes"]
    S --> O
    O --> V["Link and validate"]
    V --> A["Accepted artifact"]
    V --> R["Rejection record"]
    A --> H["Held-out execution checks"]

Capture and profiling are separate runs. In this backend they require non-flat caches, absolute output paths, and fresh output files; they cannot run simultaneously. Profiling disables chaining to obtain its software observations. Its instrumentation therefore belongs to training, outside the final timing campaign. The bootstrap below handles those details. Capture implementation, profile implementation

Available transformations

The checked-in pipelines expose distinct optimization experiments. Select one deliberately and inspect its pass results.

RouteImplemented behaviorMain boundary
identityPackages the unchanged baseline and checks the identity path.Establishes the control artifact; an ordinary canonical input is byte-equal after packaging.
b2-layoutClassifies hot/cold blocks, clusters hot blocks using weighted edges, and orders the remaining sections.Moves eligible units around fixed obstacles; requires a compatible profile for meaningful ordering. Produces v5.
b3Specializes return continuations, propagates constants, folds branches, removes dead host operations, and installs guarded return/static connections.Uses certified facts, bounded variants, exact runtime admission, and symbolic checks. Guarded artifacts require the v6 loader.
scopt b4 packageReplaces proved-dead executor-state stores with same-length NOPs.Register/flag, I/O-state, and plugin-value classes have separate observer rules. Uses bound state layout and proof gates; produces v5.
host-inlineReplaces eligible helper calls with transfers to appended native helper bodies.Standalone v5 pipeline; checked x86-64 SysV helpers and exact native images.
host-inline-spliceInserts a supported helper body directly into the caller's fall-through path.Narrow register/argument pattern, one splice per block, with rewritten physical offsets and recovery metadata.
host-inline-extremeConsiders all captured host calls and independently checks call-site coverage.Strict mode rejects incomplete coverage. Explicit partial mode publishes only proved edits.

The B2 and B3 pass names and order are defined in their pipeline files. The B4 command is the dedicated state-store packaging interface. A separate scopt sfb package command repairs an icount-entry store-forwarding pattern; it is a baseline TCG code-shape experiment and should be reported separately from cache optimization.

Native inlining cannot be combined with B3 or layout capabilities in one pipeline at this revision: the CLI rejects that combination. Semantic transformations also have stricter proof requirements than layout changes. An unsupported instruction or unknown helper effect can prevent an edit without invalidating the original baseline. Optimizer command

Lab: inline a real QEMU helper

The supplied Cortex-M3 fixture performs 65,536 iterations of 32-bit bit reversal and addition. QEMU translates its guest RBIT instruction into calls to the real helper_rbit. FastDyn prints the final register and stops at a benchmark marker. Two seeds train the optimizer; two different seeds validate it. An independent Python arithmetic oracle supplies the expected outputs.

The following workflow is derived from the checked-in fixture and bootstrap script. It is a source-locked integration workflow, not a claim that its emulator runs were repeated while writing this chapter.

1. Prepare the qualified host

The Python tool requires Python 3.12 or newer. This particular bootstrap requires Python 3.12 on x86-64 Linux and checks the exact Ubuntu 24.04 package versions recorded in source-lock.json. These include GCC 13.3.0, the recorded Ubuntu binutils 2.42 build, GDB for state-layout extraction, and binutils-arm-none-eabi for the guest fixture. Merely installing the newest packages is not the same environment.

The bootstrap also verifies the runtime source, setup-patch hash, QEMU revision, and an -O2 -g QEMU build. The runtime sources at this chapter's commit satisfy its recorded starting-revision check. The execution harness uses setarch x86_64 -R; the host must permit that execution mode so captures can be reused with stable mappings. Retain the produced binaries and run files through optimization and validation.

From a fresh checkout, run the remaining blocks in the same Bash session and continue only after each command succeeds:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-scopt
cd FastDyn-scopt
git checkout --detach 124699db203aae581735b4bdfb82e9b949332405

python3.12 -m venv scopt-env
source scopt-env/bin/activate
python -m pip install -e 'tools/scopt[test]'
scopt --help
scopt contracts check

An editable installation keeps the tool's pipeline and fixture resources available. The Python installation and contract check do not build QEMU or qualify a native cache.

2. Capture and qualify the baseline

Choose a work directory that does not exist. The bootstrap creates it, initializes the pinned submodules, invokes the source build, assembles the guest, resolves its marker symbols, and renders the configuration.

SCOPT_WORK="$PWD/out/scopt-host-inline"
python tools/scopt/scripts/bootstrap_host_inline.py \
  --source-lock tools/scopt/fixtures/host-inline/source-lock.json \
  --work-dir "$SCOPT_WORK"

export SCOPT_ENVLAYOUT_PATH="$SCOPT_WORK/envlayouts"
export FASTDYN_ROOT="$PWD" SCOPT_FASTDYN_SRC="$PWD"
SCOPT_QEMU="$PWD/third_party/common/qemu/build/qemu-system-arm"
SCOPT_SNAPSHOT=$(python -c \
  'import json,sys; print(json.load(open(sys.argv[1]))["snapshot"])' \
  "$SCOPT_WORK/baseline.json")

The generated configuration selects generic-cortexm, a Cortex-M3 CPU, non-flat Supercache, a file-backed input memory bank, and the existing benchmark_start, printreg, and benchmark_end callbacks. Addresses come from the newly assembled ELF.

Before writing baseline.json, the script checks uncached execution, cold and warm cache behavior, captures the training runs, extracts EnvLayout, creates identities, imports a snapshot, collects a steady-phase profile, and packages an identity artifact. It reimports that artifact and checks the snapshot identity. Both held-out inputs must match the arithmetic oracle, with zero appended translation blocks in the warm baseline and identity runs.

Keep bootstrap.log, build-evidence.json, and the complete output directory. They record the actual commands, package versions, binary digests, captures, profiles, oracle results, and cache-use evidence. Rebuilding the runtime requires a fresh qualification.

3. Build the checked native bridge

Host inlining uses scopt-native, a bridge to LLVM/BOLT's inliner. It requires CMake, Ninja, LLVM 20.1.2 development libraries, and the exact LLVM 20.1.2 source archive. The script defaults to llvm-config-20; set LLVM_CONFIG to the matching executable if necessary.

With those prerequisites and curl available:

mkdir -p out
curl --fail --location \
  https://github.com/llvm/llvm-project/releases/download/llvmorg-20.1.2/llvm-project-20.1.2.src.tar.xz \
  -o out/llvm-project-20.1.2.src.tar.xz

tools/scopt/native/build.sh \
  "$PWD/out/llvm-project-20.1.2.src.tar.xz" \
  "$PWD/out/scopt-native"
export SCOPT_HOST_INLINE_BRIDGE="$PWD/out/scopt-native/build/bin/scopt-native"
"$SCOPT_HOST_INLINE_BRIDGE" --version

The build checks the archive SHA-256 and llvm-config version, applies the checked-in BOLT adaptations, and builds the bridge. Its expected version string is scopt-native bridge 1 (LLVM/BOLT 20.1.2). The bridge hash and eligibility policy participate in the optimization's input identity. Native build and contract, build script

4. Inspect calls and optimize

The initial inventory shows captured host calls and their profile weights. Those weights are translation-block entries, a hotness proxy; they are not exact dynamic call counts.

scopt host-calls "$SCOPT_SNAPSHOT" \
  --profile "$SCOPT_WORK/profile/merged.profile.json" \
  --out "$SCOPT_WORK/host-calls.json"

scopt optimize "$SCOPT_SNAPSHOT" --pipeline host-inline \
  --profile "$SCOPT_WORK/profile/merged.profile.json" \
  --store "$SCOPT_WORK/inline-store" --json \
  > "$SCOPT_WORK/inline-result.json"

SCOPT_ARTIFACT=$(python -c \
  'import json,sys; d=json.load(open(sys.argv[1])); assert d["status"]=="published"; print(d["artifact_dir"])' \
  "$SCOPT_WORK/inline-result.json")

optimize exits 0 after publishing an artifact and 2 after rejecting a candidate. A rejection record identifies the failed condition. Publication does not by itself mean that a pass made a change: inspect ledger.jsonl, the provenance sidecar, and the coverage report. Outcomes such as no_change, skipped_unsupported, skipped_unknown, or budget_exhausted remain meaningful results.

The published directory contains cache.sc, its capture metadata, bundle and runtime identity, profile information, validation.json, ledger.jsonl, and MANIFEST.sha256. It is immutable. Its cache.sc.scopt.json provenance is distinct from FastDyn's per-run .sc.fastdyn.json launch fingerprint. The execution harness deploys a writable copy with the correct launch manifest; do not point QEMU directly at the read-only store artifact. Linking and publication

5. Validate on held-out inputs

scopt validate "$SCOPT_ARTIFACT" --snapshot "$SCOPT_SNAPSHOT"

scopt validate "$SCOPT_ARTIFACT" --dynamic \
  -c "$SCOPT_WORK/host-inline.toml" --baseline "$SCOPT_SNAPSHOT" \
  --qemu "$SCOPT_QEMU" \
  --inputs "$SCOPT_WORK/heldout-0.bin" \
  --inputs "$SCOPT_WORK/heldout-1.bin" \
  --out "$SCOPT_WORK/inline-v10"

scopt host-calls "$SCOPT_SNAPSHOT" --coverage \
  --artifact "$SCOPT_ARTIFACT" \
  --profile "$SCOPT_WORK/profile/merged.profile.json" \
  --out "$SCOPT_WORK/inline-coverage.json"

Static validation checks the packaged v5 artifact and its metadata. Dynamic validation, called V10, compares baseline and artifact runs using fresh directories and cache-use evidence. For this fixture, inspect inline-v10/dynamic.json: both arms should append zero blocks. The measurement script requires qualifying V10 records before timing and verifies every timed output against the oracle.

This static scopt validate interface is for v5 artifacts. B3's v6 artifacts use their packaging checks and the verifying scopt publish path. Do not interpret a v5-only parser error as a completed v6 validation.

An ablation using --disable host-inline supplies another control; the bootstrap already supplies the identity artifact. To evaluate host-inline-splice, repeat optimization and validation with that pipeline name and separate output directories. It shares the same captured baseline and checked bridge, but applies a different rewrite.

What makes host inlining admissible

The native path binds a call to the captured guest instruction, its helper metadata, its direct displacement or immutable pool reference, and the exact loaded image. It checks the module digest, mapping, load bias, symbol range, and compiled bytes. A rebuild or changed mapping is not interchangeable evidence.

For host-inline, the admitted bodies are supported x86-64 SysV integer helpers using registers, ordinary returns, and direct internal control flow. Unsupported memory or stack effects, nested calls, traps, external transfers, and recovery dependencies receive refusals. The BOLT bridge constructs the native control-flow representation and performs inlining; an independent V24 check verifies the final placed machine bytes, source correspondence, and continuation relocations.

The island form appends helper bodies after the original pool and preserves original guest-instruction offsets. The splice form handles a narrower straight-line pattern: one 32-bit argument enters in edi, the return leaves in eax, and a suitable adjacent argument load permits removing a redundant copy. It updates physical offsets and the guest recovery search table. Derived capture metadata records those changes for independent reimport.

Both paths assume the audited runtime's normal stack and calling behavior. Their equivalence contract excludes observing eliminated return-address slots or asynchronously unwinding through the removed frame. It qualifies ordinary execution under that contract, rather than arbitrary debugger, unwinder, or interposition behavior. Island admission and proof, splice admission and proof

The stricter host-inline-extreme pipeline also inventories cold and unprofiled calls. Its default is all-or-nothing: a missing or unsupported call prevents publication. allow_partial=true is an explicit relaxation recorded in provenance. The current fixture's strict attempt rejects at 2 approved of 6 observed sites. Partial mode splices benchmark_start and the hot helper_rbit; the cold RBIT shares the virtual's block, and the format allows only one splice per block. The framed virtual retains its nested clock call. The accepted depth setting is 1 or 2, with 1 the default. This is bounded, checked coverage, not unrestricted recursive inlining. Extreme-mode implementation and recorded result

Measure the result

After the held-out validation succeeds, use a fresh evidence directory:

python tools/scopt/scripts/measure_host_inline.py \
  --baseline "$SCOPT_WORK" --inline-artifact "$SCOPT_ARTIFACT" \
  --inline-v10 "$SCOPT_WORK/inline-v10/dynamic.json" \
  --out "$SCOPT_WORK/performance" --repetitions 6 --seed 20261118

This compares the warm baseline, identity artifact, and inline artifact in an interleaved campaign. It writes the frozen campaign, individual run evidence, and performance.json. Keep training and held-out inputs separate, report code growth and skipped sites, and compare equivalent completion conditions. Offline optimization, deployment preparation, and warm firmware execution answer different cost questions; retain all three when judging whether repeated runs amortize the work.

The pinned source documentation reports these separate campaigns under Rosetta on Apple Silicon, not physical x86-64 measurements:

CampaignRunsMedian paired firmware-time reduction versus its warm baselineVariation
Native islands363.86%MAD 2.22 percentage points; pairs ranged from 8.42% faster to 9.79% slower.
Fall-through splices485.95%MAD 4.07 percentage points; pairs ranged from 19.01% faster to 4.29% slower.

These percentages are paired comparisons, not ratios of pooled medians. The island artifact added 164 bytes across two sites; the splice artifact added 144 bytes. The source reports oracle agreement and zero appended blocks for the measured runs. Per-run deployment preparation was approximately 0.52 seconds for the island campaign and 0.475 seconds for the splice campaign, outside the firmware interval. The island report also records approximately 2.8 seconds of offline selection and bridge work. These results describe one small fixture and its host. Island measurements, splice measurements

Validation level of this chapter

On 18 November 2026, the documentation review installed the Python tool in an isolated environment, ran its CLI and contract checks, and ran a focused existing test selection: 223 passed, 12 skipped, and 25 deselected. The checks covered synthetic cache formats, pass capabilities, invalidation, linking and rollback, duplicate-key handling, immutable publication, image binding, native correspondence, splice metadata, strict-coverage rejection, and mutation rejection.

Eleven skipped tests require an actual BOLT bridge; one requires real RBIT splice evidence. The pass-framework tests deliberately mock bridge responses where appropriate. No native bridge build, source-locked bootstrap, QEMU execution, or timing campaign was run for this documentation change. The performance figures above are the pinned source's reported results, while the observed local results establish the narrower Python and synthetic contracts. Existing unit tests, mutation checks

Source guide

FirmBOLT

FirmBOLT applies LLVM/BOLT's binary optimization machinery to firmware and checks whether the result can be emitted within the firmware's constraints. Its direct Cortex-M backend understands Thumb instructions, vector entries, literal pools, relocations, and the distinction between executable bytes and data embedded in flash. The default publication path emits a new candidate ELF with qualified function bodies inside their existing ranges and retains the original implementation when a candidate cannot satisfy its checks.

This chapter is pinned to FastDyn's firmbolt branch at b14f14cb4992d28d56cda5e73685a5f7c432c5cf. The branch applies patches/bolt-fastdyn-preflight.patch to LLVM 7864c0736a8a09670dfbfc513f1e9649799f2486. The checked-in QEMU gitlink is 99b54836ded8dc3271eba52deee7453efc0a13b9. Pinned submodules, patch application

FirmBOLT rewrites the firmware ELF. The Supercache optimizer rewrites saved native translation blocks produced by QEMU. They operate at different stages and have different input identities, supported transformations, and validation workflows.

The direct Cortex-M backend

The backend adds an ARM instruction builder, Cortex-M CPU qualification, Thumb symbol handling, ARM relocation support, AArch32 JITLink integration, and annotation-aware emission. Its Cortex-M input is little-endian ELF32 with Thumb code. An explicit --firmbolt-cortex-m-cpu must agree with the ELF architecture attributes.

CPU optionArchitectureWhat the qualification means
cortex-m0, cortex-m0plusArmv6-MThumb-1 decoding, branch/literal handling, and bounded optimization fixtures.
cortex-m3Armv7-MThumb-2 backend and executable architectural fixtures.
cortex-m4, cortex-m7Armv7E-MFeature-qualified decoding; the real FreeRTOS execution fixture uses M4.
cortex-m23, cortex-m33Armv8-M Baseline/MainlineExplicit architecture matching; TrustZone instructions fence their containing functions from optimization.
cortex-m55, cortex-m85Armv8.1-M MainlineMVE decoding/exact re-emission and PACBTI-M decoding/opaque retention are separately covered.

This table identifies accepted CPU profiles, not equal execution coverage across every core. ARM-state regions, decode failures, and unsupported effects cause preservation or rejection. DSP, floating-point, MVE, security-state, and authentication instructions do not acquire arbitrary optimization permission merely because the decoder recognizes them. Backend and CPU checks, qualified scope

The audited ARM pipeline is enabled by default. --firmbolt-arm-full-pipeline=false selects an identity/emission diagnostic. Production optimization requires an explicit .isr_vector section or a validated vector_table, g_pfnVectors, or __Vectors symbol. Exact primary handler entries have a narrow contract for ordinary frame-load forwarding; secondary entries protect the whole containing function.

What it can optimize

Frame optimization, or FOP, is a useful starting point for O0 firmware. A value stored into a stack slot may still be available in a register when the code reloads it. FirmBOLT can replace a qualified reload with a register operation while retaining the original store. Byte and halfword cases use appropriate zero/sign extension, preserving the loaded width rather than accidentally retaining discarded high bits.

The default --firmbolt-preserve-guest-instruction-count=true policy retains same-width redundant moves and original explicit branches where ordinary BOLT cleanup would remove instructions. This is a per-function count constraint, not proof of an identical dynamic interrupt or device schedule. Stores, exception returns, instruction origins, and operation-specific admission remain separate obligations.

CapabilityImplemented contract
Ordinary FOP--frame-opt=all or hot selects frame optimization. The ordinary path retains stores; experimental stack-store removal is rejected by the Cortex-M firmware policy.
Block layout and branch repairProfile-driven block ordering, instruction shortening, and bounded relaxation operate with typed references and final placement checks.
Direct-call inliningRequires --firmbolt-allow-inlining; emitted callee instructions carry cloned original identities.
Tail duplication and propagationDuplication requires --firmbolt-allow-tail-duplication; removal of register definitions through propagation has its own --firmbolt-allow-tail-duplication-propagation contract.
Loop inversion and double-jump peepholesSeparate --firmbolt-allow-loop-inversion and --firmbolt-allow-control-flow-peepholes permissions admit the corresponding control-flow changes.
Indirect-call and method promotionProfiled hot targets receive checked guards and an original fallback. Call, tail-call, method-load, ABI, and Thumb-1 literal-read permissions are distinct.
Switch and read-only-load simplificationHot-index promotion uses recovered table identities. Scalar load elision requires --firmbolt-allow-read-only-load-elision and qualified immutable data; removing a read also changes its possible fault/event behavior.

These permission flags accompany the relevant BOLT pass options; they do not individually select every pass. The qualification runner contains complete per-fixture combinations and their negative controls. Some explicitly relax the global count policy. Apply those combinations only with the corresponding workload contract.

Publication is part of the optimization

In the default compact mode, BOLT may analyze and assemble more functions than it ultimately installs. The publication policy selects functions changed by a recorded, audited transformation, checks their final linked bodies, and retains the original bytes when a body is missing, over capacity, incorrectly attributed, or incompatible with the contract.

flowchart TD
    I["Firmware ELF and profile"] --> B["Patched BOLT passes"]
    B --> P["Publication checks"]
    P -->|Accepted| N["New function body"]
    P -->|Retained| R["Original function body"]
    N --> E["Candidate ELF and origins"]
    R --> E

The default acceptance checks preserve the entry point, program headers, allocated section ranges, and protected vector bytes. New allocated RX/RW ranges are forbidden. Non-allocated ELF metadata can change, so whole-file size and flash occupancy are separate measurements.

Reference handling covers literal loads, ADR, supported MOVW/MOVT references, qualified relocations, and recovered jump tables. Literal bytes are typed data with owners and users. Veneer space comes from qualified capacity inside a caller or explicitly reserved .firmbolt.veneer slots, rather than an arbitrary gap. Final reports retain original, cloned, and synthesized instruction identities and linker-resolved output addresses. A rejected function's origins describe the retained original body.

This revision also implements an explicit relocation mode using --relocs --use-old-text. It can reorder functions within the qualified original .text range when retained relocation evidence is available. The checked-in regression verifies moved Thumb entry pointers, calls, code labels, and relocation-section ownership. That mode permits address changes and is separate from the fixed-address lab below; its presence does not establish a whole-application performance result. Publication and linking implementation, relocation-mode regression

Lab: create and inspect a Cortex-M3 candidate

This small example uses the checked-in assembly and linker script. It builds a reference ELF, invokes the real backend, and runs the repository's static layout/reference checks. Emulator execution is a separate step in the full gate.

1. Build the pinned ARM-enabled BOLT

Use a Linux development host with Git, a working C/C++ toolchain, CMake, Ninja, and Python. The fixture uses the Arm GNU 13.3.Rel1 toolchain; place its bin directory on PATH. Python 3.12 with the following dependencies supports the inspection runner.

From a fresh checkout:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-FirmBOLT
cd FastDyn-FirmBOLT
git checkout --detach b14f14cb4992d28d56cda5e73685a5f7c432c5cf
git submodule update --init third_party/preflight/llvm-project

python3.12 -m venv firmbolt-env
source firmbolt-env/bin/activate
python -m pip install capstone==5.0.7 pyelftools==0.32

scripts/preflight/apply-bolt-extension.sh
cmake -S third_party/preflight/llvm-project/llvm \
  -B third_party/preflight/llvm-build -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DLLVM_ENABLE_ASSERTIONS=ON \
  -DLLVM_ENABLE_PROJECTS=bolt \
  -DLLVM_TARGETS_TO_BUILD='X86;ARM;AArch64;RISCV'
cmake --build third_party/preflight/llvm-build \
  --target llvm-bolt llvm-bat-dump llvm-mc yaml2obj --parallel 2

The apply script verifies the exact LLVM revision and accepts either a cleanly applicable patch or that same patch already applied. The explicit ARM build target matters: the generic build-bolt.sh helper at this revision lists X86, AArch64, and RISCV only. The configuration above includes the backend needed here. Build helper, ARM build integration

2. Assemble and optimize the fixture

Continue from the repository root in the activated environment. Choose a fresh output directory:

FIRMBOLT_WORK="$PWD/build/preflight/book-m3"
FIRMBOLT_BIN="$PWD/third_party/preflight/llvm-build/bin/llvm-bolt"
mkdir -p "$FIRMBOLT_WORK"

arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -nostdlib \
  -Wl,--emit-relocs \
  -Wl,-T,tests/preflight/fixtures/firm_bolt_cortex_m3.ld \
  tests/preflight/fixtures/firm_bolt_cortex_m3.s \
  -o "$FIRMBOLT_WORK/reference.elf"

"$FIRMBOLT_BIN" "$FIRMBOLT_WORK/reference.elf" \
  --firmbolt-cortex-m-cpu=cortex-m3 \
  --firmbolt-arm-full-pipeline --frame-opt=all \
  --eliminate-unreachable=false \
  --fastdyn-firmware-report="$FIRMBOLT_WORK/pass-report.json" \
  --keep-tmp -o "$FIRMBOLT_WORK/candidate.elf"

These compiler and backend options follow build_m3_fixture() and run_bolt() in the runner. Keeping unreachable-code elimination disabled avoids treating a reconstructed CFG alone as permission to remove firmware bytes.

The assembly exercises ordinary and narrow stack forwarding, stack-pointer rebasing, and a wide frame. This minimal command supplies no training profile, so it does not reproduce the full gate's separate profiled-layout case.

3. Check the emitted artifact

The backend writes candidate.elf, a post-pass report, and pass-report.json.layout.json with final linked addresses. The following snippet reuses the actual runner's inspection functions:

python - "$FIRMBOLT_WORK" <<'PY'
import json
import runpy
import sys
from pathlib import Path

work = Path(sys.argv[1])
gate = runpy.run_path("scripts/preflight/run-firm-bolt-cortex-m-port.py")
reference = work / "reference.elf"
candidate = work / "candidate.elf"
native = json.loads((work / "pass-report.json").read_text())
layout = json.loads((work / "pass-report.json.layout.json").read_text())
summary = native["summary"]
assert summary["unmapped_instruction_count"] == 0
assert (
    summary["synthesized_control_edge_instruction_count"]
    == summary["verified_synthesized_control_edge_instruction_count"]
)

checks = {
    "layout": gate["validate_in_place"](
        reference, candidate, {".isr_vector": None}),
    "mapping_symbols": gate["validate_arm_mapping_symbols"](candidate),
    "jump_tables": gate["validate_inline_jump_tables"](
        reference, candidate, layout),
    "pc_relative_data": gate["validate_pc_relative_data_references"](
        reference, candidate, layout),
    "publication": gate["summarize_pass_publication"](
        reference, candidate, native, layout),
}
(work / "static-checks.json").write_text(
    json.dumps(checks, indent=2, sort_keys=True) + "\n")
print(json.dumps(checks["publication"], indent=2, sort_keys=True))
PY

Successful checks establish the inspected layout, mapping, provenance, and reference properties. They do not execute the guest or establish equivalence for arbitrary inputs.

Read selected_function_count, byte_changed_function_count, and rejection reasons separately. An installed body may reproduce the input bytes. Per-pass affected-byte counts can overlap when several transformations touch the same function; unique_changed_executable_bytes_in_selected_ranges avoids double-counting. These distinctions are implemented by the publication summary.

Run the complete acceptance gate

The full runner builds architectural fixtures, checks positive and negative cases, and optionally executes them through FastDyn. Its existing environment must provide:

  • The patched LLVM checkout and built llvm-bolt, llvm-mc, and yaml2obj.
  • Arm GNU 13.3.Rel1 at the runner's fixed /data/arm-gnu-toolchain-13.3.rel1-x86_64-arm-none-eabi/bin/ location, including GCC and nm.
  • /usr/bin/ld.lld-18 for the linked read-only-data fixture.
  • The external ESCape32 O0 image at third_party/preflight/escape32-64k-O0/ESCAPE1-rev12.1.elf; it is not supplied by a fresh clone.
  • A source-built FastDyn runtime for this branch, with its matching QEMU, and permission to use the runner's local QMP sockets.

The Arm compiler, LLD, and ESCape32 image locations are constants in this script; --bolt and --fastdyn override only their named executables. With those prerequisites satisfied:

python scripts/preflight/run-firm-bolt-cortex-m-port.py \
  --bolt "$FIRMBOLT_BIN" \
  --fastdyn "$PWD/fastdyn-env/bin/fastdyn" \
  --skip-build --full-pipeline --frame-opt=all \
  --output "$PWD/build/preflight/book-cortex-m-gate"

--skip-build skips rebuilding BOLT but still builds the firmware fixtures. --skip-fastdyn omits runtime execution and records those stages as skipped_by_request. Inspect the complete report.json, per-case pass/layout reports, and commands-and-logs/; a top-level result must be interpreted with its skipped stages.

The gate compares final mapping symbols, protected bytes, PC-relative targets, jump tables, relocation identities, and emitted origins. Its runtime cases compare specified RAM results, including hot/cold fallback paths and selected fault cases. The M4 smoke compares a 2 MiB RAM prefix after 10,000 completed work units with two reference runs. That is finite execution evidence under the fixture's configuration. Runner options and checks

The direct workflow is independent of the older python -m fastdyn.preflight identity adapter. At this pin, its generic Python qualify_firmware() has not adopted the direct ARM backend. Use the patched llvm-bolt and Cortex-M runner for the operations described here.

Artifacts and execution contracts

The broader firmware wrapper can publish a FirmwareCandidate v1 containing the image, target, entry points, memory map, origin map, and optimization report. Its publisher hashes those components, checks the staged artifact, and atomically installs a new destination. Loading it rechecks integrity.

That format is consumer-neutral: it contains no FastDyn patch plan, hook binding, device model, or observation trace. Integrity verification does not establish semantic equivalence. The direct Cortex-M command above emits its ELF and reports; it does not automatically package them as a FirmwareCandidate. Artifact contract and publisher

For instrumented execution, addresses and observations remain part of the workload contract. A changed call boundary, removed flash read, different exception-visible stack state, or relocated instruction can affect a hook or fault observer even when the ordinary return value agrees. FirmBOLT's explicit permissions and original-instruction maps expose those distinctions; the existence of a backend or origin map does not imply that arbitrary MPU, interrupt, device, or vulnerability behavior has been verified.

Evidence and performance

The pinned documentation reports a 28-case v107 production/architectural gate. Its M4 publication selected 171 of 607 functions, with 127 byte-changing bodies and 678 changed executable bytes. Those are publication statistics. The real ESCape32 image has structural/vector/reference coverage, while original-board/device execution remains unavailable.

The same source reports 55 ARM BOLT lit tests, 11 AArch32 JITLink lit tests, and 19 AArch32 JITLink unit tests passing. Its 208 Core parameterizations comprise 79 passes and 129 explicit skips. The broad aggregate was not green and was not rerun to completion after the described correction.

These are source-reported historical results, not tests repeated for this chapter. Their generated build/preflight reports are absent from the checkout, and the patch hash printed in the report differs from the patch at this revision. The recorded environment also retained existing FastDyn/QEMU worktree modifications, so the QEMU gitlink identifies its base rather than a complete executable identity. Requalify an actual build before assigning those results to its output. Recorded gate and validation scope, environment pins

The LEMIX evaluation explains why both local mechanisms and completed application work matter:

Source-reported experimentResult and boundary
Exact x86-64 SmartSpeaker accessorOrdinary FOP reduced a 29-byte body to 24 bytes and reduced CPU cost per call by about 20%.
Timer-paced SmartSpeaker applicationThe reference/FOP ratio was 0.9949 with a 0.9568–1.0166 interval. Equal timer-supplied markers did not establish application capacity.
FreeRTOS POSIX queue comparisonAcross 30 paired two-million-message blocks, FirmBOLT was about 2.38% slower than O3 while meeting a frozen 5% comparability gate; checksums agreed. This is an x86-64 rehost result.

These measurements do not establish Cortex-M hardware speed or a universal FastDyn gain. The SmartSpeaker rehost uses zero-backed MMIO mappings, and no hardware-counter claim follows from it. The alias counterexample in the evaluation is equally useful: removing a seemingly private accessor stack store changed behavior when an input pointed into that stack. Ordinary FOP retained the store. LEMIX evaluation, FreeRTOS comparison

For a new experiment, freeze the firmware hash, tool/patch versions, pass options, profile, input set, completion condition, and observation checks. Separate training from held-out selection. Record live code changes, placement repairs, offline cost, and CPU cost per completed unit. Keep an unchanged reference available when a candidate fails acceptance or has no measured benefit.

During this documentation review, three CLI help checks succeeded and a selected Python suite produced 54 passed, 34 skipped, and 2 failed. Passing checks covered Python artifacts, bounded synthetic contracts, and supplied trace comparisons. The failures occurred while opening absent patched-LLVM source and an absent external SDK example, before their behavioral assertions; the wrapper and policy tests required missing source or generated evidence. No LLVM build, native wrapper acceptance, Cortex-M execution, or benchmark was established by this local run.

Source guide

  • Direct backend patch: target integration, audited pass scheduling, origins, relocation repair, publication policy, and native regressions.
  • Cortex-M runner: exact options, fixture construction, independent static checks, runtime cases, and reporting.
  • Firmware fixtures: bounded positive and negative architecture examples.
  • BOLT-first wrapper: supported-host compact import, typed reference repair, and installation checks.
  • FirmwareCandidate v1: hash-bound artifact publication and loading.
  • Recorded evaluation: mechanism-level results, acceptance boundaries, measurement methods, and limitations.

Inline device modeling

FastDyn's legacy finline interface installs a small host-memory operation at a selected guest instruction. For a simple modeled register, this can move the value transfer into translated execution and avoid the ordinary device callback. This interface is deliberately manual: supply an access map, identify the guest register, and separately arrange for the original MMIO instruction to be skipped when the inline operation replaces it.

The manual lab in this chapter remains pinned to FastDyn 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c, its QEMU dependency 99b54836ded8dc3271eba52deee7453efc0a13b9, and the accompanying FastDyn patches. It extends Device models and Virtual instructions and modifiers.

The experimental automatic alternative

FastDyn e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576 adds an implemented experimental path, mmio_opt. fastdyn build-model --mmio-opt derives a bounded operation table from elder-model source. Firmware preparation uses shared constant propagation to discover candidate accesses; native initialization binds eligible reads to the actual state returned by the model's init. QEMU emits effective-address, observer, alignment, and MPU guards around the original protected load, without a separate PC-skipping modifier. Model metadata ABI 2 and the matched analyzed LLVM IR are required. See the pinned model builder, runtime binding, and QEMU implementation.

Use Automatic MMIO optimization for that workflow, its shipped demonstration, and its experimental limits. The manual lab below explains a different backing-state and replacement contract; its examples have not been repinned or qualified against the new optimizer.

What the manual path provides

[Machine].finline names a text file. FastDyn forwards that path to the native plugin, which parses the file once and looks up each instruction PC during translation. A matching row installs QEMU_PLUGIN_INLINE_LOAD_IO or QEMU_PLUGIN_INLINE_STORE_IO against a host address.

The backing allocation is currently one global array:

char gpio_memory[0x400];

Every selected site uses &gpio_memory[offset]. Despite its name, the array does not implement GPIO register semantics. It is a zero-initialized, 1 KiB block in the plugin process. It is shared by the installed inline sites, not created separately for each device or CPU.

This is also distinct from a configured [Memory.main] or additional RAM bank. Setting backend = "file" and share = true shares guest RAM through its backing file; it does not relocate gpio_memory or connect it to an elder model. At this lab's 5b8bf3d revision, the public FdModel descriptor does not expose a way to bind an instance's state to this inline allocation.

That makes the manual path useful for controlled register-state experiments and for studying which operations can move out of device dispatch. Mixing this array with ordinary model callbacks requires an explicit common-state policy; the newer automatic path has its own instance-binding mechanism.

The access-map contract

Each accepted row has five whitespace-separated fields:

0x0800000e W state 0x000 0x0
0x08000010 R state 0x000 0x2
FieldMeaning
PCExact guest instruction address, parsed as hexadecimal
DirectionR/READ or W/WRITE, case-insensitively
Device labelParsed name, currently unused for selecting backing state
OffsetHexadecimal byte offset into gpio_memory
RegisterHexadecimal target-backend register slot

Use explicit hexadecimal spelling throughout. For ARM r10, the register field is 0xa; a bare 10 is parsed as hexadecimal 16. A Thumb instruction's address is its actual even PC, not the odd function-pointer representation.

The first matching row for a PC wins. There is no width, effective-address guard, CPU selector, reset value, or side-effect description in the format. Different labels with the same offset refer to the same bytes. Invalid rows are skipped, and failure to open the file is logged without making this parser terminate the run. Check the file and the resulting behavior before relying on it, particularly if a PC modifier would still skip an access when its map row is missing.

Use finline = "None" to disable the map. The native disabled-value check also accepts empty, null, false, and 0 spellings. Relative map paths are passed through to QEMU, so the examples below run from the FastDyn repository root.

Replacement requires two operations

At an instruction, the relevant native registration order is:

  1. Coverage and register logging.
  2. A configured virtual callback.
  3. Inline I/O.
  4. Modifiers.
  5. Legacy detour handling.

The QEMU inline-I/O helpers only generate host loads and stores. They do not remove the guest instruction. Without an additional control-flow change, a guest load can overwrite the supplied value and a guest store still performs its original access.

For the ARM32 example below, a modifier writes the address of the following instruction into r15. The pinned ARM backend updates the PC and exits the translation block. Because the inline operation was registered first, the intended sequence is the host-memory transfer followed by the PC change; execution resumes after the original MMIO instruction.

The replacement is appropriate only when it represents all relevant instruction behavior. A simple unconditional word load into a general register is a manageable starting point. An instruction with base-register writeback, multiple transfers, conditional execution, an IT block, sign extension, exclusive-access semantics, or a fault that matters to the experiment needs additional reasoning and support. Skipping it would also skip those effects.

Ordering matters for ordinary register changes too. A modifier setting r0 at a store site runs after the inline store has sampled r0. Set the input at an earlier site. A printreg virtual at an inline load site runs before that load; observe the result at the next instruction. Avoid placing required updates after a PC-redirection modifier, which exits the block.

A small ARM32 lab

The following is a newly constructed, source-reviewed lab recipe, not a shipped nonempty-finline integration test. It was not executed while writing this chapter. It compares a one-word elder model with the manual inline path using the same tiny firmware. The expected output follows from the reviewed implementation; verify it on your build before using the recipe as evidence.

Prerequisites are a Linux x86_64 host, FastDyn's Python environment and native plugin with device-model support, the pinned patched qemu-system-arm, and GNU Arm Embedded arm-none-eabi-as, arm-none-eabi-ld, and arm-none-eabi-objdump. The guest is Cortex-M3 in Thumb state. No C runtime, physical board, or FMU is involved.

Use the host dependencies described in Installation, but select this chapter's historical source revision explicitly. For a separate lab checkout:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-inline-lab
cd FastDyn-inline-lab
git checkout --detach 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c
source ./setup.sh --build-qemu

An existing checkout at that exact revision is also suitable. Use its matching built plugin and patched QEMU throughout the comparison; record the Arm binutils version along with the firmware disassembly.

Create and inspect the firmware

From the FastDyn root:

mkdir -p out/inline-state
cat > out/inline-state/demo.S <<'ASM'
.syntax unified
.cpu cortex-m3
.thumb
.section .vectors, "a"
.word 0x20010000
.word 0x08000009
.text
.global reset
.thumb_func
reset:
    movs r0, #42
    movs r1, #0x40
    lsls r1, r1, #24
    str.n r0, [r1]
    ldr.n r2, [r1]
    nop
1:  b.n 1b
ASM

cat > out/inline-state/demo.ld <<'LD'
ENTRY(reset)
SECTIONS {
  . = 0x08000000;
  .vectors : { *(.vectors) }
  .text : { *(.text*) }
}
LD

arm-none-eabi-as -mcpu=cortex-m3 \
  out/inline-state/demo.S -o out/inline-state/demo.o
arm-none-eabi-ld -T out/inline-state/demo.ld \
  out/inline-state/demo.o -o out/inline-state/demo.elf
arm-none-eabi-objdump -d out/inline-state/demo.elf

fastdyn build-model tests/models/elder_echo.c \
  -o out/inline-state/models --no-vio

Verify that the store is at 0x0800000e, the load at 0x08000010, the nop at 0x08000012, and the final branch at 0x08000014. Both memory instructions must be two-byte encodings. The firmware sets r1 to 0x40000000, writes 42, then reads the same word into r2. If your disassembly differs, update the vector, map, triggers, and next-PC values together.

Establish ordinary device behavior

Save this complete configuration as out/inline-state/baseline.toml:

[Memory.main]
id = "ram0"
base_address = "0x20000000"
memory_size = "512K"
backend = "ram"
share = false

[Machine]
platform = "generic-cortexm"
enable_gdb = false
stop_on_start = false
monitor_port = 0
qmp_socket = "/tmp/fastdyn-inline-state.qmp"
log_options = "none"
coverage = false
finline = "None"

[[CPU.cpu0]]
arch = "arm"
machine = "cortexm"
cpu = "cortex-m3"
plugin_library = "build/libfastdyn.so"
binary = "out/inline-state/demo.elf"
init_nsvtor = "0x08000000"

[[CPU.cpu0.virtuals]]
at = "0x08000008"
instruction = "benchmark_start"

[[CPU.cpu0.virtuals]]
at = "0x08000012"
instruction = "printreg"
args = ["2"]

[[CPU.cpu0.virtuals]]
at = "0x08000014"
instruction = "benchmark_end"
args = ["inline-state"]

[Device.Models.elder]

[Device.state]
ranges = [["0x40000000", "0x4000000f"]]
reset = 0

[[Device.state.handlers]]
model = "elder"
enabled = true
scroll = "out/inline-state/models/elder_echo.so"

Run it:

fastdyn -q run -c out/inline-state/baseline.toml \
  -o out/inline-state/baseline-run

The shipped echo model stores and returns its data word at offset zero. The expected functional observation is:

Reg 2:0x0000002a

A [BENCH][inline-state] line follows and ends QEMU. Here that line is a completion marker; its elapsed time is not a comparative performance result. The baseline's io.log should record the store and load through elder.

Install the manual replacement

Create out/inline-state/accesses.txt with the two map rows shown earlier. Copy baseline.toml to inline.toml, replace its existing finline setting with:

finline = "out/inline-state/accesses.txt"

Append these two modifiers to inline.toml:

[[CPU.cpu0.modifiers]]
at = "0x0800000e"
patch = "r15 <- 0x08000010"

[[CPU.cpu0.modifiers]]
at = "0x08000010"
patch = "r15 <- 0x08000012"

Run the second configuration separately:

test -s out/inline-state/accesses.txt
fastdyn -q run -c out/inline-state/inline.toml \
  -o out/inline-state/inline-run

The expected register output is again 42, now transferred through the shared inline word. Those two original MMIO transactions should no longer appear in device dispatch's io.log. Inspect the generated virtuals/modifiers.txt and virtuals/virtuals.txt if the register value or termination differs.

This compares two independently initialized implementations of one word. Keeping elder configured in the inline run does not synchronize its private state with gpio_memory: elder's data word remains at its reset value. An unmodified third access to the same register would take the ordinary path and could see different state. That is why a partial optimization requires a common backing-state contract, not just matching addresses and return values.

Keep the ordinary path available deliberately

An instruction without a map row retains its ordinary execution. Its MMIO follows the configured QEMU/FastDyn device route described in Device models. That gives a manual way to leave FIFO operations, commands, interrupts, and external I/O in a full model.

There is no generated runtime guard in the current finline format. A selected PC always uses its configured host offset, even if the guest instruction's effective address changes between visits. Neither a different device label nor a failed semantic assumption triggers an automatic fallback. Only select sites whose address and behavior you have established.

Similarly, normal device routing is not a general ordered chain of models. Dynamic ranges are first-match; configure ownership explicitly. A classic fallback currently returns zero on reads and ignores writes. It does not provide coherence with the inline array or complete peripheral semantics.

Architecture and state invariants

The ARM32 helpers use tcg_gen_ld_i32 and tcg_gen_st_i32: a native 32-bit host transfer, independent of the original instruction's width. For this path, keep offsets four-byte aligned and in 0x000..0x3fc, and use suitable general-register slots. The parser does not validate register bounds or allocation bounds. Byte loads, halfword stores, signed extension, and endian conversion are not inferred from the guest instruction.

FastDyn supports several guest architectures, but this particular primitive is not one uniform portable contract. The pinned x86 backend uses target-word loads and stores. The RISC-V backend defines a store helper but no corresponding load override; the generic load helper is a no-op. The ARM32 helper does not establish an AArch64 xN implementation. Port this experiment only after reviewing the target's helpers and PC-update behavior.

Before extending the lab, preserve these invariants:

ConcernRequired decision
Exactly one operationEither execute the original access or perform a complete replacement; avoid duplicate effects
Shared stateEvery participating fast and ordinary path must use the same authoritative state
Device side effectsPreserve read-to-clear, write masks, FIFO movement, IRQ changes, and scheduling, or leave the operation ordinary
ObservationA bypassed MMIO does not call virtual_notify_mmio, the device logger, or its trace/replay handler
Time and interruptsCompare virtual-time progress and IRQ ordering under the same instruction-count and timer policy
ResetThe inline array is host state; guest RAM restoration does not automatically restore it
ConcurrencyOne global array has no per-device isolation or synchronization protocol for concurrent writers
Translation lifetimeHost addresses and site bindings must remain valid while generated code can use them

Fresh process launches initialize the array again. In-process fuzzing resets, device resets, and coordinated physical-model restoration need an explicit state policy. Do not treat a successful guest-only snapshot restore as evidence that the inline model also returned to its initial state.

Discovery, browser flags, and evidence

The CLI's inline device-model browser is a terminal interface for discovering configuration forms. Its name does not select inline execution:

fastdyn help device-models --browse
fastdyn help device-models --no-browse
fastdyn help modifiers --no-browse

Interactive browsing defaults on when stdin and stdout are terminals. --browse forces the picker and --no-browse prints the catalog. These flags do not enable finline, discover MMIO sites, or rewrite models.

The shipped configs/minimal.toml uses the current machine/CPU schema with finline disabled. The older configs/inline_classic_config.toml contains placeholder paths and earlier schema placement; use it as historical context rather than a ready-to-run configuration.

At the lab's 5b8bf3d snapshot, find_mmio_accesses() is a separate Capstone-based ARM32/ARM64 heuristic. That launcher does not call it when finline is set. The helper does not analyze model callbacks, prove all possible effective addresses, bind elder state, or create the required replacement policy. Its MMIOAccess.size is the instruction's encoding length, not the memory transaction width. Its test depends on an optional firmware path and checks discovery, not inline-runtime equivalence.

At e44dca2, the helper delegates to the shared constant-propagation service. Its results distinguish instruction_size from transfer_size; size remains a compatibility alias for encoded length. The automatic consumer selects Cortex-M Thumb accesses and prepares a separate pending plan. These additions do not make a manual finline map self-discovering.

There is no dedicated nonempty-finline integration test in the lab's historical checkout. A useful validation campaign would extend the lab with boundary offsets, changed values, deliberate ordinary-path accesses, conditional instructions that remain unoptimized, observer behavior, and repeated resets. Compare outcomes and model transitions before measuring dispatch reduction. Include the cost of PC redirection and translation-block exits in that measurement. The newer automatic feature has a separate integration fixture; its assertions do not validate this manual replacement recipe.

Source guide

Automatic MMIO optimization

Status: implemented, conservatively gated on FastDyn e44dca2. The initial a38af40 implementation has since been corrected: extraction rejects unproven effects and address predicates, the backend preserves alignment faults, and active or late-registered MMIO observers retain the ordinary access path. These are bounded validation results, not a general semantic equivalence proof for arbitrary C models.

The workflow needs neither a hand-written PC list nor a second register description. Model compilation produces operation metadata; run preparation finds candidate accesses; native initialization binds those candidates to the model's existing state. Guest loads with an admitted replacement can read that live state directly, while other operations retain ordinary device dispatch.

This is a separate mechanism from the manual inline device modeling access map and the JIT patcher. Automatic MMIO replaces a load inside the decoder's instruction implementation. It does not insert an extra guest instruction or require a PC modifier to skip the original access.

Build the matching revision

The installation chapter supplies the Ubuntu 24.04 build prerequisites. Its core walkthrough uses an older source snapshot, so select this feature's revision explicitly. Also provide Clang 18 or a compatible clang, GNU Arm Embedded assembler/linker tools (arm-none-eabi-as, arm-none-eabi-ld), and the normal GLib development headers and pkg-config. Setup installs the Python dependencies used for firmware decoding and ELF analysis.

For a separate checkout:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-mmio
cd FastDyn-mmio
git checkout --detach e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576
git submodule update --init --depth 1 third_party/common/qemu
source ./setup.sh --build-qemu \
  --qemu-root "$PWD/third_party/common/qemu" --skip-optifuzz

Run the remaining commands from this FastDyn repository root. An existing checkout at the same revision is also suitable. Setup builds qemu-system-arm and build/libfastdyn.so with device-model support. Its five-patch QEMU series is ordered as follows:

  1. qemu-fastdyn-plugin-icount.patch
  2. qemu-fastdyn-insn-fragments.patch
  3. qemu-fastdyn-mmio.patch
  4. qemu-fastdyn-mmio-pc.patch
  5. qemu-fastdyn-constant-pc.patch

The setup script detects an already applied prefix and applies the remaining patches. It rejects an incompatible checkout instead of resetting it. Use matching QEMU headers, executable, plugin, and model library; the runtime SDK now includes the required qemu/fastdyn-mmio.h ABI.

Start with the shipped demonstration

FASTDYN_KEEP_TEST_TMP=1 tests/integration/run_fastdyn_mmio_opt.sh

The runner prints the temporary artifact directory, assembles a Cortex-M4 Thumb fixture, builds the unmodified tests/models/elder_echo.c with MMIO metadata, and creates complete optimized and baseline configurations. It runs both, checks their firmware success markers, validates the optimized installation report, and prints fresh timing measurements. Keeping the temporary directory lets you inspect its generated models, configurations, logs, and work directories.

The runner now checks six baseline/optimized pairs: echo, safety, predicates, alignment, observer, and late-observer. For each case it requires a firmware PASS and applies focused counters and observation assertions. Output includes lines such as PASS echo: installed=... fast=... fallback=..., followed by summary.json. The firmware ELF is stripped before running, so the test now exercises symbol-independent discovery.

The safety case includes read-to-clear state, unused volatile/effectful operations, mutable selectors, and narrow integer behavior. Predicate tests preserve multiple selector conditions; alignment checks exercise the original fault behavior. Observer checks cover both an observer registered during setup and one registered after translation; the latter must force the original path even when sites were previously registered. The echo loop executes one million reads. These are repository test contracts and CI evidence, not a local firmware run performed while editing this book.

The default executables are third_party/common/qemu/build/qemu-system-arm, build/libfastdyn.so, and fastdyn-env/bin/fastdyn. Override them with FASTDYN_QEMU_BIN, FASTDYN_PLUGIN_LIB, and FASTDYN_BIN. Without FASTDYN_KEEP_TEST_TMP=1, the runner deletes its temporary directory on exit. Set FASTDYN_MMIO_ARTIFACTS=/absolute/new/directory to retain a reproducible artifact tree, including the paired configurations, stripped ELFs, compressed ordinary io.log.gz traces, timing events, model build reports, and summary.json. The destination must not already exist.

Build and configure your model

The public model-build command enables extraction explicitly:

fastdyn build-model --mmio-opt --no-vio \
  tests/models/elder_echo.c -o out/mmio-models --json

This produces out/mmio-models/elder_echo.so and elder_echo.mmio.json. The shared library retains its normal fastdyn_model descriptor and includes a generated fastdyn_mmio_model table. The JSON file is an inspection report; the runtime reads the embedded table, so copying a JSON file beside an ordinary library does not enable optimization.

--mmio-opt selects clang-18 when available, otherwise clang, rather than the ordinary CC selection. Analysis and optimized-model compilation use the same host LLVM IR, generated with -fPIC -O1 before user CFLAGS. The actual library links that analyzed IR rather than recompiling C with different preprocessor flags. Dependencies include the IR, so changes affecting only slow callbacks or initialization still trigger a rebuild. Host LLVM's data layout computes GEP offsets and checks that every byte lies within a proven allocation; TBAA metadata is not an address source. Model metadata ABI 2 is required: rebuild any older --mmio-opt model libraries. --no-vio avoids the optional LibVIO dependency for this echo example; it is not the optimization switch. --json prints the build result, including each model's mmio_operations count.

The current extractor requires one C source file per model. A directory can still contain several independent models, but combining several sources into one model with --name is unsupported for this pass. If no admissible operation is found, the requested optimized build fails and removes an older output library. To retain ordinary execution for such a model, build it without --mmio-opt.

Extend an existing single-CPU Cortex-M configuration with the following settings. Replace the absolute library path with the output you just built; this fragment supplies device/plugin settings, not a complete machine configuration:

[CPU.cpu0.plugins.mmio_opt]
enabled = true

[Device.Models.elder]

[Device.echo]
ranges = [["0x40010000", "0x400100ff"]]
irq = [16]
reset = 287454020

[[Device.echo.handlers]]
model = "elder"
enabled = true
scroll = "/absolute/path/to/out/mmio-models/elder_echo.so"

The plugin currently consumes only its enabled setting. It obtains device ranges and the firmware analysis session from the ordinary run context; there are no user-facing PC, register, or expression lists to maintain. Keep [Machine].finline = "None" for this workflow. The complete smoke configuration uses arch = "arm", machine = "cortexm", cpu = "cortex-m4", coverage = false, and twintrace = "None".

For a comparison, create a second configuration with mmio_opt.enabled = false, use a separate work directory, and keep the firmware, compiled model, initial state, and execution policy fixed. Disabling the plugin leaves the same library usable through its ordinary elder callbacks.

From model source to a guarded load

flowchart TD
    A["Elder model C source"] --> B["Analyze one matching LLVM IR"]
    C["Firmware and device ranges"] --> D["Discover effective-address candidates"]
    B --> E["Prove pure reads, bounds and predicates"]
    D --> F["Bind initialized elder instance"]
    E --> F
    F --> G{"Address / predicate / observer / alignment / MPU guards"}
    G -->|Admitted| H["Read live model state"]
    G -->|Declined or guard fails| I["Original protected load"]
    H --> J["Complete original instruction"]
    I --> J

The model pass starts at the fastdyn_model initializer and proves a single constant-sized malloc/calloc state allocation (or NULL), bounded state accesses, and read-only paths under an explicit instruction admission list. Stores, volatile/atomic operations, calls, fences, unknown operations, escaping state pointers, and unproved state lifetime decline rather than substitute. This rejects read-to-clear and other side-effectful operations, including effects whose return value is unused. Selector fields must be immutable across the reachable read/write/IRQ callbacks and aliases; each admitted address predicate is retained at binding (up to eight conjuncts). Unsupported combinations remain slow.

The bounded expression format supports constants, unsigned 8/16/32-bit state loads, and representable arithmetic/bitwise computations. It preserves narrow unsigned wraparound, truncation, and zero extension. Sign extension, unrepresentable wide or variable-shift operations, and unknown offset/alias cases decline; they are not approximated. Expressions remain limited to 16 operations.

The firmware pass uses the shared, cached ctx.analysis.constant_propagation service for ELF inputs. It follows vector/ELF entry points and direct control flow and attempts bounded constant propagation through literal loads, movw/movt, register copies, and immediate arithmetic. The MMIO plugin filters the resulting address candidates against configured device ranges. It distinguishes the instruction's encoded length from the memory transfer width. Undiscovered sites use ordinary execution. The host-analysis chapter records the current limits of these candidates; the API's KnownMemoryAccess name does not establish a complete dataflow proof.

The native module loads its pending plan during plugin initialization and registers virtual_register_post_device_init() work. After dev_init, elder resolves each candidate against an initialized device and its opaque allocation. virtual_register_mmio_replacement() installs the typed descriptor and copied expression; the state pointer remains bound to the live allocation. Register before guest execution: load translation seals the registry, and normal TB invalidation does not discard it.

At execution, the fast branch checks the actual effective address, active MMIO observers, alignment, and enabled MPU state. A matching admitted load evaluates the expression from live model state. A failed guard runs the original protected QEMU load with its original MemOp flags. Unaligned predicted sites decline installation; finalized MemOps demanding alignment checks also decline substitution. Thus CCR.UNALIGN_TRP faults are retained. Fast/fallback counters count completed loads rather than retries or faulted attempts. The decoder retains destination placement, predication, writeback, PC advancement, and instruction accounting. The host still restricts automatic substitution to compatible serialized runs.

Supported scope and compatibility gates

The automatic runtime path currently targets little-endian Cortex-M Thumb scalar LDR, LDRB, and LDRH, with 1-, 2-, or 4-byte transfers. It does not optimize writes. Signed loads, wider transfers, other guest architectures, and arbitrary device side effects are outside this workflow.

ConditionCurrent behavior
More than one CPUPreparation error: one serialized CPU is required
Architecture other than arm, or machine other than cortexm/cortexm7Preparation error
No configured device rangesPreparation error
Coverage, edge coverage, fuzzing, manual finline, twintrace, hardware trace, or exact-budget capability enabledOptimization disabled; installation.json records disabled_reason, and no pending plan is used
An effectful/volatile/atomic callback, unproved allocation or selector, unsupported predicate, or unsupported expressionSite declined; ordinary execution remains
Unaligned predicted site or finalized alignment-sensitive MemOpOptimization declined or original protected load retained
MMIO observer active at bindingSite declined; ordinary dispatch and notifications retained
MMIO observer registered after translationLive guard redirects installed sites to ordinary dispatch
Admitted site with a different live address or enabled MPUGuarded fallback to the original load

The capability names checked by the host plugin are exactly coverage, edge_coverage, fuzzing, finline, twintrace, hardware_trace, and exact_budget. This list is not a universal detection system for every custom observer or runtime extension.

The current plan and replacement registries each hold up to 4096 records; the ARM load emitter considers up to 64 matching records for a PC and width. A successful registration does not prove that a site was reached or that its target load was emitted through the fast path. Check execution counters as well as installation status.

Read the generated artifacts

ArtifactWhat it establishes
<model>.mmio.json beside the libraryRead callback, claimed state size, operation count, declined-path count, selectors, and expression instructions produced by model analysis
run-artifacts/mmio_opt/discovery.jsonFirmware path, configured ranges, decoded access records, and discovery/plan preparation time
run-artifacts/mmio_opt/pending-plan.txtModel-independent rows: PC, address, transfer size, instruction size, and direction
run-artifacts/mmio_opt/installation.jsonPrepared and registered counts; per-site address, width, device, hook ID, installation reason, fast count, and guarded fallback count

installation.json first contains a pending-device-initialization marker, is rewritten after binding, and is updated with counters by the exit callback. Stop normally when you need final counts. Its installed field means QEMU accepted a registration; fast_count establishes completed fast executions. fallback_count counts completed guarded slow loads, excluding retries and faults, not every unoptimized access in the run. Where several records match one instruction and width, that branch is counted against the first matching record.

discovery.json's preparation_seconds measures firmware discovery and plan creation. It excludes model compilation, native device binding, and guest execution. The model report counts declined paths but does not provide a detailed reason for every such path. Treat each artifact as evidence of its own stage.

Safety and observation contract

The revised extractor and native guards close the specific failures reproduced during the previous review: read-to-clear or volatile operations no longer silently disappear; LLVM GEP offsets replace misleading TBAA offsets; mutable selector fields and incomplete address predicates decline; narrow unsigned arithmetic retains wraparound; and fault-sensitive unaligned loads fall back to the original memory operation. Host-generated metadata and linked library code now derive from the same analyzed LLVM IR.

MMIO observers are deliberately not accelerated. Observers active when the model is bound cause sites to decline. A later registration sets a live guard that forces already translated sites through ordinary dispatch, preserving observer counts. This assumes the serialized vCPU observer-registration lifecycle; concurrent host-thread registration is outside the evaluated contract. Fast reads without observers still skip ordinary device dispatch and per-read io.log writes. A model with effects or a workload requiring complete ordinary I/O tracing is not an appropriate candidate for this optimization.

These properties are bounded by the admitted model language, the Cortex-M Thumb scalar load path, and the available regression fixtures. They do not prove equivalence for arbitrary device models, other CPU architectures, unmodeled resets, or external state writers. Compare return values, post-read model state, faults, callback observations, and firmware outcomes against normal dispatch before using a new model in a fuzzing campaign. Fuzzing and coverage currently disable this optimization, rather than relying on an unproven fast-path equivalence.

Evidence and recorded measurement

The source-pinned six-case reference report contains these echo-case values:

Echo workload quantityChecked-in value
Discovered / installed / declined sites12 / 10 / 2
Fast reads / completed guarded fallbacks1,000,010 / 2
Baseline machine0.qemu_execution1.1445 seconds
Optimized machine0.qemu_execution0.1354 seconds
Firmware discovery and plan0.0319 seconds
Shared optimized-model compilation for three fixtures0.4957 seconds

These numbers come from the checked-in reference on its development host, not from an execution performed during this book update. The echo comparison removes both dispatch and ordinary io.log writes; it is not an isolated dispatch-speed claim. Two observer cases compare equal per-access observer counters, with zero fast reads. The safety, predicates, and alignment cases exercise conservative declines and fallbacks. CI uses functional checks and counters, not timing thresholds. Review individual summary.json, installation.json, and compressed logs when comparing your own model.

FastDyn CI for e44dca2 completed successfully on 12 November 2026. Its successful steps included the unit suite, the six-case MMIO integration runner, two fragment smoke suites, the constant-PC chaining smoke, the minimal configuration, and bundled FreeRTOS introspection. This is a reported CI run, not an independent physical-board or firmware-fuzzing campaign run by the book maintainer.

The public regression is tests/integration/run_fastdyn_mmio_opt.sh; it writes complete evidence when FASTDYN_MMIO_ARTIFACTS is supplied. Performance measurement explains how to report compilation, discovery, binding, guest execution, and changed observation volume separately.

Source guide

Hot-path optimizations: MMIO saved PC and fixed-PC chaining

Reviewed main revision: FastDyn e44dca2, with pinned QEMU base 99b54836ded8dc3271eba52deee7453efc0a13b9 and the ordered FastDyn patch series. Both mechanisms are implemented in current main. They address different recurring costs and are independent of automatic MMIO read substitution.

PathOld repeated workCurrent admitted optimization
Ordinary device MMIO callbackAllocate a register buffer and ask the GDB-style register reader for PCQEMU passes a scalar saved_pc directly to version-2 MMIO callbacks
ARM32 fixed-PC modifierWrite PC and take a general translated-block exit on every redirectWhen safe, emit a QEMU-managed direct goto_tb / exit_tb chain

Neither changes firmware bytes, eliminates arbitrary device-model code, or guarantees a speedup for workloads not dominated by these operations.

Build a matching QEMU

From a separate FastDyn source checkout, on the supported Linux build host:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-hotpaths
cd FastDyn-hotpaths
git checkout --detach e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576
git submodule update --init --depth 1 third_party/common/qemu
source ./setup.sh --build-qemu \
  --qemu-targets arm-softmmu,aarch64-softmmu,x86_64-softmmu,riscv32-softmmu,riscv64-softmmu

The setup script applies the five ordered overlays: qemu-fastdyn-plugin-icount.patch, qemu-fastdyn-insn-fragments.patch, qemu-fastdyn-mmio.patch, qemu-fastdyn-mmio-pc.patch, and qemu-fastdyn-constant-pc.patch. Rebuild both QEMU and build/libfastdyn.so after changing the patch series; a stock QEMU or stale plugin header is not interchangeable. The installation chapter describes the other dependencies. The test matrix requires GNU Arm tools and, for x86 fixture assembly, NASM.

1. Scalar saved PC in ordinary MMIO callbacks

This is an optimization of ordinary device dispatch, not a replacement for it. QEMU snapshots the PC-register value from first_cpu at exporter entry and forwards a scalar to the v2 FastDyn callback. Its definition is the value the existing FastDyn register-read path would have returned at callback entry; it is not a new instruction-exact PC service. Valid zero is distinguished from an absent value using QEMU_PLUGIN_MMIO_SAVED_PC_VALID.

The target hooks retain AArch32 R15, the selected AArch64 PC register, and the prior GDB-width normalization for x86 EIP/RIP (without adding CS.base) and RISC-V XLEN. The ordinary callback no longer needs a per-access GByteArray allocation, free, or GDB register-reader call. core_get_pc() remains available for other clients. Model reads/writes and their observations still pass through the normal dispatch path.

Run the semantic equivalence probe after building all five QEMU targets:

FASTDYN_QEMU_BUILD="$PWD/third_party/common/qemu/build" \
  tests/integration/run_fastdyn_mmio_pc_equivalence.sh

It compares the scalar with the existing plugin/GDB register value on Cortex-M, AArch32, AArch64, x86-16/32/64, RV32, and RV64; the x86-16 fixture uses nonzero CS.base. It also checks a valid saved PC of zero, the non-vCPU first_cpu case, and malformed/missing or version-mismatched callback descriptors.

The separate timed runner uses a legacy plugin built against the updated header plus a patched plugin, with MMIO substitution disabled:

FASTDYN_MMIO_PC_BASELINE_PLUGIN=/path/to/legacy/libfastdyn.so \
FASTDYN_MMIO_PC_PATCHED_PLUGIN="$PWD/build/libfastdyn.so" \
FASTDYN_MMIO_PC_ARTIFACTS=/tmp/mmio-pc-results \
  tests/integration/run_fastdyn_mmio_pc.sh

The checked-in benchmark record describes five alternating pairs on 11 November 2026: median machine0.qemu_execution 0.999059 s for the legacy path and 0.894460 s for the scalar path, or 1.1169× on its million-access fixture. Each run completed 1,000,012 reads and one write. These are source-recorded host results, not measurements rerun for this book.

2. ARM32 constant-PC modifier chaining

An existing modifier like this is eligible for automatic promotion without any syntax or configuration change:

[[CPU.cpu0.modifiers]]
at = "0x08001234"
patch = "r15 <- 0x08001000"

On 32-bit ARM A32 and Thumb, an unconditional fixed immediate PC assignment may be lowered to QEMU's own goto_tb / exit_tb with normal linking and invalidation. The source and absolute destination must lie on the same guest page; the destination must fit ARM32 and meet the active instruction-mode alignment. A free outgoing TB slot is required. Promotion is blocked in IT/ECI/ICI or single-step state and for conflicts with fragments, uncertain or state-changing earlier callbacks, legacy detours, context-save/return regions, a second redirect in the TB, state-dependent targets, or disabled chaining. AArch64 r15 is not the PC. Ineligible sites retain the original exit semantics rather than failing the run.

The optimized path keeps the original instruction's identity, accounting and block suffix. PC-relative TB reuse checks the source page at runtime; an alias mismatch performs the same absolute PC write and general exit as the legacy path. It does not convert to a relative branch or change ARM mode.

To compare with the legacy lowering, set the switch before translation:

FASTDYN_CONST_PC_CHAIN=0 fastdyn -q run -c /path/to/config.toml

For developer translation diagnostics, set FASTDYN_CONST_PC_CHAIN_TRACE=1. This is not a per-execution counter. The structural/firmware regression checks both lowering modes, A32 and Thumb outcomes, TCG operation sequences, and actual QEMU link events:

tests/integration/run_fastdyn_constant_pc.sh

The optional benchmark is separate from CI:

FASTDYN_CONST_PC_ARTIFACTS=/tmp/fastdyn-const-pc-results \
  fastdyn-env/bin/python tests/integration/constant_pc/benchmark.py

The recorded benchmark (12 November 2026, five alternating pairs of 5 million redirects) reports median 0.122967 s with FASTDYN_CONST_PC_CHAIN=0 versus 0.047947 s with chaining, a 2.565× ratio on that redirect-heavy fixture. The checked minimal FastDyn configuration has zero fixed-PC candidates; no benefit was claimed there. Neither ratio establishes a speedup for general firmware workloads.

Reproducibility and security boundaries

Preserve the exact FastDyn and QEMU revisions, compiled plugin, firmware image, CPU/mode, enabled observer/logging settings, success markers, raw timings, and structural evidence. Compare the same semantic work. MMIO saved-PC timing includes ordinary dispatch, not automatic read substitution; the constant-PC microbenchmark measures redirect cost, not peripheral access or fuzzing throughput. The source reports no timing threshold as a CI acceptance criterion.

At main CI run 43180410321, the MMIO saved-PC equivalence runner is not one of the visible CI steps; its source contains a standalone run script and a source-recorded passing matrix. The constant-PC smoke and automatic-MMIO six-case regression are explicit successful CI steps. Do not conflate these with a local rerun or a full-device test. For the separate read-substitution mechanism and its observer gates, see Automatic MMIO optimization.

Source guide

JIT patcher

FastDyn can insert a bounded sequence of guest instruction bytes immediately before an existing firmware instruction. Its patched QEMU translates those bytes through the target's own instruction decoder and emits their operations into the same TCG stream as the original instruction. This is useful for computing a register value, masking an argument, or changing the flags that the next firmware instruction observes.

The implementation described here is present in FastDyn main at 5b8bf3d. Its public name is guest instruction fragments, and its native SDK entry point is virtual_insert_before. The API accepts encoded guest bytes and an explicit encoding profile. Assembly text is assembled ahead of time with external tools; there is no public runtime assembler API.

For a fixed register assignment or a native action, see virtual instructions and modifiers. The translation insertion design explains the address and decoder boundaries behind this facility.

What executes, and where

A fragment is attached to an existing guest PC. Its bytes live in a host-owned registration, outside the firmware image. Decoding advances through that buffer without relocating the original code. If the original instruction is at P and its length is L, its ordinary fallthrough remains the architecture-defined P + L. Symbols, original instruction bytes, and plugin instruction identities remain tied to the firmware.

At a matching site, the start-of-instruction observer executes first, fragments execute in registration order, and the original instruction then observes their effects. Fragments deliberately change architectural registers and flags; FastDyn does not automatically save or restore them. A fragment runs whenever execution reaches its site. If an exception retry reaches that site again, the fragment runs again, so the contract is not exactly once per retired original instruction.

Inserted operations do not create extra guest instruction handles or increase guest instruction counts. They add translated host work and can change the firmware's subsequent path. Instruction counting therefore does not measure the amount of inserted work, and this mechanism does not assign simulated cycle costs to that work.

Public C API and lifecycle

Include fastdyn_runtime.h, which requires the patched QEMU header qemu/fastdyn-fragments.h:

bool virtual_insert_before(const VirtualContext *ctx, uint64_t guest_pc,
                           const uint8_t *code, size_t code_size,
                           const FastDynCodeSpec *code_spec,
                           uint64_t *out_hook_id);
ArgumentContract
ctxThe plugin's runtime context, supplied to its initializer
guest_pcNumeric original instruction address, subject to the profile's width and alignment rules
code, code_sizeNonempty buffer of complete instructions for the specified guest encoding
code_specFastDynCodeSpec with isa, mode, and instruction_order
out_hook_idOptional output pointer; receives a nonzero opaque ID on success and zero on failure

Register from the native plugin initializer, before guest translation starts. Calling from a translation hook is already too late. The first translation seals the registry, and there is no live replacement, removal, or per-vCPU variant. Registrations survive ordinary translation-block invalidation; retranslation emits the registered operations again from the same immutable plan.

A successful call copies both the descriptor and the bytes. Stack-backed descriptors and temporary byte buffers can therefore be released or changed after registration. The ID identifies a registration for diagnostics; it is not a patch-editing handle. Matching uses the numeric PC plus the complete ISA, mode, and instruction-order profile. Different profiles can coexist at the same numeric address, but bytes registered for one profile are never reinterpreted as another. An inactive profile does not make its fragment execute.

The limits are 128 decoded instructions and 2048 input bytes, checked independently for each fragment and for all matching fragments at one site/profile. The current registry holds at most 1024 registrations across the QEMU execution. Splitting a larger sequence into several registrations at the same site does not evade the combined limit.

A concrete initializer

This reduced example uses the committed Thumb bytes from the shipped plugin. It is specific to tests/integration/guest_code_fragments/thumb_external.S, whose original mov r1, r0 is at 0x0a:

#include <fastdyn_runtime.h>

static int initialize(const VirtualContext *ctx)
{
    /* and.w r0, r0, #255; add.w r0, r0, #7 */
    static const uint8_t code[] = {
        0x00, 0xf0, 0xff, 0x00, 0x00, 0xf1, 0x07, 0x00,
    };
    const FastDynCodeSpec spec = {
        .isa = FASTDYN_GUEST_ISA_ARM,
        .mode = FASTDYN_CODE_MODE_THUMB,
        .instruction_order = FASTDYN_INSN_ORDER_LITTLE_ENDIAN,
    };
    uint64_t hook_id = 0;

    if (!virtual_insert_before(ctx, UINT64_C(0x0a), code, sizeof(code),
                               &spec, &hook_id)) {
        return -1;
    }
    return 0;
}

FASTDYN_EXTERNAL_PLUGIN("guest_code_fragments", initialize);

The address is the even Thumb instruction address, not a function pointer carrying the Thumb-state bit. For another firmware image, determine the actual instruction address and active mode again. The shipped initializer reads its address and profile from a prepared artifact instead of hard-coding them.

Encoding profiles and inline eligibility

The profile constants use the prefixes FASTDYN_GUEST_ISA_, FASTDYN_CODE_MODE_, and FASTDYN_INSN_ORDER_. For example, the Thumb descriptor above combines ISA ARM, mode THUMB, and order LITTLE_ENDIAN.

ISA and modesAddress and instruction-order rulesExamples of admitted forms
ARM: A3232-bit PC, 4-byte alignment, active instruction byte orderAL-condition scalar register/immediate arithmetic and logical forms, comparisons, immediate operand shifts, MOVW/MOVT
ARM: THUMB32-bit PC, 2-byte alignment, active instruction byte order16-bit scalar shifts and data processing; selected Thumb-2 logical/arithmetic forms, ADDW/SUBW, SBFX/UBFX
AARCH64: A644-byte alignment, little-endian instruction bytesAdd/sub, logical forms, MOVZ/MOVN/MOVK, bitfield shifts and extensions
X86: X86_16, X86_32, X86_64Any byte address; 16/32-bit modes require a 32-bit PC; little-endianRegister-only MOV/ADD/OR/AND/SUB/XOR/CMP/TEST, selected immediates and shifts, MOVZX/MOVSX, long-mode MOVSXD
RISCV: RV32, RV642-byte alignment; RV32 requires a 32-bit PC; little-endianLUI, base integer arithmetic, logical operations, shifts, comparisons, RV64 word forms, selected compressed integer forms

These are bounded subsets, not all instructions in each family. Guest-memory operands, PC-relative and literal accesses, branches and other control transfers, exception instructions, system operations, atomics, floating point, and vectors are excluded. There is no callback or interpreter fallback for an ineligible fragment. Admitted instructions use the existing frontend's lowering; the API does not expose arbitrary TCG operations, host helpers, or host-state bindings.

Architecture semantics still matter. AArch32 rejects insertion at an IT instruction or in active IT/ECI/ICI state. Fragment instructions execute when the site is reached and can alter the flags used by the original instruction. A64 retains the operand-dependent ZR/SP meaning of register 31 and zero-extension on W-register writes. x86 retains partial-register, operand-size, REX, and lazy-condition-code behavior. RISC-V preserves x0, restores operation width between inserted instructions, and requires C or Zca for admitted compressed encodings.

FastDyn also checks the QEMU target before registration. The arm target accepts A32/Thumb; aarch64 accepts A64 and its AArch32 profiles; x86_64 accepts all three x86 modes, while i386 accepts 16/32-bit modes. The riscv32 and riscv64 targets admit their corresponding profiles. Availability of a profile does not establish that every CPU model, instruction encoding, or machine setup has been exercised.

Other hooks at the same address

The current observer whitelist contains printreg, debug_log, benchmark_start, and bench_tick. These callbacks can coexist with fragments and observe the state before fragment execution. A custom callback does not become compatible merely because its author intends it to be read-only; the public API has no fragment-specific observer classification flag.

A same-site program-counter modifier, detour, or unclassified/state-changing virtual callback is rejected before the affected block executes. This preserves the insertion's placement relative to the original instruction. Choose separate sites when the experiment needs both fragment arithmetic and a control-changing action.

Run the shipped external plugin

Use revision 5b8bf3d for this workflow; the older checkout in the core installation tutorial predates the fragment API and smoke scripts. After installing the build prerequisites, create a dedicated checkout from the directory where you keep repositories:

git clone --filter=blob:none https://github.com/boardrunner2049/FastDyn.git FastDyn-jit
cd FastDyn-jit
git checkout --detach 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c

Run the remaining commands from this FastDyn source repository root. The public smoke needs a host C compiler, pkg-config with GLib development files, GNU Arm assembler/linker tools, patched qemu-system-arm, build/libfastdyn.so, and the FastDyn Python environment.

source ./setup.sh --build-qemu \
  --qemu-root "$PWD/third_party/common/qemu" --skip-optifuzz
tests/integration/run_fastdyn_guest_code_fragment_smoke.sh

Setup applies qemu-fastdyn-plugin-icount.patch followed by qemu-fastdyn-insn-fragments.patch. Its ordered patch handling recognizes an applied series and rejects an incompatible checkout. A stale header cannot silently disable the feature: the runtime SDK requires the fragment ABI include.

The runner compiles tests/plugins/guest_code_fragments/runtime/guest_code_fragments.c into a shared library linked against the same libfastdyn.so that QEMU loads. It copies the host preprocessor into a temporary plugin directory, assembles the Cortex-M fixture, writes a complete configuration, and launches FastDyn. The preprocessor writes a namespaced settings.txt; the native initializer selects the committed bytes and registers them.

For your own configuration, the plugin settings have this shape. The source directory must contain the prepared host/ code and compiled runtime/ library; use the fixture's PC only with that fixture:

[CPU.cpu0.plugins.guest_code_fragments]
enabled = true
source = "/absolute/path/to/prepared-plugin"
profile = "thumb"
pc = 0x0a

The available plugin profile strings are a32, thumb, a64, x86_16, x86_32, x86_64, rv32, and rv64.

The fixture initializes r0 to 1. Its printreg observer runs at 0x0a before the fragment, so the expected observation is Reg 0:0x00000001. The fragment computes (r0 & 255) + 7; the unchanged original mov r1, r0 then copies 8 into r1. The fixture checks that result and prints PASS fastdyn external fragment. The runner also requires these success markers:

PASS FastDyn external-plugin initialization and public fragment API
PASS same-site observer ordering: observer, fragment, original instruction

Further cases deliberately reject a PC modifier, a state-changing callback, and an A64 profile requested from the ARM target. Those expected failures are part of the smoke. The runner removes its temporary files on exit. Override FASTDYN_QEMU_ROOT, FASTDYN_QEMU_BIN, FASTDYN_PLUGIN_LIB, or FASTDYN_BIN when using nondefault source, binary, library, or environment paths.

Architecture probes and byte regeneration

The wider matrix uses a direct QEMU plugin to test the fragment ABI and target frontends. It additionally needs NASM, LLVM's llvm-mc, LLD's ld.lld, and host binutils. Build the five QEMU executables and run:

source ./setup.sh --build-qemu \
  --qemu-root "$PWD/third_party/common/qemu" --skip-optifuzz \
  --qemu-targets arm-softmmu,aarch64-softmmu,x86_64-softmmu,riscv32-softmmu,riscv64-softmmu
FASTDYN_QEMU_BUILD="$PWD/third_party/common/qemu/build" \
  tests/integration/run_guest_code_fragments_smoke.sh
Shipped probeAssertions and boundaries
Cortex-A A32/Thumb and Cortex-M Thumb100 inserted arithmetic instructions, consumption by original firmware, fragment-produced flags; separate Thumb IT rejection
A64 on Cortex-A53100-instruction sequence including X20, 64-bit values, W-write zero-extension, and XZR sources
x86-16/32/64Real, protected, and long-mode sites; ordering, copied buffers, retranslation, original plugin handles/sizes, page-boundary rollback, and lazy-flag exception restoration
RV32/RV64100-instruction sequences exercising integer predicates, x0, and RV64 word results; separate RV32 compressed-extension acceptance/rejection
Registry validationMalformed/truncated input, a forbidden x86 tail, address constraints, separate byte/instruction limits, combined-site limits, and registration after translation starts

The complete FastDyn SDK and external-plugin path is exercised by the separate Thumb smoke above. The matrix uses little-endian fixtures; it does not establish big-endian AArch32 coverage, every CPU model, or every admitted encoding. Both runners are configured in the pinned FastDyn CI workflow. The tests and assertions described here were inspected in source; no QEMU build or firmware smoke was executed while preparing this chapter.

To verify that source assembly still produces the committed plugin byte arrays, run:

tests/plugins/guest_code_fragments/fragments/regenerate.sh

This script uses GNU Arm tools, LLVM including llvm-objcopy, and NASM, rejects unresolved relocations, and compares the emitted .text bytes with the committed arrays. Its expected success line is PASS generated fragment bytes match the committed C fixtures and contain no relocations. These assemblers are development dependencies; registration consumes the prepared bytes directly.

Diagnose a rejected or inactive fragment

Validation has two stages. Registration checks the descriptor, target availability, address, buffer structure, instruction count, and byte limits. A failed registration returns false, leaves the output ID zero, and installs no new fragment. Return an initializer error when registration is required, as the shipped plugin does.

Live translation completes the target-specific checks, including instruction eligibility, CPU extensions, and ARM continuation state. A successful registration alone does not prove that every matching site can translate. A translation failure reports the hook ID, PC, fragment byte offset, encoding profile, and reason, then terminates translation before that block executes. A valid prefix is not executed as a partial fallback.

For an inactive fragment, verify that execution reaches the numeric PC in the registered mode and instruction byte order. For translation has started, move registration into initialization. For an unavailable profile, select the matching patched QEMU target. For a subset or continuation-state rejection, choose admitted encodings and a legal site. For an unexpected register value, check observer ordering and whether the original instruction overwrites the fragment's result.

Source guide

Insert instructions during translation

Status: implemented with a bounded instruction subset at FastDyn 5b8bf3d. The JIT patcher chapter covers the native API, supported profiles, and shipped example. This page explains the design: additional guest instructions become translated work at an existing firmware address while the original image and address layout remain intact.

Add execution without moving the firmware

A plugin supplies encoded instructions for the guest ISA and an anchor PC. FastDyn validates the registration, and the patched QEMU frontend translates an admitted fragment immediately before the original instruction. The bytes are input to translation; they are not written into the firmware image or decoded as host machine code.

This is useful when a small register computation belongs directly in the translated path. A fragment can prepare an argument, mask a value, or adjust arithmetic state before an existing instruction consumes it. An assembler may produce the byte array during development, but the runtime API accepts bytes and an explicit encoding profile. It does not expose the full TCG interface.

Adding fragment operations increases the translated work at the site. It does not relocate functions, overwrite a prologue, or require a trampoline in guest memory. The original instruction retains its guest address, length, and plugin identity. Its ordinary fallthrough is still determined by that original instruction and the target architecture.

Keep the anchor and decode cursor separate

The anchor identifies an instruction in the original image. The fragment cursor identifies a position in the additional byte sequence. Advancing the latter must not advance the firmware's decode position.

flowchart TD
    A["Decode original anchor"] --> B{"Insertion registered?"}
    B -->|No| E["Translate original instruction"]
    B -->|Yes| C["Decode injected guest bytes"]
    C --> D["Emit injected operations"]
    D --> E
    E --> F["Continue original guest addresses"]

The frontend emits the accepted fragment into the same TCG stream, restores the original decode context, and translates the original instruction. Fragment offsets support diagnostics without becoming new guest addresses. The reader-visible API and the target adapters enforce this distinction together.

One registration contract, explicit target profiles

virtual_insert_before() takes the guest PC, bytes, length, and a FastDynCodeSpec identifying ISA, instruction mode, and instruction byte order. The shared layer owns registration and lifecycle. Target-specific classifiers and decoders determine which encodings are admitted and preserve their architectural register and flag semantics.

ContractImplemented behavior
IdentityMatch both the numeric guest PC and the complete encoding profile. Registrations for different modes at one address do not reinterpret each other's bytes.
OwnershipCopy the descriptor and byte buffer during registration. The caller does not need to keep its buffer alive.
OrderingApply matching fragments in registration order before the original instruction.
LifetimeSeal registration when guest translation begins. Ordinary TB invalidation preserves the registry, and retranslation emits the matching fragments again.
BoundsLimit each fragment and all matching fragments at a site/profile to 128 decoded instructions and 2048 input bytes. Both bounds apply.
ValidationCheck descriptors, structure, and limits at registration; complete checks involving the live frontend, mode, extensions, and execution state during translation. Unsupported cases fail without a callback or interpreter fallback.

The supported profiles span A32, Thumb, A64, x86, and RISC-V. Their admitted instruction subsets differ. Portability means selecting a supported target profile and valid encodings for it; it does not mean reusing one machine-code byte array across ISAs. The JIT patcher support table gives the concrete boundaries.

Preserve the intended observation boundary

A fragment deliberately changes architectural state. Its register and flag effects can affect the original instruction, including the conditions under which that instruction acts. The implementation rejects matching Thumb insertions on an IT instruction or in active IT/ECI/ICI continuation state instead of assuming a universal predication rule.

The existing start-of-instruction observer runs before the fragments. The supported same-site observer classification is explicit; an arbitrary callback is not assumed to be read-only. Conflicting PC changes, detours, or unclassified callbacks are rejected before the affected TB executes.

Fragment operations do not add original guest instructions to plugin enumeration or icount. This preserves that counting boundary while allowing the fragment's effects to change the firmware's subsequent execution path. It is not a promise that the experiment's overall instruction count or time remains unchanged.

An exception retry that reaches the anchor again runs its fragments again. The contract is execution at the site, not exactly one fragment execution per retired original instruction. A test should therefore examine the relevant exception and retry behavior as well as the ordinary path.

Work outside the current contract

The implemented subset excludes guest-memory operations, branches and other guest control transfers, privileged operations, floating point, and vectors. It also excludes live replacement/removal, automatic register preservation, host-state bindings, and a public TCG/IR interface. A plugin that needs those behaviors must use another supported mechanism or extend the implementation and its tests first.

This distinction matters for automatic MMIO optimization. Implemented experimentally at a38af40, that pipeline uses a separate typed load-replacement API and binds directly to initialized elder state. Register-only guest fragments do not supply that state access or prove that a peripheral read is safe to replace. The inline device chapter compares the automatic pipeline with the older manual finline mechanism.

Source guide

The tests establish what the repository checks. They were inspected for this documentation update, not rerun as a new runtime qualification or performance experiment.

FastDyn as a secondary simulator

FastDyn can execute firmware under an external controller that decides when the guest may advance. The controller grants a slice of virtual time, waits for the guest to pause, and then inspects or exchanges state before granting another slice. This supports bounded firmware experiments and coordinated runs of several guests.

The implementation calls this co-simulation slave mode. Its shipped controller is named BudgetMaster, and its examples retain names such as cosim_slave.toml. This chapter uses secondary for FastDyn's role and preserves those actual API and file names.

The source baseline is FastDyn e44dca2, with QEMU submodule 99b54836 and that FastDyn revision's ordered patches. This is an implemented QMP control interface, independent of the Tempo scheduler. Tempo currently demonstrates its own mock participants; the QMP workflow here runs independently.

Who controls what

ComponentResponsibility
External controllerChoose time grants, wait for completion, coordinate exchanges, and manage the experiment's processes
Patched QEMUExecute guest instructions, maintain the virtual clock and budget deadline, and publish QMP events
FastDynPrepare the machine, load firmware and instrumentation, and supply configured device behavior
A physical modelEvolve its own state according to its integration and input policy

Secondary execution does not replace peripheral models or move physics into the controller. In the shipped RLC example, firmware execution and the physical model share one QEMU process, with the model loaded through FastDyn's native plugin. The external Python program controls when that guest may advance.

There is no single slave = true switch. The configuration combines a QMP socket, a paused startup, and an instruction-counted clock. The controller then uses the budget commands supplied by the patched backend.

Understand the clock and budget

The example uses:

[Machine]
qmp_socket = "/tmp/fastdyn-cosim.qmp"
stop_on_start = true
icount = { shift = 5, sleep = false, align = false }

These are selected fields from configs/cosim_slave.toml, not a complete machine configuration. FastDyn emits QEMU's -S, Unix QMP server, and -icount options. The paused start prevents firmware from running ahead while the controller connects.

The fixed shift = 5 maps each counted instruction to 32 ns. This is a virtual-time policy, not a Cortex-M cycle-accurate timing model. Wall-clock duration measures the host's cost of executing the experiment; it is a different quantity. QEMU's instruction budgeting rounds to its instruction quantum, so the examples use representable intervals such as 500,000 ns and 20,000,000 ns. See the pinned backend's icount conversion, rounding, and system-emulation contract.

The QMP interface has three budget operations:

CommandArgumentsMeaning
run-for{"budget": 20000000}Add nanoseconds to the maintained cumulative deadline and resume execution when budget remains
query-budgetNoneRead totalbudget, currenttime, and exact without granting time
set-budget-mode{"exact": true}Select synchronous deadline stopping; false selects the default mode

totalbudget and currenttime are unsigned 64-bit nanosecond values. The former is the backend's deadline; the latter is the virtual time reached. A run-for reply acknowledges the grant. It does not mean the guest finished executing it. The controller must wait for a STOP event and then query the budget. Events can arrive before a command's reply, which is why the shipped client buffers them.

In the default mode, the budget timer requests an asynchronous VM stop. Guest execution can continue before that request takes effect. In exact mode, the timer stops the VM synchronously on the main-loop path. Use the reported clock and deadline to check the result rather than treating the requested duration as an observation.

The deadline is cumulative. For example, after a 20 ms grant, a default-mode guest might report 20.1 ms reached against a 20 ms deadline. Adding another 20 ms normally targets 40 ms, leaving approximately 19.9 ms from the current position. The backend can also move its deadline forward when an exhaustion callback sees time already beyond it. Consequently, read back both fields; totalbudget is not an immutable accounting ledger of requested durations. These behaviors are implemented in the budget patch.

Pinned-version detail: the configuration contains exact_budget_stop = true, but at e44dca2 the native call that applies that option is commented out. Use the controller's --exact or BudgetMaster(..., exact_stop=True). Those paths actively send set-budget-mode; the configuration flag alone is insufficient at this revision. Compare the native option handling with the client connection sequence.

Run the supplied RLC guest

Use a Linux x86-64 host for this fixture. Its FMU build packages an x86_64-linux native library, and its firmware targets the Cortex-M3. Install the general build dependencies from Installation, then add the firmware compiler and world runtime dependencies:

sudo apt-get install -y gcc-arm-none-eabi binutils-arm-none-eabi \
  libxml2-dev libminizip-dev

Create a checkout at this chapter's revision. All subsequent commands use its repository root as the working directory:

git clone https://github.com/boardrunner2049/FastDyn.git FastDyn-secondary
cd FastDyn-secondary
git checkout --detach e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576
source ./setup.sh --build-qemu --skip-optifuzz \
  --qemu-root third_party/common/qemu

Setup applies the complete ordered backend patch set and builds the matching plugin. Applying only the icount patch to stock QEMU does not satisfy this FastDyn revision's other required interfaces.

The optional tools/world submodule requires access to its PSecLab repository. Build it and the supplied firmware:

git submodule update --init --checkout tools/world
python3 -m venv tools/world/venv
tools/world/venv/bin/pip install -e tools/world
cmake -S tools/world -B tools/world/build -DWM_BUILD_TESTS=ON
cmake --build tools/world/build
tests/firmwares/world_rlc_gpio/build.sh

meson setup --reconfigure build
ninja -C build
export LD_LIBRARY_PATH="$PWD/tools/world/build:$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

The world build produces tools/world/examples/rlc/out/RLC.fmu. Reconfiguring FastDyn afterward matters: its world plugin is compiled only when Meson finds the world header and shared library. The reconfiguration preserves the existing feature options. The required library discovery and FMU packaging are established by FastDyn's world build definition and the pinned world CMake project.

In terminal 1, start the secondary:

fastdyn run -c configs/cosim_slave.toml -o out/cosim

In terminal 2, from the same checkout, run the controller:

source fastdyn-env/bin/activate
python utils/fastdyn_cosim.py /tmp/fastdyn-cosim.qmp \
  --exact --slice-ms 20 --slices 6

The expected behavior is a connection reporting exact-stop mode, followed by six rows with paused status and zero overshoot. Starting from time zero, the final reached time should be 120,000,000 ns. These are checks to make on your run, not measurements obtained while preparing this chapter. Firmware output should show the capacitor charging and discharging as its pin toggles.

The controller exits after its six grants. The continuously running firmware remains paused in terminal 1; stop that process with Ctrl-C when finished. Do not launch another fixture against the same /tmp/fastdyn-cosim.qmp socket or RAM file while it is active.

Use the Python controller

utils/fastdyn_cosim.py uses Python's standard library and can also be imported. With a fresh instance waiting in terminal 1, this is a runnable alternative to the CLI controller when executed from the FastDyn root:

from utils.fastdyn_cosim import BudgetMaster

with BudgetMaster("/tmp/fastdyn-cosim.qmp", exact_stop=True) as master:
    for _ in range(6):
        reached = master.run_slice(20_000_000)
        if reached != master.budget_ns:
            raise RuntimeError("guest did not stop at its reported deadline")
        print(master.budget_ns, reached, master.status)
InterfaceContract
BudgetMaster(socket, connect_timeout=15.0, slice_timeout=60.0, exact_stop=False)Configure the Unix-socket client; timeouts are host seconds
connect() / context manager entryConnect, negotiate QMP, optionally request exact mode, and read initial budget state
grant(duration_ns)Require a positive duration, acknowledge the grant, and return its cumulative deadline
wait_for_slice()Wait for STOP, refresh state, and return actual virtual time
run_slice(duration_ns)Perform a grant followed by a wait
time_ns, budget_ns, exact_stopCached state refreshed on connection and completed waits
statusQuery the guest's current QMP run status
close() / context manager exitClose the controller connection

grant() does not immediately refresh the cached fields. Use its return value for the acknowledged deadline and wait_for_slice() for completion. Passing exact_stop=False leaves the backend's mode unchanged; it does not disable a mode another client already enabled.

Use one scheduling owner per guest. The client does not correlate a STOP event with a particular reason, so an unrelated debugger pause or manual QMP stop can interrupt the assumed budget sequence. It is a synchronous controller, not a concurrent command dispatcher.

Coordinate two guests

The supplied lockstep helper launches multiple instances and grants each one a slice before waiting for any of them. After all have stopped, it prints their reached times and their spread:

python utils/cosim_lockstep.py --config configs/cosim_slave.toml \
  --instances 2 --exact --slice-ms 20 --slices 4 \
  --work-dir /tmp/fastdyn-lockstep-demo

Run this from the prepared checkout with its world-library environment. The helper uses fastdyn-env/bin/fastdyn directly. It derives separate QMP sockets, RAM files, configurations, work directories, and logs, then terminates the processes it launched on completion. Keep the work path short because these are Unix sockets.

Expect zero spread at each exact-mode boundary and final virtual times of 80,000,000 ns for fresh guests. Time agreement does not demonstrate communication: this example connects no UARTs, radios, or shared plant between its instances. Its configuration rewriting also expects exactly one qmp_socket and one memory_file line; it is a focused helper for this fixture, not a general resource-isolation engine. See Multiple firmware instances for campaign-level alternatives.

Keep physics and exchange policy explicit

The RLC plugin advances its world on pin access. Before changing an output, it integrates to the current guest time under the previous input value, then applies the new value. Before an analog read, it integrates and samples the result. Its step_ns = 100000 controls the world's integration/communication quantum, independently of the controller's 20 ms grants.

A budget pause does not itself call wm_world_advance_to(). The internal world's last evaluated time can therefore precede a QMP boundary until another pin access occurs. A controller should not infer that every model has reached currenttime merely because QEMU stopped there. The world callbacks establish this policy.

For an experiment that already has an external transport or shared model, specify what happens between exchanges. A boundary-held input policy uses the values available at one boundary throughout the next interval, then publishes newly observed values at the following boundary. That policy introduces a delay of up to the exchange interval. It is an experiment-level choice, not behavior implemented by BudgetMaster.

Smaller grants increase the number of QMP exchanges and pauses. Smaller physical-model steps change numerical integration work and accuracy. Measure host elapsed time separately, and compare outputs across step sizes rather than assuming that a faster run or an exact clock boundary proves equivalent physics. The World models chapter describes the pin adapter and its peripheral-fidelity boundary.

Lifecycle and validation limits

The client reports CosimError for QMP failures, a closed connection, an observed shutdown during a slice, and a slice that never produces STOP before its timeout. Early firmware termination is not returned as a successful partial step. Closing the client does not stop a guest that is still running or reset the experiment.

There is no reset() or rollback operation in BudgetMaster. A new experiment should launch a fresh process and reinitialize the configured memory and physical state. The fixture's reset_memory_files = true applies during launch; it is not coordinated restoration of firmware, devices, and FMUs. Reconnecting to an existing process reads its existing clock and deadline rather than starting them at zero.

The demonstrated path is one Cortex-M3 guest per QEMU process. The QMP budgeting code is not an ARM register API, but that does not establish an architecture-wide validation matrix. This fixture's world pin adapter uses ARM register indices, and QEMU icount is a system-emulation feature incompatible with multi-threaded TCG. External live inputs also remain part of the experiment's reproducibility contract.

Validation for this chapter: implementation, configuration, and tests were inspected at the pinned revisions. The 11 test_fastdyn_cosim.py tests exercise a fake QMP server, including overshoot reporting, event ordering, exact-mode selection, shutdown, and timeout handling. Their local execution was attempted but blocked at Unix socket creation by the execution environment, before protocol assertions. No QEMU/FMU integration run or timing benchmark was executed for this chapter.

The repository also ships run_cosim_slave_smoke.sh. At this pin its exact-mode stage relies on the inactive configuration-only switch discussed above, so its presence is not evidence of a passing end-to-end test. The explicitly requested exact-mode workflows in this chapter avoid that configuration assumption.

Source guide

Tempo: schedule a federation

Tempo coordinates participants under one logical clock and controls when values cross their connections. Its native scheduler, federation compiler, typed ports, and trace buffer provide a concrete way to experiment with communication timing. Python and TOML describe the experiment; C executes it.

This chapter reviews Tempo at 771b99650004fcbf3ab216970cf8fd9fae91aa6c. The shipped participants are mocks. This source contains no working FastDyn or FMI adapter. Names such as firmware_a and world in the examples identify roles in an experiment, not attached firmware or a physical simulator. The examples are useful for understanding and checking the scheduler's actual contracts.

What Tempo owns

A federation is a set of participants, typed ports, and connections compiled into an execution plan. Tempo owns the federation's logical time, participant execution order, delivery queue, and synchronization points. Each participant owns its internal behavior and reports how far it advanced.

ComponentResponsibility
Python/TOML control planeDeclare participants and connections, request compilation, start runs, inspect plans and traces
Native federation compilerValidate declarations and resolve names into participant, port, and route indices
Native schedulerChoose deadlines, call participants, publish inputs, and manage same-time iteration
Participant implementationAdvance its own state, read input slots, write output slots, and report a stop reason
Trace infrastructureRecord execution and communication events without converting them to text in the execution loop

Python calls the native library through CFFI. A call to sim.run() enters the native scheduler; it does not invoke Python for each participant step or routed value. The scheduler works with the public participant interface, without QEMU instructions, peripheral registers, or FMI semantics in its core.

Build and run the supplied mocks

Use a C11 compiler, Python 3.11 or newer with virtual-environment support, Meson, Ninja, CFFI, and pytest. The following follows the repository's build path while selecting the reviewed revision explicitly:

git clone https://github.com/boardrunner2049/tempo.git
cd tempo
git checkout --detach 771b99650004fcbf3ab216970cf8fd9fae91aa6c
python3 -m venv .venv
source .venv/bin/activate
python -m pip install meson ninja cffi pytest
meson setup build --buildtype=debugoptimized
ninja -C build
meson test -C build --print-errorlogs
python -m pip install -e .

The native build produces libtempo and the trace-conversion tool. The editable Python installation supplies the tempo import and tempo-run command. If the Python loader cannot find a separately built library, TEMPO_LIB can name its full path. The Meson test setup includes Python tests only when its selected interpreter can import CFFI and pytest; check the test list rather than assuming a C-only success covered both layers.

Run these commands from the Tempo repository root:

tempo-run examples/two_firmware.toml --explain
tempo-run examples/two_firmware.toml --stats --trace run.trace
./build/tools/tempo-trace/tempo-trace info run.trace
./build/tools/tempo-trace/tempo-trace dump run.trace
python examples/motor_and_sensor.py

--explain compiles and prints the plan without running participants. The normal run reaches the configured 10ms, prints scheduler counters, and saves a trace. The Python example also prints final values: command 0.350, world output 1.120, and observed value 1.120.

Those values come from simple mock behavior. The first participant emits 0.70 at 3ms and 0.35 at 7ms. The world mock multiplies a changed input by 3.2; the receiving mock copies it. Each connection declares 500us. This is an algebraic echo experiment, not motor dynamics or a firmware flight test. Read the trace to see when the scheduler actually harvests and delivers each value; adding the two connection delays alone does not describe every participant's reaction time.

Declare ports and connections

The supplied TOML separates [simulation], [scheduler], [trace], [[participants]], [[connections]], and optional [[subscriptions]] tables. At this revision, mock is the registered participant type.

SettingMeaning
[simulation].end_timeRequired positive logical end time
[scheduler].policyconservative, the implemented scheduling policy
[scheduler].quantumMaximum communication window before other constraints shorten it
[scheduler].default_delayDelay for connections that omit one; otherwise follows the quantum
[scheduler].max_microstepsBound on same-time iteration and persistent lack of progress
[trace].enabled, capacityWhether to allocate a trace buffer and how many records to retain

Durations accept strings such as "500us", "3.5ms", or "10s"; bare numbers mean nanoseconds. A connection names an output and an input, for example:

[[connections]]
from = "firmware_a.motor_command"
to = "world.motor_command"
delay = "500us"

This fragment belongs to a federation that already declares those participants and ports. The compiler rejects missing endpoints, wrong directions, type mismatches, and multiple writers to one input. Unknown TOML keys also fail during setup, with a table or connection location in the diagnostic.

Ports support bool, int64, float32, float64, and bytes. A byte port declares a capacity, capped at 4096 bytes; a connection cannot route a wider declared sender into a narrower receiver. Participants access native slot arrays directly. Input slots have a generation counter that changes when the scheduler publishes a delivery, allowing inexpensive change detection.

Outputs are compared against shadow copies. Rewriting the same bytes normally creates no new delivery; a participant can increment the output generation to request a repeated value. Port names have become indices by this point, so ordinary routing does not search strings.

Use the Python control plane

This complete example uses the same mock API and leaves the connection at its default delay, which equals the 1ms quantum:

from tempo import Mock, Simulation

sim = Simulation(end_time="10ms", quantum="1ms", trace=True)
source = sim.add(Mock(
    "source",
    script="3ms:emit_sync 0 0.70",
    outputs={"command": "float64"},
))
sink = sim.add(Mock(
    "sink", echo=True, gain=3.2,
    inputs={"command": "float64"},
    outputs={"response": "float64"},
))
sim.connect(source["command"], sink["command"])

with sim:
    print(sim.explain())
    sim.run("5ms")
    print(sim.now, sim.value("sink.response"))
    sim.run()
    print(sim.finished, sim.stats)

The intermediate logical time is 5000000 nanoseconds and the response is approximately 2.24. The second run() continues to the federation's end; it does not restart it. The context manager releases the native participants, scheduler, plan, and trace.

Use sim.step() to execute one communication window. It returns whether more work remains. sim.participant_time(name) exposes individual progress, which can be ahead of sim.now; global time and every participant's current time are not interchangeable. Inspect sim.plan.execution_order, routes, components, and cyclic_components when a connection behaves differently from your expectation.

Time, horizons, and early return

Logical time is an unsigned 64-bit nanosecond count. Same-time ordering uses a separate microstep, forming a tag (time, microstep). A change from (3000000, 0) to (3000000, 1) advances event ordering without adding a fictitious nanosecond of physical time.

The native participant contract is advance_to(target, result): execute without passing the target, then report reached_time and a stop reason. Returning before the target is valid. The scheduler rejects backwards time and overshoot; participants can report target reached, an externally relevant event, blocked execution, completion, or failure.

A window first delivers values due at the current communication point. It then computes a horizon from the quantum, run limit, earliest queued delivery, and advertised next-event predictions. Participants below that horizon advance in compiled order. Global time becomes the minimum live participant time, capped at the horizon.

Timing boundary at this revision: that horizon is computed before the participant loop. A new short-delay delivery created during the loop does not immediately shorten the deadline already used for the remaining participants. A recipient can therefore have advanced beyond a newly discovered delivery time. A focused public-API check during handbook validation reproduced this: with a 1ms quantum, a source emitting at 250us, and a 100us connection delay, the recipient reached 1ms before the 350us delivery was processed.

Inspect recipient times and delivery traces around unexpected early returns. The default delay equal to the quantum avoids this particular within-window delivery case. Arbitrary short-delay or zero-delay experiments should not be treated as a general proof of conservative causality.

When a participant returns, Tempo harvests its output slots and dates changes at the reported reached time. A producer that returns as it writes provides a precise production boundary. A producer that continues running exposes its latest output only when the call ends; several intervening writes can be coalesced. A trace observation and a routed output are consequently different records with different purposes.

The mock makes this distinction directly testable:

Script actionBehavior
trapReturn control without writing an output
emit_sync 0 0.7Write output slot zero and return
emit_observe 0 0.7Write the slot and continue executing the script
mark 0 0.7Emit an observation without stopping
finishReport that the participant has finished

For example, "3500us:trap" produces an early return with a 1ms quantum. Adding predict=True lets the scheduler select 3500us as a horizon first, so the same stop is no longer early. max_step separately limits how far a mock advances per call. These options make timing behavior observable without attaching another simulator.

Same-time propagation

Zero-delay routes use microsteps. At a communication point, Tempo publishes due inputs, notifies affected participants, and invokes eligible same-time reactions until no additional due delivery remains. Reactions require the participant to be at the current logical time; a participant already ahead is not rewound.

The destination of a zero-delay route must advertise SAME_TIME_ITER, and its source must advertise EARLY_RETURN or PREDICT_NEXT. An echo mock supplies same-time behavior. Setup rejects missing capabilities instead of discovering them halfway through execution.

The compiler keeps the full dependency graph and a separate graph containing only zero-delay connections. Strongly connected components of the latter determine a stable execution order, with participant IDs breaking ties. A delayed connection does not create a same-time cycle. max_microsteps bounds propagation, and a cycle that keeps changing values reports TEMPO_ERR_NON_CONVERGENT instead of iterating forever. The supplied examples/same_time_chain.py demonstrates this mechanism with mocks.

Observe, reset, and compare

Tempo records fixed-size native events containing logical time, microstep, participant ID, type, flags, and sequence number. Observation records do not themselves stop a participant. Synchronizing behavior comes from the participant returning control; a trace flag describes that distinction.

With trace=True, Python requests 65,536 records. The default event selection includes scheduler decisions, port writes, and route deliveries. Explicit subscriptions narrow recording through the implemented type/namespace and participant masks; post-run filtering selects among records already collected. Address/argument predicates and subscription break requests are represented in configuration but are not enforced by the current execution path. Use the actual emitted records rather than assuming an address-specific subscription has filtered everything else.

The CLI warns when the ring drops records. Python exposes sim.trace.dropped; check it before treating a trace as complete. Save and convert outside the scheduling loop:

./build/tools/tempo-trace/tempo-trace dump --format=jsonl run.trace > run.jsonl
./build/tools/tempo-trace/tempo-trace dump --format=csv run.trace > run.csv

sim.reset() requires reset support from every participant. It resets participant progress, delivery state, slots, scheduler counters, and global time. It also emits a reset event. It does not clear the trace buffer, and sim.trace.clear() discards retained records without restarting sequence numbers or the cumulative dropped-record count. For repeat-run comparisons, save the first trace, reset, clear the buffer explicitly, and compare behavioral fields while accounting for sequence offsets. Record the starting dropped count and check its change during the run. Independent fresh runs can use fresh buffers for exact record comparison.

The repository's tests cover early return, prediction, delayed propagation, same-time chains and cycles, capability errors, deterministic mock runs, reset, configuration validation, and trace overflow. During handbook validation on x86-64 Linux with GCC 14.2.0 and Python 3.12.14, all six Meson test targets passed, including 51 Python cases. The README mock example and TOML run, plan inspection, and trace conversion also completed successfully.

Those results establish specific synthetic cases, not a blanket guarantee for every participant interaction. The implementation is single-threaded and exposes one scheduling policy. Its trace cause field is not automatically populated with complete causal parents by the scheduler, so chronological communication records alone are not a full data-provenance analysis.

Source guide

Command-line reference

The installed entry point is fastdyn, provided by fastdyn.main:cli. Run commands from the FastDyn repository root unless your paths are explicitly configured for another location. The examples assume the environment from installation is active.

fastdyn --help
fastdyn COMMAND --help

This reference covers the core CLI at f9666d7f518c373e89831d8e14a6371a27fe6436, with later additions labeled by revision. Plugin-specific settings belong in TOML rather than new top-level flags.

Global options

Place these before the command:

OptionEffect
--versionPrint the installed FastDyn version.
-v, --verboseSet the default console log level to DEBUG.
-q, --quietSet it to WARNING. Cannot be combined with -v.
--log-level [LOGGER=]LEVELSet a global or namespace-specific level; repeatable.
--log-file PATHAlso write Python log messages at DEBUG and above to a file.
--helpDisplay group help.

Without a level option, FASTDYN_LOG_LEVEL supplies the default, falling back to INFO. Native plugin messages use the native threshold but are emitted directly by QEMU, so --log-file does not collect them. Put saved log files outside a work directory that the runner will replace.

fastdyn --log-level fastdyn.targets=DEBUG run -c configs/minimal.toml

run

fastdyn run -c CONFIG [-o WORK_DIR]
OptionDefaultMeaning
-c, --config PATHRequiredExisting TOML file.
-o, --work-dir PATH./fastdyn_workRun outputs; an existing directory is replaced by default.
-s, --svd PATHRepository defaultExplicit SVD file or catalog.
-p, --persist-work-dirOffRetain an existing work directory.
--fmu NAMETOML selectionOverride the active FMU model.
--no-build-fmuOffSkip automatic FMU generation. The required artifact must already exist.
--no-run-processesOffSkip [Rumoca] and [Run.processes] helpers.
-m, --map-file PATHNoneAccepted legacy option; currently unused by the run implementation.

The run path validates runtime configuration, prepares the output directory, handles optional FMU generation, starts configured helpers, preprocesses the target, and launches QEMU. Guest module boot through [Run].bridge_boot remains active with --no-run-processes; it is a separate mechanism.

Configuration or launch failures produce an error. An unexpected QEMU failure also produces a nonzero command result. Ctrl-C produces the conventional exit status 130 after shutdown handling.

loop

loop accepts the same options as run:

fastdyn loop -c configs/target.toml -o out/repeated-target

After a clean exit it restarts with a fresh work directory. After a QEMU runtime error or a terminating helper failure, it restarts while preserving the directory for inspection. Configuration and setup errors stop the loop instead of retrying indefinitely. Automatic FMU generation is attempted only for the first iteration.

This is repeated execution of the configured experiment. It does not itself construct a function-level calling context or define a fuzzing snapshot boundary.

swarm

swarm launches isolated copies of one configuration:

fastdyn swarm -c configs/copter462.toml -n 2 \
  -o out/swarm/copter --base-port 18000 --dry-run
OptionDefaultMeaning
-c, --config PATHRequiredShared configuration template.
-n, --instances N1Number of workers.
-o, --work-dir-root PATH./fastdyn_swarmParent of worker output directories.
--base-port N15000Base for worker port allocation.
--port-stride N20Spacing between each worker's port set.
--jobs NNumber of instancesMaximum concurrently running workers.
--loopOffUse fastdyn loop for each worker.
--fmu NAMETOML selectionSelect the active model.
--no-build-fmuOffSkip the one-time build before workers start.
--no-run-processesOffSkip helper processes in each worker.
--timeout-sec SECONDSNoneOverall campaign timeout.
--smoke-sec SECONDSNoneRequire workers to remain alive for a bounded smoke interval, then stop.
--stop-on-failureOffStop launching new workers after a nonzero exit.
--skip-port-checkOffSkip the preflight TCP/UDP conflict check.
--dry-runOffPrint plans and commands without launching workers or building the FMU.

Workers receive separate RAM backing, QMP sockets, output paths, and configured service ports. Dry-run output verifies the plan, not firmware or FMU execution. A swarm does not implicitly connect the guest devices or physical worlds; see multiple firmwares.

build-model

Compile C device models into shared libraries:

fastdyn build-model models/uart.c -o build/models
fastdyn build-model models/ -o build/models -r -j 8
fastdyn build-model --name spi4 models/spi4.c models/spi4_dma.c -o build/models

The source paths must exist. -o/--out-dir is required. By default each C source becomes a model; --name combines the given files into one named model.

OptionMeaning
-r, --recursiveFind C sources below input directories.
-j, --jobs NParallel compilation; defaults to CPU count.
-k, --keep-goingContinue other model builds after a failure.
--exclude PATTERNExclude matching sources; repeatable.
--no-vioBuild without LibVIO.
--pkg NAMEAdd a pkg-config package; repeatable. fastdyn links the fuzzer hooks.
--jsonEmit a machine-readable build report.

Sources, headers, and the compiler command determine whether a model is rebuilt. A failed model does not retain an old output .so, and any failure makes the command exit with status 1. See writing a model for the ABI.

Addition at a38af40: --mmio-opt

At a38af408451394ea2f41be1e9cf1e96bc46c370f, build-model --mmio-opt enables experimental extraction of read-operation metadata. Run this example from a matching FastDyn checkout with the corresponding QEMU headers and build environment:

fastdyn build-model --mmio-opt --no-vio \
  tests/models/elder_echo.c -o build/mmio-models --json

This option selects clang-18, falling back to clang, and currently requires one C source per model. It embeds metadata in the normal .so and writes elder_echo.mmio.json beside it. The separate --json flag prints the build report, including mmio_operations; it is not required to create the metadata report.

Building metadata does not enable substitution by itself. Configure the library as an elder scroll and enable [CPU.cpu0.plugins.mmio_opt] in the run configuration. The feature has reviewed correctness limitations; use the automatic MMIO workflow for its matching setup, supported execution scope, reports, and validation requirements. Ordinary build-model usage does not require this option or its Clang dependency.

help

This command browses configuration choices, distinct from Click's --help option:

fastdyn help
fastdyn help platforms STM32
fastdyn help virtuals --no-browse

Available topics are platforms, virtuals, plugins, modifiers, device-models, machine, memory, firmware, and run. plugins currently aliases virtuals, so both display virtual actions and run-wide plugins.

Use --browse to force the picker or --no-browse for plain output. platforms accepts an optional vendor/platform query and -s/--svd PATH. The top-level help browser also accepts an SVD path. The platform catalog must be present, normally from setup.

timing-summary

fastdyn timing-summary out/first-run/fastdyn_timing.jsonl --top 20

The positional file must exist. --top defaults to 30. The command reports completed phases and marks, then lists phases by descending duration. Nested phases overlap, so summing all displayed durations does not give total execution time.

Source guide

Configuration reference

FastDyn reads one TOML file for a machine experiment. The core sections are [Machine], [Memory.main], and one or more CPU array tables such as [[CPU.cpu0]]. Device handling, plugins, FMU generation, and helper processes add their own sections.

This reference describes the current parser. Examples are fragments to merge into a complete configuration; do not paste a second definition of an existing TOML table or key. Use configure a firmware for the guided workflow and the feature chapters for plugin-specific settings.

Machine controls

Key in [Machine]Preferred value / defaultBehavior
platformOptional stringSVD platform metadata; generic-cortexm allows a generic Cortex-M profile.
qemu_pathOptional executable pathExplicit QEMU selection. Otherwise use FASTDYN_QEMU, recorded build metadata, then the architecture executable on PATH.
displayString, "none"QEMU display backend.
serialOptional stringExplicit QEMU serial backend.
monitorOptional stringExplicit monitor backend, overriding the default TCP choice.
monitor_portInteger, 5555Default monitor TCP port; 0 disables it.
qmp_socketString, "/tmp/qmp.sock"QMP socket; the default is replaced with a run-specific path.
enable_gdbBoolean, falseEnable QEMU's GDB server.
gdb_portInteger, 1234GDB server port.
stop_on_startBoolean, falseStart paused.
launch_gdbBoolean, falseRequest the automatic GDB-launch path.
log_optionsStringQEMU -d categories; "none" disables instruction logging.
log_filePath stringQEMU log destination; relative paths are under the work directory.
semihostingBoolean, false in the TOML parserEnable semihosting for supported targets.
semihosting_config"enable=on,target=native"QEMU semihosting configuration.
print_commandBoolean, falsePrint the generated QEMU command.
exit_timeout_msPositive integer, 5000Wait before force-killing QEMU during shutdown.
reset_memory_filesBoolean, falseClear file-backed RAM before launch.
biosOptional path stringFallback BIOS image for a CPU without its own bios.

The default QMP path becomes <work-dir>/qmp.sock. If that path exceeds Unix socket limits, the launcher selects a shorter per-user location. A nondefault explicit socket path remains explicit.

Simulation time

[Machine]
icount = { shift = 5, sleep = false, align = false }
timer_irq_period_ns = 1000000
exact_budget_stop = false

icount accepts a QEMU option string, a boolean, or a table. The table supports enabled, nonnegative integer or string shift, boolean sleep and align, and extra as a string or string array. enabled = false disables it. FASTDYN_QEMU_ICOUNT overrides the generated value.

timer_irq_period_ns selects the periodic board interrupt interval when used by the configured runtime. The maintained vehicle profiles use 1,000,000 ns. This is a simulation-time setting, not a claim that the host executes a step in one millisecond.

exact_budget_stop is parsed as a co-simulation stopping-mode option and defaults to false. At the reviewed e44dca2 revision, its native enabling call is commented out, so setting this field alone does not activate exact mode. Select exact stopping through the controller's --exact option or BudgetMaster(..., exact_stop=True), which sends QMP set-budget-mode. See FastDyn as a secondary simulator for the complete setup, timing contract, and validation limits.

Coverage and fuzzing

KeyDefaultMeaning
coveragefalseEnable the configured coverage path; requires a compatible build.
edge_coveragefalseAdd cumulative edge output when coverage is available.
fuzzingfalseStart the compiled input backend.
fuzzing_schemaAbsentJSON schema file for the generic native fuzzer.
finlineAbsentExisting static inline-I/O mapping path; see inline device modeling for its access-map and original-instruction handling.
savestate_extra_rangesEmpty arrayAdditional { start, size } regions for the native save-state machinery.

FASTDYN_COVERAGE, FASTDYN_EDGE_COVERAGE, and FASTDYN_FUZZING override their corresponding booleans. A save-state range accepts integer or integer-string addresses and a positive size; ranges exceeding the 64-bit address space are rejected. These settings do not make the current ARM-oriented snapshot implementation architecture-independent.

Memory banks

The main bank is a plain table. Additional banks use array tables:

[Memory.main]
id = "ram0"
base_address = "0x20000000"
memory_size = "256K"
backend = "file"
share = true

[[Memory.ram1]]
id = "ram1"
base_address = "0x30000000"
memory_size = "64K"
backend = "ram"
KeyDefaultMeaning
memory_sizeRequiredQEMU size string, for example "256K" or "8M".
base_addressUnsetGuest mapping base where supported by the machine.
idBank nameQEMU memory-backend identifier.
memory_type"SRAM"Metadata label: SRAM, MMIO, FLASH, DRAM, RAM, or SYSTEM.
backend"file"file, ram, or memfd.
memory_fileRun-local fileBacking path for a file backend.
sharetrueRequest shared mapping of the backend.

The generic Cortex-M machine maps additional banks through its custom properties. Other QEMU machines retain their own memory layout. Additional bank indices are generated in sorted name order. index and prealloc appear in some historical examples but are not consumed by the current TOML memory parser; do not rely on those keys to change the run.

Explicitly use backend = "file" when depending on swarm's FASTDYN_QEMU_MEMORY_DIR override. Keep arbitrary external RAM paths separate between concurrent runs. reset_memory_files clears guest RAM backing, not external device or helper state.

CPU and firmware

[[CPU.cpu0]]
arch = "arm"
machine = "cortexm"
cpu = "cortex-m4"
binary = "firmware.elf"
init_nsvtor = "0x08000000"
plugin_library = "build/libfastdyn.so"
KeyDefault / purpose
arch"arm"; selects architecture-specific launch behavior.
machine"cortexm"; QEMU machine model.
cpu"cortex-m4"; QEMU CPU model.
binaryFirmware path; supply the correct image for the selected machine.
init_nsvtorCortex-M initial vector address; when omitted for the generic Cortex-M ELF path, the launcher attempts to derive it.
plugin_libraryDefault FastDyn build library path.
drive_file, drive_formatOptional disk-image boot input; format defaults to "raw".
biosOptional CPU BIOS image, with machine-level fallback.
monitor_elfOptional monitor image used by existing monitor-based integrations.
twintrace"record", "replay", or disabled/"None".
hardware_traceTrace file for record/replay.
existing_config_pathDirectory containing existing virtual/modifier rules; false or empty disables it.
logger_contentExisting plugin-logger configuration text.

A QEMU instance with multiple CPUs requires homogeneous arch, machine, cpu, and binary, plus a common plugin library. The parser consumes the first entry under each CPU name. Do not put different firmware images into multiple entries of [[CPU.cpu0]] expecting separate instances.

Virtuals and modifiers are child arrays:

[[CPU.cpu0.virtuals]]
at = "0x080068b0"
instruction = "printreg"
args = ["0"]

[[CPU.cpu0.modifiers]]
at = "0x0800397e"
patch = "r0 <- 3"

Those addresses are from the bundled minimal fixture. The exact grammar and register support are described in virtuals and modifiers.

Run-wide plugins

[CPU.cpu0.plugins.function_counter]
enabled = true

Each plugin owns the remaining fields of its table. An optional source names an external plugin directory, resolved relative to the configuration file. FastDyn removes source before handing settings to the plugin. See virtual plugins for the host/runtime contract.

Devices and handlers

[Device.Models.<name>] registers a model family and its optional backend. [Device.<device>] declares regions and model-specific configuration. Each [[Device.<device>.handlers]] entry needs model and enabled; optional fields include scroll, args, and type.

[Device.Models.elder]

[Device.uart]
ranges = [["0x40004400", "0x400047ff"]]
irq = [54]

[[Device.uart.handlers]]
model = "elder"
enabled = true
scroll = "models/uart.so"

This fragment requires an actual model implementing the selected device. Device-specific fields outside FastDyn's reserved keys are carried to the model. slaves and connections support attached devices and host endpoints as documented in the device chapters.

irq is a list of numbers, numeric strings, SVD names, or inclusive [first, last] ranges. Cortex-M numeric values are exception numbers. The old colon-separated string form is rejected. FastDyn also rejects enabling both passthrough and twintrace hardware backends for the same device, because both would issue accesses to the physical probe.

FMU selection and generation

[FMU]
active = "quadrotor"
auto_build = true

[FMU.models.quadrotor]
model = "FastDyn.Copter"
model_file = "modelica/FastDyn/Copter.mo"
source_roots = ["modelica", "third_party/common/modelica_models"]
output = "out/fmi3/Copter"
build = true
release = false

active, FASTDYN_FMI_NAME, or --fmu selects a named entry, in increasing precedence. A configuration may alternatively place one model directly in [FMU], in which case --fmu NAME is not applicable.

model and model_file identify the Modelica model. Supply source_roots as a nonempty path array, or source_root for one root. output defaults under out/fmi3/. build = true requests a packaged FMU; false emits a source tree that still needs a compiled runtime binary before execution. auto_build defaults to false, while the maintained vehicle profiles enable it. release controls the Rumoca Cargo build mode.

[FMU.models.<name>.parameters] holds numeric parameter overrides. compose selects a composition file; an inline physics table is an alternative and must name the same model. These alternatives cannot be combined. [FMU].rumoca_dir or FASTDYN_RUMOCA_DIR selects the compiler checkout. See physics and FMU for package loading and the model interface.

Helpers, bridge boot, and profiling

[Run] supplies cwd and env defaults for helpers. Each [Run.processes.<name>] accepts:

KeyDefault / behavior
commandRequired string or string array. A string uses a shell by default.
enabledtrue
cwdRun default, then repository root
envAdditional helper environment
backgroundtrue; false runs the helper synchronously during startup
quietfalse; true discards stdout/stderr
start_delay_sec0; delayed startup
ready_messagePrinted after starting; it is not a readiness probe
stop_on_exittrue; stop the helper when FastDyn exits
terminate_run_on_exitfalse; when true, helper exit stops QEMU
shellExplicit shell behavior override

[Run].bridge_boot selects the console initialization script used by profiles such as PX4. It is independent of helpers. FASTDYN_BRIDGE_BOOT overrides it; an explicitly empty value disables automatic console initialization.

[Rumoca] configures the optional separate Rumoca viewer/lockstep process. It is normally disabled in the in-process ArduPilot FMU path.

[Run.profiling] supports timing and timing_echo (both default true), python (false), fmu (defaults to the timing setting), perf ("off", "stat", or "record"), perf_events, and perf_frequency_hz (99). Profiling outputs live under the work directory; Linux perf use also depends on host availability and permissions.

Path and environment rules

Field familyResolution
Firmware, hardware trace, scroll, slave device_scroll, Python endpoint helperConfiguration directory first if the file exists there; otherwise current-directory behavior.
External plugin sourceConfiguration directory.
existing_config_path, fuzzing schemaConfiguration directory, current directory, then discovered repository root.
FMU sources/output and helper working directoriesRepository-root-relative unless absolute.
TOML bridge_bootRepository root; environment override is caller-directory-relative.
QEMU log_fileWork directory when relative.

Helper strings support ${NAME} and ${NAME:-default} expansion. That is not a promise of arbitrary shell expansion in every TOML field. Swarm injects explicit overrides for monitor/GDB/service ports, RAM backing, and QMP sockets.

Core configuration is not a uniformly closed schema: a key found in an old example may be ignored by today's parser. Use this reference and the source of the consuming plugin, and inspect generated artifacts when changing a critical field.

Source guide

Plugin and callback catalog

FastDyn uses several extension mechanisms. A virtual instruction is a named action triggered at a guest PC. A run plugin prepares a feature for a CPU and may generate many internal hooks. Device handlers, physics backends, and campaign drivers have their own interfaces. Similar names do not make them interchangeable configuration namespaces.

This catalog covers the pinned main revision used by the book. For configuration snippets from your checkout, run:

fastdyn help virtuals --no-browse
fastdyn help plugins --no-browse
fastdyn help modifiers --no-browse
fastdyn help device-models --no-browse

plugins currently aliases the virtual/plugin browser. That browser shows definitions carrying public ConfigurationHelp; it does not enumerate every native callback installed by optional backends or generated by a firmware profile. A help entry also does not prove that an optional native library was included in your build.

Public core virtual instructions

These fifteen names appear in both the core native registry and Python's built-in virtual definitions. Configure them with [[CPU.cpuN.virtuals]], at, instruction, and optional args. Names are case-sensitive; raise_irq is a compatibility alias normalized to raiseirq by preparation.

Exact namePurposeImportant contract
printregPrint one registerArgument is the target register number
debug_logEmit a guest-event diagnosticArguments become a message string
updatememRead/write guest memoryUse its address/direction/length/byte-list grammar
randstateRandomize selected stateRegister numbers and addresses have different interpretation; do not randomize the PC
raiseirqRaise an interruptNumeric arguments are exception vectors; symbolic preparation is Cortex-M-specific
pulseirqPulse an interruptRequires the appropriate target IRQ semantics
raise_periodic_irqRegister a repeating interruptOptional period is in nanoseconds
timer_startStart the legacy timerSeparate from the benchmark timer
start_budgetingEnter budget waitingIntended for an experiment with a controller/budget contract
benchmark_startBegin a timing regionUses host monotonic time
bench_tickCount benchmark ticksOperates on the benchmark state
benchmark_endReport a timing region and terminate QEMUA terminal action, not a passive marker
dyninstCopy a host file into guest memoryChanges guest memory at runtime
dyninst_libLoad an ELF through the QEMU plugin APIRequires a compatible ELF and loading context
dumplogDump an internal logger bufferUses the logger-index/file argument form

These are registry names, not a promise that every action has identical meaning on every guest architecture. See virtuals and modifiers for argument grammar, register conventions, and same-PC conflicts.

Run-wide plugins

These are the six in-tree RunDefinition names discovered from feature-owned host/preprocessor.py files. Enable them with [CPU.cpuN.plugins.<name>] and enabled = true, then supply the feature's own settings.

Exact plugin namePrepared/runtime behaviorScope and output
function_counterSelect executable function entries and count hitsELF symbols; functions.tsv, final counts.tsv
function_tracerPrepare entry-argument layouts and record callsSupported DWARF/ABI forms; arguments.tsv, trace.tsv, counts
variable_watchResolve one variable or address range and observe overlapping accessesCurrent Thumb/M-profile planner; watch.tsv, events.tsv
object_sanitizerSelect objects/allocation sites and track supported provenanceCurrent Thumb/M-profile planner; object lifecycle and violation records
introspectionIdentify supported RTOS hooks and prepare kernel schemasAdapter-specific task/resource events; schema.txt, activity.jsonl
worldPrepare a physical-world description and firmware pin bindingsRequires built tools/world native dependency; world state and optional observation

The first five native modules are included by the normal virtuals/meson.build feature list. World is automatically compiled when the expected header and tools/world/build/libworld_model.so exist. Enabling its TOML table cannot manufacture a missing native runtime.

The narrative guides cover tracing and object checking, RTOS introspection, and World integration.

Internal callbacks belong to their feature

Run plugins may register native callbacks that are implementation details. For example, Function Counter generates function_counter; ObjectSan uses object_sanitizer_alloc_call, object_sanitizer_alloc_return, and object_sanitizer_free; World uses world_digital_out and world_analog_in. Introspection selects numerous RTOS-specific hook names from the firmware.

Configure the owning plugin rather than manually reproducing its schema and internal rules. The callback registry only connects a name to native behavior; it does not supply the prepared manifest, target layout, or correct argument convention by itself. Two plugins that generate different callbacks at the same PC still encounter the dispatcher's one-callback restriction.

Optional mechanisms and their gates

MechanismHow it is selectedBuild/runtime requirement
Inline modifiersCPU modifiers arrayPatched target backend; register/width semantics are architecture-specific
Specialized inline I/O[Machine].finlineStatic access-map path with explicit backing state and original-instruction handling; see inline device modeling
Device handlers[Device.Models.*] and handler assignmentsDevice-model build; hardware paths also require libhw
Vehicle physics[FMU], physics options, and controller profilesPHY=true; FMU=true for FMUs; FLIGHT_CONTROLLERS=true for controller adapters
Legacy Gazebo physicsSelected Gazebo backendPHY=true LIBGZ=true and matching Gazebo dependencies
Native firmware fuzzingMachine fuzzing/coverage settings and a harnessLibAFL or AFLNet build; initialized coverage and snapshot ranges
External runtime pluginPlugin table's source folderRegistered host half and compatible runtime/*.so descriptor/SDK linkage
Swarm/campaign orchestrationCLI or downstream driverSeparate worker configuration and dependencies; not a run-plugin name

The feature browser advertises device-handler names classic, passthrough, elder, twintrace, and unhandled. These are not virtual instruction names. The legacy halucinator/Python embedding path is separately gated and is documented upstream as currently failing to build.

When a native fuzzing build initializes with coverage, it registers assert, fuzz_advance_time, fuzz_snap_point, fuzz_snap_sync_point, fuzz_state_point, fuzz_sync_point, and fuzz_virtual_millis. These are conditional native callbacks, not additional public core definitions. Use the fuzzing harness guide for their lifecycle rather than assuming they exist in the minimal build.

Controller integrations likewise register profile-specific actions such as start_advancing_sim, ins_block_read, write_channel, and bridge_px4_uorb. Their names and ABI expectations belong to the flight-controller integration, not a generic sensor protocol.

Adding a new feature

Register user-facing help beside the feature, keep derived data in artifacts, and declare required capabilities on virtual definitions where applicable. The generic preparation code supplies core, conditionally fuzzing and fmu, plus explicit host-provided capabilities. Build options, available artifacts, target support, and enablement remain separate facts that the feature must handle consistently.

See writing plugins for the supported host/native registration and external-plugin workflow.

Source guide

Capability status

This book records the source revision behind each explanation. Core chapters retain the FastDyn baseline f9666d7f518c373e89831d8e14a6371a27fe6436; the JIT patcher and manual inline lab use 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c. Current main hot paths, automatic MMIO, and secondary execution are pinned to e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576 (12 November 2026). Tempo is reviewed at 771b99650004fcbf3ab216970cf8fd9fae91aa6c. Supercache has separate frontend/backend requirements in its chapter; its offline optimizer is reviewed at FastDyn scopt revision 124699db203aae581735b4bdfb82e9b949332405. FirmBOLT is reviewed at FastDyn firmbolt revision b14f14cb4992d28d56cda5e73685a5f7c432c5cf. Presence in source does not mean every combination was executed during documentation preparation, and separately pinned branch features are not silently treated as main-branch configuration options.

Main-branch capabilities

CapabilityStatus and scopeGuide
Configurable firmware executionPatched QEMU, native plugin, TOML frontend, public Python run APIFirst run
Multiple guest targetsARM examples; RISC-V/x86 templates and architecture-specific helpers; feature support variesPortability
PC-triggered virtualsNative runtime callbacks selected during preparation/translationVirtuals and modifiers
Register/memory modifiersCurrent specialized inline operation grammar and target restrictionsVirtuals and modifiers
Manual inline device modelingExplicit finline access map and a single fixed GPIO backing buffer; manual site selection and target-specific behaviorInline device modeling
Automatic MMIO optimizationBounded, tested experimental path at e44dca2: ABI 2 effect/predicate/width analysis, live elder-state binding, and guarded Cortex-M Thumb read replacement. Alignment faults and active or later-registered observers remain on original dispatch; unsupported cases decline. Not a proof for arbitrary models; coverage/fuzzing disable substitution.Automatic MMIO
Saved-PC MMIO exporterMain e44dca2: version-2 callbacks receive the existing saved PC as a scalar instead of allocating a GDB-style register buffer per access; still ordinary device dispatchHot-path optimizations
Constant-PC chainingMain e44dca2: safe ARM32 A32/Thumb fixed immediate r15 redirects can use QEMU TB chaining; same-page, mode, callback and slot restrictions with legacy fallbackHot-path optimizations
JIT patcherAt 5b8bf3d: immutable guest instruction fragments inserted before an original PC; explicit ISA/mode profiles and bounded register-only subsetsJIT patcher
Shared host analysisLazy image, symbol, DWARF, decoding, and RTOS facts; at e44dca2, cached constant-propagation access candidates. Shared decoding currently targets Thumb/M-profile.Host analysis
In-tree and external pluginsPreparation registration, native SDK, external runtime ABI v1Plugin development
RTOS introspectionSix adapters; task walkers and event hooks have different coverageIntrospection
Function counts and tracesEntry instrumentation, counts, and selected argument decodingTracing
VariableWatchELF-backed candidate analysis for named data or raw address rangesTracing
ObjectSanInstrumented object-bound checks with explicit modeled-object and target scopeSanitizers
C peripheral modelsElder model ABI v2 and incremental shared-library builderWriting models
Hardware and replaylibhw passthrough and twintrace modes with their current transaction/IRQ rulesHardware and traces
FMI physicsIn-process FMI 3 runtime, build/package handling, and controller adaptersPhysics
Flight-controller profilesArduPilot and main-branch PX4 examples; selected software boundaries and model shapesFlight controllers
Optional world integrationPhysical endpoint/pin adapter and observer with current ARM/scalar constraintsWorld models
Independent campaignsLoop and swarm tooling with worker isolationMultiple firmwares
Coordinated guest progressQMP budget commands, BudgetMaster, and a multi-guest barrier example; application supplies inter-firmware links. At e44dca2, select exact stopping explicitly through QMP or the client's --exact.FastDyn as a secondary simulator
FuzzingOptional fuzz engines, coverage, schema flows, and campaign integrations with target-specific reset semanticsFuzzing
Timing/profilingPhase records, optional helper cProfile, QEMU perf, and FMU profilingPerformance

Separately pinned components

SnapshotWhat it addsEvidence boundary
INAV: 3910be12b82443efe8abb75ef89aa02f5ef047f4MATEKF405 firmware adaptation, FMU bridge, receiver input, and smoke testsDocumented source compatibility patch; short functional/flight checks, not a blanket mission qualification
PX4: 0e13b73986a66270a6d8452b2c0147af7b874d29FMUv6C profiles across five release lines, version sweep, and cache-management workVersion-specific validation levels and cache configuration requirements
SupercacheTranslated-code caching in a separately pinned QEMU backend; managed cache configuration in the PX4 frontend snapshotThe pinned QEMU submodule base in main e44dca2, even after its ordinary five FastDyn patches, does not provide the separately developed persistent-cache backend. Follow the Supercache chapter for the exact revisions, setup, and compatibility boundary.
Supercache optimizer: FastDyn scopt at 124699db203aae581735b4bdfb82e9b949332405Offline snapshot import, profile-guided layout, cross-block transforms, state-sync reduction, and checked native host inliningUses QEMU 934890ed5119ef70da69276991d921573f23ed4f and pass-specific capture, runtime, metadata, and validation contracts. The optimizer chapter separates inspected code, local checks, and source-recorded runtime evidence.
FirmBOLT: FastDyn firmbolt at b14f14cb4992d28d56cda5e73685a5f7c432c5cfExtended BOLT with a direct Cortex-M/Thumb backend, typed references and exact origins, and firmware acceptance/compact-publication workflowsUses the tracked extension over LLVM/BOLT 7864c0736a8a09670dfbfc513f1e9649799f2486. CPU qualification, timing/observation policy, and reference completeness determine eligibility. The FirmBOLT chapter distinguishes source-recorded Cortex-M checks, x86-64 measurements, and the Python checks repeated for this book.
Tempo: 771b99650004fcbf3ab216970cf8fd9fae91aa6cNative scheduler, federation compiler, typed port routing, tracing, and Python/TOML control planeThe shipped participant adapter and executable examples use mocks. The Tempo chapter records the current scheduling and observation limits; this revision has no FastDyn or FMI adapter.

Branch previews gives the INAV and PX4 checkout commands, firmware identities, source links, and reported outcomes. The Supercache chapter specifies its separate frontend/backend pair. The book does not independently rerun those flight validations.

Read a result at its actual boundary

A boot smoke test, a sensor/motor check, and an autonomous mission establish different behavior. A high-level sensor hook and a register-level peripheral model execute different portions of the firmware. A four-channel plant interface does not establish a six-motor integration merely because a hexa configuration file exists.

Record the firmware, model, adaptation, time policy, and success condition with every result. Use the testing and reproducibility guide to decide what evidence is needed for the question being asked.

Source guide

Glossary

The terms below distinguish the firmware being executed, the tools preparing its environment, and the native code that implements the experiment. A capability can belong to the general framework while a particular adapter still has an architecture or firmware-specific contract.

Execution and instrumentation

TermMeaning in FastDynRead more
GuestThe emulated target CPU, firmware, memory, and visible devices. A guest register or address belongs to this target, not to the machine running FastDyn.System model
HostThe real machine and software running Python preparation, QEMU, native plugins, model libraries, and optional helpers. Host-side analysis is separate from guest execution.Execution pipeline
RehostingExecuting a firmware image in a reconstructed environment that supplies the CPU, memory, device behavior, and other dependencies required by the selected workload. Booting is one milestone, not a complete validation criterion.Choose a workflow
ISAInstruction set architecture: the instruction encodings and architectural behavior expected by a firmware. CPU mode and enabled extensions also matter; an architecture family name alone may not determine decoding.Portability
ABIApplication binary interface: conventions for arguments, return values, stack use, data layout, and related boundaries. A callback replacing a function must honor the target's ABI. FastDyn's x86-64 convenience macros use System V AMD64, not Windows x64.Virtual plugins
Guest address / PCAn address in the target's address space; the program counter identifies execution position. Numeric trigger PCs are tied to an image and load layout. Some architectures also encode execution mode in function-pointer representations.Virtuals and modifiers
Translation block (TB)QEMU's unit of translated guest code. TB formation depends on translator constraints and runtime state; a TB is not guaranteed to match one source-level basic block.Execution pipeline
TCGQEMU's Tiny Code Generator, which uses an intermediate representation to generate host code for guest execution. FastDyn's translation hooks and supported modifiers interact with this path.Execution pipeline
SupercacheA separately versioned QEMU backend facility for persisting and reusing translated code. Backend compatibility, cache identity, and supported execution modes are part of its setup contract.Supercache
Supercache optimizer / scoptAn offline tool on the FastDyn scopt branch that imports captured host translations and metadata, applies selected passes, and validates separate output artifacts against the recorded runtime and experiment.Supercache optimizer
Native host inliningIn scopt, replacing an admitted host call with a checked native fragment inside the saved translation. The implementation checks the callee's bytes, runtime binding, effects, and emitted correspondence before accepting the candidate.Supercache optimizer
FirmBOLTThe separately pinned firmbolt branch's extended BOLT pipeline and firmware acceptance layer. It rewrites eligible firmware instructions, including a direct Cortex-M/Thumb path, and checks references, origins, layout, and the selected observation contract before publication.FirmBOLT
FirmwareCandidateA versioned artifact containing an exact firmware image, target description, memory/layout evidence, origin map, and optimization report. Consumer-specific hook rebinding and execution validation are separate steps.FirmBOLT
Virtual instructionA named FastDyn runtime action triggered at a guest PC, usually implemented as a callback. It does not mean a new opcode was written into the firmware image.Virtuals and modifiers
ModifierA configured state operation associated with a guest PC, such as a register update or supported memory operation. The supported forms are lowered through the patched translation machinery; the original firmware bytes remain unchanged.Virtuals and modifiers
JIT patcher / guest instruction fragmentA native SDK facility that registers bounded, admitted guest instruction bytes before an original PC. The target frontend translates them without placing the bytes in the firmware image or relocating its instructions.JIT patcher
HookA selected event or execution point where instrumentation takes effect. PC callbacks, interrupt entry/exit observers, and translation hooks are different hook types with different contexts.Virtual plugins
Host preprocessorPython code that runs during preparation to resolve symbols, select instrumentation, generate rules, and write runtime input artifacts. It is not invoked for every guest instruction.Host analysis
Runtime pluginA native extension using FastDyn's runtime SDK inside the QEMU process. It can register callbacks and observers and access its artifacts. This differs from the top-level libfastdyn.so QEMU plugin that hosts the extensions.Plugin catalog
Host analysis sessionA lazy, scoped source of reusable facts about an immutable firmware image: image data, symbols, DWARF, and supported decoding. Plugins retain ownership of selection policy and instrumentation plans.Host analysis

Devices and physical models

TermMeaning in FastDynRead more
MMIOMemory-mapped input/output: accesses to guest addresses whose meaning is supplied by a device rather than ordinary RAM. Reads and writes may have side effects such as consuming data, clearing status, or starting DMA.Device models
Device modelA runtime implementation of a device's observable behavior, including registers, transactions, state transitions, and interrupts as required by the experiment. A physical transfer function supplies only part of this behavior.Writing a model
Inline device modelingA translated device operation at a selected firmware PC using host backing state. The legacy manual finline path uses a separate buffer and requires explicit handling of the original instruction.Inline device modeling
Automatic MMIO optimizationThe experimental mmio_opt pipeline introduced at a38af40: model-operation extraction, shared firmware access discovery, binding to initialized elder state, and guarded load replacement. Its analyzer and runtime have documented correctness limits.Automatic MMIO
Hardware passthroughForwarding selected peripheral interactions to a real board through libhw and a probe. The real peripheral contributes behavior while firmware execution remains in QEMU.Hardware and traces
TwinTraceFastDyn's hardware-trace recording and replay machinery. Replay follows the recorded interaction contract; it does not create an unrestricted generative model of the device.Hardware and traces
LibVIOThe companion library providing reusable bus, signal, DMA, and host-I/O mechanisms for C device models. Device-specific register semantics still belong to the model.Writing a model
SVDCMSIS System View Description data used for device/register and interrupt metadata. Selecting an SVD platform does not automatically implement that platform's peripherals.Configuration
Firmware profileA concrete configuration and associated hooks or adapters for a particular firmware, version, and execution path. Courbet vehicle profiles contain this firmware-specific knowledge.Flight controllers
FMIFunctional Mock-up Interface, the interface through which a model is instantiated, receives inputs, advances, and supplies outputs. The maintained FastDyn path uses FMI 3 Co-Simulation.Physics and FMU
FMUFunctional Mock-up Unit: the model artifact, commonly packaged with modelDescription.xml, executable binaries or sources, and resources. FastDyn's current backend loads the compiled model into the QEMU process.Physics and FMU
PlantThe physical system modeled around the controller, such as a motor, vehicle, circuit, or thermal process. Firmware produces actuation inputs; the plant produces states or observations delivered back through an adapter.World models

Time and orchestration

TermMeaning in FastDynRead more
Host elapsed timeReal elapsed duration on the computer executing the experiment. It includes the work being measured and can be affected by scheduling, logging, and other host load. It is distinct from simulated time.Performance
Guest virtual timeQEMU's simulation clock, exposed by FastDyn in nanoseconds. How it advances depends on the configured timing mode; it is not automatically a cycle-accurate MCU clock.Multiple firmwares
Plant timeThe time to which a physical model has been advanced. The integration policy aligns plant progress with guest time; the FMI boundary may express times in seconds while FastDyn scheduling uses nanoseconds.Physics and FMU
Instruction count / icountQEMU icount relates instruction progress to virtual time. It is separate from FastDyn's virtual_icount() counter, whose current wiring depends on twintrace. Neither establishes real hardware instruction latency.Configuration
Secondary simulator / co-simulation slaveA FastDyn guest whose execution is paced by an external controller through QMP time grants. The shipped client is BudgetMaster; state exchange and physical-model ownership remain explicit parts of the experiment.Secondary execution
SliceA bounded interval of virtual execution granted to a secondary by its controller. Completion is established by a stop event and observed time; the stopping mode and instruction-time granularity determine the reached boundary.Secondary execution
Physics stepAn advancement interval used by the physical model or its integration loop. It is separate from a TB and from a controller's execution slice, even when the experiment coordinates these intervals.World models
LockstepCoordinated advancement in which participants exchange required inputs or results at defined synchronization boundaries. Synchronizing clocks alone does not define the data connections between participants.Multiple firmwares
SwarmFastDyn's orchestration of isolated copies of a configuration with distinct worker resources. It scales independent experiments; cross-worker device or physical connections must be defined separately.CLI reference
TempoThe companion native co-simulation scheduler and federation compiler, configured through Python or TOML. The reviewed revision executes mock participants.Tempo
FederationIn Tempo, a configured collection of participant instances, typed input/output ports, connections, and scheduling settings, compiled into a native execution plan.Tempo
MicrostepTempo's ordering index for activity at one physical timestamp. A tag combines time and microstep so same-time work can be processed in a defined order subject to the configured iteration bound.Tempo

Analysis and testing

TermMeaning in FastDynRead more
Fuzzing schemaA JSON description of input fields, incremental streams, injection hooks, and optional snapshot/synchronization flow. The schema describes a chosen harness; it does not prove its state assumptions are valid.Fuzzing
CoverageFeedback recording executed regions or transitions, such as translated-block PCs and cumulative edges. It helps compare exploration but does not establish correctness, physical feasibility, or a lossless instruction trace.Fuzzing
SnapshotCaptured guest state used to repeat an execution boundary. The current native fuzzing implementation has ARM-oriented register and memory contracts. Rewinding it does not automatically rewind arbitrary host services, physical boards, or external model state.Fuzzing

Source guide

Source map and documentation index

The core chapters and original documentation index below retain the FastDyn baseline f9666d7f518c373e89831d8e14a6371a27fe6436. The JIT patcher and manual inline lab use 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c. Automatic MMIO, current runtime fast paths, and secondary execution are reviewed at e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576. Tempo uses 771b99650004fcbf3ab216970cf8fd9fae91aa6c. The Supercache optimizer uses FastDyn scopt at 124699db203aae581735b4bdfb82e9b949332405 with QEMU 934890ed5119ef70da69276991d921573f23ed4f; the earlier cache-reuse chapter retains its separate frontend/backend pair. FirmBOLT uses FastDyn firmbolt at b14f14cb4992d28d56cda5e73685a5f7c432c5cf, with the tracked extension over LLVM/BOLT 7864c0736a8a09670dfbfc513f1e9649799f2486. Links identify the recorded revision so a later change to main does not silently change the evidence behind an explanation.

The book organizes the material by reader workflow and system boundary. The original pages, target-specific notes, and example assets remain useful for detailed port work. A mapping below identifies the new chapter that explains the topic; it does not mean every historical command or measured result has been repeated or revalidated.

How to establish current behavior

Use the implementation and shipped configurations at the recorded revision to determine supported interfaces and defaults. Tests identify intended contracts and meaningful validation paths. Actual run records establish whether a particular build and experiment passed them. The presence of a test or workflow is not a passing result.

Where earlier documentation differs from current code, this book follows the inspected implementation. Its chapters and source mappings cover available interfaces, their prerequisites, and the limits established by code and validation evidence.

FastDyn's submodules have their own revisions. The top-level revision pins their gitlinks; check those recorded commits before attributing behavior from a newer upstream QEMU, LibVIO, Rumoca, or model library to this snapshot.

Advanced execution sources

Book chapterImplementation sources and scope
SupercacheSeparately pinned QEMU Supercache implementation and PX4 frontend cache-management code. The chapter distinguishes these from main's older QEMU gitlink.
Supercache optimizerFastDyn scopt at 124699d: offline workflow, host-inline pass, native BOLT bridge, and the matching runtime source lock. The chapter records artifact identity, pass admission, publication checks, and validation scope.
FirmBOLTFastDyn firmbolt at b14f14c: direct Cortex-M/Thumb BOLT extension, native firmware report pass, Cortex-M qualification runner, and firmware wrapper. The chapter separates the direct firmware rewrite path, publication contracts, consumer-specific validation, and source-recorded measurements.
Inline device modelingMain 5b8bf3d access-map preparation, native LOAD_IO/STORE_IO registration, GPIO backing state, and the pinned QEMU lowering. This is the existing manual mechanism.
Automatic MMIO optimizationAt e44dca2: AutomaticMMIOOptimization.md, model extractor, native binding, and QEMU replacement patch. The chapter records the experimental workflow, correctness fixes, and current limits.
Shared access discoveryThe a38af40 constant-propagation service, session integration, and MMIO compatibility adapter. Plugins filter shared candidates and own their installation policy.
JIT patcherGuestInstructionFragments.md, native SDK, tracked QEMU patch, and shipped plugin/probes at 5b8bf3d.
Translation insertion designImplemented address, lifecycle, admission, and observation contracts for guest instruction fragments; retained at its original URL.
Runtime fast pathsAt e44dca2, the MMIO saved-PC callback and ARM32 constant-PC chaining implementations, matching QEMU overlays, regressions, and recorded benchmarks.
FastDyn as a secondary simulatorAt e44dca2, BudgetMaster, lockstep controller, the QEMU budget patch, native exact-mode option handling, and the RLC world fixture.
TempoAt 771b996, federation compilation, native scheduling, Python/TOML configuration, mock participants, and trace/reset behavior.

The source guides in these chapters pin the exact files used. Check each chapter's revision and prerequisites before combining its commands with another checkout, especially for separately versioned backends and branch-only features.

Earlier pages in docs/

The following pages in the original f9666d7 snapshot's docs/ directory provide background for implemented interfaces. The newer execution mechanisms are mapped in the Advanced table above.

Original sourceNew book chapterMaterial to retain
ActivityMonitor.mdRTOS introspectionActivity events, monitor configuration, and observation workflow.
Building.mdInstallationSource builds, optional components, and model-build installation.
BuildingAConfig.mdConfigure a firmwareELF-to-config and guided discovery.
ClassicDeviceModel.mdDevice modelsClassic backend entry point.
CoSimulationOverview.mdMultiple firmwaresCoordination, model coupling, and clock boundaries.
CoSimulationSlave.mdMultiple firmwaresQMP budget protocol, slices, and stop semantics.
CodingConventions.mdVirtual plugins, testingSource conventions, SDK boundaries, and contributor expectations.
Configuration.mdConfiguration referenceTables, runtime options, paths, and environment overrides.
ElderScrollDeviceModel.mdWriting a modelNative model libraries and device callbacks.
FastDynDeviceModel.mdDevice modelsHandler families and their role in a run.
FastDyn_STR_Integration.mdFuzzing, CLIIntegration inputs, schema concepts, and campaign artifacts; check examples against the current schema parser.
FlightControllerSimulation.mdFlight controllersVehicle runs, mission helpers, visualization, and parallel campaigns.
FunctionCounterPlugin.mdTracing and sanitizersFunction selection, entry counts, and output artifacts.
FunctionTracerPlugin.mdTracing and sanitizersFunction-entry and argument observation.
Fuzzing.mdFuzzingNative input fuzzing and OptiFuzz workflow selection.
HostAnalysisAPI.mdHost analysisShared image, symbol, DWARF, and decoder contracts.
HostAnalysisMigration.mdHost analysisExtraction inventory, consumers, deliberate non-migrations, and historical verification records.
HostAnalysisRuntimeGuide.mdHost analysisPreparation-time use, sessions, and division between reusable facts and plugin policy.
IntrospectionExamples.mdRTOS introspectionBundled RTOS fixture configurations.
ObjectSan.mdTracing and sanitizersObject selection, static/dynamic checks, and supported analysis scope.
PassthroughDeviceModel.mdHardware and tracesPhysical-board access entry point.
PlatformBrowser.mdConfigure a firmware, CLIArchitecture presets and SVD platform discovery.
RunningFastDyn.mdFirst experiment, debuggingRun lifecycle, output directory, and logging.
VariableWatch.mdTracing and sanitizersSymbolic and raw-range data-access observation.
VirtualPluginBrowser.mdPlugin catalog, CLIDiscoverable virtual/plugin choices.
VirtualPreprocessing.mdVirtual pluginsPreparation contexts, results, generated artifacts, and collisions.
VirtualsAndModifiers.mdVirtuals and modifiersUser syntax, built-in actions, and translation/runtime distinction.
WorldPlugin.mdWorld modelsImplemented endpoints, pin hooks, advancement, and observers.
WritingVirtuals.mdVirtual pluginsAdding native and host halves, registering modules, and testing.
chaos.mdFuzzingTask-loop execution controls and coverage mechanisms, checked against the runtime implementation.

Specialized READMEs and fixture guides

These links preserve the concrete entry points that a broad chapter cannot replace.

Source guideNew book chapterSpecific purpose
Repository READMEWelcome, installationProject entry point and repository quick start.
Runtime SDKVirtual pluginsPublic native operations, architecture headers, and complete module examples.
Fuzzer implementationFuzzingNative backends and protocol-harness entry points.
LibAFL libraryFuzzing, installationRust backend and older container workflow.
OptiFuzz/CP-ExploreFuzzingParameters, physical properties, vehicle selection, and campaign outputs.
Generic schemaFuzzingComplete field, expression, stream, hook, and flow grammar.
Physics integrationPhysics and FMU, flight controllersMaintained FMU path, timing, and legacy backend notes.
Physics backend contractPhysics and FMUNative backend boundary and backend implementations.
Legacy high-fidelity altimeterPhysics and FMUOpenModelica/FMI 2 harness; it cannot directly load an FMI 3 model.
CourbetFlight controllersFirmware profiles, MAVLink helpers, mission assets, and local tests.
PX4 FMUv6CFlight controllersConsole initialization, UART bridging, and the specific PX4 profile.
Rover 4.6.2Flight controllersTitle-only port stub; inspect its surrounding assets and the active config.
Rover lidar variantFlight controllersTitle-only variant stub; it is not a complete verified walkthrough.
Rover fuzzing variantFuzzingTitle-only historical port stub; follow the current campaign interfaces.
ELF-to-configConfigure a firmwareMetadata extraction, hints, and reviewable configuration generation.
Ghidra launcherDebuggingRepository-provided GDB launcher integration for a matching Ghidra project.
Unit testsTesting and reproducibilityPython test commands and conventions.
Integration testsTesting and reproducibilityNative execution, RTOS, vehicle, and swarm checks.
STM32F429I FreeRTOS fixtureTesting, introspectionTwo task-owned LED counters and the fixture build.
Raw firmware fixturesTesting and reproducibilityRaw conversion commands and the metadata discarded by that format.
Idle hardware firmwareHardware and tracesBoard-side interrupt servers, prebuilt images, and the IRQ-number contract.

Recent implementation guides

The post-core changes reviewed at FastDyn e44dca2 have dedicated source notes: automatic MMIO and six-case regressions, MMIO saved-PC callback contract and recorded benchmark, and ARM32 constant-PC chaining and recorded benchmark. The book maps these to Automatic MMIO, hot-path optimizations, and testing. Older core-source links in the map intentionally remain pinned to their original f9666d7 baseline.

Find the owning implementation

LocationStart here when changing or checking
src/fastdyn/main.pyCommand names, Click options, and CLI defaults.
src/fastdyn/runner.py, runtime_config.pyRun preparation, helper lifecycle, work directories, and profiling configuration.
src/fastdyn/toml_parser.py, targets/qemu_target.pyTOML consumption, path resolution, QEMU options, and generated native rules.
src/fastdyn/virtual_preprocessing.pyHost extension discovery, preparation contexts, and rule validation.
src/fastdyn/host/Reusable immutable-image analysis; plugin-specific policies stay with their consumer.
core/core.cTranslation instrumentation, dispatch infrastructure, coverage producer/consumer behavior, and core lifecycle.
include/fastdyn_runtime.h, include/fastdyn/arch/Native SDK contracts and target register/ABI constants.
include/fastdyn/device_model.h, device_models/Device ABI, routing, model-family implementations, and hardware sessions.
configs/Concrete user settings and examples; inspect placeholder paths and feature prerequisites.
virtuals/<feature>/host/, runtime/A feature's preprocessing policy, manifest, native behavior, and outputs.
virtuals/physics/Physics backends, vehicle adapters, Courbet profiles, and mission assets.
virtuals/fuzzer/Native fuzzing lifecycle, schemas, input backends, and OptiFuzz.
tests/unit/, tests/integration/Expected contracts and executable validation boundaries.
tests/firmwares/, tests/binaries/Fixture source and image identity behind smoke tests.
tools/, utils/Configuration generation, binary utilities, co-simulation controllers, reports, and optional tool integrations.
.gitmodules, third_party/Dependency ownership and pinned source boundaries. tools/raw2elf and tools/world are also submodules.
setup.sh, scripts/setup/, Makefile, meson.buildWhat a build actually enables and how dependencies are selected.

Use rg from the FastDyn repository root to follow a feature across its layers:

rg --files src core include configs tests virtuals tools utils
rg -n 'register_run_preprocessor|VIRTUAL_PLUGIN' src virtuals tests/plugins
rg -n 'timer_irq_period_ns|exact_budget_stop' src core include configs virtuals
rg -n 'fuzzing_schema|schema_load' src virtuals

Begin with the user-facing configuration, find where the parser consumes it, follow the generated artifact or native argument, and then read the runtime consumer. Finally, check tests for the precise boundary the repository exercises. This makes it easier to spot a stale example, an unsupported field, or an implementation detail that should not be advertised as a portable contract.

Publish and maintain the book

The FastDyn handbook is an mdBook published at boardrunner2049.github.io/fastdyn/ through GitHub Pages. Its source lives on the main branch of boardrunner2049/boardrunner2049.github.io. The same Pages deployment includes the project's landing page, blog, and shared assets.

Repository layout

PathPurpose
fastdyn/book.tomlmdBook settings, source directory, renderer, and Mermaid preprocessor configuration
fastdyn/src/index.mdHandbook landing page
fastdyn/src/SUMMARY.mdChapter order, nesting, and part headings
fastdyn/src/<topic>/*.mdEditable chapter sources
fastdyn/book/Generated book output, ignored by Git
site-theme.cssShared BoardRunner colors and fonts used by the website and handbook
scripts/install-book-tools.shInstall the pinned Linux prebuilt tools under .tools/bin
scripts/build-site.shBuild the handbook, assemble the complete _site tree, and validate it
scripts/check-site.pyCheck rendered local links, anchors, and navigation
.github/workflows/pages.ymlBuild and deploy the complete site from main

Edit the Markdown under fastdyn/src/. Generated output and downloaded tools are build products. Commit source files and intentional build configuration changes; keep fastdyn/book/, _site/, .tools/, and generated Mermaid assets out of source commits.

The shared visual design belongs to root site-theme.css: the website's styles.css imports it, and the build copies it to ignored fastdyn/theme/site-theme.css for mdBook to load before fastdyn/theme/fastdyn.css. Edit and commit the shared source, never the generated copy. The handbook uses the same BR mark, wordmark, and site navigation. It defaults to the light palette even when the operating system prefers dark mode; manually selected dark themes use charcoal and peach. The custom fastdyn/theme/mermaid-init.js reads the CSS palette and uses Mermaid's base theme, refreshing diagrams when readers switch between light and dark palettes.

Install the pinned tools

Run all commands in this chapter from the website repository root:

git clone https://github.com/boardrunner2049/boardrunner2049.github.io.git
cd boardrunner2049.github.io

The build uses mdBook 0.5.4 and mdbook-mermaid 0.17.1. On the supported Linux host, install the prebuilt tools with:

./scripts/install-book-tools.sh

The installer places executables under .tools/bin. The build script discovers that location automatically. It can also use matching executables already available on PATH.

For a platform using a local Rust toolchain instead of the Linux prebuilt installer:

cargo install mdbook --locked --version 0.5.4
cargo install mdbook-mermaid --locked --version 0.17.1

Ensure Cargo's executable directory is on PATH. Keep both version pins aligned with the repository scripts when deliberately updating the toolchain. A local installation of a different mdBook version is not the same build environment as the Pages workflow.

Build and preview the complete site

./scripts/build-site.sh
python3 -m http.server 8000 --directory _site

Open http://localhost:8000/fastdyn/. The site root and blog are served by the same preview, so inspect those entry points when changing shared navigation or assets.

The build script runs mdbook-mermaid install fastdyn to materialize the ignored JavaScript assets required by the Mermaid renderer, then builds the book using fastdyn/book.toml. It stages the rendered handbook under _site/fastdyn/ alongside the main site's files. This preserves the public /fastdyn/ path while keeping the existing site content in the same deployment.

Preview the handbook's Mermaid diagrams in a browser after a renderer or diagram change; successful Markdown parsing alone does not establish that a diagram rendered correctly. The source remains in ordinary mermaid code fences, so the diagrams stay editable with their surrounding explanations.

The build also runs the rendered-site checker. To repeat that check against the existing _site tree:

python3 scripts/check-site.py

It checks local destinations, fragment anchors, and navigation. Browser review should additionally cover the landing page, sidebar groups, code blocks, tables, search, and diagrams. Follow at least one cross-chapter link and one pinned implementation-source link. Rebuild after editing a chapter; the simple HTTP server serves the files currently staged in _site.

fastdyn/src/SUMMARY.md is mdBook's navigation source. A part title uses a single #, even though the file also commonly begins with # Summary:

# Summary

[FastDyn](index.md)

# Architecture

* [The system model](architecture/system-model.md)
* [The execution pipeline](architecture/execution-pipeline.md)

Add each chapter once and point to its relative .md path. Links inside a chapter are relative to that chapter's directory. mdBook rewrites Markdown chapter links for the rendered site; keep source links as .md rather than hard-coding generated .html paths.

Each chapter begins with its own H1. YAML frontmatter is not needed. When moving a chapter or renaming a heading, update incoming links and rerun the rendered checker, including fragment links to the changed heading.

The syntax and build behavior follow the official mdBook summary format and build-command documentation.

Publish through the existing Pages workflow

Commit the reviewed source changes to main, or merge a documentation pull request into main. The existing .github/workflows/pages.yml workflow builds the whole _site tree, validates it, uploads that directory as the Pages artifact, and deploys it. The workflow can also be started manually through its dispatch trigger.

Use that single site workflow for handbook changes. It owns the root site and /fastdyn/ together, so a book update must not publish only the book output over the site's root artifact.

Check the workflow result and then inspect the live /fastdyn/ page. A successful source commit, a successful local build, and a completed Pages deployment are separate outcomes. Record the one actually observed when reporting a release.

Updating the source baseline

Historical core chapters retain FastDyn baseline f9666d7f518c373e89831d8e14a6371a27fe6436. The JIT patcher and manual inline lab use 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c; automatic MMIO, the current vCPU fast-path changes, and secondary execution are reviewed at e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576. Tempo uses 771b99650004fcbf3ab216970cf8fd9fae91aa6c. The Supercache optimizer uses FastDyn scopt at 124699db203aae581735b4bdfb82e9b949332405 with QEMU 934890ed5119ef70da69276991d921573f23ed4f. FirmBOLT uses FastDyn firmbolt at b14f14cb4992d28d56cda5e73685a5f7c432c5cf, including its checked-in patch over LLVM/BOLT 7864c0736a8a09670dfbfc513f1e9649799f2486. Supercache has separate frontend/backend pins. A baseline update should review the public APIs, configuration parser, build defaults, shipped examples, and tests before replacing source-link SHAs in bulk. Update the workflow's checkout instructions as well as its source links so readers do not run a newer feature from an older tutorial checkout.

Keep branch-preview evidence pinned to the revision that was inspected. When a branch is merged, check the resulting main implementation instead of assuming the earlier branch text is still exact. The source map identifies the original documentation and code locations behind each chapter.

Contribute to the handbook

A useful contribution helps a reader complete an experiment or understand an important contract. Explain the question, the required setup, the action, the observable result, and the implementation boundary. Prefer one complete example over a list of features with no working path between them.

Handbook source changes belong in boardrunner2049/boardrunner2049.github.io, under fastdyn/src/. This repository builds the book with mdBook and publishes it at /fastdyn/ as part of the project's GitHub Pages site.

Contact

For questions about contributing to the FastDyn book, contact Arslan Khan at arslankhan@psu.edu.

Choose the right chapter

User workflows belong in getting started, instrumentation, devices, simulation, and analysis. Advanced execution mechanisms belong in advanced; API and extension contracts belong in extending and reference. Architectural explanations should identify component responsibilities and show how a decision affects execution. Add a capability when its implementation can be inspected, and connect it to a practical chapter. Keep an existing URL when it remains useful as design rationale for implemented behavior.

Use the source map before adding a new page. It helps avoid creating a second explanation of an API that already has a natural home.

Ground the claims

Read the current implementation and relevant tests, not only an older README. Add a short source guide with pinned links to the files that establish the chapter's contract. Use tests as evidence of what is asserted, and distinguish the existence of a test from a test result observed during the documentation change.

The core implementation baseline is f9666d7f518c373e89831d8e14a6371a27fe6436; the JIT patcher and manual inline lab use 5b8bf3ddb01d63a4d5f86701d358e390a950cb9c. Automatic MMIO, the current MMIO/ARM32 hot-path changes, and secondary execution are reviewed at e44dca2edbc3b32cb1f2a48d3d0be203bd9b5576. Tempo uses 771b99650004fcbf3ab216970cf8fd9fae91aa6c. The Supercache optimizer uses FastDyn scopt at 124699db203aae581735b4bdfb82e9b949332405 with QEMU 934890ed5119ef70da69276991d921573f23ed4f. FirmBOLT uses FastDyn firmbolt at b14f14cb4992d28d56cda5e73685a5f7c432c5cf, including its checked-in patch over LLVM/BOLT 7864c0736a8a09670dfbfc513f1e9649799f2486. Supercache additionally records separate frontend/backend revisions. Preserve chapter-level pins when updating only part of the book. For a branch-only feature, name the branch, pin the revision, and state the prerequisites and validation level. For an implemented experiment, distinguish available commands from established correctness. Keep the handbook limited to implemented capabilities, their prerequisites, validation evidence, and current limitations.

If code and earlier documentation disagree, document the behavior the inspected implementation provides and keep the explanation useful to the reader. A handbook chapter should not become an unrelated backlog of every issue found during inspection.

Write examples that can be followed

State the working directory, required build options, firmware fixture, and expected output. Use the public CLI or API that the feature actually supports. Configuration fragments should identify the existing table they extend and any required surrounding configuration.

Do not transplant literal addresses into a different firmware image. Explain when symbol resolution, instruction validation, or layout checks must run again. Keep architecture-specific register and ABI assumptions explicit.

For source-code contributors, follow FastDyn's coding conventions. In particular, retain feature ownership: plugin policy stays with the plugin, reusable immutable facts can move into host analysis, and downstream orchestration stays with the downstream project.

Explain fidelity and performance precisely

Describe the firmware boundary an experiment exercises. A sensor-publication hook, a peripheral register model, and hardware passthrough each answer different questions. State the actual input representation, time policy, and modeled state when they matter to the result.

A performance claim needs a baseline, completion condition, configuration, raw measurements, and a statement of the behavior preserved. Avoid universal speed, fidelity, architecture, or losslessness claims based on one configuration.

Keep mdBook structure consistent

Begin a chapter with one H1 and use concise section headings beneath it. No YAML frontmatter is needed. Source files live under fastdyn/src/; mdBook settings live in fastdyn/book.toml.

Add a new page to fastdyn/src/SUMMARY.md exactly once. In that navigation file, part headings use a single #. Use the same list marker as the surrounding entries and a path relative to fastdyn/src/. The special part-heading convention in SUMMARY.md does not change the heading hierarchy inside a chapter.

Use relative .md links between book pages, with fragment anchors where necessary, and pinned URLs for implementation sources. For example, a page in maintainers/ can link to ../reference/cli.md. Let mdBook translate chapter links into output URLs. Add a term to the glossary when several chapters need the same definition.

Use language-tagged fences such as bash, toml, python, c, or json for examples. A schematic snippet should say so in the surrounding text. An expected-output block should identify which parts are stable and which depend on the run.

For visual changes, edit root site-theme.css for shared colors and fonts, and fastdyn/theme/fastdyn.css for the handbook's layout and component styling. Preserve the common BR mark, wordmark, and site navigation. The build regenerates fastdyn/theme/site-theme.css from the shared source; keep that ignored copy out of commits. Review the website and handbook together, including the default light palette, optional charcoal and peach dark themes, and Mermaid diagrams after a light/dark switch. The publishing guide explains how the shared design reaches the built site.

Maintain the diagrams

The handbook's fenced Mermaid diagrams are built through mdbook-mermaid, so retain the mermaid fence and keep the diagram source with its chapter. The build installs the required generated JavaScript assets; contributors do not need to commit those assets.

Use diagrams when they explain a boundary, feedback loop, or branching workflow more clearly than prose. Keep each diagram focused and use short labels. Supporting details belong in the surrounding text. Tables work well for configuration fields, API mappings, and support differences.

A link checker cannot establish that a diagram is legible. Inspect the rendered diagram after editing it, including how labels fit in the narrow reading column.

Build and review a contribution

Use mdBook 0.5.4 and mdbook-mermaid 0.17.1. From the website repository root, the Linux setup and review path is:

./scripts/install-book-tools.sh
./scripts/build-site.sh
python3 -m http.server 8000 --directory _site

The installer writes the tools to .tools/bin, which the build script discovers automatically. Matching tools on PATH also work. On other platforms, install the pinned Cargo versions as described in publishing.

Open http://localhost:8000/fastdyn/. Check the changed chapter, its sidebar entry, local links and anchors, code blocks, tables, and diagrams. The build script runs python3 scripts/check-site.py against the assembled output; that command can also be rerun directly after a build.

The full-site preview includes the root landing page, blog, and shared assets. Check those surfaces when changing common navigation or the build. Keep generated fastdyn/book/, _site/, .tools/, and Mermaid JavaScript assets out of commits.

For runtime examples, state whether they were run and with which build. A successful documentation build or syntax check is useful evidence, but it is not a firmware integration test. Commit the source change and its validation record; the existing Pages workflow publishes the complete site after the change reaches main.