@@ -457,8 +457,17 @@ void Environment::InitializeLibuv(bool start_profiler_idle_notifier) {
457457 // will be recorded with state=IDLE.
458458 uv_prepare_init (event_loop (), &idle_prepare_handle_);
459459 uv_check_init (event_loop (), &idle_check_handle_);
460+ uv_async_init (
461+ event_loop (),
462+ &cleanup_finalization_groups_async_,
463+ [](uv_async_t * async) {
464+ Environment* env = ContainerOf (
465+ &Environment::cleanup_finalization_groups_async_, async);
466+ env->CleanupFinalizationGroups ();
467+ });
460468 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_prepare_handle_));
461469 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_check_handle_));
470+ uv_unref (reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_));
462471
463472 thread_stopper ()->Install (
464473 this , static_cast <void *>(this ), [](uv_async_t * handle) {
@@ -521,6 +530,10 @@ void Environment::RegisterHandleCleanups() {
521530 reinterpret_cast <uv_handle_t *>(&idle_check_handle_),
522531 close_and_finish,
523532 nullptr );
533+ RegisterHandleCleanup (
534+ reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_),
535+ close_and_finish,
536+ nullptr );
524537}
525538
526539void Environment::CleanupHandles () {
@@ -1052,19 +1065,27 @@ void Environment::AddArrayBufferAllocatorToKeepAliveUntilIsolateDispose(
10521065 keep_alive_allocators_->insert (allocator);
10531066}
10541067
1055- bool Environment::RunWeakRefCleanup () {
1068+ void Environment::RunWeakRefCleanup () {
10561069 isolate ()->ClearKeptObjects ();
1070+ }
10571071
1058- while (!cleanup_finalization_groups_.empty ()) {
1072+ void Environment::CleanupFinalizationGroups () {
1073+ HandleScope handle_scope (isolate ());
1074+ Context::Scope context_scope (context ());
1075+ TryCatchScope try_catch (this );
1076+
1077+ while (!cleanup_finalization_groups_.empty () && can_call_into_js ()) {
10591078 Local<FinalizationGroup> fg =
10601079 cleanup_finalization_groups_.front ().Get (isolate ());
10611080 cleanup_finalization_groups_.pop_front ();
10621081 if (!FinalizationGroup::Cleanup (fg).FromMaybe (false )) {
1063- return false ;
1082+ if (try_catch.HasCaught () && !try_catch.HasTerminated ())
1083+ errors::TriggerUncaughtException (isolate (), try_catch);
1084+ // Re-schedule the execution of the remainder of the queue.
1085+ uv_async_send (&cleanup_finalization_groups_async_);
1086+ return ;
10641087 }
10651088 }
1066-
1067- return true ;
10681089}
10691090
10701091void AsyncRequest::Install (Environment* env, void * data, uv_async_cb target) {
0 commit comments