Debian Codegraph @

src/allocator.rs

raw symbols SCIP
1 //! # allocator infrastructure
2 //!
3 //! The public interface allows setting a custom allocator, but we need to configure a default
4 //! allocator if the user did not configure one. We have two choices, configured by feature flags:
5 //!
6 //! - `"rust-allocator"` uses the rust global allocator
7 //! - `"c-allocator"` uses an allocator based on `malloc` and `free`
8 //!
9 //! When both configured, `"rust-allocator"` is preferred.
10 //!
11 //! The interface for the allocator is not a great fit for rust. In particular, rust always needs
12 //! the layout of an allocation to deallocate it, and C interfaces don't usually provide this
13 //! information. Luckily in the library we know in all cases how big the allocation was at the
14 //! point where we deallocate it.
15
16 #[cfg(feature = "rust-allocator")]
17 extern crate alloc;
18
19 use core::ffi::{c_int, c_void};
20
21 use crate::bzlib::{BzStream, StreamState};
22
23 type AllocFunc = unsafe extern "C" fn(*mut c_void, c_int, c_int) -> *mut c_void;
24 type FreeFunc = unsafe extern "C" fn(*mut c_void, *mut c_void) -> ();
25
26 pub(crate) enum Allocator {
27 #[cfg(feature = "rust-allocator")]
28 Rust,
29 #[cfg(feature = "c-allocator")]
30 C,
31 Custom {
32 allocate: AllocFunc,
33 deallocate: FreeFunc,
34 opaque: *mut c_void,
35 },
36 }
37
38 impl Allocator {
39 #[allow(unreachable_code)]
40 pub(crate) const DEFAULT: Option<Self> = 'blk: {
41 #[cfg(feature = "rust-allocator")]
42 break 'blk Some(Self::Rust);
43
44 #[cfg(feature = "c-allocator")]
45 break 'blk Some(Self::C);
46
47 None
48 };
49
50 #[allow(unreachable_code)]
51 pub(crate) fn default_function_pointers() -> Option<(AllocFunc, FreeFunc)> {
52 #[cfg(feature = "rust-allocator")]
53 return Some(rust_allocator::ALLOCATOR);
54
55 #[cfg(feature = "c-allocator")]
56 return Some(c_allocator::ALLOCATOR);
57
58 None
59 }
60
61 /// # Safety
62 ///
63 /// - `strm.bzalloc` and `strm.opaque` must form a valid allocator, meaning `strm.bzalloc` returns either
64 /// * a `NULL` pointer
65 /// * a valid pointer to an allocation of `len * size_of::<T>()` bytes aligned to at least `align_of::<usize>()`
66 /// - `strm.bzfree` frees memory allocated by `strm.bzalloc`
67 pub(crate) unsafe fn from_bz_stream<S: StreamState>(strm: &BzStream<S>) -> Option<Self> {
68 let bzalloc = strm.bzalloc?;
69 let bzfree = strm.bzfree?;
70
71 #[cfg(feature = "rust-allocator")]
72 if (bzalloc, bzfree) == rust_allocator::ALLOCATOR {
73 return Some(Self::Rust);
74 }
75
76 #[cfg(feature = "c-allocator")]
77 if (bzalloc, bzfree) == c_allocator::ALLOCATOR {
78 return Some(Self::C);
79 }
80
81 Some(Self::custom(bzalloc, bzfree, strm.opaque))
82 }
83
84 /// # Safety
85 ///
86 /// - `allocate` and `opaque` must form a valid allocator, meaning `allocate` returns either
87 /// * a `NULL` pointer
88 /// * a valid pointer to an allocation of `len * size_of::<T>()` bytes aligned to at least `align_of::<usize>()`
89 /// - `deallocate` frees memory allocated by `allocate`
90 pub(crate) fn custom(allocate: AllocFunc, deallocate: FreeFunc, opaque: *mut c_void) -> Self {
91 Self::Custom {
92 allocate,
93 deallocate,
94 opaque,
95 }
96 }
97 }
98
99 #[cfg(feature = "c-allocator")]
100 pub(crate) mod c_allocator {
101 use super::*;
102
103 // make sure that the only way these function pointers leave this module is via this constant
104 // that way the function pointer address is a reliable way to know that the default C allocator
105 // is used.
106 pub(crate) static ALLOCATOR: (AllocFunc, FreeFunc) = (self::allocate, self::deallocate);
107
108 unsafe extern "C" fn allocate(_opaque: *mut c_void, count: c_int, size: c_int) -> *mut c_void {
109 // NOTE: allocations bigger than isize::MAX are UB in LLVM.
110 let (Ok(count), Ok(size)) = (isize::try_from(count), isize::try_from(size)) else {
111 return core::ptr::null_mut();
112 };
113
114 let Some(len) = count.checked_mul(size) else {
115 return core::ptr::null_mut();
116 };
117
118 let Ok(len) = usize::try_from(len) else {
119 return core::ptr::null_mut();
120 };
121
122 unsafe { libc::malloc(len) }
123 }
124
125 unsafe extern "C" fn deallocate(_opaque: *mut c_void, ptr: *mut c_void) {
126 if !ptr.is_null() {
127 unsafe {
128 libc::free(ptr);
129 }
130 }
131 }
132 }
133
134 #[cfg(feature = "rust-allocator")]
135 mod rust_allocator {
136 use super::*;
137
138 // make sure that the only way these function pointers leave this module is via this constant
139 // that way the function pointer address is a reliable way to know that the default C allocator
140 // is used.
141 pub(crate) static ALLOCATOR: (AllocFunc, FreeFunc) = (self::allocate, self::deallocate);
142
143 unsafe extern "C" fn allocate(
144 _opaque: *mut c_void,
145 _count: c_int,
146 _size: c_int,
147 ) -> *mut c_void {
148 unreachable!("the default rust allocation function should never be called directly");
149 }
150
151 unsafe extern "C" fn deallocate(_opaque: *mut c_void, _ptr: *mut c_void) {
152 unreachable!("the default rust deallocation function should never be called directly");
153 }
154 }
155
156 impl Allocator {
157 /// Allocates `count` contiguous values of type `T`, and zeros out all elements.
158 pub(crate) fn allocate_zeroed<T>(&self, count: usize) -> Option<*mut T> {
159 const {
160 assert!(size_of::<T>() != 0);
161 }
162 assert_ne!(count, 0);
163
164 match self {
165 #[cfg(feature = "rust-allocator")]
166 Allocator::Rust => {
167 let layout = core::alloc::Layout::array::<T>(count).unwrap();
168 let ptr = unsafe { alloc::alloc::alloc_zeroed(layout) };
169 (!ptr.is_null()).then_some(ptr.cast())
170 }
171 #[cfg(feature = "c-allocator")]
172 Allocator::C => {
173 let ptr = unsafe { libc::calloc(count, core::mem::size_of::<T>()) };
174 (!ptr.is_null()).then_some(ptr.cast())
175 }
176 Allocator::Custom {
177 allocate, opaque, ..
178 } => unsafe {
179 let ptr = (allocate)(*opaque, count as i32, core::mem::size_of::<T>() as i32);
180 let ptr = ptr.cast::<T>();
181
182 if ptr.is_null() {
183 return None;
184 }
185
186 core::ptr::write_bytes(ptr, 0, count);
187
188 Some(ptr)
189 },
190 }
191 }
192
193 pub(crate) unsafe fn deallocate<T>(&self, ptr: *mut T, count: usize) {
194 if ptr.is_null() || count == 0 {
195 return;
196 }
197
198 match self {
199 #[cfg(feature = "rust-allocator")]
200 Allocator::Rust => {
201 let layout = core::alloc::Layout::array::<T>(count).unwrap();
202 unsafe { alloc::alloc::dealloc(ptr.cast(), layout) }
203 }
204 #[cfg(feature = "c-allocator")]
205 Allocator::C => {
206 unsafe { libc::free(ptr.cast()) };
207 }
208 Allocator::Custom {
209 deallocate, opaque, ..
210 } => {
211 unsafe { deallocate(*opaque, ptr.cast()) };
212 }
213 }
214 }
215 }