Skip to content

Commit eae3ee3

Browse files
committed
src: implement countObjectsWithPrototype
This implements an internal utility for counting objects in the heap with a specified prototype. In addition this adds a checkIfCollectableByCounting() test helper.
1 parent c87af16 commit eae3ee3

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

src/heap_utils.cc

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ using v8::Number;
3838
using v8::Object;
3939
using v8::ObjectTemplate;
4040
using v8::String;
41+
using v8::Symbol;
42+
using v8::TryCatch;
4143
using v8::Uint8Array;
4244
using v8::Value;
4345

@@ -474,6 +476,40 @@ void TriggerHeapSnapshot(const FunctionCallbackInfo<Value>& args) {
474476
return args.GetReturnValue().Set(filename_v);
475477
}
476478

479+
class PrototypeChainHas : public v8::QueryObjectPredicate {
480+
public:
481+
PrototypeChainHas(Local<Context> context, Local<Object> search)
482+
: context_(context),
483+
search_(search) {}
484+
485+
// What we can do in the filter can be quite limited, but looking up
486+
// the prototype chain is something that the inspector console API
487+
// queryObject() does so it is supported.
488+
bool Filter(Local<Object> object) override {
489+
for (Local<Value> proto = object->GetPrototype(); proto->IsObject();
490+
proto = proto.As<Object>()->GetPrototype()) {
491+
if (search_ == proto) return true;
492+
}
493+
return false;
494+
}
495+
496+
private:
497+
Local<Context> context_;
498+
Local<Object> search_;
499+
};
500+
501+
void CountObjectsWithPrototype(const FunctionCallbackInfo<Value>& args) {
502+
CHECK_EQ(args.Length(), 1);
503+
CHECK(args[0]->IsObject());
504+
Local<Object> proto = args[0].As<Object>();
505+
Isolate* isolate = args.GetIsolate();
506+
Local<Context> context = isolate->GetCurrentContext();
507+
PrototypeChainHas prototype_chain_has(context, proto);
508+
std::vector<Global<Object>> out;
509+
isolate->GetHeapProfiler()->QueryObjects(context, &prototype_chain_has, &out);
510+
args.GetReturnValue().Set(static_cast<uint32_t>(out.size()));
511+
}
512+
477513
void Initialize(Local<Object> target,
478514
Local<Value> unused,
479515
Local<Context> context,
@@ -482,12 +518,15 @@ void Initialize(Local<Object> target,
482518
SetMethod(context, target, "triggerHeapSnapshot", TriggerHeapSnapshot);
483519
SetMethod(
484520
context, target, "createHeapSnapshotStream", CreateHeapSnapshotStream);
521+
SetMethod(
522+
context, target, "countObjectsWithPrototype", CountObjectsWithPrototype);
485523
}
486524

487525
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
488526
registry->Register(BuildEmbedderGraph);
489527
registry->Register(TriggerHeapSnapshot);
490528
registry->Register(CreateHeapSnapshotStream);
529+
registry->Register(CountObjectsWithPrototype);
491530
}
492531

493532
} // namespace heap

test/common/gc.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,54 @@ async function runAndBreathe(fn, repeat, waitTime = 20) {
7575
}
7676
}
7777

78+
/**
79+
* This requires --expose-internals.
80+
* This function can be used to check if an object factory leaks or not by
81+
* iterating over the heap and count objects with the specified class
82+
* (which is checked by looking up the prototype chain).
83+
* @param {(i: number) => number} fn The factory receiving iteration count
84+
* and returning number of objects created. The return value should be
85+
* precise otherwise false negatives can be produced.
86+
* @param {Function} klass The class whose object is used to count the objects
87+
* @param {number} count Number of iterations that this check should be done
88+
* @param {number} waitTime Optional breathing time for GC.
89+
*/
90+
async function checkIfCollectableByCounting(fn, klass, count, waitTime = 20) {
91+
const { internalBinding } = require('internal/test/binding');
92+
const { countObjectsWithPrototype } = internalBinding('heap_utils');
93+
const { prototype, name } = klass;
94+
const initialCount = countObjectsWithPrototype(prototype);
95+
console.log(`Initial count of ${name}: ${initialCount}`);
96+
let totalCreated = 0;
97+
for (let i = 0; i < count; ++i) {
98+
const created = await fn(i);
99+
totalCreated += created;
100+
console.log(`#${i}: created ${created} ${name}, total ${totalCreated}`);
101+
await wait(waitTime); // give GC some breathing room.
102+
const currentCount = countObjectsWithPrototype(prototype);
103+
const collected = totalCreated - (currentCount - initialCount);
104+
console.log(`#${i}: counted ${currentCount} ${name}, collected ${collected}`);
105+
if (collected > 0) {
106+
console.log(`Detected ${collected} collected ${name}, finish early`);
107+
return;
108+
}
109+
}
110+
111+
await wait(waitTime); // give GC some breathing room.
112+
const currentCount = countObjectsWithPrototype(prototype);
113+
const collected = totalCreated - (currentCount - initialCount);
114+
console.log(`Last count: counted ${currentCount} ${name}, collected ${collected}`);
115+
// Some objects with the prototype can be collected.
116+
if (collected > 0) {
117+
console.log(`Detected ${collected} collected ${name}`);
118+
return;
119+
}
120+
121+
throw new Error(`${name} cannot be collected`);
122+
}
123+
78124
module.exports = {
79125
checkIfCollectable,
80126
runAndBreathe,
127+
checkIfCollectableByCounting,
81128
};

0 commit comments

Comments
 (0)