diff --git a/src/node_api.cc b/src/node_api.cc index e0e7cca2a4ba..40bdf143a98f 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -770,6 +770,8 @@ void napi_module_register_by_symbol(v8::Local exports, // Create a new napi_env for this specific module. napi_env env = node_napi_env__::New(context, module_filename, module_api_version); + // `module_api_version` is not supported. + if (env == nullptr) return; napi_value _exports = nullptr; env->CallIntoModule([&](napi_env env) { diff --git a/test/node-api/test_module_version_mismatch/binding.gyp b/test/node-api/test_module_version_mismatch/binding.gyp new file mode 100644 index 000000000000..e87600d8fa48 --- /dev/null +++ b/test/node-api/test_module_version_mismatch/binding.gyp @@ -0,0 +1,12 @@ +{ + 'targets': [ + { + 'target_name': 'test_module_version_mismatch', + 'sources': [ 'test_module_version_mismatch.c' ], + # One below NAPI_VERSION_EXPERIMENTAL, so it is always above + # NODE_API_SUPPORTED_VERSION_MAX and never becomes a real version, but is + # not the experimental value the version check deliberately allows. + 'defines': [ 'NAPI_VERSION=2147483646' ] + } + ] +} diff --git a/test/node-api/test_module_version_mismatch/test.js b/test/node-api/test_module_version_mismatch/test.js new file mode 100644 index 000000000000..84d8e9c78195 --- /dev/null +++ b/test/node-api/test_module_version_mismatch/test.js @@ -0,0 +1,12 @@ +'use strict'; +const common = require('../../common'); +const assert = require('assert'); + +// An add-on that requires a newer Node-API version than this binary supports +// must be rejected with an error that `require()` can catch. The version check +// in `node_napi_env__::New()` already produces that error, but its nullptr +// return used to be dereferenced by `napi_module_register_by_symbol()`, so the +// process segfaulted before the error could surface. +assert.throws( + () => require(`./build/${common.buildType}/test_module_version_mismatch`), + /requires Node-API version 2147483646, but this version of Node\.js only supports version \d+ add-ons\./); diff --git a/test/node-api/test_module_version_mismatch/test_module_version_mismatch.c b/test/node-api/test_module_version_mismatch/test_module_version_mismatch.c new file mode 100644 index 000000000000..63027b705b29 --- /dev/null +++ b/test/node-api/test_module_version_mismatch/test_module_version_mismatch.c @@ -0,0 +1,7 @@ +#include + +// This add-on declares a Node-API version that no build supports, so loading it +// must fail with an error -- not a crash. +NAPI_MODULE_INIT() { + return exports; +}