Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add start location transformation to allow more weakly aligned heaps #28

Closed

Conversation

davenpcj5542009
Copy link

In this example, allocation fails despite the heap being large enough due to the weak alignment of the start location.

The init/add_to_heap function doesn't find any 4KB-aligned 4KB blocks within the 6KB region.

use std::alloc::{GlobalAlloc, Layout};
use buddy_system_allocator::{LockedHeap};

fn main() {
    unsafe {
        HEAP_ALLOCATOR.lock().init(HEAP.0.as_ptr() as usize, HEAP.0.len());
        println!("heap: {:?}", *HEAP_ALLOCATOR.lock());
        let ptr = HEAP_ALLOCATOR.alloc(Layout::from_size_align_unchecked(0xb88, 4));
        println!("ptr: {:x}", ptr as usize);
    }
}
pub static mut HEAP_ALLOCATOR: LockedHeap<16> = LockedHeap::empty();

//#[repr(align(4096))]  // works when aligned to 4k boundary
//#[repr(align(256))]    // does not work with weaker alignment
struct Aligned<T>(T);

static mut HEAP:Aligned = Aligned([0u8;0x1800]);

output:

heap: Heap { user: 0, allocated: 0, total: 6144 }
ptr: 0

After the change, the allocation can succeed, as a 4096 block is available at a non-4096-byte-aligned address, and the 6KB heap is decomposed into a 4KB and 2KB block.

heap: Heap { user: 0, allocated: 0, total: 6144 }
{32768: [], 16384: [], 8192: [], 4096: [0x7ff65ca14180], 2048: [0x7ff65ca15180], 1024: [], 
512: [], 256: [], 128: [], 64: [], 32: [], 16: [], 8: [], 4: [], 2: [], 1: []}
ptr: 7ff65ca14180

@jiegec
Copy link
Member

jiegec commented Sep 2, 2023

Although the 6KB region is split into 4KB and 2KB ones, the 4KB region is not aligned to 4KB boundary. This is an assumption for alloc() to satisfy Layout requiremenets.

@davenpcj5542009
Copy link
Author

Although the 6KB region is split into 4KB and 2KB ones, the 4KB region is not aligned to 4KB boundary. This is an assumption for alloc() to satisfy Layout requiremenets.

The basic pointer-alignment guarantees are still met, which suffices for most usage; But I do see the Layout's required alignment is unmet during allocation, especially during over-aligned allocations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants