Skip to content

Commit 8a8e086

Browse files
committed
v8: support gc profile
1 parent 5d50b84 commit 8a8e086

8 files changed

+482
-2
lines changed

doc/api/v8.md

+77
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,83 @@ The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the
390390
command line or the API is called more than once. `limit` must be a positive
391391
integer. See [`--heapsnapshot-near-heap-limit`][] for more information.
392392

393+
## `v8.takeGCProfile(options)`
394+
395+
<!-- YAML
396+
added: REPLACEME
397+
-->
398+
399+
* `options` {Object}
400+
* `filename` {string} Node.js will write data to `filename`.
401+
* `duration` {number} how long you want to collect the gc data.
402+
403+
* Returns: {Promise}
404+
405+
This API collects gc data over a period of time and write it to the `filename`.
406+
The content is as follows.
407+
408+
```json
409+
{
410+
"version": 1,
411+
"startTime": 1674059033862,
412+
"statistics": [
413+
{
414+
"gcType": "Scavenge",
415+
"beforeGC": {
416+
"heapStatistics": {
417+
"totalHeapSize": 5005312,
418+
"totalHeapSizeExecutable": 524288,
419+
"totalPhysicalSize": 5226496,
420+
"totalAvailableSize": 4341325216,
421+
"totalGlobalHandlesSize": 8192,
422+
"usedGlobalHandlesSize": 2112,
423+
"usedHeapSize": 4883840,
424+
"heapSizeLimit": 4345298944,
425+
"mallocedMemory": 254128,
426+
"externalMemory": 225138,
427+
"peakMallocedMemory": 181760
428+
},
429+
"heapSpaceStatistics": [
430+
{
431+
"spaceName": "read_only_space",
432+
"spaceSize": 0,
433+
"spaceUsedSize": 0,
434+
"spaceAvailableSize": 0,
435+
"physicalSpaceSize": 0
436+
}
437+
]
438+
},
439+
"cost": 1574.14,
440+
"afterGC": {
441+
"heapStatistics": {
442+
"totalHeapSize": 6053888,
443+
"totalHeapSizeExecutable": 524288,
444+
"totalPhysicalSize": 5500928,
445+
"totalAvailableSize": 4341101384,
446+
"totalGlobalHandlesSize": 8192,
447+
"usedGlobalHandlesSize": 2112,
448+
"usedHeapSize": 4059096,
449+
"heapSizeLimit": 4345298944,
450+
"mallocedMemory": 254128,
451+
"externalMemory": 225138,
452+
"peakMallocedMemory": 181760
453+
},
454+
"heapSpaceStatistics": [
455+
{
456+
"spaceName": "read_only_space",
457+
"spaceSize": 0,
458+
"spaceUsedSize": 0,
459+
"spaceAvailableSize": 0,
460+
"physicalSpaceSize": 0
461+
}
462+
]
463+
}
464+
}
465+
],
466+
"endtTime": 1674059036865
467+
}
468+
```
469+
393470
## Serialization API
394471

395472
The serialization API provides means of serializing JavaScript values in a way

lib/v8.js

+29-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const {
3333
} = primordials;
3434

