From 99fc87e07042bcc23bf09bf1b05ca9c730b91e88 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. PR-URL: https://github.com/nodejs/node/pull/13872 Reviewed-By: James M Snell Reviewed-By: Michael Dawson Reviewed-By: Timothy Gu --- 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 b35a99f5c46021..8063eaf7348dc0 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*