laverdet / isolated-vm

Secure & isolated JS environments for nodejs
ISC License
2.18k stars 154 forks source link

Is there any way to request garbage collector inside an isolate? #478

Closed h0gar closed 5 months ago

laverdet commented 5 months ago

Nope

h0gar commented 5 months ago

Alright, thanks for the quick answer!

h0gar commented 5 months ago

@laverdet Sorry to bother you again. I have another related question. Is it possible somehow to dump the heap snapshot of an isolate? Like we would usually do with v8.writeHeapSnapshot.

In fact I tried to call v8.writeHeapSnapshot from outside the isolate, but the produced snapshot does not contain anything from the isolate.

laverdet commented 5 months ago

You can do this with the inspector API:

async function getHeapSnapshot(isolate) {
    const inspector = isolate.createInspectorSession();
    let snapshot = "";
    inspector.onNotification = payload => {
        const message = JSON.parse(payload);
        if (message.method === "HeapProfiler.addHeapSnapshotChunk") {
            snapshot += message.params.chunk;
        }
    };
    await new Promise(resolve => {
        inspector.onResponse = callId => {
            if (callId === 1) {
                resolve();
            }
        };
        inspector.dispatchProtocolMessage(JSON.stringify({ id: 0, method: "Debugger.enable", params: {} }));
        inspector.dispatchProtocolMessage(JSON.stringify({ id: 1, method: "HeapProfiler.takeHeapSnapshot", params: { captureNumericValue: false, exposeInternals: false } }));
    });
    inspector.dispose();
    return snapshot;
}
h0gar commented 5 months ago

Awesome, thank you!