Skip to content

Commit e57ab16

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

8 files changed

+422
-2
lines changed

doc/api/v8.md

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

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

lib/v8.js

+22-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, JSONParse } = primordials;
6768
/**
6869
* Generates a snapshot of the current V8 heap
6970
* and writes it to a JSON file.
@@ -397,6 +398,24 @@ function deserialize(buffer) {
397398
return der.readValue();
398399
}
399400

401+
/**
402+
* @param {{
403+
* duration: number,
404+
* }} [options]
405+
*/
406+
function collectGCProfile(options) {
407+
validateObject(options, 'options');
408+
validateNumber(options.duration, 'options.duration', 1);
409+
return new Promise((resolve) => {
410+
const profiler = new binding.GCProfiler();
411+
profiler.start();
412+
setUnrefTimeout(() => {
413+
const data = profiler.stop();
414+
resolve(JSONParse(data));
415+
}, options.duration);
416+
});
417+
}
418+
400419
module.exports = {
401420
cachedDataVersionTag,
402421
getHeapSnapshot,
@@ -416,4 +435,5 @@ module.exports = {
416435
promiseHooks,
417436
startupSnapshot,
418437
setHeapSnapshotNearHeapLimit,
438+
collectGCProfile,
419439
};

src/node_v8.cc

+186
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,181 @@ 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 "UnKnown";
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->current_gc_type = gc_type;
286+
profiler->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->current_gc_type = 0;
299+
writer->json_keyvalue("cost", (uv_hrtime() - profiler->start_time) / 1e3);
300+
profiler->start_time = 0;
301+
writer->json_objectstart("afterGC");
302+
SetHeapStatistics(writer, isolate);
303+
writer->json_objectend();
304+
writer->json_end();
305+
}
306+
307+
GCProfiler::GCProfiler(Environment* env, Local<Object> object)
308+
: BaseObject(env, object),
309+
start_time(0),
310+
current_gc_type(0),
311+
state(GCProfilerState::kInitialized),
312+
writer_(out_stream_, false) {
313+
MakeWeak();
314+
}
315+
316+
// This function will be called when
317+
// 1. StartGCProfile and StopGCProfile are called and
318+
// JS land do not keep the object any more.
319+
// 2. StartGCProfile is called then the env exits before
320+
// StopGCProfile is called.
321+
GCProfiler::~GCProfiler() {
322+
if (state != GCProfiler::GCProfilerState::kInitialized) {
323+
env()->isolate()->RemoveGCPrologueCallback(BeforeGCCallback, this);
324+
env()->isolate()->RemoveGCEpilogueCallback(AfterGCCallback, this);
325+
}
326+
}
327+
328+
JSONWriter* GCProfiler::writer() {
329+
return &writer_;
330+
}
331+
332+
std::ostringstream* GCProfiler::out_stream() {
333+
return &out_stream_;
334+
}
335+
336+
void GCProfiler::New(const FunctionCallbackInfo<Value>& args) {
337+
CHECK(args.IsConstructCall());
338+
Environment* env = Environment::GetCurrent(args);
339+
new GCProfiler(env, args.This());
340+
}
341+
342+
void GCProfiler::Start(const FunctionCallbackInfo<Value>& args) {
343+
Environment* env = Environment::GetCurrent(args);
344+
GCProfiler* profiler;
345+
ASSIGN_OR_RETURN_UNWRAP(&profiler, args.Holder());
346+
if (profiler->state != GCProfiler::GCProfilerState::kInitialized) {
347+
return;
348+
}
349+
profiler->writer()->json_start();
350+
profiler->writer()->json_keyvalue("version", 1);
351+
352+
uv_timeval64_t ts;
353+
if (uv_gettimeofday(&ts) == 0) {
354+
profiler->writer()->json_keyvalue("startTime",
355+
ts.tv_sec * 1000 + ts.tv_usec / 1000);
356+
} else {
357+
profiler->writer()->json_keyvalue("startTime", 0);
358+
}
359+
profiler->writer()->json_arraystart("statistics");
360+
env->isolate()->AddGCPrologueCallback(BeforeGCCallback,
361+
static_cast<void*>(profiler));
362+
env->isolate()->AddGCEpilogueCallback(AfterGCCallback,
363+
static_cast<void*>(profiler));
364+
profiler->state = GCProfiler::GCProfilerState::kStarted;
365+
}
366+
367+
void GCProfiler::Stop(const FunctionCallbackInfo<v8::Value>& args) {
368+
Environment* env = Environment::GetCurrent(args);
369+
GCProfiler* profiler;
370+
ASSIGN_OR_RETURN_UNWRAP(&profiler, args.Holder());
371+
if (profiler->state != GCProfiler::GCProfilerState::kStarted) {
372+
return;
373+
}
374+
profiler->writer()->json_arrayend();
375+
uv_timeval64_t ts;
376+
if (uv_gettimeofday(&ts) == 0) {
377+
profiler->writer()->json_keyvalue("endtTime",
378+
ts.tv_sec * 1000 + ts.tv_usec / 1000);
379+
} else {
380+
profiler->writer()->json_keyvalue("endtTime", 0);
381+
}
382+
profiler->writer()->json_end();
383+
profiler->state = GCProfiler::GCProfilerState::kStopped;
384+
args.GetReturnValue().Set(
385+
String::NewFromUtf8(env->isolate(), profiler->out_stream()->str().c_str())
386+
.ToLocalChecked());
387+
}
388+
213389
void Initialize(Local<Object> target,
214390
Local<Value> unused,
215391
Local<Context> context,
@@ -272,6 +448,14 @@ void Initialize(Local<Object> target,
272448

273449
// Export symbols used by v8.setFlagsFromString()
274450
SetMethod(context, target, "setFlagsFromString", SetFlagsFromString);
451+
452+
// GCProfiler
453+
Local<FunctionTemplate> t =
454+
NewFunctionTemplate(env->isolate(), GCProfiler::New);
455+
t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
456+
SetProtoMethod(env->isolate(), t, "start", GCProfiler::Start);
457+
SetProtoMethod(env->isolate(), t, "stop", GCProfiler::Stop);
458+
SetConstructorFunction(context, target, "GCProfiler", t);
275459
}
276460

277461
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
@@ -281,6 +465,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
281465
registry->Register(UpdateHeapSpaceStatisticsBuffer);
282466
registry->Register(SetFlagsFromString);
283467
registry->Register(SetHeapSnapshotNearHeapLimit);
468+
registry->Register(GCProfiler::Start);
469+
registry->Register(GCProfiler::Stop);
284470
}
285471

