Skip to content

Commit

Permalink
string_decoder: throw an error when writing a too long buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
kylo5aby committed Mar 27, 2024
1 parent 1264414 commit f691105
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/string_decoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ MaybeLocal<String> MakeString(Isolate* isolate,
Local<Value> error;
MaybeLocal<Value> ret;
if (encoding == UTF8) {
MaybeLocal<String> utf8_string = String::NewFromUtf8(
isolate,
data,
v8::NewStringType::kNormal,
length);
MaybeLocal<String> utf8_string;
if (length <= static_cast<size_t>(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<String>();
Expand Down
30 changes: 30 additions & 0 deletions test/pummel/test-string-decoder-large-buffer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
const common = require('../common');

// buffer with size > INT32_MAX

Check failure on line 4 in test/pummel/test-string-decoder-large-buffer.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Comments should not begin with a lowercase character
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.alloc(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');
}

0 comments on commit f691105

Please sign in to comment.