Skip to content

Commit 761ff4c

Browse files
committed
fix(runtime): leak probe review fixes
- Settle before the snapshot (a full V8 collection and a flush), so wrappers that died since the last collection no longer read as holding their Java objects, and a queued wrapper never does. - Model the Java object a resurrected wrapper lives for: an edge from it to the wrapper, whose handle is not a root. - Keep the runtime's handles out of the roots even for records of objects the probe's own Java collection let go of. - Only "(Global handles)" edges to the runtime's handles are dropped. - No System.runFinalization() on the JS thread: a finalizer reaching JS would wait on it. - Keep V8 object ids while DevTools is connected. - Move the Java side to a debugTools source set the optimized runtime does not get; the native side builds the pinned array itself. - Delete only stale dumps, report a search cut short as truncated, scope edge-name handles, and fix two HPROF error messages. - Document the report's fields.
1 parent 023b02e commit 761ff4c

10 files changed

Lines changed: 226 additions & 130 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -269,15 +269,18 @@ records), the Java heap from an HPROF dump (`android.os.Debug.dumpHprofData`;
269269
its GC roots minus the runtime's object table, `Reference` referents skipped),
270270
and the runtime's own edges between them (a live wrapper holds its Java object;
271271
a Java object holds its canary record: state, prototype and implementation
272-
object). A `WeakMap` value is followed from its key only. A Java object the
272+
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
273273
runtime holds for a live wrapper, and that nothing else reaches, is leaked. For each, the report gives the path from the Java
274274
object to its own wrapper through fields, properties and the runtime's edges,
275275
a `signature` (the path's node labels from their smallest rotation, free of
276276
ids), and the Java classes of the leaked objects on it (`members`).
277277
`leakedOutsideCycles` counts leaked objects on no reported cycle: held by one,
278-
or past the search limit (`truncated`, after 256 searches). Java is collected
279-
twice before the dump, so objects only weak entries hold are gone and not
280-
counted. In `"resurrecting"` mode the report is empty and no dump is taken:
278+
or past the search limits (`truncated`: after 256 searches, or a search that
279+
visited 2,000,000 nodes). V8 collects and the runtime settles the wrappers that
280+
died before the snapshot, and Java is collected twice before the dump, so
281+
objects only weak entries hold are gone and not counted. The report also gives
282+
`mode`, `probed` (the Java objects modeled), `jsNodes`, `javaObjects`,
283+
`dumpBytes` and `durationMs`. In `"resurrecting"` mode the report is empty and no dump is taken:
281284
resurrection breaks these cycles.
282285

283286
The probe is built into debug runtimes only; in a release build the function
@@ -290,7 +293,7 @@ runtime's wrappers are modeled: an object held only through another runtime's
290293
(a worker's) wrappers can read as leaked, and probes in several runtimes run
291294
one at a time. Cycles through JNI global references native code holds are
292295
missed, since those are roots. The V8 object ids the snapshot assigns are
293-
cleared afterwards unless something else (DevTools) holds heap snapshots.
296+
cleared afterwards, unless DevTools is connected and relies on them.
294297

295298
**Weak collections.** What could notice a new canary is whatever keys on the
296299
old one without keeping it, so in canary mode a builtin

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

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,6 @@ describe("Wrapper lifetime leak probe", function () {
5252
weak.probeWeak = new WeakRef(weak);
5353
})();
5454
setTimeout(function () {
55-
gc();
56-
java.lang.System.nanoTime();
5755
report = runtime.findLeakCycles();
5856
console.log("leak probe: " + JSON.stringify({
5957
leaked: report.leaked,
@@ -106,7 +104,7 @@ describe("Wrapper lifetime leak probe", function () {
106104
return;
107105
}
108106
expect(cycles.length).toBe(2);
109-
expect(cycles[0].path).toContain("--ns:record-->");
107+
expect(cycles[0].path).toContain("--ns:kept-->");
110108
expect(cycles[0].path).toContain("--ns:wrapper-->");
111109
expect(cycles[0].members.length).toBe(1);
112110
});
@@ -146,4 +144,17 @@ describe("Wrapper lifetime leak probe", function () {
146144
it("does not report a back reference through a WeakRef", function () {
147145
expect(cyclesThrough("probeWeak").length).toBe(0);
148146
});
147+
148+
it("settles the wrappers that died since the last collection first", function () {
149+
if (!canary) {
150+
return;
151+
}
152+
(function () {
153+
for (var i = 0; i < 50; i++) {
154+
new java.lang.StringBuilder("probeGarbage");
155+
}
156+
})();
157+
// Read as leaked if unsettled: their Java objects are still held for them.
158+
expect(runtime.findLeakCycles().leaked).toBeLessThan(report.leaked + 50);
159+
}, 20000);
149160
});

‎test-app/runtime/build.gradle‎

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

9393
// embed runtime binding generator in runtime, while keeping it in a separate project
9494
java.srcDirs = [bindingGeneratorSourcePath, defaultSrcPath]
95+
// The Java side of debug-only native tools (CMake's DEBUG_TOOL_SOURCES).
96+
if (!optimized) {
97+
java.srcDirs += "src/debugTools/java"
98+
}
9599
}
96100
}
97101

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+
}

‎test-app/runtime/src/main/cpp/JsV8InspectorClient.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe
7575
return JsV8InspectorClient::GetInstance()->isConnected_;
7676
}
7777

78+
// As inspectorIsConnected, without creating the client.
79+
static bool IsConnected() {
80+
JsV8InspectorClient* client = GetInstanceIfCreated();
81+
return client != nullptr && client->isConnected_;
82+
}
83+
7884
static std::map<std::string, v8::Persistent<v8::Object>*> Domains;
7985

8086
private:

0 commit comments

Comments
 (0)