Skip to content

fix(core): Avoid crash when Function.prototype is frozen #7899

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

Merged
merged 4 commits into from
Apr 20, 2023
Merged
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
16 changes: 11 additions & 5 deletions packages/core/src/integrations/functiontostring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ export class FunctionToString implements Integration {
// eslint-disable-next-line @typescript-eslint/unbound-method
originalFunctionToString = Function.prototype.toString;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {
const context = getOriginalFunction(this) || this;
return originalFunctionToString.apply(context, args);
};
// intrinsics (like Function.prototype) might be immutable in some environments
// e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)
try {
Copy link
Member

Choose a reason for hiding this comment

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

Could you add a comment here for why this try-catch exists? For future reference :) Would also be nice to have an example when/why this may be frozen.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

for example:

pwsh> node --frozen-intrinsics
(node:26089) ExperimentalWarning: The --frozen-intrinsics flag is experimental
(Use `node --trace-warnings ...` to show where the warning was created)
Welcome to Node.js v19.9.0.
Type ".help" for more information.
> 'use strict'; Function.prototype.toString = function () { return '' }
Uncaught:
TypeError <Object <Object <[Object: null prototype] {}>>>: Cannot assign to read only property 'toString' of object 'function () { [native code] }'
    at Function.setter (node:internal/freeze_intrinsics:499:17)

image

Copy link
Member

Choose a reason for hiding this comment

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

thanks, that's perfect!

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {
const context = getOriginalFunction(this) || this;
return originalFunctionToString.apply(context, args);
};
} catch {
// ignore errors here, just don't patch this
}
}
}