xref: /relibc/src/platform/allocator/dragonos_malloc.rs (revision d1bdffaaa6f4737e8899008ae7ca1b1bbed0edb5)
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 fn align_up(addr: usize, align: usize) -> usize {
50     (addr + align - 1) & !(align - 1)
51 }
52 pub unsafe fn alloc_align(mut size: usize, alignment: usize) -> *mut c_void {
53     // println!("alloc align size: {}, alignment: {}", size, alignment);
54     size = align_up(size, alignment);
55 
56     // TODO: 实现对齐分配
57     _dragonos_malloc(size)
58     //mspace_memalign(ALLOCATOR.get_book_keeper(), alignment, size)
59 }
60 
61 pub unsafe fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
62     todo!()
63 }
64 
65 pub unsafe fn free(ptr: *mut c_void) {
66     // println!("free ptr: {:#018x}", ptr as usize);
67     _dragonos_free(ptr);
68     //mspace_free(ALLOCATOR.get_book_keeper(), ptr)
69 }
70 
71 #[cfg(target_os = "dragonos")]
72 pub fn new_mspace() -> usize {
73     // dbg!("new_mspace");
74     1
75 }
76