Skip to contentSkip to conversation

Add Rust build support, ARM PL011 device impl

PATCH In review Manos Pitsidianakis 2 participants 11 messages Oct 3, 2024 – Oct 4, 2024

Subsystems (2)
lore
Share & tools
lore
#9 lore raw

PATCH v11 9/9 rust: add PL011 device model

In reply to Manos Pitsidianakis

This commit adds a re-implementation of hw/char/pl011.c in Rust.

How to build:

1. Configure a QEMU build with:
--enable-system --target-list=aarch64-softmmu --enable-rust
2. Launching a VM with qemu-system-aarch64 should use the Rust version of the pl011 device

---
 MAINTAINERS                                   |   5 +
 meson.build                                   |  24 +
 hw/arm/Kconfig                                |  30 +-
 rust/Kconfig                                  |   1 +
 rust/hw/Kconfig                               |   2 +
 rust/hw/char/Kconfig                          |   3 +
 rust/hw/char/meson.build                      |   1 +
 rust/hw/char/pl011/.gitignore                 |   2 +
 rust/hw/char/pl011/Cargo.lock                 | 134 ++++
 rust/hw/char/pl011/Cargo.toml                 |  26 +
 rust/hw/char/pl011/README.md                  |  31 +
 rust/hw/char/pl011/meson.build                |  26 +
 rust/hw/char/pl011/src/device.rs              | 599 ++++++++++++++++++
 rust/hw/char/pl011/src/device_class.rs        |  70 ++
 rust/hw/char/pl011/src/lib.rs                 | 586 +++++++++++++++++
 rust/hw/char/pl011/src/memory_ops.rs          |  59 ++
 rust/hw/meson.build                           |   1 +
 rust/meson.build                              |   2 +
 scripts/archive-source.sh                     |   4 +-
 scripts/make-release                          |   4 +-
 scripts/rust/rust_root_crate.sh               |  13 +
 subprojects/.gitignore                        |   7 +
 subprojects/arbitrary-int-1-rs.wrap           |   7 +
 subprojects/bilge-0.2-rs.wrap                 |   7 +
 subprojects/bilge-impl-0.2-rs.wrap            |   7 +
 subprojects/either-1-rs.wrap                  |   7 +
 subprojects/itertools-0.11-rs.wrap            |   7 +
 .../arbitrary-int-1-rs/meson.build            |  19 +
 .../packagefiles/bilge-0.2-rs/meson.build     |  29 +
 .../bilge-impl-0.2-rs/meson.build             |  45 ++
 .../packagefiles/either-1-rs/meson.build      |  24 +
 .../itertools-0.11-rs/meson.build             |  30 +
 .../proc-macro-error-1-rs/meson.build         |  40 ++
 .../proc-macro-error-attr-1-rs/meson.build    |  32 +
 .../unicode-ident-1-rs/meson.build            |  20 +
 subprojects/proc-macro-error-1-rs.wrap        |   7 +
 subprojects/proc-macro-error-attr-1-rs.wrap   |   7 +
 37 files changed, 1906 insertions(+), 12 deletions(-)
 create mode 100644 rust/hw/Kconfig
 create mode 100644 rust/hw/char/Kconfig
 create mode 100644 rust/hw/char/meson.build
 create mode 100644 rust/hw/char/pl011/.gitignore
 create mode 100644 rust/hw/char/pl011/Cargo.lock
 create mode 100644 rust/hw/char/pl011/Cargo.toml
 create mode 100644 rust/hw/char/pl011/README.md
 create mode 100644 rust/hw/char/pl011/meson.build
 create mode 100644 rust/hw/char/pl011/src/device.rs
 create mode 100644 rust/hw/char/pl011/src/device_class.rs
 create mode 100644 rust/hw/char/pl011/src/lib.rs
 create mode 100644 rust/hw/char/pl011/src/memory_ops.rs
 create mode 100644 rust/hw/meson.build
 create mode 100755 scripts/rust/rust_root_crate.sh
 create mode 100644 subprojects/arbitrary-int-1-rs.wrap
 create mode 100644 subprojects/bilge-0.2-rs.wrap
 create mode 100644 subprojects/bilge-impl-0.2-rs.wrap
 create mode 100644 subprojects/either-1-rs.wrap
 create mode 100644 subprojects/itertools-0.11-rs.wrap
 create mode 100644 subprojects/packagefiles/arbitrary-int-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/bilge-0.2-rs/meson.build
 create mode 100644 subprojects/packagefiles/bilge-impl-0.2-rs/meson.build
 create mode 100644 subprojects/packagefiles/either-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/itertools-0.11-rs/meson.build
 create mode 100644 subprojects/packagefiles/proc-macro-error-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/proc-macro-error-attr-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/unicode-ident-1-rs/meson.build
 create mode 100644 subprojects/proc-macro-error-1-rs.wrap
 create mode 100644 subprojects/proc-macro-error-attr-1-rs.wrap
