Skip to content

Commit 2a9315d

Browse files
committed
Fix realloc by updating the stored Layout. Previously the old Layout was copied over but not updated to account for the new size.
Signed-off-by: Ludvig Liljenberg <[email protected]>
1 parent b115c42 commit 2a9315d

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/hyperlight_guest/src/memory.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,18 +78,23 @@ pub extern "C" fn hlrealloc(ptr: *mut c_void, size: usize) -> *mut c_void {
7878
}
7979

8080
unsafe {
81+
let total_new_size = size
82+
.checked_add(size_of::<Layout>())
83+
.expect("data and layout size should not overflow in realloc");
84+
8185
let block_start = (ptr as *const Layout).sub(1);
82-
let layout = block_start.read();
83-
let total_new_size = size + size_of::<Layout>();
86+
let old_layout = block_start.read();
87+
let new_layout = Layout::from_size_align(total_new_size, align_of::<usize>()).unwrap();
88+
8489
let new_block_start =
8590
alloc::alloc::realloc(block_start as *mut u8, layout, total_new_size) as *mut Layout;
8691

8792
if new_block_start.is_null() {
8893
// Realloc failed
8994
abort_with_code(ErrorCode::MallocFailed as i32);
9095
} else {
91-
// Return the pointer just after the layout information
92-
// since old layout should still as it would have been copied
96+
// Update the stored Layout, then return ptr to memory right after the Layout.
97+
new_block_start.write(new_layout);
9398
new_block_start.add(1) as *mut c_void
9499
}
95100
}

0 commit comments

Comments
 (0)