Skip to main content

bdwgc_alloc/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3
4mod error;
5
6use bdwgc_alloc_sys::{
7    GC_SUCCESS, GC_alloc_lock, GC_alloc_unlock, GC_allow_register_threads, GC_free, GC_gcollect,
8    GC_get_stack_base, GC_init, GC_memalign, GC_realloc, GC_register_finalizer,
9    GC_register_my_thread, GC_set_stackbottom, GC_stack_base, GC_unregister_my_thread,
10};
11use core::{
12    alloc::{self, AllocError, GlobalAlloc, Layout},
13    ffi::c_void,
14    marker::PhantomData,
15    ptr::{NonNull, copy_nonoverlapping, null_mut},
16};
17
18// A collector aligns memory blocks to granules of two pointers.
19const GRANULE_SIZE: usize = 2 * size_of::<*const c_void>();
20
21/// An allocator.
22#[derive(Clone, Copy)]
23pub struct Allocator(());
24
25impl Allocator {
26    /// Creates an allocator.
27    ///
28    /// # Safety
29    ///
30    /// The allocator must be used only in a main thread or threads registered
31    /// to a collector, and its memory blocks must not be referenced only from
32    /// memory the collector does not scan, such as memory of other allocators.
33    pub const unsafe fn new() -> Self {
34        Self(())
35    }
36
37    /// Locks a collector.
38    pub fn lock() {
39        unsafe { GC_alloc_lock() }
40    }
41
42    /// Unlocks a collector.
43    pub fn unlock() {
44        unsafe { GC_alloc_unlock() }
45    }
46
47    /// Initializes a collector.
48    ///
49    /// # Safety
50    ///
51    /// This function must be called in a main thread.
52    pub unsafe fn initialize() {
53        unsafe {
54            GC_init();
55            GC_allow_register_threads();
56        }
57    }
58
59    /// Registers a current thread to a collector.
60    ///
61    /// # Safety
62    ///
63    /// A collector must be initialized already, and a pointer into it held by
64    /// the thread must be handed off to another thread before the registration
65    /// is dropped.
66    pub unsafe fn register_current_thread() -> Result<ThreadRegistration, error::Error> {
67        let mut base = GC_stack_base {
68            mem_base: null_mut(),
69        };
70
71        if unsafe { GC_get_stack_base(&mut base) } != GC_SUCCESS {
72            return Err(error::Error::new("failed to get stack base"));
73        } else if unsafe { GC_register_my_thread(&base) } != GC_SUCCESS {
74            return Err(error::Error::new("failed to register a thread for GC"));
75        }
76
77        Ok(ThreadRegistration(PhantomData))
78    }
79
80    /// Sets a bottom of a stack.
81    ///
82    /// You do not have to call this function in most cases.
83    /// A collector detects the bottom on initialization automatically.
84    ///
85    /// # Safety
86    ///
87    /// The bottom address must be valid.
88    pub unsafe fn set_stack_bottom(bottom: *const u8) {
89        unsafe {
90            GC_set_stackbottom(
91                null_mut(),
92                &GC_stack_base {
93                    mem_base: bottom.cast_mut().cast(),
94                },
95            )
96        }
97    }
98
99    /// Runs a garbage collection forcibly.
100    pub fn force_collect() {
101        unsafe { GC_gcollect() }
102    }
103
104    /// Registers a finalizer of an object.
105    ///
106    /// # Safety
107    ///
108    /// The given finalizer must not be null and handle pointers properly.
109    pub unsafe fn register_finalizer(
110        ptr: *const c_void,
111        finalizer: extern "C" fn(*mut c_void, *mut c_void),
112        client_data: *const c_void,
113    ) {
114        unsafe {
115            GC_register_finalizer(
116                ptr.cast_mut(),
117                Some(finalizer),
118                client_data.cast_mut(),
119                null_mut(),
120                null_mut(),
121            )
122        };
123    }
124}
125
126/// A registration of a current thread to a collector.
127///
128/// The thread is removed from a collector when this value is dropped.
129#[must_use]
130pub struct ThreadRegistration(PhantomData<*mut ()>);
131
132impl Drop for ThreadRegistration {
133    fn drop(&mut self) {
134        unsafe { GC_unregister_my_thread() };
135    }
136}
137
138unsafe impl alloc::Allocator for Allocator {
139    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
140        Ok(NonNull::slice_from_raw_parts(
141            if layout.size() == 0 {
142                layout.dangling_ptr()
143            } else {
144                NonNull::new(unsafe { GC_memalign(layout.align(), layout.size()) }.cast())
145                    .ok_or(AllocError)?
146            },
147            layout.size(),
148        ))
149    }
150
151    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
152        if layout.size() != 0 {
153            unsafe { GC_free(ptr.as_ptr().cast()) }
154        }
155    }
156}
157
158unsafe impl GlobalAlloc for Allocator {
159    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
160        (unsafe { GC_memalign(layout.align(), layout.size()) }) as *mut u8
161    }
162
163    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
164        unsafe { GC_free(ptr as *mut c_void) }
165    }
166
167    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 {
168        if layout.align() <= GRANULE_SIZE {
169            return (unsafe { GC_realloc(ptr as *mut c_void, size) }) as *mut u8;
170        }
171
172        let new_ptr =
173            unsafe { self.alloc(Layout::from_size_align_unchecked(size, layout.align())) };
174
175        if !new_ptr.is_null() {
176            unsafe {
177                copy_nonoverlapping(ptr, new_ptr, layout.size().min(size));
178                self.dealloc(ptr, layout);
179            }
180        }
181
182        new_ptr
183    }
184}