Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: add initial support for single executable applications #45038

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
6559b90
src: add initial support for single executable applications
RaisinTen Oct 21, 2022
444ca79
test: fix `'node': No such file or directory` error on CI
RaisinTen Dec 23, 2022
a30e3fc
test: fix `Cannot find module '../common'` error on Jenkins CI
RaisinTen Dec 23, 2022
5caad76
test: skip test on failing platforms
RaisinTen Dec 23, 2022
1c5968d
test: make sure that double backslashes in Windows paths aren't removed
RaisinTen Dec 23, 2022
290d69f
src: move argv replacement to another function
RaisinTen Jan 3, 2023
da1b134
doc: fix info about using notes on ELF
RaisinTen Jan 3, 2023
f08ca63
test: test code signing on Windows
RaisinTen Jan 3, 2023
afc5d75
lib,test: emit experimental warning
RaisinTen Jan 3, 2023
da74406
fixup! src: move argv replacement to another function
RaisinTen Jan 3, 2023
412d592
test: skip on debug builds on Linux
RaisinTen Jan 4, 2023
10b0fcd
test: skip on shared builds
RaisinTen Jan 4, 2023
3addc19
test: skip on --without-ssl and --shared-openssl
RaisinTen Jan 4, 2023
232ece5
test: skip on test-ibm-rhel8-s390x-1
RaisinTen Jan 4, 2023
f24e37c
test: skip on smartos
RaisinTen Jan 4, 2023
8126bb3
test: skip when cross-compiling
RaisinTen Jan 4, 2023
3c5c2cd
src: speed up case where no resource is present
RaisinTen Jan 5, 2023
b47b68d
src: use custom fuse string
RaisinTen Jan 5, 2023
2fe91c6
test: do not skip on asan builds
RaisinTen Jan 5, 2023
e0a9af3
src,doc,test: remove :0 from sentinel fuse string
RaisinTen Jan 9, 2023
665e5f8
test: skip on asan builds
RaisinTen Jan 9, 2023
fe6d488
src: change segment name from `__POSTJECT` to `NODE_JS` on macOS
RaisinTen Jan 19, 2023
8c5ba96
test: only run test on Ubuntu for Linux
RaisinTen Jan 30, 2023
2855679
test: skip on non-x64 Linux archictectures
RaisinTen Jan 31, 2023
9daeaf0
test: add back ubuntu check for linux
RaisinTen Jan 31, 2023
bf4e519
src: call IsSingleExecutable() before FindSingleExecutableCode()
RaisinTen Feb 2, 2023
a4ac355
lib: expose require without fs access
RaisinTen Feb 2, 2023
13dd503
src: wrap macho_segment_name assignment into a pre-processor for macOS
RaisinTen Feb 3, 2023
ea4a139
test: detect Ubuntu by parsing '/etc/os-release'
RaisinTen Feb 3, 2023
5664222
test: set utf8 encoding while reading
RaisinTen Feb 3, 2023
3a42a29
fixup! test: detect Ubuntu by parsing '/etc/os-release'
RaisinTen Feb 6, 2023
0eb3dee
Apply suggestions from code review
RaisinTen Feb 6, 2023
925775c
test: fix lint error
RaisinTen Feb 6, 2023
e841b26
doc: use "`node` binary" instead of just "binary"
RaisinTen Feb 8, 2023
aca1db7
doc: add note about linux support
RaisinTen Feb 8, 2023
e51708d
src: use external string
RaisinTen Feb 8, 2023
2ad8e30
src: move all SEA code to per_process::sea in node_sea.cc
RaisinTen Feb 8, 2023
2c6bb38
src: add TODO for non-ASCII character inputs
RaisinTen Feb 8, 2023
eceb1f7
src: create sea binding
RaisinTen Feb 8, 2023
732b4e0
src: add a TODO to reuse LoadEnvironment
RaisinTen Feb 8, 2023
a1b2643
src: use UnionBytes insteda of extending from ExternalOneByteStringSi…
RaisinTen Feb 9, 2023
b62393b
src: avoid storing sea statics globally
RaisinTen Feb 9, 2023
4d118cf
doc: move the second para above the first one
RaisinTen Feb 9, 2023
b040491
doc: https://github.com/nodejs/node/pull/45038#discussion_r1100745618
RaisinTen Feb 9, 2023
b4ab7f0
doc: https://github.com/nodejs/node/pull/45038#discussion_r1100746143
RaisinTen Feb 9, 2023
17a019d
build: add TODO comment to node.gyp
RaisinTen Feb 9, 2023
ec052a1
doc: https://github.com/nodejs/node/pull/45038#discussion_r1101352130
RaisinTen Feb 9, 2023
c3c1ace
test: skip asan build only on linux
RaisinTen Feb 9, 2023
2aee17f
test: move sea script to test/fixtures
RaisinTen Feb 9, 2023
d711de1
test: use execFileSync instead of execSync
RaisinTen Feb 9, 2023
e8819fb
Update test/parallel/test-single-executable-application.js
RaisinTen Feb 9, 2023
5c7bdfd
Apply suggestions from code review
RaisinTen Feb 10, 2023
44930d7
src: remove per_process nesting for the sea namespace
RaisinTen Feb 10, 2023
1747349
fixup! Apply suggestions from code review
RaisinTen Feb 10, 2023
308418e
doc: move technical details below
RaisinTen Feb 10, 2023
daa8f4d
src: fix bug from UnionBytes going out of scope
RaisinTen Feb 10, 2023
132bfcd
src: add TODO for using 1 byte strings for ASCII-only sources
RaisinTen Feb 10, 2023
a0117da
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
dfa4272
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
aef7e26
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
d63ebf1
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
6f6b7c0
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
04842d0
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
aaa4b1b
fixup! Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
0ad4016
Update doc/api/single-executable-applications.md
RaisinTen Feb 10, 2023
7ebf905
doc: add explanation to clarify the steps
RaisinTen Feb 10, 2023
eecf141
build: use postect-api.h from deps
RaisinTen Feb 11, 2023
8201ef9
Apply suggestions from code review
RaisinTen Feb 12, 2023
c276f2e
fixup! Apply suggestions from code review
RaisinTen Feb 12, 2023
7fff038
doc: clarify platform support
RaisinTen Feb 12, 2023
824945b
test: use fixtures helper for postject CLI path
RaisinTen Feb 12, 2023
b4a22ba
src: explain POSTJECT_SENTINEL_FUSE macro
RaisinTen Feb 12, 2023
e454d1b
test: skip on --with-intl=system-icu
RaisinTen Feb 17, 2023
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
10 changes: 10 additions & 0 deletions configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@
default=None,
help='use on deprecated SunOS systems that do not support ifaddrs.h')

