From 57897f80cd3227a5de0056e25b0127b0627f218c Mon Sep 17 00:00:00 2001 From: Kohei Ueno Date: Wed, 2 Nov 2022 08:59:26 +0900 Subject: [PATCH] lib: fix TypeError when converting a detached buffer source PR-URL: https://github.com/nodejs/node/pull/44020 Reviewed-By: James M Snell Reviewed-By: Antoine du Hamel --- lib/internal/encoding.js | 22 +++++++++++++++---- ...test-whatwg-encoding-custom-textdecoder.js | 7 ++++++ test/wpt/status/encoding.json | 7 +----- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index f9fa43228d5f57..3a3d558361e118 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -412,7 +412,13 @@ function makeTextDecoderICU() { decode(input = empty, options = kEmptyObject) { validateDecoder(this); if (isAnyArrayBuffer(input)) { - input = lazyBuffer().from(input); + try { + input = lazyBuffer().from(input); + } catch { + // If the buffer is detached, + // use an empty Uint8Array to avoid TypeError + input = empty; + } } else if (!isArrayBufferView(input)) { throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'ArrayBufferView'], @@ -485,10 +491,18 @@ function makeTextDecoderJS() { decode(input = empty, options = kEmptyObject) { validateDecoder(this); if (isAnyArrayBuffer(input)) { - input = lazyBuffer().from(input); + try { + input = lazyBuffer().from(input); + } catch { + input = empty; + } } else if (isArrayBufferView(input)) { - input = lazyBuffer().from(input.buffer, input.byteOffset, - input.byteLength); + try { + input = lazyBuffer().from(input.buffer, input.byteOffset, + input.byteLength); + } catch { + input = empty; + } } else { throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'ArrayBufferView'], diff --git a/test/parallel/test-whatwg-encoding-custom-textdecoder.js b/test/parallel/test-whatwg-encoding-custom-textdecoder.js index 74c6a002223255..75a2a4735cd6ef 100644 --- a/test/parallel/test-whatwg-encoding-custom-textdecoder.js +++ b/test/parallel/test-whatwg-encoding-custom-textdecoder.js @@ -211,3 +211,10 @@ if (common.hasIntl) { assert.strictEqual(e.code, 'ERR_ENCODING_NOT_SUPPORTED'); } } + +{ + const buffer = new ArrayBuffer(1); + new MessageChannel().port1.postMessage(buffer, [buffer]); // buffer is detached + const decoder = new TextDecoder(); + assert.strictEqual(decoder.decode(buffer), ''); +} diff --git a/test/wpt/status/encoding.json b/test/wpt/status/encoding.json index 47d8c5f487fff9..ed98d966297ce2 100644 --- a/test/wpt/status/encoding.json +++ b/test/wpt/status/encoding.json @@ -61,12 +61,7 @@ "requires": ["small-icu"] }, "streams/decode-utf8.any.js": { - "requires": ["small-icu"], - "fail": { - "expected": [ - "decoding a transferred ArrayBuffer chunk should give no output" - ] - } + "requires": ["small-icu"] }, "streams/decode-bad-chunks.any.js": { "fail": {