diff --git a/src/string_decoder.cc b/src/string_decoder.cc index 203445f9381159..4c30c1119f1bd8 100644 --- a/src/string_decoder.cc +++ b/src/string_decoder.cc @@ -31,11 +31,11 @@ MaybeLocal MakeString(Isolate* isolate, Local error; MaybeLocal ret; if (encoding == UTF8) { - MaybeLocal utf8_string = String::NewFromUtf8( - isolate, - data, - v8::NewStringType::kNormal, - length); + MaybeLocal utf8_string; + if (length <= static_cast(v8::String::kMaxLength)) { + utf8_string = String::NewFromUtf8( + isolate, data, v8::NewStringType::kNormal, length); + } if (utf8_string.IsEmpty()) { isolate->ThrowException(node::ERR_STRING_TOO_LONG(isolate)); return MaybeLocal(); diff --git a/test/pummel/test-string-decoder-large-buffer.js b/test/pummel/test-string-decoder-large-buffer.js new file mode 100644 index 00000000000000..0ad1ee021c1fe7 --- /dev/null +++ b/test/pummel/test-string-decoder-large-buffer.js @@ -0,0 +1,30 @@ +'use strict'; +const common = require('../common'); + +// Buffer with size > INT32_MAX +common.skipIf32Bits(); + +const assert = require('assert'); +const { StringDecoder } = require('node:string_decoder'); +const kStringMaxLength = require('buffer').constants.MAX_STRING_LENGTH; + +const size = 2 ** 31; + +const stringTooLongError = { + message: `Cannot create a string longer than 0x${kStringMaxLength.toString(16)}` + + ' characters', + code: 'ERR_STRING_TOO_LONG', + name: 'Error', +}; + +try { + const buf = Buffer.allocUnsafe(size); + const decoder = new StringDecoder('utf8'); + assert.throws(() => decoder.write(buf), stringTooLongError); + assert.throws(() => decoder.end(buf), stringTooLongError); +} catch (e) { + if (e.code !== 'ERR_MEMORY_ALLOCATION_FAILED') { + throw e; + } + common.skip('insufficient space for Buffer.alloc'); +}