fix: 修复slab分配器的UAF\内存越界问题 (#1111)

- 新增 `tests.rs` 模块,包含多个测试用例以验证内存分配器的正确性和性能。
- 优化 `pages.rs` 中的 `Bitfield` 实现,移除不必要的 `get_offset_for_align` 函数。
- 在 `zone.rs` 中新增 `try_reclaim_pages_in_slab` 方法,用于在特定 slab 中回收页面。
- 修复 `kernel_allocator.rs` 中的 `allocator_select_condition` 逻辑,移除对 `slab_init_state` 的依赖。
- 移除 `slab.rs` 中的 `slab_init_state` 函数,简化初始化状态检查。

Signed-off-by: longjin <longjin@DragonOS.org>
This commit is contained in:
LoGin
2025-03-24 23:21:22 +08:00
committed by GitHub
parent 13514f6695
commit f8c5e12d70
7 changed files with 637 additions and 75 deletions

View File

@ -15,7 +15,7 @@ use core::{
use super::{
page_frame::{FrameAllocator, PageFrameCount},
slab::{slab_init_state, SLABALLOCATOR},
slab::SLABALLOCATOR,
};
/// 类kmalloc的分配器应当实现的trait
@ -95,7 +95,7 @@ impl LocalAlloc for KernelAllocator {
}
unsafe fn local_dealloc(&self, ptr: *mut u8, layout: Layout) {
if allocator_select_condition(layout) || ((ptr as usize) % 4096) == 0 {
if allocator_select_condition(layout) {
self.free_in_buddy(ptr, layout)
} else if let Some(ref mut slab) = SLABALLOCATOR {
slab.deallocate(ptr, layout).unwrap()
@ -137,7 +137,7 @@ unsafe impl GlobalAlloc for KernelAllocator {
/// 判断选择buddy分配器还是slab分配器
fn allocator_select_condition(layout: Layout) -> bool {
layout.size() > 2048 || !slab_init_state()
layout.size() > 2048
}
fn alloc_debug_log(source: LogSource, layout: Layout, ptr: *mut u8) {

View File

@ -72,11 +72,6 @@ pub unsafe fn slab_init() {
SLABINITSTATE = true.into();
}
// 查看slab初始化状态
pub fn slab_init_state() -> bool {
unsafe { *SLABINITSTATE.get_mut() }
}
pub unsafe fn slab_usage() -> SlabUsage {
if let Some(ref mut slab) = SLABALLOCATOR {
slab.zone.usage()