From fbc52e572902150d0448619b430abdb4915c4afd Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Fri, 5 Aug 2022 02:32:06 +0800 Subject: [PATCH] src: disambiguate terms used to refer to builtins and addons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The term "native module" dates back to some of the oldest code in the code base. Within the context of Node.js core it usually refers to modules that are native to Node.js (e.g. fs, http), but it can cause confusion for people who don't work on this part of the code base, as "native module" can also refer to native addons - which is even the case in some of the API docs and error messages. This patch tries to make the usage of these terms more consistent. Now within the context of Node.js core: - JavaScript scripts that are built-in to Node.js are now referred to as "built-in(s)". If they are available as modules, they can also be referred to as "built-in module(s)". - Dynamically-linked shared objects that are loaded into the Node.js processes are referred to as "addons". We will try to avoid using the term "native modules" because it could be ambiguous. Changes in this patch: File names: - node_native_module.h -> node_builtins.h, - node_native_module.cc -> node_builtins.cc C++ binding names: - `native_module` -> `builtins` `node::Environment`: - `native_modules_without_cache` -> `builtins_without_cache` - `native_modules_with_cache` -> `builtins_with_cache` - `native_modules_in_snapshot` -> `builtins_in_cache` - `native_module_require` -> `builtin_module_require` `node::EnvSerializeInfo`: - `native_modules` -> `builtins `node::native_module::NativeModuleLoader`: - `native_module` namespace -> `builtins` namespace - `NativeModuleLoader` -> `BuiltinLoader` - `NativeModuleRecordMap` -> `BuiltinSourceMap` - `NativeModuleCacheMap` -> `BuiltinCodeCacheMap` - `ModuleIds` -> `BuiltinIds` - `ModuleCategories` -> `BuiltinCategories` - `LoadBuiltinModuleSource` -> `LoadBuiltinSource` `loader.js`: - `NativeModule` -> `BuiltinModule` (the `NativeModule` name used in `process.moduleLoadList` is kept for compatibility) And other clarifications in the documentation and comments. PR-URL: https://github.com/nodejs/node/pull/44135 Backport-PR-URL: https://github.com/nodejs/node/pull/45663 Fixes: https://github.com/nodejs/node/issues/44036 Reviewed-By: Jacob Smith Reviewed-By: Matteo Collina Reviewed-By: Michael Dawson Reviewed-By: Richard Lau Reviewed-By: Jiawen Geng Reviewed-By: Chengzhong Wu Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Tobias Nießen Reviewed-By: Jan Krems --- .github/CODEOWNERS | 2 +- doc/api/deprecations.md | 4 +- doc/api/modules.md | 4 +- doc/api/n-api.md | 8 +- doc/contributing/adding-new-napi-api.md | 2 +- lib/assert.js | 4 +- lib/internal/bootstrap/loaders.js | 30 ++++--- lib/internal/bootstrap/node.js | 4 +- lib/internal/bootstrap/pre_execution.js | 6 +- lib/internal/debugger/inspect_repl.js | 4 +- lib/internal/main/mksnapshot.js | 4 +- lib/internal/modules/cjs/helpers.js | 12 +-- lib/internal/modules/cjs/loader.js | 34 +++---- lib/internal/modules/esm/loader.js | 6 +- lib/internal/modules/esm/resolve.js | 10 +-- lib/internal/modules/esm/translators.js | 4 +- lib/internal/util/inspect.js | 4 +- lib/process.js | 2 +- lib/repl.js | 4 +- node.gyp | 8 +- src/api/environment.cc | 10 ++- src/crypto/crypto_keys.cc | 5 +- src/env.cc | 25 +++--- src/env.h | 12 +-- src/node.cc | 22 ++--- src/node_api.h | 2 +- src/node_binding.cc | 10 +-- ...node_native_module.cc => node_builtins.cc} | 89 ++++++++++--------- src/{node_native_module.h => node_builtins.h} | 55 ++++++------ ...ive_module_env.cc => node_builtins_env.cc} | 82 ++++++++--------- ...ative_module_env.h => node_builtins_env.h} | 22 ++--- src/node_code_cache_stub.cc | 8 +- src/node_config.cc | 3 +- src/node_errors.h | 2 +- src/node_external_reference.h | 2 +- src/node_internals.h | 4 +- src/node_main_instance.cc | 1 + test/addons/force-context-aware/test.js | 2 +- test/addons/symlinked-module/test.js | 2 +- test/cctest/test_per_process.cc | 27 +++--- test/node-api/test_general/test.js | 2 +- test/parallel/test-bootstrap-modules.js | 2 +- test/parallel/test-code-cache.js | 2 +- tools/code_cache/README.md | 4 +- tools/code_cache/cache_builder.cc | 25 +++--- tools/code_cache/cache_builder.h | 4 +- tools/code_cache/mkcodecache.cc | 2 +- tools/js2c.py | 10 +-- 48 files changed, 297 insertions(+), 295 deletions(-) rename src/{node_native_module.cc => node_builtins.cc} (77%) rename src/{node_native_module.h => node_builtins.h} (60%) rename src/{node_native_module_env.cc => node_builtins_env.cc} (70%) rename src/{node_native_module_env.h => node_builtins_env.h} (80%) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4708568325cabe..48691479c44e7c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -108,7 +108,7 @@ /benchmark/misc/startup.js @nodejs/startup /src/node.cc @nodejs/startup /src/node_code_cache_stub.cc @nodejs/startup -/src/node_native_module* @nodejs/startup +/src/node_builtins* @nodejs/startup /src/node_snapshot* @nodejs/startup /lib/internal/bootstrap/* @nodejs/startup /tools/code_cache/* @nodejs/startup diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index d3171be5531e05..b107ebefbf5586 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -2003,7 +2003,7 @@ changes: Type: Compile-time -Certain versions of `node::MakeCallback` APIs available to native modules are +Certain versions of `node::MakeCallback` APIs available to native addons are deprecated. Please use the versions of the API that accept an `async_context` parameter. @@ -2751,7 +2751,7 @@ changes: Type: Documentation-only The `node:repl` module exports a `_builtinLibs` property that contains an array -with native modules. It was incomplete so far and instead it's better to rely +of built-in modules. It was incomplete so far and instead it's better to rely upon `require('node:module').builtinModules`. ### DEP0143: `Transform._transformState` diff --git a/doc/api/modules.md b/doc/api/modules.md index 7f42c287bbb8dc..a46db2da8a328d 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -705,8 +705,8 @@ This does not apply to [native addons][], for which reloading will result in an error. Adding or replacing entries is also possible. This cache is checked before -native modules and if a name matching a native module is added to the cache, -only `node:`-prefixed require calls are going to receive the native module. +built-in modules and if a name matching a built-in module is added to the cache, +only `node:`-prefixed require calls are going to receive the built-in module. Use with care! diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 54a3ea7a2ce11f..ad08d94f6466d8 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -201,9 +201,9 @@ GitHub projects using CMake.js. #### prebuildify [prebuildify][] is a tool based on node-gyp. The advantage of prebuildify is -that the built binaries are bundled with the native module when it's +that the built binaries are bundled with the native addon when it's uploaded to npm. The binaries are downloaded from npm and are immediately -available to the module user when the native module is installed. +available to the module user when the native addon is installed. ## Usage @@ -1381,7 +1381,7 @@ callback throws an exception with no way to recover. ### Fatal errors -In the event of an unrecoverable error in a native module, a fatal error can be +In the event of an unrecoverable error in a native addon, a fatal error can be thrown to immediately terminate the process. #### `napi_fatal_error` @@ -5745,7 +5745,7 @@ Returns `napi_ok` if the API succeeded. This function gives V8 an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object -that points to its own memory allocated by a native module). Registering +that points to its own memory allocated by a native addon). Registering externally allocated memory will trigger global garbage collections more often than it would otherwise. diff --git a/doc/contributing/adding-new-napi-api.md b/doc/contributing/adding-new-napi-api.md index d29236cb5cc561..8d2233bc30f690 100644 --- a/doc/contributing/adding-new-napi-api.md +++ b/doc/contributing/adding-new-napi-api.md @@ -1,6 +1,6 @@ # Contributing a new API to Node-API -Node-API is the next-generation ABI-stable API for native modules. +Node-API is the next-generation ABI-stable API for native addons. While improving the API surface is encouraged and welcomed, the following are a set of principles and guidelines to keep in mind while adding a new Node-API. diff --git a/lib/assert.js b/lib/assert.js index fc3127f3bf4214..82c3a285f51abd 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -65,7 +65,7 @@ const { openSync, closeSync, readSync } = require('fs'); const { inspect } = require('internal/util/inspect'); const { isPromise, isRegExp } = require('internal/util/types'); const { EOL } = require('internal/constants'); -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { isError } = require('internal/util'); const errorCache = new SafeMap(); @@ -303,7 +303,7 @@ function getErrMessage(message, fn) { // Skip Node.js modules! if (StringPrototypeStartsWith(filename, 'node:') && - NativeModule.exists(StringPrototypeSlice(filename, 5))) { + BuiltinModule.exists(StringPrototypeSlice(filename, 5))) { errorCache.set(identifier, undefined); return; } diff --git a/lib/internal/bootstrap/loaders.js b/lib/internal/bootstrap/loaders.js index 41162fabcbc589..a3c3d375f7090e 100644 --- a/lib/internal/bootstrap/loaders.js +++ b/lib/internal/bootstrap/loaders.js @@ -24,7 +24,7 @@ // and have their nm_flags set to NM_F_INTERNAL. // // Internal JavaScript module loader: -// - NativeModule: a minimal module system used to load the JavaScript core +// - BuiltinModule: a minimal module system used to load the JavaScript core // modules found in lib/**/*.js and deps/**/*.js. All core modules are // compiled into the node binary via node_javascript.cc generated by js2c.py, // so they can be loaded faster without the cost of I/O. This class makes the @@ -180,9 +180,9 @@ let internalBinding; const loaderId = 'internal/bootstrap/loaders'; const { - moduleIds, + builtinIds, compileFunction -} = internalBinding('native_module'); +} = internalBinding('builtins'); const getOwn = (target, property, receiver) => { return ObjectPrototypeHasOwnProperty(target, property) ? @@ -195,13 +195,13 @@ const getOwn = (target, property, receiver) => { * Be careful not to expose this to user land unless --expose-internals is * used, in which case there is no compatibility guarantee about this class. */ -class NativeModule { +class BuiltinModule { /** * A map from the module IDs to the module instances. - * @type {Map} + * @type {Map} */ static map = new SafeMap( - ArrayPrototypeMap(moduleIds, (id) => [id, new NativeModule(id)]) + ArrayPrototypeMap(builtinIds, (id) => [id, new BuiltinModule(id)]) ); constructor(id) { @@ -216,7 +216,7 @@ class NativeModule { this.loading = false; // The following properties are used by the ESM implementation and only - // initialized when the native module is loaded by users. + // initialized when the built-in module is loaded by users. /** * The C++ ModuleWrap binding used to interface with the ESM implementation. * @type {ModuleWrap|undefined} @@ -232,7 +232,7 @@ class NativeModule { // To be called during pre-execution when --expose-internals is on. // Enables the user-land module loader to access internal modules. static exposeInternals() { - for (const { 0: id, 1: mod } of NativeModule.map) { + for (const { 0: id, 1: mod } of BuiltinModule.map) { // Do not expose this to user land even with --expose-internals. if (id !== loaderId) { mod.canBeRequiredByUsers = true; @@ -241,11 +241,11 @@ class NativeModule { } static exists(id) { - return NativeModule.map.has(id); + return BuiltinModule.map.has(id); } static canBeRequiredByUsers(id) { - const mod = NativeModule.map.get(id); + const mod = BuiltinModule.map.get(id); return mod && mod.canBeRequiredByUsers; } @@ -326,6 +326,8 @@ class NativeModule { requireWithFallbackInDeps : nativeModuleRequire; const fn = compileFunction(id); + // Arguments must match the parameters specified in + // BuiltinLoader::LookupAndCompile(). fn(this.exports, requireFn, this, process, internalBinding, primordials); this.loaded = true; @@ -333,6 +335,8 @@ class NativeModule { this.loading = false; } + // "NativeModule" is a legacy name of "BuiltinModule". We keep it + // here to avoid breaking users who parse process.moduleLoadList. ArrayPrototypePush(moduleLoadList, `NativeModule ${id}`); return this.exports; } @@ -342,7 +346,7 @@ class NativeModule { // written in CommonJS style. const loaderExports = { internalBinding, - NativeModule, + BuiltinModule, require: nativeModuleRequire }; @@ -351,7 +355,7 @@ function nativeModuleRequire(id) { return loaderExports; } - const mod = NativeModule.map.get(id); + const mod = BuiltinModule.map.get(id); // Can't load the internal errors module from here, have to use a raw error. // eslint-disable-next-line no-restricted-syntax if (!mod) throw new TypeError(`Missing internal module '${id}'`); @@ -361,7 +365,7 @@ function nativeModuleRequire(id) { // Allow internal modules from dependencies to require // other modules from dependencies by providing fallbacks. function requireWithFallbackInDeps(request) { - if (!NativeModule.map.has(request)) { + if (!BuiltinModule.map.has(request)) { request = `internal/deps/${request}`; } return nativeModuleRequire(request); diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js index df40eb9f67f46c..d02c70466b10d3 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js @@ -34,7 +34,7 @@ // `MessagePort` implementation. // - `lib/internal/bootstrap/loaders.js`: this sets up internal binding and // module loaders, including `process.binding()`, `process._linkedBinding()`, -// `internalBinding()` and `NativeModule`. +// `internalBinding()` and `BuiltinModule`. // // The initialization done in this script is included in both the main thread // and the worker threads. After this, further initialization is done based @@ -102,7 +102,7 @@ process.domain = null; process._exiting = false; // process.config is serialized config.gypi -const nativeModule = internalBinding('native_module'); +const nativeModule = internalBinding('builtins'); // TODO(@jasnell): Once this has gone through one full major // release cycle, remove the Proxy and setter and update the diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index 337b95133bc94e..a9f463c4d00db0 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -290,7 +290,7 @@ function initializeReport() { function setupDebugEnv() { require('internal/util/debuglog').initializeDebugEnv(process.env.NODE_DEBUG); if (getOptionValue('--expose-internals')) { - require('internal/bootstrap/loaders').NativeModule.exposeInternals(); + require('internal/bootstrap/loaders').BuiltinModule.exposeInternals(); } } @@ -512,8 +512,8 @@ function initializePolicy() { } function initializeWASI() { - const { NativeModule } = require('internal/bootstrap/loaders'); - const mod = NativeModule.map.get('wasi'); + const { BuiltinModule } = require('internal/bootstrap/loaders'); + const mod = BuiltinModule.map.get('wasi'); mod.canBeRequiredByUsers = getOptionValue('--experimental-wasi-unstable-preview1'); } diff --git a/lib/internal/debugger/inspect_repl.js b/lib/internal/debugger/inspect_repl.js index c2b741e0d5d8d6..965aa64b0fbcc6 100644 --- a/lib/internal/debugger/inspect_repl.js +++ b/lib/internal/debugger/inspect_repl.js @@ -117,8 +117,8 @@ function extractFunctionName(description) { } const { - moduleIds: PUBLIC_BUILTINS, -} = internalBinding('native_module'); + builtinIds: PUBLIC_BUILTINS, +} = internalBinding('builtins'); const NATIVES = internalBinding('natives'); function isNativeUrl(url) { url = RegExpPrototypeSymbolReplace(/\.js$/, url, ''); diff --git a/lib/internal/main/mksnapshot.js b/lib/internal/main/mksnapshot.js index 616a436e0a9483..053457cfebb288 100644 --- a/lib/internal/main/mksnapshot.js +++ b/lib/internal/main/mksnapshot.js @@ -7,7 +7,7 @@ const { } = primordials; const binding = internalBinding('mksnapshot'); -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { compileSerializeMain, } = binding; @@ -92,7 +92,7 @@ function supportedInUserSnapshot(id) { } function requireForUserSnapshot(id) { - if (!NativeModule.canBeRequiredByUsers(id)) { + if (!BuiltinModule.canBeRequiredByUsers(id)) { // eslint-disable-next-line no-restricted-syntax const err = new Error( `Cannot find module '${id}'. ` diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js index 20c167f8599f7b..3c49ab0a5d84cb 100644 --- a/lib/internal/modules/cjs/helpers.js +++ b/lib/internal/modules/cjs/helpers.js @@ -17,7 +17,7 @@ const { ERR_MANIFEST_DEPENDENCY_MISSING, ERR_UNKNOWN_BUILTIN_MODULE } = require('internal/errors').codes; -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { validateString } = require('internal/validators'); const path = require('path'); @@ -42,10 +42,10 @@ const cjsConditions = new SafeSet([ ...userConditions, ]); -function loadNativeModule(filename, request) { - const mod = NativeModule.map.get(filename); +function loadBuiltinModule(filename, request) { + const mod = BuiltinModule.map.get(filename); if (mod?.canBeRequiredByUsers) { - debug('load native module %s', request); + debug('load built-in module %s', request); // compileForPublicLoader() throws if mod.canBeRequiredByUsers is false: mod.compileForPublicLoader(); return mod; @@ -73,7 +73,7 @@ function makeRequireFunction(mod, redirects) { const href = destination.href; if (destination.protocol === 'node:') { const specifier = destination.pathname; - const mod = loadNativeModule(specifier, href); + const mod = loadBuiltinModule(specifier, href); if (mod && mod.canBeRequiredByUsers) { return mod.exports; } @@ -230,7 +230,7 @@ module.exports = { addBuiltinLibsToObject, cjsConditions, hasEsmSyntax, - loadNativeModule, + loadBuiltinModule, makeRequireFunction, normalizeReferrerURL, stripBOM, diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 395546c2f5d491..1bca6706ea9b44 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -74,7 +74,7 @@ module.exports = { get hasLoadedAnyUserCJSModule() { return hasLoadedAnyUserCJSModule; } }; -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { maybeCacheSourceMap, } = require('internal/source_map/source_map_cache'); @@ -98,7 +98,7 @@ const { safeGetenv } = internalBinding('credentials'); const { cjsConditions, hasEsmSyntax, - loadNativeModule, + loadBuiltinModule, makeRequireFunction, normalizeReferrerURL, stripBOM, @@ -206,9 +206,9 @@ function Module(id = '', parent) { } const builtinModules = []; -for (const { 0: id, 1: mod } of NativeModule.map) { +for (const { 0: id, 1: mod } of BuiltinModule.map) { if (mod.canBeRequiredByUsers && - NativeModule.canBeRequiredWithoutScheme(id)) { + BuiltinModule.canBeRequiredWithoutScheme(id)) { ArrayPrototypePush(builtinModules, id); } } @@ -216,7 +216,7 @@ for (const { 0: id, 1: mod } of NativeModule.map) { const allBuiltins = new SafeSet( ArrayPrototypeFlatMap(builtinModules, (bm) => [bm, `node:${bm}`]) ); -NativeModule.getSchemeOnlyModuleNames().forEach((builtin) => allBuiltins.add(`node:${builtin}`)); +BuiltinModule.getSchemeOnlyModuleNames().forEach((builtin) => allBuiltins.add(`node:${builtin}`)); ObjectFreeze(builtinModules); Module.builtinModules = builtinModules; @@ -279,7 +279,7 @@ ObjectDefineProperty(Module, 'wrapper', { const isPreloadingDesc = { get() { return isPreloading; } }; ObjectDefineProperty(Module.prototype, 'isPreloading', isPreloadingDesc); -ObjectDefineProperty(NativeModule.prototype, 'isPreloading', isPreloadingDesc); +ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc); function getModuleParent() { return moduleParentCache.get(this); @@ -712,8 +712,8 @@ if (isWindows) { } Module._resolveLookupPaths = function(request, parent) { - if (NativeModule.canBeRequiredByUsers(request) && - NativeModule.canBeRequiredWithoutScheme(request)) { + if (BuiltinModule.canBeRequiredByUsers(request) && + BuiltinModule.canBeRequiredWithoutScheme(request)) { debug('looking for %j in []', request); return null; } @@ -800,7 +800,7 @@ function getExportsForCircularRequire(module) { // Check the cache for the requested file. // 1. If a module already exists in the cache: return its exports object. // 2. If the module is native: call -// `NativeModule.prototype.compileForPublicLoader()` and return the exports. +// `BuiltinModule.prototype.compileForPublicLoader()` and return the exports. // 3. Otherwise, create a new module for the file and save it to the cache. // Then have it load the file contents before returning its exports // object. @@ -830,7 +830,7 @@ Module._load = function(request, parent, isMain) { // Slice 'node:' prefix const id = StringPrototypeSlice(request, 5); - const module = loadNativeModule(id, request); + const module = loadBuiltinModule(id, request); if (!module?.canBeRequiredByUsers) { throw new ERR_UNKNOWN_BUILTIN_MODULE(request); } @@ -852,9 +852,9 @@ Module._load = function(request, parent, isMain) { } } - const mod = loadNativeModule(filename, request); + const mod = loadBuiltinModule(filename, request); if (mod?.canBeRequiredByUsers && - NativeModule.canBeRequiredWithoutScheme(filename)) { + BuiltinModule.canBeRequiredWithoutScheme(filename)) { return mod.exports; } @@ -905,10 +905,10 @@ Module._resolveFilename = function(request, parent, isMain, options) { if ( ( StringPrototypeStartsWith(request, 'node:') && - NativeModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) + BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) ) || ( - NativeModule.canBeRequiredByUsers(request) && - NativeModule.canBeRequiredWithoutScheme(request) + BuiltinModule.canBeRequiredByUsers(request) && + BuiltinModule.canBeRequiredWithoutScheme(request) ) ) { return request; @@ -1344,9 +1344,9 @@ Module._preloadModules = function(requests) { }; Module.syncBuiltinESMExports = function syncBuiltinESMExports() { - for (const mod of NativeModule.map.values()) { + for (const mod of BuiltinModule.map.values()) { if (mod.canBeRequiredByUsers && - NativeModule.canBeRequiredWithoutScheme(mod.id)) { + BuiltinModule.canBeRequiredWithoutScheme(mod.id)) { mod.syncExports(); } } diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 624bdba889a9fb..d247f5327eda8b 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -721,7 +721,7 @@ class ESMLoader { filename: '', } ); - const { NativeModule } = require('internal/bootstrap/loaders'); + const { BuiltinModule } = require('internal/bootstrap/loaders'); // We only allow replacing the importMetaInitializer during preload, // after preload is finished, we disable the ability to replace it // @@ -739,8 +739,8 @@ class ESMLoader { globalThis, // Param getBuiltin (builtinName) => { - if (NativeModule.canBeRequiredByUsers(builtinName) && - NativeModule.canBeRequiredWithoutScheme(builtinName)) { + if (BuiltinModule.canBeRequiredByUsers(builtinName) && + BuiltinModule.canBeRequiredWithoutScheme(builtinName)) { return require(builtinName); } throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName); diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index a3b4b1946d371d..b0748394b2d8ef 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -26,7 +26,7 @@ const { StringPrototypeStartsWith, } = primordials; const internalFS = require('internal/fs/utils'); -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { realpathSync, statSync, @@ -791,8 +791,8 @@ function parsePackageName(specifier, base) { * @returns {URL} */ function packageResolve(specifier, base, conditions) { - if (NativeModule.canBeRequiredByUsers(specifier) && - NativeModule.canBeRequiredWithoutScheme(specifier)) { + if (BuiltinModule.canBeRequiredByUsers(specifier) && + BuiltinModule.canBeRequiredWithoutScheme(specifier)) { return new URL('node:' + specifier); } @@ -976,8 +976,8 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) { return { url: parsed.href }; } - if (NativeModule.canBeRequiredByUsers(specifier) && - NativeModule.canBeRequiredWithoutScheme(specifier)) { + if (BuiltinModule.canBeRequiredByUsers(specifier) && + BuiltinModule.canBeRequiredWithoutScheme(specifier)) { throw new ERR_NETWORK_IMPORT_DISALLOWED( specifier, parsedParentURL, diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 1211974ba9cf9d..6f25b2e67ab776 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -28,7 +28,7 @@ const { readFileSync } = require('fs'); const { extname, isAbsolute } = require('path'); const { hasEsmSyntax, - loadNativeModule, + loadBuiltinModule, stripBOM, } = require('internal/modules/cjs/helpers'); const { @@ -254,7 +254,7 @@ translators.set('builtin', async function builtinStrategy(url) { debug(`Translating BuiltinModule ${url}`); // Slice 'node:' scheme const id = StringPrototypeSlice(url, 5); - const module = loadNativeModule(id, url); + const module = loadBuiltinModule(id, url); if (!StringPrototypeStartsWith(url, 'node:') || !module) { throw new ERR_UNKNOWN_BUILTIN_MODULE(url); } diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 9e307ccf96eeb5..fed5b8fd068fa3 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -151,7 +151,7 @@ const { const assert = require('internal/assert'); -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { validateObject, validateString, @@ -1395,7 +1395,7 @@ function formatError(err, constructor, tag, ctx, keys) { let esmWorkingDirectory; for (let line of lines) { const core = RegExpPrototypeExec(coreModuleRegExp, line); - if (core !== null && NativeModule.exists(core[1])) { + if (core !== null && BuiltinModule.exists(core[1])) { newStack += `\n${ctx.stylize(line, 'undefined')}`; } else { newStack += '\n'; diff --git a/lib/process.js b/lib/process.js index 43c8bf96f0bd48..aea7351ba4fd5b 100644 --- a/lib/process.js +++ b/lib/process.js @@ -1,4 +1,4 @@ 'use strict'; -// Re-export process as a native module +// Re-export process as a built-in module module.exports = process; diff --git a/lib/repl.js b/lib/repl.js index 8a0533191c3970..8252c39a05fa58 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -99,7 +99,7 @@ const { globalThis, } = primordials; -const { NativeModule } = require('internal/bootstrap/loaders'); +const { BuiltinModule } = require('internal/bootstrap/loaders'); const { makeRequireFunction, addBuiltinLibsToObject @@ -130,7 +130,7 @@ let _builtinLibs = ArrayPrototypeFilter( const nodeSchemeBuiltinLibs = ArrayPrototypeMap( _builtinLibs, (lib) => `node:${lib}`); ArrayPrototypeForEach( - NativeModule.getSchemeOnlyModuleNames(), + BuiltinModule.getSchemeOnlyModuleNames(), (lib) => ArrayPrototypePush(nodeSchemeBuiltinLibs, `node:${lib}`), ); const domain = require('domain'); diff --git a/node.gyp b/node.gyp index 24505da7babe46..5a91d76f458d5d 100644 --- a/node.gyp +++ b/node.gyp @@ -444,6 +444,7 @@ 'src/node_binding.cc', 'src/node_blob.cc', 'src/node_buffer.cc', + 'src/node_builtins.cc', 'src/node_config.cc', 'src/node_constants.cc', 'src/node_contextify.cc', @@ -459,8 +460,7 @@ 'src/node_main_instance.cc', 'src/node_messaging.cc', 'src/node_metadata.cc', - 'src/node_native_module.cc', - 'src/node_native_module_env.cc', + 'src/node_builtins_env.cc', 'src/node_options.cc', 'src/node_os.cc', 'src/node_perf.cc', @@ -543,6 +543,7 @@ 'src/node_binding.h', 'src/node_blob.h', 'src/node_buffer.h', + 'src/node_builtins.h', 'src/node_constants.h', 'src/node_context_data.h', 'src/node_contextify.h', @@ -563,8 +564,7 @@ 'src/node_messaging.h', 'src/node_metadata.h', 'src/node_mutex.h', - 'src/node_native_module.h', - 'src/node_native_module_env.h', + 'src/node_builtins_env.h', 'src/node_object_wrap.h', 'src/node_options.h', 'src/node_options-inl.h', diff --git a/src/api/environment.cc b/src/api/environment.cc index edfb42eb92a272..0e0dd42aafb573 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -1,8 +1,10 @@ #include "node.h" +#include "node_builtins.h" #include "node_context_data.h" #include "node_errors.h" #include "node_internals.h" -#include "node_native_module_env.h" +#include "node_builtins_env.h" +#include "node_options-inl.h" #include "node_platform.h" #include "node_v8_platform-inl.h" #include "uv.h" @@ -434,7 +436,7 @@ MaybeLocal LoadEnvironment( // TODO(addaleax): Avoid having a global table for all scripts. std::string name = "embedder_main_" + std::to_string(env->thread_id()); - native_module::NativeModuleEnv::Add( + builtins::BuiltinEnv::Add( name.c_str(), UnionBytes(**main_utf16, main_utf16->length())); env->set_main_utf16(std::move(main_utf16)); @@ -443,7 +445,7 @@ MaybeLocal LoadEnvironment( env->require_string()}; std::vector> args = { env->process_object(), - env->native_module_require()}; + env->builtin_module_require()}; return ExecuteBootstrapper(env, name.c_str(), ¶ms, &args); }); } @@ -685,7 +687,7 @@ bool InitializePrimordials(Local context) { global_string, exports_string, primordials_string}; Local arguments[] = {context->Global(), exports, primordials}; MaybeLocal maybe_fn = - native_module::NativeModuleEnv::LookupAndCompile( + builtins::BuiltinEnv::LookupAndCompile( context, *module, ¶meters, nullptr); Local fn; if (!maybe_fn.ToLocal(&fn)) { diff --git a/src/crypto/crypto_keys.cc b/src/crypto/crypto_keys.cc index 6ce4e2dc7e92d0..d44005ea439658 100644 --- a/src/crypto/crypto_keys.cc +++ b/src/crypto/crypto_keys.cc @@ -1380,8 +1380,9 @@ BaseObjectPtr NativeKeyObject::KeyObjectTransferData::Deserialize( Local key_ctor; Local arg = FIXED_ONE_BYTE_STRING(env->isolate(), "internal/crypto/keys"); - if (env->native_module_require()-> - Call(context, Null(env->isolate()), 1, &arg).IsEmpty()) { + if (env->builtin_module_require() + ->Call(context, Null(env->isolate()), 1, &arg) + .IsEmpty()) { return {}; } switch (data_->GetKeyType()) { diff --git a/src/env.cc b/src/env.cc index c4c7d2466b9e1b..32f02408e9da74 100644 --- a/src/env.cc +++ b/src/env.cc @@ -1547,12 +1547,12 @@ void Environment::PrintInfoForSnapshotIfDebug() { if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) { fprintf(stderr, "BaseObjects at the exit of the Environment:\n"); PrintAllBaseObjects(); - fprintf(stderr, "\nNative modules without cache:\n"); - for (const auto& s : native_modules_without_cache) { + fprintf(stderr, "\nBuiltins without cache:\n"); + for (const auto& s : builtins_without_cache) { fprintf(stderr, "%s\n", s.c_str()); } - fprintf(stderr, "\nNative modules with cache:\n"); - for (const auto& s : native_modules_with_cache) { + fprintf(stderr, "\nBuitins modules with cache:\n"); + for (const auto& s : builtins_with_cache) { fprintf(stderr, "%s\n", s.c_str()); } fprintf(stderr, "\nStatic bindings (need to be registered):\n"); @@ -1608,8 +1608,8 @@ EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) { SerializeBindingData(this, creator, &info); // Currently all modules are compiled without cache in builtin snapshot // builder. - info.native_modules = std::vector( - native_modules_without_cache.begin(), native_modules_without_cache.end()); + info.builtins = std::vector(builtins_without_cache.begin(), + builtins_without_cache.end()); info.async_hooks = async_hooks_.Serialize(ctx, creator); info.immediate_info = immediate_info_.Serialize(ctx, creator); @@ -1676,9 +1676,9 @@ std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) { << "// -- bindings begins --\n" << i.bindings << ",\n" << "// -- bindings ends --\n" - << "// -- native_modules begins --\n" - << i.native_modules << ",\n" - << "// -- native_modules ends --\n" + << "// -- builtins begins --\n" + << i.builtins << ",\n" + << "// -- builtins ends --\n" << "// -- async_hooks begins --\n" << i.async_hooks << ",\n" << "// -- async_hooks ends --\n" @@ -1730,7 +1730,7 @@ void Environment::DeserializeProperties(const EnvSerializeInfo* info) { RunDeserializeRequests(); - native_modules_in_snapshot = info->native_modules; + builtins_in_snapshot = info->builtins; async_hooks_.Deserialize(ctx); immediate_info_.Deserialize(ctx); tick_info_.Deserialize(ctx); @@ -1962,9 +1962,8 @@ void Environment::MemoryInfo(MemoryTracker* tracker) const { // Iteratable STLs have their own sizes subtracted from the parent // by default. tracker->TrackField("isolate_data", isolate_data_); - tracker->TrackField("native_modules_with_cache", native_modules_with_cache); - tracker->TrackField("native_modules_without_cache", - native_modules_without_cache); + tracker->TrackField("builtins_with_cache", builtins_with_cache); + tracker->TrackField("builtins_without_cache", builtins_without_cache); tracker->TrackField("destroy_async_id_list", destroy_async_id_list_); tracker->TrackField("exec_argv", exec_argv_); tracker->TrackField("exiting", exiting_); diff --git a/src/env.h b/src/env.h index 7605433fe01dae..bd36e11c637f79 100644 --- a/src/env.h +++ b/src/env.h @@ -35,8 +35,8 @@ #include "node.h" #include "node_binding.h" #include "node_external_reference.h" +#include "node_builtins.h" #include "node_main_instance.h" -#include "node_native_module.h" #include "node_options.h" #include "node_perf_common.h" #include "node_snapshotable.h" @@ -548,7 +548,7 @@ class NoArrayBufferZeroFillScope { V(maybe_cache_generated_source_map, v8::Function) \ V(messaging_deserialize_create_object, v8::Function) \ V(message_port, v8::Object) \ - V(native_module_require, v8::Function) \ + V(builtin_module_require, v8::Function) \ V(performance_entry_callback, v8::Function) \ V(performance_entry_template, v8::Function) \ V(prepare_stack_trace_callback, v8::Function) \ @@ -947,7 +947,7 @@ struct DeserializeRequest { struct EnvSerializeInfo { std::vector bindings; - std::vector native_modules; + std::vector builtins; AsyncHooks::SerializeInfo async_hooks; TickInfo::SerializeInfo tick_info; ImmediateInfo::SerializeInfo immediate_info; @@ -1154,11 +1154,11 @@ class Environment : public MemoryRetainer { inline std::vector* destroy_async_id_list(); std::set internal_bindings; - std::set native_modules_with_cache; - std::set native_modules_without_cache; + std::set builtins_with_cache; + std::set builtins_without_cache; // This is only filled during deserialization. We use a vector since // it's only used for tests. - std::vector native_modules_in_snapshot; + std::vector builtins_in_snapshot; std::unordered_multimap hash_to_module_map; std::unordered_map id_to_module_map; diff --git a/src/node.cc b/src/node.cc index 69c1c90c7d98c8..8555a771b795bb 100644 --- a/src/node.cc +++ b/src/node.cc @@ -28,11 +28,12 @@ #include "histogram-inl.h" #include "memory_tracker-inl.h" #include "node_binding.h" +#include "node_builtins.h" #include "node_errors.h" #include "node_internals.h" #include "node_main_instance.h" #include "node_metadata.h" -#include "node_native_module_env.h" +#include "node_builtins_env.h" #include "node_options-inl.h" #include "node_perf.h" #include "node_process-inl.h" @@ -126,8 +127,6 @@ namespace node { -using native_module::NativeModuleEnv; - using v8::EscapableHandleScope; using v8::Function; using v8::FunctionCallbackInfo; @@ -181,7 +180,8 @@ MaybeLocal ExecuteBootstrapper(Environment* env, std::vector>* arguments) { EscapableHandleScope scope(env->isolate()); MaybeLocal maybe_fn = - NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env); + builtins::BuiltinEnv::LookupAndCompile(env->context(), + id, parameters, env); Local fn; if (!maybe_fn.ToLocal(&fn)) { @@ -336,7 +336,7 @@ MaybeLocal Environment::BootstrapInternalLoaders() { Local require = loader_exports_obj->Get(context(), require_string()).ToLocalChecked(); CHECK(require->IsFunction()); - set_native_module_require(require.As()); + set_builtin_module_require(require.As()); return scope.Escape(loader_exports); } @@ -352,7 +352,7 @@ MaybeLocal Environment::BootstrapNode() { primordials_string()}; std::vector> node_args = { process_object(), - native_module_require(), + builtin_module_require(), internal_binding_loader(), primordials()}; @@ -441,7 +441,7 @@ MaybeLocal StartExecution(Environment* env, const char* main_script_id) { std::vector> arguments = { env->process_object(), - env->native_module_require(), + env->builtin_module_require(), env->internal_binding_loader(), env->primordials(), NewFunctionTemplate(env->isolate(), MarkBootstrapComplete) @@ -466,8 +466,8 @@ MaybeLocal StartExecution(Environment* env, StartExecutionCallback cb) { return {}; StartExecutionCallbackInfo info = { - env->process_object(), - env->native_module_require(), + env->process_object(), + env->builtin_module_require(), }; return scope.EscapeMaybe(cb(info)); @@ -982,11 +982,11 @@ int InitializeNodeWithArgs(std::vector* argv, #endif // defined(NODE_HAVE_I18N_SUPPORT) - NativeModuleEnv::InitializeCodeCache(); + builtins::BuiltinEnv::InitializeCodeCache(); // We should set node_is_initialized here instead of in node::Start, // otherwise embedders using node::Init to initialize everything will not be - // able to set it and native modules will not load for them. + // able to set it and native addons will not load for them. node_is_initialized = true; return 0; } diff --git a/src/node_api.h b/src/node_api.h index 07af926cafb536..8e6af2cf284e85 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -3,7 +3,7 @@ #ifdef BUILDING_NODE_EXTENSION #ifdef _WIN32 -// Building native module against node +// Building native addon against node #define NAPI_EXTERN __declspec(dllimport) #elif defined(__wasm32__) #define NAPI_EXTERN __attribute__((__import_module__("napi"))) diff --git a/src/node_binding.cc b/src/node_binding.cc index 5d090abbf05b4a..9a1be9da496463 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc @@ -1,9 +1,10 @@ #include "node_binding.h" #include #include "env-inl.h" +#include "node_builtins.h" #include "node_errors.h" #include "node_external_reference.h" -#include "node_native_module_env.h" +#include "node_builtins_env.h" #include "util.h" #include @@ -43,6 +44,7 @@ V(blob) \ V(block_list) \ V(buffer) \ + V(builtins) \ V(cares_wrap) \ V(config) \ V(contextify) \ @@ -60,7 +62,6 @@ V(messaging) \ V(module_wrap) \ V(mksnapshot) \ - V(native_module) \ V(options) \ V(os) \ V(performance) \ @@ -592,14 +593,13 @@ void GetInternalBinding(const FunctionCallbackInfo& args) { exports->SetPrototype(env->context(), Null(env->isolate())).FromJust()); DefineConstants(env->isolate(), exports); } else if (!strcmp(*module_v, "natives")) { - exports = native_module::NativeModuleEnv::GetSourceObject(env->context()); + exports = builtins::BuiltinEnv::GetSourceObject(env->context()); // Legacy feature: process.binding('natives').config contains stringified // config.gypi CHECK(exports ->Set(env->context(), env->config_string(), - native_module::NativeModuleEnv::GetConfigString( - env->isolate())) + builtins::BuiltinEnv::GetConfigString(env->isolate())) .FromJust()); } else { return THROW_ERR_INVALID_MODULE(env, "No such module: %s", *module_v); diff --git a/src/node_native_module.cc b/src/node_builtins.cc similarity index 77% rename from src/node_native_module.cc rename to src/node_builtins.cc index 5d20e1d6a86416..9343382e0253cd 100644 --- a/src/node_native_module.cc +++ b/src/node_builtins.cc @@ -1,9 +1,12 @@ -#include "node_native_module.h" -#include "util-inl.h" +#include "node_builtins.h" #include "debug_utils-inl.h" +#include "env-inl.h" +#include "node_external_reference.h" +#include "node_internals.h" +#include "util-inl.h" namespace node { -namespace native_module { +namespace builtins { using v8::Context; using v8::EscapableHandleScope; @@ -16,21 +19,21 @@ using v8::ScriptCompiler; using v8::ScriptOrigin; using v8::String; -NativeModuleLoader NativeModuleLoader::instance_; +BuiltinLoader BuiltinLoader::instance_; -NativeModuleLoader::NativeModuleLoader() : config_(GetConfig()) { +BuiltinLoader::BuiltinLoader() : config_(GetConfig()) { LoadJavaScriptSource(); } -NativeModuleLoader* NativeModuleLoader::GetInstance() { +BuiltinLoader* BuiltinLoader::GetInstance() { return &instance_; } -bool NativeModuleLoader::Exists(const char* id) { +bool BuiltinLoader::Exists(const char* id) { return source_.find(id) != source_.end(); } -bool NativeModuleLoader::Add(const char* id, const UnionBytes& source) { +bool BuiltinLoader::Add(const char* id, const UnionBytes& source) { if (Exists(id)) { return false; } @@ -38,7 +41,7 @@ bool NativeModuleLoader::Add(const char* id, const UnionBytes& source) { return true; } -Local NativeModuleLoader::GetSourceObject(Local context) { +Local BuiltinLoader::GetSourceObject(Local context) { Isolate* isolate = context->GetIsolate(); Local out = Object::New(isolate); for (auto const& x : source_) { @@ -48,11 +51,11 @@ Local NativeModuleLoader::GetSourceObject(Local context) { return out; } -Local NativeModuleLoader::GetConfigString(Isolate* isolate) { +Local BuiltinLoader::GetConfigString(Isolate* isolate) { return config_.ToStringChecked(isolate); } -std::vector NativeModuleLoader::GetModuleIds() { +std::vector BuiltinLoader::GetBuiltinIds() { std::vector ids; ids.reserve(source_.size()); for (auto const& x : source_) { @@ -61,9 +64,9 @@ std::vector NativeModuleLoader::GetModuleIds() { return ids; } -void NativeModuleLoader::InitializeModuleCategories() { - if (module_categories_.is_initialized) { - DCHECK(!module_categories_.can_be_required.empty()); +void BuiltinLoader::InitializeBuiltinCategories() { + if (builtin_categories_.is_initialized) { + DCHECK(!builtin_categories_.can_be_required.empty()); return; } @@ -79,17 +82,16 @@ void NativeModuleLoader::InitializeModuleCategories() { "internal/main/" }; - module_categories_.can_be_required.emplace( + builtin_categories_.can_be_required.emplace( "internal/deps/cjs-module-lexer/lexer"); - module_categories_.cannot_be_required = std::set { + builtin_categories_.cannot_be_required = std::set { #if !HAVE_INSPECTOR - "inspector", - "internal/util/inspector", + "inspector", "internal/util/inspector", #endif // !HAVE_INSPECTOR #if !NODE_USE_V8_PLATFORM || !defined(NODE_HAVE_I18N_SUPPORT) - "trace_events", + "trace_events", #endif // !NODE_USE_V8_PLATFORM || !defined(NODE_HAVE_I18N_SUPPORT) #if !HAVE_OPENSSL @@ -123,46 +125,45 @@ void NativeModuleLoader::InitializeModuleCategories() { continue; } if (id.find(prefix) == 0 && - module_categories_.can_be_required.count(id) == 0) { - module_categories_.cannot_be_required.emplace(id); + builtin_categories_.can_be_required.count(id) == 0) { + builtin_categories_.cannot_be_required.emplace(id); } } } for (auto const& x : source_) { const std::string& id = x.first; - if (0 == module_categories_.cannot_be_required.count(id)) { - module_categories_.can_be_required.emplace(id); + if (0 == builtin_categories_.cannot_be_required.count(id)) { + builtin_categories_.can_be_required.emplace(id); } } - module_categories_.is_initialized = true; + builtin_categories_.is_initialized = true; } -const std::set& NativeModuleLoader::GetCannotBeRequired() { - InitializeModuleCategories(); - return module_categories_.cannot_be_required; +const std::set& BuiltinLoader::GetCannotBeRequired() { + InitializeBuiltinCategories(); + return builtin_categories_.cannot_be_required; } -const std::set& NativeModuleLoader::GetCanBeRequired() { - InitializeModuleCategories(); - return module_categories_.can_be_required; +const std::set& BuiltinLoader::GetCanBeRequired() { + InitializeBuiltinCategories(); + return builtin_categories_.can_be_required; } -bool NativeModuleLoader::CanBeRequired(const char* id) { +bool BuiltinLoader::CanBeRequired(const char* id) { return GetCanBeRequired().count(id) == 1; } -bool NativeModuleLoader::CannotBeRequired(const char* id) { +bool BuiltinLoader::CannotBeRequired(const char* id) { return GetCannotBeRequired().count(id) == 1; } -NativeModuleCacheMap* NativeModuleLoader::code_cache() { +BuiltinCodeCacheMap* BuiltinLoader::code_cache() { return &code_cache_; } -ScriptCompiler::CachedData* NativeModuleLoader::GetCodeCache( - const char* id) const { +ScriptCompiler::CachedData* BuiltinLoader::GetCodeCache(const char* id) const { Mutex::ScopedLock lock(code_cache_mutex_); const auto it = code_cache_.find(id); if (it == code_cache_.end()) { @@ -172,10 +173,10 @@ ScriptCompiler::CachedData* NativeModuleLoader::GetCodeCache( return it->second.get(); } -MaybeLocal NativeModuleLoader::CompileAsModule( +MaybeLocal BuiltinLoader::CompileAsModule( Local context, const char* id, - NativeModuleLoader::Result* result) { + BuiltinLoader::Result* result) { Isolate* isolate = context->GetIsolate(); std::vector> parameters = { FIXED_ONE_BYTE_STRING(isolate, "exports"), @@ -204,8 +205,8 @@ static std::string OnDiskFileName(const char* id) { } #endif // NODE_BUILTIN_MODULES_PATH -MaybeLocal NativeModuleLoader::LoadBuiltinModuleSource(Isolate* isolate, - const char* id) { +MaybeLocal BuiltinLoader::LoadBuiltinSource(Isolate* isolate, + const char* id) { #ifdef NODE_BUILTIN_MODULES_PATH if (strncmp(id, "embedder_main_", strlen("embedder_main_")) == 0) { #endif // NODE_BUILTIN_MODULES_PATH @@ -238,16 +239,16 @@ MaybeLocal NativeModuleLoader::LoadBuiltinModuleSource(Isolate* isolate, // Returns Local of the compiled module if return_code_cache // is false (we are only compiling the function). // Otherwise return a Local containing the cache. -MaybeLocal NativeModuleLoader::LookupAndCompile( +MaybeLocal BuiltinLoader::LookupAndCompile( Local context, const char* id, std::vector>* parameters, - NativeModuleLoader::Result* result) { + BuiltinLoader::Result* result) { Isolate* isolate = context->GetIsolate(); EscapableHandleScope scope(isolate); Local source; - if (!LoadBuiltinModuleSource(isolate, id).ToLocal(&source)) { + if (!LoadBuiltinSource(isolate, id).ToLocal(&source)) { return {}; } @@ -286,7 +287,7 @@ MaybeLocal NativeModuleLoader::LookupAndCompile( nullptr, options); - // This could fail when there are early errors in the native modules, + // This could fail when there are early errors in the built-in modules, // e.g. the syntax errors Local fun; if (!maybe_fun.ToLocal(&fun)) { @@ -320,5 +321,5 @@ MaybeLocal NativeModuleLoader::LookupAndCompile( return scope.Escape(fun); } -} // namespace native_module +} // namespace builtins } // namespace node diff --git a/src/node_native_module.h b/src/node_builtins.h similarity index 60% rename from src/node_native_module.h rename to src/node_builtins.h index 7acd154d419de8..21bcfe032764f5 100644 --- a/src/node_native_module.h +++ b/src/node_builtins.h @@ -1,5 +1,5 @@ -#ifndef SRC_NODE_NATIVE_MODULE_H_ -#define SRC_NODE_NATIVE_MODULE_H_ +#ifndef SRC_NODE_BUILTINS_H_ +#define SRC_NODE_BUILTINS_H_ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS @@ -15,32 +15,27 @@ class PerProcessTest; namespace node { -namespace native_module { +namespace builtins { -using NativeModuleRecordMap = std::map; -using NativeModuleCacheMap = +using BuiltinSourceMap = std::map; +using BuiltinCodeCacheMap = std::unordered_map>; -// The native (C++) side of the NativeModule in JS land, which -// handles compilation and caching of builtin modules (NativeModule) -// and bootstrappers, whose source are bundled into the binary -// as static data. -// This class should not depend on any Environment, or depend on access to -// the its own singleton - that should be encapsulated in NativeModuleEnv -// instead. -class NODE_EXTERN_PRIVATE NativeModuleLoader { +// Handles compilation and caching of built-in JavaScript modules and +// bootstrap scripts, whose source are bundled into the binary as static data. +class NODE_EXTERN_PRIVATE BuiltinLoader { public: - NativeModuleLoader(const NativeModuleLoader&) = delete; - NativeModuleLoader& operator=(const NativeModuleLoader&) = delete; + BuiltinLoader(const BuiltinLoader&) = delete; + BuiltinLoader& operator=(const BuiltinLoader&) = delete; private: // Only allow access from friends. - friend class NativeModuleEnv; + friend class BuiltinEnv; friend class CodeCacheBuilder; - NativeModuleLoader(); - static NativeModuleLoader* GetInstance(); + BuiltinLoader(); + static BuiltinLoader* GetInstance(); // Generated by tools/js2c.py as node_javascript.cc void LoadJavaScriptSource(); // Loads data into source_ @@ -51,25 +46,25 @@ class NODE_EXTERN_PRIVATE NativeModuleLoader { v8::Local GetSourceObject(v8::Local context); v8::Local GetConfigString(v8::Isolate* isolate); - std::vector GetModuleIds(); + std::vector GetBuiltinIds(); - struct ModuleCategories { + struct BuiltinCategories { bool is_initialized = false; std::set can_be_required; std::set cannot_be_required; }; - void InitializeModuleCategories(); + void InitializeBuiltinCategories(); const std::set& GetCannotBeRequired(); const std::set& GetCanBeRequired(); bool CanBeRequired(const char* id); bool CannotBeRequired(const char* id); - NativeModuleCacheMap* code_cache(); + BuiltinCodeCacheMap* code_cache(); v8::ScriptCompiler::CachedData* GetCodeCache(const char* id) const; enum class Result { kWithCache, kWithoutCache }; - v8::MaybeLocal LoadBuiltinModuleSource(v8::Isolate* isolate, - const char* id); + v8::MaybeLocal LoadBuiltinSource(v8::Isolate* isolate, + const char* id); // If an exception is encountered (e.g. source code contains // syntax error), the returned value is empty. v8::MaybeLocal LookupAndCompile( @@ -81,10 +76,10 @@ class NODE_EXTERN_PRIVATE NativeModuleLoader { const char* id, Result* result); - static NativeModuleLoader instance_; - ModuleCategories module_categories_; - NativeModuleRecordMap source_; - NativeModuleCacheMap code_cache_; + static BuiltinLoader instance_; + BuiltinCategories builtin_categories_; + BuiltinSourceMap source_; + BuiltinCodeCacheMap code_cache_; UnionBytes config_; // Used to synchronize access to the code cache map @@ -92,10 +87,10 @@ class NODE_EXTERN_PRIVATE NativeModuleLoader { friend class ::PerProcessTest; }; -} // namespace native_module +} // namespace builtins } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_NODE_NATIVE_MODULE_H_ +#endif // SRC_NODE_BUILTINS_H_ diff --git a/src/node_native_module_env.cc b/src/node_builtins_env.cc similarity index 70% rename from src/node_native_module_env.cc rename to src/node_builtins_env.cc index 523c5152f3c8dc..a115591ca2df52 100644 --- a/src/node_native_module_env.cc +++ b/src/node_builtins_env.cc @@ -1,9 +1,9 @@ -#include "node_native_module_env.h" +#include "node_builtins_env.h" #include "env-inl.h" #include "node_external_reference.h" namespace node { -namespace native_module { +namespace builtins { using v8::Context; using v8::DEFAULT; @@ -33,23 +33,23 @@ Local ToJsSet(Local context, const std::set& in) { return out; } -bool NativeModuleEnv::Add(const char* id, const UnionBytes& source) { - return NativeModuleLoader::GetInstance()->Add(id, source); +bool BuiltinEnv::Add(const char* id, const UnionBytes& source) { + return BuiltinLoader::GetInstance()->Add(id, source); } -bool NativeModuleEnv::Exists(const char* id) { - return NativeModuleLoader::GetInstance()->Exists(id); +bool BuiltinEnv::Exists(const char* id) { + return BuiltinLoader::GetInstance()->Exists(id); } -Local NativeModuleEnv::GetSourceObject(Local context) { - return NativeModuleLoader::GetInstance()->GetSourceObject(context); +Local BuiltinEnv::GetSourceObject(Local context) { + return BuiltinLoader::GetInstance()->GetSourceObject(context); } -Local NativeModuleEnv::GetConfigString(Isolate* isolate) { - return NativeModuleLoader::GetInstance()->GetConfigString(isolate); +Local BuiltinEnv::GetConfigString(Isolate* isolate) { + return BuiltinLoader::GetInstance()->GetConfigString(isolate); } -void NativeModuleEnv::GetModuleCategories( +void BuiltinEnv::GetModuleCategories( Local property, const PropertyCallbackInfo& info) { Environment* env = Environment::GetCurrent(info); Isolate* isolate = env->isolate(); @@ -58,9 +58,9 @@ void NativeModuleEnv::GetModuleCategories( // Copy from the per-process categories std::set cannot_be_required = - NativeModuleLoader::GetInstance()->GetCannotBeRequired(); + BuiltinLoader::GetInstance()->GetCannotBeRequired(); std::set can_be_required = - NativeModuleLoader::GetInstance()->GetCanBeRequired(); + BuiltinLoader::GetInstance()->GetCanBeRequired(); if (!env->owns_process_state()) { can_be_required.erase("trace_events"); @@ -80,7 +80,7 @@ void NativeModuleEnv::GetModuleCategories( info.GetReturnValue().Set(result); } -void NativeModuleEnv::GetCacheUsage(const FunctionCallbackInfo& args) { +void BuiltinEnv::GetCacheUsage(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); Local context = env->context(); @@ -88,56 +88,56 @@ void NativeModuleEnv::GetCacheUsage(const FunctionCallbackInfo& args) { result ->Set(env->context(), OneByteString(isolate, "compiledWithCache"), - ToJsSet(context, env->native_modules_with_cache)) + ToJsSet(context, env->builtins_with_cache)) .FromJust(); result ->Set(env->context(), OneByteString(isolate, "compiledWithoutCache"), - ToJsSet(context, env->native_modules_without_cache)) + ToJsSet(context, env->builtins_without_cache)) .FromJust(); result ->Set(env->context(), OneByteString(isolate, "compiledInSnapshot"), - ToV8Value(env->context(), env->native_modules_in_snapshot) + ToV8Value(env->context(), env->builtins_in_snapshot) .ToLocalChecked()) .FromJust(); args.GetReturnValue().Set(result); } -void NativeModuleEnv::ModuleIdsGetter(Local property, +void BuiltinEnv::ModuleIdsGetter(Local property, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); std::vector ids = - NativeModuleLoader::GetInstance()->GetModuleIds(); + BuiltinLoader::GetInstance()->GetBuiltinIds(); info.GetReturnValue().Set( ToV8Value(isolate->GetCurrentContext(), ids).ToLocalChecked()); } -void NativeModuleEnv::ConfigStringGetter( +void BuiltinEnv::ConfigStringGetter( Local property, const PropertyCallbackInfo& info) { info.GetReturnValue().Set(GetConfigString(info.GetIsolate())); } -void NativeModuleEnv::RecordResult(const char* id, - NativeModuleLoader::Result result, +void BuiltinEnv::RecordResult(const char* id, + BuiltinLoader::Result result, Environment* env) { - if (result == NativeModuleLoader::Result::kWithCache) { - env->native_modules_with_cache.insert(id); + if (result == BuiltinLoader::Result::kWithCache) { + env->builtins_with_cache.insert(id); } else { - env->native_modules_without_cache.insert(id); + env->builtins_without_cache.insert(id); } } -void NativeModuleEnv::CompileFunction(const FunctionCallbackInfo& args) { +void BuiltinEnv::CompileFunction(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsString()); node::Utf8Value id_v(env->isolate(), args[0].As()); const char* id = *id_v; - NativeModuleLoader::Result result; + BuiltinLoader::Result result; MaybeLocal maybe = - NativeModuleLoader::GetInstance()->CompileAsModule( + BuiltinLoader::GetInstance()->CompileAsModule( env->context(), id, &result); RecordResult(id, result, env); Local fn; @@ -149,14 +149,14 @@ void NativeModuleEnv::CompileFunction(const FunctionCallbackInfo& args) { // Returns Local of the compiled module if return_code_cache // is false (we are only compiling the function). // Otherwise return a Local containing the cache. -MaybeLocal NativeModuleEnv::LookupAndCompile( +MaybeLocal BuiltinEnv::LookupAndCompile( Local context, const char* id, std::vector>* parameters, Environment* optional_env) { - NativeModuleLoader::Result result; + BuiltinLoader::Result result; MaybeLocal maybe = - NativeModuleLoader::GetInstance()->LookupAndCompile( + BuiltinLoader::GetInstance()->LookupAndCompile( context, id, parameters, &result); if (optional_env != nullptr) { RecordResult(id, result, optional_env); @@ -172,7 +172,7 @@ void HasCachedBuiltins(const FunctionCallbackInfo& args) { // TODO(joyeecheung): It is somewhat confusing that Class::Initialize // is used to initialize to the binding, but it is the current convention. // Rename this across the code base to something that makes more sense. -void NativeModuleEnv::Initialize(Local target, +void BuiltinEnv::Initialize(Local target, Local unused, Local context, void* priv) { @@ -190,7 +190,7 @@ void NativeModuleEnv::Initialize(Local target, .Check(); target ->SetAccessor(context, - FIXED_ONE_BYTE_STRING(env->isolate(), "moduleIds"), + FIXED_ONE_BYTE_STRING(env->isolate(), "builtinIds"), ModuleIdsGetter, nullptr, MaybeLocal(), @@ -210,15 +210,15 @@ void NativeModuleEnv::Initialize(Local target, SideEffectType::kHasNoSideEffect) .Check(); - SetMethod(context, target, "getCacheUsage", NativeModuleEnv::GetCacheUsage); + SetMethod(context, target, "getCacheUsage", BuiltinEnv::GetCacheUsage); SetMethod( - context, target, "compileFunction", NativeModuleEnv::CompileFunction); + context, target, "compileFunction", BuiltinEnv::CompileFunction); SetMethod(context, target, "hasCachedBuiltins", HasCachedBuiltins); - // internalBinding('native_module') should be frozen + // internalBinding('builtins') should be frozen target->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromJust(); } -void NativeModuleEnv::RegisterExternalReferences( +void BuiltinEnv::RegisterExternalReferences( ExternalReferenceRegistry* registry) { registry->Register(ConfigStringGetter); registry->Register(ModuleIdsGetter); @@ -228,11 +228,11 @@ void NativeModuleEnv::RegisterExternalReferences( registry->Register(HasCachedBuiltins); } -} // namespace native_module +} // namespace builtins } // namespace node NODE_MODULE_CONTEXT_AWARE_INTERNAL( - native_module, node::native_module::NativeModuleEnv::Initialize) + builtins, node::builtins::BuiltinEnv::Initialize) NODE_MODULE_EXTERNAL_REFERENCE( - native_module, - node::native_module::NativeModuleEnv::RegisterExternalReferences) + builtins, + node::builtins::BuiltinEnv::RegisterExternalReferences) diff --git a/src/node_native_module_env.h b/src/node_builtins_env.h similarity index 80% rename from src/node_native_module_env.h rename to src/node_builtins_env.h index 0a53771ff5d1ca..77634efad1996b 100644 --- a/src/node_native_module_env.h +++ b/src/node_builtins_env.h @@ -1,19 +1,19 @@ -#ifndef SRC_NODE_NATIVE_MODULE_ENV_H_ -#define SRC_NODE_NATIVE_MODULE_ENV_H_ +#ifndef SRC_NODE_BUILTINS_ENV_H_ +#define SRC_NODE_BUILTINS_ENV_H_ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_native_module.h" +#include "node_builtins.h" namespace node { class Environment; class ExternalReferenceRegistry; -namespace native_module { +namespace builtins { extern const bool has_code_cache; -class NativeModuleEnv { +class BuiltinEnv { public: static void RegisterExternalReferences(ExternalReferenceRegistry* registry); static void Initialize(v8::Local target, @@ -33,7 +33,7 @@ class NativeModuleEnv { static bool Exists(const char* id); static bool Add(const char* id, const UnionBytes& source); - // Loads data into NativeModuleLoader::.instance.code_cache_ + // Loads data into BuiltinLoader::.instance.code_cache_ // Generated by mkcodecache as node_code_cache.cc when // the build is configured with --code-cache-path=.... They are noops // in node_code_cache_stub.cc @@ -41,17 +41,17 @@ class NativeModuleEnv { private: static void RecordResult(const char* id, - NativeModuleLoader::Result result, + BuiltinLoader::Result result, Environment* env); static void GetModuleCategories( v8::Local property, const v8::PropertyCallbackInfo& info); static void GetCacheUsage(const v8::FunctionCallbackInfo& args); // Passing ids of builtin module source code into JS land as - // internalBinding('native_module').moduleIds + // internalBinding('builtins').builtinIds static void ModuleIdsGetter(v8::Local property, const v8::PropertyCallbackInfo& info); - // Passing config.gypi into JS land as internalBinding('native_module').config + // Passing config.gypi into JS land as internalBinding('builtins').config static void ConfigStringGetter( v8::Local property, const v8::PropertyCallbackInfo& info); @@ -59,10 +59,10 @@ class NativeModuleEnv { static void CompileFunction(const v8::FunctionCallbackInfo& args); }; -} // namespace native_module +} // namespace builtins } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_NODE_NATIVE_MODULE_ENV_H_ +#endif // SRC_NODE_BUILTINS_ENV_H_ diff --git a/src/node_code_cache_stub.cc b/src/node_code_cache_stub.cc index 9d9901738f63b0..b668380f9d9b26 100644 --- a/src/node_code_cache_stub.cc +++ b/src/node_code_cache_stub.cc @@ -2,7 +2,7 @@ // NODE_WANT_INTERNALS, so we define it here manually. #define NODE_WANT_INTERNALS 1 -#include "node_native_module_env.h" +#include "node_builtins_env.h" // The stub here is used when configure is run without `--code-cache-path`. // When --code-cache-path is set this stub will not be used and instead @@ -10,13 +10,13 @@ // more information. namespace node { -namespace native_module { +namespace builtins { const bool has_code_cache = false; // The generated source code would insert pairs // into NativeModuleLoader::instance.code_cache_. -void NativeModuleEnv::InitializeCodeCache() {} +void BuiltinEnv::InitializeCodeCache() {} -} // namespace native_module +} // namespace builtins } // namespace node diff --git a/src/node_config.cc b/src/node_config.cc index 176daa88b0fab1..49e5de25581c40 100644 --- a/src/node_config.cc +++ b/src/node_config.cc @@ -1,8 +1,9 @@ #include "env-inl.h" #include "memory_tracker.h" #include "node.h" +#include "node_builtins.h" #include "node_i18n.h" -#include "node_native_module_env.h" +#include "node_builtins_env.h" #include "node_options.h" #include "util-inl.h" diff --git a/src/node_errors.h b/src/node_errors.h index 7e0d3a3b26ca32..f9332d04fb9bc5 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -167,7 +167,7 @@ ERRORS_WITH_CODE(V) "The V8 platform used by this instance of Node does not support " \ "creating Workers") \ V(ERR_NON_CONTEXT_AWARE_DISABLED, \ - "Loading non context-aware native modules has been disabled") \ + "Loading non context-aware native addons has been disabled") \ V(ERR_SCRIPT_EXECUTION_INTERRUPTED, \ "Script execution was interrupted by `SIGINT`") \ V(ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED, "Failed to set PSK identity hint") \ diff --git a/src/node_external_reference.h b/src/node_external_reference.h index 306c726631a214..9f50f623510dfa 100644 --- a/src/node_external_reference.h +++ b/src/node_external_reference.h @@ -56,6 +56,7 @@ class ExternalReferenceRegistry { V(binding) \ V(blob) \ V(buffer) \ + V(builtins) \ V(contextify) \ V(credentials) \ V(env_var) \ @@ -67,7 +68,6 @@ class ExternalReferenceRegistry { V(heap_utils) \ V(messaging) \ V(mksnapshot) \ - V(native_module) \ V(options) \ V(os) \ V(performance) \ diff --git a/src/node_internals.h b/src/node_internals.h index f7314c906e5806..de4ae22fe3da7a 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -43,8 +43,8 @@ struct sockaddr; namespace node { -namespace native_module { -class NativeModuleLoader; +namespace builtins { +class BuiltinLoader; } namespace per_process { diff --git a/src/node_main_instance.cc b/src/node_main_instance.cc index 07dc4d88a7f8b4..e4101bbcff2c11 100644 --- a/src/node_main_instance.cc +++ b/src/node_main_instance.cc @@ -1,6 +1,7 @@ #include "node_main_instance.h" #include #include "debug_utils-inl.h" +#include "node_builtins.h" #include "node_external_reference.h" #include "node_internals.h" #include "node_options-inl.h" diff --git a/test/addons/force-context-aware/test.js b/test/addons/force-context-aware/test.js index cc2ed940d9223d..d4a0ab3e614204 100644 --- a/test/addons/force-context-aware/test.js +++ b/test/addons/force-context-aware/test.js @@ -5,4 +5,4 @@ const assert = require('assert'); assert.throws(() => { require(`./build/${common.buildType}/binding`); -}, /^Error: Loading non context-aware native modules has been disabled$/); +}, /^Error: Loading non context-aware native addons has been disabled$/); diff --git a/test/addons/symlinked-module/test.js b/test/addons/symlinked-module/test.js index cbd01e938fe25f..d47a84b98d1ed8 100644 --- a/test/addons/symlinked-module/test.js +++ b/test/addons/symlinked-module/test.js @@ -4,7 +4,7 @@ const fs = require('fs'); const path = require('path'); const assert = require('assert'); -// This test verifies that symlinked native modules can be required multiple +// This test verifies that symlinked native addons can be required multiple // times without error. The symlinked module and the non-symlinked module // should be the same instance. This expectation was not previously being // tested and ended up being broken by https://github.com/nodejs/node/pull/5950. diff --git a/test/cctest/test_per_process.cc b/test/cctest/test_per_process.cc index 43af8dd65a72d0..1e3dff7114e337 100644 --- a/test/cctest/test_per_process.cc +++ b/test/cctest/test_per_process.cc @@ -1,18 +1,17 @@ -#include "node_native_module.h" +#include "node_builtins.h" #include "gtest/gtest.h" #include "node_test_fixture.h" #include - -using node::native_module::NativeModuleLoader; -using node::native_module::NativeModuleRecordMap; +using node::builtins::BuiltinLoader; +using node::builtins::BuiltinSourceMap; class PerProcessTest : public ::testing::Test { protected: - static const NativeModuleRecordMap get_sources_for_test() { - return NativeModuleLoader::instance_.source_; + static const BuiltinSourceMap get_sources_for_test() { + return BuiltinLoader::instance_.source_; } }; @@ -20,15 +19,13 @@ namespace { TEST_F(PerProcessTest, EmbeddedSources) { const auto& sources = PerProcessTest::get_sources_for_test(); - ASSERT_TRUE( - std::any_of(sources.cbegin(), sources.cend(), - [](auto p){ return p.second.is_one_byte(); })) - << "NativeModuleLoader::source_ should have some 8bit items"; - - ASSERT_TRUE( - std::any_of(sources.cbegin(), sources.cend(), - [](auto p){ return !p.second.is_one_byte(); })) - << "NativeModuleLoader::source_ should have some 16bit items"; + ASSERT_TRUE(std::any_of(sources.cbegin(), sources.cend(), [](auto p) { + return p.second.is_one_byte(); + })) << "BuiltinLoader::source_ should have some 8bit items"; + + ASSERT_TRUE(std::any_of(sources.cbegin(), sources.cend(), [](auto p) { + return !p.second.is_one_byte(); + })) << "BuiltinLoader::source_ should have some 16bit items"; } } // end namespace diff --git a/test/node-api/test_general/test.js b/test/node-api/test_general/test.js index 77550c02927fb4..f51ef2367f5b90 100644 --- a/test/node-api/test_general/test.js +++ b/test/node-api/test_general/test.js @@ -23,7 +23,7 @@ tmpdir.refresh(); const urlTestFile = path.join(urlTestDir, path.basename(filename)); fs.mkdirSync(urlTestDir, { recursive: true }); fs.copyFileSync(filename, urlTestFile); - // Use a child process as indirection so that the native module is not loaded + // Use a child process as indirection so that the built-in modules is not loaded // into this process and can be removed here. const reportedFilename = child_process.spawnSync( process.execPath, diff --git a/test/parallel/test-bootstrap-modules.js b/test/parallel/test-bootstrap-modules.js index d108b9a6cf5286..a74d27dfaaafad 100644 --- a/test/parallel/test-bootstrap-modules.js +++ b/test/parallel/test-bootstrap-modules.js @@ -12,6 +12,7 @@ const expectedModules = new Set([ 'Internal Binding async_wrap', 'Internal Binding block_list', 'Internal Binding buffer', + 'Internal Binding builtins', 'Internal Binding config', 'Internal Binding constants', 'Internal Binding contextify', @@ -24,7 +25,6 @@ const expectedModules = new Set([ 'Internal Binding mksnapshot', 'Internal Binding messaging', 'Internal Binding module_wrap', - 'Internal Binding native_module', 'Internal Binding options', 'Internal Binding performance', 'Internal Binding pipe_wrap', diff --git a/test/parallel/test-code-cache.js b/test/parallel/test-code-cache.js index f61ed9f5c54077..661206896d97f5 100644 --- a/test/parallel/test-code-cache.js +++ b/test/parallel/test-code-cache.js @@ -13,7 +13,7 @@ const { const { getCacheUsage, moduleCategories: { canBeRequired, cannotBeRequired } -} = internalBinding('native_module'); +} = internalBinding('builtins'); for (const key of canBeRequired) { require(`node:${key}`); diff --git a/tools/code_cache/README.md b/tools/code_cache/README.md index 8feb280caae585..34726451a81df6 100644 --- a/tools/code_cache/README.md +++ b/tools/code_cache/README.md @@ -18,8 +18,8 @@ In the default build of the Node.js executable, to embed the V8 code cache of the native modules into the Node.js executable, `libnode` is first built with these unresolved symbols: -- `node::native_module::has_code_cache` -- `node::native_module::NativeModuleEnv::InitializeCodeCache` +- `node::builtins::has_code_cache` +- `node::builtins::NativeModuleEnv::InitializeCodeCache` Then the `mkcodecache` executable is built with C++ files in this directory, as well as `src/node_code_cache_stub.cc` which defines the unresolved symbols. diff --git a/tools/code_cache/cache_builder.cc b/tools/code_cache/cache_builder.cc index 837357a0fbda76..6d253d955d82af 100644 --- a/tools/code_cache/cache_builder.cc +++ b/tools/code_cache/cache_builder.cc @@ -1,6 +1,7 @@ #include "cache_builder.h" #include "debug_utils-inl.h" -#include "node_native_module.h" +#include "node_builtins.h" +#include "node_builtins_env.h" #include "util.h" #include @@ -10,7 +11,7 @@ #include namespace node { -namespace native_module { +namespace builtins { using v8::Context; using v8::Local; @@ -68,12 +69,12 @@ static std::string GenerateCodeCache( const std::map& data) { std::stringstream ss; ss << R"(#include -#include "node_native_module_env.h" +#include "node_builtins_env.h" // This file is generated by mkcodecache (tools/code_cache/mkcodecache.cc) namespace node { -namespace native_module { +namespace builtins { const bool has_code_cache = true; @@ -95,9 +96,9 @@ const bool has_code_cache = true; total_str.c_str()); } - ss << R"(void NativeModuleEnv::InitializeCodeCache() { - NativeModuleCacheMap& code_cache = - *NativeModuleLoader::GetInstance()->code_cache(); + ss << R"(void BuiltinEnv::InitializeCodeCache() { + BuiltinCodeCacheMap& code_cache = + *BuiltinLoader::GetInstance()->code_cache(); CHECK(code_cache.empty()); auto policy = v8::ScriptCompiler::CachedData::BufferPolicy::BufferNotOwned; )"; @@ -110,15 +111,15 @@ const bool has_code_cache = true; ss << R"( } -} // namespace native_module +} // namespace builtins } // namespace node )"; return ss.str(); } std::string CodeCacheBuilder::Generate(Local context) { - NativeModuleLoader* loader = NativeModuleLoader::GetInstance(); - std::vector ids = loader->GetModuleIds(); + BuiltinLoader* loader = BuiltinLoader::GetInstance(); + std::vector ids = loader->GetBuiltinIds(); std::map data; @@ -128,7 +129,7 @@ std::string CodeCacheBuilder::Generate(Local context) { // are still very flexible. We should look into auto-generating // the parameters from the source somehow. if (loader->CanBeRequired(id.c_str())) { - NativeModuleLoader::Result result; + BuiltinLoader::Result result; USE(loader->CompileAsModule(context, id.c_str(), &result)); ScriptCompiler::CachedData* cached_data = loader->GetCodeCache(id.c_str()); @@ -144,5 +145,5 @@ std::string CodeCacheBuilder::Generate(Local context) { return GenerateCodeCache(data); } -} // namespace native_module +} // namespace builtins } // namespace node diff --git a/tools/code_cache/cache_builder.h b/tools/code_cache/cache_builder.h index d5a6cd4241dfb0..11f51e463d6107 100644 --- a/tools/code_cache/cache_builder.h +++ b/tools/code_cache/cache_builder.h @@ -5,12 +5,12 @@ #include "v8.h" namespace node { -namespace native_module { +namespace builtins { class CodeCacheBuilder { public: static std::string Generate(v8::Local context); }; -} // namespace native_module +} // namespace builtins } // namespace node #endif // TOOLS_CODE_CACHE_CACHE_BUILDER_H_ diff --git a/tools/code_cache/mkcodecache.cc b/tools/code_cache/mkcodecache.cc index babf8535dbb3e7..41028784d69d10 100644 --- a/tools/code_cache/mkcodecache.cc +++ b/tools/code_cache/mkcodecache.cc @@ -9,7 +9,7 @@ #include "libplatform/libplatform.h" #include "v8.h" -using node::native_module::CodeCacheBuilder; +using node::builtins::CodeCacheBuilder; using v8::ArrayBuffer; using v8::Context; using v8::HandleScope; diff --git a/tools/js2c.py b/tools/js2c.py index d93be2123e0f8c..e295949a18508d 100755 --- a/tools/js2c.py +++ b/tools/js2c.py @@ -48,24 +48,24 @@ def ReadFile(filename): TEMPLATE = """ #include "env-inl.h" -#include "node_native_module.h" +#include "node_builtins.h" #include "node_internals.h" namespace node {{ -namespace native_module {{ +namespace builtins {{ {0} -void NativeModuleLoader::LoadJavaScriptSource() {{ +void BuiltinLoader::LoadJavaScriptSource() {{ {1} }} -UnionBytes NativeModuleLoader::GetConfig() {{ +UnionBytes BuiltinLoader::GetConfig() {{ return UnionBytes(config_raw, {2}); // config.gypi }} -}} // namespace native_module +}} // namespace builtins }} // namespace node """