Skip to content
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
42 changes: 42 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1996,6 +1996,41 @@ added: v0.1.3
Print node command-line options.
The output of this option is less detailed than this document.

### `--hide-internal-stack-frames`

<!-- YAML
added: REPLACEME
-->

Collapse stack frames that originate from Node.js internal modules (those
whose file name starts with `node:internal/`), and from the wrapper scripts
Node.js generates around [`--eval`][] and stdin input, in printed stack
traces. Each
run of consecutive internal frames is replaced with a single
`at <node:internal> (N frames hidden)` line. Frames from user code and from
public built-in modules such as `node:fs` are kept.

```console
$ node --hide-internal-stack-frames -e "require('node:fs').readFileSync('missing')"
...
Error: ENOENT: no such file or directory, open 'missing'
at Object.openSync (node:fs:779:18)
at Object.readFileSync (node:fs:625:35)
at [eval]:1:20
at <node:internal> (7 frames hidden) {
...
```

This applies to `error.stack` and to the stack traces Node.js prints itself,
such as those from [`--trace-uncaught`][], [`--trace-exit`][],
[`--trace-sync-io`][], [`--process-timeout`][], and the JavaScript stack in a
[diagnostic report][].

Frames are collapsed after V8 collects them, so a trace still contains at most
[`Error.stackTraceLimit`][] frames. The flag affects only the default
formatter: an `Error.prepareStackTrace` function set by the user still
receives every frame, and [`util.getCallSites()`][] is unaffected.

### `--icu-data-dir=file`

