@@ -460,8 +460,17 @@ void Environment::InitializeLibuv(bool start_profiler_idle_notifier) {
460460 // will be recorded with state=IDLE.
461461 uv_prepare_init (event_loop (), &idle_prepare_handle_);
462462 uv_check_init (event_loop (), &idle_check_handle_);
463+ uv_async_init (
464+ event_loop (),
465+ &cleanup_finalization_groups_async_,
466+ [](uv_async_t * async) {
467+ Environment* env = ContainerOf (
468+ &Environment::cleanup_finalization_groups_async_, async);
469+ env->CleanupFinalizationGroups ();
470+ });
463471 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_prepare_handle_));
464472 uv_unref (reinterpret_cast <uv_handle_t *>(&idle_check_handle_));
473+ uv_unref (reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_));
465474
466475 thread_stopper ()->Install (
467476 this , static_cast <void *>(this ), [](uv_async_t * handle) {
@@ -524,6 +533,10 @@ void Environment::RegisterHandleCleanups() {
524533 reinterpret_cast <uv_handle_t *>(&idle_check_handle_),
525534 close_and_finish,
526535 nullptr );
536+ RegisterHandleCleanup (
537+ reinterpret_cast <uv_handle_t *>(&cleanup_finalization_groups_async_),
538+ close_and_finish,
539+ nullptr );
527540}
528541
529542void Environment::CleanupHandles () {
@@ -1040,19 +1053,27 @@ char* Environment::Reallocate(char* data, size_t old_size, size_t size) {
10401053 return new_data;
10411054}
10421055
1043- bool Environment::RunWeakRefCleanup () {
1056+ void Environment::RunWeakRefCleanup () {
10441057 isolate ()->ClearKeptObjects ();
1058+ }
10451059
1046- while (!cleanup_finalization_groups_.empty ()) {
1060+ void Environment::CleanupFinalizationGroups () {
1061+ HandleScope handle_scope (isolate ());
1062+ Context::Scope context_scope (context ());
1063+ TryCatchScope try_catch (this );
1064+
1065+ while (!cleanup_finalization_groups_.empty () && can_call_into_js ()) {
10471066 Local<FinalizationGroup> fg =
10481067 cleanup_finalization_groups_.front ().Get (isolate ());
10491068 cleanup_finalization_groups_.pop_front ();
10501069 if (!FinalizationGroup::Cleanup (fg).FromMaybe (false )) {
1051- return false ;
1070+ if (try_catch.HasCaught () && !try_catch.HasTerminated ())
1071+ errors::TriggerUncaughtException (isolate (), try_catch);
1072+ // Re-schedule the execution of the remainder of the queue.
1073+ uv_async_send (&cleanup_finalization_groups_async_);
1074+ return ;
10521075 }
10531076 }
1054-
1055- return true ;
10561077}
10571078
10581079void AsyncRequest::Install (Environment* env, void * data, uv_async_cb target) {
0 commit comments