From 10e30e593727775f9ae54aaceb9b485b00f87364 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Thu, 22 Jun 2017 14:10:05 +0300 Subject: [PATCH] N-API: Implement stricter wrapping Use a stronger criterion to identify objects in the prototype chain that store pointers to native data that were added by previous calls to `napi_wrap()`. Whereas the old criterion for identifying `napi_wrap()`-injected prototype chain objects was to consider an object with an internal field count of 1 to be such an object, the new criterion is to consider an object with an internal field count of 2 such that the second field holds a `v8::External` which itself contains a pointer to a global static string unique to N-API to be a `napi_wrap()`-injected prototype chain object. This greatly reduces the possibility of returning a pointer that was not previously added with `napi_wrap()`, and it allows us to recognize that an object has already undergone `napi_wrap()` and we can thus prevent a chain of wrappers only the first of which is accessible from appearing in the prototype chain, as would be the result of multiple calls to `napi_wrap()` using the same object. --- doc/api/n-api.md | 8 ++- src/node_api.cc | 64 +++++++++++++++----- test/addons-napi/test_general/test.js | 8 +++ test/addons-napi/test_general/test_general.c | 19 ++++++ 4 files changed, 83 insertions(+), 16 deletions(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index ac66f27035c7e1..aab13420aab35f 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -2876,8 +2876,8 @@ napi_status napi_wrap(napi_env env, Returns `napi_ok` if the API succeeded. -Wraps a native instance in JavaScript object of the corresponding type. -The native instance can be retrieved later using `napi_unwrap()`. +Wraps a native instance in a JavaScript object. The native instance can be +retrieved later using `napi_unwrap()`. When JavaScript code invokes a constructor for a class that was defined using `napi_define_class()`, the `napi_callback` for the constructor is invoked. @@ -2905,6 +2905,10 @@ required in order to enable correct proper of the reference. Afterward, additional manipulation of the wrapper's prototype chain may cause `napi_unwrap()` to fail. +*Note*: Calling `napi_wrap()` a second time on an object that already has a +native instance associated with it by virtue of a previous call to +`napi_wrap()` will cause an error to be returned. + ### *napi_unwrap*