Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
lib: fix max size check in Buffer constructor
Browse files Browse the repository at this point in the history
A number -> uint32 type coercion bug made buffer sizes
larger than kMaxLength (0x3fffffff) wrap around.

Instead of rejecting the requested size with an exception,
the constructor created a buffer with the wrong size.

PR-URL: nodejs/node#657
Reviewed-By: Trevor Norris <[email protected]>
  • Loading branch information
bnoordhuis authored and trevnorris committed Feb 10, 2015
1 parent 605329d commit 04b63e0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function Buffer(subject, encoding) {
return new Buffer(subject, encoding);

if (util.isNumber(subject)) {
this.length = subject > 0 ? subject >>> 0 : 0;
this.length = +subject;

} else if (util.isString(subject)) {
if (!util.isString(encoding) || encoding.length === 0)
Expand All @@ -61,8 +61,7 @@ function Buffer(subject, encoding) {
} else if (util.isObject(subject)) {
if (subject.type === 'Buffer' && util.isArray(subject.data))
subject = subject.data;
// Must use floor() because array length may be > kMaxLength.
this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
this.length = +subject.length;

} else {
throw new TypeError('must start with number, buffer, array or string');
Expand All @@ -73,6 +72,11 @@ function Buffer(subject, encoding) {
'size: 0x' + kMaxLength.toString(16) + ' bytes');
}

if (this.length < 0)
this.length = 0;
else
this.length >>>= 0; // Coerce to uint32.

this.parent = undefined;
if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
if (this.length > poolSize - poolOffset)
Expand Down
3 changes: 3 additions & 0 deletions test/simple/test-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1184,3 +1184,6 @@ assert.throws(function() {
var b = new Buffer(1);
b.equals('abc');
});

// Regression test for https://github.com/iojs/io.js/issues/649.
assert.throws(function() { Buffer(1422561062959).toString('utf8'); });

0 comments on commit 04b63e0

Please sign in to comment.