MAINTAINERS +5 -0
index 92bf3e3e8f..19c7e75955 100644
@@ -1139,6 +1139,11 @@ F: include/hw/*/microbit*.h
 F: tests/qtest/microbit-test.c
 F: docs/system/arm/nrf.rst
 
+ARM PL011 Rust device
+M: Manos Pitsidianakis <[email protected]>
+S: Maintained
+F: rust/hw/char/pl011/
+
 AVR Machines
 -------------
 
meson.build +24 -0
index c952b3b15a..9a59219712 100644
@@ -3519,6 +3519,7 @@ qom_ss = ss.source_set()
 system_ss = ss.source_set()
 specific_fuzz_ss = ss.source_set()
 specific_ss = ss.source_set()
+rust_devices_ss = ss.source_set()
 stub_ss = ss.source_set()
 trace_ss = ss.source_set()
 user_ss = ss.source_set()
@@ -4066,6 +4067,29 @@ foreach target : target_dirs
   arch_srcs += target_specific.sources()
   arch_deps += target_specific.dependencies()
 
+  if have_rust and have_system
+    target_rust = rust_devices_ss.apply(config_target, strict: false)
+    crates = []
+    foreach dep : target_rust.dependencies()
+      crates += dep.get_variable('crate')
+    endforeach
+    if crates.length() > 0
+      rlib_rs = custom_target('rust_' + target.underscorify() + '.rs',
+                              output: 'rust_' + target.underscorify() + '.rs',
+                              command: [find_program('scripts/rust/rust_root_crate.sh')] + crates,
+                              capture: true,
+                              build_by_default: true,
+                              build_always_stale: true)
+      rlib = static_library('rust_' + target.underscorify(),
+                            rlib_rs,
+                            dependencies: target_rust.dependencies(),
+                            override_options: ['rust_std=2021', 'build.rust_std=2021'],
+                            rust_args: rustc_args,
+                            rust_abi: 'c')
+      arch_deps += declare_dependency(link_whole: [rlib])
+    endif
+  endif
+
   # allow using headers from the dependencies but do not include the sources,
   # because this emulator only needs those in "objects".  For external
   # dependencies, the full dependency is included below in the executable.
hw/arm/Kconfig +20 -10
index a70ceff504..0876e06e91 100644
@@ -20,7 +20,8 @@ config ARM_VIRT
     select PCI_EXPRESS
     select PCI_EXPRESS_GENERIC_BRIDGE
     select PFLASH_CFI01
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL031 # RTC
     select PL061 # GPIO
     select GPIO_PWR
@@ -73,7 +74,8 @@ config HIGHBANK
     select AHCI
     select ARM_TIMER # sp804
     select ARM_V7M
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL022 # SPI
     select PL031 # RTC
     select PL061 # GPIO
@@ -86,7 +88,8 @@ config INTEGRATOR
     depends on TCG && ARM
     select ARM_TIMER
     select INTEGRATOR_DEBUG
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL031 # RTC
     select PL041 # audio
     select PL050 # keyboard/mouse
@@ -104,7 +107,8 @@ config MUSCA
     default y
     depends on TCG && ARM
     select ARMSSE
-    select PL011
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL031
     select SPLIT_IRQ
     select UNIMP
@@ -169,7 +173,8 @@ config REALVIEW
     select WM8750 # audio codec
     select LSI_SCSI_PCI
     select PCI
-    select PL011  # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL031  # RTC
     select PL041  # audio codec
     select PL050  # keyboard/mouse
@@ -194,7 +199,8 @@ config SBSA_REF
     select PCI_EXPRESS
     select PCI_EXPRESS_GENERIC_BRIDGE
     select PFLASH_CFI01
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL031 # RTC
     select PL061 # GPIO
     select USB_XHCI_SYSBUS
@@ -218,7 +224,8 @@ config STELLARIS
     select ARM_V7M
     select CMSDK_APB_WATCHDOG
     select I2C
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL022 # SPI
     select PL061 # GPIO
     select SSD0303 # OLED display
@@ -278,7 +285,8 @@ config VEXPRESS
     select ARM_TIMER # sp804
     select LAN9118
     select PFLASH_CFI01
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select PL041 # audio codec
     select PL181  # display
     select REALVIEW
@@ -362,7 +370,8 @@ config RASPI
     default y
     depends on TCG && ARM
     select FRAMEBUFFER
-    select PL011 # UART
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select SDHCI
     select USB_DWC2
     select BCM2835_SPI
@@ -437,7 +446,8 @@ config XLNX_VERSAL
     select ARM_GIC
     select CPU_CLUSTER
     select DEVICE_TREE
-    select PL011
+    select PL011 if !HAVE_RUST # UART
+    select X_PL011_RUST if HAVE_RUST # UART
     select CADENCE
     select VIRTIO_MMIO
     select UNIMP
rust/Kconfig +1 -0
index e69de29bb2..f9f5c39098 100644
@@ -0,0 +1 @@
+source hw/Kconfig
rust/hw/Kconfig new file +2 -0
new file mode 100644
index 0000000000..4d934f30af
@@ -0,0 +1,2 @@
+# devices Kconfig
+source char/Kconfig
rust/hw/char/Kconfig new file +3 -0
new file mode 100644
index 0000000000..a1732a9e97
@@ -0,0 +1,3 @@
+config X_PL011_RUST
+    bool
+    default y if HAVE_RUST
rust/hw/char/meson.build new file +1 -0
new file mode 100644
index 0000000000..5716dc43ef
@@ -0,0 +1 @@
+subdir('pl011')
rust/hw/char/pl011/.gitignore new file +2 -0
new file mode 100644
index 0000000000..71eaff2035
@@ -0,0 +1,2 @@
+# Ignore generated bindings file overrides.
+src/bindings.rs.inc
rust/hw/char/pl011/Cargo.lock new file +134 -0

134 lines not on this page · raw message

rust/hw/char/pl011/Cargo.toml new file +26 -0
new file mode 100644
index 0000000000..b089e3dded
@@ -0,0 +1,26 @@
+[package]
+name = "pl011"
+version = "0.1.0"
+edition = "2021"
+authors = ["Manos Pitsidianakis <[email protected]>"]
+license = "GPL-2.0-or-later"
+readme = "README.md"
+homepage = "https://www.qemu.org"
+description = "pl011 device model for QEMU"
+repository = "https://gitlab.com/epilys/rust-for-qemu"
+resolver = "2"
+publish = false
+keywords = []
+categories = []
+
+[lib]
+crate-type = ["staticlib"]
+
+[dependencies]
+bilge = { version = "0.2.0" }
+bilge-impl = { version = "0.2.0" }
+qemu_api = { path = "../../../qemu-api" }
+qemu_api_macros = { path = "../../../qemu-api-macros" }
+
+# Do not include in any global workspace
+[workspace]
rust/hw/char/pl011/README.md new file +31 -0
new file mode 100644
index 0000000000..cd7dea3163
@@ -0,0 +1,31 @@
+# PL011 QEMU Device Model
+
+This library implements a device model for the PrimeCell® UART (PL011)
+device in QEMU.
+
+## Build static lib
+
+Host build target must be explicitly specified:
+
+```sh
+cargo build --target x86_64-unknown-linux-gnu
+```
+
+Replace host target triplet if necessary.
+
+## Generate Rust documentation
+
+To generate docs for this crate, including private items:
+
+```sh
+cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu
+```
+
+To include direct dependencies like `bilge` (bitmaps for register types):
+
+```sh
+cargo tree --depth 1 -e normal --prefix none \
+ | cut -d' ' -f1 \
+ | xargs printf -- '-p %s\n' \
+ | xargs cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu
+```
rust/hw/char/pl011/meson.build new file +26 -0
new file mode 100644
index 0000000000..547cca5a96
@@ -0,0 +1,26 @@
+subproject('bilge-0.2-rs', required: true)
+subproject('bilge-impl-0.2-rs', required: true)
+
+bilge_dep = dependency('bilge-0.2-rs')
+bilge_impl_dep = dependency('bilge-impl-0.2-rs')
+
+_libpl011_rs = static_library(
+  'pl011',
+  files('src/lib.rs'),
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  dependencies: [
+    bilge_dep,
+    bilge_impl_dep,
+    qemu_api,
+    qemu_api_macros,
+  ],
+)
+
+rust_devices_ss.add(when: 'CONFIG_X_PL011_RUST', if_true: [declare_dependency(
+  link_whole: [_libpl011_rs],
+  # Putting proc macro crates in `dependencies` is necessary for Meson to find
+  # them when compiling the root per-target static rust lib.
+  dependencies: [bilge_impl_dep, qemu_api_macros],
+  variables: {'crate': 'pl011'},
+)])
rust/hw/char/pl011/src/device.rs new file +599 -0

599 lines not on this page · raw message

rust/hw/char/pl011/src/device_class.rs new file +70 -0

70 lines not on this page · raw message

rust/hw/char/pl011/src/lib.rs new file +586 -0

586 lines not on this page · raw message

rust/hw/char/pl011/src/memory_ops.rs new file +59 -0

59 lines not on this page · raw message

rust/hw/meson.build new file +1 -0
new file mode 100644
index 0000000000..860196645e
@@ -0,0 +1 @@
+subdir('char')
rust/meson.build +2 -0
index 7a32b1b195..def77389cd 100644
@@ -1,2 +1,4 @@
 subdir('qemu-api-macros')
 subdir('qemu-api')
+
+subdir('hw')
scripts/archive-source.sh +3 -1
index 6239cf1815..6189e47c8a 100755
@@ -28,7 +28,9 @@ sub_file="${sub_tdir}/submodule.tar"
 # different to the host OS.
 subprojects="keycodemapdb libvfio-user berkeley-softfloat-3
   berkeley-testfloat-3 unicode-ident-1.0.12 proc-macro2-1.0.84
-  quote-1.0.36 syn-2.0.66"
+  quote-1.0.36 syn-2.0.66 arbitrary-int-1.2.7 bilge-0.2.0 bilge-impl-0.2.0
+  either-1.12.0 itertools-0.11.0 proc-macro-error-1.0.4
+  proc-macro-error-attr-1.0.4"
 sub_deinit=""
 
 function cleanup() {
scripts/make-release +3 -1
index 076e588953..02cf4accce 100755
@@ -18,7 +18,9 @@ fi
 
 # Only include wraps that are invoked with subproject()
 SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3
-  proc-macro2-1.0.84 quote-1.0.36 syn-2.0.66 unicode-ident-1.0.12"
+  proc-macro2-1.0.84 quote-1.0.36 syn-2.0.66 unicode-ident-1.0.12
+  arbitrary-int-1.2.7 bilge-0.2.0 bilge-impl-0.2.0 either-1.12.0 itertools-0.11.0
+  proc-macro-error-1.0.4 proc-macro-error-attr-1.0.4"
 
 src="$1"
 version="$2"
scripts/rust/rust_root_crate.sh new file +13 -0
new file mode 100755
index 0000000000..975bddf7f1
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+set -eu
+
+cat <<EOF
+// @generated
+// This file is autogenerated by scripts/rust_root_crate.sh
+
+EOF
+
+for crate in $*; do
+    echo "extern crate $crate;"
+done
subprojects/.gitignore +7 -0
index b6888182ca..50f173f90d 100644
@@ -6,6 +6,13 @@
 /keycodemapdb
 /libvfio-user
 /slirp
+/arbitrary-int-1.2.7
+/bilge-0.2.0
+/bilge-impl-0.2.0
+/either-1.12.0
+/itertools-0.11.0
+/proc-macro-error-1.0.4
+/proc-macro-error-attr-1.0.4
 /proc-macro2-1.0.84
 /quote-1.0.36
 /syn-2.0.66
subprojects/arbitrary-int-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..e580538a87
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = arbitrary-int-1.2.7
+source_url = https://crates.io/api/v1/crates/arbitrary-int/1.2.7/download
+source_filename = arbitrary-int-1.2.7.tar.gz
+source_hash = c84fc003e338a6f69fbd4f7fe9f92b535ff13e9af8997f3b14b6ddff8b1df46d
+#method = cargo
+patch_directory = arbitrary-int-1-rs
subprojects/bilge-0.2-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..7a4339d298
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = bilge-0.2.0
+source_url = https://crates.io/api/v1/crates/bilge/0.2.0/download
+source_filename = bilge-0.2.0.tar.gz
+source_hash = dc707ed8ebf81de5cd6c7f48f54b4c8621760926cdf35a57000747c512e67b57
+#method = cargo
+patch_directory = bilge-0.2-rs
subprojects/bilge-impl-0.2-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..eefb10c36c
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = bilge-impl-0.2.0
+source_url = https://crates.io/api/v1/crates/bilge-impl/0.2.0/download
+source_filename = bilge-impl-0.2.0.tar.gz
+source_hash = feb11e002038ad243af39c2068c8a72bcf147acf05025dcdb916fcc000adb2d8
+#method = cargo
+patch_directory = bilge-impl-0.2-rs
subprojects/either-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..6046712036
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = either-1.12.0
+source_url = https://crates.io/api/v1/crates/either/1.12.0/download
+source_filename = either-1.12.0.tar.gz
+source_hash = 3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b
+#method = cargo
+patch_directory = either-1-rs
subprojects/itertools-0.11-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..66b05252cd
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = itertools-0.11.0
+source_url = https://crates.io/api/v1/crates/itertools/0.11.0/download
+source_filename = itertools-0.11.0.tar.gz
+source_hash = b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57
+#method = cargo
+patch_directory = itertools-0.11-rs
subprojects/packagefiles/arbitrary-int-1-rs/meson.build new file +19 -0
new file mode 100644
index 0000000000..34a189cbae
@@ -0,0 +1,19 @@
+project('arbitrary-int-1-rs', 'rust',
+  version: '1.2.7',
+  license: 'MIT',
+  default_options: [])
+
+_arbitrary_int_rs = static_library(
+  'arbitrary_int',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  dependencies: [],
+)
+
+arbitrary_int_dep = declare_dependency(
+  link_with: _arbitrary_int_rs,
+)
+
+meson.override_dependency('arbitrary-int-1-rs', arbitrary_int_dep)
subprojects/packagefiles/bilge-0.2-rs/meson.build new file +29 -0
new file mode 100644
index 0000000000..a6ed4a8f0c
@@ -0,0 +1,29 @@
+project(
+  'bilge-0.2-rs',
+  'rust',
+  version : '0.2.0',
+  license : 'MIT or Apache-2.0',
+)
+
+subproject('arbitrary-int-1-rs', required: true)
+subproject('bilge-impl-0.2-rs', required: true)
+
+arbitrary_int_dep = dependency('arbitrary-int-1-rs')
+bilge_impl_dep = dependency('bilge-impl-0.2-rs')
+
+lib = static_library(
+  'bilge',
+  'src/lib.rs',
+  override_options : ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi : 'rust',
+  dependencies: [
+    arbitrary_int_dep,
+    bilge_impl_dep,
+  ],
+)
+
+bilge_dep = declare_dependency(
+  link_with : [lib],
+)
+
+meson.override_dependency('bilge-0.2-rs', bilge_dep)
subprojects/packagefiles/bilge-impl-0.2-rs/meson.build new file +45 -0

45 lines not on this page · raw message

subprojects/packagefiles/either-1-rs/meson.build new file +24 -0
new file mode 100644
index 0000000000..a5842eb3a6
@@ -0,0 +1,24 @@
+project('either-1-rs', 'rust',
+  version: '1.12.0',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+_either_rs = static_library(
+  'either',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2018', 'build.rust_std=2018'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'feature="use_std"',
+    '--cfg', 'feature="use_alloc"',
+  ],
+  dependencies: [],
+  native: true,
+)
+
+either_dep = declare_dependency(
+  link_with: _either_rs,
+)
+
+meson.override_dependency('either-1-rs', either_dep, native: true)
subprojects/packagefiles/itertools-0.11-rs/meson.build new file +30 -0
new file mode 100644
index 0000000000..13d2d27019
@@ -0,0 +1,30 @@
+project('itertools-0.11-rs', 'rust',
+  version: '0.11.0',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('either-1-rs', required: true)
+
+either_dep = dependency('either-1-rs', native: true)
+
+_itertools_rs = static_library(
+  'itertools',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2018', 'build.rust_std=2018'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'feature="use_std"',
+    '--cfg', 'feature="use_alloc"',
+  ],
+  dependencies: [
+    either_dep,
+  ],
+  native: true,
+)
+
+itertools_dep = declare_dependency(
+  link_with: _itertools_rs,
+)
+
+meson.override_dependency('itertools-0.11-rs', itertools_dep, native: true)
subprojects/packagefiles/proc-macro-error-1-rs/meson.build new file +40 -0
new file mode 100644
index 0000000000..38ea7b89d3
@@ -0,0 +1,40 @@
+project('proc-macro-error-1-rs', 'rust',
+  version: '1.0.4',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('proc-macro-error-attr-1-rs', required: true)
+subproject('quote-1-rs', required: true)
+subproject('syn-2-rs', required: true)
+subproject('proc-macro2-1-rs', required: true)
+
+proc_macro_error_attr_dep = dependency('proc-macro-error-attr-1-rs', native: true)
+proc_macro2_dep = dependency('proc-macro2-1-rs', native: true)
+quote_dep = dependency('quote-1-rs', native: true)
+syn_dep = dependency('syn-2-rs', native: true)
+
+_proc_macro_error_rs = static_library(
+  'proc_macro_error',
+  files('src/lib.rs'),
+  override_options: ['rust_std=2018', 'build.rust_std=2018'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'use_fallback',
+    '--cfg', 'feature="syn-error"',
+    '--cfg', 'feature="proc-macro"',
+    '-A', 'non_fmt_panics'
+  ],
+  dependencies: [
+    proc_macro_error_attr_dep,
+    proc_macro2_dep,
+    quote_dep,
+    syn_dep,
+  ],
+  native: true,
+)
+
+proc_macro_error_dep = declare_dependency(
+  link_with: _proc_macro_error_rs,
+)
+
+meson.override_dependency('proc-macro-error-1-rs', proc_macro_error_dep, native: true)
subprojects/packagefiles/proc-macro-error-attr-1-rs/meson.build new file +32 -0
new file mode 100644
index 0000000000..d900c54cfd
@@ -0,0 +1,32 @@
+project('proc-macro-error-attr-1-rs', 'rust',
+  version: '1.12.0',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('proc-macro2-1-rs', required: true)
+subproject('quote-1-rs', required: true)
+
+proc_macro2_dep = dependency('proc-macro2-1-rs', native: true)
+quote_dep = dependency('quote-1-rs', native: true)
+
+rust = import('rust')
+_proc_macro_error_attr_rs = rust.proc_macro(
+  'proc_macro_error_attr',
+  files('src/lib.rs'),
+  override_options: ['rust_std=2018', 'build.rust_std=2018'],
+  rust_args: [
+    '--cfg', 'use_fallback',
+    '--cfg', 'feature="syn-error"',
+    '--cfg', 'feature="proc-macro"'
+  ],
+  dependencies: [
+    proc_macro2_dep,
+    quote_dep,
+  ],
+)
+
+proc_macro_error_attr_dep = declare_dependency(
+  link_with: _proc_macro_error_attr_rs,
+)
+
+meson.override_dependency('proc-macro-error-attr-1-rs', proc_macro_error_attr_dep, native: true)
subprojects/packagefiles/unicode-ident-1-rs/meson.build new file +20 -0
new file mode 100644
index 0000000000..54f2376854
@@ -0,0 +1,20 @@
+project('unicode-ident-1-rs', 'rust',
+  version: '1.0.12',
+  license: '(MIT OR Apache-2.0) AND Unicode-DFS-2016',
+  default_options: [])
+
+_unicode_ident_rs = static_library(
+  'unicode_ident',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  dependencies: [],
+  native: true,
+)
+
+unicode_ident_dep = declare_dependency(
+  link_with: _unicode_ident_rs,
+)
+
+meson.override_dependency('unicode-ident-1-rs', unicode_ident_dep, native: true)
subprojects/proc-macro-error-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..b7db03b06a
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = proc-macro-error-1.0.4
+source_url = https://crates.io/api/v1/crates/proc-macro-error/1.0.4/download
+source_filename = proc-macro-error-1.0.4.tar.gz
+source_hash = da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c
+#method = cargo
+patch_directory = proc-macro-error-1-rs
subprojects/proc-macro-error-attr-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..d13d8a239a
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = proc-macro-error-attr-1.0.4
+source_url = https://crates.io/api/v1/crates/proc-macro-error-attr/1.0.4/download
+source_filename = proc-macro-error-attr-1.0.4.tar.gz
+source_hash = a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869
+#method = cargo
+patch_directory = proc-macro-error-attr-1-rs
Signature · 1 line
γαῖα πυρί μιχθήτω
#6 lore raw

PATCH v11 6/9 meson.build: add HAVE_GLIB_WITH_ALIGNED_ALLOC flag

In reply to Manos Pitsidianakis

Rust crates, introduced from the next commit onwards, can optionally use the glib allocator API and need to know whether g_aligned_alloc etc are available.

This commit adds a define in config_host_data that depends on glib version >= 2.72.

---
 meson.build | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
meson.build +7 -1
index 04fd17bb6b..c952b3b15a 100644
@@ -948,7 +948,9 @@ have_xen_pci_passthrough = get_option('xen_pci_passthrough') \
 ################
 
 # When bumping glib minimum version, please check also whether to increase
-# the _WIN32_WINNT setting in osdep.h according to the value from glib
+# the _WIN32_WINNT setting in osdep.h according to the value from glib.
+# You should also check if any of the glib.version() checks
+# below can also be removed.
 glib_req_ver = '>=2.66.0'
 glib_pc = dependency('glib-2.0', version: glib_req_ver, required: true,
                     method: 'pkg-config')
@@ -998,6 +1000,9 @@ glib = declare_dependency(dependencies: [glib_pc, gmodule],
 # TODO: remove this check and the corresponding workaround (qtree) when
 # the minimum supported glib is >= 2.75.3
 glib_has_gslice = glib.version().version_compare('<2.75.3')
+# Check whether glib has the aligned_alloc family of functions.
+# <https://docs.gtk.org/glib/func.aligned_alloc.html>
+glib_has_aligned_alloc = glib.version().version_compare('>=2.72.0')
 
 # override glib dep to include the above refinements
 meson.override_dependency('glib-2.0', glib)
@@ -2536,6 +2541,7 @@ config_host_data.set('CONFIG_TIMERFD', cc.has_function('timerfd_create'))
 config_host_data.set('HAVE_COPY_FILE_RANGE', cc.has_function('copy_file_range'))
 config_host_data.set('HAVE_GETIFADDRS', cc.has_function('getifaddrs'))
 config_host_data.set('HAVE_GLIB_WITH_SLICE_ALLOCATOR', glib_has_gslice)
+config_host_data.set('HAVE_GLIB_WITH_ALIGNED_ALLOC', glib_has_aligned_alloc)
 config_host_data.set('HAVE_OPENPTY', cc.has_function('openpty', dependencies: util))
 config_host_data.set('HAVE_STRCHRNUL', cc.has_function('strchrnul'))
 config_host_data.set('HAVE_SYSTEM_FUNCTION', cc.has_function('system', prefix: '#include <stdlib.h>'))
Signature · 1 line
γαῖα πυρί μιχθήτω
#0 lore raw

v11 cover Add Rust build support, ARM PL011 device impl

WARNING: This series contains a patch with blob diffs (update of python wheels) and thus problems may arise with your patch workflow. The revision is available at
https://gitlab.com/epilys/qemu/-/tree/20240814-rust-pl011-v7-v11 for you to fetch. HEAD is 6ec1d4fb8db2a1d7ba94c73e65d9770371b7857d

Hello everyone,

This series adds:

- build system support for the Rust compiler
- a small Rust library, qemu-api, which includes bindings to QEMU's C interface generated with bindgen, and qemu-api-macros, a procedural macro library.
- a proof of concept ARM PL011 device implementation in Rust, chosen for its low complexity. The device is used in the arm virt machine if qemu is compiled with rust enabled (./configure --enable-rust [...])

---
Changes in v11:
- rebased against current master
- addressed review comments by Junjie
- addressed review comments by Paolo
- added r-o-bs
- use rustified and bitfield enum generation with bindgen
- use size_t instead of usize for FFI
- Link to v10: https://lore.kernel.org/qemu-devel/[email protected]

See also range-diff against v10 at the end of the cover letter.

Changes in v10:
- Removed unnecessary meson version check (thanks Alex)
- Added warning in configure when Rust is not disabled about what to
do if bindgen does not detect the correct libclang and fails to find certain system header files.
- Disabled rust qemu allocator by default
- Added changes by Paolo to detect the correct rust target for cross compilation in configure script.
- Made PL011State::init fn unsafe (Paolo)
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Addressed v8 review comment: removed rustfmt.toml symlink (Junjie Mao)
- Addressed v8 review comment: removed unused cstr files (Junjie Mao)
- Addressed v8 review comment: added HAVE_GLIB_WITH_ALIGNED_ALLOC config host def to check whether glib's aligned alloc functions are available (Junjie Mao)
- qemu_api: Changed default alignment condition in allocator (alignment is always nonzero)
- qemu_api: Enabled allocator by default in builds
- pl011: fixed invalid cast of byte buffer to u32 in pl011_receive() leading to misaligned read

- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- Allow for compilation of more than one Rust-based component in Meson by compiling all Rust static libraries into one "root" library before linking it to each target emulation executable.
- Added a qemu_api_macros procedural macro library.
- (minor) Moved generated bindings.rs to qemu_api crate using meson's structured_source() instead of compiling it as a standalone crate which was unnecessary.
- (minor) Removed unnecessary rustc optimization/debug flags (should be handled by meson instead).
- (minor) Moved build scripts under scripts/rust/
- (minor) Fixed license issues

Previous version was: <[email protected]>

https://lore.kernel.org/qemu-devel/[email protected]/

Outstanding issues that are not blocking for merge are:

- Cross-compilation for aarch64 is not possible out-of-the-box because of this bug:
<https://github.com/rust-lang/rust/issues/125619> in llvm which when fixed, must be ported to upstream rust's llvm fork. Since the problem is an extraneous symbol we could strip it with objcopy -N|--strip-symbol Fix is in upstream llvm, we're awaiting for rust upstream to pick it up.

Manos Pitsidianakis (7):
build-sys: Add rust feature option
rust: add bindgen step as a meson dependency .gitattributes: add Rust diff and merge attributes meson.build: add HAVE_GLIB_WITH_ALIGNED_ALLOC flag
rust: add crate to expose bindings and interfaces
rust: add utility procedural macro crate
rust: add PL011 device model

Paolo Bonzini (2):
Require meson version 1.5.0
configure, meson: detect Rust toolchain

 MAINTAINERS                                   |  21 +
 configure                                     | 170 ++++-
 meson.build                                   | 125 +++-
 rust/wrapper.h                                |  47 ++
 .gitattributes                                |   3 +
 Kconfig                                       |   1 +
 Kconfig.host                                  |   3 +
 hw/arm/Kconfig                                |  30 +-
 meson_options.txt                             |   3 +
 python/scripts/vendor.py                      |   4 +-
 python/wheels/meson-1.2.3-py3-none-any.whl    | Bin 964928 -> 0 bytes
 python/wheels/meson-1.5.0-py3-none-any.whl    | Bin 0 -> 959846 bytes
 pythondeps.toml                               |   2 +-
 rust/.gitignore                               |   3 +
 rust/Kconfig                                  |   1 +
 rust/hw/Kconfig                               |   2 +
 rust/hw/char/Kconfig                          |   3 +
 rust/hw/char/meson.build                      |   1 +
 rust/hw/char/pl011/.gitignore                 |   2 +
 rust/hw/char/pl011/Cargo.lock                 | 134 ++++
 rust/hw/char/pl011/Cargo.toml                 |  26 +
 rust/hw/char/pl011/README.md                  |  31 +
 rust/hw/char/pl011/meson.build                |  26 +
 rust/hw/char/pl011/src/device.rs              | 599 ++++++++++++++++++
 rust/hw/char/pl011/src/device_class.rs        |  70 ++
 rust/hw/char/pl011/src/lib.rs                 | 586 +++++++++++++++++
 rust/hw/char/pl011/src/memory_ops.rs          |  59 ++
 rust/hw/meson.build                           |   1 +
 rust/meson.build                              |   4 +
 rust/qemu-api-macros/Cargo.lock               |  47 ++
 rust/qemu-api-macros/Cargo.toml               |  25 +
 rust/qemu-api-macros/README.md                |   1 +
 rust/qemu-api-macros/meson.build              |  25 +
 rust/qemu-api-macros/src/lib.rs               |  43 ++
 rust/qemu-api/.gitignore                      |   2 +
 rust/qemu-api/Cargo.lock                      |   7 +
 rust/qemu-api/Cargo.toml                      |  26 +
 rust/qemu-api/README.md                       |  17 +
 rust/qemu-api/build.rs                        |  14 +
 rust/qemu-api/meson.build                     |  24 +
 rust/qemu-api/src/definitions.rs              |  97 +++
 rust/qemu-api/src/device_class.rs             | 128 ++++
 rust/qemu-api/src/lib.rs                      | 166 +++++
 rust/qemu-api/src/tests.rs                    |  49 ++
 rust/rustfmt.toml                             |   7 +
 scripts/archive-source.sh                     |   6 +-
 scripts/make-release                          |   5 +-
 scripts/meson-buildoptions.sh                 |   3 +
 scripts/rust/rust_root_crate.sh               |  13 +
 scripts/rust/rustc_args.py                    |  84 +++
 subprojects/.gitignore                        |  11 +
 subprojects/arbitrary-int-1-rs.wrap           |   7 +
 subprojects/bilge-0.2-rs.wrap                 |   7 +
 subprojects/bilge-impl-0.2-rs.wrap            |   7 +
 subprojects/either-1-rs.wrap                  |   7 +
 subprojects/itertools-0.11-rs.wrap            |   7 +
 .../arbitrary-int-1-rs/meson.build            |  19 +
 .../packagefiles/bilge-0.2-rs/meson.build     |  29 +
 .../bilge-impl-0.2-rs/meson.build             |  45 ++
 .../packagefiles/either-1-rs/meson.build      |  24 +
 .../itertools-0.11-rs/meson.build             |  30 +
 .../proc-macro-error-1-rs/meson.build         |  40 ++
 .../proc-macro-error-attr-1-rs/meson.build    |  32 +
 .../packagefiles/proc-macro2-1-rs/meson.build |  31 +
 .../packagefiles/quote-1-rs/meson.build       |  29 +
 subprojects/packagefiles/syn-2-rs/meson.build |  40 ++
 .../unicode-ident-1-rs/meson.build            |  20 +
 subprojects/proc-macro-error-1-rs.wrap        |   7 +
 subprojects/proc-macro-error-attr-1-rs.wrap   |   7 +
 subprojects/proc-macro2-1-rs.wrap             |   7 +
 subprojects/quote-1-rs.wrap                   |   7 +
 subprojects/syn-2-rs.wrap                     |   7 +
 subprojects/unicode-ident-1-rs.wrap           |   7 +
 subprojects/unicode-ident-1-rs/meson.build    |  20 +
 tests/lcitool/mappings.yml                    |   2 +-
 75 files changed, 3174 insertions(+), 21 deletions(-)
 create mode 100644 rust/wrapper.h
 delete mode 100644 python/wheels/meson-1.2.3-py3-none-any.whl
 create mode 100644 python/wheels/meson-1.5.0-py3-none-any.whl
 create mode 100644 rust/.gitignore
 create mode 100644 rust/Kconfig
 create mode 100644 rust/hw/Kconfig
 create mode 100644 rust/hw/char/Kconfig
 create mode 100644 rust/hw/char/meson.build
 create mode 100644 rust/hw/char/pl011/.gitignore
 create mode 100644 rust/hw/char/pl011/Cargo.lock
 create mode 100644 rust/hw/char/pl011/Cargo.toml
 create mode 100644 rust/hw/char/pl011/README.md
 create mode 100644 rust/hw/char/pl011/meson.build
 create mode 100644 rust/hw/char/pl011/src/device.rs
 create mode 100644 rust/hw/char/pl011/src/device_class.rs
 create mode 100644 rust/hw/char/pl011/src/lib.rs
 create mode 100644 rust/hw/char/pl011/src/memory_ops.rs
 create mode 100644 rust/hw/meson.build
 create mode 100644 rust/meson.build
 create mode 100644 rust/qemu-api-macros/Cargo.lock
 create mode 100644 rust/qemu-api-macros/Cargo.toml
 create mode 100644 rust/qemu-api-macros/README.md
 create mode 100644 rust/qemu-api-macros/meson.build
 create mode 100644 rust/qemu-api-macros/src/lib.rs
 create mode 100644 rust/qemu-api/.gitignore
 create mode 100644 rust/qemu-api/Cargo.lock
 create mode 100644 rust/qemu-api/Cargo.toml
 create mode 100644 rust/qemu-api/README.md
 create mode 100644 rust/qemu-api/build.rs
 create mode 100644 rust/qemu-api/meson.build
 create mode 100644 rust/qemu-api/src/definitions.rs
 create mode 100644 rust/qemu-api/src/device_class.rs
 create mode 100644 rust/qemu-api/src/lib.rs
 create mode 100644 rust/qemu-api/src/tests.rs
 create mode 100644 rust/rustfmt.toml
 create mode 100755 scripts/rust/rust_root_crate.sh
 create mode 100644 scripts/rust/rustc_args.py
 create mode 100644 subprojects/arbitrary-int-1-rs.wrap
 create mode 100644 subprojects/bilge-0.2-rs.wrap
 create mode 100644 subprojects/bilge-impl-0.2-rs.wrap
 create mode 100644 subprojects/either-1-rs.wrap
 create mode 100644 subprojects/itertools-0.11-rs.wrap
 create mode 100644 subprojects/packagefiles/arbitrary-int-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/bilge-0.2-rs/meson.build
 create mode 100644 subprojects/packagefiles/bilge-impl-0.2-rs/meson.build
 create mode 100644 subprojects/packagefiles/either-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/itertools-0.11-rs/meson.build
 create mode 100644 subprojects/packagefiles/proc-macro-error-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/proc-macro-error-attr-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/proc-macro2-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/quote-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/syn-2-rs/meson.build
 create mode 100644 subprojects/packagefiles/unicode-ident-1-rs/meson.build
 create mode 100644 subprojects/proc-macro-error-1-rs.wrap
 create mode 100644 subprojects/proc-macro-error-attr-1-rs.wrap
 create mode 100644 subprojects/proc-macro2-1-rs.wrap
 create mode 100644 subprojects/quote-1-rs.wrap
 create mode 100644 subprojects/syn-2-rs.wrap
 create mode 100644 subprojects/unicode-ident-1-rs.wrap
 create mode 100644 subprojects/unicode-ident-1-rs/meson.build

Range-diff against v10:
1: 9335dd9849 ! 1: 74e1eb4b13 Require meson version 1.5.0
@@ pythondeps.toml
# The install key should match the version in python/wheels/
-meson = { accepted = ">=1.1.0", installed = "1.2.3", canary = "meson" } +meson = { accepted = ">=1.5.0", installed = "1.5.0", canary = "meson" }
+ pycotap = { accepted = ">=1.1.0", installed = "1.3.1" }

[docs]
- # Please keep the installed versions in sync with docs/requirements.txt

## tests/lcitool/mappings.yml ##
@@ tests/lcitool/mappings.yml: mappings:

 2:  b7508a1a2c =  2:  14642d80fb build-sys: Add rust feature option
 3:  a764b69afa =  3:  207d2640b3 configure, meson: detect Rust toolchain
 4:  492e93bf71 !  4:  1be89a2771 rust: add bindgen step as a meson dependency
    @@ meson.build: common_all = static_library('common',
                                  dependencies: common_ss.all_dependencies())
      
     +if have_rust and have_system
    -+  rustc_config_args = run_command(
    ++  rustc_args = run_command(
     +    find_program('scripts/rust/rustc_args.py'),
     +    '--config-headers', meson.project_build_root() / 'config-host.h',
     +    capture : true,
     +    check: true).stdout().strip().split()
    ++  rustc_args += ['-D', 'unsafe_op_in_unsafe_fn']
    ++  bindgen_args = [
    ++    '--disable-header-comment',
    ++    '--raw-line', '// @generated',
    ++    '--ctypes-prefix', 'core::ffi',
    ++    '--formatter', 'rustfmt',
    ++    '--generate-block',
    ++    '--generate-cstr',
    ++    '--impl-debug',
    ++    '--merge-extern-blocks',
    ++    '--no-doc-comments',
    ++    '--use-core',
    ++    '--with-derive-default',
    ++    '--no-size_t-is-usize',
    ++    '--no-layout-tests',
    ++    '--no-prepend-enum-name',
    ++    '--allowlist-file', meson.project_source_root() + '/include/.*',
    ++    '--allowlist-file', meson.project_source_root() + '/.*',
    ++    '--allowlist-file', meson.project_build_root() + '/.*'
    ++    ]
    ++  c_enums = [
    ++    'DeviceCategory',
    ++    'GpioPolarity',
    ++    'MachineInitPhase',
    ++    'MemoryDeviceInfoKind',
    ++    'MigrationPolicy',
    ++    'MigrationPriority',
    ++    'QEMUChrEvent',
    ++    'QEMUClockType',
    ++    'device_endian',
    ++    'module_init_type',
    ++  ]
    ++  foreach enum : c_enums
    ++    bindgen_args += ['--rustified-enum', enum]
    ++  endforeach
    ++  c_bitfields = [
    ++    'ClockEvent',
    ++    'VMStateFlags',
    ++  ]
    ++  foreach enum : c_bitfields
    ++    bindgen_args += ['--bitfield-enum', enum]
    ++  endforeach
     +
     +  # TODO: Remove this comment when the clang/libclang mismatch issue is solved.
     +  #
    @@ meson.build: common_all = static_library('common',
     +    output: 'bindings.rs',
     +    include_directories: include_directories('.', 'include'),
     +    bindgen_version: ['>=0.69.4'],
    -+    args: [
    -+      '--disable-header-comment',
    -+      '--raw-line', '// @generated',
    -+      '--ctypes-prefix', 'core::ffi',
    -+      '--formatter', 'rustfmt',
    -+      '--generate-block',
    -+      '--generate-cstr',
    -+      '--impl-debug',
    -+      '--merge-extern-blocks',
    -+      '--no-doc-comments',
    -+      '--use-core',
    -+      '--with-derive-default',
    -+      '--allowlist-file', meson.project_source_root() + '/include/.*',
    -+      '--allowlist-file', meson.project_source_root() + '/.*',
    -+      '--allowlist-file', meson.project_build_root() + '/.*'
    -+      ],
    ++    args: bindgen_args,
     +    )
     +  subdir('rust')
     +endif
 5:  40937067f9 =  5:  278e3878b4 .gitattributes: add Rust diff and merge attributes
 6:  c9b544bc01 =  6:  23f7b0cc98 meson.build: add HAVE_GLIB_WITH_ALIGNED_ALLOC flag
 7:  f4dfecd31b !  7:  0fb23fbe21 rust: add crate to expose bindings and interfaces

@@ rust/qemu-api/meson.build (new)
+ ),
+ override_options: ['rust_std=2021', 'build.rust_std=2021'],
+ rust_abi: 'rust',
-+ rust_args: rustc_config_args + [
++ rust_args: rustc_args + [
+ '--cfg', 'MESON',
+ # '--cfg', 'feature="allocator"',
+ ],
@@ rust/qemu-api/src/definitions.rs (new)
+
+//! Definitions required by QEMU when registering a device.
+
++use ::core::ffi::{c_void, CStr};
++
++use crate::bindings::{Object, ObjectClass, TypeInfo};
++
+/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl {
+ type Class;
-+ const TYPE_INFO: crate::bindings::TypeInfo;
-+ const TYPE_NAME: &'static ::core::ffi::CStr;
-+ const PARENT_TYPE_NAME: Option<&'static ::core::ffi::CStr>;
-+ const INSTANCE_INIT: ::core::option::Option<
-+ unsafe extern "C" fn(obj: *mut crate::bindings::Object),
-+ >;
-+ const INSTANCE_POST_INIT: ::core::option::Option<
-+ unsafe extern "C" fn(obj: *mut crate::bindings::Object),
-+ >;
-+ const INSTANCE_FINALIZE: ::core::option::Option<
-+ unsafe extern "C" fn(obj: *mut crate::bindings::Object),
-+ >;
++ const TYPE_INFO: TypeInfo;
++ const TYPE_NAME: &'static CStr;
++ const PARENT_TYPE_NAME: Option<&'static CStr>;
+ const ABSTRACT: bool;
++ const INSTANCE_INIT: Option<unsafe extern "C" fn(obj: *mut Object)>;
++ const INSTANCE_POST_INIT: Option<unsafe extern "C" fn(obj: *mut Object)>;
++ const INSTANCE_FINALIZE: Option<unsafe extern "C" fn(obj: *mut Object)>;
+}
+
+pub trait Class {
-+ const CLASS_INIT: ::core::option::Option<
-+ unsafe extern "C" fn(
-+ klass: *mut crate::bindings::ObjectClass,
-+ data: *mut core::ffi::c_void,
-+ ),
-+ >;
-+ const CLASS_BASE_INIT: ::core::option::Option<
-+ unsafe extern "C" fn(
-+ klass: *mut crate::bindings::ObjectClass,
-+ data: *mut core::ffi::c_void,
-+ ),
++ const CLASS_INIT: Option<unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void)>;
++ const CLASS_BASE_INIT: Option<
++ unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut c_void),
+ >;
+}
+
@@ rust/qemu-api/src/definitions.rs (new)
+ #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
+ #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
+ pub static LOAD_MODULE: extern "C" fn() = {
-+ assert!($type < $crate::bindings::module_init_type_MODULE_INIT_MAX);
-+
+ extern "C" fn __load() {
+ unsafe {
+ $crate::bindings::register_module_init(Some($func), $type);
@@ rust/qemu-api/src/definitions.rs (new)
+ unsafe {
+ $crate::bindings::register_module_init(
+ Some($func),
-+ $crate::bindings::module_init_type_MODULE_INIT_QOM,
++ $crate::bindings::module_init_type::MODULE_INIT_QOM,
+ );
+ }
+ }
@@ rust/qemu-api/src/definitions.rs (new)
+ } else {
+ ::core::ptr::null_mut()
+ },
-+ instance_size: ::core::mem::size_of::<$t>(),
-+ instance_align: ::core::mem::align_of::<$t>(),
++ instance_size: ::core::mem::size_of::<$t>() as $crate::bindings::size_t,
++ instance_align: ::core::mem::align_of::<$t>() as $crate::bindings::size_t,
+ instance_init: <$t as $crate::definitions::ObjectImpl>::INSTANCE_INIT,
+ instance_post_init: <$t as $crate::definitions::ObjectImpl>::INSTANCE_POST_INIT,
+ instance_finalize: <$t as $crate::definitions::ObjectImpl>::INSTANCE_FINALIZE,
+ abstract_: <$t as $crate::definitions::ObjectImpl>::ABSTRACT,
-+ class_size: ::core::mem::size_of::<<$t as $crate::definitions::ObjectImpl>::Class>(),
++ class_size: ::core::mem::size_of::<<$t as $crate::definitions::ObjectImpl>::Class>() as $crate::bindings::size_t,
+ class_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_INIT,
+ class_base_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_BASE_INIT,
+ class_data: ::core::ptr::null_mut(),
@@ rust/qemu-api/src/device_class.rs (new)
+
+#[macro_export]
+macro_rules! device_class_init {
-+ ($func:ident, props => $props:ident, realize_fn => $realize_fn:expr, reset_fn => $reset_fn:expr, vmsd => $vmsd:ident$(,)*) => {
++ ($func:ident, props => $props:ident, realize_fn => $realize_fn:expr, legacy_reset_fn => $legacy_reset_fn:expr, vmsd => $vmsd:ident$(,)*) => {
+ #[no_mangle]
+ pub unsafe extern "C" fn $func(
+ klass: *mut $crate::bindings::ObjectClass,
@@ rust/qemu-api/src/device_class.rs (new)
+ let mut dc =
+ ::core::ptr::NonNull::new(klass.cast::<$crate::bindings::DeviceClass>()).unwrap();
+ dc.as_mut().realize = $realize_fn;
-+ dc.as_mut().reset = $reset_fn;
+ dc.as_mut().vmsd = &$vmsd;
++ $crate::bindings::device_class_set_legacy_reset(dc.as_mut(), $legacy_reset_fn);
+ $crate::bindings::device_class_set_props(dc.as_mut(), $props.as_mut_ptr());
+ }
+ };
@@ rust/qemu-api/src/lib.rs (new)
+ non_camel_case_types,
+ non_snake_case,
+ non_upper_case_globals,
++ unsafe_op_in_unsafe_fn,
+ clippy::missing_const_for_fn,
+ clippy::too_many_arguments,
+ clippy::approx_constant,
@@ rust/qemu-api/src/lib.rs (new)
+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+ if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
+ {
-+ g_malloc0(layout.size().try_into().unwrap()).cast::<u8>()
++ // SAFETY: g_malloc0() is safe to call.
++ unsafe { g_malloc0(layout.size().try_into().unwrap()).cast::<u8>() }
+ } else {
+ #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
+ {
-+ g_aligned_alloc0(
-+ layout.size().try_into().unwrap(),
-+ 1,
-+ (8 * layout.align()).try_into().unwrap(),
-+ )
-+ .cast::<u8>()
++ // SAFETY: g_aligned_alloc0() is safe to call.
++ unsafe {
++ g_aligned_alloc0(
++ layout.size().try_into().unwrap(),
++ 1,
++ layout.align().try_into().unwrap(),
++ )
++ .cast::<u8>()
++ }
+ }
+ #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
+ {
-+ qemu_memalign(8 * layout.align(), layout.size()).cast::<u8>()
++ // SAFETY: qemu_memalign() is safe to call.
++ unsafe { qemu_memalign(layout.align(), layout.size()).cast::<u8>() }
+ }
+ }
+ }
@@ rust/qemu-api/src/lib.rs (new)
+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
+ if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
+ {
-+ g_free(ptr.cast::<_>())
++ // SAFETY: ptr must have been allocated by Self::alloc thus a valid
++ // glib-allocated pointer, so g_freeing is safe.
++ unsafe { g_free(ptr.cast::<_>()) }
+ } else {
+ #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
+ {
-+ g_aligned_free(ptr.cast::<_>())
++ // SAFETY: ptr must have been allocated by Self::alloc thus a valid aligned
++ // glib-allocated pointer, so g_aligned_freeing is safe.
++ unsafe { g_aligned_free(ptr.cast::<_>()) }
+ }
+ #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
+ {
-+ qemu_vfree(ptr.cast::<_>())
++ // SAFETY: ptr must have been allocated by Self::alloc thus a valid aligned
++ // glib-allocated pointer, so qemu_vfreeing is safe.
++ unsafe { qemu_vfree(ptr.cast::<_>()) }
+ }
+ }
+ }
8: 6dc9aced83 ! 8: dd64564240 rust: add utility procedural macro crate
@@ Commit message
generates a constructor to register a QOM TypeInfo on init and it must be used on types that implement qemu_api::definitions::ObjectImpl trait.

+ Reviewed-by: Junjie Mao <[email protected]>

## MAINTAINERS ##
@@ rust/qemu-api-macros/src/lib.rs (new)
+ unsafe {
+ ::qemu_api::bindings::register_module_init(
+ Some(__register),
-+ ::qemu_api::bindings::module_init_type_MODULE_INIT_QOM
++ ::qemu_api::bindings::module_init_type::MODULE_INIT_QOM
+ );
+ }
+ }
9: a8b4c239a3 ! 9: 6ec1d4fb8d rust: add PL011 device model

    @@ meson.build: foreach target : target_dirs
     +                            rlib_rs,
     +                            dependencies: target_rust.dependencies(),
     +                            override_options: ['rust_std=2021', 'build.rust_std=2021'],
    -+                            rust_args: rustc_config_args,
    ++                            rust_args: rustc_args,
     +                            rust_abi: 'c')
     +      arch_deps += declare_dependency(link_whole: [rlib])
     +    endif
    @@ hw/arm/Kconfig: config MUSCA
          select PL031
          select SPLIT_IRQ
          select UNIMP
    -@@ hw/arm/Kconfig: config Z2
    -     depends on TCG && ARM
    -     select PFLASH_CFI01
    -     select WM8750
    --    select PL011 # UART
    -+    select PL011 if !HAVE_RUST # UART
    -+    select X_PL011_RUST if HAVE_RUST # UART
    -     select PXA2XX
    - 
    - config REALVIEW
     @@ hw/arm/Kconfig: config REALVIEW
          select WM8750 # audio codec
          select LSI_SCSI_PCI
    @@ rust/hw/char/pl011/meson.build (new)
     +  variables: {'crate': 'pl011'},
     +)])
     
    - ## rust/hw/char/pl011/src/definitions.rs (new) ##
    -@@
    -+// Copyright 2024, Linaro Limited
    -+// Author(s): Manos Pitsidianakis <[email protected]>
    -+// SPDX-License-Identifier: GPL-2.0-or-later
    -+
    -+//! Definitions required by QEMU when registering the device.
    -+
    -+use core::mem::MaybeUninit;
    -+
    -+use qemu_api::{bindings::*, definitions::ObjectImpl};
    -+
    -+use crate::device::PL011State;
    -+
    -+pub const TYPE_PL011: &std::ffi::CStr = c"pl011";
    -+
    -+#[used]
    -+pub static VMSTATE_PL011: VMStateDescription = VMStateDescription {
    -+    name: PL011State::TYPE_INFO.name,
    -+    unmigratable: true,
    -+    ..unsafe { MaybeUninit::<VMStateDescription>::zeroed().assume_init() }
    -+};
    -
      ## rust/hw/char/pl011/src/device.rs (new) ##
     @@
     +// Copyright 2024, Linaro Limited
    @@ rust/hw/char/pl011/src/device.rs (new)
     +impl ObjectImpl for PL011State {
     +    type Class = PL011Class;
     +    const TYPE_INFO: qemu_api::bindings::TypeInfo = qemu_api::type_info! { Self };
    -+    const TYPE_NAME: &'static CStr = c"pl011";
    ++    const TYPE_NAME: &'static CStr = crate::TYPE_PL011;
     +    const PARENT_TYPE_NAME: Option<&'static CStr> = Some(TYPE_SYS_BUS_DEVICE);
     +    const ABSTRACT: bool = false;
     +    const INSTANCE_INIT: Option<unsafe extern "C" fn(obj: *mut Object)> = Some(pl011_init);
    @@ rust/hw/char/pl011/src/device.rs (new)
     +                CLK_NAME.as_ptr(),
     +                None, /* pl011_clock_update */
     +                addr_of_mut!(*self).cast::<c_void>(),
    -+                ClockEvent_ClockUpdate,
    ++                ClockEvent::ClockUpdate.0,
     +            ))
     +            .unwrap();
     +        }
    @@ rust/hw/char/pl011/src/device.rs (new)
     +    }
     +
     +    pub fn event(&mut self, event: QEMUChrEvent) {
    -+        if event == bindings::QEMUChrEvent_CHR_EVENT_BREAK && !self.fifo_enabled() {
    ++        if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.fifo_enabled() {
     +            self.put_fifo(DATA_BREAK);
     +            self.receive_status_error_clear.set_break_error(true);
     +        }
    @@ rust/hw/char/pl011/src/device.rs (new)
     +#[no_mangle]
     +pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int {
     +    unsafe {
    -+        assert!(!opaque.is_null());
    ++        debug_assert!(!opaque.is_null());
     +        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
     +        state.as_ref().can_receive().into()
     +    }
    @@ rust/hw/char/pl011/src/device.rs (new)
     +    size: core::ffi::c_int,
     +) {
     +    unsafe {
    -+        assert!(!opaque.is_null());
    ++        debug_assert!(!opaque.is_null());
     +        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
     +        if state.as_ref().loopback_enabled() {
     +            return;
     +        }
     +        if size > 0 {
    -+            assert!(!buf.is_null());
    ++            debug_assert!(!buf.is_null());
     +            state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))
     +        }
     +    }
    @@ rust/hw/char/pl011/src/device.rs (new)
     +#[no_mangle]
     +pub unsafe extern "C" fn pl011_event(opaque: *mut core::ffi::c_void, event: QEMUChrEvent) {
     +    unsafe {
    -+        assert!(!opaque.is_null());
    ++        debug_assert!(!opaque.is_null());
     +        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
     +        state.as_mut().event(event)
     +    }
    @@ rust/hw/char/pl011/src/device.rs (new)
     +) -> *mut DeviceState {
     +    unsafe {
     +        let dev: *mut DeviceState = qdev_new(PL011State::TYPE_INFO.name);
    -+        assert!(!dev.is_null());
    -+        let sysbus: *mut SysBusDevice = dev as *mut SysBusDevice;
    ++        let sysbus: *mut SysBusDevice = dev.cast::<SysBusDevice>();
     +
     +        qdev_prop_set_chr(dev, bindings::TYPE_CHARDEV.as_ptr(), chr);
     +        sysbus_realize_and_unref(sysbus, addr_of!(error_fatal) as *mut *mut Error);
    @@ rust/hw/char/pl011/src/device.rs (new)
     +#[no_mangle]
     +pub unsafe extern "C" fn pl011_init(obj: *mut Object) {
     +    unsafe {
    -+        assert!(!obj.is_null());
    ++        debug_assert!(!obj.is_null());
     +        let mut state = NonNull::new_unchecked(obj.cast::<PL011State>());
     +        state.as_mut().init();
     +    }
    @@ rust/hw/char/pl011/src/device_class.rs (new)
     +
     +use core::ptr::NonNull;
     +
    -+use qemu_api::bindings::*;
    ++use qemu_api::{bindings::*, definitions::ObjectImpl};
     +
    -+use crate::{definitions::VMSTATE_PL011, device::PL011State};
    ++use crate::device::PL011State;
    ++
    ++#[used]
    ++pub static VMSTATE_PL011: VMStateDescription = VMStateDescription {
    ++    name: PL011State::TYPE_INFO.name,
    ++    unmigratable: true,
    ++    ..unsafe { ::core::mem::MaybeUninit::<VMStateDescription>::zeroed().assume_init() }
    ++};
     +
     +qemu_api::declare_properties! {
     +    PL011_PROPERTIES,
    @@ rust/hw/char/pl011/src/device_class.rs (new)
     +    pl011_class_init,
     +    props => PL011_PROPERTIES,
     +    realize_fn => Some(pl011_realize),
    -+    reset_fn => Some(pl011_reset),
    ++    legacy_reset_fn => Some(pl011_reset),
     +    vmsd => VMSTATE_PL011,
     +}
     +
    @@ rust/hw/char/pl011/src/lib.rs (new)
     +//! the [`registers`] module for register types.
     +
     +#![deny(
    -+    unsafe_op_in_unsafe_fn,
     +    rustdoc::broken_intra_doc_links,
     +    rustdoc::redundant_explicit_links,
     +    clippy::correctness,
    @@ rust/hw/char/pl011/src/lib.rs (new)
     +extern crate bilge_impl;
     +extern crate qemu_api;
     +
    -+pub mod definitions;
     +pub mod device;
     +pub mod device_class;
     +pub mod memory_ops;
     +
    ++pub const TYPE_PL011: &::core::ffi::CStr = c"pl011";
    ++
     +/// Offset of each register from the base memory address of the device.
     +///
     +/// # Source
    @@ rust/hw/char/pl011/src/memory_ops.rs (new)
     +    write: Some(pl011_write),
     +    read_with_attrs: None,
     +    write_with_attrs: None,
    -+    endianness: device_endian_DEVICE_NATIVE_ENDIAN,
    ++    endianness: device_endian::DEVICE_NATIVE_ENDIAN,
     +    valid: unsafe { MaybeUninit::<MemoryRegionOps__bindgen_ty_1>::zeroed().assume_init() },
     +    impl_: MemoryRegionOps__bindgen_ty_2 {
     +        min_access_size: 4,

base-commit: 35ba77d2fcd10efd6db8318bbd4d21fa9402143b

Signature · 1 line
γαῖα πυρί μιχθήτω
#8 lore raw

PATCH v11 8/9 rust: add utility procedural macro crate

This commit adds a helper crate library, qemu-api-macros for derive (and other procedural) macros to be used along qemu-api.

It needs to be a separate library because in Rust, procedural macros, or macros that can generate arbitrary code, need to be special separate compilation units.

Only one macro is introduced in this patch, #[derive(Object)]. It generates a constructor to register a QOM TypeInfo on init and it must be used on types that implement qemu_api::definitions::ObjectImpl trait.

---
 MAINTAINERS                                   |  1 +
 rust/meson.build                              |  1 +
 rust/qemu-api-macros/Cargo.lock               | 47 +++++++++++++++++++
 rust/qemu-api-macros/Cargo.toml               | 25 ++++++++++
 rust/qemu-api-macros/README.md                |  1 +
 rust/qemu-api-macros/meson.build              | 25 ++++++++++
 rust/qemu-api-macros/src/lib.rs               | 43 +++++++++++++++++
 rust/qemu-api/meson.build                     |  3 ++
 scripts/archive-source.sh                     |  4 +-
 scripts/make-release                          |  3 +-
 subprojects/.gitignore                        |  4 ++
 .../packagefiles/proc-macro2-1-rs/meson.build | 31 ++++++++++++
 .../packagefiles/quote-1-rs/meson.build       | 29 ++++++++++++
 subprojects/packagefiles/syn-2-rs/meson.build | 40 ++++++++++++++++
 subprojects/proc-macro2-1-rs.wrap             |  7 +++
 subprojects/quote-1-rs.wrap                   |  7 +++
 subprojects/syn-2-rs.wrap                     |  7 +++
 subprojects/unicode-ident-1-rs.wrap           |  7 +++
 subprojects/unicode-ident-1-rs/meson.build    | 20 ++++++++
 19 files changed, 303 insertions(+), 2 deletions(-)
 create mode 100644 rust/qemu-api-macros/Cargo.lock
 create mode 100644 rust/qemu-api-macros/Cargo.toml
 create mode 100644 rust/qemu-api-macros/README.md
 create mode 100644 rust/qemu-api-macros/meson.build
 create mode 100644 rust/qemu-api-macros/src/lib.rs
 create mode 100644 subprojects/packagefiles/proc-macro2-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/quote-1-rs/meson.build
 create mode 100644 subprojects/packagefiles/syn-2-rs/meson.build
 create mode 100644 subprojects/proc-macro2-1-rs.wrap
 create mode 100644 subprojects/quote-1-rs.wrap
 create mode 100644 subprojects/syn-2-rs.wrap
 create mode 100644 subprojects/unicode-ident-1-rs.wrap
 create mode 100644 subprojects/unicode-ident-1-rs/meson.build
MAINTAINERS +1 -0
index bf235430dc..92bf3e3e8f 100644
@@ -3301,6 +3301,7 @@ Rust
 M: Manos Pitsidianakis <[email protected]>
 S: Maintained
 F: rust/qemu-api
+F: rust/qemu-api-macros
 F: rust/rustfmt.toml
 
 SLIRP
rust/meson.build +1 -0
index 4a58d106b1..7a32b1b195 100644
@@ -1 +1,2 @@
+subdir('qemu-api-macros')
 subdir('qemu-api')
rust/qemu-api-macros/Cargo.lock new file +47 -0

47 lines not on this page · raw message

rust/qemu-api-macros/Cargo.toml new file +25 -0
new file mode 100644
index 0000000000..144cc3650f
@@ -0,0 +1,25 @@
+[package]
+name = "qemu_api_macros"
+version = "0.1.0"
+edition = "2021"
+authors = ["Manos Pitsidianakis <[email protected]>"]
+license = "GPL-2.0-or-later"
+readme = "README.md"
+homepage = "https://www.qemu.org"
+description = "Rust bindings for QEMU - Utility macros"
+repository = "https://gitlab.com/qemu-project/qemu/"
+resolver = "2"
+publish = false
+keywords = []
+categories = []
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1"
+quote = "1"
+syn = "2"
+
+# Do not include in any global workspace
+[workspace]
rust/qemu-api-macros/README.md new file +1 -0
new file mode 100644
index 0000000000..f60f54ac4b
@@ -0,0 +1 @@
+# `qemu-api-macros` - Utility macros for defining QEMU devices
rust/qemu-api-macros/meson.build new file +25 -0
new file mode 100644
index 0000000000..48af91ed38
@@ -0,0 +1,25 @@
+add_languages('rust', required: true, native: true)
+
+quote_dep = dependency('quote-1-rs', native: true)
+syn_dep = dependency('syn-2-rs', native: true)
+proc_macro2_dep = dependency('proc-macro2-1-rs', native: true)
+
+_qemu_api_macros_rs = import('rust').proc_macro(
+  'qemu_api_macros',
+  files('src/lib.rs'),
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_args: [
+    '--cfg', 'use_fallback',
+    '--cfg', 'feature="syn-error"',
+    '--cfg', 'feature="proc-macro"',
+  ],
+  dependencies: [
+    proc_macro2_dep,
+    quote_dep,
+    syn_dep,
+  ],
+)
+
+qemu_api_macros = declare_dependency(
+  link_with: _qemu_api_macros_rs,
+)
rust/qemu-api-macros/src/lib.rs new file +43 -0

43 lines not on this page · raw message

rust/qemu-api/meson.build +3 -0
index 439ef73c29..c72d34b607 100644
@@ -14,6 +14,9 @@ _qemu_api_rs = static_library(
     '--cfg', 'MESON',
     # '--cfg', 'feature="allocator"',
   ],
+  dependencies: [
+    qemu_api_macros,
+  ],
 )
 
 qemu_api = declare_dependency(
scripts/archive-source.sh +3 -1
index 65af8063e4..6239cf1815 100755
@@ -26,7 +26,9 @@ sub_file="${sub_tdir}/submodule.tar"
 # independent of what the developer currently has initialized
 # in their checkout, because the build environment is completely
 # different to the host OS.
-subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 berkeley-testfloat-3"
+subprojects="keycodemapdb libvfio-user berkeley-softfloat-3
+  berkeley-testfloat-3 unicode-ident-1.0.12 proc-macro2-1.0.84
+  quote-1.0.36 syn-2.0.66"
 sub_deinit=""
 
 function cleanup() {
scripts/make-release +2 -1
index 6e0433de24..076e588953 100755
@@ -17,7 +17,8 @@ if [ $# -ne 2 ]; then
 fi
 
 # Only include wraps that are invoked with subproject()
-SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3"
+SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3
+  proc-macro2-1.0.84 quote-1.0.36 syn-2.0.66 unicode-ident-1.0.12"
 
 src="$1"
 version="$2"
subprojects/.gitignore +4 -0
index adca0266be..b6888182ca 100644
@@ -6,3 +6,7 @@
 /keycodemapdb
 /libvfio-user
 /slirp
+/proc-macro2-1.0.84
+/quote-1.0.36
+/syn-2.0.66
+/unicode-ident-1.0.12
subprojects/packagefiles/proc-macro2-1-rs/meson.build new file +31 -0
new file mode 100644
index 0000000000..818ec59336
@@ -0,0 +1,31 @@
+project('proc-macro2-1-rs', 'rust',
+  version: '1.0.84',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('unicode-ident-1-rs', required: true)
+
+unicode_ident_dep = dependency('unicode-ident-1-rs', native: true)
+
+_proc_macro2_rs = static_library(
+  'proc_macro2',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'feature="proc-macro"',
+    '--cfg', 'span_locations',
+    '--cfg', 'wrap_proc_macro',
+  ],
+  dependencies: [
+    unicode_ident_dep,
+  ],
+  native: true,
+)
+
+proc_macro2_dep = declare_dependency(
+  link_with: _proc_macro2_rs,
+)
+
+meson.override_dependency('proc-macro2-1-rs', proc_macro2_dep, native: true)
subprojects/packagefiles/quote-1-rs/meson.build new file +29 -0
new file mode 100644
index 0000000000..d36609bd3c
@@ -0,0 +1,29 @@
+project('quote-1-rs', 'rust',
+  version: '1.12.0',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('proc-macro2-1-rs', required: true)
+
+proc_macro2_dep = dependency('proc-macro2-1-rs', native: true)
+
+_quote_rs = static_library(
+  'quote',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'feature="proc-macro"',
+  ],
+  dependencies: [
+    proc_macro2_dep,
+  ],
+  native: true,
+)
+
+quote_dep = declare_dependency(
+  link_with: _quote_rs,
+)
+
+meson.override_dependency('quote-1-rs', quote_dep, native: true)
subprojects/packagefiles/syn-2-rs/meson.build new file +40 -0
new file mode 100644
index 0000000000..a53335f309
@@ -0,0 +1,40 @@
+project('syn-2-rs', 'rust',
+  version: '2.0.66',
+  license: 'MIT OR Apache-2.0',
+  default_options: [])
+
+subproject('proc-macro2-1-rs', required: true)
+subproject('quote-1-rs', required: true)
+subproject('unicode-ident-1-rs', required: true)
+
+proc_macro2_dep = dependency('proc-macro2-1-rs', native: true)
+quote_dep = dependency('quote-1-rs', native: true)
+unicode_ident_dep = dependency('unicode-ident-1-rs', native: true)
+
+_syn_rs = static_library(
+  'syn',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  rust_args: [
+    '--cfg', 'feature="full"',
+    '--cfg', 'feature="derive"',
+    '--cfg', 'feature="parsing"',
+    '--cfg', 'feature="printing"',
+    '--cfg', 'feature="clone-impls"',
+    '--cfg', 'feature="proc-macro"',
+  ],
+  dependencies: [
+    quote_dep,
+    proc_macro2_dep,
+    unicode_ident_dep,
+  ],
+  native: true,
+)
+
+syn_dep = declare_dependency(
+  link_with: _syn_rs,
+)
+
+meson.override_dependency('syn-2-rs', syn_dep, native: true)
subprojects/proc-macro2-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..7053e2c013
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = proc-macro2-1.0.84
+source_url = https://crates.io/api/v1/crates/proc-macro2/1.0.84/download
+source_filename = proc-macro2-1.0.84.0.tar.gz
+source_hash = ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a49d6
+#method = cargo
+patch_directory = proc-macro2-1-rs
subprojects/quote-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..6e7ea69049
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = quote-1.0.36
+source_url = https://crates.io/api/v1/crates/quote/1.0.36/download
+source_filename = quote-1.0.36.0.tar.gz
+source_hash = 0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7
+#method = cargo
+patch_directory = quote-1-rs
subprojects/syn-2-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..13ffdac3c3
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = syn-2.0.66
+source_url = https://crates.io/api/v1/crates/syn/2.0.66/download
+source_filename = syn-2.0.66.0.tar.gz
+source_hash = c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5
+#method = cargo
+patch_directory = syn-2-rs
subprojects/unicode-ident-1-rs.wrap new file +7 -0
new file mode 100644
index 0000000000..4609f96ed9
@@ -0,0 +1,7 @@
+[wrap-file]
+directory = unicode-ident-1.0.12
+source_url = https://crates.io/api/v1/crates/unicode-ident/1.0.12/download
+source_filename = unicode-ident-1.0.12.tar.gz
+source_hash = 3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b
+#method = cargo
+patch_directory = unicode-ident-1-rs
subprojects/unicode-ident-1-rs/meson.build new file +20 -0
new file mode 100644
index 0000000000..54f2376854
@@ -0,0 +1,20 @@
+project('unicode-ident-1-rs', 'rust',
+  version: '1.0.12',
+  license: '(MIT OR Apache-2.0) AND Unicode-DFS-2016',
+  default_options: [])
+
+_unicode_ident_rs = static_library(
+  'unicode_ident',
+  files('src/lib.rs'),
+  gnu_symbol_visibility: 'hidden',
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  dependencies: [],
+  native: true,
+)
+
+unicode_ident_dep = declare_dependency(
+  link_with: _unicode_ident_rs,
+)
+
+meson.override_dependency('unicode-ident-1-rs', unicode_ident_dep, native: true)
Signature · 1 line
γαῖα πυρί μιχθήτω
#7 lore raw

PATCH v11 7/9 rust: add crate to expose bindings and interfaces

In reply to Manos Pitsidianakis

Add rust/qemu-api, which exposes rust-bindgen generated FFI bindings and provides some declaration macros for symbols visible to the rest of QEMU.

---
 MAINTAINERS                       |   6 ++
 rust/meson.build                  |   1 +
 rust/qemu-api/.gitignore          |   2 +
 rust/qemu-api/Cargo.lock          |   7 ++
 rust/qemu-api/Cargo.toml          |  26 +++++
 rust/qemu-api/README.md           |  17 +++
 rust/qemu-api/build.rs            |  14 +++
 rust/qemu-api/meson.build         |  21 ++++
 rust/qemu-api/src/definitions.rs  |  97 +++++++++++++++++
 rust/qemu-api/src/device_class.rs | 128 +++++++++++++++++++++++
 rust/qemu-api/src/lib.rs          | 166 ++++++++++++++++++++++++++++++
 rust/qemu-api/src/tests.rs        |  49 +++++++++
 rust/rustfmt.toml                 |   7 ++
 13 files changed, 541 insertions(+)
 create mode 100644 rust/qemu-api/.gitignore
 create mode 100644 rust/qemu-api/Cargo.lock
 create mode 100644 rust/qemu-api/Cargo.toml
 create mode 100644 rust/qemu-api/README.md
 create mode 100644 rust/qemu-api/build.rs
 create mode 100644 rust/qemu-api/meson.build
 create mode 100644 rust/qemu-api/src/definitions.rs
 create mode 100644 rust/qemu-api/src/device_class.rs
 create mode 100644 rust/qemu-api/src/lib.rs
 create mode 100644 rust/qemu-api/src/tests.rs
 create mode 100644 rust/rustfmt.toml
MAINTAINERS +6 -0
index 82a928265c..bf235430dc 100644
@@ -3297,6 +3297,12 @@ F: hw/core/register.c
 F: include/hw/register.h
 F: include/hw/registerfields.h
 
+Rust
+M: Manos Pitsidianakis <[email protected]>
+S: Maintained
+F: rust/qemu-api
+F: rust/rustfmt.toml
+
 SLIRP
 M: Samuel Thibault <[email protected]>
 S: Maintained
rust/meson.build +1 -0
index e69de29bb2..4a58d106b1 100644
@@ -0,0 +1 @@
+subdir('qemu-api')
rust/qemu-api/.gitignore new file +2 -0
new file mode 100644
index 0000000000..b9e7e004c8
@@ -0,0 +1,2 @@
+# Ignore generated bindings file overrides.
+src/bindings.rs
rust/qemu-api/Cargo.lock new file +7 -0
new file mode 100644
index 0000000000..e9c51a243a
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "qemu_api"
+version = "0.1.0"
rust/qemu-api/Cargo.toml new file +26 -0
new file mode 100644
index 0000000000..3677def3fe
@@ -0,0 +1,26 @@
+[package]
+name = "qemu_api"
+version = "0.1.0"
+edition = "2021"
+authors = ["Manos Pitsidianakis <[email protected]>"]
+license = "GPL-2.0-or-later"
+readme = "README.md"
+homepage = "https://www.qemu.org"
+description = "Rust bindings for QEMU"
+repository = "https://gitlab.com/qemu-project/qemu/"
+resolver = "2"
+publish = false
+keywords = []
+categories = []
+
+[dependencies]
+
+[features]
+default = []
+allocator = []
+
+# Do not include in any global workspace
+[workspace]
+
+[lints.rust]
+unexpected_cfgs = { level = "warn", check-cfg = ['cfg(MESON)', 'cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)'] }
rust/qemu-api/README.md new file +17 -0
new file mode 100644
index 0000000000..7588fa29ef
@@ -0,0 +1,17 @@
+# QEMU bindings and API wrappers
+
+This library exports helper Rust types, Rust macros and C FFI bindings for internal QEMU APIs.
+
+The C bindings can be generated with `bindgen`, using this build target:
+
+```console
+$ ninja bindings.rs
+```
+
+## Generate Rust documentation
+
+To generate docs for this crate, including private items:
+
+```sh
+cargo doc --no-deps --document-private-items
+```
rust/qemu-api/build.rs new file +14 -0
new file mode 100644
index 0000000000..419b154c2d
@@ -0,0 +1,14 @@
+// Copyright 2024, Linaro Limited
+// Author(s): Manos Pitsidianakis <[email protected]>
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+use std::path::Path;
+
+fn main() {
+    if !Path::new("src/bindings.rs").exists() {
+        panic!(
+            "No generated C bindings found! Either build them manually with bindgen or with meson \
+             (`ninja bindings.rs`) and copy them to src/bindings.rs, or build through meson."
+        );
+    }
+}
rust/qemu-api/meson.build new file +21 -0
new file mode 100644
index 0000000000..439ef73c29
@@ -0,0 +1,21 @@
+_qemu_api_rs = static_library(
+  'qemu_api',
+  structured_sources(
+    [
+      'src/lib.rs',
+      'src/definitions.rs',
+      'src/device_class.rs',
+    ],
+    {'.' : bindings_rs},
+  ),
+  override_options: ['rust_std=2021', 'build.rust_std=2021'],
+  rust_abi: 'rust',
+  rust_args: rustc_args + [
+    '--cfg', 'MESON',
+    # '--cfg', 'feature="allocator"',
+  ],
+)
+
+qemu_api = declare_dependency(
+  link_with: _qemu_api_rs,
+)
rust/qemu-api/src/definitions.rs new file +97 -0

97 lines not on this page · raw message

rust/qemu-api/src/device_class.rs new file +128 -0

128 lines not on this page · raw message

rust/qemu-api/src/lib.rs new file +166 -0

166 lines not on this page · raw message

rust/qemu-api/src/tests.rs new file +49 -0

49 lines not on this page · raw message

rust/rustfmt.toml new file +7 -0
new file mode 100644
index 0000000000..ebecb99fe0
@@ -0,0 +1,7 @@
+edition = "2021"
+format_generated_files = false
+format_code_in_doc_comments = true
+format_strings = true
+imports_granularity = "Crate"
+group_imports = "StdExternalCrate"
+wrap_comments = true
Signature · 1 line
γαῖα πυρί μιχθήτω
#2 lore raw

PATCH v11 2/9 build-sys: Add rust feature option

In reply to Manos Pitsidianakis

Add rust feature in meson.build, configure, to prepare for adding Rust code in the followup commits.

---
 MAINTAINERS                   |  5 +++++
 meson.build                   | 22 +++++++++++++++++++++-
 Kconfig                       |  1 +
 Kconfig.host                  |  3 +++
 meson_options.txt             |  3 +++
 rust/Kconfig                  |  0
 scripts/meson-buildoptions.sh |  3 +++
 7 files changed, 36 insertions(+), 1 deletion(-)
 create mode 100644 rust/Kconfig
MAINTAINERS +5 -0
index 4ee2699543..35278c016a 100644
@@ -4195,6 +4195,11 @@ F: docs/sphinx/
 F: docs/_templates/
 F: docs/devel/docs.rst
 
+Rust build system integration
+M: Manos Pitsidianakis <[email protected]>
+S: Maintained
+F: rust/Kconfig
+
 Miscellaneous
 -------------
 Performance Tools and Tests
meson.build +21 -1
index 127b673540..8a106e39c2 100644
@@ -70,6 +70,19 @@ if host_os == 'darwin' and \
   all_languages += ['objc']
   objc = meson.get_compiler('objc')
 endif
+have_rust = false
+if not get_option('rust').disabled() and add_languages('rust', required: get_option('rust'), native: false)
+  rustc = meson.get_compiler('rust')
+  have_rust = true
+  if rustc.version().version_compare('<1.80.0')
+    if get_option('rust').enabled()
+      error('rustc version ' + rustc.version() + ' is unsupported: Please upgrade to at least 1.80.0')
+    else
+      warning('rustc version ' + rustc.version() + ' is unsupported: Disabling Rust compilation. Please upgrade to at least 1.80.0 to use Rust.')
+      have_rust = false
+    endif
+  endif
+endif
 
 dtrace = not_found
 stap = not_found
@@ -2158,6 +2171,7 @@ endif
 
 config_host_data = configuration_data()
 
+config_host_data.set('CONFIG_HAVE_RUST', have_rust)
 audio_drivers_selected = []
 if have_system
   audio_drivers_available = {
@@ -3104,7 +3118,8 @@ host_kconfig = \
   (host_os == 'linux' ? ['CONFIG_LINUX=y'] : []) + \
   (multiprocess_allowed ? ['CONFIG_MULTIPROCESS_ALLOWED=y'] : []) + \
   (vfio_user_server_allowed ? ['CONFIG_VFIO_USER_SERVER_ALLOWED=y'] : []) + \
-  (hv_balloon ? ['CONFIG_HV_BALLOON_POSSIBLE=y'] : [])
+  (hv_balloon ? ['CONFIG_HV_BALLOON_POSSIBLE=y'] : []) + \
+  (have_rust ? ['CONFIG_HAVE_RUST=y'] : [])
 
 ignored = [ 'TARGET_XML_FILES', 'TARGET_ABI_DIR', 'TARGET_ARCH' ]
 
@@ -4315,6 +4330,11 @@ if 'objc' in all_languages
 else
   summary_info += {'Objective-C compiler': false}
 endif
+summary_info += {'Rust support':      have_rust}
+if have_rust
+  summary_info += {'rustc version':      rustc.version()}
+  summary_info += {'rustc':      ' '.join(rustc.cmd_array())}
+endif
 option_cflags = (get_option('debug') ? ['-g'] : [])
 if get_option('optimization') != 'plain'
   option_cflags += ['-O' + get_option('optimization')]
Kconfig +1 -0
index fb6a24a2de..63ca7f46df 100644
@@ -4,3 +4,4 @@ source accel/Kconfig
 source target/Kconfig
 source hw/Kconfig
 source semihosting/Kconfig
+source rust/Kconfig
Kconfig.host +3 -0
index 17f405004b..4ade7899d6 100644
@@ -52,3 +52,6 @@ config VFIO_USER_SERVER_ALLOWED
 
 config HV_BALLOON_POSSIBLE
     bool
+
+config HAVE_RUST
+    bool
meson_options.txt +3 -0
index 783b56bcb9..bf0d5d2d2f 100644
@@ -375,3 +375,6 @@ option('hexagon_idef_parser', type : 'boolean', value : true,
 
 option('x86_version', type : 'combo', choices : ['0', '1', '2', '3', '4'], value: '1',
        description: 'tweak required x86_64 architecture version beyond compiler default')
+
+option('rust', type: 'feature', value: 'auto',
+       description: 'Rust support')
rust/Kconfig new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
scripts/meson-buildoptions.sh +3 -0
index 107a8f69ce..e2a22c0ee7 100644
@@ -172,6 +172,7 @@ meson_options_help() {
   printf "%s\n" '  rbd             Ceph block device driver'
   printf "%s\n" '  rdma            Enable RDMA-based migration'
   printf "%s\n" '  replication     replication support'
+  printf "%s\n" '  rust            Rust support'
   printf "%s\n" '  rutabaga-gfx    rutabaga_gfx support'
   printf "%s\n" '  sdl             SDL user interface'
   printf "%s\n" '  sdl-image       SDL Image support for icons'
@@ -458,6 +459,8 @@ _meson_option_parse() {
     --disable-replication) printf "%s" -Dreplication=disabled ;;
     --enable-rng-none) printf "%s" -Drng_none=true ;;
     --disable-rng-none) printf "%s" -Drng_none=false ;;
+    --enable-rust) printf "%s" -Drust=enabled ;;
+    --disable-rust) printf "%s" -Drust=disabled ;;
     --enable-rutabaga-gfx) printf "%s" -Drutabaga_gfx=enabled ;;
     --disable-rutabaga-gfx) printf "%s" -Drutabaga_gfx=disabled ;;
     --enable-safe-stack) printf "%s" -Dsafe_stack=true ;;
Signature · 1 line
γαῖα πυρί μιχθήτω
#1 lore raw

PATCH v11 1/9 Require meson version 1.5.0

In reply to Manos Pitsidianakis

From: Paolo Bonzini <[email protected]>

This is needed for Rust support.

---
 meson.build                                |   2 +-
 python/scripts/vendor.py                   |   4 ++--
 python/wheels/meson-1.2.3-py3-none-any.whl | Bin 964928 -> 0 bytes
 python/wheels/meson-1.5.0-py3-none-any.whl | Bin 0 -> 959846 bytes
 pythondeps.toml                            |   2 +-
 tests/lcitool/mappings.yml                 |   2 +-
 6 files changed, 5 insertions(+), 5 deletions(-)
 delete mode 100644 python/wheels/meson-1.2.3-py3-none-any.whl
 create mode 100644 python/wheels/meson-1.5.0-py3-none-any.whl
meson.build +1 -1
index 10464466ff..127b673540 100644
@@ -1,4 +1,4 @@
-project('qemu', ['c'], meson_version: '>=1.1.0',
+project('qemu', ['c'], meson_version: '>=1.5.0',
         default_options: ['warning_level=1', 'c_std=gnu11', 'cpp_std=gnu++11', 'b_colorout=auto',
                           'b_staticpic=false', 'stdsplit=false', 'optimization=2', 'b_pie=true'],
         version: files('VERSION'))
python/scripts/vendor.py +2 -2
index 07aff97cca..0405e910b4 100755
@@ -41,8 +41,8 @@ def main() -> int:
     parser.parse_args()
 
     packages = {
-        "meson==1.2.3":
-        "4533a43c34548edd1f63a276a42690fce15bde9409bcf20c4b8fa3d7e4d7cac1",
+        "meson==1.5.0":
+        "52b34f4903b882df52ad0d533146d4b992c018ea77399f825579737672ae7b20",
     }
 
     vendor_dir = Path(__file__, "..", "..", "wheels").resolve()
python/wheels/meson-1.2.3-py3-none-any.whl deleted binary +0 -0
deleted file mode 100644
index a8b84e5f114ad3fbec8ae56008426a90bccfc168..0000000000000000000000000000000000000000
GIT binary patch
python/wheels/meson-1.5.0-py3-none-any.whl new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..c7edeb37ade47cb8b6275cc7dfe6681d957a1dee
GIT binary patch
pythondeps.toml +1 -1
index 0a7f69b196..c03c9df81b 100644
@@ -19,7 +19,7 @@
 
 [meson]
 # The install key should match the version in python/wheels/
-meson = { accepted = ">=1.1.0", installed = "1.2.3", canary = "meson" }
+meson = { accepted = ">=1.5.0", installed = "1.5.0", canary = "meson" }
 pycotap = { accepted = ">=1.1.0", installed = "1.3.1" }
 
 [docs]
tests/lcitool/mappings.yml +1 -1
index 0ab3a89013..9c5ac87c1c 100644
@@ -89,7 +89,7 @@ mappings:
 pypi_mappings:
   # Request more recent version
   meson:
-    default: meson==0.63.2
+    default: meson==1.5.0
 
   # Drop packages that need devel headers
   python3-numpy:
Signature · 1 line
γαῖα πυρί μιχθήτω
#4 lore raw

PATCH v11 4/9 rust: add bindgen step as a meson dependency

In reply to Manos Pitsidianakis

Add bindings_rs target for generating rust bindings to target-independent qemu C APIs.

The bindings need be created before any rust crate that uses them is compiled.

The bindings.rs file will end up in BUILDDIR/bindings.rs and have the same name as a target:

ninja bindings.rs

---
 MAINTAINERS                |  4 ++
 configure                  |  7 ++++
 meson.build                | 68 ++++++++++++++++++++++++++++++
 rust/wrapper.h             | 47 +++++++++++++++++++++
 rust/.gitignore            |  3 ++
 rust/meson.build           |  0
 scripts/rust/rustc_args.py | 84 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 213 insertions(+)
 create mode 100644 rust/wrapper.h
 create mode 100644 rust/.gitignore
 create mode 100644 rust/meson.build
 create mode 100644 scripts/rust/rustc_args.py
MAINTAINERS +4 -0
index 35278c016a..82a928265c 100644
@@ -4198,7 +4198,11 @@ F: docs/devel/docs.rst
 Rust build system integration
 M: Manos Pitsidianakis <[email protected]>
 S: Maintained
+F: scripts/rust/
+F: rust/.gitignore
 F: rust/Kconfig
+F: rust/meson.build
+F: rust/wrapper.h
 
 Miscellaneous
 -------------
configure +7 -0
index 0ccc92074e..4f432e2a70 100755
@@ -2060,3 +2060,10 @@ echo ' "$@"' >>config.status
 chmod +x config.status
 
 rm -r "$TMPDIR1"
+
+if test "$rust" != disabled; then
+  echo '\nINFO: Rust bindings generation with `bindgen` might fail in some cases where'
+  echo 'the detected `libclang` does not match the expected `clang` version/target. In'
+  echo 'this case you must pass the path to `clang` and `libclang` to your build'
+  echo 'command invocation using the environment variables CLANG_PATH and LIBCLANG_PATH'
+fi
meson.build +68 -0

74 lines not on this page · raw message

rust/wrapper.h new file +47 -0

47 lines not on this page · raw message

rust/.gitignore new file +3 -0
new file mode 100644
index 0000000000..1bf71b1f68
@@ -0,0 +1,3 @@
+# Ignore any cargo development build artifacts; for qemu-wide builds, all build
+# artifacts will go to the meson build directory.
+target
rust/meson.build new file +0 -0
new file mode 100644
index 0000000000..e69de29bb2
scripts/rust/rustc_args.py new file +84 -0

84 lines not on this page · raw message

Signature · 1 line
γαῖα πυρί μιχθήτω
#5 lore raw

PATCH v11 5/9 .gitattributes: add Rust diff and merge attributes

In reply to Manos Pitsidianakis

Set rust source code to diff=rust (built-in with new git versions) and merge=binary for Cargo.lock files (they should not be merged but auto-generated by cargo)

---
 .gitattributes | 3 +++
 1 file changed, 3 insertions(+)
.gitattributes +3 -0
index a217cb7bfe..6dc6383d3d 100644
@@ -2,3 +2,6 @@
 *.h.inc         diff=c
 *.m             diff=objc
 *.py            diff=python
+*.rs            diff=rust
+*.rs.inc        diff=rust
+Cargo.lock      diff=toml merge=binary
Signature · 1 line
γαῖα πυρί μιχθήτω
#3 lore raw

PATCH v11 3/9 configure, meson: detect Rust toolchain

In reply to Manos Pitsidianakis

From: Paolo Bonzini <[email protected]>

Include the correct path and arguments to rustc in the native and cross files (native compilation is needed for procedural macros).

Based on the host architecture and OS, the compiler and optionally the argument to --cpu, the Rust target triple can be detected automatically for either a native or a cross compiler.

In general, it is only a matter of translating the architecture and OS, and adding a machine to form the triple, but there are some special cases (e.g. detecting soft vs. hard floating point on ARM) and some inconsistencies.

---
 configure   | 163 +++++++++++++++++++++++++++++++++++++++++++++++++++-
 meson.build |   5 +-
 2 files changed, 164 insertions(+), 4 deletions(-)
configure +161 -2
index aa7aae70fa..0ccc92074e 100755
@@ -207,6 +207,8 @@ for opt do
   ;;
   --objcc=*) objcc="$optarg"
   ;;
+  --rustc=*) RUSTC="$optarg"
+  ;;
   --cpu=*) cpu="$optarg"
   ;;
   --extra-cflags=*)
