Skip to content

Commit c64e524

Browse files
authored
Merge pull request #1129 from CraftSpider/fix-bib-ub
[bibtex] Fix UB caused by invalidating protected reference
2 parents 82e78d4 + 06591ac commit c64e524

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

crates/engine_bibtex/src/xbuf.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,17 @@ pub fn xcalloc_zeroed<T: SafelyZero>(len: usize) -> Option<&'static mut [T]> {
4545
}
4646
}
4747

48-
pub fn xrealloc_zeroed<T: SafelyZero>(
49-
old: &'static mut [T],
48+
/// # Safety
49+
///
50+
/// The provided `old` buffer must be valid, and allocated by `xalloc`/`xcalloc`
51+
pub unsafe fn xrealloc_zeroed<T: SafelyZero>(
52+
old: *mut [T],
5053
new_len: usize,
5154
) -> Option<&'static mut [T]> {
52-
let old_len = old.len();
55+
let old_len = (*old).len();
5356
let new_size = new_len * mem::size_of::<T>();
5457
// SAFETY: realloc can be called with any size, even 0, that will just deallocate and return null
55-
let ptr = unsafe { xrealloc((old as *mut [_]).cast(), new_size) }.cast::<T>();
58+
let ptr = unsafe { xrealloc(old.cast(), new_size) }.cast::<T>();
5659
if ptr.is_null() {
5760
None
5861
} else {
@@ -63,7 +66,7 @@ pub fn xrealloc_zeroed<T: SafelyZero>(
6366
}
6467
// SAFETY: realloc guarantees `new_size` bytes valid, plus `SafelyZero` means it's sound to
6568
// return a reference to all-zero T
66-
Some(unsafe { slice::from_raw_parts_mut(ptr.cast(), new_len) })
69+
Some(unsafe { slice::from_raw_parts_mut(ptr, new_len) })
6770
}
6871
}
6972

@@ -78,7 +81,8 @@ impl<T: SafelyZero + 'static> XBuf<T> {
7881
pub fn grow(&mut self, grow_by: usize) {
7982
let slice = mem::take(&mut self.0);
8083
let old_len = slice.len();
81-
self.0 = xrealloc_zeroed(slice, grow_by + old_len).unwrap();
84+
// TODO: Just use system allocator?
85+
self.0 = unsafe { xrealloc_zeroed(slice, grow_by + old_len) }.unwrap();
8286
}
8387
}
8488

0 commit comments

Comments
 (0)