Skip to main content

MatiOS_SDK/
allocator.rs

1#![no_std]
2#![feature(allocator_api)]
3
4use core::alloc::{GlobalAlloc, Layout};
5use core::arch::asm;
6use core::cell::UnsafeCell;
7use core::ptr::{null_mut, NonNull};
8use core::mem::{size_of, align_of};
9
10/// Wewnętrzny stan alokatora.
11struct AllocState {
12    callback: extern "win64" fn(size:u64, align:u64)->u64
13}
14
15/// Prosty linked-list allocator.
16pub struct LinkedListAlloc {
17    state: UnsafeCell<AllocState>,
18}
19
20// Safety: brak synchronizacji; jeśli używasz wielowątkowości, dodaj własną blokadę.
21unsafe impl Sync for LinkedListAlloc {}
22
23impl LinkedListAlloc {
24    pub const fn new() -> Self {
25        extern "win64" fn defaultAlloc(size:u64, align:u64)->u64 {
26            return 0
27        }
28        Self {
29            state: UnsafeCell::new(AllocState {
30                callback:defaultAlloc
31            }),
32        }
33    }
34
35    /// Inicjalizuje stertę dla alokatora.
36    /// ptr - początek regionu pamięci
37    /// size - rozmiar regionu
38    pub unsafe fn init(&self, callback: extern "win64" fn(size:u64, align:u64)->u64) {
39        let state = &mut *self.state.get();
40        state.callback=callback;
41    }
42
43    /// Alokuje blok dla danego Layout.
44    unsafe fn alloc_impl(&self, layout: Layout) -> *mut u8 {
45        let state = &mut *self.state.get();
46        return (state.callback)(layout.size() as u64, layout.align() as u64) as *mut u8;
47
48    }
49
50    /// Zwalnia blok o podanym Layout.
51    unsafe fn dealloc_impl(&self, ptr: *mut u8, layout: Layout) {
52        return;
53       
54    }
55}
56
57
58unsafe impl GlobalAlloc for LinkedListAlloc {
59    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
60        self.alloc_impl(layout)
61    }
62
63    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
64        self.dealloc_impl(ptr, layout)
65    }
66    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
67        let page = self.alloc(layout);
68        for i in 0..layout.size() {
69            *(page.offset(i as isize)) = 0;
70        }
71        return page;
72    }
73
74    unsafe fn realloc(&self, ptr: *mut u8, _layout: Layout, _new_size: usize) -> *mut u8 {
75        return ptr;
76    }
77}
78
79
80// #[global_allocator]
81// pub static ALLOC: LinkedListAlloc = LinkedListAlloc::new();
82
83
84