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