Skip to content

Commit d157131

Browse files
committed
buffers: handle bad length argument in constructor
Coerce fractional, negative and non-numeric length arguments to numbers. Fractional numbers are rounded up, negative numbers and non-numeric values are set to zero.
1 parent fcba145 commit d157131

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/buffer.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@ SlowBuffer.prototype.slice = function(start, end) {
196196
};
197197

198198

199+
function coerce(length) {
200+
// Coerce length to a number (possibly NaN), round up
201+
// in case it's fractional (e.g. 123.456) then do a
202+
// double negate to coerce a NaN to 0. Easy, right?
203+
length = ~~Math.ceil(+length);
204+
return length < 0 ? 0 : length;
205+
}
206+
207+
199208
// Buffer
200209

201210
function Buffer(subject, encoding, offset) {
@@ -207,22 +216,22 @@ function Buffer(subject, encoding, offset) {
207216

208217
// Are we slicing?
209218
if (typeof offset === 'number') {
210-
this.length = encoding;
219+
this.length = coerce(encoding);
211220
this.parent = subject;
212221
this.offset = offset;
213222
} else {
214223
// Find the length
215224
switch (type = typeof subject) {
216225
case 'number':
217-
this.length = subject;
226+
this.length = coerce(subject);
218227
break;
219228

220229
case 'string':
221230
this.length = Buffer.byteLength(subject, encoding);
222231
break;
223232

224233
case 'object': // Assume object is an array
225-
this.length = subject.length;
234+
this.length = coerce(subject.length);
226235
break;
227236

228237
default:

test/simple/test-buffer.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,3 +689,16 @@ buf.write('123456', 'base64');
689689
assert.equal(Buffer._charsWritten, 6);
690690
buf.write('00010203040506070809', 'hex');
691691
assert.equal(Buffer._charsWritten, 18);
692+
693+
// Check for fractional length args, junk length args, etc.
694+
// https://github.com/joyent/node/issues/1758
695+
Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec
696+
assert.equal(Buffer(-1).length, 0);
697+
assert.equal(Buffer(NaN).length, 0);
698+
assert.equal(Buffer(3.3).length, 4);
699+
assert.equal(Buffer({length:3.3}).length, 4);
700+
assert.equal(Buffer({length:"BAM"}).length, 0);
701+
702+
// Make sure that strings are not coerced to numbers.
703+
assert.equal(Buffer("99").length, 2);
704+
assert.equal(Buffer("13.37").length, 5);

0 commit comments

Comments
 (0)