lib: account for cwd access from snapshot serialization cb

Functions registered with `addSerializeCallback()` can access and call
`process.cwd()`. b7d836e2c7 accounted for the fact that it is
necessary to reset the cwd cache after the snapshot builder script has
run, but did not account for possible accesses from serialization
callbacks. To properly account for these, add a deserialization
callback as well.

As a related drive-by fix, also mention the execution order of
callbacks in the documentation.

Refs: https://github.com/nodejs/node/pull/49684
PR-URL: https://github.com/nodejs/node/pull/51901
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
This commit is contained in:
Anna Henningsen 2024-02-29 21:55:00 +01:00 committed by GitHub
parent f63e8b7fa7
commit 40565e90b4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 16 additions and 0 deletions

View File

@ -1021,6 +1021,8 @@ get serialized into a snapshot and exit. This can be used to release
resources that should not or cannot be serialized or to convert user data
into a form more suitable for serialization.
Callbacks are run in the order in which they are added.
### `v8.startupSnapshot.addDeserializeCallback(callback[, data])`
<!-- YAML
@ -1040,6 +1042,8 @@ serialized into the snapshot, they can be used to re-initialize the state
of the application or to re-acquire resources that the application needs
when the application is restarted from the snapshot.
Callbacks are run in the order in which they are added.
### `v8.startupSnapshot.setDeserializeMainFunction(callback[, data])`
<!-- YAML

View File

@ -4,6 +4,7 @@ const credentials = internalBinding('credentials');
const rawMethods = internalBinding('process_methods');
const {
namespace: {
addDeserializeCallback,
addSerializeCallback,
isBuildingSnapshot,
},
@ -114,8 +115,13 @@ function wrapPosixCredentialSetters(credentials) {
let cachedCwd = '';
if (isBuildingSnapshot()) {
// Reset the cwd on both serialization and deserialization so it's fine
// for process.cwd() to be accessed inside of serialization callbacks.
addSerializeCallback(() => {
cachedCwd = '';
addDeserializeCallback(() => {
cachedCwd = '';
});
});
}

View File

@ -1,10 +1,16 @@
const {
addSerializeCallback,
setDeserializeMainFunction,
} = require('v8').startupSnapshot;
// To make sure the cwd is present in the cache
process.cwd();
// Also access it from a serialization callback once
addSerializeCallback(() => {
process.cwd();
});
setDeserializeMainFunction(() => {
console.log(process.cwd());
});