Skip to content

Commit 04b63e0

Browse files
bnoordhuistrevnorris
authored andcommitted
lib: fix max size check in Buffer constructor
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: #657 Reviewed-By: Trevor Norris <[email protected]>
1 parent 605329d commit 04b63e0

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

lib/buffer.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ function Buffer(subject, encoding) {
5050
return new Buffer(subject, encoding);
5151

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

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

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

75+
if (this.length < 0)
76+
this.length = 0;
77+
else
78+
this.length >>>= 0; // Coerce to uint32.
79+
7680
this.parent = undefined;
7781
if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
7882
if (this.length > poolSize - poolOffset)

test/simple/test-buffer.js

+3
Original file line numberDiff line numberDiff line change
@@ -1184,3 +1184,6 @@ assert.throws(function() {
11841184
var b = new Buffer(1);
11851185
b.equals('abc');
11861186
});
1187+
1188+
// Regression test for https://github.com/iojs/io.js/issues/649.
1189+
assert.throws(function() { Buffer(1422561062959).toString('utf8'); });

0 commit comments

Comments
 (0)