Skip to content

Commit

Permalink
fs: fix validation of negative offset to avoid abort
Browse files Browse the repository at this point in the history
Signed-off-by: James M Snell <jasnell@gmail.com>
Fixes: #24640
  • Loading branch information
jasnell committed Apr 26, 2021
1 parent bbe24e2 commit 3e2de1e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
8 changes: 4 additions & 4 deletions lib/fs.js
Expand Up @@ -543,7 +543,7 @@ function read(fd, buffer, offset, length, position, callback) {
if (offset == null) {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}

length |= 0;
Expand Down Expand Up @@ -599,7 +599,7 @@ function readSync(fd, buffer, offset, length, position) {
if (offset == null) {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}

length |= 0;
Expand Down Expand Up @@ -679,7 +679,7 @@ function write(fd, buffer, offset, length, position, callback) {
if (offset == null || typeof offset === 'function') {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}
if (typeof length !== 'number')
length = buffer.byteLength - offset;
Expand Down Expand Up @@ -730,7 +730,7 @@ function writeSync(fd, buffer, offset, length, position) {
if (offset == null) {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}
if (typeof length !== 'number')
length = buffer.byteLength - offset;
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/fs/promises.js
Expand Up @@ -417,7 +417,7 @@ async function read(handle, bufferOrOptions, offset, length, position) {
if (offset == null) {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}

length |= 0;
Expand Down Expand Up @@ -460,7 +460,7 @@ async function write(handle, buffer, offset, length, position) {
if (offset == null) {
offset = 0;
} else {
validateInteger(offset, 'offset');
validateInteger(offset, 'offset', 0);
}
if (typeof length !== 'number')
length = buffer.byteLength - offset;
Expand Down
37 changes: 37 additions & 0 deletions test/parallel/test-fs-write-negativeoffset.js
@@ -0,0 +1,37 @@
'use strict';

// Tests that passing a negative offset does not crash the process

const common = require('../common');

const {
join,
} = require('path');

const {
closeSync,
open,
write,
writeSync,
} = require('fs');

const assert = require('assert');

const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

const filename = join(tmpdir.path, 'test.txt');

open(filename, 'w+', common.mustSucceed((fd) => {
assert.throws(() => {
write(fd, Buffer.alloc(0), -1, common.mustNotCall());
}, {
code: 'ERR_OUT_OF_RANGE',
});
assert.throws(() => {
writeSync(fd, Buffer.alloc(0), -1);
}, {
code: 'ERR_OUT_OF_RANGE',
});
closeSync(fd);
}));

0 comments on commit 3e2de1e

Please sign in to comment.