Skip to content

Commit 1d9ccb6

Browse files
committed
fix buffer out of bounds crashing instead of emitting a clean error
1 parent 7318aa6 commit 1d9ccb6

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

fd-slicer.js

+22-5
Original file line numberDiff line numberDiff line change
@@ -195,12 +195,29 @@ function BufferSlicer(buffer, options) {
195195
}
196196

197197
BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
198-
var end = position + length;
199-
var delta = end - this.buffer.length;
200-
var written = (delta > 0) ? delta : length;
201-
this.buffer.copy(buffer, offset, position, end);
198+
if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
199+
if (position < 0) throw new RangeError("position is negative: " + position);
200+
if (offset + length > buffer.length) {
201+
// The caller's buffer can't hold all the bytes they're trying to read.
202+
// Clamp the length instead of giving an error.
203+
// The callback will be informed of fewer than expected bytes written.
204+
length = buffer.length - offset;
205+
}
206+
if (position + length > this.buffer.length) {
207+
// Clamp any attempt to read past the end of the source buffer.
208+
length = this.buffer.length - position;
209+
}
210+
if (length <= 0) {
211+
// After any clamping, we're fully out of bounds or otherwise have nothing to do.
212+
// This isn't an error; it's just zero bytes written.
213+
setImmediate(function() {
214+
callback(null, 0);
215+
});
216+
return;
217+
}
218+
this.buffer.copy(buffer, offset, position, position + length);
202219
setImmediate(function() {
203-
callback(null, written);
220+
callback(null, length);
204221
});
205222
};
206223

0 commit comments

Comments
 (0)