Skip to content

Commit aebb4c3

Browse files
committed
feat(lab/7): add heap auto grow
1 parent c241eca commit aebb4c3

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

docs/labs/0x07/tasks.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -903,3 +903,52 @@ assert!(ret == heap_end, "Failed to allocate heap");
903903
_思考:文件内容什么时候会被写入到磁盘?_
904904

905905
- 综合考虑有关内存、文件、I/O 等方面的知识,讨论为什么 `mmap` 系统调用在现代操作系统中越来越受欢迎,它具有哪些优势?
906+
907+
## 加分项
908+
909+
1. 😋 尝试借助 `brk` 为用户态堆实现自动扩容:
910+
911+
- `LockedHeap` 支持 `extend` 方法,可以在堆区不足时扩容大小,但是需要用户程序分配好所需的空间;
912+
- 自定义数据结构 `BrkAllocator`,并为其实现 `GlobalAlloc` trait:
913+
914+
```rust
915+
#[global_allocator]
916+
static ALLOCATOR: BrkAllocator = BrkAllocator::empty();
917+
918+
struct BrkAllocator {
919+
allocator: LockedHeap,
920+
}
921+
922+
pub fn init() {
923+
ALLOCATOR.init();
924+
}
925+
926+
impl BrkAllocator {
927+
pub const fn empty() -> Self {
928+
Self {
929+
allocator: LockedHeap::empty(),
930+
}
931+
}
932+
933+
pub fn init(&self) {
934+
// FIXME: init heap to initial size with `brk` system call
935+
}
936+
937+
pub unsafe fn extend(&self /* maybe add params you need */) -> bool {
938+
// FIXME: extend heap size with `brk` system call
939+
// return false if failed or reach the max size (8 MiB suggested)
940+
}
941+
}
942+
943+
unsafe impl GlobalAlloc for BrkAllocator {
944+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
945+
let mut ptr = self.allocator.alloc(layout);
946+
// FIXME: if alloc failed, ptr is null
947+
// FIXME: try to extend heap size, then alloc again
948+
ptr
949+
}
950+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
951+
self.allocator.dealloc(ptr, layout)
952+
}
953+
}
954+
```

0 commit comments

Comments
 (0)