Skip to content

Commit

Permalink
lib: fix TypeError when converting a detached buffer source
Browse files Browse the repository at this point in the history
PR-URL: #44020
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
  • Loading branch information
cola119 authored and RafaelGSS committed Nov 10, 2022
1 parent d5f4d98 commit d172669
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
22 changes: 18 additions & 4 deletions lib/internal/encoding.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down Expand Up @@ -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'],
Expand Down
7 changes: 7 additions & 0 deletions test/parallel/test-whatwg-encoding-custom-textdecoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -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), '');
}
7 changes: 1 addition & 6 deletions test/wpt/status/encoding.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down

0 comments on commit d172669

Please sign in to comment.