xref: /openbmc/qemu/docs/devel/rust.rst (revision f117857b39fb42c56be23316e2d76db5b13cec8d)
1.. |msrv| replace:: 1.63.0
2
3Rust in QEMU
4============
5
6Rust in QEMU is a project to enable using the Rust programming language
7to add new functionality to QEMU.
8
9Right now, the focus is on making it possible to write devices that inherit
10from ``SysBusDevice`` in `*safe*`__ Rust.  Later, it may become possible
11to write other kinds of devices (e.g. PCI devices that can do DMA),
12complete boards, or backends (e.g. block device formats).
13
14__ https://doc.rust-lang.org/nomicon/meet-safe-and-unsafe.html
15
16Building the Rust in QEMU code
17------------------------------
18
19The Rust in QEMU code is included in the emulators via Meson.  Meson
20invokes rustc directly, building static libraries that are then linked
21together with the C code.  This is completely automatic when you run
22``make`` or ``ninja``.
23
24However, QEMU's build system also tries to be easy to use for people who
25are accustomed to the more "normal" Cargo-based development workflow.
26In particular:
27
28* the set of warnings and lints that are used to build QEMU always
29  comes from the ``rust/Cargo.toml`` workspace file
30
31* it is also possible to use ``cargo`` for common Rust-specific coding
32  tasks, in particular to invoke ``clippy``, ``rustfmt`` and ``rustdoc``.
33
34To this end, QEMU includes a ``build.rs`` build script that picks up
35generated sources from QEMU's build directory and puts it in Cargo's
36output directory (typically ``rust/target/``).  A vanilla invocation
37of Cargo will complain that it cannot find the generated sources,
38which can be fixed in different ways:
39
40* by using special shorthand targets in the QEMU build directory::
41
42    make clippy
43    make rustfmt
44    make rustdoc
45
46* by invoking ``cargo`` through the Meson `development environment`__
47  feature::
48
49    pyvenv/bin/meson devenv -w ../rust cargo clippy --tests
50    pyvenv/bin/meson devenv -w ../rust cargo fmt
51
52  If you are going to use ``cargo`` repeatedly, ``pyvenv/bin/meson devenv``
53  will enter a shell where commands like ``cargo clippy`` just work.
54
55__ https://mesonbuild.com/Commands.html#devenv
56
57* by pointing the ``MESON_BUILD_ROOT`` to the top of your QEMU build
58  tree.  This third method is useful if you are using ``rust-analyzer``;
59  you can set the environment variable through the
60  ``rust-analyzer.cargo.extraEnv`` setting.
61
62As shown above, you can use the ``--tests`` option as usual to operate on test
63code.  Note however that you cannot *build* or run tests via ``cargo``, because
64they need support C code from QEMU that Cargo does not know about.  Tests can
65be run via ``meson test`` or ``make``::
66
67   make check-rust
68
69Building Rust code with ``--enable-modules`` is not supported yet.
70
71Supported tools
72'''''''''''''''
73
74QEMU supports rustc version 1.63.0 and newer.  Notably, the following features
75are missing:
76
77* Generic Associated Types (1.65.0)
78
79* ``CStr::from_bytes_with_nul()`` as a ``const`` function (1.72.0).
80
81* "Return position ``impl Trait`` in Traits" (1.75.0, blocker for including
82  the pinned-init create).
83
84* inline const expression (stable in 1.79.0), currently worked around with
85  associated constants in the ``FnCall`` trait.
86
87* associated constants have to be explicitly marked ``'static`` (`changed in
88  1.81.0`__)
89
90* ``&raw`` (stable in 1.82.0).  Use ``addr_of!`` and ``addr_of_mut!`` instead,
91  though hopefully the need for raw pointers will go down over time.
92
93* ``new_uninit`` (stable in 1.82.0).  This is used internally by the ``pinned_init``
94  crate, which is planned for inclusion in QEMU, but it can be easily patched
95  out.
96
97* referencing statics in constants (stable in 1.83.0).  For now use a const
98  function; this is an important limitation for QEMU's migration stream
99  architecture (VMState).  Right now, VMState lacks type safety because
100  it is hard to place the ``VMStateField`` definitions in traits.
101
102* associated const equality would be nice to have for some users of
103  ``callbacks::FnCall``, but is still experimental.  ``ASSERT_IS_SOME``
104  replaces it.
105
106__ https://github.com/rust-lang/rust/pull/125258
107
108It is expected that QEMU will advance its minimum supported version of
109rustc to 1.77.0 as soon as possible; as of January 2025, blockers
110for that right now are Debian bookworm and 32-bit MIPS processors.
111This unfortunately means that references to statics in constants will
112remain an issue.
113
114QEMU also supports version 0.60.x of bindgen, which is missing option
115``--generate-cstr``.  This option requires version 0.66.x and will
116be adopted as soon as supporting these older versions is not necessary
117anymore.
118
119Writing Rust code in QEMU
120-------------------------
121
122QEMU includes four crates:
123
124* ``qemu_api`` for bindings to C code and useful functionality
125
126* ``qemu_api_macros`` defines several procedural macros that are useful when
127  writing C code
128
129* ``pl011`` (under ``rust/hw/char/pl011``) and ``hpet`` (under ``rust/hw/timer/hpet``)
130  are sample devices that demonstrate ``qemu_api`` and ``qemu_api_macros``, and are
131  used to further develop them.  These two crates are functional\ [#issues]_ replacements
132  for the ``hw/char/pl011.c`` and ``hw/timer/hpet.c`` files.
133
134.. [#issues] The ``pl011`` crate is synchronized with ``hw/char/pl011.c``
135   as of commit 02b1f7f61928.  The ``hpet`` crate is synchronized as of
136   commit 1433e38cc8.  Both are lacking tracing functionality.
137
138This section explains how to work with them.
139
140Status
141''''''
142
143Modules of ``qemu_api`` can be defined as:
144
145- *complete*: ready for use in new devices; if applicable, the API supports the
146  full functionality available in C
147
148- *stable*: ready for production use, the API is safe and should not undergo
149  major changes
150
151- *proof of concept*: the API is subject to change but allows working with safe
152  Rust
153
154- *initial*: the API is in its initial stages; it requires large amount of
155  unsafe code; it might have soundness or type-safety issues
156
157The status of the modules is as follows:
158
159================ ======================
160module           status
161================ ======================
162``assertions``   stable
163``bitops``       complete
164``callbacks``    complete
165``cell``         stable
166``errno``        complete
167``irq``          complete
168``memory``       stable
169``module``       complete
170``offset_of``    stable
171``qdev``         stable
172``qom``          stable
173``sysbus``       stable
174``timer``        stable
175``vmstate``      proof of concept
176``zeroable``     stable
177================ ======================
178
179.. note::
180  API stability is not a promise, if anything because the C APIs are not a stable
181  interface either.  Also, ``unsafe`` interfaces may be replaced by safe interfaces
182  later.
183
184Naming convention
185'''''''''''''''''
186
187C function names usually are prefixed according to the data type that they
188apply to, for example ``timer_mod`` or ``sysbus_connect_irq``.  Furthermore,
189both function and structs sometimes have a ``qemu_`` or ``QEMU`` prefix.
190Generally speaking, these are all removed in the corresponding Rust functions:
191``QEMUTimer`` becomes ``timer::Timer``, ``timer_mod`` becomes ``Timer::modify``,
192``sysbus_connect_irq`` becomes ``SysBusDeviceMethods::connect_irq``.
193
194Sometimes however a name appears multiple times in the QOM class hierarchy,
195and the only difference is in the prefix.  An example is ``qdev_realize`` and
196``sysbus_realize``.  In such cases, whenever a name is not unique in
197the hierarchy, always add the prefix to the classes that are lower in
198the hierarchy; for the top class, decide on a case by case basis.
199
200For example:
201
202========================== =========================================
203``device_cold_reset()``    ``DeviceMethods::cold_reset()``
204``pci_device_reset()``     ``PciDeviceMethods::pci_device_reset()``
205``pci_bridge_reset()``     ``PciBridgeMethods::pci_bridge_reset()``
206========================== =========================================
207
208Here, the name is not exactly the same, but nevertheless ``PciDeviceMethods``
209adds the prefix to avoid confusion, because the functionality of
210``device_cold_reset()`` and ``pci_device_reset()`` is subtly different.
211
212In this case, however, no prefix is needed:
213
214========================== =========================================
215``device_realize()``       ``DeviceMethods::realize()``
216``sysbus_realize()``       ``SysbusDeviceMethods::sysbus_realize()``
217``pci_realize()``          ``PciDeviceMethods::pci_realize()``
218========================== =========================================
219
220Here, the lower classes do not add any functionality, and mostly
221provide extra compile-time checking; the basic *realize* functionality
222is the same for all devices.  Therefore, ``DeviceMethods`` does not
223add the prefix.
224
225Whenever a name is unique in the hierarchy, instead, you should
226always remove the class name prefix.
227
228Common pitfalls
229'''''''''''''''
230
231Rust has very strict rules with respect to how you get an exclusive (``&mut``)
232reference; failure to respect those rules is a source of undefined behavior.
233In particular, even if a value is loaded from a raw mutable pointer (``*mut``),
234it *cannot* be casted to ``&mut`` unless the value was stored to the ``*mut``
235from a mutable reference.  Furthermore, it is undefined behavior if any
236shared reference was created between the store to the ``*mut`` and the load::
237
238    let mut p: u32 = 42;
239    let p_mut = &mut p;                              // 1
240    let p_raw = p_mut as *mut u32;                   // 2
241
242    // p_raw keeps the mutable reference "alive"
243
244    let p_shared = &p;                               // 3
245    println!("access from &u32: {}", *p_shared);
246
247    // Bring back the mutable reference, its lifetime overlaps
248    // with that of a shared reference.
249    let p_mut = unsafe { &mut *p_raw };              // 4
250    println!("access from &mut 32: {}", *p_mut);
251
252    println!("access from &u32: {}", *p_shared);     // 5
253
254These rules can be tested with `MIRI`__, for example.
255
256__ https://github.com/rust-lang/miri
257
258Almost all Rust code in QEMU will involve QOM objects, and pointers to these
259objects are *shared*, for example because they are part of the QOM composition
260tree.  This creates exactly the above scenario:
261
2621. a QOM object is created
263
2642. a ``*mut`` is created, for example as the opaque value for a ``MemoryRegion``
265
2663. the QOM object is placed in the composition tree
267
2684. a memory access dereferences the opaque value to a ``&mut``
269
2705. but the shared reference is still present in the composition tree
271
272Because of this, QOM objects should almost always use ``&self`` instead
273of ``&mut self``; access to internal fields must use *interior mutability*
274to go from a shared reference to a ``&mut``.
275
276Whenever C code provides you with an opaque ``void *``, avoid converting it
277to a Rust mutable reference, and use a shared reference instead.  The
278``qemu_api::cell`` module provides wrappers that can be used to tell the
279Rust compiler about interior mutability, and optionally to enforce locking
280rules for the "Big QEMU Lock".  In the future, similar cell types might
281also be provided for ``AioContext``-based locking as well.
282
283In particular, device code will usually rely on the ``BqlRefCell`` and
284``BqlCell`` type to ensure that data is accessed correctly under the
285"Big QEMU Lock".  These cell types are also known to the ``vmstate``
286crate, which is able to "look inside" them when building an in-memory
287representation of a ``struct``'s layout.  Note that the same is not true
288of a ``RefCell`` or ``Mutex``.
289
290Bindings code instead will usually use the ``Opaque`` type, which hides
291the contents of the underlying struct and can be easily converted to
292a raw pointer, for use in calls to C functions.  It can be used for
293example as follows::
294
295    #[repr(transparent)]
296    #[derive(Debug, qemu_api_macros::Wrapper)]
297    pub struct Object(Opaque<bindings::Object>);
298
299where the special ``derive`` macro provides useful methods such as
300``from_raw``, ``as_ptr`, ``as_mut_ptr`` and ``raw_get``.  The bindings will
301then manually check for the big QEMU lock with assertions, which allows
302the wrapper to be declared thread-safe::
303
304    unsafe impl Send for Object {}
305    unsafe impl Sync for Object {}
306
307Writing bindings to C code
308''''''''''''''''''''''''''
309
310Here are some things to keep in mind when working on the ``qemu_api`` crate.
311
312**Look at existing code**
313  Very often, similar idioms in C code correspond to similar tricks in
314  Rust bindings.  If the C code uses ``offsetof``, look at qdev properties
315  or ``vmstate``.  If the C code has a complex const struct, look at
316  ``MemoryRegion``.  Reuse existing patterns for handling lifetimes;
317  for example use ``&T`` for QOM objects that do not need a reference
318  count (including those that can be embedded in other objects) and
319  ``Owned<T>`` for those that need it.
320
321**Use the type system**
322  Bindings often will need access information that is specific to a type
323  (either a builtin one or a user-defined one) in order to pass it to C
324  functions.  Put them in a trait and access it through generic parameters.
325  The ``vmstate`` module has examples of how to retrieve type information
326  for the fields of a Rust ``struct``.
327
328**Prefer unsafe traits to unsafe functions**
329  Unsafe traits are much easier to prove correct than unsafe functions.
330  They are an excellent place to store metadata that can later be accessed
331  by generic functions.  C code usually places metadata in global variables;
332  in Rust, they can be stored in traits and then turned into ``static``
333  variables.  Often, unsafe traits can be generated by procedural macros.
334
335**Document limitations due to old Rust versions**
336  If you need to settle for an inferior solution because of the currently
337  supported set of Rust versions, document it in the source and in this
338  file.  This ensures that it can be fixed when the minimum supported
339  version is bumped.
340
341**Keep locking in mind**.
342  When marking a type ``Sync``, be careful of whether it needs the big
343  QEMU lock.  Use ``BqlCell`` and ``BqlRefCell`` for interior data,
344  or assert ``bql_locked()``.
345
346**Don't be afraid of complexity, but document and isolate it**
347  It's okay to be tricky; device code is written more often than bindings
348  code and it's important that it is idiomatic.  However, you should strive
349  to isolate any tricks in a place (for example a ``struct``, a trait
350  or a macro) where it can be documented and tested.  If needed, include
351  toy versions of the code in the documentation.
352
353Writing procedural macros
354'''''''''''''''''''''''''
355
356By conventions, procedural macros are split in two functions, one
357returning ``Result<proc_macro2::TokenStream, MacroError>`` with the body of
358the procedural macro, and the second returning ``proc_macro::TokenStream``
359which is the actual procedural macro.  The former's name is the same as
360the latter with the ``_or_error`` suffix.  The code for the latter is more
361or less fixed; it follows the following template, which is fixed apart
362from the type after ``as`` in the invocation of ``parse_macro_input!``::
363
364    #[proc_macro_derive(Object)]
365    pub fn derive_object(input: TokenStream) -> TokenStream {
366        let input = parse_macro_input!(input as DeriveInput);
367        let expanded = derive_object_or_error(input).unwrap_or_else(Into::into);
368
369        TokenStream::from(expanded)
370    }
371
372The ``qemu_api_macros`` crate has utility functions to examine a
373``DeriveInput`` and perform common checks (e.g. looking for a struct
374with named fields).  These functions return ``Result<..., MacroError>``
375and can be used easily in the procedural macro function::
376
377    fn derive_object_or_error(input: DeriveInput) ->
378        Result<proc_macro2::TokenStream, MacroError>
379    {
380        is_c_repr(&input, "#[derive(Object)]")?;
381
382        let name = &input.ident;
383        let parent = &get_fields(&input, "#[derive(Object)]")?[0].ident;
384        ...
385    }
386
387Use procedural macros with care.  They are mostly useful for two purposes:
388
389* Performing consistency checks; for example ``#[derive(Object)]`` checks
390  that the structure has ``#[repr[C])`` and that the type of the first field
391  is consistent with the ``ObjectType`` declaration.
392
393* Extracting information from Rust source code into traits, typically based
394  on types and attributes.  For example, ``#[derive(TryInto)]`` builds an
395  implementation of ``TryFrom``, and it uses the ``#[repr(...)]`` attribute
396  as the ``TryFrom`` source and error types.
397
398Procedural macros can be hard to debug and test; if the code generation
399exceeds a few lines of code, it may be worthwhile to delegate work to
400"regular" declarative (``macro_rules!``) macros and write unit tests for
401those instead.
402
403
404Coding style
405''''''''''''
406
407Code should pass clippy and be formatted with rustfmt.
408
409Right now, only the nightly version of ``rustfmt`` is supported.  This
410might change in the future.  While CI checks for correct formatting via
411``cargo fmt --check``, maintainers can fix this for you when applying patches.
412
413It is expected that ``qemu_api`` provides full ``rustdoc`` documentation for
414bindings that are in their final shape or close.
415
416Adding dependencies
417-------------------
418
419Generally, the set of dependent crates is kept small.  Think twice before
420adding a new external crate, especially if it comes with a large set of
421dependencies itself.  Sometimes QEMU only needs a small subset of the
422functionality; see for example QEMU's ``assertions`` module.
423
424On top of this recommendation, adding external crates to QEMU is a
425slightly complicated process, mostly due to the need to teach Meson how
426to build them.  While Meson has initial support for parsing ``Cargo.lock``
427files, it is still highly experimental and is therefore not used.
428
429Therefore, external crates must be added as subprojects for Meson to
430learn how to build them, as well as to the relevant ``Cargo.toml`` files.
431The versions specified in ``rust/Cargo.lock`` must be the same as the
432subprojects; note that the ``rust/`` directory forms a Cargo `workspace`__,
433and therefore there is a single lock file for the whole build.
434
435__ https://doc.rust-lang.org/cargo/reference/workspaces.html#virtual-workspace
436
437Choose a version of the crate that works with QEMU's minimum supported
438Rust version (|msrv|).
439
440Second, a new ``wrap`` file must be added to teach Meson how to download the
441crate.  The wrap file must be named ``NAME-SEMVER-rs.wrap``, where ``NAME``
442is the name of the crate and ``SEMVER`` is the version up to and including the
443first non-zero number.  For example, a crate with version ``0.2.3`` will use
444``0.2`` for its ``SEMVER``, while a crate with version ``1.0.84`` will use ``1``.
445
446Third, the Meson rules to build the crate must be added at
447``subprojects/NAME-SEMVER-rs/meson.build``.  Generally this includes:
448
449* ``subproject`` and ``dependency`` lines for all dependent crates
450
451* a ``static_library`` or ``rust.proc_macro`` line to perform the actual build
452
453* ``declare_dependency`` and a ``meson.override_dependency`` lines to expose
454  the result to QEMU and to other subprojects
455
456Remember to add ``native: true`` to ``dependency``, ``static_library`` and
457``meson.override_dependency`` for dependencies of procedural macros.
458If a crate is needed in both procedural macros and QEMU binaries, everything
459apart from ``subproject`` must be duplicated to build both native and
460non-native versions of the crate.
461
462It's important to specify the right compiler options.  These include:
463
464* the language edition (which can be found in the ``Cargo.toml`` file)
465
466* the ``--cfg`` (which have to be "reverse engineered" from the ``build.rs``
467  file of the crate).
468
469* usually, a ``--cap-lints allow`` argument to hide warnings from rustc
470  or clippy.
471
472After every change to the ``meson.build`` file you have to update the patched
473version with ``meson subprojects update --reset ``NAME-SEMVER-rs``.  This might
474be automated in the future.
475
476Also, after every change to the ``meson.build`` file it is strongly suggested to
477do a dummy change to the ``.wrap`` file (for example adding a comment like
478``# version 2``), which will help Meson notice that the subproject is out of date.
479
480As a last step, add the new subproject to ``scripts/archive-source.sh``,
481``scripts/make-release`` and ``subprojects/.gitignore``.
482