Skip to content

src,lib: support path in v8.writeHeapSnapshot output #58959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions doc/api/v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,9 @@ disk unless [`v8.stopCoverage()`][] is invoked before the process exits.
<!-- YAML
added: v11.13.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/58959
description: Support path option.
- version: v19.1.0
pr-url: https://github.com/nodejs/node/pull/44989
description: Support options to configure the heap snapshot.
Expand All @@ -526,6 +529,8 @@ changes:
**Default:** `false`.
* `exposeNumericValues` {boolean} If true, expose numeric values in
artificial fields. **Default:** `false`.
* `path` {string|Buffer|URL} If provided, specifies the file system location
where the snapshot will be written. **Default:** `undefined`
* Returns: {string} The filename where the snapshot was saved.

Generates a snapshot of the current V8 heap and writes it to a JSON
Expand Down
10 changes: 8 additions & 2 deletions lib/v8.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,22 @@ const { getOptionValue } = require('internal/options');
* @param {string} [filename]
* @param {{
* exposeInternals?: boolean,
* exposeNumericValues?: boolean
* exposeNumericValues?: boolean,
* path?: string,
* }} [options]
* @returns {string}
*/
function writeHeapSnapshot(filename, options) {
if (filename !== undefined) {
filename = getValidatedPath(filename);
}

if (options?.path !== undefined) {
options.path = getValidatedPath(options.path);
}

const optionArray = getHeapSnapshotOptions(options);
return triggerHeapSnapshot(filename, optionArray);
return triggerHeapSnapshot(filename, optionArray, options?.path);
}

