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
use core::mem::size_of;
use core::prelude::*;
use kernel::mm::{Allocator, Alloc, BuddyAlloc};
use util::bitv;
use rust_core::fail::{abort, out_of_memory};
pub static mut heap: Option<Alloc> = None;
pub fn init() -> Alloc {
let alloc = Alloc::new(
BuddyAlloc::new(17, bitv::Bitv { storage: 0x100_000 as *mut u32 }),
0x110_000 as *mut u8,
0,
);
unsafe {
heap = Some(alloc);
}
alloc
}
#[lang = "exchange_malloc"]
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
match get(heap).alloc(size) {
(_, 0) => out_of_memory(),
(ptr, _) => ptr
}
}
#[no_mangle]
pub unsafe extern "C" fn rust_allocate(size: uint, _align: uint) -> *mut u8 {
malloc_raw(size)
}
#[lang = "exchange_free"]
#[inline]
pub unsafe fn free<T>(ptr: *mut T) {
get(heap).free(ptr as *mut u8);
}
#[inline]
pub unsafe fn alloc<T = u8>(count: uint) -> *mut T {
match count.checked_mul(&size_of::<T>()) {
None => out_of_memory(),
Some(size) => malloc_raw(size) as *mut T
}
}
#[inline]
pub unsafe fn zero_alloc<T = u8>(count: uint) -> *mut T {
match count.checked_mul(&size_of::<T>()) {
None => out_of_memory(),
Some(size) => match get(heap).zero_alloc(size) {
(_, 0) => out_of_memory(),
(ptr, _) => ptr as *mut T
}
}
}
#[inline]
pub unsafe fn realloc_raw<T>(ptr: *mut T, count: uint) -> *mut T {
match count.checked_mul(&size_of::<T>()) {
None => out_of_memory(),
Some(0) => {
free(ptr as *mut u8);
0 as *mut T
}
Some(size) => match get(heap).realloc(ptr as *mut u8, size) {
(_, 0) => out_of_memory(),
(ptr, _) => ptr as *mut T
}
}
}
fn get<T>(opt : Option<T>) -> T {
match opt {
Some(val) => val,
None => abort(),
}
}