parser.add_argument('--disable-single-executable-application',
action='store_true',
dest='disable_single_executable_application',
default=None,
help='Disable Single Executable Application support.')

parser.add_argument("--fully-static",
action="store_true",
dest="fully_static",
Expand Down Expand Up @@ -1357,6 +1363,10 @@ def configure_node(o):
if options.no_ifaddrs:
o['defines'] += ['SUNOS_NO_IFADDRS']

o['variables']['single_executable_application'] = b(not options.disable_single_executable_application)
if options.disable_single_executable_application:
o['defines'] += ['DISABLE_SINGLE_EXECUTABLE_APPLICATION']

o['variables']['node_with_ltcg'] = b(options.with_ltcg)
if flavor != 'win' and options.with_ltcg:
raise Exception('Link Time Code Generation is only supported on Windows.')
Expand Down
1 change: 1 addition & 0 deletions doc/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
* [Readline](readline.md)
* [REPL](repl.md)
* [Report](report.md)
* [Single executable applications](single-executable-applications.md)
* [Stream](stream.md)
* [String decoder](string_decoder.md)
* [Test runner](test.md)
Expand Down
140 changes: 140 additions & 0 deletions doc/api/single-executable-applications.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Single executable applications
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved

<!--introduced_in=REPLACEME-->

> Stability: 1 - Experimental: This feature is being designed and will change.

<!-- source_link=lib/internal/main/single_executable_application.js -->

This feature allows the distribution of a Node.js application conveniently to a
system that does not have Node.js installed.

Node.js supports the creation of [single executable applications][] by allowing
the injection of a JavaScript file into the `node` binary. During start up, the
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
program checks if anything has been injected. If the script is found, it
executes its contents. Otherwise Node.js operates as it normally does.

The single executable application feature only supports running a single
embedded [CommonJS][] file.

A bundled JavaScript file can be turned into a single executable application
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
with any tool which can inject resources into the `node` binary.

Here are the steps for creating a single executable application using one such
tool, [postject][]:

1. Create a JavaScript file:
```console
$ echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js
```

2. Create a copy of the `node` executable and name it according to your needs:
```console
$ cp $(command -v node) hello
```

3. Inject the JavaScript file into the copied binary by running `postject` with
the following options:

* `hello` - The name of the copy of the `node` executable created in step 2.
* `NODE_JS_CODE` - The name of the resource / note / section in the binary
where the contents of the JavaScript file will be stored.
* `hello.js` - The name of the JavaScript file created in step 1.
* `--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2` - The
[fuse][] used by the Node.js project to detect if a file has been injected.
* `--macho-segment-name NODE_JS` (only needed on macOS) - The name of the
segment in the binary where the contents of the JavaScript file will be
stored.

To summarize, here is the required command for each platform:

* On systems other than macOS:
```console
$ npx postject hello NODE_JS_CODE hello.js \
--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2
```

* On macOS:
```console
$ npx postject hello NODE_JS_CODE hello.js \
--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \
--macho-segment-name NODE_JS
```

4. Run the binary:
```console
$ ./hello world
Hello, world!
```

## Notes

### `require(id)` in the injected module is not file based

`require()` in the injected module is not the same as the [`require()`][]
available to modules that are not injected. It also does not have any of the
properties that non-injected [`require()`][] has except [`require.main`][]. It
can only be used to load built-in modules. Attempting to load a module that can
only be found in the file system will throw an error.

Instead of relying on a file based `require()`, users can bundle their
application into a standalone JavaScript file to inject into the executable.
This also ensures a more deterministic dependency graph.

However, if a file based `require()` is still needed, that can also be achieved:

```js
const { createRequire } = require('node:module');
require = createRequire(__filename);
```

### `__filename` and `module.filename` in the injected module

The values of `__filename` and `module.filename` in the injected module are
equal to [`process.execPath`][].

### `__dirname` in the injected module

The value of `__dirname` in the injected module is equal to the directory name
of [`process.execPath`][].

### Single executable application creation process
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved

A tool aiming to create a single executable Node.js application must
inject the contents of a JavaScript file into:

* a resource named `NODE_JS_CODE` if the `node` binary is a [PE][] file
* a section named `NODE_JS_CODE` in the `NODE_JS` segment if the `node` binary
is a [Mach-O][] file
* a note named `NODE_JS_CODE` if the `node` binary is an [ELF][] file

Search the binary for the
`NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0` [fuse][] string and flip the
last character to `1` to indicate that a resource has been injected.

### Platform support

Single-executable support is tested regularly on CI only on the following
platforms:

* Windows
* macOS
* Linux (AMD64 only)

This is due to a lack of better tools to generate single-executables that can be
used to test this feature on other platforms.

Suggestions for other resource injection tools/workflows are welcomed. Please
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
start a discussion at <https://github.com/nodejs/single-executable/discussions>
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
to help us document them.

[CommonJS]: modules.md#modules-commonjs-modules
[ELF]: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
[Mach-O]: https://en.wikipedia.org/wiki/Mach-O
[PE]: https://en.wikipedia.org/wiki/Portable_Executable
[`process.execPath`]: process.md#processexecpath
[`require()`]: modules.md#requireid
[`require.main`]: modules.md#accessing-the-main-module
[fuse]: https://www.electronjs.org/docs/latest/tutorial/fuses
[postject]: https://github.com/nodejs/postject
[single executable applications]: https://github.com/nodejs/single-executable
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Maintaining Single Executable Applications support

Support for [single executable applications][] is one of the key technical
priorities identified for the success of Node.js.

RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
## High level strategy

From the [Next-10 discussions][] there are 2 approaches the project believes are
important to support:

### Compile with Node.js into executable

This is the approach followed by [boxednode][].

No additional code within the Node.js project is needed to support the
option of compiling a bundled application along with Node.js into a single
executable application.

### Bundle into existing Node.js executable

This is the approach followed by [pkg][].

The project does not plan to provide the complete solution but instead the key
elements which are required in the Node.js executable in order to enable
bundling with the pre-built Node.js binaries. This includes:

* Looking for a segment within the executable that holds bundled code.
* Running the bundled code when such a segment is found.

It is left up to external tools/solutions to:

* Bundle code into a single script.
* Generate a command line with appropriate options.
* Add a segment to an existing Node.js executable which contains
the command line and appropriate headers.
* Re-generate or removing signatures on the resulting executable
* Provide a virtual file system, and hooking it in if needed to
support native modules or reading file contents.

However, the project also maintains a separate tool, [postject][], for injecting
arbitrary read-only resources into the binary such as those needed for bundling
the application into the runtime.

## Planning

Planning for this feature takes place in the [single-executable repository][].

## Upcoming features

Currently, only running a single embedded CommonJS file is supported but support
for the following features are in the list of work we'd like to get to:

* Running an embedded ESM file.
* Running an archive of multiple files.
* Embedding [Node.js CLI options][] into the binary.
* [XCOFF][] executable format.
* Run tests on Linux architectures/distributions other than AMD64 Ubuntu.

## Disabling single executable application support

To disable single executable application support, build Node.js with the
`--disable-single-executable-application` configuration option.

## Implementation

When built with single executable application support, the Node.js process uses
[`postject-api.h`][] to check if the `NODE_JS_CODE` section exists in the
binary. If it is found, it passes the buffer to
[`single_executable_application.js`][], which executes the contents of the
embedded script.

[Next-10 discussions]: https://github.com/nodejs/next-10/blob/main/meetings/summit-nov-2021.md#single-executable-applications
[Node.js CLI options]: https://nodejs.org/api/cli.html
[XCOFF]: https://www.ibm.com/docs/en/aix/7.2?topic=formats-xcoff-object-file-format
[`postject-api.h`]: https://github.com/nodejs/node/blob/71951a0e86da9253d7c422fa2520ee9143e557fa/test/fixtures/postject-copy/node_modules/postject/dist/postject-api.h
[`single_executable_application.js`]: https://github.com/nodejs/node/blob/main/lib/internal/main/single_executable_application.js
[boxednode]: https://github.com/mongodb-js/boxednode
[pkg]: https://github.com/vercel/pkg
[postject]: https://github.com/nodejs/postject
[single executable applications]: https://github.com/nodejs/node/blob/main/doc/contributing/technical-priorities.md#single-executable-applications
[single-executable repository]: https://github.com/nodejs/single-executable
55 changes: 55 additions & 0 deletions lib/internal/main/single_executable_application.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';
const {
prepareMainThreadExecution,
markBootstrapComplete,
} = require('internal/process/pre_execution');
const { getSingleExecutableCode } = internalBinding('sea');
const { emitExperimentalWarning } = require('internal/util');
const { Module, wrapSafe } = require('internal/modules/cjs/loader');
const { codes: { ERR_UNKNOWN_BUILTIN_MODULE } } = require('internal/errors');

prepareMainThreadExecution(false, true);
markBootstrapComplete();

emitExperimentalWarning('Single executable application');

// 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.

const filename = process.execPath;
const contents = getSingleExecutableCode();
const compiledWrapper = wrapSafe(filename, contents);

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

const customExports = customModule.exports;

function customRequire(path) {
if (!Module.isBuiltin(path)) {
throw new ERR_UNKNOWN_BUILTIN_MODULE(path);
}

return require(path);
}

customRequire.main = customModule;

const customFilename = customModule.filename;

const customDirname = customModule.path;

compiledWrapper(
customExports,
customRequire,
customModule,
customFilename,
customDirname);
7 changes: 6 additions & 1 deletion node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@

'include_dirs': [
'src',
'deps/v8/include'
'deps/v8/include',
'deps/postject'
],

'sources': [
Expand Down Expand Up @@ -449,6 +450,7 @@

'include_dirs': [
'src',
'deps/postject',
'<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h
],
'dependencies': [
Expand Down Expand Up @@ -523,6 +525,7 @@
'src/node_report.cc',
'src/node_report_module.cc',
'src/node_report_utils.cc',
'src/node_sea.cc',
'src/node_serdes.cc',
'src/node_shadow_realm.cc',
'src/node_snapshotable.cc',
Expand Down Expand Up @@ -633,6 +636,7 @@
'src/node_report.h',
'src/node_revert.h',
'src/node_root_certs.h',
'src/node_sea.h',
'src/node_shadow_realm.h',
'src/node_snapshotable.h',
'src/node_snapshot_builder.h',
Expand Down Expand Up @@ -675,6 +679,7 @@
'src/util-inl.h',
# Dependency headers
'deps/v8/include/v8.h',
'deps/postject/postject-api.h'
# javascript files to make for an even more pleasant IDE experience
'<@(library_files)',
'<@(deps_files)',
Expand Down
17 changes: 17 additions & 0 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#include "node_realm-inl.h"
#include "node_report.h"
#include "node_revert.h"
#include "node_sea.h"
#include "node_snapshot_builder.h"
#include "node_v8_platform-inl.h"
#include "node_version.h"
Expand Down Expand Up @@ -122,6 +123,7 @@
#include <cstring>

#include <string>
#include <tuple>
#include <vector>

namespace node {
Expand Down Expand Up @@ -310,6 +312,18 @@ 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:
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved
//
// 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
RaisinTen marked this conversation as resolved.
Show resolved Hide resolved

if (first_argv == "inspect") {
return StartExecution(env, "internal/main/inspect");
}
Expand Down Expand Up @@ -1250,6 +1264,9 @@ static ExitCode StartInternal(int argc, char** argv) {
}

int Start(int argc, char** argv) {
#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
std::tie(argc, argv) = sea::FixupArgsForSEA(argc, argv);
#endif
return static_cast<int>(StartInternal(argc, argv));
}

Expand Down
Loading