Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
lib: account for cwd access from snapshot serialization cb
Functions registered with `addSerializeCallback()` can access and call
`process.cwd()`. b7d836e 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: #49684
  • Loading branch information
addaleax committed Feb 27, 2024
commit b9195b6e47752322bc716bf4fba2177b3989a1d8
4 changes: 4 additions & 0 deletions doc/api/v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions lib/internal/bootstrap/switches/does_own_process_state.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const credentials = internalBinding('credentials');
const rawMethods = internalBinding('process_methods');
const {
namespace: {
addDeserializeCallback,
addSerializeCallback,
isBuildingSnapshot,
},
Expand Down Expand Up @@ -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 = '';
});
});
}

Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/snapshot/cwd.js
Original file line number Diff line number Diff line change
@@ -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());
});