userspace/memory/
heap.rs

1use ample::traits::AllocatableResult;
2
3use crate::Origin;
4
5ample::r#struct!(
6    #[derive(Debug)]
7    pub struct Allocator {}
8);
9
10// ample::traits_impl_blanket_bytes!(Allocator);
11
12pub type AllocatorPointer = *mut Allocator;
13
14impl ample::traits::Allocatable<Origin> for Allocator {
15    type Ok = crate::Ok;
16    type Error = crate::Error;
17    fn allocate(numerosity_of_bytes: usize) -> crate::Result {
18        match crate::target::os::syscall::mmap(
19            core::ptr::null_mut(),
20            numerosity_of_bytes,
21            (crate::target::os::syscall::mmap::Prot::Read
22                | crate::target::os::syscall::mmap::Prot::Write) as i32,
23            (crate::target::os::syscall::mmap::Flag::Anonymous
24                | crate::target::os::syscall::mmap::Flag::Private) as i32,
25            -1,
26            0,
27        ) {
28            core::result::Result::Ok(crate::Ok::Target(crate::target::Ok::Os(
29                crate::target::os::Ok::Syscall(crate::target::os::syscall::Ok::MMap(
30                    crate::target::os::syscall::mmap::Ok::Default(m),
31                )),
32            ))) => core::result::Result::Ok(crate::Ok::Memory(crate::memory::Ok::HeapAllocate(
33                m as *mut Self,
34            ))),
35            _ => panic!("Failed to allocate memory"),
36        }
37    }
38
39    fn deallocate(ptr: *mut Self, numerosity_of_bytes: usize) -> crate::Result {
40        match crate::target::os::syscall::munmap(ptr as *mut u8, numerosity_of_bytes) {
41            _ => true,
42        };
43        core::result::Result::Ok(crate::Ok::Memory(crate::memory::Ok::HeapAllocate(
44            ptr as *mut Self,
45        )))
46    }
47}
48
49pub trait Allocating<T> {
50    fn allocate(count: usize) -> *mut T;
51    fn allocate_slice(count: usize) -> &'static mut [T];
52    fn deallocate(ptr: *mut T, count: usize) -> bool;
53    fn deallocate_slice(slice: &mut [T]) -> bool;
54}
55
56impl<T> Allocating<T> for T
57where
58    T: ample::traits::Bytes<Origin, Origin>,
59    T: Default,
60{
61    fn allocate(numerosity: usize) -> *mut T {
62        let numerosity_of_bytes = numerosity * T::BYTES_SIZE + T::BYTES_ALIGN;
63        match <Allocator as ample::traits::Allocatable<Origin>>::allocate(numerosity_of_bytes) {
64            Ok(m) => m.as_ptr() as *mut T,
65            _ => core::ptr::null_mut(),
66        }
67    }
68
69    /// Deallocate an array previously allocated with allocate_array
70    fn deallocate(ptr: *mut T, numerosity: usize) -> bool {
71        let total_size = numerosity * T::BYTES_SIZE + T::BYTES_ALIGN;
72
73        let aligned_size =
74            (total_size + crate::memory::page::SIZE - 1) & !(crate::memory::page::SIZE - 1);
75
76        // let _ = crate::target::os::syscall::munmap(ptr as *mut u8, aligned_size);
77        // true
78        match <Allocator as ample::traits::Allocatable<Origin>>::deallocate(
79            ptr as *mut Allocator,
80            aligned_size,
81        ) {
82            Ok(_) => true,
83            Err(_) => false,
84        }
85    }
86
87    /// Allocate and initialize a slice
88    fn allocate_slice(numerosity: usize) -> &'static mut [T] {
89        let ptr = Self::allocate(numerosity) as *mut T;
90
91        for i in 0..numerosity {
92            unsafe {
93                *ptr.add(i) = T::default();
94            }
95        }
96
97        unsafe { core::slice::from_raw_parts_mut(ptr, numerosity) }
98    }
99
100    fn deallocate_slice(slice: &mut [T]) -> bool {
101        Self::deallocate(slice.as_mut_ptr() as *mut T, slice.len())
102    }
103}
104
105impl<T> Allocating<T> for &[T]
106where
107    T: ample::traits::Bytes<Origin, Origin>,
108    T: Default,
109{
110    fn allocate(numerosity: usize) -> *mut T {
111        match <Allocator as ample::traits::Allocatable<Origin>>::allocate(
112            numerosity * T::BYTES_SIZE,
113        ) {
114            Ok(ptr) => ptr.as_ptr() as *mut T,
115            Err(_) => core::ptr::null_mut(),
116        }
117    }
118
119    /// Deallocate an array previously allocated with allocate_array
120    fn deallocate(ptr: *mut T, numerosity: usize) -> bool {
121        match <Allocator as ample::traits::Allocatable<Origin>>::deallocate(
122            ptr as *mut Allocator,
123            numerosity,
124        ) {
125            Ok(_) => true,
126            Err(_) => false,
127        }
128    }
129
130    /// Allocate and initialize a slice
131    fn allocate_slice(numerosity: usize) -> &'static mut [T] {
132        let ptr = match <Allocator as ample::traits::Allocatable<Origin>>::allocate(numerosity) {
133            Ok(ptr) => ptr.as_ptr() as *mut T,
134            Err(_) => core::ptr::null_mut(),
135        };
136
137        for i in 0..numerosity {
138            unsafe {
139                *ptr.add(i) = T::default();
140            }
141        }
142
143        unsafe { core::slice::from_raw_parts_mut(ptr, numerosity) }
144    }
145
146    fn deallocate_slice(slice: &mut [T]) -> bool {
147        match <Allocator as ample::traits::Allocatable<Origin>>::deallocate(
148            slice.as_mut_ptr() as *mut Allocator,
149            slice.len(),
150        ) {
151            Ok(_) => true,
152            Err(_) => false,
153        }
154    }
155}
156
157// pub type StringAllocator = *const u8;
158
159// ample::result!(
160//     Ok;
161//     "Allocate Ok";
162//     usize;
163//     [
164//         [1; USERSPACE_MEMORY_ALLOCATION_HEAP_DEFAULT_OK; Default; AllocatorPointer; "ZE"; "Entry to ze"],
165//         [2; USERSPACE_MEMORY_ALLOCATION_HEAP_ALLOCATOR_DEFAULT_OK; Allocator; AllocatorPointer; "ZE"; "Entry to ze"],
166//         [3; USERSPACE_MEMORY_ALLOCATION_HEAP_DEALLOCATOR_DEFAULT_OK; Deallocator; AllocatorPointer; "ZE"; "Entry to ze"],
167//         [4; USERSPACE_MEMORY_ALLOCATION_HEAP_STRING_DEFAULT_OK; String; StringAllocator; "ZE"; "Entry to ze"],
168//         // [2; USERSPACE_MEMORY_ALLOCATION_HEAP_ALLOCATING_OK; Allocator; crate::memory::Ok; "ZE"; "Entry to ze"],
169//     ];
170//     Error;
171//     "Allocator Ok";
172//     usize;
173//     [
174//         [1; USERSPACE_MEMORY_ALLOCATION_HEAP_DEFAULT_ERROR; Default; AllocatorPointer; "ZE"; "Entry to ze"],
175//         [2; USERSPACE_MEMORY_ALLOCATION_HEAP_ALLOCATOR_DEFAULT_ERROR; Allocator; AllocatorPointer; "ZE"; "Entry to ze"],
176//         [3; USERSPACE_MEMORY_ALLOCATION_HEAP_DEALLOCATOR_DEFAULT_ERROR; Deallocator; AllocatorPointer; "ZE"; "Entry to ze"],
177//     ]
178// );
179
180impl ample::traits::AllocatableResult for crate::Ok {
181    fn as_ptr(&self) -> *mut u8 {
182        match self {
183            crate::Ok::Memory(crate::memory::Ok::HeapAllocate(m)) => *m as *mut u8,
184            _ => core::ptr::null_mut(),
185        }
186    }
187
188    fn from_raw(raw: *mut u8) -> Self {
189        crate::Ok::Memory(crate::memory::Ok::HeapAllocate(raw as *mut Allocator))
190    }
191}
192
193impl ample::traits::AllocatableResult for crate::Error {
194    fn as_ptr(&self) -> *mut u8 {
195        match self {
196            _ => core::ptr::null_mut(),
197            // core::result::Result::Err(crate::Error::Memory(crate::memory::Error::Allocate(
198            //     crate::memory::heap::Error::Allocate(
199            //         crate::memory::Error::Default(m),
200            //     ),
201            // ))) => *m as *mut u8,
202        }
203    }
204
205    fn from_raw(_raw: *mut u8) -> Self {
206        crate::Error::Error(3)
207        // crate::Error::Memory(crate::memory::Error::Allocate(
208        //     crate::memory::heap::Error::Allocate(
209        //         crate::memory::Error::Default(core::ptr::null_mut()),
210        //     ),
211        // ))
212    }
213}