@@ -60,29 +60,34 @@ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
60
60
61
61
[dependencies ]
62
62
buddy_system_allocator = " 0.3"
63
+ ```
63
64
65
+ ``` rust
64
66
// src/lib.rs
65
- // Rust 要求 global allocator 必须在 lib.rs 中定义,因此不能放在 memory 子模块里面
66
- #![feature(alloc_error_handler)]
67
-
68
- use buddy_system_allocator :: LockedHeap ;
69
67
70
- #[global_allocator]
71
- static DYNAMIC_ALLOCATOR : LockedHeap = LockedHeap :: empty ();
68
+ #![feature(alloc_error_handler)]
72
69
73
- #[alloc_error_handler]
74
- fn alloc_error_handler (_ : core :: alloc :: Layout ) -> ! {
75
- panic! (" alloc_error_handler do nothing but panic!" );
76
- }
70
+ extern crate alloc;
71
+ ```
77
72
73
+ ``` rust
78
74
// src/consts.rs
75
+
79
76
// 内核堆大小为8MiB
80
77
pub const KERNEL_HEAP_SIZE : usize = 0x800000 ;
78
+ ```
81
79
80
+ ``` rust
82
81
// src/memory/mod.rs
83
82
84
- use crate :: DYNAMIC_ALLOCATOR ;
85
83
use crate :: consts :: * ;
84
+ use buddy_system_allocator :: LockedHeap ;
85
+
86
+ pub fn init (l : usize , r : usize ) {
87
+ FRAME_ALLOCATOR . lock (). init (l , r );
88
+ init_heap ();
89
+ println! (" ++++ setup memory! ++++" );
90
+ }
86
91
87
92
fn init_heap () {
88
93
// 同样是在内核中开一块静态内存供 buddy system allocator 使用
@@ -95,10 +100,12 @@ fn init_heap() {
95
100
}
96
101
}
97
102
98
- pub fn init (l : usize , r : usize ) {
99
- FRAME_ALLOCATOR . lock (). init (l , r );
100
- init_heap ();
101
- println! (" ++++ setup memory! ++++" );
103
+ #[global_allocator]
104
+ static DYNAMIC_ALLOCATOR : LockedHeap = LockedHeap :: empty ();
105
+
106
+ #[alloc_error_handler]
107
+ fn alloc_error_handler (_ : core :: alloc :: Layout ) -> ! {
108
+ panic! (" alloc_error_handler do nothing but panic!" );
102
109
}
103
110
```
104
111
@@ -107,10 +114,6 @@ pub fn init(l: usize, r: usize) {
107
114
现在我们来测试一下动态内存分配是否有效,分别动态分配一个整数和一个数组:
108
115
109
116
``` rust
110
- // src/lib.rs
111
-
112
- extern crate alloc;
113
-
114
117
// src/init.rs
115
118
116
119
fn dynamic_allocating_test () {
@@ -152,10 +155,10 @@ fn dynamic_allocating_test() {
152
155
>
153
156
> ``` rust
154
157
> heap_value assertion successfully!
155
- > heap_value is at 0xffffffffc0a15100
158
+ > heap_value is at 0x80a10000
156
159
> heap_value is in section . bss!
157
160
> vec assertion successfully!
158
- > vec is at 0xffffffffc0a14000
161
+ > vec is at 0x80211000
159
162
> vec is in section . bss!
160
163
> ```
161
164
0 commit comments