<!-- YAML
Expand Down Expand Up @@ -4338,6 +4373,7 @@ one is included in the list below.
* `--heap-prof`
* `--heapsnapshot-near-heap-limit`
* `--heapsnapshot-signal`
* `--hide-internal-stack-frames`
* `--http-parser`
* `--icu-data-dir`
* `--import`
Expand Down Expand Up @@ -4959,6 +4995,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[`--enable-fips`]: #--enable-fips
[`--env-file-if-exists`]: #--env-file-if-existsfile
[`--env-file`]: #--env-filefile
[`--eval`]: #-e---eval-script
[`--experimental-sea-config`]: single-executable-applications.md#1-generating-single-executable-preparation-blobs
[`--heap-prof-dir`]: #--heap-prof-dir
[`--import`]: #--importmodule
Expand All @@ -4971,6 +5008,9 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[`--redirect-warnings`]: #--redirect-warningsfile
[`--report-on-process-timeout`]: #--report-on-process-timeout
[`--require`]: #-r---require-module
[`--trace-exit`]: #--trace-exit
[`--trace-sync-io`]: #--trace-sync-io
[`--trace-uncaught`]: #--trace-uncaught
[`--use-env-proxy`]: #--use-env-proxy
[`--use-system-ca`]: #--use-system-ca
[`--watch`]: #--watch
Expand All @@ -4981,6 +5021,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`]: errors.md#err_unsupported_node_modules_type_stripping
[`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`]: errors.md#err_unsupported_typescript_syntax
[`ERR_WEBASSEMBLY_NOT_SUPPORTED`]: errors.md#err_webassembly_not_supported
[`Error.stackTraceLimit`]: errors.md#errorstacktracelimit
[`NODE_OPTIONS`]: #node_optionsoptions
[`NODE_USE_ENV_PROXY=1`]: #node_use_env_proxy1
[`NODE_V8_COVERAGE=dir`]: #node_v8_coveragedir
Expand Down Expand Up @@ -5008,6 +5049,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[`tls.DEFAULT_MAX_VERSION`]: tls.md#tlsdefault_max_version
[`tls.DEFAULT_MIN_VERSION`]: tls.md#tlsdefault_min_version
[`unhandledRejection`]: process.md#event-unhandledrejection
[`util.getCallSites()`]: util.md#utilgetcallsitesframecount-options
[`v8.startupSnapshot.addDeserializeCallback()`]: v8.md#v8startupsnapshotadddeserializecallbackcallback-data
[`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data
[`v8.startupSnapshot` API]: v8.md#startup-snapshot-api
Expand Down
4 changes: 4 additions & 0 deletions doc/node-config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,10 @@
"type": "string",
"description": "Generate heap snapshot on specified signal"
},
"hide-internal-stack-frames": {
"type": "boolean",
"description": "omit node:internal frames from stack traces"
},
"icu-data-dir": {
"type": "string",
"description": "set ICU data load path to dir (overrides NODE_ICU_DATA) (note: linked-in ICU data is present)"
Expand Down
29 changes: 29 additions & 0 deletions doc/node.1
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,33 @@ Heap.20190718.133405.15554.0.001.heapsnapshot
Print node command-line options.
The output of this option is less detailed than this document.
.
.It Fl -hide-internal-stack-frames
Collapse stack frames that originate from Node.js internal modules (those
whose file name starts with \fBnode:internal/\fR), and from the wrapper scripts
Node.js generates around \fB--eval\fR and stdin input, in printed stack
traces. Each
run of consecutive internal frames is replaced with a single
\fBat <node:internal> (N frames hidden)\fR line. Frames from user code and from
public built-in modules such as \fBnode:fs\fR are kept.
.Bd -literal
$ node --hide-internal-stack-frames -e "require('node:fs').readFileSync('missing')"
...
Error: ENOENT: no such file or directory, open 'missing'
at Object.openSync (node:fs:779:18)
at Object.readFileSync (node:fs:625:35)
at [eval]:1:20
at <node:internal> (7 frames hidden) {
...
.Ed
This applies to \fBerror.stack\fR and to the stack traces Node.js prints itself,
such as those from \fB--trace-uncaught\fR, \fB--trace-exit\fR,
\fB--trace-sync-io\fR, \fB--process-timeout\fR, and the JavaScript stack in a
diagnostic report.
Frames are collapsed after V8 collects them, so a trace still contains at most
\fBError.stackTraceLimit\fR frames. The flag affects only the default
formatter: an \fBError.prepareStackTrace\fR function set by the user still
receives every frame, and \fButil.getCallSites()\fR is unaffected.
.
.It Fl -icu-data-dir Ns = Ns Ar file
Specify ICU data load path. (Overrides \fBNODE_ICU_DATA\fR.)
.
Expand Down Expand Up @@ -2335,6 +2362,8 @@ one is included in the list below.
.It
\fB--heapsnapshot-signal\fR
.It
\fB--hide-internal-stack-frames\fR
.It
\fB--http-parser\fR
.It
\fB--icu-data-dir\fR
Expand Down
71 changes: 69 additions & 2 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ const kTypes = [
const MainContextError = Error;
const overrideStackTrace = new SafeWeakMap();
let internalPrepareStackTrace = defaultPrepareStackTrace;
let omitInternalStackFrames = false;

/**
* The default implementation of `Error.prepareStackTrace` with simple
Expand Down Expand Up @@ -115,6 +116,71 @@ function setInternalPrepareStackTrace(callback) {
internalPrepareStackTrace = callback;
}

function setHideInternalStackFrames(value) {
omitInternalStackFrames = value;
}

// Frames from Node.js internal modules, and from the `[eval]-wrapper`,
// `[stdin]-wrapper` and `[worker eval]-wrapper` scripts that Node.js generates
// around `--eval`, stdin and `eval: true` worker input.
function isInternalCallSite(callSite) {
const fileName = callSite.getFileName();
if (typeof fileName !== 'string') return false;
return StringPrototypeStartsWith(fileName, 'node:internal/') ||
(StringPrototypeStartsWith(fileName, '[') &&
StringPrototypeEndsWith(fileName, ']-wrapper'));
}

/**
* Stands in for a run of omitted `node:internal/*` call sites. It implements
* the subset of the CallSite API that the internal stack formatters use.
*/
class InternalFramesPlaceholder {
#count;
constructor(count) {
this.#count = count;
}
getFileName() { return undefined; }
getEvalOrigin() { return undefined; }
toString() {
return `<node:internal> (${this.#count} ` +
`${this.#count === 1 ? 'frame' : 'frames'} hidden)`;
}
}

function collapseInternalCallSites(trace) {
const result = [];
let hidden = 0;
for (let i = 0; i < trace.length; i++) {
if (isInternalCallSite(trace[i])) {
hidden++;
continue;
}
if (hidden > 0) {
ArrayPrototypePush(result, new InternalFramesPlaceholder(hidden));
hidden = 0;
}
ArrayPrototypePush(result, trace[i]);
}
if (hidden > 0) {
ArrayPrototypePush(result, new InternalFramesPlaceholder(hidden));
}
return result;
}

/**
* Formats the stack with the internal implementation, collapsing each run of
* `node:internal/*` frames into a placeholder when
* `--hide-internal-stack-frames` is set.
* @returns {string}
*/
function formatStackTrace(error, trace) {
if (omitInternalStackFrames) {
trace = collapseInternalCallSites(trace);
}
return internalPrepareStackTrace(error, trace);
}

function isPermissionModelError(err) {
return typeof err !== 'number' && err.code && err.code === 'ERR_ACCESS_DENIED';
}
Expand Down Expand Up @@ -158,15 +224,15 @@ function prepareStackTraceCallback(globalThis, error, trace) {

// If the Error.prepareStackTrace was not a function, fallback to the
// internal implementation.
return internalPrepareStackTrace(error, trace);
return formatStackTrace(error, trace);
}

/**
* The default Error.prepareStackTrace implementation.
* @returns {string}
*/
function ErrorPrepareStackTrace(error, trace) {
return internalPrepareStackTrace(error, trace);
return formatStackTrace(error, trace);
}

const aggregateTwoErrors = (innerError, outerError) => {
Expand Down Expand Up @@ -1104,6 +1170,7 @@ module.exports = {
kEnhanceStackBeforeInspector,
kIsNodeError,
defaultPrepareStackTrace,
setHideInternalStackFrames,
setInternalPrepareStackTrace,
overrideStackTrace,
prepareStackTraceCallback,
Expand Down
18 changes: 14 additions & 4 deletions lib/internal/process/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,13 @@ const {
} = require('internal/util');

const {
ERR_MISSING_OPTION,
ERR_ACCESS_DENIED,
ERR_VFS_INVALID_TARGET,
} = require('internal/errors').codes;
codes: {
ERR_ACCESS_DENIED,
ERR_MISSING_OPTION,
ERR_VFS_INVALID_TARGET,
},
setHideInternalStackFrames,
} = require('internal/errors');
const assert = require('internal/assert');
const {
namespace: {
Expand Down Expand Up @@ -130,6 +133,7 @@ function prepareExecution(options) {
initializePermission();

initializeSourceMapsHandlers();
initializeStackTraceFiltering();
initializeDeprecations();

// internal/dns/utils (and internal/net behind it) is only needed up front
Expand Down Expand Up @@ -814,6 +818,12 @@ function initializeSourceMapsHandlers() {
});
}

function initializeStackTraceFiltering() {
if (getOptionValue('--hide-internal-stack-frames')) {
setHideInternalStackFrames(true);
}
}

function initializeFrozenIntrinsics() {
if (getOptionValue('--frozen-intrinsics')) {
emitExperimentalWarning('Frozen intristics');
Expand Down
3 changes: 2 additions & 1 deletion lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -2011,7 +2011,8 @@ function formatError(err, constructor, tag, ctx, keys) {
let esmWorkingDirectory;
for (let line of lines) {
const core = RegExpPrototypeExec(coreModuleRegExp, line);
if (core !== null && BuiltinModule.exists(core[1])) {
if ((core !== null && BuiltinModule.exists(core[1])) ||
StringPrototypeStartsWith(line, ' at <node:internal> (')) {
newStack += `\n${ctx.stylize(line, 'undefined')}`;
} else {
newStack += '\n';
Expand Down
43 changes: 40 additions & 3 deletions src/node_errors.cc
Original file line number Diff line number Diff line change
Expand Up @@ -227,20 +227,56 @@ MaybeLocal<StackTrace> GetCurrentStackTrace(Isolate* isolate, int frame_count) {
return scope.Escape(stack);
}

bool ShouldHideInternalStackFrames(Isolate* isolate) {
Environment* env = Environment::GetCurrent(isolate);
return env != nullptr && env->options()->hide_internal_stack_frames;
}

bool IsInternalStackFrame(Isolate* isolate, Local<StackFrame> frame) {
Utf8Value script_name(isolate, frame->GetScriptName());
const std::string_view name = script_name.ToStringView();
// Also match the `[eval]-wrapper`, `[stdin]-wrapper` and
// `[worker eval]-wrapper` scripts generated in
// lib/internal/process/execution.js.
return name.starts_with("node:internal/") ||
(name.starts_with('[') && name.ends_with("]-wrapper"));
}

std::string FormatHiddenStackFrames(int count) {
return SPrintF(
"<node:internal> (%d %s hidden)", count, count == 1 ? "frame" : "frames");
}

static std::string FormatStackTrace(
Isolate* isolate,
Local<StackTrace> stack,
StackTracePrefix prefix = StackTracePrefix::kAt) {
std::string result;
const bool hide_internal = ShouldHideInternalStackFrames(isolate);
int lines = 0;
int hidden = 0;
auto next_prefix = [&]() {
lines++;
return prefix == StackTracePrefix::kAt ? std::string(" at ")
: std::to_string(lines) + ": ";
};
auto flush_hidden = [&]() {
if (hidden == 0) return;
result += next_prefix() + FormatHiddenStackFrames(hidden) + "\n";
hidden = 0;
};
for (int i = 0; i < stack->GetFrameCount(); i++) {
Local<StackFrame> stack_frame = stack->GetFrame(isolate, i);
if (hide_internal && IsInternalStackFrame(isolate, stack_frame)) {
hidden++;
continue;
}
flush_hidden();
node::Utf8Value fn_name_s(isolate, stack_frame->GetFunctionName());
node::Utf8Value script_name(isolate, stack_frame->GetScriptName());
const int line_number = stack_frame->GetLineNumber();
const int column = stack_frame->GetColumn();
std::string prefix_str = prefix == StackTracePrefix::kAt
? " at "
: std::to_string(i + 1) + ": ";
std::string prefix_str = next_prefix();
if (stack_frame->IsEval()) {
if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
result += SPrintF("%s[eval]:%i:%i\n", prefix_str, line_number, column);
Expand Down Expand Up @@ -281,6 +317,7 @@ static std::string FormatStackTrace(
result += std::string(buf.data());
}
}
flush_hidden();
return result;
}

Expand Down
12 changes: 12 additions & 0 deletions src/node_internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ constexpr int kMaxFrameCountForLogging = 10;
v8::MaybeLocal<v8::StackTrace> GetCurrentStackTrace(
v8::Isolate* isolate, int frame_count = kMaxFrameCountForLogging);

// Returns true if --hide-internal-stack-frames is in effect for the
// Environment that is current on `isolate`.
bool ShouldHideInternalStackFrames(v8::Isolate* isolate);
// Returns true if `frame` belongs to a Node.js internal module (its script
// name starts with "node:internal/") or to a generated "[eval]-wrapper"-style
// script.
bool IsInternalStackFrame(v8::Isolate* isolate,
v8::Local<v8::StackFrame> frame);
// The text that stands in for `count` consecutive hidden internal frames,
// e.g. "<node:internal> (3 frames hidden)".
std::string FormatHiddenStackFrames(int count);

enum class StackTracePrefix {
kAt, // " at "
kNumber
Expand Down
4 changes: 4 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
"experimental frozen intrinsics support",
BOOL_FIELD(frozen_intrinsics),
kAllowedInEnvvar);
AddOption("--hide-internal-stack-frames",
"omit node:internal frames from stack traces",
BOOL_FIELD(hide_internal_stack_frames),
kAllowedInEnvvar);
AddOption("--heapsnapshot-signal",
"Generate heap snapshot on specified signal",
&EnvironmentOptions::heap_snapshot_signal,
Expand Down
1 change: 1 addition & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ class EnvironmentOptions : public Options {
DEFINE_BOOL_FIELD(print_required_tla) = false;
DEFINE_BOOL_FIELD(require_module) = true;
DEFINE_BOOL_FIELD(enable_source_maps) = false;
DEFINE_BOOL_FIELD(hide_internal_stack_frames) = false;
DEFINE_BOOL_FIELD(experimental_addon_modules) = true;
DEFINE_BOOL_FIELD(experimental_bench) = EXPERIMENTALS_DEFAULT_VALUE;
DEFINE_BOOL_FIELD(experimental_eventsource) = EXPERIMENTALS_DEFAULT_VALUE;
Expand Down
Loading
Loading