@@ -252,6 +254,8 @@ python=
 download="enabled"
 skip_meson=no
 use_containers="yes"
+rust="auto"
+rust_target_triple=""
 gdb_bin=$(command -v "gdb-multiarch" || command -v "gdb")
 gdb_arches=""
 
@@ -310,6 +314,7 @@ objcopy="${OBJCOPY-${cross_prefix}objcopy}"
 ld="${LD-${cross_prefix}ld}"
 ranlib="${RANLIB-${cross_prefix}ranlib}"
 nm="${NM-${cross_prefix}nm}"
+readelf="${READELF-${cross_prefix}readelf}"
 strip="${STRIP-${cross_prefix}strip}"
 widl="${WIDL-${cross_prefix}widl}"
 windres="${WINDRES-${cross_prefix}windres}"
@@ -317,6 +322,8 @@ windmc="${WINDMC-${cross_prefix}windmc}"
 pkg_config="${PKG_CONFIG-${cross_prefix}pkg-config}"
 sdl2_config="${SDL2_CONFIG-${cross_prefix}sdl2-config}"
 
+rustc="${RUSTC-rustc}"
+
 check_define() {
 cat > $TMPC <<EOF
 #if !defined($1)
@@ -425,6 +432,7 @@ fi
 # Please keep it sorted and synchronized with meson.build's host_arch.
 host_arch=
 linux_arch=
+raw_cpu=$cpu
 case "$cpu" in
   aarch64)
     host_arch=aarch64
