Skip to main content

xwrust/xwmm/
allocator.rs

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