util: do not crash on inspecting function with `Symbol` name

Refs: https://github.com/nodejs/node/issues/56570
PR-URL: https://github.com/nodejs/node/pull/56572
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
pull/56574/head
Jordan Harband 2025-01-14 16:16:48 -08:00 committed by GitHub
parent 294abc2ffc
commit 2570f95ad1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 3 deletions

View File

@ -989,7 +989,7 @@ function formatRaw(ctx, value, recurseTimes, typedArray) {
keys = getKeys(value, ctx.showHidden);
braces = ['{', '}'];
if (typeof value === 'function') {
base = getFunctionBase(value, constructor, tag);
base = getFunctionBase(ctx, value, constructor, tag);
if (keys.length === 0 && protoProps === undefined)
return ctx.stylize(base, 'special');
} else if (constructor === 'Object') {
@ -1223,7 +1223,7 @@ function getClassBase(value, constructor, tag) {
return `[${base}]`;
}
function getFunctionBase(value, constructor, tag) {
function getFunctionBase(ctx, value, constructor, tag) {
const stringified = FunctionPrototypeToString(value);
if (StringPrototypeStartsWith(stringified, 'class') && stringified[stringified.length - 1] === '}') {
const slice = StringPrototypeSlice(stringified, 5, -1);
@ -1250,7 +1250,7 @@ function getFunctionBase(value, constructor, tag) {
if (value.name === '') {
base += ' (anonymous)';
} else {
base += `: ${value.name}`;
base += `: ${typeof value.name === 'string' ? value.name : formatValue(ctx, value.name)}`;
}
base += ']';
if (constructor !== type && constructor !== null) {

View File

@ -3426,3 +3426,13 @@ assert.strictEqual(
Object.defineProperty(BuiltinPrototype, 'constructor', desc);
}
}
{
function f() {}
Object.defineProperty(f, 'name', { value: Symbol('f') });
assert.strictEqual(
util.inspect(f),
'[Function: Symbol(f)]',
);
}