@@ -658,6 +666,8 @@ for opt do
   ;;
   --objcc=*)
   ;;
+  --rustc=*)
+  ;;
   --make=*)
   ;;
   --install=*)
@@ -777,8 +787,14 @@ for opt do
   ;;
   --container-engine=*) container_engine="$optarg"
   ;;
+  --rust-target-triple=*) rust_target_triple="$optarg"
+  ;;
   --gdb=*) gdb_bin="$optarg"
   ;;
+  --enable-rust) rust=enabled
+  ;;
+  --disable-rust) rust=disabled
+  ;;
   # everything else has the same name in configure and meson
   --*) meson_option_parse "$opt" "$optarg"
   ;;
@@ -881,6 +897,7 @@ Advanced options (experts only):
                            at build time [$host_cc]
   --cxx=CXX                use C++ compiler CXX [$cxx]
   --objcc=OBJCC            use Objective-C compiler OBJCC [$objcc]
+  --rustc=RUSTC            use Rust compiler RUSTC [$rustc]
   --extra-cflags=CFLAGS    append extra C compiler flags CFLAGS
   --extra-cxxflags=CXXFLAGS append extra C++ compiler flags CXXFLAGS
   --extra-objcflags=OBJCFLAGS append extra Objective C compiler flags OBJCFLAGS
