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

cryptovec: Fix a segmentation fault #288

Merged
merged 1 commit into from
May 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions cryptovec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,15 @@ impl CryptoVec {
let next_capacity = size.next_power_of_two();
let old_ptr = self.p;
let next_layout = std::alloc::Layout::from_size_align_unchecked(next_capacity, 1);
self.p = std::alloc::alloc_zeroed(next_layout);
let new_ptr = std::alloc::alloc_zeroed(next_layout);
if new_ptr.is_null() {
#[allow(clippy::panic)]
{
panic!("Realloc failed, pointer = {:?} {:?}", self, size)
}
}

self.p = new_ptr;
mlock(self.p, next_capacity);

if self.capacity > 0 {
Expand All @@ -261,15 +269,8 @@ impl CryptoVec {
std::alloc::dealloc(old_ptr, layout);
}

if self.p.is_null() {
#[allow(clippy::panic)]
{
panic!("Realloc failed, pointer = {:?} {:?}", self, size)
}
} else {
self.capacity = next_capacity;
self.size = size;
}
self.capacity = next_capacity;
self.size = size;
}
}
}
Expand Down Expand Up @@ -429,3 +430,23 @@ impl Drop for CryptoVec {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

// If `resize` is called with a size that is too large to be allocated, it
// should panic, and not segfault or fail silently.
#[test]
fn large_resize_panics() {
let result = std::panic::catch_unwind(|| {
let mut vec = CryptoVec::new();
// Write something into the vector, so that there is something to
// copy when reallocating, to test all code paths.
vec.push(42);

vec.resize(1_000_000_000_000)
});
assert!(result.is_err());
}
}
Loading