Skip to content
71 changes: 54 additions & 17 deletions src/jsc/bindings/napi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,36 +80,69 @@
using namespace JSC;
using namespace Zig;

// Exception scope for the N-API C ABI boundary: addon C callers can't satisfy JSC's
// exception-check discipline, so acknowledge pending checks on entry and exit instead
// of simulating a throw. A real exception still surfaces as napi_pending_exception.
class NapiBoundaryScope : public JSC::ExceptionScope {
public:
#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
NapiBoundaryScope(JSC::VM& vm, JSC::ExceptionEventLocation location)
: JSC::ExceptionScope(vm, location)
{
(void)exception();
}
~NapiBoundaryScope()
{
(void)exception();
}
#else
ALWAYS_INLINE NapiBoundaryScope(JSC::VM& vm)
: JSC::ExceptionScope(vm)
{
}
#endif
NapiBoundaryScope(const NapiBoundaryScope&) = delete;
NapiBoundaryScope(NapiBoundaryScope&&) = default;
};

#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
#define DECLARE_NAPI_BOUNDARY_SCOPE(vm__) \
NapiBoundaryScope((vm__), JSC::ExceptionEventLocation(EXCEPTION_SCOPE_POSITION_FOR_ASAN(vm__), __FUNCTION__, __FILE__, __LINE__))
#else
#define DECLARE_NAPI_BOUNDARY_SCOPE(vm__) NapiBoundaryScope((vm__))
#endif

// Every NAPI function should use this at the start. It does the following:
// - if NAPI_VERBOSE is 1, log that the function was called
// - if env is nullptr, return napi_invalid_arg
// - if there is a pending exception, return napi_pending_exception
// No do..while is used as this declares a variable that other macros need to use
#define NAPI_PREAMBLE(_env) \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
/* You should not use this throw scope directly -- if you need */ \
/* to throw or clear exceptions, make your own scope */ \
auto napi_preamble_throw_scope__ = DECLARE_THROW_SCOPE(_env->vm()); \
#define NAPI_PREAMBLE(_env) \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
/* You should not use this scope directly -- if you need */ \
/* to throw or clear exceptions, make your own scope */ \
auto napi_preamble_throw_scope__ = DECLARE_NAPI_BOUNDARY_SCOPE((_env)->vm()); \
NAPI_RETURN_IF_EXCEPTION(_env)

// Only use this for functions that need their own throw or catch scope. Functions that call into
// JS code that might throw should use NAPI_RETURN_IF_EXCEPTION.
#define NAPI_PREAMBLE_NO_THROW_SCOPE(_env) \
do { \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
} while (0)
// No do..while is used as this declares a variable that must outlive any inner ThrowScope.
#define NAPI_PREAMBLE_NO_THROW_SCOPE(_env) \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
auto napi_preamble_boundary_scope__ = DECLARE_NAPI_BOUNDARY_SCOPE((_env)->vm()); \
(void)napi_preamble_boundary_scope__

// Like NAPI_PREAMBLE but does NOT return napi_pending_exception when the env
// has a stashed napi_throw* exception. Mirrors Node.js's CHECK_ENV_NOT_IN_GC
// for pure value constructors/accessors that are safe to call while an
// exception is pending. Still declares a throw scope so NAPI_RETURN_SUCCESS
// can assert and VM-level exceptions from JSC internals are caught.
#define NAPI_PREAMBLE_NO_PENDING_CHECK(_env) \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
auto napi_preamble_throw_scope__ = DECLARE_THROW_SCOPE(_env->vm()); \
// exception is pending. Still declares a scope so NAPI_RETURN_SUCCESS can
// assert and VM-level exceptions from JSC internals are caught.
#define NAPI_PREAMBLE_NO_PENDING_CHECK(_env) \
NAPI_LOG_CURRENT_FUNCTION; \
NAPI_CHECK_ARG(_env, _env); \
auto napi_preamble_throw_scope__ = DECLARE_NAPI_BOUNDARY_SCOPE((_env)->vm()); \
NAPI_RETURN_IF_VM_EXCEPTION(_env)

// Return an error code if arg is null. Only use for input validation.
Expand Down Expand Up @@ -356,10 +389,14 @@ napi_status Napi::defineProperty(napi_env env, JSC::JSObject* to, const napi_pro
if (property.getter) {
auto name = makeString("get "_s, propertyName.isSymbol() ? String() : propertyName.string());
descriptor.setGetter(NapiClass::create(vm, env, name, property.getter, dataPtr, 0, nullptr));
// Each NapiClass::create opens and closes a throw scope; the check between
// them is required for JSC's exception-check discipline.
RETURN_IF_EXCEPTION(scope, napi_pending_exception);
}
if (property.setter) {
auto name = makeString("set "_s, propertyName.isSymbol() ? String() : propertyName.string());
descriptor.setSetter(NapiClass::create(vm, env, name, property.setter, dataPtr, 0, nullptr));
RETURN_IF_EXCEPTION(scope, napi_pending_exception);
}
} else if (property.method != nullptr) {
WTF::String name;
Expand Down
123 changes: 123 additions & 0 deletions test/napi/napi-exception-check.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isMacOS, isWindows, tempDir } from "harness";
import { join } from "path";

// Path to the in-repo copies of node_api.h / js_native_api.h.
const napiHeaderDir = join(import.meta.dir, "..", "..", "src", "runtime", "napi");

// A plain C compiler is enough: the addons below only need the N-API C ABI.
const cc = Bun.which("cc") ?? Bun.which("clang") ?? Bun.which("gcc");

// The canonical two-call Init that every N-API template emits. Addon C code cannot
// satisfy JSC's exception-check discipline between the two napi_* calls; on an
// assert-enabled build with the validator on, getting that wrong aborts at module load.
const twoCallInitSource = /* c */ `
#include <node_api.h>

static napi_value Method(napi_env env, napi_callback_info info) {
napi_value result;
napi_create_int32(env, 42, &result);
return result;
}

NAPI_MODULE_INIT() {
napi_value fn;
napi_create_function(env, NULL, 0, Method, NULL, &fn);
napi_set_named_property(env, exports, "hello", fn);
return exports;
}
`;

// A class with a getter+setter property creates two NapiClass objects back to back
// inside Napi::defineProperty, which is a second place the exception-check discipline
// has to be satisfied (this is the shape every node-addon-api ObjectWrap accessor has).
const accessorClassSource = /* c */ `
#include <node_api.h>
#include <stddef.h>

static napi_value Ctor(napi_env env, napi_callback_info info) {
napi_value this_arg;
napi_get_cb_info(env, info, NULL, NULL, &this_arg, NULL);
return this_arg;
}

static napi_value Getter(napi_env env, napi_callback_info info) {
napi_value result;
napi_create_int32(env, 42, &result);
return result;
}

static napi_value Setter(napi_env env, napi_callback_info info) {
return NULL;
}

NAPI_MODULE_INIT() {
napi_property_descriptor prop = {"value", NULL, NULL, Getter, Setter, NULL, napi_default, NULL};
napi_value cls;
napi_define_class(env, "Thing", NAPI_AUTO_LENGTH, Ctor, NULL, 1, &prop, &cls);
napi_set_named_property(env, exports, "Thing", cls);
return exports;
}
`;

async function loadAddonWithValidator(name: string, addonSource: string, loadJs: string, expectedStdout: string) {
using dir = tempDir(name, { "addon.c": addonSource, "load.js": loadJs });

await using compile = Bun.spawn({
cmd: [
cc!,
"-shared",
"-fPIC",
// The napi_* symbols are resolved from the host process at dlopen time.
// Linux ld allows undefined symbols in shared objects by default; macOS
// ld64 errors on them unless told to defer, which is what node-gyp does.
...(isMacOS ? ["-undefined", "dynamic_lookup"] : []),
`-I${napiHeaderDir}`,
"-o",
"addon.node",
"addon.c",
],
cwd: String(dir),
env: bunEnv,
stdout: "ignore",
stderr: "pipe",
});
const [compileStderr, compileExitCode] = await Promise.all([compile.stderr.text(), compile.exited]);
// Don't require an empty stderr: ld64 may warn about dynamic_lookup.
expect({ exitCode: compileExitCode, stderr: compileStderr }).toMatchObject({ exitCode: 0 });

await using proc = Bun.spawn({
cmd: [bunExe(), "load.js"],
cwd: String(dir),
env: { ...bunEnv, BUN_JSC_validateExceptionChecks: "1" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

// stderr is in the received object so the abort report shows up in the
// failure diff, but its contents are not asserted (debug builds write noise).
expect({ stdout, stderr, exitCode }).toMatchObject({ stdout: expectedStdout, exitCode: 0 });
expect(stderr).not.toContain("Unchecked JS exception");
}

test.concurrent.skipIf(isWindows || !cc)("N-API module Init runs under BUN_JSC_validateExceptionChecks", async () => {
await loadAddonWithValidator(
"napi-exception-check",
twoCallInitSource,
`const addon = require("./addon.node");\nconsole.log("loaded", addon.hello());\n`,
"loaded 42\n",
);
});

test.concurrent.skipIf(isWindows || !cc)(
"napi_define_class accessors run under BUN_JSC_validateExceptionChecks",
async () => {
await loadAddonWithValidator(
"napi-exception-check-class",
accessorClassSource,
`const { Thing } = require("./addon.node");\nconsole.log("value", new Thing().value);\n`,
"value 42\n",
);
},
);
Loading