@@ -891,8 +908,9 @@ Advanced options (experts only):
   --python=PYTHON          use specified python [$python]
   --ninja=NINJA            use specified ninja [$ninja]
   --static                 enable static build [$static]
-  --without-default-features default all --enable-* options to "disabled"
-  --without-default-devices  do not include any device that is not needed to
+  --rust-target-triple=TRIPLE  compilation target for Rust code [autodetect]
+  --without-default-features   default all --enable-* options to "disabled"
+  --without-default-devices    do not include any device that is not needed to
                            start the emulator (only use if you are including
                            desired devices in configs/devices/)
   --with-devices-ARCH=NAME override default configs/devices
@@ -1167,6 +1185,132 @@ EOF
 fi
 
 ##########################################
+# detect rust triple
+
+if test "$rust" != disabled && has "$rustc" && $rustc -vV > "${TMPDIR1}/${TMPB}.out"; then
+  rust_host_triple=$(sed -n 's/^host: //p' "${TMPDIR1}/${TMPB}.out")
+else
+  if test "$rust" = enabled; then
+    error_exit "could not execute rustc binary \"$rustc\""
+  fi
+  rust=disabled
+fi
+if test "$rust" != disabled && test -z "$rust_target_triple"; then
+  # arch and os generally matches between meson and rust
+  rust_arch=$host_arch
+  rust_os=$host_os
+  rust_machine=unknown
+  rust_osvariant=
+
+  # tweak rust_os if needed; also, machine and variant depend on the OS
+  android=no
+  case "$host_os" in
+  darwin)
+    # e.g. aarch64-apple-darwin
+    rust_machine=apple
+    ;;
+
+  linux)
+    # detect android/glibc/musl
+    if check_define __ANDROID__; then
+      rust_osvariant=android
+      android=yes
+    else
+      cat > $TMPC << EOF
+#define _GNU_SOURCE
+#include <features.h>
+#ifndef __USE_GNU
+error using musl
+#endif
+EOF
+      if compile_object; then
+        rust_osvariant=gnu
+      else
+        rust_osvariant=musl
+      fi
+    fi
+
+    case "$host_arch" in
+    arm)
+      # e.g. arm-unknown-linux-gnueabi, arm-unknown-linux-gnueabihf
+      write_c_skeleton
+      compile_object
+      if $READELF -A $TMPO | grep Tag_API_VFP_args: > /dev/null; then
+        rust_osvariant=${rust_osvariant}eabihf
+      else
+        rust_osvariant=${rust_osvariant}eabi
+      fi
+      ;;
+
+    mips64)
+      # e.g. mips64-unknown-linux-gnuabi64
+      rust_osvariant=${rust_osvariant}abi64
+      ;;
+    esac
+    ;;
+
+  netbsd)
+    # e.g. arm-unknown-netbsd-eabihf
+    test "$host_arch" = arm && rust_osvariant=eabihf
+    ;;
+
+  sunos)
+    rust_machine=pc
+    rust_os=solaris
+    ;;
+
+  windows)
+    # e.g. aarch64-pc-windows-gnullvm, x86_64-pc-windows-gnu (MSVC not supported)
+    rust_machine=pc
+    if test "$host_arch" = aarch64; then
+      rust_osvariant=gnullvm
+    else
+      rust_osvariant=gnu
+    fi
+    ;;
+  esac
+
+  # now tweak the architecture part, possibly based on pre-canonicalization --cpu
+  case "$host_arch" in
+  arm)
+    # preserve ISA version (armv7 etc.) from $raw_cpu if passed via --cpu
+    rust_arch=$raw_cpu
+    test "$rust_arch" = arm && test "$rust_os" != linux && rust_arch=armv7
+    ;;
+
+  mips|mips64)
+    # preserve ISA version (mipsisa64r6 etc.) and include endianness
+    rust_arch=${raw_cpu%el}
+    test "$bigendian" = no && rust_arch=${rust_arch}el
+    ;;
+
+  riscv32|riscv64)
+    # e.g. riscv64gc-unknown-linux-gnu, but riscv64-linux-android
+    test "$android" = no && rust_arch=${rust_arch}gc
+    ;;
+
+  sparc64)
+    if test "$rust_os" = solaris; then
+      rust_arch=sparcv9
+      rust_machine=sun
+    fi
+    ;;
+
+  x86_64)
+    # e.g. x86_64-unknown-linux-gnux32
+    test "$raw_cpu" = x32 && rust_osvariant=${rust_osvariant}x32
+    ;;
+  esac
+
+  if test "$android" = yes; then
+    # e.g. aarch64-linux-android
+    rust_target_triple=$rust_arch-$rust_os-$rust_osvariant
+  else
+    rust_target_triple=$rust_arch-$rust_machine-$rust_os${rust_osvariant+-$rust_osvariant}
+  fi
+fi
+
+##########################################
 # functions to probe cross compilers
 
 container="no"
