From f206505e9d59b072de552310264ab4c3e8a361c5 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 19 Nov 2020 16:36:01 +0100 Subject: [PATCH] util: fix instanceof checks with null prototypes during inspection Signed-off-by: Ruben Bridgewater Backport-PR-URL: https://github.com/nodejs/node/pull/37100 PR-URL: https://github.com/nodejs/node/pull/36178 Fixes: https://github.com/nodejs/node/issues/35730 Fixes: https://github.com/nodejs/node/issues/36151 Refs: https://github.com/nodejs/node/pull/35754 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Rich Trott Reviewed-By: Guy Bedford Reviewed-By: James M Snell --- lib/internal/util/inspect.js | 10 +++++++++- test/parallel/test-util-inspect.js | 11 +++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index b8f2943961114f..cf4660b1f2d4d6 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -535,6 +535,14 @@ function getEmptyFormatArray() { return []; } +function isInstanceof(object, proto) { + try { + return object instanceof proto; + } catch { + return false; + } +} + function getConstructorName(obj, ctx, recurseTimes, protoProps) { let firstProto; const tmp = obj; @@ -543,7 +551,7 @@ function getConstructorName(obj, ctx, recurseTimes, protoProps) { if (descriptor !== undefined && typeof descriptor.value === 'function' && descriptor.value.name !== '' && - tmp instanceof descriptor.value) { + isInstanceof(tmp, descriptor.value)) { if (protoProps !== undefined && (firstProto !== obj || !builtInObjects.has(descriptor.value.name))) { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 9187af18da3099..8bc14815be0803 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2866,6 +2866,17 @@ assert.strictEqual( ); } +// Check that prototypes with a null prototype are inspectable. +// Regression test for https://github.com/nodejs/node/issues/35730 +{ + function Func() {} + Func.prototype = null; + const object = {}; + object.constructor = Func; + + assert.strictEqual(util.inspect(object), '{ constructor: [Function: Func] }'); +} + // Test changing util.inspect.colors colors and aliases. { const colors = util.inspect.colors;