xref: /relibc/src/platform/allocator/dragonos_malloc.rs (revision be35961d82cd98f2a2e61c4f1869271b9f4af571)
1 use crate::ALLOCATOR;
2 use core::{
3     alloc::{GlobalAlloc, Layout},
4     ptr::null_mut,
5     sync::atomic::{AtomicUsize, Ordering},
6 };
7 
8 use super::types::*;
9 
10 extern "C" {
11     fn _dragonos_free(ptr: *mut c_void) -> *mut c_void;
12     fn _dragonos_malloc(size: usize) -> *mut c_void;
13 }
14 
15 pub struct Allocator {
16     mstate: AtomicUsize,
17 }
18 
19 pub const NEWALLOCATOR: Allocator = Allocator {
20     mstate: AtomicUsize::new(0),
21 };
22 
23 impl Allocator {
24     pub fn set_book_keeper(&self, mstate: usize) {
25         self.mstate.store(mstate, Ordering::Relaxed);
26     }
27     pub fn get_book_keeper(&self) -> usize {
28         self.mstate.load(Ordering::Relaxed)
29     }
30 }
31 
32 unsafe impl<'a> GlobalAlloc for Allocator {
33     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
34         alloc(layout.size()) as *mut u8
35         //alloc_align(layout.size(), layout.align()) as *mut u8
36     }
37 
38     unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
39         free(ptr as *mut c_void);
40     }
41 }
42 
43 pub unsafe fn alloc(size: usize) -> *mut c_void {
44     // println!("alloc size: {}", size);
45     _dragonos_malloc(size)
46     //mspace_malloc(ALLOCATOR.get_book_keeper(), size)
47 }
48 
49 pub unsafe fn alloc_align(size: usize, alignment: usize) -> *mut c_void {
50     // println!("alloc align size: {}, alignment: {}", size, alignment);
51     // TODO: 实现对齐分配
52     _dragonos_malloc(size)
53     //mspace_memalign(ALLOCATOR.get_book_keeper(), alignment, size)
54 }
55 
56 pub unsafe fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
57     todo!()
58 }
59 
60 pub unsafe fn free(ptr: *mut c_void) {
61     // println!("free ptr: {:#018x}", ptr as usize);
62     _dragonos_free(ptr);
63     //mspace_free(ALLOCATOR.get_book_keeper(), ptr)
64 }
65 
66 #[cfg(target_os = "dragonos")]
67 pub fn new_mspace() -> usize {
68     // dbg!("new_mspace");
69     1
70 }
71