1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use crate::diag::abort;
use crate::result::*;
use crate::util::PointerAndSize;
use crate::sync;
use core::ptr;

extern crate alloc;
use alloc::alloc::GlobalAlloc;
pub use alloc::alloc::Layout;

pub const PAGE_ALIGNMENT: usize = 0x1000;

pub mod rc;

// TODO: be able to change the global allocator?

pub trait Allocator {
    fn allocate(&mut self, layout: Layout) -> Result<*mut u8>;
    fn release(&mut self, addr: *mut u8, layout: Layout);

    fn new<T>(&mut self) -> Result<*mut T> {
        let layout = Layout::new::<T>();
        self.allocate(layout).map(|ptr| ptr as *mut T)
    }

    fn delete<T>(&mut self, t: *mut T) {
        let layout = Layout::new::<T>();
        self.release(t as *mut u8, layout);
    }
}

extern crate linked_list_allocator;
use linked_list_allocator::Heap as LinkedListAllocator;

impl Allocator for LinkedListAllocator {
    fn allocate(&mut self, layout: Layout) -> Result<*mut u8> {
        match self.allocate_first_fit(layout) {
            Ok(non_null_addr) => Ok(non_null_addr.as_ptr()),
            Err(_) => rc::ResultOutOfMemory::make_err()
        }
    }

    fn release(&mut self, addr: *mut u8, layout: Layout) {
        if !addr.is_null() {
            unsafe {
                self.deallocate(ptr::NonNull::new_unchecked(addr), layout);
            }
        }
    }
}

unsafe impl<A: Allocator> GlobalAlloc for sync::Locked<A> {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.get().allocate(layout).unwrap()
    }

    unsafe fn dealloc(&self, addr: *mut u8, layout: Layout) {
        self.get().release(addr, layout);
    }
}

#[global_allocator]
static mut G_ALLOCATOR_HOLDER: sync::Locked<LinkedListAllocator> = sync::Locked::new(false, LinkedListAllocator::empty());
static mut G_ALLOCATOR_ENABLED: bool = false;

pub fn initialize(heap: PointerAndSize) {
    unsafe {
        G_ALLOCATOR_HOLDER.get().init(heap.address as usize, heap.size);
        G_ALLOCATOR_ENABLED = true;
    }
}

pub(crate) fn set_enabled(enabled: bool) {
    unsafe {
        G_ALLOCATOR_ENABLED = enabled;
    }
}

pub fn is_enabled() -> bool {
    unsafe {
        G_ALLOCATOR_ENABLED
    }
}

pub fn allocate(align: usize, size: usize) -> Result<*mut u8> {
    unsafe {
        let layout = Layout::from_size_align_unchecked(size, align);
        G_ALLOCATOR_HOLDER.get().allocate(layout)
    }
}

pub fn release(addr: *mut u8, align: usize, size: usize) {
    unsafe {
        let layout = Layout::from_size_align_unchecked(size, align);
        G_ALLOCATOR_HOLDER.get().release(addr, layout);
    }
}

pub fn new<T>() -> Result<*mut T> {
    unsafe {
        G_ALLOCATOR_HOLDER.get().new::<T>()
    }
}

pub fn delete<T>(t: *mut T) {
    unsafe {
        G_ALLOCATOR_HOLDER.get().delete(t);
    }
}

pub struct Buffer<T> {
    pub ptr: *mut T,
    pub layout: Layout
}

impl<T> Buffer<T> {
    pub const fn empty() -> Self {
        Self {
            ptr: ptr::null_mut(),
            layout: Layout::new::<u8>() // Dummy value
        }
    }

    pub fn is_valid(&self) -> bool {
        !self.ptr.is_null()
    }

    pub fn new(align: usize, size: usize) -> Result<Self> {
        let ptr = allocate(align, size)? as *mut T;
        Ok(Self {
            ptr,
            layout: unsafe {
                Layout::from_size_align_unchecked(size, align)
            }
        })
    }

    pub fn new_alloc<A: Allocator>(align: usize, size: usize, allocator: &mut A) -> Result<Self> {
        let layout = unsafe {
            Layout::from_size_align_unchecked(size, align)
        };
        let ptr = allocator.allocate(layout)? as *mut T;

        Ok(Self {
            ptr,
            layout
        })
    }

    pub fn release(&self) {
        release(self.ptr as *mut u8, self.layout.align(), self.layout.size());
    }
}

#[alloc_error_handler]
fn alloc_error_handler(_layout: core::alloc::Layout) -> ! {
    // Disable memory allocation, this will avoid abort levels which would need to allocate memory
    set_enabled(false);

    // Using SvcBreak by default since this is the safest level that can be used by any context, regardless of available mem/etc.
    // TODO: default aborting system to invoke here?
    abort::abort(abort::AbortLevel::SvcBreak(), rc::ResultOutOfMemory::make())
}