Skip to content

Commit

Permalink
fs: extract out validateOffsetLengthWrite function
Browse files Browse the repository at this point in the history
PR-URL: #17682
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Anatoli Papirovski <apapirovski@mac.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
  • Loading branch information
maclover7 authored and joyeecheung committed Jan 11, 2018
1 parent 8983405 commit 300ea73
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,21 @@ function validateOffsetLengthRead(offset, length, bufferLength) {
}
}

function validateOffsetLengthWrite(offset, length, byteLength) {
let err;

if (offset > byteLength) {
err = new errors.RangeError('ERR_OUT_OF_RANGE', 'offset');
} else if (offset + length > byteLength || offset + length > kMaxLength) {
err = new errors.RangeError('ERR_OUT_OF_RANGE', 'length');
}

if (err !== undefined) {
Error.captureStackTrace(err, validateOffsetLengthWrite);
throw err;
}
}

// Special case of `makeCallback()` that is specific to async `*stat()` calls as
// an optimization, since the data passed back to the callback needs to be
// transformed anyway.
Expand Down Expand Up @@ -826,11 +841,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
length = buffer.length - offset;
if (typeof position !== 'number')
position = null;
const byteLength = buffer.byteLength;
if (offset > byteLength)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'offset');
if (offset + length > byteLength || offset + length > kMaxLength)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'length');
validateOffsetLengthWrite(offset, length, buffer.byteLength);
return binding.writeBuffer(fd, buffer, offset, length, position, req);
}

Expand Down Expand Up @@ -865,11 +876,7 @@ fs.writeSync = function(fd, buffer, offset, length, position) {
offset = 0;
if (typeof length !== 'number')
length = buffer.length - offset;
const byteLength = buffer.byteLength;
if (offset > byteLength)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'offset');
if (offset + length > byteLength || offset + length > kMaxLength)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'length');
validateOffsetLengthWrite(offset, length, buffer.byteLength);
return binding.writeBuffer(fd, buffer, offset, length, position);
}
if (typeof buffer !== 'string')
Expand Down

0 comments on commit 300ea73

Please sign in to comment.