Skip to content
Merged
Show file tree
Hide file tree
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
17 changes: 17 additions & 0 deletions crates/perry-runtime/src/object/object_ops/keys_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,23 @@ pub(crate) unsafe fn own_key_present(
if obj.is_null() || (obj as usize) < 0x10000 || (obj as usize) & 0x7 != 0 || key.is_null() {
return false;
}
// Only a genuine `GC_TYPE_OBJECT` carries a `keys_array` at ObjectHeader
// offset 16. A non-object receiver that still cleared the alignment/range
// guard above — most importantly a real `Map`/`Set`, whose 16-byte header
// is only `size`/`capacity`/`entries` — has no such field, so reading
// `(*obj).keys_array` loads 8 bytes past the header into the adjacent
// allocation. A `Map` reaching `js_object_get_field_by_name`'s `.size`
// fast path (an `any`-typed `map.size` dispatched by name) did exactly
// that: the out-of-bounds word was a live neighbour's GC-header value,
// which cleared the keys-pointer guard below and then SIGBUS'd on the
// `[keys-8]` type-tag read. `try_read_gc_header` rejects header-less slab
// allocations and non-heap addresses without dereferencing them. A
// non-object has no own string keys, so answer false and let the caller
// fall through to the type-specific tail (which serves e.g. `Map.size`).
match crate::value::addr_class::try_read_gc_header(obj as usize) {
Some(h) if h.obj_type == crate::gc::GC_TYPE_OBJECT => {}
_ => return false,
}
let keys = (*obj).keys_array;
if keys.is_null() {
return false;
Expand Down
37 changes: 37 additions & 0 deletions crates/perry-runtime/src/object/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1029,3 +1029,40 @@ fn class_capture_value_or_rejects_tag_stripped_fallback() {
assert!(fallback_is_tag_stripped(stripped));
assert!(!fallback_is_tag_stripped(undef));
}

/// Reading `.size` on a `Map` *by name* — the shape a minified bundle produces
/// when the receiver's `Map` type is erased to `any` (`map.size` dispatched
/// through `js_object_get_field_by_name`) — reaches the `.size` fast path,
/// which calls `own_key_present(map, "size")`. A `MapHeader` is 16 bytes
/// (`size`/`capacity`/`entries`) with no `keys_array` field at offset 16, so
/// `(*obj).keys_array` used to read 8 bytes past the header into the adjacent
/// allocation; that stray word cleared the keys-pointer alignment/range guard
/// and then SIGBUS'd on the `[keys-8]` GC-type-tag load. `own_key_present` now
/// answers `false` for a non-`GC_TYPE_OBJECT` receiver, so the read falls
/// through to the `Map.size` tail instead of dereferencing garbage.
#[test]
fn map_size_by_name_does_not_oob_read_keys_array() {
unsafe {
let size_key = crate::string::js_string_from_bytes(b"size".as_ptr(), 4);

// Empty Map — the exact shape observed crashing (size 0).
let empty = crate::map::js_map_alloc(4);
assert!(!empty.is_null());
// The precise frame that faulted: a Map is not an object, so it has no
// own string key. This must answer false without dereferencing
// `[obj+16]` past the 16-byte MapHeader.
assert!(!own_key_present(empty as *mut ObjectHeader, size_key));
let v0 = crate::object::js_object_get_field_by_name(empty as *const ObjectHeader, size_key);
assert!(v0.is_number(), "empty Map .size must be a number");
assert_eq!(v0.as_number(), 0.0, "empty Map .size");

// Populated Map — `.size` by name must still return the real size.
let m = crate::map::js_map_alloc(4);
crate::map::js_map_set(m, 10.0, 100.0);
crate::map::js_map_set(m, 20.0, 200.0);
assert!(!own_key_present(m as *mut ObjectHeader, size_key));
let v2 = crate::object::js_object_get_field_by_name(m as *const ObjectHeader, size_key);
assert!(v2.is_number(), "populated Map .size must be a number");
assert_eq!(v2.as_number(), 2.0, "populated Map .size");
}
}
91 changes: 91 additions & 0 deletions crates/perry/tests/issue_map_size_by_name_oob.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Regression: reading `.size` on a `Map` whose static type has been erased to
//! `any` — as a minified/bundled program produces when a `Map` flows through a
//! dynamically-dispatched `getX(): any` call — dispatched the read *by name*
//! through `js_object_get_field_by_name`. Its `class X extends Map|Set` `.size`
//! fast path calls `own_key_present(map, "size")`, which read `(*obj).keys_array`
//! at `ObjectHeader` offset 16. A `MapHeader` is only 16 bytes
//! (`size`/`capacity`/`entries`) with no `keys_array` field, so that load went
//! out of bounds into the adjacent allocation; when the stray word was a live
//! neighbour's GC-header value it cleared the keys-pointer guard and then
//! SIGBUS'd on the `[keys-8]` GC-type-tag read.

use std::path::PathBuf;
use std::process::Command;

fn perry_bin() -> PathBuf {
PathBuf::from(env!("CARGO_BIN_EXE_perry"))
}

fn compile_and_run(dir: &std::path::Path, source: &str) -> String {
let entry = dir.join("main.ts");
let output = dir.join("main_bin");
std::fs::write(&entry, source).expect("write entry");

let compile = Command::new(perry_bin())
.current_dir(dir)
.arg("compile")
.arg(&entry)
.arg("-o")
.arg(&output)
.output()
.expect("run perry compile");
assert!(
compile.status.success(),
"perry compile failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&compile.stdout),
String::from_utf8_lossy(&compile.stderr)
);

let run = Command::new(&output)
.current_dir(dir)
.output()
.expect("run compiled binary");
assert!(
run.status.success(),
"compiled binary crashed (Bug: OOB keys_array read on a Map receiver)\n\
status: {:?}\nstdout:\n{}\nstderr:\n{}",
run.status,
String::from_utf8_lossy(&run.stdout),
String::from_utf8_lossy(&run.stderr)
);
String::from_utf8_lossy(&run.stdout).into_owned()
}

#[test]
fn any_typed_map_size_by_name_does_not_crash() {
let dir = tempfile::tempdir().expect("tempdir");
let stdout = compile_and_run(
dir.path(),
r#"
function makeManager(): any {
const q = new Map<string, { state: string }>();
const b = new Map<string, number>();
const c = new Map<string, number>();
q.set("s1", { state: "running" });
q.set("s2", { state: "error" });
function getAllServers() { return q; }
function count() { return b.size + c.size; }
return { getAllServers, count };
}
let mgr: any;
function getManager(): any { return mgr; }
function anyEnabled(): boolean {
const m = getManager();
if (!m) return false;
const servers = m.getAllServers(); // `any`: the Map's static type is erased
if (servers.size === 0) return false; // by-name `.size` read on a Map
for (const s of servers.values()) if (s.state !== "error") return true;
return false;
}
console.log("first", anyEnabled());
mgr = makeManager();
console.log("size", getManager().getAllServers().size);
console.log("second", anyEnabled());
console.log("done");
"#,
);
assert!(stdout.contains("first false"), "first: {stdout}");
assert!(stdout.contains("size 2"), "map .size by name: {stdout}");
assert!(stdout.contains("second true"), "second: {stdout}");
assert!(stdout.contains("done"), "reached end: {stdout}");
}
Loading