Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(napi): Make napi_wrap work on regular objects #15622

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 76 additions & 58 deletions src/bun.js/bindings/napi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,21 @@ extern "C" void napi_module_register(napi_module* mod)
globalObject->m_pendingNapiModuleAndExports[1].set(vm, globalObject, object);
}

static inline NapiRef* getWrapContentsIfExists(VM& vm, JSGlobalObject* globalObject, JSObject* object)
{
if (auto* napi_instance = jsDynamicCast<NapiPrototype*>(object)) {
return napi_instance->napiRef;
} else {
JSValue contents = object->getDirect(vm, WebCore::builtinNames(vm).napiWrappedContentsPrivateName());
if (contents.isEmpty()) {
return nullptr;
} else {
// jsCast asserts: we should not have stored anything but a NapiExternal here
return static_cast<NapiRef*>(jsCast<Bun::NapiExternal*>(contents)->value());
}
}
}

extern "C" napi_status napi_wrap(napi_env env,
napi_value js_object,
void* native_object,
Expand All @@ -1039,50 +1054,46 @@ extern "C" napi_status napi_wrap(napi_env env,
{
NAPI_PREMABLE

JSValue value = toJS(js_object);
if (!value || value.isUndefinedOrNull()) {
return napi_object_expected;
}

auto* globalObject = toJS(env);

NapiRef** refPtr = nullptr;
if (auto* val = jsDynamicCast<NapiPrototype*>(value)) {
refPtr = &val->napiRef;
} else if (auto* val = jsDynamicCast<NapiClass*>(value)) {
refPtr = &val->napiRef;
auto& vm = globalObject->vm();
JSValue jsc_value = toJS(js_object);
if (jsc_value.isEmpty()) {
return napi_invalid_arg;
}

if (!refPtr) {
JSObject* jsc_object = jsc_value.getObject();
if (!jsc_object) {
return napi_object_expected;
}

if (*refPtr) {
// Calling napi_wrap() a second time on an object will return an error.
// To associate another native instance with the object, use
// napi_remove_wrap() first.
// NapiPrototype has an inline field to store a napi_ref, so we use that if we can
auto* napi_instance = jsDynamicCast<NapiPrototype*>(jsc_object);

const JSC::Identifier& propertyName = WebCore::builtinNames(vm).napiWrappedContentsPrivateName();

if (getWrapContentsIfExists(vm, globalObject, jsc_object)) {
// already wrapped
return napi_invalid_arg;
}

// create a new weak reference (refcount 0)
auto* ref = new NapiRef(globalObject, 0);
ref->weakValueRef.set(jsc_value, weakValueHandleOwner(), ref);

ref->weakValueRef.set(value, weakValueHandleOwner(), ref);
ref->finalizer.finalize_cb = finalize_cb;
ref->finalizer.finalize_hint = finalize_hint;
ref->data = native_object;

if (finalize_cb) {
ref->finalizer.finalize_cb = finalize_cb;
ref->finalizer.finalize_hint = finalize_hint;
}

if (native_object) {
ref->data = native_object;
if (napi_instance) {
napi_instance->napiRef = ref;
} else {
// wrap the ref in an external so that it can serve as a JSValue
auto* external = Bun::NapiExternal::create(globalObject->vm(), globalObject->NapiExternalStructure(), ref, nullptr, nullptr);
jsc_object->putDirect(vm, propertyName, JSValue(external));
}

*refPtr = ref;

if (result) {
*result = toNapi(ref);
}

return napi_ok;
}

Expand All @@ -1091,35 +1102,41 @@ extern "C" napi_status napi_remove_wrap(napi_env env, napi_value js_object,
{
NAPI_PREMABLE

JSValue value = toJS(js_object);
if (!value || value.isUndefinedOrNull()) {
JSValue jsc_value = toJS(js_object);
if (jsc_value.isEmpty()) {
return napi_invalid_arg;
}
JSObject* jsc_object = jsc_value.getObject();
if (!js_object) {
return napi_object_expected;
}
// may be null
auto* napi_instance = jsDynamicCast<NapiPrototype*>(jsc_object);

NapiRef** refPtr = nullptr;
if (auto* val = jsDynamicCast<NapiPrototype*>(value)) {
refPtr = &val->napiRef;
} else if (auto* val = jsDynamicCast<NapiClass*>(value)) {
refPtr = &val->napiRef;
}
auto* globalObject = toJS(env);
auto& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
NapiRef* ref = getWrapContentsIfExists(vm, globalObject, jsc_object);

if (!refPtr) {
return napi_object_expected;
if (!ref) {
return napi_invalid_arg;
}

if (!(*refPtr)) {
// not sure if this should succeed or return an error
return napi_ok;
if (napi_instance) {
napi_instance->napiRef = nullptr;
} else {
const JSC::Identifier& propertyName = WebCore::builtinNames(vm).napiWrappedContentsPrivateName();
jsc_object->deleteProperty(globalObject, propertyName);
}

auto* ref = *refPtr;
*refPtr = nullptr;

if (result) {
*result = ref->data;
}
delete ref;
ref->finalizer.finalize_cb = nullptr;

// don't delete the ref: if weak, it'll delete itself when the JS object is deleted;
// if strong, native addon needs to clean it up.
// the external is garbage collected.
return napi_ok;
}

Expand All @@ -1128,23 +1145,24 @@ extern "C" napi_status napi_unwrap(napi_env env, napi_value js_object,
{
NAPI_PREMABLE

JSValue value = toJS(js_object);

if (!value.isObject()) {
return NAPI_OBJECT_EXPECTED;
JSValue jsc_value = toJS(js_object);
if (jsc_value.isEmpty()) {
return napi_invalid_arg;
}
JSObject* jsc_object = jsc_value.getObject();
if (!jsc_object) {
return napi_object_expected;
}

NapiRef* ref = nullptr;
if (auto* val = jsDynamicCast<NapiPrototype*>(value)) {
ref = val->napiRef;
} else if (auto* val = jsDynamicCast<NapiClass*>(value)) {
ref = val->napiRef;
} else {
ASSERT(false);
auto* globalObject = toJS(env);
auto& vm = globalObject->vm();
NapiRef* ref = getWrapContentsIfExists(vm, globalObject, jsc_object);
if (!ref) {
return napi_invalid_arg;
}

if (ref && result) {
*result = ref ? ref->data : nullptr;
if (result) {
*result = ref->data;
}

return napi_ok;
Expand Down
1 change: 1 addition & 0 deletions src/js/builtins/BunBuiltinNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ using namespace JSC;
macro(writing) \
macro(written) \
macro(napiDlopenHandle) \
macro(napiWrappedContents) \
BUN_ADDITIONAL_BUILTIN_NAMES(macro)
// --- END of BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME ---

Expand Down
Binary file modified test/bun.lockb
Binary file not shown.
175 changes: 175 additions & 0 deletions test/js/third_party/@napi-rs/canvas/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore

# Logs

logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Caches

.cache

# Diagnostic reports (https://nodejs.org/api/report.html)

report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

# Runtime data

pids
_.pid
_.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover

lib-cov

# Coverage directory used by tools like istanbul

coverage
*.lcov

# nyc test coverage

.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)

.grunt

# Bower dependency directory (https://bower.io/)

bower_components

# node-waf configuration

.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)

build/Release

# Dependency directories

node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)

web_modules/

# TypeScript cache

*.tsbuildinfo

# Optional npm cache directory

.npm

# Optional eslint cache

.eslintcache

# Optional stylelint cache

.stylelintcache

# Microbundle cache

.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history

.node_repl_history

# Output of 'npm pack'

*.tgz

# Yarn Integrity file

.yarn-integrity

# dotenv environment variable files

.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)

.parcel-cache

# Next.js build output

.next
out

# Nuxt.js build / generate output

.nuxt
dist

# Gatsby files

# Comment in the public line in if your project uses Gatsby and not Next.js

# https://nextjs.org/blog/next-9-1#public-directory-support

# public

# vuepress build output

.vuepress/dist

# vuepress v2.x temp and cache directory

.temp

# Docusaurus cache and generated files

.docusaurus

# Serverless directories

.serverless/

# FuseBox cache

.fusebox/

# DynamoDB Local files

.dynamodb/

# TernJS port file

.tern-port

# Stores VSCode versions used for testing VSCode extensions

.vscode-test

# yarn v2

.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# IntelliJ based IDEs
.idea

# Finder (MacOS) folder config
.DS_Store
Binary file added test/js/third_party/@napi-rs/canvas/expected.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading