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