/**
Expand Down
54 changes: 38 additions & 16 deletions src/heap_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -448,30 +448,52 @@ void CreateHeapSnapshotStream(const FunctionCallbackInfo<Value>& args) {
void TriggerHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = args.GetIsolate();
CHECK_EQ(args.Length(), 2);
CHECK_EQ(args.Length(), 3);
Local<Value> filename_v = args[0];
auto options = GetHeapSnapshotOptions(args[1]);
bool has_path = !args[2]->IsUndefined() && !args[2]->IsNull();
std::string final_filename;
BufferValue path_v(isolate, args[2]);
ToNamespacedPath(env, &path_v);

if (filename_v->IsUndefined()) {
DiagnosticFilename name(env, "Heap", "heapsnapshot");
THROW_IF_INSUFFICIENT_PERMISSIONS(
env,
permission::PermissionScope::kFileSystemWrite,
Environment::GetCwd(env->exec_path()));
if (WriteSnapshot(env, *name, options).IsNothing()) return;
if (String::NewFromUtf8(isolate, *name).ToLocal(&filename_v)) {
args.GetReturnValue().Set(filename_v);
if (!has_path) {
THROW_IF_INSUFFICIENT_PERMISSIONS(
env,
permission::PermissionScope::kFileSystemWrite,
Environment::GetCwd(env->exec_path()));
final_filename = *name;
} else {
THROW_IF_INSUFFICIENT_PERMISSIONS(
env,
permission::PermissionScope::kFileSystemWrite,
path_v.ToStringView());
final_filename = path_v.ToString() + "/" +
*name; // NOLINT(readability/pointer_notation)
}
} else {
BufferValue filename(isolate, filename_v);
CHECK_NOT_NULL(*filename);

if (has_path) {
final_filename = path_v.ToString() + "/" + filename.ToString();
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kFileSystemWrite, final_filename);
} else {
ToNamespacedPath(env, &filename);
THROW_IF_INSUFFICIENT_PERMISSIONS(
env,
permission::PermissionScope::kFileSystemWrite,
filename.ToStringView());
final_filename = filename.ToString();
}
return;
}

BufferValue path(isolate, filename_v);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kFileSystemWrite, path.ToStringView());
if (WriteSnapshot(env, *path, options).IsNothing()) return;
return args.GetReturnValue().Set(filename_v);
if (WriteSnapshot(env, final_filename.c_str(), options).IsNothing()) return;

args.GetReturnValue().Set(
String::NewFromUtf8(isolate, final_filename.c_str()).ToLocalChecked());
Copy link
Member

@jasnell jasnell Jul 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this is going to be a problem because it assumes the final_filename is utf8 encoded. Consider the following case:

const path = Buffer.from([0xe6]);  // latin 1 character
fs.mkdirSync(path);
const res = v8.writeHeapSnapshot(undefined, { path });
fs.readfileSync(res);  // fails! path doesn't exist

The reason fs.readfileSync would fail here is because the returned res will have interpreted the 0xe6 character incorrectly and will have replaced it with the unicode replacement char. The snapshot will have been written to disk correctly, but the returned path is wrong.

This likely needs to return the resulting path as a Buffer if the path was given as a Buffer and allow the API to accept an encoding option that optionally decodes the result as a string. But, that gets a bit awkward.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love how picky this is, aaah, let me put the encoding option to make this a bit more consistent and leave utf8 as default encoding.

Nice catch, thanks! Anything else missing?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing that sticks out, but I should have time to take another pass through by end of day monday

}

void Initialize(Local<Object> target,
Expand Down
12 changes: 4 additions & 8 deletions src/node_internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -422,16 +422,17 @@ namespace heap {
v8::Maybe<void> WriteSnapshot(Environment* env,
const char* filename,
v8::HeapProfiler::HeapSnapshotOptions options);
}

namespace heap {

void DeleteHeapSnapshot(const v8::HeapSnapshot* snapshot);
using HeapSnapshotPointer =
DeleteFnPtr<const v8::HeapSnapshot, DeleteHeapSnapshot>;

BaseObjectPtr<AsyncWrap> CreateHeapSnapshotStream(
Environment* env, HeapSnapshotPointer&& snapshot);

v8::HeapProfiler::HeapSnapshotOptions GetHeapSnapshotOptions(
v8::Local<v8::Value> options);

} // namespace heap

node_module napi_module_to_node_module(const napi_module* mod);
Expand Down Expand Up @@ -460,11 +461,6 @@ std::ostream& operator<<(std::ostream& output,

bool linux_at_secure();

namespace heap {
v8::HeapProfiler::HeapSnapshotOptions GetHeapSnapshotOptions(
v8::Local<v8::Value> options);
} // namespace heap

enum encoding ParseEncoding(v8::Isolate* isolate,
v8::Local<v8::Value> encoding_v,
v8::Local<v8::Value> encoding_id,
Expand Down
12 changes: 12 additions & 0 deletions test/common/heap.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,18 @@ function getHeapSnapshotOptionTests() {
],
}],
},
// This is the same as the previous case, but with a path option.
// The path option will be mutated by the test
// test-write-heapsnapshot-options.js
// Refs: https://github.com/nodejs/node/issues/58857
{
options: { exposeNumericValues: true, path: 'TBD' },
expected: [{
children: [
{ edge_name: 'numeric', node_name: 'smi number' },
],
}],
},
];
return {
fixtures: fixtures.path('klass-with-fields.js'),
Expand Down
24 changes: 22 additions & 2 deletions test/sequential/test-write-heapsnapshot-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

require('../common');

const assert = require('assert');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
const { getHeapSnapshotOptionTests, recordState } = require('../common/heap');

class ReadStream {
Expand All @@ -20,7 +22,12 @@ if (process.argv[2] === 'child') {
const { writeHeapSnapshot } = require('v8');
require(tests.fixtures);
const { options, expected } = tests.cases[parseInt(process.argv[3])];
const { path } = options;
// If path is set, writeHeapSnapshot will write to the tmpdir.
if (path) options.path = tmpdir.path;
const filename = writeHeapSnapshot(undefined, options);
// If path is set, the filename will be the provided path.
if (path) assert(filename.includes(tmpdir.path));
const snapshot = recordState(new ReadStream(filename));
console.log('Snapshot nodes', snapshot.snapshot.length);
console.log('Searching for', expected[0].children);
Expand All @@ -30,8 +37,6 @@ if (process.argv[2] === 'child') {
}

const { spawnSync } = require('child_process');
const assert = require('assert');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

// Start child processes to prevent the heap from growing too big.
Expand All @@ -48,3 +53,18 @@ for (let i = 0; i < tests.cases.length; ++i) {
console.log('[STDOUT]', stdout);
assert.strictEqual(child.status, 0);
}

{
// Don't need to spawn child process for this test, it will fail inmediately.
// Refs: https://github.com/nodejs/node/issues/58857
for (const pathName of [null, true, false, {}, [], () => {}, 1, 0, NaN]) {
assert.throws(() => {
require('v8').writeHeapSnapshot(undefined, {
path: pathName
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
name: 'TypeError'
});
}
}
Loading