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

process: add execve #56496

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 26 additions & 2 deletions doc/api/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -2486,8 +2486,7 @@ if (process.getuid) {
}
```

This function is only available on POSIX platforms (i.e. not Windows or
Android).
This function not available on Windows.

## `process.hasUncaughtExceptionCaptureCallback()`

Expand Down Expand Up @@ -3303,6 +3302,31 @@ In custom builds from non-release versions of the source tree, only the
`name` property may be present. The additional properties should not be
relied upon to exist.

## \`process.execve(file\[, args\[, env]])\`

<!-- YAML
added: REPLACEME
-->

* `file` {string} The name or path of the executable file to run.
* `args` {string\[]} List of string arguments. No argument can contain a null-byte (`\u0000`).
* `env` {Object} Environment key-value pairs.
No key or value can contain a null-byte (`\u0000`).
**Default:** `process.env`.

Replaces the current process with a new process.

This is achieved by using the `execve` Unix function and therefore no memory or other
resources from the current process are preserved, except for the standard input,
standard output and standard error file descriptor.

All other resources are discarded by the system when the processes are swapped, without triggering
any exit or close events and without running any cleanup handler.

This function will never return, unless an error occurred.
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved

This function is only available on POSIX platforms (i.e. not Windows or Android).

## `process.report`

<!-- YAML
Expand Down
1 change: 1 addition & 0 deletions lib/internal/bootstrap/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ const rawMethods = internalBinding('process_methods');
process.availableMemory = rawMethods.availableMemory;
process.kill = wrapped.kill;
process.exit = wrapped.exit;
process.execve = wrapped.execve;
process.ref = perThreadSetup.ref;
process.unref = perThreadSetup.unref;

Expand Down
50 changes: 50 additions & 0 deletions lib/internal/process/per_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const {
FunctionPrototypeCall,
NumberMAX_SAFE_INTEGER,
ObjectDefineProperty,
ObjectEntries,
ObjectFreeze,
ReflectApply,
RegExpPrototypeExec,
Expand All @@ -24,6 +25,7 @@ const {
SetPrototypeEntries,
SetPrototypeValues,
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeReplace,
StringPrototypeSlice,
Symbol,
Expand All @@ -34,17 +36,20 @@ const {
const {
ErrnoException,
codes: {
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_OUT_OF_RANGE,
ERR_UNKNOWN_SIGNAL,
ERR_WORKER_UNSUPPORTED_OPERATION,
},
} = require('internal/errors');
const format = require('internal/util/inspect').format;
const {
validateArray,
validateNumber,
validateObject,
validateString,
} = require('internal/validators');

const constants = internalBinding('constants').os.signals;
Expand Down Expand Up @@ -101,6 +106,7 @@ function wrapProcessMethods(binding) {
rss,
resourceUsage: _resourceUsage,
loadEnvFile: _loadEnvFile,
execve: _execve,
} = binding;

function _rawDebug(...args) {
Expand Down Expand Up @@ -223,6 +229,49 @@ function wrapProcessMethods(binding) {
return true;
}

function execve(execPath, args, env) {
const { isMainThread } = require('internal/worker');

if (!isMainThread) {
throw new ERR_WORKER_UNSUPPORTED_OPERATION('Calling process.execve');
} else if (process.platform === 'win32') {
throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('process.execve');
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved
}

validateString(execPath, 'execPath');
validateArray(args, 'args');

for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (typeof arg !== 'string' || StringPrototypeIncludes(arg, '\u0000')) {
throw new ERR_INVALID_ARG_VALUE(`args[${i}]`, arg, 'must be a string without null bytes');
}
}

if (env !== undefined) {
validateObject(env, 'env');

for (const { 0: key, 1: value } of ObjectEntries(env)) {
if (
typeof key !== 'string' ||
typeof value !== 'string' ||
StringPrototypeIncludes(key, '\u0000') ||
StringPrototypeIncludes(value, '\u0000')
) {
throw new ERR_INVALID_ARG_VALUE(
'env', env, 'must be an object with string keys and values without null bytes',
);
}
}
}

// Construct the environment array.
const envArray = ArrayPrototypeMap(ObjectEntries(env || {}), ({ 0: key, 1: value }) => `${key}=${value}`);

// Perform the system call
_execve(execPath, args, envArray);
}

const resourceValues = new Float64Array(16);
function resourceUsage() {
_resourceUsage(resourceValues);
Expand Down Expand Up @@ -267,6 +316,7 @@ function wrapProcessMethods(binding) {
memoryUsage,
kill,
exit,
execve,
loadEnvFile,
};
}
Expand Down
5 changes: 5 additions & 0 deletions src/node_errors.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
#include <sstream>

namespace node {
// This forward declaration is required to have the method
// available in error messages.
namespace errors {
const char* errno_string(int errorno);
}

enum ErrorHandlingMode { CONTEXTIFY_ERROR, FATAL_ERROR, MODULE_ERROR };
void AppendExceptionLine(Environment* env,
Expand Down
98 changes: 98 additions & 0 deletions src/node_process_methods.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@
#if defined(_MSC_VER)
#include <direct.h>
#include <io.h>
#include <process.h>
#define umask _umask
typedef int mode_t;
#else
#include <pthread.h>
#include <sys/resource.h> // getrlimit, setrlimit
#include <termios.h> // tcgetattr, tcsetattr
#include <unistd.h>
#endif

namespace node {
Expand Down Expand Up @@ -471,6 +473,94 @@ static void ReallyExit(const FunctionCallbackInfo<Value>& args) {
env->Exit(code);
}

#ifdef __POSIX__
inline int persist_standard_stream(int fd) {
int flags = fcntl(fd, F_GETFD, 0);

if (flags < 0) {
return flags;
}

flags &= ~FD_CLOEXEC;
return fcntl(fd, F_SETFD, flags);
}

static void Execve(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
Local<Context> context = env->context();

THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kChildProcess, "");

CHECK(args[0]->IsString());
CHECK(args[1]->IsArray());
CHECK(args[2]->IsArray());

Local<Array> argv_array = args[1].As<Array>();
Local<Array> envp_array = args[2].As<Array>();

// Copy arguments and environment
Utf8Value executable(isolate, args[0]);
std::vector<std::string> argv_strings(argv_array->Length());
std::vector<std::string> envp_strings(envp_array->Length());
std::vector<char*> argv(argv_array->Length() + 1);
std::vector<char*> envp(envp_array->Length() + 1);

for (unsigned int i = 0; i < argv_array->Length(); i++) {
Local<Value> str;
if (!argv_array->Get(context, i).ToLocal(&str)) {
THROW_ERR_INVALID_ARG_VALUE(env, "Failed to deserialize argument.");
return;
}

argv_strings[i] = Utf8Value(isolate, str).ToString();
argv[i] = argv_strings[i].data();
}
argv[argv_array->Length()] = nullptr;

for (unsigned int i = 0; i < envp_array->Length(); i++) {
Local<Value> str;
if (!envp_array->Get(context, i).ToLocal(&str)) {
THROW_ERR_INVALID_ARG_VALUE(
env, "Failed to deserialize environment variable.");
return;
}

envp_strings[i] = Utf8Value(isolate, str).ToString();
envp[i] = envp_strings[i].data();
}

envp[envp_array->Length()] = nullptr;

// Set stdin, stdout and stderr to be non-close-on-exec
// so that the new process will inherit it.
if (persist_standard_stream(0) < 0 || persist_standard_stream(1) < 0 ||
persist_standard_stream(2) < 0) {
env->ThrowErrnoException(errno, "fcntl");
}

// Perform the execve operation.
RunAtExit(env);
execve(*executable, argv.data(), envp.data());

// If it returns, it means that the execve operation failed.
// In that case we abort the process.
auto error_message = std::string("process.execve failed with error code ") +
errors::errno_string(errno);

// Abort the process
Local<v8::Value> exception =
ErrnoException(isolate, errno, "execve", *executable);
Local<v8::Message> message = v8::Exception::CreateMessage(isolate, exception);

std::string info = FormatErrorMessage(
isolate, context, error_message.c_str(), message, true);
FPrintF(stderr, "%s\n", info);
ABORT();
}
#endif
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is quite hard-to-follow C++ with lots of unnecessary explicit memory management that Node.js has been doing a lot of effort to move away from. I'd recommend looking a bit a how other parts of the Node.js code base handle strings and conversion between C++ and JS values.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm absolutely willing to. Since I'm not familiar with the C++ codebase, do you have any suggestion of places I can look to?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ShogunPanda Well, mostly anywhere else works. As a general rule, you'll want to get rid of new, new[], char*, memcpy() and strdup() as much as possible, and replace them with std::vector, std::string/Utf8Value as much as possible.

(You won't be entirely able to avoid something like std::vector<char*> because execve expects char** arguments, but the std::vector<char*>'s entries could point to the entries of a std::vector<std::string> or std::vector<Utf8Value> rather than having to manage memory manually).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@addaleax I vastly refactored the C++ part following your suggestions. It was great, thanks a lot for all the good hint.

I tried to use a single vector but when I instantiate a std::string or a Utf8Value inside a for loop it obviously went out of scope and garbage collected.
So I have to use two vectors for argv and two for envp. Is this the right approach or am I still missing something?


static void LoadEnvFile(const v8::FunctionCallbackInfo<v8::Value>& args) {
Environment* env = Environment::GetCurrent(args);
std::string path = ".env";
Expand Down Expand Up @@ -662,6 +752,10 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetMethodNoSideEffect(isolate, target, "cwd", Cwd);
SetMethod(isolate, target, "dlopen", binding::DLOpen);
SetMethod(isolate, target, "reallyExit", ReallyExit);

#ifdef __POSIX__
SetMethod(isolate, target, "execve", Execve);
#endif
SetMethodNoSideEffect(isolate, target, "uptime", Uptime);
SetMethod(isolate, target, "patchProcessObject", PatchProcessObject);

Expand Down Expand Up @@ -704,6 +798,10 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Cwd);
registry->Register(binding::DLOpen);
registry->Register(ReallyExit);

#ifdef __POSIX__
registry->Register(Execve);
#endif
registry->Register(Uptime);
registry->Register(PatchProcessObject);

Expand Down
28 changes: 28 additions & 0 deletions test/parallel/test-process-execve-abort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

const { isMainThread, skip, isWindows, getPrintedStackTrace } = require('../common');
const { strictEqual, ok } = require('assert');
const { spawnSync } = require('child_process');

if (!isMainThread) {
skip('process.execve is not available in Workers');
} else if (isWindows) {
skip('process.execve is not available in Windows');
}

if (process.argv[2] === 'child') {
process.execve(
process.execPath + '_non_existing',
[__filename, 'replaced'],
{ EXECVE_A: 'FIRST', EXECVE_B: 'SECOND', CWD: process.cwd() }
);
} else {
const child = spawnSync(`${process.execPath}`, [`${__filename}`, 'child']);
const stderr = child.stderr.toString();

strictEqual(child.stdout.toString(), '');
const { nativeStack, jsStack } = getPrintedStackTrace(stderr);

ok(nativeStack[0].includes('node::Execve'));

Check failure on line 26 in test/parallel/test-process-execve-abort.js

View workflow job for this annotation

GitHub Actions / test-linux

--- stderr --- node:internal/assert/utils:281 throw err; ^ AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value: ok(nativeStack[0].includes('node::Execve')) at Object.<anonymous> (/home/runner/work/node/node/node/test/parallel/test-process-execve-abort.js:26:3) at Module._compile (node:internal/modules/cjs/loader:1739:14) at Object..js (node:internal/modules/cjs/loader:1904:10) at Module.load (node:internal/modules/cjs/loader:1473:32) at Function._load (node:internal/modules/cjs/loader:1285:12) at TracingChannel.traceSync (node:diagnostics_channel:322:14) at wrapModuleLoad (node:internal/modules/cjs/loader:234:24) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:151:5) at node:internal/main/run_main_module:33:47 { generatedMessage: true, code: 'ERR_ASSERTION', actual: false, expected: true, operator: '==' } Node.js v24.0.0-pre Command: out/Release/node --test-reporter=./test/common/test-error-reporter.js --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /home/runner/work/node/node/node/test/parallel/test-process-execve-abort.js
ok(jsStack[0].includes('execve'));
}
17 changes: 17 additions & 0 deletions test/parallel/test-process-execve-on-exit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

const { isMainThread, mustNotCall, skip, isWindows } = require('../common');
const { strictEqual } = require('assert');

if (!isMainThread) {
skip('process.execve is not available in Workers');
} else if (isWindows) {
skip('process.execve is not available in Windows');
}

if (process.argv[2] === 'replaced') {
strictEqual(process.argv[2], 'replaced');
} else {
process.on('exit', mustNotCall());
process.execve(process.execPath, [process.execPath, __filename, 'replaced']);
}
20 changes: 20 additions & 0 deletions test/parallel/test-process-execve-permission-fail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Flags: --permission --allow-fs-read=*

'use strict';

const { isMainThread, mustCall, skip, isWindows } = require('../common');
const { fail, throws } = require('assert');

if (!isMainThread) {
skip('process.execve is not available in Workers');
} else if (isWindows) {
skip('process.execve is not available in Windows');
}

if (process.argv[2] === 'replaced') {
fail('process.execve should not have been allowed.');
} else {
throws(mustCall(() => {
process.execve(process.execPath, [process.execPath, __filename, 'replaced']);
}), { name: 'Error', code: 'ERR_ACCESS_DENIED' });
}
18 changes: 18 additions & 0 deletions test/parallel/test-process-execve-permission-granted.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Flags: --permission --allow-fs-read=* --allow-child-process

'use strict';

const { isMainThread, skip, isWindows } = require('../common');
const { deepStrictEqual } = require('assert');

if (!isMainThread) {
skip('process.execve is not available in Workers');
} else if (isWindows) {
skip('process.execve is not available in Windows');
}

if (process.argv[2] === 'replaced') {
deepStrictEqual(process.argv, [process.execPath, __filename, 'replaced']);
} else {
process.execve(process.execPath, [process.execPath, __filename, 'replaced']);
}
Loading
Loading