Skip to content

Commit

Permalink
Handle allocation errors (#1850)
Browse files Browse the repository at this point in the history
Fixes #1847 by wrapping the `std::alloc::alloc()` call in `try_alloc()`, which checks that the returned pointer is non-null and handles allocation errors that way. It will now abort the process instead of executing UB in the error path
  • Loading branch information
y21 committed Feb 20, 2022
1 parent 29cd909 commit fabbf15
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions boa/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
};
use rustc_hash::FxHashSet;
use std::{
alloc::{alloc, dealloc, Layout},
alloc::{alloc, dealloc, handle_alloc_error, Layout},
borrow::Borrow,
cell::Cell,
hash::{Hash, Hasher},
Expand Down Expand Up @@ -174,6 +174,14 @@ const MAX_CONSTANT_STRING_LENGTH: usize = {
max
};

unsafe fn try_alloc(layout: Layout) -> *mut u8 {
let ptr = alloc(layout);
if ptr.is_null() {
handle_alloc_error(layout);
}
ptr
}

thread_local! {
static CONSTANTS: FxHashSet<JsString> = {
let mut constants = FxHashSet::default();
Expand Down Expand Up @@ -217,7 +225,7 @@ impl Inner {
.expect("failed to extend memory layout");

let inner = unsafe {
let inner = alloc(layout).cast::<Self>();
let inner = try_alloc(layout).cast::<Self>();

// Write the first part, the Inner.
inner.write(Self {
Expand Down Expand Up @@ -257,7 +265,7 @@ impl Inner {
.expect("failed to extend memory layout");

let inner = unsafe {
let inner = alloc(layout).cast::<Self>();
let inner = try_alloc(layout).cast::<Self>();

// Write the first part, the Inner.
inner.write(Self {
Expand Down

0 comments on commit fabbf15

Please sign in to comment.