rust.rst 21 KB

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