Skip to content

Commit

Permalink
module: bootstrap module loaders in shadow realm
Browse files Browse the repository at this point in the history
  • Loading branch information
legendecas committed Jul 5, 2023
1 parent 59a6ca5 commit e1e63e3
Show file tree
Hide file tree
Showing 26 changed files with 476 additions and 168 deletions.
10 changes: 8 additions & 2 deletions lib/internal/bootstrap/realm.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ const internalBuiltinIds = builtinIds
.filter((id) => StringPrototypeStartsWith(id, 'internal/') && id !== selfId);

// When --expose-internals is on we'll add the internal builtin ids to these.
const canBeRequiredByUsersList = new SafeSet(publicBuiltinIds);
const canBeRequiredByUsersWithoutSchemeList =
let canBeRequiredByUsersList = new SafeSet(publicBuiltinIds);
let canBeRequiredByUsersWithoutSchemeList =
new SafeSet(publicBuiltinIds.filter((id) => !schemelessBlockList.has(id)));

/**
Expand Down Expand Up @@ -269,6 +269,12 @@ class BuiltinModule {
}
}

static setRealmAllowRequireByUsers(ids) {
canBeRequiredByUsersList = new SafeSet(ids.filter((id) => publicBuiltinIds.includes(id)));
canBeRequiredByUsersWithoutSchemeList =
new SafeSet(ids.filter((id) => !schemelessBlockList.has(id)));
}

// To be called during pre-execution when --expose-internals is on.
// Enables the user-land module loader to access internal modules.
static exposeInternals() {
Expand Down
47 changes: 47 additions & 0 deletions lib/internal/bootstrap/shadow_realm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict';

// In ShadowRealm.

const {
prepareShadowRealmExecution,
} = require('internal/process/pre_execution');
const {
BuiltinModule,
} = require('internal/bootstrap/realm');
const { setDefaultImportModuleDynamically } = require('internal/modules/esm/utils');

BuiltinModule.setRealmAllowRequireByUsers([
'assert',
'assert/strict',
'buffer',
'console',
'constants',
'cypto',
'diagnostics_channel',
'events',
'module',
'path',
'path/posix',
'path/win32',
'readline',
'readline/promises',
'repl',
'stream',
'stream/consumers',
'stream/promises',
'stream/web',
'string_decoder',
'url',
'util',
'util/types',
'zlib',
]);

prepareShadowRealmExecution();

// The handler for `ShadowRealm.prototype.importValue`.
setDefaultImportModuleDynamically((specifier, assertions) => {
const { esmLoader } = require('internal/process/esm_loader');
// `parentUrl` is not set in the case of a ShadowRealm top-level import.
return esmLoader.import(specifier, undefined, assertions);
});
5 changes: 4 additions & 1 deletion lib/internal/main/worker_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ port.on('message', (message) => {
const isLoaderWorker =
doEval === 'internal' &&
filename === require('internal/modules/esm/utils').loaderWorkerId;
setupUserModules(isLoaderWorker);
setupUserModules({
__proto__: null,
isLoaderWorker,
});

if (!hasStdin)
process.stdin.push(null);
Expand Down
9 changes: 9 additions & 0 deletions lib/internal/modules/esm/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ const {
} = internalBinding('module_wrap');
const assert = require('internal/assert');

let defaultImportModuleDynamically;
function setDefaultImportModuleDynamically(importModuleDynamically) {
defaultImportModuleDynamically = importModuleDynamically;
}

let defaultConditions;
function getDefaultConditions() {
assert(defaultConditions !== undefined);
Expand Down Expand Up @@ -139,6 +144,9 @@ async function importModuleDynamicallyCallback(symbol, specifier, assertions) {
return importModuleDynamically(specifier, callbackReferrer, assertions);
}
}
if (defaultImportModuleDynamically) {
return defaultImportModuleDynamically(specifier, assertions);
}
throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();
}

Expand Down Expand Up @@ -220,6 +228,7 @@ async function initializeHooks() {

module.exports = {
registerModule,
setDefaultImportModuleDynamically,
initializeESM,
initializeHooks,
getDefaultConditions,
Expand Down
21 changes: 19 additions & 2 deletions lib/internal/process/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const {
exposeLazyInterfaces,
defineReplaceableLazyAttribute,
setupCoverageHooks,
kEmptyObject,
} = require('internal/util');

const {
Expand Down Expand Up @@ -57,6 +58,18 @@ function prepareWorkerThreadExecution() {
});
}

function prepareShadowRealmExecution() {
// Patch the process object with legacy properties and normalizations
// Do not expand argv1 as it is not available in ShadowRealm
patchProcessObject(false);
setupDebugEnv();

setupUserModules({
__proto__: null,
noPreloadModules: true,
});
}

function prepareExecution(options) {
const { expandArgv1, initializeModules, isMainThread } = options;

Expand Down Expand Up @@ -132,12 +145,15 @@ function setupSymbolDisposePolyfill() {
Symbol.asyncDispose ??= SymbolAsyncDispose;
}

function setupUserModules(isLoaderWorker = false) {
function setupUserModules(options = kEmptyObject) {
const { isLoaderWorker = false, noPreloadModules = false } = options;
initializeCJSLoader();
initializeESMLoader(isLoaderWorker);
const CJSLoader = require('internal/modules/cjs/loader');
assert(!CJSLoader.hasLoadedAnyUserCJSModule);
loadPreloadModules();
if (!noPreloadModules) {
loadPreloadModules();
}
// Need to be done after --require setup.
initializeFrozenIntrinsics();
}
Expand Down Expand Up @@ -666,5 +682,6 @@ module.exports = {
setupUserModules,
prepareMainThreadExecution,
prepareWorkerThreadExecution,
prepareShadowRealmExecution,
markBootstrapComplete,
};
15 changes: 8 additions & 7 deletions src/async_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ void AsyncWrap::CreatePerContextProperties(Local<Object> target,
Local<Context> context,
void* priv) {
Environment* env = Environment::GetCurrent(context);
Realm* realm = Realm::GetCurrent(context);
Isolate* isolate = env->isolate();
HandleScope scope(isolate);

Expand Down Expand Up @@ -446,13 +447,13 @@ void AsyncWrap::CreatePerContextProperties(Local<Object> target,

#undef FORCE_SET_TARGET_FIELD

env->set_async_hooks_init_function(Local<Function>());
env->set_async_hooks_before_function(Local<Function>());
env->set_async_hooks_after_function(Local<Function>());
env->set_async_hooks_destroy_function(Local<Function>());
env->set_async_hooks_promise_resolve_function(Local<Function>());
env->set_async_hooks_callback_trampoline(Local<Function>());
env->set_async_hooks_binding(target);
realm->set_async_hooks_init_function(Local<Function>());
realm->set_async_hooks_before_function(Local<Function>());
realm->set_async_hooks_after_function(Local<Function>());
realm->set_async_hooks_destroy_function(Local<Function>());
realm->set_async_hooks_promise_resolve_function(Local<Function>());
realm->set_async_hooks_callback_trampoline(Local<Function>());
realm->set_async_hooks_binding(target);
}

void AsyncWrap::RegisterExternalReferences(
Expand Down
2 changes: 2 additions & 0 deletions src/env-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
}

v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
DCHECK_EQ(env()->isolate()->GetCurrentContext(),
env()->principal_realm()->context());
if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
js_execution_async_resources_.Reset(
env()->isolate(), v8::Array::New(env()->isolate()));
Expand Down
12 changes: 8 additions & 4 deletions src/env.cc
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,7 @@ void IsolateData::CreateProperties() {
binding::CreateInternalBindingTemplates(this);

contextify::ContextifyContext::InitializeGlobalTemplates(this);
CreateEnvProxyTemplate(this);
}

IsolateData::IsolateData(Isolate* isolate,
Expand Down Expand Up @@ -1587,10 +1588,13 @@ void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
void AsyncHooks::grow_async_ids_stack() {
async_ids_stack_.reserve(async_ids_stack_.Length() * 3);

env()->async_hooks_binding()->Set(
env()->context(),
env()->async_ids_stack_string(),
async_ids_stack_.GetJSArray()).Check();
env()
->principal_realm()
->async_hooks_binding()
->Set(env()->context(),
env()->async_ids_stack_string(),
async_ids_stack_.GetJSArray())
.Check();
}

void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
Expand Down
Loading

0 comments on commit e1e63e3

Please sign in to comment.