Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/internal/main/embedding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';
const {
prepareMainThreadExecution,
markBootstrapComplete,
} = require('internal/process/pre_execution');
const { isSea } = internalBinding('sea');
const { emitExperimentalWarning } = require('internal/util');
const { embedderRequire, embedderRunCjs } = require('internal/util/embedding');
const { getEmbedderEntryFunction } = internalBinding('mksnapshot');

prepareMainThreadExecution(false, true);
markBootstrapComplete();

if (isSea) {
emitExperimentalWarning('Single executable application');
}

return getEmbedderEntryFunction()(embedderRequire, embedderRunCjs);
13 changes: 0 additions & 13 deletions lib/internal/main/environment.js

This file was deleted.

11 changes: 10 additions & 1 deletion lib/internal/main/mksnapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,25 @@ function main() {
const {
prepareMainThreadExecution
} = require('internal/process/pre_execution');
const path = require('path');

let serializeMainFunction = getEmbedderEntryFunction();
const serializeMainArgs = [requireForUserSnapshot];

if (serializeMainFunction) { // embedded case
prepareMainThreadExecution(false, false);
// TODO(addaleax): Make this `embedderRunCjs` once require('module')
// is supported in snapshots.
const filename = process.execPath;
const dirname = path.dirname(filename);
function minimalRunCjs(source) {
const fn = compileSerializeMain(filename, source);
return fn(requireForUserSnapshot, filename, dirname);
}
serializeMainArgs.push(minimalRunCjs);
} else {
prepareMainThreadExecution(true, false);
const file = process.argv[1];
const path = require('path');
const filename = path.resolve(file);
const dirname = path.dirname(filename);
const source = readFileSync(file, 'utf-8');
Expand Down
55 changes: 0 additions & 55 deletions lib/internal/main/single_executable_application.js

This file was deleted.

47 changes: 47 additions & 0 deletions lib/internal/util/embedding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict';
const { codes: { ERR_UNKNOWN_BUILTIN_MODULE } } = require('internal/errors');
const { Module, wrapSafe } = require('internal/modules/cjs/loader');

// This is roughly the same as:
//
// const mod = new Module(filename);
// mod._compile(contents, filename);
//
// but the code has been duplicated because currently there is no way to set the
// value of require.main to module.
//
// TODO(RaisinTen): Find a way to deduplicate this.

function embedderRunCjs(contents) {
const filename = process.execPath;
const compiledWrapper = wrapSafe(filename, contents);

const customModule = new Module(filename, null);
customModule.filename = filename;
customModule.paths = Module._nodeModulePaths(customModule.path);

const customExports = customModule.exports;

embedderRequire.main = customModule;

const customFilename = customModule.filename;

const customDirname = customModule.path;

return compiledWrapper(
customExports,
embedderRequire,
customModule,
customFilename,
customDirname);
}

function embedderRequire(path) {
if (!Module.isBuiltin(path)) {
Comment thread
joyeecheung marked this conversation as resolved.
throw new ERR_UNKNOWN_BUILTIN_MODULE(path);
}

return require(path);
}

module.exports = { embedderRequire, embedderRunCjs };
16 changes: 7 additions & 9 deletions src/api/environment.cc
Original file line number Diff line number Diff line change
Expand Up @@ -528,17 +528,15 @@ MaybeLocal<Value> LoadEnvironment(
return StartExecution(env, cb);
}

MaybeLocal<Value> LoadEnvironment(
Environment* env,
const char* main_script_source_utf8) {
CHECK_NOT_NULL(main_script_source_utf8);
MaybeLocal<Value> LoadEnvironment(Environment* env,
std::string_view main_script_source_utf8) {
CHECK_NOT_NULL(main_script_source_utf8.data());
return LoadEnvironment(
env, [&](const StartExecutionCallbackInfo& info) -> MaybeLocal<Value> {
std::string name = "embedder_main_" + std::to_string(env->thread_id());
Comment thread
addaleax marked this conversation as resolved.
env->builtin_loader()->Add(name.c_str(), main_script_source_utf8);
Realm* realm = env->principal_realm();

return realm->ExecuteBootstrapper(name.c_str());
Local<Value> main_script =
ToV8Value(env->context(), main_script_source_utf8).ToLocalChecked();
return info.run_cjs->Call(
env->context(), Null(env->isolate()), 1, &main_script);
});
}

Expand Down
37 changes: 11 additions & 26 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@
namespace node {

using v8::EscapableHandleScope;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
Expand Down Expand Up @@ -277,22 +279,17 @@ MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {

if (cb != nullptr) {
EscapableHandleScope scope(env->isolate());
// TODO(addaleax): pass the callback to the main script more directly,
// e.g. by making StartExecution(env, builtin) parametrizable
env->set_embedder_mksnapshot_entry_point(std::move(cb));
Comment thread
joyeecheung marked this conversation as resolved.
Outdated
auto reset_entry_point =
OnScopeLeave([&]() { env->set_embedder_mksnapshot_entry_point({}); });

if (env->isolate_data()->options()->build_snapshot) {
// TODO(addaleax): pass the callback to the main script more directly,
// e.g. by making StartExecution(env, builtin) parametrizable
env->set_embedder_mksnapshot_entry_point(std::move(cb));
auto reset_entry_point =
OnScopeLeave([&]() { env->set_embedder_mksnapshot_entry_point({}); });
const char* entry = env->isolate_data()->options()->build_snapshot
? "internal/main/mksnapshot"
: "internal/main/embedding";

return StartExecution(env, "internal/main/mksnapshot");
}

if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
return scope.EscapeMaybe(cb({
env->process_object(),
env->builtin_module_require(),
}));
return scope.EscapeMaybe(StartExecution(env, entry));
}

// TODO(joyeecheung): move these conditions into JS land and let the
Expand All @@ -312,18 +309,6 @@ MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
first_argv = env->argv()[1];
}

#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
if (sea::IsSingleExecutable()) {
// TODO(addaleax): Find a way to reuse:
//
// LoadEnvironment(Environment*, const char*)
//
// instead and not add yet another main entry point here because this
// already duplicates existing code.
return StartExecution(env, "internal/main/single_executable_application");
}
#endif

if (first_argv == "inspect") {
return StartExecution(env, "internal/main/inspect");
}
Expand Down
4 changes: 2 additions & 2 deletions src/node.h
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,7 @@ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
struct StartExecutionCallbackInfo {
v8::Local<v8::Object> process_object;
v8::Local<v8::Function> native_require;
v8::Local<v8::Function> run_cjs;
};

using StartExecutionCallback =
Expand All @@ -691,8 +692,7 @@ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
Environment* env,
StartExecutionCallback cb);
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
Environment* env,
const char* main_script_source_utf8);
Environment* env, std::string_view main_script_source_utf8);
NODE_EXTERN void FreeEnvironment(Environment* env);

// Set a callback that is called when process.exit() is called from JS,
Expand Down
11 changes: 10 additions & 1 deletion src/node_main_instance.cc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "node_internals.h"
#include "node_options-inl.h"
#include "node_realm.h"
#include "node_sea.h"
#include "node_snapshot_builder.h"
#include "node_snapshotable.h"
#include "node_v8_platform-inl.h"
Expand Down Expand Up @@ -86,7 +87,15 @@ ExitCode NodeMainInstance::Run() {

void NodeMainInstance::Run(ExitCode* exit_code, Environment* env) {
if (*exit_code == ExitCode::kNoFailure) {
LoadEnvironment(env, StartExecutionCallback{});
bool is_sea = false;
#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
if (sea::IsSingleExecutable()) {
Comment thread
addaleax marked this conversation as resolved.
LoadEnvironment(env, sea::FindSingleExecutableCode());
}
#endif
if (!is_sea) {
LoadEnvironment(env, StartExecutionCallback{});
}

*exit_code =
SpinEventLoopInternal(env).FromMaybe(ExitCode::kGenericUserError);
Expand Down
52 changes: 11 additions & 41 deletions src/node_sea.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@

#if !defined(DISABLE_SINGLE_EXECUTABLE_APPLICATION)

using v8::Boolean;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;

namespace {
namespace node {
namespace sea {

const std::string_view FindSingleExecutableCode() {
std::string_view FindSingleExecutableCode() {
CHECK(IsSingleExecutable());
static const std::string_view sea_code = []() -> std::string_view {
size_t size;
#ifdef __APPLE__
Expand All @@ -49,40 +53,6 @@ const std::string_view FindSingleExecutableCode() {
return sea_code;
}

void GetSingleExecutableCode(const FunctionCallbackInfo<Value>& args) {
node::Environment* env = node::Environment::GetCurrent(args);

static const std::string_view sea_code = FindSingleExecutableCode();

if (sea_code.empty()) {
return;
}

// TODO(joyeecheung): Use one-byte strings for ASCII-only source to save
// memory/binary size - using UTF16 by default results in twice of the size
// than necessary.
static const node::UnionBytes sea_code_union_bytes =
[]() -> node::UnionBytes {
size_t expected_u16_length =
simdutf::utf16_length_from_utf8(sea_code.data(), sea_code.size());
Comment thread
addaleax marked this conversation as resolved.
auto out = std::make_shared<std::vector<uint16_t>>(expected_u16_length);
size_t u16_length = simdutf::convert_utf8_to_utf16(
sea_code.data(),
sea_code.size(),
reinterpret_cast<char16_t*>(out->data()));
out->resize(u16_length);
return node::UnionBytes{out};
}();

args.GetReturnValue().Set(
sea_code_union_bytes.ToStringChecked(env->isolate()));
}

} // namespace

namespace node {
namespace sea {

bool IsSingleExecutable() {
return postject_has_resource();
}
Expand Down Expand Up @@ -113,13 +83,13 @@ void Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
SetMethod(
context, target, "getSingleExecutableCode", GetSingleExecutableCode);
Environment* env = Environment::GetCurrent(context);
Isolate* isolate = env->isolate();
READONLY_PROPERTY(
Comment thread
joyeecheung marked this conversation as resolved.
Outdated
target, "isSea", Boolean::New(isolate, IsSingleExecutable()));
}

void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(GetSingleExecutableCode);
}
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {}

} // namespace sea
} // namespace node
Expand Down
2 changes: 2 additions & 0 deletions src/node_sea.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@

#if !defined(DISABLE_SINGLE_EXECUTABLE_APPLICATION)

#include <string_view>
#include <tuple>

namespace node {
namespace sea {

bool IsSingleExecutable();
std::string_view FindSingleExecutableCode();
std::tuple<int, char**> FixupArgsForSEA(int argc, char** argv);

} // namespace sea
Expand Down
Loading