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 3 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
8 changes: 8 additions & 0 deletions doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -2445,6 +2445,13 @@ An invalid timestamp value was provided for a performance mark or measure.

Invalid options were provided for a performance measure.

<a id="ERR_PROCESS_EXECVE_FAILED"></a>

### `ERR_PROCESS_EXECVE_FAILED`

Replacing the current process with [`process.execve()`][] has failed due to some
system error.

<a id="ERR_PROTO_ACCESS"></a>

### `ERR_PROTO_ACCESS`
Expand Down Expand Up @@ -4263,6 +4270,7 @@ An error occurred trying to allocate memory. This should never happen.
[`package.json`]: packages.md#nodejs-packagejson-field-definitions
[`postMessage()`]: worker_threads.md#portpostmessagevalue-transferlist
[`postMessageToThread()`]: worker_threads.md#workerpostmessagetothreadthreadid-value-transferlist-timeout
[`process.execve()`]: process.md#processexecvefile-args-env
[`process.on('exit')`]: process.md#event-exit
[`process.send()`]: process.md#processsendmessage-sendhandle-options-callback
[`process.setUncaughtExceptionCaptureCallback()`]: process.md#processsetuncaughtexceptioncapturecallbackfn
Expand Down
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
14 changes: 13 additions & 1 deletion 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 Expand Up @@ -111,7 +116,8 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details);
V(ERR_WASI_NOT_STARTED, Error) \
V(ERR_ZLIB_INITIALIZATION_FAILED, Error) \
V(ERR_WORKER_INIT_FAILED, Error) \
V(ERR_PROTO_ACCESS, Error)
V(ERR_PROTO_ACCESS, Error) \
V(ERR_PROCESS_EXECVE_FAILED, Error)

#define V(code, type) \
template <typename... Args> \
Expand Down Expand Up @@ -253,6 +259,12 @@ inline v8::Local<v8::Object> ERR_STRING_TOO_LONG(v8::Isolate* isolate) {
return ERR_STRING_TOO_LONG(isolate, message);
}

inline void THROW_ERR_PROCESS_EXECVE_FAILED(Environment* env, int code) {
auto message = std::string("process.execve failed with error code ") +
errors::errno_string(code);
THROW_ERR_PROCESS_EXECVE_FAILED(env, message.c_str());
}

#define THROW_AND_RETURN_IF_NOT_BUFFER(env, val, prefix) \
do { \
if (!Buffer::HasInstance(val)) \
Expand Down
80 changes: 80 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,76 @@ 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++) {
argv_strings[i] =
Utf8Value(isolate, argv_array->Get(context, i).ToLocalChecked())
.ToString();
argv[i] = argv_strings[i].data();
}
argv[argv_array->Length()] = nullptr;

for (unsigned int i = 0; i < envp_array->Length(); i++) {
envp_strings[i] =
Utf8Value(isolate, envp_array->Get(context, i).ToLocalChecked())
.ToString();
Comment on lines +519 to +521
Copy link
Member

Choose a reason for hiding this comment

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

For things like this, instead of using ToLocalChecked(), use a pattern like the following... this will avoid a process crash when a throw is appropriate:

Local<Value> str;
if (!envp_array->Get(context, i).ToLocal(&str)) {
  return;
}
envp_strings[i] = Utf8Value(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.
for (int i = 0; i < 3; i++) {
Copy link
Member

Choose a reason for hiding this comment

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

rather than a using a loop here, consider something like:

if (persist_standard_stream(0) < 0 ||
    persist_standard_stream(1) < 0 ||
    persist_standard_stream(2) < 0) {
  THROW_ERR_PROCSS_EXECVE_FAILED(env, errno);
}

Or persist all three at once in one call to persist_standard_stream()

// Operation failed. Free up memory, then throw.
if (persist_standard_stream(i) < 0) {
THROW_ERR_PROCESS_EXECVE_FAILED(env, errno);
}
}

// Perform the execve operation.
// If it returns, it means that the execve operation failed.
RunAtExit(env);

execve(*executable, argv.data(), envp.data());
int error_code = errno;

THROW_ERR_PROCESS_EXECVE_FAILED(env, error_code);
Copy link
Member

@jasnell jasnell Jan 11, 2025

Choose a reason for hiding this comment

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

Given that you're running the RunAtExit(...) here, and given that the expectation is for this process to be replaced, I wonder if it would be more appropriate to crash the process here instead of just throwing (a throw can be caught and ignored and I'm not sure we want that here)

}
#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 +734,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 +780,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
Loading
Loading