Skip to content

Commit 43c5726

Browse files
bnoordhuisevanlucas
authored andcommitted
src: fix UB in InternalModuleReadFile()
`&vec[0]` is undefined behavior when `vec.size() == 0`. It is mostly academic because package.json files are not usually empty and because with most STL implementations it decays to something that is legal C++ as long as the result is not dereferenced, but better safe than sorry. Note that the tests don't actually fail because of that, I added them as sanity checks. PR-URL: #16871 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Franziska Hinkelmann <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 28b7bf0 commit 43c5726

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

src/node_file.cc

+11-6
Original file line numberDiff line numberDiff line change
@@ -515,12 +515,17 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
515515
start = 3; // Skip UTF-8 BOM.
516516
}
517517

518-
Local<String> chars_string =
519-
String::NewFromUtf8(env->isolate(),
520-
&chars[start],
521-
String::kNormalString,
522-
offset - start);
523-
args.GetReturnValue().Set(chars_string);
518+
const size_t size = offset - start;
519+
if (size == 0) {
520+
args.GetReturnValue().SetEmptyString();
521+
} else {
522+
Local<String> chars_string =
523+
String::NewFromUtf8(env->isolate(),
524+
&chars[start],
525+
String::kNormalString,
526+
size);
527+
args.GetReturnValue().Set(chars_string);
528+
}
524529
}
525530

526531
// Used to speed up module loading. Returns 0 if the path refers to

test/fixtures/empty-with-bom.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+


test/parallel/test-module-binding.js

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
'use strict';
2+
require('../common');
3+
const fixtures = require('../common/fixtures');
4+
const { internalModuleReadFile } = process.binding('fs');
5+
const { strictEqual } = require('assert');
6+
7+
strictEqual(internalModuleReadFile('nosuchfile'), undefined);
8+
strictEqual(internalModuleReadFile(fixtures.path('empty.txt')), '');
9+
strictEqual(internalModuleReadFile(fixtures.path('empty-with-bom.txt')), '');

0 commit comments

Comments
 (0)