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:
| Need | Extension |
|---|---|
| A fixed register or memory assignment | A configured modifier |
| An action at a selected PC | Native callback and VirtualDefinition |
| An action requiring prepared arguments or files | Callback, VirtualDefinition, and per-virtual prepare() |
| Firmware-wide selection or setup | RunDefinition and run prepare(); native callbacks as needed |
| Observation of MMIO or translation events | Native 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 folder | Role |
|---|---|
host/preprocessor.py | Self-register Python definitions |
runtime/<name>.c | Optional native runtime implementation |
runtime/*.so | Built native libraries for an external plugin |
meson.build | In-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 group | Operations |
|---|---|
| Lifecycle/output | virtual_register_callback, virtual_artifact_path, virtual_register_exit, virtual_log |
| Execution state | virtual_pc, virtual_sp, virtual_icount, virtual_guest_time_ns |
| Registers | virtual_read_register_bytes, virtual_write_register_bytes; 32-bit convenience forms virtual_read_register, virtual_write_register |
| Memory/IRQs | virtual_read_memory, virtual_write_memory, virtual_raise_irq |
| Observers | virtual_register_irq_hook, virtual_register_mmio_observer, virtual_register_tb_translation_hook |
| Runtime-derived instrumentation | virtual_register_rule, virtual_register_update, virtual_register_gated_modifier |
| Experiment integration | virtual_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.
| API | Contract |
|---|---|
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
- Preprocessing types, discovery, external loading, and cleanup
- Public runtime SDK and external ABI descriptor
- Native SDK implementation and loader checks
- Complete external example, host half
- Complete external example, runtime half
- Native instrumentation and counter implementation
a38af40post-device-init and typed replacement APIsa38af40MMIO plugin lifecycle example