@@ -1628,6 +1772,9 @@ if test "$container" != no; then
     echo "RUNC=$runc" >> $config_host_mak
 fi
 echo "SUBDIRS=$subdirs" >> $config_host_mak
+if test "$rust" != disabled; then
+  echo "RUST_TARGET_TRIPLE=$rust_target_triple" >> $config_host_mak
+fi
 echo "PYTHON=$python" >> $config_host_mak
 echo "MKVENV_ENSUREGROUP=$mkvenv ensuregroup $mkvenv_online_flag" >> $config_host_mak
 echo "GENISOIMAGE=$genisoimage" >> $config_host_mak
@@ -1764,12 +1911,20 @@ if test "$skip_meson" = no; then
   echo "c = [$(meson_quote $cc $CPU_CFLAGS)]" >> $cross
   test -n "$cxx" && echo "cpp = [$(meson_quote $cxx $CPU_CFLAGS)]" >> $cross
   test -n "$objcc" && echo "objc = [$(meson_quote $objcc $CPU_CFLAGS)]" >> $cross
+  if test "$rust" != disabled; then
+    if test "$rust_host_triple" != "$rust_target_triple"; then
+      echo "rust = [$(meson_quote $rustc --target "$rust_target_triple")]" >> $cross
+    else
+      echo "rust = [$(meson_quote $rustc)]" >> $cross
+    fi
+  fi
   echo "ar = [$(meson_quote $ar)]" >> $cross
   echo "dlltool = [$(meson_quote $dlltool)]" >> $cross
   echo "nm = [$(meson_quote $nm)]" >> $cross
   echo "pkgconfig = [$(meson_quote $pkg_config)]" >> $cross
   echo "pkg-config = [$(meson_quote $pkg_config)]" >> $cross
   echo "ranlib = [$(meson_quote $ranlib)]" >> $cross