286472
} // namespace v8_utils

src/node_v8.h

+28
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33

44
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
55

6+
#include <sstream>
67
#include "aliased_buffer.h"
78
#include "base_object.h"
9+
#include "json_utils.h"
810
#include "node_snapshotable.h"
911
#include "util.h"
1012
#include "v8.h"
@@ -34,6 +36,32 @@ class BindingData : public SnapshotableObject {
3436
SET_MEMORY_INFO_NAME(BindingData)
3537
};
3638

39+
class GCProfiler : public BaseObject {
40+
public:
41+
enum class GCProfilerState { kInitialized, kStarted, kStopped };
42+
GCProfiler(Environment* env, v8::Local<v8::Object> object);
43+
inline ~GCProfiler() override;
44+
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
45+
static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);
46+
static void Stop(const v8::FunctionCallbackInfo<v8::Value>& args);
47+
48+
JSONWriter* writer();
49+
50+
std::ostringstream* out_stream();
51+
52+
SET_NO_MEMORY_INFO()
53+
SET_MEMORY_INFO_NAME(GCProfiler)
54+
SET_SELF_SIZE(GCProfiler)
55+
56+
u_int64_t start_time;
57+
u_int8_t current_gc_type;
58+
GCProfilerState state;
59+
60+
private:
61+
std::ostringstream out_stream_;
62+
JSONWriter writer_;
63+
};
64+
3765
} // namespace v8_utils
3866

3967
} // namespace node

0 commit comments

Comments
 (0)