ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
pub struct BumpAllocator {
    heap_start: usize,
    heap_end: usize,
    next: usize,
    allocations: usize,
}

impl BumpAllocator {
    pub const fn new() -> Self {
        BumpAllocator {
            heap_start: 0,
            heap_end: 0,
            next: 0,
            allocations: 0,
        }
    }
    /// # Safety
    ///
    /// The caller must provide an unused, valid heap region that remains
    /// exclusively owned by this allocator for the lifetime of the kernel.
    pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
        self.heap_start = heap_start;
        self.heap_end = heap_start + heap_size;
        self.next = self.heap_start;
        // DEBUG — verify init was called
        crate::serial_println!(
            "[BUMP] init called: start={:#x} size={:#x} end={:#x}",
            heap_start,
            heap_size,
            self.heap_end
        );
    }
}

impl Default for BumpAllocator {
    fn default() -> Self {
        Self::new()
    }
}

use super::Locked;
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr;

unsafe impl GlobalAlloc for Locked<BumpAllocator> {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let mut bump = self.lock();

        let alloc_start = align_up(bump.next, layout.align());
        let alloc_end = match alloc_start.checked_add(layout.size()) {
            Some(end) => end,
            None => return ptr::null_mut(),
        };

        if alloc_end > bump.heap_end {
            // DEBUG — 打印分配器状态
            crate::serial_println!("[BUMP] OOM: next={:#x} end={:#x} size={} align={} alloc_start={:#x} alloc_end={:#x}",
                bump.next, bump.heap_end, layout.size(), layout.align(), alloc_start, alloc_end);
            ptr::null_mut()
        } else {
            bump.next = alloc_end;
            bump.allocations += 1;
            alloc_start as *mut u8
        }
    }

    unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
        let mut bump = self.lock();

        bump.allocations -= 1;
        // BumpAllocator never reuses freed memory — next pointer stays put
    }
}

fn align_up(addr: usize, align: usize) -> usize {
    (addr + align - 1) & !(align - 1)
}