解决内存allocate函数有可能访问未知内存的问题

This commit is contained in:
pointer-to-bios 2024-02-05 21:55:42 +08:00
parent e99d51e81f
commit 0542277e31
5 changed files with 20 additions and 14 deletions

View File

@ -6,14 +6,5 @@ edition = "2021"
# 此Cargo.toml仅用于rust-analyzer识别rust部分的代码
# 不应使用cargo编译
[build]
type = "staticlib"
rustflags = [
"-C", "embed-bitcode=no",
"-C", "code-model=large",
"-C", "relocation-model=static",
"-L", "crate=${PWD}/../rustlib/${ARCH}/src/"
]
[target.'cfg(target_arch = "x86_64")']
target = "x86_64-unknown-none"

View File

@ -139,9 +139,9 @@ allocator对象在进程与内核之间传递时一律使用内核空间的映
*/
void *memm_allocate(usize size, usize pid);
#define memm_addr_set_allocator(mem, allocator) \
*(allocator_t **)(mem - 16) = allocator;
*(allocator_t **)((void *)(mem) - 16) = allocator;
#define memm_addr_get_allocator(mem) \
((*(allocator_t **)(mem - 16)))
((*(allocator_t **)((void *)(mem) - 16)))
void *memm_kernel_allocate(usize size);

View File

@ -200,7 +200,8 @@ void *memm_allocate(usize size, usize pid)
ptr = new_allocator->allocate(&new_allocator->allocator_instance, orgsize, 0);
after_allocation:
memm_addr_set_allocator(ptr, allocator);
if (ptr != nullptr)
memm_addr_set_allocator(ptr, allocator);
return ptr;
}

View File

@ -1,6 +1,9 @@
extern crate core;
use core::alloc::{GlobalAlloc, Layout};
use core::{
alloc::{GlobalAlloc, Layout},
ptr::null_mut,
};
extern "C" {
pub fn memm_kernel_allocate(size: usize) -> *mut u8;
@ -12,7 +15,14 @@ pub struct KernelAllocator {}
unsafe impl GlobalAlloc for KernelAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
memm_kernel_allocate(layout.size())
let res = memm_kernel_allocate(layout.size());
if res == null_mut() {
panic!(
"Kernel allocator failed to allocate {} byte(s) memory.",
layout.size()
);
}
res
}
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {

View File

@ -96,6 +96,10 @@ SECTIONS {
{
*(.debug_pubtypes)
}
.debug_frame :
{
*(.debug_frame)
}
.kend :
{
*(.kend)