Skip to content

Commit c4f6077

Browse files
bnoordhuistargos
authored andcommitted
tools: make code cache and snapshot deterministic
Use a fixed random seed to ensure that the generated sources are identical across runs. The final node binary still reseeds itself on start-up so there should be no security implications caused by predictable random numbers (e.g., `Math.random()`, ASLR, the hash seed, etc.) Fixes: #29108 PR-URL: #29142 Reviewed-By: Gus Caplan <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent d4e397a commit c4f6077

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

test/parallel/test-math-random.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
const { spawnSync } = require('child_process');
6+
7+
const results = new Set();
8+
for (let i = 0; i < 10; i++) {
9+
const result = spawnSync(process.execPath, ['-p', 'Math.random()']);
10+
assert.strictEqual(result.status, 0);
11+
results.add(result.stdout.toString());
12+
}
13+
// It's theoretically possible if _very_ unlikely to see some duplicates.
14+
// Therefore, don't expect that the size of the set is exactly 10 but do
15+
// assume it's > 1 because if you get 10 duplicates in a row you should
16+
// go out real quick and buy some lottery tickets, you lucky devil you!
17+
assert(results.size > 1);

tools/code_cache/mkcodecache.cc

+5
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ int wmain(int argc, wchar_t* argv[]) {
2626
int main(int argc, char* argv[]) {
2727
#endif // _WIN32
2828

29+
v8::V8::SetFlagsFromString("--random_seed=42");
30+
2931
if (argc < 2) {
3032
std::cerr << "Usage: " << argv[0] << " <path/to/output.cc>\n";
3133
return 1;
@@ -53,6 +55,9 @@ int main(int argc, char* argv[]) {
5355
v8::Local<v8::Context> context = v8::Context::New(isolate);
5456
v8::Context::Scope context_scope(context);
5557

58+
// The command line flags are part of the code cache's checksum so reset
59+
// --random_seed= to its default value before creating the code cache.
60+
v8::V8::SetFlagsFromString("--random_seed=0");
5661
std::string cache = CodeCacheBuilder::Generate(context);
5762
out << cache;
5863
out.close();

tools/snapshot/node_mksnapshot.cc

+2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ int wmain(int argc, wchar_t* argv[]) {
1919
int main(int argc, char* argv[]) {
2020
#endif // _WIN32
2121

22+
v8::V8::SetFlagsFromString("--random_seed=42");
23+
2224
if (argc < 2) {
2325
std::cerr << "Usage: " << argv[0] << " <path/to/output.cc>\n";
2426
return 1;

0 commit comments

Comments
 (0)