sel4_dlmalloc/
lib.rs

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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

#![no_std]

use core::alloc::{GlobalAlloc, Layout};
use core::cell::{RefCell, UnsafeCell};
use core::mem;
use core::ptr;

use dlmalloc::{Allocator as DlmallocAllocator, Dlmalloc};
use lock_api::{Mutex, RawMutex};

pub type StaticDlmallocGlobalAlloc<R, T> = DlmallocGlobalAlloc<R, StaticDlmallocAllocator<T>>;

impl<R, T> StaticDlmallocGlobalAlloc<R, T> {
    pub const fn new(raw_mutex: R, get_bounds: T) -> Self {
        Self {
            dlmalloc: Mutex::from_raw(
                raw_mutex,
                Dlmalloc::new_with_allocator(StaticDlmallocAllocator::new(get_bounds)),
            ),
        }
    }

    pub const fn mutex(&self) -> &Mutex<R, Dlmalloc<StaticDlmallocAllocator<T>>> {
        &self.dlmalloc
    }
}

pub struct DlmallocGlobalAlloc<R, T> {
    dlmalloc: Mutex<R, Dlmalloc<T>>,
}

unsafe impl<R: RawMutex, T: DlmallocAllocator> GlobalAlloc for DlmallocGlobalAlloc<R, T> {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.dlmalloc.lock().malloc(layout.size(), layout.align())
    }

    #[inline]
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        self.dlmalloc.lock().calloc(layout.size(), layout.align())
    }

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        self.dlmalloc
            .lock()
            .free(ptr, layout.size(), layout.align())
    }

    #[inline]
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        self.dlmalloc
            .lock()
            .realloc(ptr, layout.size(), layout.align(), new_size)
    }
}

pub struct StaticDlmallocAllocator<T> {
    state: RefCell<StaticDlmallocAllocatorState<T>>,
}

unsafe impl<T: Send> Send for StaticDlmallocAllocatorState<T> {}

enum StaticDlmallocAllocatorState<T> {
    Uninitialized { get_initial_bounds: T },
    Initializing,
    Initialized { free: Free },
}

// TODO: ptr, watermark: usize, size: usize
struct Free {
    watermark: *mut u8,
    end: *mut u8,
}

impl Free {
    fn new(bounds: StaticHeapBounds) -> Self {
        let end = bounds.ptr.wrapping_add(bounds.size);
        Self {
            watermark: bounds.ptr,
            end,
        }
    }

    fn alloc(&mut self, size: usize) -> Option<*mut u8> {
        let start = self.watermark;
        let end = start.wrapping_offset(size.try_into().unwrap());
        if end < start || end > self.end {
            None
        } else {
            self.watermark = end;
            Some(start)
        }
    }
}

impl<T> StaticDlmallocAllocator<T> {
    pub const fn new(get_initial_bounds: T) -> Self {
        Self {
            state: RefCell::new(StaticDlmallocAllocatorState::Uninitialized { get_initial_bounds }),
        }
    }
}

impl<T: GetStaticHeapBounds> StaticDlmallocAllocatorState<T> {
    fn as_free(&mut self) -> &mut Free {
        if matches!(self, Self::Uninitialized { .. }) {
            if let Self::Uninitialized { get_initial_bounds } =
                mem::replace(self, Self::Initializing)
            {
                *self = Self::Initialized {
                    free: Free::new(get_initial_bounds.bounds()),
                };
            } else {
                unreachable!()
            }
        }
        if let Self::Initialized { free } = self {
            free
        } else {
            unreachable!()
        }
    }
}

unsafe impl<T: GetStaticHeapBounds + Send> DlmallocAllocator for StaticDlmallocAllocator<T> {
    fn alloc(&self, size: usize) -> (*mut u8, usize, u32) {
        match self.state.borrow_mut().as_free().alloc(size) {
            Some(start) => (start, size, 0),
            None => (ptr::null_mut(), 0, 0),
        }
    }

    fn remap(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize, _can_move: bool) -> *mut u8 {
        ptr::null_mut()
    }

    fn free_part(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize) -> bool {
        false
    }

    fn free(&self, _ptr: *mut u8, _size: usize) -> bool {
        false
    }

    fn can_release_part(&self, _flags: u32) -> bool {
        false
    }

    fn allocates_zeros(&self) -> bool {
        true
    }

    fn page_size(&self) -> usize {
        // TODO should depend on configuration
        4096
    }
}

pub trait GetStaticHeapBounds {
    fn bounds(self) -> StaticHeapBounds;
}

pub struct StaticHeapBounds {
    ptr: *mut u8,
    size: usize,
}

impl StaticHeapBounds {
    pub fn new(ptr: *mut u8, size: usize) -> Self {
        Self { ptr, size }
    }
}

impl<T: FnOnce() -> StaticHeapBounds> GetStaticHeapBounds for T {
    fn bounds(self) -> StaticHeapBounds {
        (self)()
    }
}

#[repr(C)]
pub struct StaticHeap<const N: usize, A = ()> {
    _alignment: [A; 0],
    space: UnsafeCell<[u8; N]>,
}

unsafe impl<const N: usize, A> Sync for StaticHeap<N, A> {}

impl<const N: usize, A> StaticHeap<N, A> {
    pub const fn new() -> Self {
        Self {
            _alignment: [],
            space: UnsafeCell::new([0; N]),
        }
    }
}

impl<const N: usize, A> Default for StaticHeap<N, A> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> GetStaticHeapBounds for &StaticHeap<N> {
    fn bounds(self) -> StaticHeapBounds {
        StaticHeapBounds::new(self.space.get().cast(), N)
    }
}