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