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