+  echo "readelf = [$(meson_quote $readelf)]" >> $cross
   if has $sdl2_config; then
     echo "sdl2-config = [$(meson_quote $sdl2_config)]" >> $cross
   fi
@@ -1799,6 +1954,9 @@ if test "$skip_meson" = no; then
     echo "# Automatically generated by configure - do not modify" > $native
     echo "[binaries]" >> $native
     echo "c = [$(meson_quote $host_cc)]" >> $native
+    if test "$rust" != disabled; then
+      echo "rust = [$(meson_quote $rustc)]" >> $cross
+    fi
     mv $native config-meson.native
     meson_option_add --native-file
     meson_option_add config-meson.native
@@ -1817,6 +1975,7 @@ if test "$skip_meson" = no; then
   test "$pie" = no && meson_option_add -Db_pie=false
 
   # QEMU options
+  test "$rust" != "auto" && meson_option_add "-Drust=$rust"
   test "$cfi" != false && meson_option_add "-Dcfi=$cfi" "-Db_lto=$cfi"
   test "$docs" != auto && meson_option_add "-Ddocs=$docs"
   test -n "${LIB_FUZZING_ENGINE+xxx}" && meson_option_add "-Dfuzzing_engine=$LIB_FUZZING_ENGINE"
meson.build +3 -2
index 8a106e39c2..8ddb5fa38d 100644
@@ -4332,8 +4332,9 @@ else
 endif
 summary_info += {'Rust support':      have_rust}
 if have_rust
