Scripts: an error's authored check hashes its name and message without copying them

An error the interpreter throws keeps a hash of its description, and a run compares the error's
current name and message with it to tell whether the text is the script's own. The comparison
copied the whole description first, so a rejected error whose message a script had replaced with
a long string was copied whole at the end of the run. The hash is now fed the strings' code units
a piece at a time along the rope, so nothing is copied, and a change anywhere in the message is
still seen.
This commit is contained in:
dotCooCoo committed 2026-11-24 06:12:42 -08:00
1 parent ff9ed631fa
commit 71d1600dab
3 files changed
+86 -4

No files matched your search

+49 -4
View File
@@ -50,12 +50,37 @@ fn internal<T>(message: &str) -> JsResult<T> {
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
fn description_hash(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::hash::DefaultHasher::new();
text.hash(&mut h);
let mut h = DescriptionHash::default();
h.text(text);
h.finish()
}
/// A [`description_hash`] fed the description's code units a run at a time, so a long string is
/// hashed without being copied.
#[derive(Default)]
struct DescriptionHash(std::hash::DefaultHasher);
impl DescriptionHash {
fn units(&mut self, units: &[u16]) {
use std::hash::Hasher;
for &u in units {
self.0.write_u16(u);
}
}
fn text(&mut self, text: &str) {
use std::hash::Hasher;
for u in text.encode_utf16() {
self.0.write_u16(u);
}
}
fn finish(&self) -> u64 {
use std::hash::Hasher;
self.0.finish()
}
}
/// The kinds of error object the engine throws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ErrorType {
@@ -591,7 +616,7 @@ impl Interp {
let Value::Object(o) = v else { return true };
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
let hash = *hash;
description_hash(&self.describe(v)) != hash
self.describe_hash(*o) != hash
}
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
@@ -3113,6 +3138,26 @@ impl Interp {
(None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())),
}
}
/// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read
/// along its strings without copying them.
fn describe_hash(&self, o: ObjId) -> u64 {
let data = |k: &str| match self.find_property(o, &key(k)) {
Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s),
_ => None,
};
let mut h = DescriptionHash::default();
match (data("name"), data("message")) {
(Some(n), Some(m)) if m.len() != 0 => {
n.for_each_chunk(|c| h.units(c));
h.text(": ");
m.for_each_chunk(|c| h.units(c));
}
(Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)),
(None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))),
}
h.finish()
}
}
/// A compile failure, before it becomes an exception or a run error.
+22
View File
@@ -204,6 +204,28 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() {
assert_eq!(got, want);
}
#[test]
fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() {
let mut r = realm();
r.run(
"var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\
var e; try { null.x; } catch (x) { e = x; }\n\
e.message = ab;\n\
Promise.reject(e);\n\
try { null.x; } catch (x) { Promise.reject(x); }",
)
.unwrap();
let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect();
assert_eq!(got.len(), 2);
assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true));
assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]);
let interp = r.interp();
match interp.find_property(interp.global, &crate::heap::key("ab")) {
Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"),
other => panic!("{other:?}"),
}
}
#[test]
fn a_rejection_handled_in_a_later_job_is_not_reported() {
let mut r = realm();
+15
View File
@@ -219,6 +219,21 @@ impl Str {
}
String::from_utf16_lossy(&units)
}
/// Calls `f` with each run of code units in order, read along the rope without flattening it.
pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) {
let mut stack = vec![self.clone()];
while let Some(s) = stack.pop() {
match &*s.0.borrow() {
Node::Flat(units) => f(units),
Node::Concat { left, right, .. } => {
stack.push(right.clone());
stack.push(left.clone());
}
Node::Taken => {}
}
}
}
}
impl PartialEq for Str {