mirror of
https://github.com/nodejs/node.git
synced 2026-11-29 14:27:57 -05:00
src: add option to hide internal stack frames
By default, when node.js prints a stack it includes
all of the `node:internal` frames. This make the
output more verbose but it's often providing
extraneous detail the user can't do anything about.
This adds a cli flag to hide those details. It can
be set in NODE_OPTIONS.
```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) {
...
```
Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Claude
PR-URL: https://github.com/nodejs/node/pull/67715
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
This commit is contained in:
1 parent
41c43a9404
commit
8ec2665e6e
13 files changed
+376
-13
No files matched your search
@@ -1989,6 +1989,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
|
||||
@@ -4396,6 +4431,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`
|
||||
@@ -5018,6 +5054,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
|
||||
@@ -5031,6 +5068,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
|
||||
@@ -5041,6 +5081,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
|
||||
@@ -5070,6 +5111,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
|
||||
|
||||
@@ -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)"
|
||||
|
||||
+29
@@ -1079,6 +1079,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.)
|
||||
.
|
||||
@@ -2369,6 +2396,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
|
||||
|
||||
+69
-2
@@ -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
|
||||
@@ -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';
|
||||
}
|
||||
@@ -158,7 +224,7 @@ 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,7 +232,7 @@ function prepareStackTraceCallback(globalThis, error, trace) {
|
||||
* @returns {string}
|
||||
*/
|
||||
function ErrorPrepareStackTrace(error, trace) {
|
||||
return internalPrepareStackTrace(error, trace);
|
||||
return formatStackTrace(error, trace);
|
||||
}
|
||||
|
||||
const aggregateTwoErrors = (innerError, outerError) => {
|
||||
@@ -1104,6 +1170,7 @@ module.exports = {
|
||||
kEnhanceStackBeforeInspector,
|
||||
kIsNodeError,
|
||||
defaultPrepareStackTrace,
|
||||
setHideInternalStackFrames,
|
||||
setInternalPrepareStackTrace,
|
||||
overrideStackTrace,
|
||||
prepareStackTraceCallback,
|
||||
|
||||
@@ -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: {
|
||||
@@ -130,6 +133,7 @@ function prepareExecution(options) {
|
||||
initializePermission();
|
||||
|
||||
initializeSourceMapsHandlers();
|
||||
initializeStackTraceFiltering();
|
||||
initializeDeprecations();
|
||||
|
||||
// internal/dns/utils (and internal/net behind it) is only needed up front
|
||||
@@ -811,6 +815,12 @@ function initializeSourceMapsHandlers() {
|
||||
});
|
||||
}
|
||||
|
||||
function initializeStackTraceFiltering() {
|
||||
if (getOptionValue('--hide-internal-stack-frames')) {
|
||||
setHideInternalStackFrames(true);
|
||||
}
|
||||
}
|
||||
|
||||
function initializeFrozenIntrinsics() {
|
||||
if (getOptionValue('--frozen-intrinsics')) {
|
||||
emitExperimentalWarning('Frozen intristics');
|
||||
|
||||
@@ -2010,7 +2010,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';
|
||||
|
||||
+40
-3
@@ -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);
|
||||
@@ -281,6 +317,7 @@ static std::string FormatStackTrace(
|
||||
result += std::string(buf.data());
|
||||
}
|
||||
}
|
||||
flush_hidden();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -973,6 +973,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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -520,8 +520,20 @@ static void PrintJavaScriptStack(JSONWriter* writer,
|
||||
|
||||
writer->json_keyvalue("message", trigger);
|
||||
writer->json_arraystart("stack");
|
||||
const bool hide_internal = ShouldHideInternalStackFrames(isolate);
|
||||
int hidden = 0;
|
||||
auto flush_hidden = [&]() {
|
||||
if (hidden == 0) return;
|
||||
writer->json_element("at " + FormatHiddenStackFrames(hidden));
|
||||
hidden = 0;
|
||||
};
|
||||
for (int i = 0; i < stack->GetFrameCount(); i++) {
|
||||
Local<StackFrame> frame = stack->GetFrame(isolate, i);
|
||||
if (hide_internal && IsInternalStackFrame(isolate, frame)) {
|
||||
hidden++;
|
||||
continue;
|
||||
}
|
||||
flush_hidden();
|
||||
|
||||
Utf8Value function_name(isolate, frame->GetFunctionName());
|
||||
Utf8Value script_name(isolate, frame->GetScriptName());
|
||||
@@ -532,6 +544,7 @@ static void PrintJavaScriptStack(JSONWriter* writer,
|
||||
"at %s (%s:%d:%d)", function_name, script_name, line_number, column);
|
||||
writer->json_element(stack_line);
|
||||
}
|
||||
flush_hidden();
|
||||
writer->json_arrayend();
|
||||
writer->json_objectstart("errorProperties");
|
||||
writer->json_objectend();
|
||||
|
||||
+21
-3
@@ -144,10 +144,23 @@ std::string FormatProcessTimeoutHeader(const std::string& duration) {
|
||||
}
|
||||
// LCOV_EXCL_STOP
|
||||
|
||||
std::string FormatJavaScriptStack(Isolate* isolate, Local<StackTrace> stack) {
|
||||
std::string FormatJavaScriptStack(Isolate* isolate,
|
||||
Local<StackTrace> stack,
|
||||
bool hide_internal) {
|
||||
std::string result;
|
||||
int hidden = 0;
|
||||
auto flush_hidden = [&]() {
|
||||
if (hidden == 0) return;
|
||||
result += " at " + FormatHiddenStackFrames(hidden) + "\n";
|
||||
hidden = 0;
|
||||
};
|
||||
for (int i = 0; i < stack->GetFrameCount(); i++) {
|
||||
Local<StackFrame> frame = stack->GetFrame(isolate, i);
|
||||
if (hide_internal && IsInternalStackFrame(isolate, frame)) {
|
||||
hidden++;
|
||||
continue;
|
||||
}
|
||||
flush_hidden();
|
||||
Utf8Value function_name(isolate, frame->GetFunctionName());
|
||||
Utf8Value script_name(isolate, frame->GetScriptName());
|
||||
const int line = frame->GetLineNumber();
|
||||
@@ -159,6 +172,7 @@ std::string FormatJavaScriptStack(Isolate* isolate, Local<StackTrace> stack) {
|
||||
" at %s (%s:%d:%d)\n", function_name, script_name, line, column);
|
||||
}
|
||||
}
|
||||
flush_hidden();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -352,7 +366,8 @@ std::string FormatProcessTimeoutDiagnostics(Environment* env) {
|
||||
.ToLocal(&stack) &&
|
||||
stack->GetFrameCount() > 0) {
|
||||
result += "Main thread was executing JavaScript:\n";
|
||||
result += FormatJavaScriptStack(isolate, stack);
|
||||
result += FormatJavaScriptStack(
|
||||
isolate, stack, env->options()->hide_internal_stack_frames);
|
||||
} else {
|
||||
result += "Main thread was not executing JavaScript.\n";
|
||||
}
|
||||
@@ -411,7 +426,10 @@ void RequestWorkerStacks(Environment* env,
|
||||
if (GetCurrentStackTrace(
|
||||
isolate, static_cast<int>(worker_env->stack_trace_limit()))
|
||||
.ToLocal(&trace)) {
|
||||
stack = FormatJavaScriptStack(isolate, trace);
|
||||
stack = FormatJavaScriptStack(
|
||||
isolate,
|
||||
trace,
|
||||
worker_env->options()->hide_internal_stack_frames);
|
||||
}
|
||||
resources = FormatResources(worker_env, "its");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
|
||||
// Tests that --hide-internal-stack-frames collapses node:internal frames into
|
||||
// a placeholder in every stack Node.js formats, while keeping user and public
|
||||
// builtin frames.
|
||||
|
||||
const common = require('../common');
|
||||
const assert = require('assert');
|
||||
const { spawnSyncAndAssert } = require('../common/child_process');
|
||||
|
||||
const kPlaceholder = /^ {4}at <node:internal> \(\d+ frames? hidden\)$/m;
|
||||
const kInternalFrame = /node:internal\/|\]-wrapper:/;
|
||||
|
||||
const script = `
|
||||
const fs = require('fs');
|
||||
try {
|
||||
fs.readFileSync('/does-not-exist-' + process.pid);
|
||||
} catch (err) {
|
||||
console.log(err.stack);
|
||||
}
|
||||
`;
|
||||
|
||||
// Without the flag, the CJS loader frames are present.
|
||||
spawnSyncAndAssert(process.execPath, ['-e', script], {
|
||||
stdout(output) {
|
||||
assert.match(output, kInternalFrame);
|
||||
assert.doesNotMatch(output, kPlaceholder);
|
||||
},
|
||||
});
|
||||
|
||||
const checkHidden = {
|
||||
stdout: common.mustCall((output) => {
|
||||
assert.doesNotMatch(output, kInternalFrame);
|
||||
assert.match(output, kPlaceholder);
|
||||
assert.match(output, /at Object\.readFileSync \(node:fs:/);
|
||||
assert.match(output, /\[eval\]:4:/);
|
||||
// The generated [eval]-wrapper frame is folded in with the internals.
|
||||
assert.match(output, /\[eval\]:4:\d+\)?\n {4}at <node:internal> \(\d+ frames hidden\)\n/);
|
||||
}, 3),
|
||||
};
|
||||
|
||||
spawnSyncAndAssert(process.execPath,
|
||||
['--hide-internal-stack-frames', '-e', script],
|
||||
checkHidden);
|
||||
|
||||
spawnSyncAndAssert(process.execPath, ['-e', script], {
|
||||
env: { ...process.env, NODE_OPTIONS: '--hide-internal-stack-frames' },
|
||||
}, checkHidden);
|
||||
|
||||
// Works together with --enable-source-maps.
|
||||
spawnSyncAndAssert(process.execPath,
|
||||
['--hide-internal-stack-frames', '--enable-source-maps',
|
||||
'-e', script],
|
||||
checkHidden);
|
||||
|
||||
// Consecutive internal frames are collapsed into a single placeholder.
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames',
|
||||
'-e',
|
||||
'console.log(new Error().stack)',
|
||||
], {
|
||||
stdout(output) {
|
||||
const lines = output.trimEnd().split('\n').slice(1);
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
assert.ok(!(kPlaceholder.test(lines[i]) && kPlaceholder.test(lines[i - 1])),
|
||||
`adjacent placeholders in:\n${output}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// A user-provided Error.prepareStackTrace still receives every frame.
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames',
|
||||
'-e',
|
||||
`Error.prepareStackTrace = (err, trace) =>
|
||||
trace.some((cs) => cs.getFileName()?.startsWith('node:internal/'));
|
||||
console.log(new Error().stack);`,
|
||||
], {
|
||||
stdout: 'true\n',
|
||||
});
|
||||
|
||||
// Stacks printed from C++ are filtered as well.
|
||||
const checkNativeStderr = {
|
||||
stderr: common.mustCall((output) => {
|
||||
assert.doesNotMatch(output, kInternalFrame);
|
||||
assert.match(output, kPlaceholder);
|
||||
}, 2),
|
||||
};
|
||||
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames', '--trace-exit', '-e', 'process.exit(0)',
|
||||
], checkNativeStderr);
|
||||
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames', '--trace-uncaught', '-e', 'throw 1',
|
||||
], { status: 1, ...checkNativeStderr });
|
||||
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames', '--process-timeout=100ms',
|
||||
'-e', 'for (;;);',
|
||||
], {
|
||||
status: 124,
|
||||
stderr(output) {
|
||||
assert.match(output, /Main thread was executing JavaScript:/);
|
||||
assert.doesNotMatch(output, kInternalFrame);
|
||||
assert.match(output, kPlaceholder);
|
||||
},
|
||||
});
|
||||
|
||||
// Diagnostic report JavaScript stacks.
|
||||
spawnSyncAndAssert(process.execPath, [
|
||||
'--hide-internal-stack-frames',
|
||||
'-e',
|
||||
'console.log(JSON.stringify(process.report.getReport().javascriptStack.stack))',
|
||||
], {
|
||||
stdout(output) {
|
||||
const stack = JSON.parse(output);
|
||||
assert.ok(stack.length > 0);
|
||||
for (const line of stack) {
|
||||
assert.doesNotMatch(line, kInternalFrame);
|
||||
}
|
||||
assert.ok(stack.some((line) => /^at <node:internal> \(\d+ frames? hidden\)$/.test(line)),
|
||||
`no placeholder in ${output}`);
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user