Skip to content

Commit

Permalink
fs: account for buffer alloc failure in readFile
Browse files Browse the repository at this point in the history
PR-URL: #16219
Refs: #15362
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
addaleax authored and MylesBorins committed Oct 23, 2017
1 parent 118724f commit 62f802a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 19 deletions.
34 changes: 16 additions & 18 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,11 @@ function readFileAfterStat(err) {
return context.close(err);
}

context.buffer = Buffer.allocUnsafeSlow(size);
try {
context.buffer = Buffer.allocUnsafeSlow(size);
} catch (err) {
return context.close(err);
}
context.read();
}

Expand Down Expand Up @@ -492,27 +496,21 @@ function readFileAfterClose(err) {
if (context.err || err)
return callback(context.err || err);

if (context.size === 0)
buffer = Buffer.concat(context.buffers, context.pos);
else if (context.pos < context.size)
buffer = context.buffer.slice(0, context.pos);
else
buffer = context.buffer;

if (context.encoding) {
return tryToString(buffer, context.encoding, callback);
}

callback(null, buffer);
}

function tryToString(buf, encoding, callback) {
try {
buf = buf.toString(encoding);
if (context.size === 0)
buffer = Buffer.concat(context.buffers, context.pos);
else if (context.pos < context.size)
buffer = context.buffer.slice(0, context.pos);
else
buffer = context.buffer;

if (context.encoding)
buffer = buffer.toString(context.encoding);
} catch (err) {
return callback(err);
}
callback(null, buf);

callback(null, buffer);
}

function tryStatSync(fd, isUserFd) {
Expand Down
3 changes: 2 additions & 1 deletion test/sequential/test-fs-readfile-tostring-fail.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ stream.on('finish', common.mustCall(function() {
// make sure that the toString does not throw an error
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
assert.ok(err instanceof Error);
assert.strictEqual('"toString()" failed', err.message);
assert(/^(Array buffer allocation failed|"toString\(\)" failed)$/
.test(err.message));
assert.strictEqual(buf, undefined);
}));
}));
Expand Down

0 comments on commit 62f802a

Please sign in to comment.