Skip to content

Commit 3833a0f

Browse files
committed
buffer: fix Buffer.utf8Write fails when length exceeds integer range
1 parent 0951e7b commit 3833a0f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/node_buffer.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,9 @@ void StringWrite(const FunctionCallbackInfo<Value>& args) {
724724
&max_length));
725725

726726
max_length = std::min(ts_obj_length - offset, max_length);
727+
if (max_length > static_cast<size_t>(v8::String::kMaxLength)) {
728+
ThrowErrStringTooLong(env->isolate());
729+
}
727730

728731
if (max_length == 0)
729732
return args.GetReturnValue().Set(0);

test/parallel/test-buffer-alloc.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const {
88
SlowBuffer,
99
kMaxLength,
1010
} = require('buffer');
11+
const kStringMaxLength = require('buffer').constants.MAX_STRING_LENGTH;
1112

1213
// Verify the maximum Uint8Array size. There is no concrete limit by spec. The
1314
// internal limits should be updated if this fails.
@@ -107,6 +108,13 @@ const outOfRangeError = {
107108
name: 'RangeError'
108109
};
109110

111+
const stringTooLongError = {
112+
message: `Cannot create a string longer than 0x${kStringMaxLength.toString(16)}` +
113+
' characters',
114+
code: 'ERR_STRING_TOO_LONG',
115+
name: 'Error',
116+
};
117+
110118
// Try to write a 0-length string beyond the end of b
111119
assert.throws(() => b.write('', 2048), outOfRangeError);
112120

@@ -1147,6 +1155,22 @@ assert.throws(() => {
11471155
assert.strictEqual(ubuf.buffer.byteLength, 10);
11481156
}
11491157

1158+
// Invalid length of Buffer.utf8Write
1159+
{
1160+
const ubuf = Buffer.allocUnsafeSlow(2 ** 32);
1161+
assert.throws(() => {
1162+
ubuf.utf8Write('a', 2, kStringMaxLength + 2);
1163+
}, stringTooLongError);
1164+
}
1165+
1166+
// Invalid length of Buffer.write
1167+
{
1168+
const ubuf = Buffer.allocUnsafeSlow(2 ** 32);
1169+
assert.throws(() => {
1170+
ubuf.write('a', 2, kStringMaxLength + 2);
1171+
}, stringTooLongError);
1172+
}
1173+
11501174
// Regression test to verify that an empty ArrayBuffer does not throw.
11511175
Buffer.from(new ArrayBuffer());
11521176

0 commit comments

Comments
 (0)