Skip to content

Commit a5f3dd1

Browse files
kylo5abymarco-ippolito
authored andcommittedJun 17, 2024
string_decoder: throw an error when writing a too long buffer
PR-URL: #52215 Fixes: #52214 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: theanarkh <theratliter@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 739adf9 commit a5f3dd1

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed
 

‎src/string_decoder.cc

+5-5
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,11 @@ MaybeLocal<String> MakeString(Isolate* isolate,
3131
Local<Value> error;
3232
MaybeLocal<Value> ret;
3333
if (encoding == UTF8) {
34-
MaybeLocal<String> utf8_string = String::NewFromUtf8(
35-
isolate,
36-
data,
37-
v8::NewStringType::kNormal,
38-
length);
34+
MaybeLocal<String> utf8_string;
35+
if (length <= static_cast<size_t>(v8::String::kMaxLength)) {
36+
utf8_string = String::NewFromUtf8(
37+
isolate, data, v8::NewStringType::kNormal, length);
38+
}
3939
if (utf8_string.IsEmpty()) {
4040
isolate->ThrowException(node::ERR_STRING_TOO_LONG(isolate));
4141
return MaybeLocal<String>();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
// Buffer with size > INT32_MAX
5+
common.skipIf32Bits();
6+
7+
const assert = require('assert');
8+
const { StringDecoder } = require('node:string_decoder');
9+
const kStringMaxLength = require('buffer').constants.MAX_STRING_LENGTH;
10+
11+
const size = 2 ** 31;
12+
13+
const stringTooLongError = {
14+
message: `Cannot create a string longer than 0x${kStringMaxLength.toString(16)}` +
15+
' characters',
16+
code: 'ERR_STRING_TOO_LONG',
17+
name: 'Error',
18+
};
19+
20+
try {
21+
const buf = Buffer.allocUnsafe(size);
22+
const decoder = new StringDecoder('utf8');
23+
assert.throws(() => decoder.write(buf), stringTooLongError);
24+
} catch (e) {
25+
if (e.code !== 'ERR_MEMORY_ALLOCATION_FAILED') {
26+
throw e;
27+
}
28+
common.skip('insufficient space for Buffer.alloc');
29+
}

0 commit comments

Comments
 (0)
Please sign in to comment.