Skip to main content

xwrust/xwmm/
allocator.rs

1//! XWOS RUST:全局内存分配器
2//! ========
3//!
4//! Rust的 `#![no_std]` 环境要求用户定义 [`global_allocator`] ,作为动态内存管理的实现。
5//!
6//!
7//! # 允许动态内存的情况
8//!
9//! 若用户需要使用基于动态内存的特性,例如 [`Box<T>`] 和 [`Arc<T>`] ,
10//! 需要在应用代码中定义 `GLOBAL_ALLOCATOR` 并赋值为 [`XwrustAllocator`] 。
11//!
12//! ```rust
13//! #![no_std]
14//! use xwrust::xwmm::allocator::XwrustAllocator;
15//!
16//! #[global_allocator]
17//! pub static GLOBAL_ALLOCATOR: XwrustAllocator = XwrustAllocator;
18//!
19//! #[no_mangle]
20//! pub unsafe extern "C" fn xwrust_main() {
21//!     // 用户代码
22//! }
23//! ```
24//!
25//!
26//! # 禁止动态内存的情况
27//!
28//! 若用户禁止在代码中使用动态内存,只使用静态内存,
29//! 需要在应用代码中定义 `GLOBAL_ALLOCATOR` 并赋值为 [`DummyAllocator`] 。
30//!
31//! ```rust
32//! use xwrust::xwmm::allocator::DummyAllocator;
33//!
34//! #[global_allocator]
35//! pub static GLOBAL_ALLOCATOR: DummyAllocator = DummyAllocator;
36//!
37//! #[no_mangle]
38//! pub unsafe extern "C" fn xwrust_main() {
39//!     // 用户代码
40//! }
41//! ```
42//!
43//! 在禁止使用动态内存管理的场合下,下列模块不可以使用:
44//!
45//! + [`Box<T>`]
46//! + [`Arc<T>`]
47//! + [动态线程]
48//! + [Xwmq]
49//!
50//!
51//! [`global_allocator`]: <https://doc.rust-lang.org/core/prelude/v1/attr.global_allocator.html>
52//! [`Box<T>`]: <https://doc.rust-lang.org/alloc/boxed/struct.Box.html>
53//! [`Arc<T>`]: <https://doc.rust-lang.org/alloc/sync/struct.Arc.html>
54//! [动态线程]: crate::xwos::thd
55//! [Xwmq]: crate::xwmd::xwmq
56
57extern crate core;
58use core::ffi::*;
59use core::ptr;
60use core::alloc::{GlobalAlloc, Layout};
61
62extern "C" {
63    fn xwrustffi_allocator_alloc(alignment: usize, size: usize) -> *mut c_void;
64    fn xwrustffi_allocator_free(mem: *mut c_void);
65}
66
67/// 内存分配器
68pub struct XwrustAllocator;
69
70unsafe impl GlobalAlloc for XwrustAllocator {
71    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
72        xwrustffi_allocator_alloc(layout.align(), layout.size()) as *mut _
73    }
74
75    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
76        xwrustffi_allocator_free(ptr as *mut _);
77    }
78}
79
80/// 虚假的内存分配器
81pub struct DummyAllocator;
82
83unsafe impl GlobalAlloc for DummyAllocator {
84    #[allow(unreachable_code)]
85    unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
86        loop {
87        }
88        ptr::null_mut()
89    }
90
91    unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
92        loop {
93        }
94    }
95}