Skip to content

Truly independent web browser

LibJS: Remember where the last exception was thrown

Shannon Booth2c91f0adb999
diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cpp
index abf03dca56d..f6f261e415e 100644
--- a/Libraries/LibJS/Runtime/VM.cpp
+++ b/Libraries/LibJS/Runtime/VM.cpp
@@ -507,6 +507,13 @@ Vector<StackTraceElement> VM::stack_trace() const
return stack_trace;
}
+Optional<SourceRange> VM::take_throw_site_of(Value value)
+{
+ auto throw_site = source_range_from_abi(js_vm_throw_site_of(vm_abi(*this), value_to_abi(value)));
+ js_vm_forget_throw_site_of(vm_abi(*this), value_to_abi(value));
+ return throw_site;
+}
+
ThrowCompletionOr<GC::Ptr<Environment>> VM::resolve_binding(Utf16FlyString const& name, Strict strict, GC::Ptr<Environment> environment)
{
// 1. If env is not present or if env is undefined, then
diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.h
index edf6724ed20..8a2906f8d33 100644
--- a/Libraries/LibJS/Runtime/VM.h
+++ b/Libraries/LibJS/Runtime/VM.h
@@ -451,6 +451,10 @@ public:
// The frames of the execution context stack from the running one down, with where in its source code each one is.
[[nodiscard]] Vector<StackTraceElement> stack_trace() const;
+ // Where the given value was thrown, if it is the last exception thrown. Only one report may take the location of a
+ // throw.
+ [[nodiscard]] Optional<SourceRange> take_throw_site_of(Value);
+
private:
friend class InterpreterStack;
friend struct HostHookThunks;
diff --git a/Libraries/LibJS/Rust/src/embedding/debugger.rs b/Libraries/LibJS/Rust/src/embedding/debugger.rs
index ff0707110ed..1e384a425ab 100644
--- a/Libraries/LibJS/Rust/src/embedding/debugger.rs
+++ b/Libraries/LibJS/Rust/src/embedding/debugger.rs
@@ -145,7 +145,7 @@ pub(crate) fn stack_frame_into_abi(element: &StackTraceElement) -> JSDebuggerSta
}
}
-fn source_range_into_abi(source_range: Option<&SourceRange>) -> JSDebuggerSourceRange {
+pub(crate) fn source_range_into_abi(source_range: Option<&SourceRange>) -> JSDebuggerSourceRange {
source_range.map_or(
JSDebuggerSourceRange {
source_code: core::ptr::null(),
diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rs
index 466704b80be..d9354341fdd 100644
--- a/Libraries/LibJS/Rust/src/embedding/vm.rs
+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs
@@ -9,8 +9,12 @@
use core::ffi::c_void;
use core::ptr::NonNull;
-use crate::embedding::abi_types::{JSRealm, cell_from_abi, completion_into_abi, optional_cell_from_abi, vm_from_abi};
-use crate::embedding::debugger::{JSDebuggerStackFrame, stack_frame_into_abi};
+use crate::embedding::abi_types::{
+ JSRealm, cell_from_abi, completion_into_abi, optional_cell_from_abi, value_from_abi, vm_from_abi,
+};
+use crate::embedding::debugger::{
+ JSDebuggerSourceRange, JSDebuggerStackFrame, source_range_into_abi, stack_frame_into_abi,
+};
use crate::embedding::hooks::{
Embedder, EmbedderAgent, JSAgent, JSImportedModulePayload, JSImportedModuleReferrer, JSModuleRequest, JSPromiseJob,
JSVmHostHooks, imported_module_payload_from_abi, imported_module_referrer_from_abi, install_embedder,
@@ -133,6 +137,31 @@ pub unsafe extern "C" fn js_vm_did_reach_stack_space_limit(vm: *mut JSVM) -> boo
unsafe { vm_from_abi(vm) }.did_reach_stack_space_limit()
}
+/// VM::take_throw_site_of(): where `value` was thrown, or no source code if it is not the last exception thrown. The VM
+/// keeps the source code alive until it forgets the throw. Only the VM's thread may call this.
+///
+/// # Safety
+///
+/// `vm` must be a live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_vm_throw_site_of(vm: *mut JSVM, value: JSValue) -> JSDebuggerSourceRange {
+ // SAFETY: The caller passes a live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ source_range_into_abi(vm.throw_site_of(value_from_abi(value)).as_ref())
+}
+
+/// VM::take_throw_site_of(): forgets where `value` was thrown, if it is the last exception thrown. Only the VM's thread
+/// may call this.
+///
+/// # Safety
+///
+/// `vm` must be a live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_vm_forget_throw_site_of(vm: *mut JSVM, value: JSValue) {
+ // SAFETY: The caller passes a live VM.
+ unsafe { vm_from_abi(vm) }.forget_throw_site_of(value_from_abi(value));
+}
+
/// Receives each StackTraceElement of a stack trace, which lives for the call.
#[repr(C)]
pub struct JSStackTraceSink {
diff --git a/Libraries/LibJS/Rust/src/interpreter/run.rs b/Libraries/LibJS/Rust/src/interpreter/run.rs
index 90ef04e0f0c..f45bcbef50e 100644
--- a/Libraries/LibJS/Rust/src/interpreter/run.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/run.rs
@@ -579,6 +579,12 @@ impl Vm {
/// Unwinds to the innermost handler of an exception thrown at `program_counter` in the running frame, leaving
/// frames the interpreter entered without returning to the runtime.
pub fn handle_exception(&self, mut program_counter: u32, exception: Value) -> HandleExceptionResponse {
+ // An exception that unwinds out to a native caller enters here again in the frame that called it, so remember
+ // only where it was first thrown.
+ if !self.is_last_throw(exception) {
+ self.did_throw(exception, program_counter);
+ }
+
if let Some(debugger) = self.debugger() {
let mut exception_will_be_caught = false;
// The caller frame and return offset of the previous frame that runs an executable.
@@ -627,10 +633,11 @@ impl Vm {
if let Some(handler) = executable.exception_handlers_for_offset(program_counter) {
context.register(register::EXCEPTION).set(exception);
context.program_counter.set(handler.handler_offset);
- if handler.catches_exception
- && let Some(debugger) = self.debugger()
- {
- debugger.did_finish_exception_propagation(exception);
+ if handler.catches_exception {
+ self.forget_throw_site_of(exception);
+ if let Some(debugger) = self.debugger() {
+ debugger.did_finish_exception_propagation(exception);
+ }
}
return HandleExceptionResponse::ContinueInThisExecutable;
}
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
index 51441e9cc91..63e06db0530 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
@@ -1464,6 +1464,8 @@ impl RuntimeFunctions for Runtime {
}
fn throw(vm: &Vm, pc: u32, _instruction: &op::Throw, values: &mut op::ThrowValues) -> SlowPathControl {
+ // A throw statement throws its value anew, even one that was thrown before and never caught by a catch clause.
+ vm.did_throw(values.src, pc);
handle_asm_exception(vm, pc, values.src)
}
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index f2c5af6c263..8e1f46844fc 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -322,6 +322,12 @@ pub struct LoadedModules {
define_cell!(LoadedModules, Other);
+/// An exception, and where in its source code the instruction that threw it is.
+struct ThrowSite {
+ value: Value,
+ source_range: Option<SourceRange>,
+}
+
/// HostResizeArrayBuffer, which hosts may override.
pub type HostResizeArrayBuffer = fn(&Vm, &ArrayBuffer, usize) -> ThrowCompletionOr<HandledByHost>;
@@ -586,6 +592,9 @@ pub struct Vm {
intrinsic_accessors: RefCell<IntrinsicAccessorMap>,
/// The debugger, which the head points to while it is attached.
debugger: RefCell<Option<Box<Debugger>>>,
+ /// The last exception thrown, and where. A thrown value that is not an Error carries no location of its own, and
+ /// its frames are gone by the time the embedder reports it.
+ last_throw: RefCell<Option<ThrowSite>>,
/// The properties defined with Object::define_unimplemented_property. The objects are weak: the sweep callback
/// forgets the ones that die.
unimplemented_properties: RefCell<UnimplementedPropertyMap>,
@@ -728,6 +737,7 @@ impl Vm {
next_private_environment_id: Cell::new(1),
intrinsic_accessors: RefCell::new(HashMap::default()),
debugger: RefCell::new(None),
+ last_throw: RefCell::new(None),
unimplemented_properties: RefCell::new(HashMap::default()),
on_unimplemented_property_access: Cell::new(None),
options,
@@ -1088,6 +1098,9 @@ impl Vm {
if let Some(debugger) = self.debugger.borrow().as_ref() {
debugger.trace(visitor);
}
+ if let Some(throw_site) = self.last_throw.borrow().as_ref() {
+ throw_site.value.trace(visitor);
+ }
}
pub fn enable_debugging(&self) {
@@ -1295,6 +1308,40 @@ impl Vm {
self.head.type_error_realm_override_depth.set(previous.depth);
}
+ /// Remembers that the running executable's instruction at `program_counter` threw `value`.
+ pub fn did_throw(&self, value: Value, program_counter: u32) {
+ *self.last_throw.borrow_mut() = Some(ThrowSite {
+ value,
+ source_range: self.current_executable().source_range_at(program_counter),
+ });
+ }
+
+ /// Whether `value` is the last exception thrown.
+ pub fn is_last_throw(&self, value: Value) -> bool {
+ self.last_throw
+ .borrow()
+ .as_ref()
+ .is_some_and(|throw_site| throw_site.value == value)
+ }
+
+ /// Forgets where `value` was thrown once a catch clause catches it or a report takes its location, so that reporting
+ /// an equal value later does not take its location from this throw.
+ pub fn forget_throw_site_of(&self, value: Value) {
+ let mut last_throw = self.last_throw.borrow_mut();
+ if last_throw.as_ref().is_some_and(|throw_site| throw_site.value == value) {
+ *last_throw = None;
+ }
+ }
+
+ /// Where `value` was thrown, if it is the last exception thrown.
+ pub fn throw_site_of(&self, value: Value) -> Option<SourceRange> {
+ self.last_throw
+ .borrow()
+ .as_ref()
+ .filter(|throw_site| throw_site.value == value)
+ .and_then(|throw_site| throw_site.source_range.clone())
+ }
+
/// The frames of every execution context, from the running one down, with where each is in its executable.
pub fn stack_trace(&self) -> MarkedVec<'_, StackTraceElement> {
let stack_trace = MarkedVec::new(self);
diff --git a/Libraries/LibJS/Rust/src/runtime/promise.rs b/Libraries/LibJS/Rust/src/runtime/promise.rs
index 52487ea2973..16f6c32cec8 100644
--- a/Libraries/LibJS/Rust/src/runtime/promise.rs
+++ b/Libraries/LibJS/Rust/src/runtime/promise.rs
@@ -304,6 +304,9 @@ impl Promise {
pub fn reject_function_steps(vm: &Vm, promise: Gc<Promise>, already_resolved: &Cell<bool>) -> Value {
let reason = vm.argument(0);
+ // NB: An exception that rejects a promise is no longer thrown, even when the promise is already resolved.
+ vm.forget_throw_site_of(reason);
+
// 1. Let F be the active function object.
// 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
// 3. Let promise be F.[[Promise]].
@@ -351,6 +354,9 @@ impl Promise {
// 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
pub fn reject(&self, vm: &Vm, reason: Value) {
+ // NB: An exception that rejects a promise is no longer thrown.
+ vm.forget_throw_site_of(reason);
+
// 1. Assert: The value of promise.[[PromiseState]] is pending.
assert!(self.state.get() == PromiseState::Pending);