diff --git a/src/node_api.cc b/src/node_api.cc index 196f5512c9cd0f..ec477e1d23c92a 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -448,10 +448,25 @@ class Reference : private Finalizer { } private: + // The N-API finalizer callback may make calls into the engine. V8's heap is + // not in a consistent state during the weak callback, and therefore it does + // not support calls back into it. However, it provides a mechanism for adding + // a finalizer which may make calls back into the engine by allowing us to + // attach such a second-pass finalizer from the first pass finalizer. Thus, + // we do that here to ensure that the N-API finalizer callback is free to call + // into the engine. static void FinalizeCallback(const v8::WeakCallbackInfo& data) { Reference* reference = data.GetParameter(); + + // The reference must be reset during the first pass. reference->_persistent.Reset(); + data.SetSecondPassCallback(SecondPassCallback); + } + + static void SecondPassCallback(const v8::WeakCallbackInfo& data) { + Reference* reference = data.GetParameter(); + // Check before calling the finalize callback, because the callback might // delete it. bool delete_self = reference->_delete_self;