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