xref: /openbmc/qemu/rust/qemu-api/src/lib.rs (revision 907d2bbb)
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 unsafe impl Sync for bindings::VMStateField {}
30 unsafe impl Sync for bindings::VMStateInfo {}
31 
32 pub mod c_str;
33 pub mod definitions;
34 pub mod device_class;
35 pub mod vmstate;
36 pub mod zeroable;
37 
38 use std::{
39     alloc::{GlobalAlloc, Layout},
40     os::raw::c_void,
41 };
42 
43 #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
44 extern "C" {
45     fn g_aligned_alloc0(
46         n_blocks: bindings::gsize,
47         n_block_bytes: bindings::gsize,
48         alignment: bindings::gsize,
49     ) -> bindings::gpointer;
50     fn g_aligned_free(mem: bindings::gpointer);
51 }
52 
53 #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
54 extern "C" {
55     fn qemu_memalign(alignment: usize, size: usize) -> *mut c_void;
56     fn qemu_vfree(ptr: *mut c_void);
57 }
58 
59 extern "C" {
60     fn g_malloc0(n_bytes: bindings::gsize) -> bindings::gpointer;
61     fn g_free(mem: bindings::gpointer);
62 }
63 
64 /// An allocator that uses the same allocator as QEMU in C.
65 ///
66 /// It is enabled by default with the `allocator` feature.
67 ///
68 /// To set it up manually as a global allocator in your crate:
69 ///
70 /// ```ignore
71 /// use qemu_api::QemuAllocator;
72 ///
73 /// #[global_allocator]
74 /// static GLOBAL: QemuAllocator = QemuAllocator::new();
75 /// ```
76 #[derive(Clone, Copy, Debug)]
77 #[repr(C)]
78 pub struct QemuAllocator {
79     _unused: [u8; 0],
80 }
81 
82 #[cfg_attr(all(feature = "allocator", not(test)), global_allocator)]
83 pub static GLOBAL: QemuAllocator = QemuAllocator::new();
84 
85 impl QemuAllocator {
86     // From the glibc documentation, on GNU systems, malloc guarantees 16-byte
87     // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See
88     // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html.
89     // This alignment guarantee also applies to Windows and Android. On Darwin
90     // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems.
91     #[cfg(all(
92         target_pointer_width = "32",
93         not(any(target_os = "macos", target_os = "openbsd"))
94     ))]
95     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(8);
96     #[cfg(all(
97         target_pointer_width = "64",
98         not(any(target_os = "macos", target_os = "openbsd"))
99     ))]
100     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(16);
101     #[cfg(all(
102         any(target_pointer_width = "32", target_pointer_width = "64"),
103         any(target_os = "macos", target_os = "openbsd")
104     ))]
105     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = Some(16);
106     #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
107     pub const DEFAULT_ALIGNMENT_BYTES: Option<usize> = None;
108 
109     pub const fn new() -> Self {
110         Self { _unused: [] }
111     }
112 }
113 
114 impl Default for QemuAllocator {
115     fn default() -> Self {
116         Self::new()
117     }
118 }
119 
120 // Sanity check.
121 const _: [(); 8] = [(); ::core::mem::size_of::<*mut c_void>()];
122 
123 unsafe impl GlobalAlloc for QemuAllocator {
124     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
125         if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
126         {
127             // SAFETY: g_malloc0() is safe to call.
128             unsafe { g_malloc0(layout.size().try_into().unwrap()).cast::<u8>() }
129         } else {
130             #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
131             {
132                 // SAFETY: g_aligned_alloc0() is safe to call.
133                 unsafe {
134                     g_aligned_alloc0(
135                         layout.size().try_into().unwrap(),
136                         1,
137                         layout.align().try_into().unwrap(),
138                     )
139                     .cast::<u8>()
140                 }
141             }
142             #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
143             {
144                 // SAFETY: qemu_memalign() is safe to call.
145                 unsafe { qemu_memalign(layout.align(), layout.size()).cast::<u8>() }
146             }
147         }
148     }
149 
150     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
151         if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0))
152         {
153             // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid
154             // glib-allocated pointer, so `g_free`ing is safe.
155             unsafe { g_free(ptr.cast::<_>()) }
156         } else {
157             #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)]
158             {
159                 // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid aligned
160                 // glib-allocated pointer, so `g_aligned_free`ing is safe.
161                 unsafe { g_aligned_free(ptr.cast::<_>()) }
162             }
163             #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))]
164             {
165                 // SAFETY: `ptr` must have been allocated by Self::alloc thus a valid aligned
166                 // glib-allocated pointer, so `qemu_vfree`ing is safe.
167                 unsafe { qemu_vfree(ptr.cast::<_>()) }
168             }
169         }
170     }
171 }
172