Repository navigation
Reset Error.prepareStackTrace finally - #16187
Conversation
liuxingbaoyu
commented
Dec 21, 2023
| Q | A |
|---|---|
| Fixed Issues? | Fixes #16099 |
| Patch: Bug Fix? | |
| Major: Breaking Change? | |
| Minor: New Feature? | |
| Tests Added + Pass? | √ |
| Documentation PR Link | |
| Any Dependency Changes? | |
| License | MIT |
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/63279 |
c4a52d2 to
4d041b2
Compare
4d041b2 to
6a42b03
Compare
Error.prepareStackTrace on finallyError.prepareStackTrace finally
f3a5753 to
58d0bc7
Compare
58d0bc7 to
38e063f
Compare
38e063f to
950fb08
Compare
|
@liuxingbaoyu Could you rebase this PR? |
950fb08 to
7c360c2
Compare
|
@JLHwung Done! Sorry for the delay, because I rewrote this fix. |
7c360c2 to
e1770e9
Compare
|
commit: |
| }; | ||
| function resetPrepareStackTrace() { | ||
| if (--stackTraceRewriterRefCount > 0) return; | ||
| Error.prepareStackTrace = originalPrepareStackTrace; |
There was a problem hiding this comment.
Can we reset only if Error.prepareStackTrace is stackTraceRewriter? So we will not mess up with other libraries that might also overwrite Error.prepareStackTrace. Ditto for stackTraceLimit.
| } catch (err) { | ||
| // Format the stack while the rewriter is still installed. | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-expressions | ||
| (err as Error).stack; |
There was a problem hiding this comment.
can we guard this with the non-null and typeof object check? Otherwise if a plugin throw null here, the error will be very confusing.
| "restores stack settings after an asynchronous $mode call (fails: $fails)", | ||
| async function ({ mode, fails }) { | ||
| const { prepareStackTrace, stackTraceLimit } = Error; | ||
| const { promise: paused, resolve: resume } = Promise.withResolvers(); |
There was a problem hiding this comment.
This comment is from Claude:
Promise.withResolvers requires Node ^22.18, when backporting to 7.x we may have to revise the test here.
| } | ||
| Error.stackTraceLimit = originalMaxStackTraceLimit; | ||
| if (Error.prepareStackTrace !== stackTraceRewriter) { | ||
| stackTraceRewriterRefCount = -1; |
There was a problem hiding this comment.
When resetPrepareStackTrace is called, if Error.prepareStackTrace is a function defined in a Babel plugin, then the stackTraceRewriterRefCount will be -1, and it seems now any future resetPrepareStackTrace and setupPrepareStackTrace will exit early right? If so how do we reset Error.prepareStackTrace to the original one?
There was a problem hiding this comment.
It seems we can't safely remove it unless we ignore the user's changes.
There was a problem hiding this comment.
If we don't keep the hook installed during the call, but rather do it in the catch of withStackTraceRewriting:
- Install the rewriter, chained to current hook (We don't care if it is modified or not)
- Read err.stack
- Put the previous hook back
This happens in one sync step, so no other codes can see Babel's hook. Does it work around this issue?
The following diff is my local experiment with the help of Claude, could you check if it solves this issue?
diff --git a/packages/babel-core/src/errors/rewrite-stack-trace.ts b/packages/babel-core/src/errors/rewrite-stack-trace.ts
index 0817a369f5..dd9d29c25c 100644
--- a/packages/babel-core/src/errors/rewrite-stack-trace.ts
+++ b/packages/babel-core/src/errors/rewrite-stack-trace.ts
@@ -104,31 +104,29 @@ export function beginHiddenCallStack<A extends unknown[], R>(
);
}
-// Keep the lifecycle inside the generator so all gensync entry points release
-// the hook on completion, before invoking a callback or settling a promise.
-// The STOP_HIDING boundary stays outside gensync to hide its internal frames.
+// Only Error.stackTraceLimit has to stay raised for the whole call, so that
+// errors capture enough frames. Error.prepareStackTrace is swapped in just for
+// the synchronous `.stack` read at the API boundary: V8 formats stacks lazily
+// on first access, so no other code can ever observe Babel's formatter.
export function withStackTraceRewriting<A extends unknown[], R>(
fn: (...args: A) => Handler<R>,
): (...args: A) => Handler<R> {
if (!SUPPORTED) return fn;
return function* rewriteStackTrace(...args: A): Handler<R> {
- setupPrepareStackTrace();
+ raiseStackTraceLimit();
try {
return yield* fn(...args);
} catch (err) {
- // Format the stack while the rewriter is still installed.
if (
err !== null &&
- (typeof err === "object" || typeof err === "function") &&
- "stack" in err
+ (typeof err === "object" || typeof err === "function")
) {
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
- err.stack;
+ formatStack(err as Error);
}
throw err;
} finally {
- resetPrepareStackTrace();
+ restoreStackTraceLimit();
}
};
}
@@ -147,11 +145,52 @@ export function endHiddenCallStack<A extends unknown[], R>(
);
}
-let originalPrepareStackTrace: (err: Error, trace: CallSite[]) => string;
-let originalMaxStackTraceLimit: number;
-let stackTraceRewriterRefCount = 0;
+let activeCalls = 0;
+let originalStackTraceLimit: number;
+let raisedStackTraceLimit: number;
-function stackTraceRewriter(err: Error, trace: CallSite[]) {
+function raiseStackTraceLimit() {
+ if (activeCalls++ > 0) return;
+ originalStackTraceLimit = Error.stackTraceLimit;
+ // We add some extra frames to Error.stackTraceLimit, so that we can
+ // always show some useful frames even after deleting ours.
+ // However, we only do it if the user did not explicitly set it to 0.
+ const MIN_STACK_TRACE_LIMIT = 50;
+ Error.stackTraceLimit &&= Math.max(
+ Error.stackTraceLimit,
+ MIN_STACK_TRACE_LIMIT,
+ );
+ raisedStackTraceLimit = Error.stackTraceLimit;
+}
+
+function restoreStackTraceLimit() {
+ if (--activeCalls > 0) return;
+ // Leave it alone if someone else changed it in the meantime.
+ if (Error.stackTraceLimit === raisedStackTraceLimit) {
+ Error.stackTraceLimit = originalStackTraceLimit;
+ }
+}
+
+function formatStack(err: Error) {
+ const prepareStackTrace = Error.prepareStackTrace;
+ Error.prepareStackTrace = function stackTraceRewriter(err, trace) {
+ return (prepareStackTrace || defaultPrepareStackTrace)(
+ err,
+ rewriteTrace(err, trace),
+ );
+ };
+ try {
+ // Formats the stack if nothing has read it yet; no-op otherwise.
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
+ err.stack;
+ } catch {
+ // e.g. a throwing `stack` getter: not our business
+ } finally {
+ Error.prepareStackTrace = prepareStackTrace;
+ }
+}
+
+function rewriteTrace(err: Error, trace: CallSite[]) {
let newTrace = [];
const isExpected = expectedErrors.has(err);
@@ -170,50 +209,13 @@ function stackTraceRewriter(err: Error, trace: CallSite[]) {
}
} else if (status === "unknown") {
// Unexpected internal error, show the full stack trace
- newTrace = trace;
- break;
+ return trace;
}
} else if (status !== "hiding") {
newTrace.push(trace[i]);
}
}
-
- return (originalPrepareStackTrace || defaultPrepareStackTrace)(err, newTrace);
-}
-
-function setupPrepareStackTrace() {
- if (stackTraceRewriterRefCount < 0 || stackTraceRewriterRefCount++ > 0) {
- return;
- }
- originalPrepareStackTrace = Error.prepareStackTrace;
- originalMaxStackTraceLimit = Error.stackTraceLimit;
-
- // We add some extra frames to Error.stackTraceLimit, so that we can
- // always show some useful frames even after deleting ours.
- // STACK_TRACE_LIMIT_DELTA should be around the maximum expected number
- // of internal frames, and not too big because capturing the stack trace
- // is slow (this is why Error.stackTraceLimit does not default to Infinity!).
- // Increase it if needed.
- // However, we only do it if the user did not explicitly set it to 0.
- const MIN_STACK_TRACE_LIMIT = 50;
- Error.stackTraceLimit &&= Math.max(
- Error.stackTraceLimit,
- MIN_STACK_TRACE_LIMIT,
- );
-
- Error.prepareStackTrace = stackTraceRewriter;
-}
-
-function resetPrepareStackTrace() {
- if (stackTraceRewriterRefCount < 0 || --stackTraceRewriterRefCount > 0) {
- return;
- }
- Error.stackTraceLimit = originalMaxStackTraceLimit;
- if (Error.prepareStackTrace !== stackTraceRewriter) {
- stackTraceRewriterRefCount = -1;
- return;
- }
- Error.prepareStackTrace = originalPrepareStackTrace;
+ return newTrace;
}
function defaultPrepareStackTrace(err: Error, trace: CallSite[]) {
diff --git a/packages/babel-core/test/errors-stacks.js b/packages/babel-core/test/errors-stacks.js
index b29c7884ec..822c420c92 100644
--- a/packages/babel-core/test/errors-stacks.js
+++ b/packages/babel-core/test/errors-stacks.js
@@ -335,7 +335,7 @@ describe("@babel/core errors", function () {
async pre() {
started();
await paused;
- expect(Error.prepareStackTrace).not.toBeNull();
+ expect(Error.prepareStackTrace).toBeNull();
expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
if (fails) throw new Error("asynchronous plugin failure");
},
@@ -356,7 +356,7 @@ describe("@babel/core errors", function () {
});
});
await entered;
- expect(Error.prepareStackTrace).not.toBeNull();
+ expect(Error.prepareStackTrace).toBeNull();
resume();
const outcome = await pending.then(
result => ({ result }),
@@ -395,7 +395,7 @@ describe("@babel/core errors", function () {
() => ({
pre() {
const rewriter = Error.prepareStackTrace;
- expect(rewriter).not.toBeNull();
+ expect(rewriter).toBeNull();
babel.parseSync("bar;", { configFile: false, babelrc: false });
expect(Error.prepareStackTrace).toBe(rewriter);
expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
@@ -442,7 +442,7 @@ describe("@babel/core errors", function () {
releases[0]();
await pending[0];
expect(Error.prepareStackTrace).toBe(rewriter);
- expect(Error.prepareStackTrace).not.toBeNull();
+ expect(Error.prepareStackTrace).toBeNull();
expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
releases[1]();
await pending[1];
@@ -485,6 +485,43 @@ describe("@babel/core errors", function () {
}
});
+ it("keeps hooks installed by other code during a call, and keeps hiding frames", function () {
+ const { prepareStackTrace, stackTraceLimit } = Error;
+ const foreign = (err, trace) => `${err}\n at ${trace.join("\n at ")}`;
+ try {
+ Error.prepareStackTrace = null;
+ Error.stackTraceLimit = 10;
+ babel.transformSync("foo;", {
+ configFile: false,
+ babelrc: false,
+ plugins: [
+ () => ({
+ pre() {
+ Error.prepareStackTrace = foreign;
+ Error.stackTraceLimit = 33;
+ },
+ }),
+ ],
+ });
+ expect(Error.prepareStackTrace).toBe(foreign);
+ expect(Error.stackTraceLimit).toBe(33);
+ Error.stackTraceLimit = 10;
+ // Frames are still hidden, and formatted by the current hook.
+ try {
+ babel.parseSync("foo;", { root: fixture("invalid-json") });
+ } catch (e) {
+ // Only the virtual config frame and the public entry point remain.
+ const frames = e.stack.split("\n").slice(1, 3);
+ expect(frames[0]).toMatch(/invalid-json\/babel\.config\.json$/);
+ expect(frames[1]).toMatch(/^\s+at Module\.parseSync /);
+ }
+ expect(Error.prepareStackTrace).toBe(foreign);
+ } finally {
+ Error.prepareStackTrace = prepareStackTrace;
+ Error.stackTraceLimit = stackTraceLimit;
+ }
+ });
+
it("should not throw in `node --frozen-intrinsics`", function () {
expect(
spawnSync(There was a problem hiding this comment.
Thanks! This looks good.
If err.stack has already been read, it won’t take effect, but I think that’s fine.
Apply JLHwung's suggestion to install the formatter only while reading an error stack, while keeping the stack trace limit raised during the call. Source: babel#16187 (comment) Assisted-by: GPT-6
JLHwung
left a comment
There was a problem hiding this comment.
Thank you, I have no other comments.