@@ -42,6 +42,7 @@ struct napi_env__ {
42
42
v8::Persistent<v8::ObjectTemplate> function_data_template;
43
43
v8::Persistent<v8::ObjectTemplate> accessor_data_template;
44
44
napi_extended_error_info last_error;
45
+ int open_handle_scopes = 0 ;
45
46
};
46
47
47
48
#define ENV_OBJECT_TEMPLATE (env, prefix, destination, field_count ) \
@@ -499,12 +500,16 @@ class CallbackWrapperBase : public CallbackWrapper {
499
500
// Make sure any errors encountered last time we were in N-API are gone.
500
501
napi_clear_last_error (env);
501
502
503
+ int open_handle_scopes = env->open_handle_scopes ;
504
+
502
505
napi_value result = cb (env, cbinfo_wrapper);
503
506
504
507
if (result != nullptr ) {
505
508
this ->SetReturnValue (result);
506
509
}
507
510
511
+ CHECK_EQ (env->open_handle_scopes , open_handle_scopes);
512
+
508
513
if (!env->last_exception .IsEmpty ()) {
509
514
isolate->ThrowException (
510
515
v8::Local<v8::Value>::New (isolate, env->last_exception ));
@@ -2580,6 +2585,7 @@ napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) {
2580
2585
2581
2586
*result = v8impl::JsHandleScopeFromV8HandleScope (
2582
2587
new v8impl::HandleScopeWrapper (env->isolate ));
2588
+ env->open_handle_scopes ++;
2583
2589
return napi_clear_last_error (env);
2584
2590
}
2585
2591
@@ -2588,7 +2594,11 @@ napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) {
2588
2594
// JS exceptions.
2589
2595
CHECK_ENV (env);
2590
2596
CHECK_ARG (env, scope);
2597
+ if (env->open_handle_scopes == 0 ) {
2598
+ return napi_handle_scope_mismatch;
2599
+ }
2591
2600
2601
+ env->open_handle_scopes --;
2592
2602
delete v8impl::V8HandleScopeFromJsHandleScope (scope);
2593
2603
return napi_clear_last_error (env);
2594
2604
}
@@ -2603,6 +2613,7 @@ napi_status napi_open_escapable_handle_scope(
2603
2613
2604
2614
*result = v8impl::JsEscapableHandleScopeFromV8EscapableHandleScope (
2605
2615
new v8impl::EscapableHandleScopeWrapper (env->isolate ));
2616
+ env->open_handle_scopes ++;
2606
2617
return napi_clear_last_error (env);
2607
2618
}
2608
2619
@@ -2613,8 +2624,12 @@ napi_status napi_close_escapable_handle_scope(
2613
2624
// JS exceptions.
2614
2625
CHECK_ENV (env);
2615
2626
CHECK_ARG (env, scope);
2627
+ if (env->open_handle_scopes == 0 ) {
2628
+ return napi_handle_scope_mismatch;
2629
+ }
2616
2630
2617
2631
delete v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope (scope);
2632
+ env->open_handle_scopes --;
2618
2633
return napi_clear_last_error (env);
2619
2634
}
2620
2635
0 commit comments