Skip to content

Commit 9831d0e

Browse files
committed
Check that allocation does not exceed isize::MAX
See rust-lang/rust#101899
1 parent 7f14d93 commit 9831d0e

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/lua.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,11 @@ impl Lua {
402402
return ptr::null_mut();
403403
}
404404

405+
// Do not allocate more than isize::MAX
406+
if nsize > isize::MAX as usize {
407+
return ptr::null_mut();
408+
}
409+
405410
// Are we fit to the memory limits?
406411
let mut mem_diff = nsize as isize;
407412
if !ptr.is_null() {
@@ -411,12 +416,14 @@ impl Lua {
411416
if mem_info.memory_limit > 0 && new_used_memory > mem_info.memory_limit {
412417
return ptr::null_mut();
413418
}
414-
415-
let new_layout = Layout::from_size_align_unchecked(nsize, ffi::SYS_MIN_ALIGN);
416419
mem_info.used_memory += mem_diff;
417420

418421
if ptr.is_null() {
419422
// Allocate new memory
423+
let new_layout = match Layout::from_size_align(nsize, ffi::SYS_MIN_ALIGN) {
424+
Ok(layout) => layout,
425+
Err(_) => return ptr::null_mut(),
426+
};
420427
let new_ptr = alloc::alloc(new_layout) as *mut c_void;
421428
if new_ptr.is_null() {
422429
alloc::handle_alloc_error(new_layout);
@@ -428,7 +435,7 @@ impl Lua {
428435
let old_layout = Layout::from_size_align_unchecked(osize, ffi::SYS_MIN_ALIGN);
429436
let new_ptr = alloc::realloc(ptr as *mut u8, old_layout, nsize) as *mut c_void;
430437
if new_ptr.is_null() {
431-
alloc::handle_alloc_error(new_layout);
438+
alloc::handle_alloc_error(old_layout);
432439
}
433440
new_ptr
434441
}

0 commit comments

Comments
 (0)