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