Skip to content

Commit f6bce20

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 93aad55 commit f6bce20

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/buffer.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,15 @@ SlowBuffer.prototype.slice = function(start, end) {
123123
};
124124

125125

126+
function coerce(length) {
127+
// Coerce length to a number (possibly NaN), round up
128+
// in case it's fractional (e.g. 123.456) then do a
129+
// double negate to coerce a NaN to 0. Easy, right?
130+
length = ~~Math.ceil(+length);
131+
return length < 0 ? 0 : length;
132+
}
133+
134+
126135
// Buffer
127136

128137
function Buffer(subject, encoding, offset) {
@@ -134,22 +143,22 @@ function Buffer(subject, encoding, offset) {
134143

135144
// Are we slicing?
136145
if (typeof offset === 'number') {
137-
this.length = encoding;
146+
this.length = coerce(encoding);
138147
this.parent = subject;
139148
this.offset = offset;
140149
} else {
141150
// Find the length
142151
switch (type = typeof subject) {
143152
case 'number':
144-
this.length = subject;
153+
this.length = coerce(subject);
145154
break;
146155

147156
case 'string':
148157
this.length = Buffer.byteLength(subject, encoding);
149158
break;
150159

151160
case 'object': // Assume object is an array
152-
this.length = subject.length;
161+
this.length = coerce(subject.length);
153162
break;
154163

155164
default:

test/simple/test-buffer.js

+13
Original file line numberDiff line numberDiff line change
@@ -572,3 +572,16 @@ buf.write('0123456789', 'binary');
572572
assert.equal(Buffer._charsWritten, 9);
573573
buf.write('123456', 'base64');
574574
assert.equal(Buffer._charsWritten, 6);
575+
576+
// Check for fractional length args, junk length args, etc.
577+
// https://github.com/joyent/node/issues/1758
578+
Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec
579+
assert.equal(Buffer(-1).length, 0);
580+
assert.equal(Buffer(NaN).length, 0);
581+
assert.equal(Buffer(3.3).length, 4);
582+
assert.equal(Buffer({length:3.3}).length, 4);
583+
assert.equal(Buffer({length:"BAM"}).length, 0);
584+
585+
// Make sure that strings are not coerced to numbers.
586+
assert.equal(Buffer("99").length, 2);
587+
assert.equal(Buffer("13.37").length, 5);

0 commit comments

Comments
 (0)