Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(v8): preserve weak handles through isolate teardown

ldm033a26f4622d0
diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rs
index 17a0a1322..94ba8750e 100644
--- a/moli-renderer-v8/src/script_vm/document_isolate.rs
+++ b/moli-renderer-v8/src/script_vm/document_isolate.rs
@@ -740,6 +740,22 @@ mod tests {
}
}
+ struct ContextSlotDropProbe {
+ dropped: Rc<Cell<usize>>,
+ isolate_handle_was_live: Rc<Cell<usize>>,
+ isolate_handle: v8::IsolateHandle,
+ }
+
+ impl Drop for ContextSlotDropProbe {
+ fn drop(&mut self) {
+ self.dropped.set(self.dropped.get().saturating_add(1));
+ if self.isolate_handle.cancel_terminate_execution() {
+ self.isolate_handle_was_live
+ .set(self.isolate_handle_was_live.get().saturating_add(1));
+ }
+ }
+ }
+
#[test]
fn context_annex_weak_handles_are_safe_during_isolate_teardown() {
crate::ensure_v8_for_test();
@@ -747,17 +763,22 @@ mod tests {
const ISOLATE_COUNT: usize = 4;
const CONTEXTS_PER_ISOLATE: usize = 32;
let dropped_slots = Rc::new(Cell::new(0));
+ let slots_dropped_with_live_isolate = Rc::new(Cell::new(0));
for _ in 0..ISOLATE_COUNT {
let mut isolate = v8::Isolate::new(Default::default());
+ let isolate_handle = isolate.thread_safe_handle();
let mut contexts = Vec::with_capacity(CONTEXTS_PER_ISOLATE);
{
let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
for _ in 0..CONTEXTS_PER_ISOLATE {
let context = v8::Context::new(scope, Default::default());
- let replaced = context
- .set_slot(Rc::new(ContextSlotDropCounter(Rc::clone(&dropped_slots))));
+ let replaced = context.set_slot(Rc::new(ContextSlotDropProbe {
+ dropped: Rc::clone(&dropped_slots),
+ isolate_handle_was_live: Rc::clone(&slots_dropped_with_live_isolate),
+ isolate_handle: isolate_handle.clone(),
+ }));
assert!(replaced.is_none());
contexts.push(v8::Global::new(scope, context));
}
@@ -769,6 +790,11 @@ mod tests {
}
assert_eq!(dropped_slots.get(), ISOLATE_COUNT * CONTEXTS_PER_ISOLATE);
+ assert_eq!(
+ slots_dropped_with_live_isolate.get(),
+ ISOLATE_COUNT * CONTEXTS_PER_ISOLATE,
+ "context annex slots must drop while their weak V8 handles can still be reset"
+ );
}
#[test]
diff --git a/vendor/v8-152.2.0/MOLI_VENDORING.md b/vendor/v8-152.2.0/MOLI_VENDORING.md
index 385f8393e..d2cfb2050 100644
--- a/vendor/v8-152.2.0/MOLI_VENDORING.md
+++ b/vendor/v8-152.2.0/MOLI_VENDORING.md
@@ -43,6 +43,9 @@ Version-specific corrections:
context-annex finalizers before disposing the isolate handle. This lets their
`Weak` globals reset while V8 is live and prevents unserialized native-context
handles from reaching `SnapshotCreator::CreateBlob()`.
+- ordinary isolate teardown uses the same ordering before V8's final teardown
+ GC. Weak handles also retain their callback data until V8's second pass has
+ run, even when the guaranteed-finalizer map is being drained.
- ordinary isolate teardown and snapshot-creator teardown are covered by
`context_annex_weak_handles_are_safe_during_isolate_teardown` and
`snapshot_creator_cleans_up_context_annex_before_creating_blob` in
diff --git a/vendor/v8-152.2.0/src/handle.rs b/vendor/v8-152.2.0/src/handle.rs
index 039bde074..ea535fd60 100644
--- a/vendor/v8-152.2.0/src/handle.rs
+++ b/vendor/v8-152.2.0/src/handle.rs
@@ -856,6 +856,7 @@ impl<T> Weak<T> {
let weak_data = Box::new(WeakData {
pointer: Default::default(),
finalizer_id,
+ second_pass_called: Cell::new(false),
weak_dropped: Cell::new(false),
});
let data = data.cast().as_ptr();
@@ -976,21 +977,10 @@ impl<T> Weak<T> {
/// GC'd.
pub fn into_raw(mut self) -> Option<NonNull<WeakData<T>>> {
if let Some(data) = self.data.take() {
- let has_finalizer = if let Some(finalizer_id) = data.finalizer_id {
- // SAFETY: We're in the isolate's thread because Weak isn't Send or Sync
- let isolate_ptr = unsafe { self.isolate_handle.get_isolate_ptr() };
- if isolate_ptr.is_null() {
- // Disposed isolates have no finalizers.
- false
- } else {
- let isolate = unsafe { Isolate::from_raw_ptr(isolate_ptr) };
- isolate.get_finalizer_map().map.contains_key(&finalizer_id)
- }
- } else {
- false
- };
+ let second_pass_pending =
+ data.finalizer_id.is_some() && !data.second_pass_called.get();
- if data.pointer.get().is_none() && !has_finalizer {
+ if data.pointer.get().is_none() && !second_pass_pending {
// If the pointer is None and we're not waiting for the second pass,
// drop the box and release its count. A `Some(raw)` return keeps the
// count until `from_raw` re-adopts the box and the resulting `Weak`
@@ -1100,6 +1090,7 @@ impl<T> Weak<T> {
let ptr = v8__WeakCallbackInfo__GetParameter(wci);
&*(ptr as *mut WeakData<T>)
};
+ weak_data.second_pass_called.set(true);
let mut isolate = unsafe { Isolate::from_raw_ptr(isolate) };
let finalizer: Option<FinalizerCallback> = {
@@ -1163,10 +1154,14 @@ impl<T> Drop for Weak<T> {
unsafe { v8__Global__Reset(data.cast().as_ptr()) };
remove_finalizer(self.data.as_ref().unwrap().finalizer_id);
} else if let Some(weak_data) = self.data.take() {
- // The second pass callback removes the finalizer, so if there is one,
- // the second pass hasn't yet run, and WeakData will have to be alive.
- // In that case we leak the WeakData but remove the finalizer.
- if remove_finalizer(weak_data.finalizer_id) {
+ // A guaranteed finalizer is removed from the isolate map before its
+ // callback runs. Track second-pass completion on WeakData itself so a
+ // Weak dropped by that callback cannot free the parameter V8 still owns.
+ let second_pass_pending = weak_data.pointer.get().is_none()
+ && weak_data.finalizer_id.is_some()
+ && !weak_data.second_pass_called.get();
+ remove_finalizer(weak_data.finalizer_id);
+ if second_pass_pending {
weak_data.weak_dropped.set(true);
Box::leak(weak_data);
}
@@ -1225,6 +1220,7 @@ where
pub struct WeakData<T> {
pointer: Cell<Option<NonNull<T>>>,
finalizer_id: Option<FinalizerId>,
+ second_pass_called: Cell<bool>,
weak_dropped: Cell<bool>,
}
diff --git a/vendor/v8-152.2.0/src/isolate.rs b/vendor/v8-152.2.0/src/isolate.rs
index 93ace61a8..872ecbce3 100644
--- a/vendor/v8-152.2.0/src/isolate.rs
+++ b/vendor/v8-152.2.0/src/isolate.rs
@@ -1123,14 +1123,12 @@ impl Isolate {
self.set_data_internal(Self::ANNEX_SLOT, annex_ptr as *mut _);
}
- /// Prepare annex teardown while keeping `ANNEX_SLOT` pointing at the annex.
+ /// Prepare annex teardown while keeping both the annex and isolate live.
///
- /// Nulls the `IsolateHandle`'s inner pointer, reclaims
- /// `create_param_allocations`, and drops the slot storage. The annex
- /// allocation itself stays alive and `ANNEX_SLOT` keeps pointing at it,
- /// so code that runs during the subsequent V8 teardown GC (weak
- /// callbacks, guaranteed finalizers, embedder slot drops) can still
- /// resolve the annex through `get_annex()` / `get_annex_mut()`.
+ /// Reclaims `create_param_allocations` and drops the slot storage. The
+ /// isolate remains reachable through its liveness handles until
+ /// [`Self::mark_annex_isolate_disposed`] is called, because slot destructors
+ /// and guaranteed finalizers may need to reset V8 handles.
///
/// The returned pointer must be passed exactly once to
/// [`Self::finish_annex_dispose`] (or, on the snapshot path, dropped by
@@ -1155,20 +1153,6 @@ impl Isolate {
// `get_annex()`. An outer `&mut IsolateAnnex` held across that
// re-entry would alias the shared borrow they obtain.
- // SAFETY: `annex_ptr` is non-null and points at a live `IsolateAnnex`
- // (ANNEX_SLOT is only cleared by code further down this teardown
- // path).
- unsafe {
- // Release Globals dropped by threads that could not touch the
- // isolate, then null the `IsolateHandle` so handles outliving the
- // isolate see a disposed state.
- (*annex_ptr)
- .global_liveness()
- .close_deferred_global_resets();
- (*annex_ptr).global_liveness().dispose();
- (*annex_ptr).isolate_handle.dispose();
- }
-
// Reclaim `create_param_allocations` so the caller can keep it alive
// for as long as V8 needs (during snapshot blob creation, V8 reads
// external references out of it).
@@ -1184,6 +1168,29 @@ impl Isolate {
(annex_ptr, create_param_allocations)
}
+ /// Close deferred resets and make all liveness handles observe disposal.
+ ///
+ /// This phase must run only after Rust-owned slots and guaranteed
+ /// finalizers have dropped their V8 handles, and before C++ starts the final
+ /// isolate teardown.
+ ///
+ /// # Safety
+ ///
+ /// `annex_ptr` must point at this isolate's live annex. The caller must be
+ /// allowed to reset globals, or must already have closed the deferred reset
+ /// queue while holding the shared isolate's lock.
+ pub(crate) unsafe fn mark_annex_isolate_disposed(
+ annex_ptr: *mut IsolateAnnex,
+ ) {
+ unsafe {
+ (*annex_ptr)
+ .global_liveness()
+ .close_deferred_global_resets();
+ (*annex_ptr).global_liveness().dispose();
+ (*annex_ptr).isolate_handle.dispose();
+ }
+ }
+
/// Drain `finalizer_map` and invoke any guaranteed finalizers.
///
/// New finalizers registered by the running callbacks land in the
@@ -1251,13 +1258,7 @@ impl Isolate {
// what lets `Weak::drop` reset the corresponding V8 global handle.
unsafe { Self::run_remaining_guaranteed_finalizers(annex_ptr) };
- unsafe {
- (*annex_ptr)
- .global_liveness()
- .close_deferred_global_resets();
- (*annex_ptr).global_liveness().dispose();
- (*annex_ptr).isolate_handle.dispose();
- }
+ unsafe { Self::mark_annex_isolate_disposed(annex_ptr) };
let create_param_allocations =
unsafe { (*annex_ptr).create_param_allocations.take().unwrap() };
@@ -1306,10 +1307,6 @@ impl Isolate {
assert!(prev.is_none());
}
- pub(crate) fn get_finalizer_map(&self) -> &FinalizerMap {
- &self.get_annex().finalizer_map
- }
-
pub(crate) fn get_finalizer_map_mut(&mut self) -> &mut FinalizerMap {
&mut self.get_annex_mut().finalizer_map
}
@@ -2939,6 +2936,7 @@ impl Drop for OwnedIsolate {
// teardown GC has a chance to fire weak callbacks that need the
// annex.
Isolate::run_remaining_guaranteed_finalizers(annex_ptr);
+ Isolate::mark_annex_isolate_disposed(annex_ptr);
Platform::notify_isolate_shutdown(&get_current_platform(), self);
// V8's final teardown runs here. `ANNEX_SLOT` still references the
// (drained) annex, so any re-entrant access from weak callbacks or
diff --git a/vendor/v8-152.2.0/src/locker.rs b/vendor/v8-152.2.0/src/locker.rs
index f283e54f1..a8f5cecf8 100644
--- a/vendor/v8-152.2.0/src/locker.rs
+++ b/vendor/v8-152.2.0/src/locker.rs
@@ -199,6 +199,7 @@ impl Drop for SharedIsolateInner {
let (annex_ptr, _create_param_allocations) =
isolate.prepare_annex_for_dispose();
Isolate::run_remaining_guaranteed_finalizers(annex_ptr);
+ Isolate::mark_annex_isolate_disposed(annex_ptr);
crate::Platform::notify_isolate_shutdown(
&crate::V8::get_current_platform(),
&isolate,