Skip to content

Commit 3800d60

Browse files
ronagjasnell
authored andcommitted
buffer: throw when writing beyond buffer"
This reverts commit dd8eeec. PR-URL: #54588 Refs: #54524 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent e1d8b4f commit 3800d60

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

lib/internal/buffer.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -1036,33 +1036,33 @@ function addBufferPrototypeMethods(proto) {
10361036
proto.hexSlice = hexSlice;
10371037
proto.ucs2Slice = ucs2Slice;
10381038
proto.utf8Slice = utf8Slice;
1039-
proto.asciiWrite = function(string, offset = 0, length = this.byteLength) {
1039+
proto.asciiWrite = function(string, offset = 0, length = this.byteLength - offset) {
10401040
if (offset < 0 || offset > this.byteLength) {
10411041
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10421042
}
1043-
if (length < 0) {
1043+
if (length < 0 || length > this.byteLength - offset) {
10441044
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10451045
}
10461046
return asciiWriteStatic(this, string, offset, length);
10471047
};
10481048
proto.base64Write = base64Write;
10491049
proto.base64urlWrite = base64urlWrite;
1050-
proto.latin1Write = function(string, offset = 0, length = this.byteLength) {
1050+
proto.latin1Write = function(string, offset = 0, length = this.byteLength - offset) {
10511051
if (offset < 0 || offset > this.byteLength) {
10521052
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10531053
}
1054-
if (length < 0) {
1054+
if (length < 0 || length > this.byteLength - offset) {
10551055
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10561056
}
10571057
return latin1WriteStatic(this, string, offset, length);
10581058
};
10591059
proto.hexWrite = hexWrite;
10601060
proto.ucs2Write = ucs2Write;
1061-
proto.utf8Write = function(string, offset = 0, length = this.byteLength) {
1061+
proto.utf8Write = function(string, offset = 0, length = this.byteLength - offset) {
10621062
if (offset < 0 || offset > this.byteLength) {
10631063
throw new ERR_BUFFER_OUT_OF_BOUNDS('offset');
10641064
}
1065-
if (length < 0) {
1065+
if (length < 0 || length > this.byteLength - offset) {
10661066
throw new ERR_BUFFER_OUT_OF_BOUNDS('length');
10671067
}
10681068
return utf8WriteStatic(this, string, offset, length);

test/parallel/test-buffer-write.js

+13
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,16 @@ assert.throws(() => {
121121
}, common.expectsError({
122122
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
123123
}));
124+
125+
126+
assert.throws(() => {
127+
Buffer.alloc(1).asciiWrite('ww', 0, 2);
128+
}, common.expectsError({
129+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
130+
}));
131+
132+
assert.throws(() => {
133+
Buffer.alloc(1).asciiWrite('ww', 1, 1);
134+
}, common.expectsError({
135+
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
136+
}));

0 commit comments

Comments
 (0)