node/test/fixtures/snapshot/mutate-error-stack-trace-limit.js
Joyee Cheung 33bbf3751b src: fixup Error.stackTraceLimit during snapshot building
When V8 creates a context for snapshot building, it does not
install Error.stackTraceLimit. As a result, error.stack would
be undefined in the snapshot builder script unless users
explicitly initialize Error.stackTraceLimit, which may be
surprising.

This patch initializes Error.stackTraceLimit based on the
value of --stack-trace-limit to prevent the surprise. If
users have modified Error.stackTraceLimit in the builder
script, the modified value would be restored during
deserialization. Otherwise, the fixed up limit would be
deleted since V8 expects to find it unset and re-initialize
it during snapshot deserialization.

PR-URL: https://github.com/nodejs/node/pull/55121
Fixes: https://github.com/nodejs/node/issues/55100
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
2024-09-30 15:05:12 +00:00

44 lines
1.1 KiB
JavaScript

const {
addSerializeCallback,
setDeserializeMainFunction,
} = require('v8').startupSnapshot;
const assert = require('assert');
if (process.env.TEST_IN_SERIALIZER) {
addSerializeCallback(checkMutate);
} else {
checkMutate();
}
function checkMutate() {
// Check that mutation to Error.stackTraceLimit is effective in the snapshot
// builder script.
assert.strictEqual(typeof Error.stackTraceLimit, 'number');
Error.stackTraceLimit = 0;
assert.strictEqual(getError('', 30), 'Error');
}
setDeserializeMainFunction(() => {
// Check that the mutation is preserved in the deserialized main function.
assert.strictEqual(Error.stackTraceLimit, 0);
assert.strictEqual(getError('', 30), 'Error');
// Check that it can still be mutated.
Error.stackTraceLimit = 10;
const error = getError('', 30);
const matches = [...error.matchAll(/at recurse/g)];
assert.strictEqual(matches.length, 10);
});
function getError(message, depth) {
let counter = 1;
function recurse() {
if (counter++ < depth) {
return recurse();
}
const error = new Error(message);
return error.stack;
}
return recurse();
}