Skip to content

Commit d8abff2

Browse files
authored
feat(runtime): find the JS/Java cycles canary mode keeps alive (experimental) (#2130)
### Description Fifth of the stacked wrapper-lifetime series (on #2128), and **experimental**: an Android counterpart of NativeScript/ios#576's leak probe. Canary mode keeps the JS ↔ Java cycles resurrection used to break; this finds them. It is a new design rather than a port: iOS counts outside owners with `-retainCount` and walks ObjC ivars, and Java has neither retain counts nor a safe in-process field walk with a known root set. What Java does have is an exact heap dump. #### `ns:runtime` `findLeakCycles()` Each heap has its own collector, so neither sees a cycle that crosses into the other. The probe joins both heaps into one graph and asks what a single collector would keep: - **JS heap:** a V8 heap snapshot, taken before the probe holds any handle to a wrapper or state, after a full V8 collection and a settle, so wrappers that died since the last collection no longer read as holding their Java objects. Its roots exclude the runtime's own handles to canary records and resurrected wrappers (the `(Global handles)` root's edges to those targets), even for records of objects the probe's own Java collection let go of; weak and shortcut edges are skipped. - **Java heap:** an HPROF dump from `android.os.Debug.dumpHprofData`, parsed natively from a memory map (streaming, two passes: records, then fields by class layout). Its GC roots are used as is, except that the runtime's object table (`ObjectTable$Leaf.values`), `Reference.referent`, `FinalizerReference.zombie` and the probe's own pin array are not followed. The objects the runtime knows are pinned in order in `LeakProbe.pinned` so the analysis can find them in the dump. - **The runtime's cross-heap edges:** a live wrapper holds its Java object (canaries always, resurrecting wrappers until they are weakened), a Java object holds its canary record (its state and weak-collection key and, for a JS-extended object, the first canary's prototype, internal fields and implementation object, from the class data the records of one class share, plus the shell copied from its last rebuilt canary while it exists; all listed among the record's values, so none reads as a root), and a Java object held weakly for a resurrected wrapper holds that wrapper. A `WeakMap` value is followed from its key only (V8 also links it from the map's table, which would hide every cycle through a WeakMap value). Java is collected twice before the dump, so objects only weak entries hold are gone. A Java object the runtime holds for a live wrapper, and that nothing else reaches, is leaked: a unified collector would free it. For each, the report gives the shortest path from the Java object to its own wrapper through Java fields, JS properties and the runtime's edges, closed by the wrapper → Java edge; a `signature` (the path's node labels from their smallest rotation, with V8's `@id` suffixes stripped); and the leaked classes on it (`members`). `leakedOutsideCycles` counts leaked objects on no reported cycle: held by one, or past the search limits (`truncated`: after 256 searches, or a search that visited 2,000,000 nodes). In `"resurrecting"` the report is empty and no dump is taken: resurrection breaks these cycles. Under `canary`/`extended` every plain wrapper is a canary too (#2127), so a cycle through a plain wrapper, which resurrection used to break in that scope, is now reported as a leak there, as under `"all"` (documented). Report fields: `mode`, `cycles`, `leaked`, `leakedOutsideCycles`, `truncated`, `probed`, `jsNodes`, `javaObjects`, `dumpBytes`, `durationMs`. #### Cost Slow by design and on demand only: the dump suspends the process, is written to the app's cache directory (deleted once parsed; a dump a killed process left is swept by the next probe), and both heaps are graphed in native memory. On the test app (arm64 emulator): a 44 MB dump, about 3 s per call. **Debug builds only, like iOS's debug-only framework:** `LeakProbe.cpp` and the accessor it reads compile only into debug runtimes (`APPLICATION_IN_DEBUG`, the `optimized-with-inspector` AAR). The Java side (`LeakProbe.java`) lives in a `src/debugTools/java` source set every runtime but `optimized` builds, so the release AAR carries none of it, Java or native, but keeps `findLeakCycles` in `ns:runtime`, which throws "available in debug builds only". Unlike iOS there is no way to ship it in a release build. Probes in several runtimes run one at a time. The V8 object ids the snapshot assigns are cleared afterwards unless DevTools is connected (a snapshot otherwise leaves V8 tracking object moves on every scavenge). #### What it found Run on the test app under `canary`/`all`, after the suite's own specs had run, it reported, besides the shapes the new spec plants: - `MyButton9` (a TypeScript `Button` subclass from `testsForTypescript.js`) ↔ its `View.OnClickListener` implementation, whose `onClick` closure captures the button: the listener cycle canary mode keeps (two instances); - several `Runnable`/`Predicate` implementations whose `run`/`test` closure captures the implementation itself. Example path for the planted list cycle: `com.tns.gen.java.lang.Runnable --ns:kept--> JS Object --probeList--> JS java.util.ArrayList --ns:wrapper--> java.util.ArrayList --java.util.ArrayList.elementData--> java.lang.Object[] --[]--> com.tns.gen.java.lang.Runnable`. #### Blind spots - JNI global references the app or a plugin holds are GC roots, so cycles through them read as legitimately held, not leaked (missed, not misreported). - The V8 snapshot and the Java dump are taken one after the other, not atomically; a reference that moves between them can hide or invent a path. - Only the calling runtime's wrappers are modeled: an object held only through a worker's wrappers can read as leaked. - Runtime handles are excluded by target, so a record value a real root also reaches counts as reached (correctly), and one reached only through the runtime's handles does not. ### Testing - New `testWrapperLifetimeLeaks.js` (one probe for the whole suite, on a later task than the planting, since a `WeakRef` keeps its target alive until its job ends): an object whose JS state references it (two, with equal signatures), a cycle through a Java `ArrayList`, an object held by a Java static (not reported), a back reference through a `WeakRef` (not reported), a `WeakMap` value referencing its key (reported through `WeakMap value`), a `Runnable` whose `run` closes over the object itself (`probeClosed`: the cycle runs through the record's prototype handle, its implementation object, reported with `ns:kept` and `ns:wrapper` edges), a cycle through a Java list whose canary was rebuilt before the probe (`probeRebuiltList`: a shell read as a root would hide it), and the report's fields; in `"resurrecting"` no cycle is reported. Each cycle's signature is logged. - Release packaging: in the `optimized` AAR's `libNativeScript.so` none of the probe's strings are present and the stub's message is; the `optimized-with-inspector` AAR has the probe. - An independent review pass (second commit) fixed: V8 left tracking object moves after the snapshot; cycles through WeakMap values hidden by the table's edge; GC-timing-dependent counts; no gating (now debug builds only); concurrent probes sharing the pin array; no early return outside canary mode; uncapped cycle searches; C++ exceptions not caught; a malformed string record. - Full suite on an arm64 emulator, on this branch (on `main` at a59e6ba): 0 failures in each of `resurrecting`/`extended` (1909 specs), `canary`/`extended` and `canary`/`all` (1907 each). The probe itself, measured before the latest rebase onto #2128 and not re-measured since: about 3 s on a 44 MB dump per run; nothing in `"resurrecting"` and 16 leaked objects in 15 cycles in canary mode. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added a debug-build diagnostic that analyzes JavaScript and Java heap data to identify possible leak cycles, including cycle paths and report metrics. * The diagnostic may pause the app while collecting and analyzing a full heap dump. Cycle searches are limited, and reports indicate when results are truncated. The diagnostic is unavailable in release builds. * **Documentation** * Documented the diagnostic’s availability, report details, search limits, and runtime caveats. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 14f065d commit d8abff2

14 files changed

Lines changed: 1513 additions & 4 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ wrapper.
105105
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
106106
| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. |
107107
| `getWrapperClassCounts()` | Per Java class name (`<unknown>` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
108+
| `findLeakCycles()` | Experimental and slow, debug builds only (release builds throw): joins a V8 heap snapshot and a Java heap dump to find the JS ↔ Java cycles canary mode keeps alive (see [Wrapper lifetime](#wrapper-lifetime)). |
108109
| `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). |
109110

110111
*Platform note (Android):* the original exception is the Java throwable `x`
@@ -274,6 +275,42 @@ object's state with its link, and the released canary is a plain JS object
274275
from then on: what the weak collections keyed on its Java object stays keyed
275276
on it, and lives as long as it does.
276277

278+
**Finding leaked cycles (experimental).** Each heap has its own collector,
279+
so neither sees a cycle that crosses into the other. `findLeakCycles()` joins
280+
them into one graph and asks what a single collector would keep: the JS heap
281+
from a V8 heap snapshot (its roots minus the runtime's handles to canary
282+
records), the Java heap from an HPROF dump (`android.os.Debug.dumpHprofData`;
283+
its GC roots minus the runtime's object table, `Reference` referents skipped),
284+
and the runtime's own edges between them (a live wrapper holds its Java object;
285+
a Java object holds its canary record: state, weak-collection key, prototype
286+
and implementation object; a Java object held weakly for a resurrected wrapper holds that wrapper). A `WeakMap` value is followed from its key only. A Java object the
287+
runtime holds for a live wrapper, and that nothing else reaches, is leaked. For each, the report gives the path from the Java
288+
object to its own wrapper through fields, properties and the runtime's edges,
289+
a `signature` (the path's node labels from their smallest rotation, free of
290+
ids), and the Java classes of the leaked objects on it (`members`).
291+
`leakedOutsideCycles` counts leaked objects on no reported cycle: held by one,
292+
or past the search limits (`truncated`: after 256 searches, or a search that
293+
visited 2,000,000 nodes). V8 collects and the runtime settles the wrappers that
294+
died before the snapshot, and Java is collected twice before the dump, so
295+
objects only weak entries hold are gone and not counted. The report also gives
296+
`mode`, `probed` (the Java objects modeled), `jsNodes`, `javaObjects`,
297+
`dumpBytes` and `durationMs`. In `"resurrecting"` mode the report is empty and no dump is taken:
298+
resurrection breaks these cycles. Under `"canary"` every wrapper is a canary
299+
in either scope, so under `"extended"` too a cycle through a plain wrapper,
300+
which resurrection used to break, is reported as a leak.
301+
302+
The probe is built into debug runtimes only; in a release build the function
303+
exists but throws `findLeakCycles is available in debug builds only`. It suspends the whole process for the dump, writes the Java heap to
304+
the app's cache directory (deleted once parsed, and swept by the next probe if
305+
the process died first) and builds graphs of both heaps in native memory, so
306+
it takes seconds; on the main thread that can trip an ANR. The snapshot and
307+
the dump are taken one after the other, not atomically. Only the calling
308+
runtime's wrappers are modeled: an object held only through another runtime's
309+
(a worker's) wrappers can read as leaked, and probes in several runtimes run
310+
one at a time. Cycles through JNI global references native code holds are
311+
missed, since those are roots. The V8 object ids the snapshot assigns are
312+
cleared afterwards, unless DevTools is connected and relies on them.
313+
277314
**Weak collections.** What could notice a new canary is whatever keys on the
278315
old one without keeping it, so in canary mode a builtin
279316
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ require("./tests/testWrapperLifetimeStateWrites");
6666
require("./tests/testWrapperLifetimeFieldWrites");
6767
require("./tests/testWrapperLifetimeRecordSharing");
6868
require("./tests/testWrapperLifetimeWeakCollections");
69+
require("./tests/testWrapperLifetimeLeaks");
6970
require("./tests/testsMemoryManagement");
7071
require("./tests/testFieldGetSet");
7172
require("./tests/extendedClassesTests");

‎test-app/app/src/main/assets/app/tests/testNsRuntime.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ describe("ns:runtime", function () {
1111
// The export set is public API, declared alongside docs/ns-builtin-modules.md
1212
// — all of them change together.
1313
it("exposes exactly the declared surface", function () {
14-
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
14+
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "findLeakCycles", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
1515
});
1616

1717
it("rejects unknown keys", function () {
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
describe("Wrapper lifetime leak probe", function () {
2+
var runtime = require("ns:runtime");
3+
var mode = runtime.getConfig("wrapperLifetimeMode");
4+
var canary = mode === "canary";
5+
var Holder = com.tns.tests.WrapperHolder;
6+
// WeakRefs, so the spec itself keeps nothing it planted alive.
7+
var planted = [];
8+
// Alive for the whole suite: what leaks is the entry's value.
9+
var probeMap = new WeakMap();
10+
var report;
11+
var canaryRebuilds;
12+
13+
function cyclesThrough(edge) {
14+
return report.cycles.filter(function (cycle) {
15+
return cycle.path.indexOf("--" + edge + "-->") !== -1;
16+
});
17+
}
18+
19+
// Each probe dumps the Java heap, so every shape is planted once and probed once, on a
20+
// later task: a WeakRef keeps its target alive until the job that made it ends.
21+
beforeAll(function (done) {
22+
// A cycle through Java whose object's canary was rebuilt since: the record also
23+
// keeps a copy of the rebuilt canary, which must not read as a root.
24+
(function () {
25+
var rebuilt = new java.lang.Runnable({ run: function () {} });
26+
var list = new java.util.ArrayList();
27+
list.add(rebuilt);
28+
rebuilt.probeRebuiltList = list;
29+
planted.push(new WeakRef(rebuilt));
30+
Holder.held = list;
31+
})();
32+
// The canary dies on a later job: a WeakRef keeps its target until the job ends.
33+
setTimeout(function () {
34+
gc();
35+
java.lang.System.nanoTime();
36+
java.lang.Runtime.getRuntime().gc();
37+
gc();
38+
java.lang.System.nanoTime();
39+
var rebuildsBefore = runtime.getWrapperLifetimeStats().canaryRebuilds;
40+
(function () {
41+
// A read: the rebuilt canary's copy stays current.
42+
Holder.held.get(0).probeRebuiltList.size();
43+
})();
44+
canaryRebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds - rebuildsBefore;
45+
Holder.held = null;
46+
(function () {
47+
// A JS property referencing its own object.
48+
var selfReferencing = new java.lang.Runnable({ run: function () {} });
49+
selfReferencing.probeSelf = selfReferencing;
50+
planted.push(new WeakRef(selfReferencing));
51+
52+
var twin = new java.lang.Runnable({ run: function () {} });
53+
twin.probeSelf = twin;
54+
planted.push(new WeakRef(twin));
55+
56+
// A cycle through Java: the object's state holds a list that holds the object.
57+
var listed = new java.lang.Runnable({ run: function () {} });
58+
var list = new java.util.ArrayList();
59+
list.add(listed);
60+
listed.probeList = list;
61+
planted.push(new WeakRef(listed));
62+
63+
// Held by a Java static: alive for a reason of its own, not a leak.
64+
var held = new java.lang.Runnable({ run: function () {} });
65+
held.probeHeld = held;
66+
Holder.held = held;
67+
planted.push(new WeakRef(held));
68+
69+
// A WeakMap value referencing its own key: in canary mode the key is the
70+
// object's lifetime key, which its record holds.
71+
var mapped = new java.lang.Runnable({ run: function () {} });
72+
probeMap.set(mapped, { probeMapped: mapped });
73+
planted.push(new WeakRef(mapped));
74+
75+
// A back reference through a WeakRef keeps nothing.
76+
var weak = new java.lang.Runnable({ run: function () {} });
77+
weak.probeWeak = new WeakRef(weak);
78+
})();
79+
(function () {
80+
// A method closing over its own object: the cycle runs through the object's
81+
// prototype, its implementation object. In a function of its own, so no other
82+
// planted closure shares the context that holds it.
83+
var probeClosed = new java.lang.Runnable({
84+
run: function () {
85+
return probeClosed;
86+
}
87+
});
88+
planted.push(new WeakRef(probeClosed));
89+
})();
90+
setTimeout(function () {
91+
report = runtime.findLeakCycles();
92+
console.log("leak probe: " + JSON.stringify({
93+
leaked: report.leaked,
94+
leakedOutsideCycles: report.leakedOutsideCycles,
95+
probed: report.probed,
96+
cycles: report.cycles.length,
97+
durationMs: report.durationMs,
98+
dumpBytes: report.dumpBytes
99+
}));
100+
report.cycles.forEach(function (cycle) {
101+
console.log("leak probe cycle: " + cycle.signature);
102+
});
103+
done();
104+
}, 0);
105+
}, 0);
106+
}, 20000);
107+
108+
afterAll(function () {
109+
Holder.held = null;
110+
planted.forEach(function (ref) {
111+
var object = ref.deref();
112+
if (object !== undefined) {
113+
__releaseNativeCounterpart(object);
114+
}
115+
});
116+
planted = [];
117+
report = null;
118+
});
119+
120+
it("reports the heaps it joined (" + mode + ")", function () {
121+
expect(report.mode).toBe(mode);
122+
expect(Array.isArray(report.cycles)).toBe(true);
123+
if (!canary) {
124+
// Nothing to look for: no dump is taken.
125+
expect(report.leaked).toBe(0);
126+
expect(report.javaObjects).toBeUndefined();
127+
return;
128+
}
129+
expect(report.javaObjects).toBeGreaterThan(0);
130+
expect(report.jsNodes).toBeGreaterThan(0);
131+
expect(report.probed).toBeGreaterThan(0);
132+
expect(report.truncated).toBe(false);
133+
expect(report.durationMs).toBeGreaterThan(0);
134+
});
135+
136+
it("finds an object whose JS state references it", function () {
137+
var cycles = cyclesThrough("probeSelf");
138+
if (!canary) {
139+
// Resurrection breaks it: nothing keeps the object once JS lets go.
140+
expect(cycles.length).toBe(0);
141+
return;
142+
}
143+
expect(cycles.length).toBe(2);
144+
expect(cycles[0].path).toContain("--ns:kept-->");
145+
expect(cycles[0].path).toContain("--ns:wrapper-->");
146+
expect(cycles[0].members.length).toBe(1);
147+
});
148+
149+
it("gives the same shape the same signature, free of ids", function () {
150+
if (!canary) {
151+
return;
152+
}
153+
var cycles = cyclesThrough("probeSelf");
154+
expect(cycles[0].signature).toBe(cycles[1].signature);
155+
});
156+
157+
it("finds a cycle through a Java collection", function () {
158+
var cycles = cyclesThrough("probeList");
159+
if (!canary) {
160+
expect(cycles.length).toBe(0);
161+
return;
162+
}
163+
expect(cycles.length).toBe(1);
164+
expect(cycles[0].path).toContain("--java.util.ArrayList.elementData-->");
165+
});
166+
167+
it("finds a cycle through a WeakMap value that references its key", function () {
168+
var cycles = cyclesThrough("probeMapped");
169+
if (!canary) {
170+
expect(cycles.length).toBe(0);
171+
return;
172+
}
173+
expect(cycles.length).toBe(1);
174+
expect(cycles[0].path).toContain("--WeakMap value-->");
175+
});
176+
177+
it("finds a cycle through a method that closes over its object", function () {
178+
var cycles = cyclesThrough("probeClosed");
179+
if (!canary) {
180+
expect(cycles.length).toBe(0);
181+
return;
182+
}
183+
expect(cycles.length).toBe(1);
184+
expect(cycles[0].path).toContain("--ns:kept-->");
185+
expect(cycles[0].path).toContain("--ns:wrapper-->");
186+
});
187+
188+
it("finds a cycle through Java after the object's canary was rebuilt", function () {
189+
var cycles = cyclesThrough("probeRebuiltList");
190+
if (!canary) {
191+
expect(cycles.length).toBe(0);
192+
return;
193+
}
194+
expect(canaryRebuilds).toBeGreaterThan(0);
195+
expect(cycles.length).toBe(1);
196+
});
197+
198+
it("does not report an object Java holds for a reason of its own", function () {
199+
expect(cyclesThrough("probeHeld").length).toBe(0);
200+
});
201+
202+
it("does not report a back reference through a WeakRef", function () {
203+
expect(cyclesThrough("probeWeak").length).toBe(0);
204+
});
205+
206+
it("settles the wrappers that died since the last collection first", function () {
207+
if (!canary) {
208+
return;
209+
}
210+
(function () {
211+
for (var i = 0; i < 50; i++) {
212+
new java.lang.StringBuilder("probeGarbage");
213+
}
214+
})();
215+
// Read as leaked if unsettled: their Java objects are still held for them.
216+
expect(runtime.findLeakCycles().leaked).toBeLessThanOrEqual(report.leaked);
217+
}, 20000);
218+
});

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,17 @@ if (NOT OPTIMIZED_BUILD OR OPTIMIZED_WITH_INSPECTOR_BUILD)
151151
src/main/cpp/v8_inspector/ns-v8-tracing-agent-impl.cpp
152152
src/main/cpp/v8_inspector/Utils.cpp
153153
)
154+
155+
# ns:runtime findLeakCycles(); release builds keep a stub that throws.
156+
set(
157+
DEBUG_TOOL_SOURCES
158+
159+
src/main/cpp/LeakProbe.cpp
160+
)
154161
else ()
155162
# When building in Release mode we do not include the V8 inspector sources
156163
set(INSPECTOR_SOURCES)
164+
set(DEBUG_TOOL_SOURCES)
157165
endif ()
158166

159167
# The Node-API test addons back the NapiTests/NapiCoverageTests specs of the
@@ -269,6 +277,7 @@ add_library(
269277

270278
# V8 inspector source files will be included only in Release mode
271279
${INSPECTOR_SOURCES}
280+
${DEBUG_TOOL_SOURCES}
272281

273282
# Node-API test addons, local Debug builds only
274283
${NAPI_TEST_SOURCES}

‎test-app/runtime/build.gradle‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ android {
9999

100100
// embed runtime binding generator in runtime, while keeping it in a separate project
101101
java.srcDirs = [bindingGeneratorSourcePath, defaultSrcPath]
102+
// The Java side of debug-only native tools (CMake's DEBUG_TOOL_SOURCES).
103+
if (!optimized || optimizedWithInspector) {
104+
java.srcDirs += "src/debugTools/java"
105+
}
102106
}
103107
}
104108

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.tns;
2+
3+
import java.io.File;
4+
5+
/**
6+
* ns:runtime findLeakCycles()'s Java side, in debug runtimes only. During the heap dump,
7+
* {@link #pinned} holds the Java objects the analysis maps to JS wrappers and states; the
8+
* analysis finds that array through this static field by name and does not count it as a
9+
* reference.
10+
*/
11+
final class LeakProbe {
12+
static final String DUMP_PREFIX = "ns-leak-probe";
13+
14+
// Older than any dump a probe of this process or another one may still be parsing.
15+
private static final long STALE_DUMP_AGE_MS = 10 * 60 * 1000;
16+
17+
static Object[] pinned;
18+
19+
private LeakProbe() {
20+
}
21+
22+
// Before the probe takes strong references: objects only weak entries hold would
23+
// otherwise read as leaked until Java collects them.
24+
static void collectGarbage() {
25+
for (int i = 0; i < 2; i++) {
26+
java.lang.Runtime.getRuntime().gc();
27+
}
28+
}
29+
30+
// Writes an HPROF dump with objects pinned in order; returns its path, or null if it
31+
// could not be written. The caller deletes the dump once parsed.
32+
static String dump(Object[] objects) {
33+
// pinned is shared by every runtime of the process.
34+
synchronized (LeakProbe.class) {
35+
deleteStaleDumps();
36+
File file = null;
37+
try {
38+
file = File.createTempFile(DUMP_PREFIX, ".hprof");
39+
pinned = objects;
40+
android.os.Debug.dumpHprofData(file.getAbsolutePath());
41+
return file.getAbsolutePath();
42+
} catch (Throwable t) {
43+
android.util.Log.w("JS", "findLeakCycles could not dump the Java heap", t);
44+
if (file != null) {
45+
file.delete();
46+
}
47+
return null;
48+
} finally {
49+
pinned = null;
50+
}
51+
}
52+
}
53+
54+
// Dumps a killed process left behind.
55+
private static void deleteStaleDumps() {
56+
String tmp = System.getProperty("java.io.tmpdir");
57+
File[] files = tmp != null ? new File(tmp).listFiles() : null;
58+
if (files == null) {
59+
return;
60+
}
61+
long staleBefore = System.currentTimeMillis() - STALE_DUMP_AGE_MS;
62+
for (File file : files) {
63+
String name = file.getName();
64+
if (name.startsWith(DUMP_PREFIX) && name.endsWith(".hprof")
65+
&& file.lastModified() < staleBefore) {
66+
file.delete();
67+
}
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)