-  summary_info += {'rustc version':      rustc.version()}
-  summary_info += {'rustc':      ' '.join(rustc.cmd_array())}
+  summary_info += {'rustc version':   rustc.version()}
+  summary_info += {'rustc':           ' '.join(rustc.cmd_array())}
+  summary_info += {'Rust target':     config_host['RUST_TARGET_TRIPLE']}
 endif
 option_cflags = (get_option('debug') ? ['-g'] : [])
 if get_option('optimization') != 'plain'
Signature · 1 line
γαῖα πυρί μιχθήτω
#10 lore raw
In reply to Manos Pitsidianakis
Quoted 11 lines · Manos Pitsidianakis

WARNING: This series contains a patch with blob diffs (update of python wheels) and thus problems may arise with your patch workflow. The revision is available at
https://gitlab.com/epilys/qemu/-/tree/20240814-rust-pl011-v7-v11 for you to fetch. HEAD is 6ec1d4fb8db2a1d7ba94c73e65d9770371b7857d

Hello everyone,

This series adds:

Quoted 7 lines

- build system support for the Rust compiler
- a small Rust library, qemu-api, which includes bindings to QEMU's C interface generated with bindgen, and qemu-api-macros, a procedural macro library.
- a proof of concept ARM PL011 device implementation in Rust, chosen for its low complexity. The device is used in the arm virt machine if qemu is compiled with rust enabled (./configure --enable-rust [...])

Thanks, I think this is good for committing. There are certainly a lot of things that are still a bit rough, but they can be handled separately. In particular the priorities for the build system should be:

- lowering the minimum supported Rust version

- completing support for CI and for clippy

- possibly, figuring out the magic that Linux uses to run doctests, and port it to meson (ideally upstream meson would do that and also support "cargo doc", but a QEMU-specific implementation would do)

As to PL011State, some mostly independent steps could be:

- improve initialization to avoid use of raw pointers. Two different ways could be simply to use MaybeUninit<>, or something more complex like the Linux pinned_init crate

- write bindings to the Chardev API (probably requires basic support for QOM methods first, for which
https://lore.kernel.org/r/all/[email protected]/
has some mostly-developed ideas)

- generalize the extern "C" "thunks" that invoke idiomatic-Rust
implementations via a reusable trait, in particular:
- figuring out the design for the callback design pattern (see for
example https://lpc.events/event/18/contributions/1786/attachments/1431/3226/hrtimer%20Rust%20Abstractions.pdf),
i.e.
- make functions like pl011_realize or pl011_reset generic, so that
other devices can reuse them

- expand #[derive(Object)] into a more complete design that allows overriding QOM methods, for example taking care of defining the class_init methods

I was also wondering if an useful exercise could be to place a level of maturity for each of the files, for example:

A: ready for production use, API supports the full functionality available in C
B: ready for production use, API should be safe (when possible) and stable
C: proof of concept for safe and/or idiomatic Rust code
D: still essentially C code

Paolo