Skip to content

Commit e211888

Browse files
author
blake2-ppc
committed
std::at_vec: Fix segfault on overflow when resizing ~[@t]
Easy to reproduce: let mut v = ~[@1]; v.resize(-1); // success a.k.a silent failure v.push(@2); // segfault
1 parent 6e538ed commit e211888

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

src/libstd/at_vec.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,16 @@ pub mod raw {
230230
// Implementation detail. Shouldn't be public
231231
#[allow(missing_doc)]
232232
pub fn reserve_raw(ty: *TyDesc, ptr: *mut *mut Box<Vec<()>>, n: uint) {
233-
233+
// check for `uint` overflow
234234
unsafe {
235-
let size_in_bytes = n * (*ty).size;
236-
if size_in_bytes > (**ptr).data.alloc {
237-
let total_size = size_in_bytes + sys::size_of::<Vec<()>>();
235+
if n > (**ptr).data.alloc / (*ty).size {
236+
let alloc = n * (*ty).size;
237+
let total_size = alloc + sys::size_of::<Vec<()>>();
238+
if alloc / (*ty).size != n || total_size < alloc {
239+
fail!("vector size is too large: %u", n);
240+
}
238241
(*ptr) = local_realloc(*ptr as *(), total_size) as *mut Box<Vec<()>>;
239-
(**ptr).data.alloc = size_in_bytes;
242+
(**ptr).data.alloc = alloc;
240243
}
241244
}
242245

src/libstd/vec.rs

+8
Original file line numberDiff line numberDiff line change
@@ -3659,6 +3659,14 @@ mod tests {
36593659
v.push(2);
36603660
}
36613661

3662+
#[test]
3663+
#[should_fail]
3664+
fn test_overflow_does_not_cause_segfault_managed() {
3665+
let mut v = ~[@1];
3666+
v.reserve(-1);
3667+
v.push(@2);
3668+
}
3669+
36623670
#[test]
36633671
fn test_mut_split() {
36643672
let mut values = [1u8,2,3,4,5];

0 commit comments

Comments
 (0)