xref: /openbmc/qemu/rust/qemu-api/src/lib.rs (revision 2e1cacfb)
1 // Copyright 2024, Linaro Limited
2 // Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 
5 #![cfg_attr(not(MESON), doc = include_str!("../README.md"))]
6 
7 #[allow(
8     dead_code,
9     improper_ctypes_definitions,
10     improper_ctypes,
11     non_camel_case_types,
12     non_snake_case,
13     non_upper_case_globals,
14     unsafe_op_in_unsafe_fn,
15     clippy::missing_const_for_fn,
16     clippy::too_many_arguments,
17     clippy::approx_constant,
18     clippy::use_self,
19     clippy::useless_transmute,
20     clippy::missing_safety_doc,
21 )]
22 #[rustfmt::skip]
23 pub mod bindings;
24 
25 unsafe impl Send for bindings::Property {}
26 unsafe impl Sync for bindings::Property {}
27 unsafe impl Sync for bindings::TypeInfo {}
28 unsafe impl Sync for bindings::VMStateDescription {}
29 
30 pub mod definitions;
31 pub mod device_class;
32 
33 #[cfg(test)]
34 mod tests;
35 
36 use std::alloc::{GlobalAlloc, Layout};
37 
38 #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
39 extern "C" {
40     fn g_aligned_alloc0(
41         n_blocks: bindings::gsize,
42         n_block_bytes: bindings::gsize,
43         alignment: bindings::gsize,
44     ) -> bindings::gpointer;
45     fn g_aligned_free(mem: bindings::gpointer);
46 }
47 
48 #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
49 extern "C" {
50     fn qemu_memalign(alignment: usize, size: usize) -> *mut ::core::ffi::c_void;
51     fn qemu_vfree(ptr: *mut ::core::ffi::c_void);
52 }
53 
54 extern "C" {
55     fn g_malloc0(n_bytes: bindings::gsize) -> bindings::gpointer;
56     fn g_free(mem: bindings::gpointer);
57 }
58 
59 /// An allocator that uses the same allocator as QEMU in C.
60 ///
61 /// It is enabled by default with the `allocator` feature.
62 ///
63 /// To set it up manually as a global allocator in your crate:
64 ///
65 /// ```ignore
66 /// use qemu_api::QemuAllocator;
67 ///
68 /// #[global_allocator]
69 /// static GLOBAL: QemuAllocator = QemuAllocator::new();
70 /// ```
71 #[derive(Clone, Copy, Debug)]
72 #[repr(C)]
73 pub struct QemuAllocator {
74     _unused: [u8; 0],
75 }
76 
77 #[cfg_attr(all(feature = "allocator", not(test)), global_allocator)]
78 pub static GLOBAL: QemuAllocator = QemuAllocator::new();
79 
80 impl QemuAllocator {
81     // From the glibc documentation, on GNU systems, malloc guarantees 16-byte
82     // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See
83     // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html.
84     // This alignment guarantee also applies to Windows and Android. On Darwin
85     // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems.
86     #[cfg(all(
87         target_pointer_width = "32",
88         not(any(target_os = "macos", target_os = "openbsd"))
89     ))]
90     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(8);
91     #[cfg(all(
92         target_pointer_width = "64",
93         not(any(target_os = "macos", target_os = "openbsd"))
94     ))]
95     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(16);
96     #[cfg(all(
97         any(target_pointer_width = "32", target_pointer_width = "64"),
98         any(target_os = "macos", target_os = "openbsd")
99     ))]
100     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(16);
101     #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
102     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = None;
103 
104     pub const fn new() -> Self {
105         Self { _unused: [] }
106     }
107 }
108 
109 impl Default for QemuAllocator {
110     fn default() -> Self {
111         Self::new()
112     }
113 }
114 
115 // Sanity check.
116 const _: [(); 8] = [(); ::core::mem::size_of::<*mut ::core::ffi::c_void>()];
117 
118 unsafe impl GlobalAlloc for QemuAllocator {
119     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
120         if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
121         {
122             // SAFETY: g_malloc0() is safe to call.
123             unsafe { g_malloc0(layout.size().try_into().unwrap()).cast::<u8>() }
124         } else {
125             #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
126             {
127                 // SAFETY: g_aligned_alloc0() is safe to call.
128                 unsafe {
129                     g_aligned_alloc0(
130                         layout.size().try_into().unwrap(),
131                         1,
132                         layout.align().try_into().unwrap(),
133                     )
134                     .cast::<u8>()
135                 }
136             }
137             #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
138             {
139                 // SAFETY: qemu_memalign() is safe to call.
140                 unsafe { qemu_memalign(layout.align(), layout.size()).cast::<u8>() }
141             }
142         }
143     }
144 
145     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
146         if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
147         {
148             // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid
149             // glib-allocated pointer, so `g_free`ing is safe.
150             unsafe { g_free(ptr.cast::<_>()) }
151         } else {
152             #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
153             {
154                 // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid aligned
155                 // glib-allocated pointer, so `g_aligned_free`ing is safe.
156                 unsafe { g_aligned_free(ptr.cast::<_>()) }
157             }
158             #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
159             {
160                 // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid aligned
161                 // glib-allocated pointer, so `qemu_vfree`ing is safe.
162                 unsafe { qemu_vfree(ptr.cast::<_>()) }
163             }
164         }
165     }
166 }
167