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