Skip to content

Commit 62f802a

Browse files
addaleaxMylesBorins
authored andcommitted
fs: account for buffer alloc failure in readFile
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>
1 parent 118724f commit 62f802a

File tree

2 files changed

+18
-19
lines changed

2 files changed

+18
-19
lines changed

lib/fs.js

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,11 @@ function readFileAfterStat(err) {
457457
return context.close(err);
458458
}
459459

460-
context.buffer = Buffer.allocUnsafeSlow(size);
460+
try {
461+
context.buffer = Buffer.allocUnsafeSlow(size);
462+
} catch (err) {
463+
return context.close(err);
464+
}
461465
context.read();
462466
}
463467

@@ -492,27 +496,21 @@ function readFileAfterClose(err) {
492496
if (context.err || err)
493497
return callback(context.err || err);
494498

495-
if (context.size === 0)
496-
buffer = Buffer.concat(context.buffers, context.pos);
497-
else if (context.pos < context.size)
498-
buffer = context.buffer.slice(0, context.pos);
499-
else
500-
buffer = context.buffer;
501-
502-
if (context.encoding) {
503-
return tryToString(buffer, context.encoding, callback);
504-
}
505-
506-
callback(null, buffer);
507-
}
508-
509-
function tryToString(buf, encoding, callback) {
510499
try {
511-
buf = buf.toString(encoding);
500+
if (context.size === 0)
501+
buffer = Buffer.concat(context.buffers, context.pos);
502+
else if (context.pos < context.size)
503+
buffer = context.buffer.slice(0, context.pos);
504+
else
505+
buffer = context.buffer;
506+
507+
if (context.encoding)
508+
buffer = buffer.toString(context.encoding);
512509
} catch (err) {
513510
return callback(err);
514511
}
515-
callback(null, buf);
512+
513+
callback(null, buffer);
516514
}
517515

518516
function tryStatSync(fd, isUserFd) {

test/sequential/test-fs-readfile-tostring-fail.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ stream.on('finish', common.mustCall(function() {
2929
// make sure that the toString does not throw an error
3030
fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
3131
assert.ok(err instanceof Error);
32-
assert.strictEqual('"toString()" failed', err.message);
32+
assert(/^(Array buffer allocation failed|"toString\(\)" failed)$/
33+
.test(err.message));
3334
assert.strictEqual(buf, undefined);
3435
}));
3536
}));

0 commit comments

Comments
 (0)