From 2a80f7d0c53d234c48b549f8d75a723ddb0f0ff1 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 27 Aug 2024 10:58:40 +0200 Subject: [PATCH] buffer: Throw when writing beyond buffer" This reverts commit dd8eeec3f036549f1d8ed3c8b648b80795a48099. PR-URL: https://github.com/nodejs/node/pull/54588/ Refs: https://github.com/nodejs/node/pull/54524 --- lib/internal/buffer.js | 12 ++++++------ test/parallel/test-buffer-write.js | 13 +++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index 20b22ad529385a..dc21fb3e334588 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1036,33 +1036,33 @@ function addBufferPrototypeMethods(proto) { proto.hexSlice = hexSlice; proto.ucs2Slice = ucs2Slice; proto.utf8Slice = utf8Slice; - proto.asciiWrite = function(string, offset = 0, length = this.byteLength) { + proto.asciiWrite = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return asciiWriteStatic(this, string, offset, length); }; proto.base64Write = base64Write; proto.base64urlWrite = base64urlWrite; - proto.latin1Write = function(string, offset = 0, length = this.byteLength) { + proto.latin1Write = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return latin1WriteStatic(this, string, offset, length); }; proto.hexWrite = hexWrite; proto.ucs2Write = ucs2Write; - proto.utf8Write = function(string, offset = 0, length = this.byteLength) { + proto.utf8Write = function(string, offset = 0, length = this.byteLength - offset) { if (offset < 0 || offset > this.byteLength) { throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); } - if (length < 0) { + if (length < 0 || length > this.byteLength - offset) { throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } return utf8WriteStatic(this, string, offset, length); diff --git a/test/parallel/test-buffer-write.js b/test/parallel/test-buffer-write.js index 309367c9c75ca1..81076629b1d847 100644 --- a/test/parallel/test-buffer-write.js +++ b/test/parallel/test-buffer-write.js @@ -121,3 +121,16 @@ assert.throws(() => { }, common.expectsError({ code: 'ERR_BUFFER_OUT_OF_BOUNDS', })); + + +assert.throws(() => { + Buffer.alloc(1).asciiWrite('ww', 0, 2); +}, common.expectsError({ + code: 'ERR_BUFFER_OUT_OF_BOUNDS', +})); + +assert.throws(() => { + Buffer.alloc(1).asciiWrite('ww', 1, 1); +}, common.expectsError({ + code: 'ERR_BUFFER_OUT_OF_BOUNDS', +}));