3535
const { Buffer } = require('buffer');
36-
const { validateString, validateUint32 } = require('internal/validators');
36+
const { validateString, validateUint32, validateObject, validateNumber } = require('internal/validators');
3737
const {
3838
Serializer,
3939
Deserializer
@@ -63,7 +63,8 @@ const {
6363
} = require('internal/heap_utils');
6464
const promiseHooks = require('internal/promise_hooks');
6565
const { getOptionValue } = require('internal/options');
66-
66+
const { setUnrefTimeout } = require('internal/timers');
67+
const { Promise } = primordials;
6768
/**
6869
* Generates a snapshot of the current V8 heap
6970
* and writes it to a JSON file.
@@ -397,6 +398,31 @@ function deserialize(buffer) {
397398
return der.readValue();
398399
}
399400

401+
/**
402+
* @param {{
403+
* filename: string,
404+
* duration: number,
405+
* }} [options]
406+
*/
407+
function takeGCProfile(options) {
408+
validateObject(options, 'options');
409+
validateString(options.filename, 'options.filename');
410+
validateNumber(options.duration, 'options.duration', 1);
411+
return new Promise((resolve, reject) => {
412+
const profiler = new binding.GCProfiler();
413+
try {
414+
profiler.startGCProfile(options.filename);
415+
} catch (e) {
416+
reject(e);
417+
return;
418+
}
419+
setUnrefTimeout(() => {
420+
profiler.stopGCProfile();
421+
resolve();
422+
}, options.duration);
423+
});
424+
}
425+
400426
module.exports = {
401427
cachedDataVersionTag,
402428
getHeapSnapshot,
@@ -416,4 +442,5 @@ module.exports = {
416442
promiseHooks,
417443
startupSnapshot,
418444
setHeapSnapshotNearHeapLimit,
445+
takeGCProfile,
419446
};

src/node_v8.cc

+211
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ namespace v8_utils {
3333
using v8::Array;
3434
using v8::Context;
3535
using v8::FunctionCallbackInfo;
36+
using v8::FunctionTemplate;
3637
using v8::HandleScope;
3738
using v8::HeapCodeStatistics;
3839
using v8::HeapSpaceStatistics;
@@ -210,6 +211,205 @@ void SetFlagsFromString(const FunctionCallbackInfo<Value>& args) {
210211
V8::SetFlagsFromString(*flags, static_cast<size_t>(flags.length()));
211212
}
212213

214+
static const char* GetGCTypeName(v8::GCType gc_type) {
215+
switch (gc_type) {
216+
case v8::GCType::kGCTypeScavenge:
217+
return "Scavenge";
218+
case v8::GCType::kGCTypeMarkSweepCompact:
219+
return "MarkSweepCompact";
220+
case v8::GCType::kGCTypeIncrementalMarking:
221+
return "IncrementalMarking";
222+
case v8::GCType::kGCTypeProcessWeakCallbacks:
223+
return "ProcessWeakCallbacks";
224+
default:
225+
return "UnKnow";
226+
}
227+
}
228+
229+
static void SetHeapStatistics(JSONWriter* writer, Isolate* isolate) {
230+
HeapStatistics heap_statistics;
231+
isolate->GetHeapStatistics(&heap_statistics);
232+
writer->json_objectstart("heapStatistics");
233+
writer->json_keyvalue("totalHeapSize", heap_statistics.total_heap_size());
234+
writer->json_keyvalue("totalHeapSizeExecutable",
235+
heap_statistics.total_heap_size_executable());
236+
writer->json_keyvalue("totalPhysicalSize",
237+
heap_statistics.total_physical_size());
238+
writer->json_keyvalue("totalAvailableSize",
239+
heap_statistics.total_available_size());
240+
writer->json_keyvalue("totalGlobalHandlesSize",
241+
heap_statistics.total_global_handles_size());
242+
writer->json_keyvalue("usedGlobalHandlesSize",
243+
heap_statistics.used_global_handles_size());
244+
writer->json_keyvalue("usedHeapSize", heap_statistics.used_heap_size());
245+
writer->json_keyvalue("heapSizeLimit", heap_statistics.heap_size_limit());
246+
writer->json_keyvalue("mallocedMemory", heap_statistics.malloced_memory());
247+
writer->json_keyvalue("externalMemory", heap_statistics.external_memory());
248+
writer->json_keyvalue("peakMallocedMemory",
249+
heap_statistics.peak_malloced_memory());
250+
writer->json_objectend();
251+
252+
int space_count = isolate->NumberOfHeapSpaces();
253+
writer->json_arraystart("heapSpaceStatistics");
254+
for (int i = 0; i < space_count; i++) {
255+
HeapSpaceStatistics heap_space_statistics;
256+
isolate->GetHeapSpaceStatistics(&heap_space_statistics, i);
257+
writer->json_start();
258+
writer->json_keyvalue("spaceName", heap_space_statistics.space_name());
259+
writer->json_keyvalue("spaceSize", heap_space_statistics.space_size());
260+
writer->json_keyvalue("spaceUsedSize",
261+
heap_space_statistics.space_used_size());
262+
writer->json_keyvalue("spaceAvailableSize",
263+
heap_space_statistics.space_available_size());
264+
writer->json_keyvalue("physicalSpaceSize",
265+
heap_space_statistics.physical_space_size());
266+
writer->json_end();
267+
}
268+
writer->json_arrayend();
269+
}
270+
271+
static void BeforeGCCallback(Isolate* isolate,
272+
v8::GCType gc_type,
273+
v8::GCCallbackFlags flags,
274+
void* data) {
275+
GCProfiler* profiler = static_cast<GCProfiler*>(data);
276+
if (profiler->current_gc_type() != 0) {
277+
return;
278+
}
279+
JSONWriter* writer = profiler->writer();
280+
writer->json_start();
281+
writer->json_keyvalue("gcType", GetGCTypeName(gc_type));
282+
writer->json_objectstart("beforeGC");
283+
SetHeapStatistics(writer, isolate);
284+
writer->json_objectend();
285+
profiler->set_current_gc_type(gc_type);
286+
profiler->set_start_time(uv_hrtime());
287+
}
288+
289+
static void AfterGCCallback(Isolate* isolate,
290+
v8::GCType gc_type,
291+
v8::GCCallbackFlags flags,
292+
void* data) {
293+
GCProfiler* profiler = static_cast<GCProfiler*>(data);
294+
if (profiler->current_gc_type() != gc_type) {
295+
return;
296+
}
297+
JSONWriter* writer = profiler->writer();
298+
profiler->set_current_gc_type(0);
299+
u_int64_t start_time = profiler->start_time();
300+
profiler->set_start_time(0);
301+
writer->json_keyvalue("cost", (uv_hrtime() - start_time) / 1e3);
302+
writer->json_objectstart("afterGC");
303+
SetHeapStatistics(writer, isolate);
304+
writer->json_objectend();
305+
writer->json_end();
306+
}
307+
308+
GCProfiler::GCProfiler(Environment* env, Local<Object> object)
309+
: BaseObject(env, object), writer_(outfile_, false) {
310+
MakeWeak();
311+
}
312+
313+
// This function will be called when
314+
// 1. StartGCProfile and StopGCProfile are called and
315+
// JS land do not keep the object any more.
316+
// 2. StartGCProfile is called then the env exits before
317+
// StopGCProfile is called.
318+
GCProfiler::~GCProfiler() {
319+
if (state_ != GCProfiler::GCProfilerState::kInitialized) {
320+
env()->isolate()->RemoveGCPrologueCallback(BeforeGCCallback, this);
321+
env()->isolate()->RemoveGCEpilogueCallback(AfterGCCallback, this);
322+
}
323+
}
324+
325+
GCProfiler::GCProfilerState GCProfiler::state() {
326+
return state_;
327+
}
328+
329+
void GCProfiler::set_state(GCProfiler::GCProfilerState state) {
330+
state_ = state;
331+
}
332+
333+
u_int64_t GCProfiler::start_time() {
334+
return start_time_;
335+
}
336+
337+
void GCProfiler::set_start_time(u_int64_t time) {
338+
start_time_ = time;
339+
}
340+
341+
u_int8_t GCProfiler::current_gc_type() {
342+
return current_gc_type_;
343+
}
344+
345+
void GCProfiler::set_current_gc_type(u_int8_t type) {
346+
current_gc_type_ = type;
347+
}
348+
349+
JSONWriter* GCProfiler::writer() {
350+
return &writer_;
351+
}
352+
353+
std::ofstream* GCProfiler::outfile() {
354+
return &outfile_;
355+
}
356+
357+
void GCProfiler::New(const FunctionCallbackInfo<Value>& args) {
358+
CHECK(args.IsConstructCall());
359+
Environment* env = Environment::GetCurrent(args);
360+
new GCProfiler(env, args.This());
361+
}
362+
363+
void GCProfiler::StartGCProfile(const FunctionCallbackInfo<Value>& args) {
364+
GCProfiler* profiler;
365+
ASSIGN_OR_RETURN_UNWRAP(&profiler, args.Holder());
366+
if (profiler->state() != GCProfiler::GCProfilerState::kInitialized) {
367+
return;
368+
}
369+
Environment* env = Environment::GetCurrent(args);
370+
Isolate* isolate = args.GetIsolate();
371+
node::Utf8Value filename(env->isolate(), args[0]);
372+
profiler->outfile()->open(*filename, std::ios::out | std::ios::binary);
373+
if (!profiler->outfile()->is_open()) {
374+
env->ThrowError("failed to open file");
375+
return;
376+
}
377+
profiler->writer()->json_start();
378+
profiler->writer()->json_keyvalue("version", 1);
379+
380+
uv_timeval64_t ts;
381+
if (uv_gettimeofday(&ts) == 0) {
382+
profiler->writer()->json_keyvalue("startTime",
383+
ts.tv_sec * 1000 + ts.tv_usec / 1000);
384+
} else {
385+
profiler->writer()->json_keyvalue("startTime", 0);
386+
}
387+
profiler->writer()->json_arraystart("statistics");
388+
isolate->AddGCPrologueCallback(BeforeGCCallback,
389+
static_cast<void*>(profiler));
390+
isolate->AddGCEpilogueCallback(AfterGCCallback, static_cast<void*>(profiler));
391+
profiler->set_state(GCProfiler::GCProfilerState::kStarted);
392+
}
393+
394+
void GCProfiler::StopGCProfile(const FunctionCallbackInfo<v8::Value>& args) {
395+
GCProfiler* profiler;
396+
ASSIGN_OR_RETURN_UNWRAP(&profiler, args.Holder());
397+
if (profiler->state() != GCProfiler::GCProfilerState::kStarted) {
398+
return;
399+
}
400+
profiler->writer()->json_arrayend();
401+
uv_timeval64_t ts;
402+
if (uv_gettimeofday(&ts) == 0) {
403+
profiler->writer()->json_keyvalue("endtTime",
404+
ts.tv_sec * 1000 + ts.tv_usec / 1000);
405+
} else {
406+
profiler->writer()->json_keyvalue("endtTime", 0);
407+
}
408+
profiler->writer()->json_end();
409+
profiler->outfile()->close();
410+
profiler->set_state(GCProfiler::GCProfilerState::kStopped);
411+
}
412+
213413
void Initialize(Local<Object> target,
214414
Local<Value> unused,
215415
Local<Context> context,
@@ -272,6 +472,15 @@ void Initialize(Local<Object> target,
272472

273473
// Export symbols used by v8.setFlagsFromString()
274474
SetMethod(context, target, "setFlagsFromString", SetFlagsFromString);
475+
476+
// GCProfiler
477+
Local<FunctionTemplate> t =
478+
NewFunctionTemplate(env->isolate(), GCProfiler::New);
479+
t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
480+
SetProtoMethod(
481+
env->isolate(), t, "startGCProfile", GCProfiler::StartGCProfile);
482+
SetProtoMethod(env->isolate(), t, "stopGCProfile", GCProfiler::StopGCProfile);
483+
SetConstructorFunction(context, target, "GCProfiler", t);
275484
}
276485

277486
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
@@ -281,6 +490,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
281490
registry->Register(UpdateHeapSpaceStatisticsBuffer);
282491
registry->Register(SetFlagsFromString);
283492
registry->Register(SetHeapSnapshotNearHeapLimit);
493+
registry->Register(GCProfiler::StartGCProfile);
494+
registry->Register(GCProfiler::StopGCProfile);
284495
}
285496

286497
} // namespace v8_utils

0 commit comments

Comments
 (0)