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