調查記憶體外洩
如果您正在調查記憶體外洩,並且想知道為何物件未被垃圾回收,可以使用 %DebugTrackRetainingPath(object)
在每個 GC 上列印物件的實際保留路徑。
這需要 --allow-natives-syntax --track-retaining-path
執行時間旗標,且在發行和偵錯模式中都能運作。在 CL 說明中取得更多資訊。
考慮以下 test.js
function foo() {
const x = { bar: 'bar' };
%DebugTrackRetainingPath(x);
return () => { return x; }
}
const closure = foo();
gc();
範例(使用偵錯模式或 v8_enable_object_print = true
以取得更詳細的輸出)
$ out/x64.release/d8 --allow-natives-syntax --track-retaining-path --expose-gc test.js
#################################################
Retaining path for 0x245c59f0c1a1:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 6: 0x245c59f0c1a1 <Object map = 0x2d919f0d729>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 5: 0x245c59f0c169 <FixedArray[5]>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 4: 0x245c59f0c219 <JSFunction (sfi = 0x1fbb02e2d7f1)>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 3: 0x1fbb02e2d679 <FixedArray[5]>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 2: 0x245c59f0c139 <FixedArray[4]>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Distance from root 1: 0x1fbb02e03d91 <FixedArray[279]>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Root: (Isolate)
-------------------------------------------------
偵錯器支援 #
在偵錯器工作階段(例如 gdb
/lldb
)中,假設您已將上述旗標傳遞給程序(即 --allow-natives-syntax --track-retaining-path
),您可能可以在感興趣的物件上 print isolate->heap()->PrintRetainingPath(HeapObject*)
。