Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ wrapper.
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. |
| `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)). |
| `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)). |
| `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)). |

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

**Finding leaked cycles (experimental).** Each heap has its own collector,
so neither sees a cycle that crosses into the other. `findLeakCycles()` joins
them into one graph and asks what a single collector would keep: the JS heap
from a V8 heap snapshot (its roots minus the runtime's handles to canary
records), the Java heap from an HPROF dump (`android.os.Debug.dumpHprofData`;
its GC roots minus the runtime's object table, `Reference` referents skipped),
and the runtime's own edges between them (a live wrapper holds its Java object;
a Java object holds its canary record: state, weak-collection key, prototype
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
runtime holds for a live wrapper, and that nothing else reaches, is leaked. For each, the report gives the path from the Java
object to its own wrapper through fields, properties and the runtime's edges,
a `signature` (the path's node labels from their smallest rotation, free of
ids), and the Java classes of the leaked objects 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). V8 collects and the runtime settles the wrappers that
died before the snapshot, and Java is collected twice before the dump, so
objects only weak entries hold are gone and not counted. The report also gives
`mode`, `probed` (the Java objects modeled), `jsNodes`, `javaObjects`,
`dumpBytes` and `durationMs`. In `"resurrecting"` mode the report is empty and no dump is taken:
resurrection breaks these cycles. Under `"canary"` every wrapper is a canary
in either scope, so under `"extended"` too a cycle through a plain wrapper,
which resurrection used to break, is reported as a leak.

The probe is built into debug runtimes only; in a release build the function
exists but throws `findLeakCycles is available in debug builds only`. It suspends the whole process for the dump, writes the Java heap to
the app's cache directory (deleted once parsed, and swept by the next probe if
the process died first) and builds graphs of both heaps in native memory, so
it takes seconds; on the main thread that can trip an ANR. The snapshot and
the dump are taken one after the other, not atomically. Only the calling
runtime's wrappers are modeled: an object held only through another runtime's
(a worker's) wrappers can read as leaked, and probes in several runtimes run
one at a time. Cycles through JNI global references native code holds are
missed, since those are roots. The V8 object ids the snapshot assigns are
cleared afterwards, unless DevTools is connected and relies on them.

**Weak collections.** What could notice a new canary is whatever keys on the
old one without keeping it, so in canary mode a builtin
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and
Expand Down
1 change: 1 addition & 0 deletions test-app/app/src/main/assets/app/mainpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ require("./tests/testWrapperLifetimeStateWrites");
require("./tests/testWrapperLifetimeFieldWrites");
require("./tests/testWrapperLifetimeRecordSharing");
require("./tests/testWrapperLifetimeWeakCollections");
require("./tests/testWrapperLifetimeLeaks");
require("./tests/testsMemoryManagement");
require("./tests/testFieldGetSet");
require("./tests/extendedClassesTests");
Expand Down
2 changes: 1 addition & 1 deletion test-app/app/src/main/assets/app/tests/testNsRuntime.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe("ns:runtime", function () {
// The export set is public API, declared alongside docs/ns-builtin-modules.md
// — all of them change together.
it("exposes exactly the declared surface", function () {
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "findLeakCycles", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
});

it("rejects unknown keys", function () {
Expand Down
218 changes: 218 additions & 0 deletions test-app/app/src/main/assets/app/tests/testWrapperLifetimeLeaks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
describe("Wrapper lifetime leak probe", function () {
var runtime = require("ns:runtime");
var mode = runtime.getConfig("wrapperLifetimeMode");
var canary = mode === "canary";
var Holder = com.tns.tests.WrapperHolder;
// WeakRefs, so the spec itself keeps nothing it planted alive.
var planted = [];
// Alive for the whole suite: what leaks is the entry's value.
var probeMap = new WeakMap();
var report;
var canaryRebuilds;

function cyclesThrough(edge) {
return report.cycles.filter(function (cycle) {
return cycle.path.indexOf("--" + edge + "-->") !== -1;
});
}

// Each probe dumps the Java heap, so every shape is planted once and probed once, on a
// later task: a WeakRef keeps its target alive until the job that made it ends.
beforeAll(function (done) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// A cycle through Java whose object's canary was rebuilt since: the record also
// keeps a copy of the rebuilt canary, which must not read as a root.
(function () {
var rebuilt = new java.lang.Runnable({ run: function () {} });
var list = new java.util.ArrayList();
list.add(rebuilt);
rebuilt.probeRebuiltList = list;
planted.push(new WeakRef(rebuilt));
Holder.held = list;
})();
// The canary dies on a later job: a WeakRef keeps its target until the job ends.
setTimeout(function () {
gc();
java.lang.System.nanoTime();
java.lang.Runtime.getRuntime().gc();
gc();
java.lang.System.nanoTime();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
var rebuildsBefore = runtime.getWrapperLifetimeStats().canaryRebuilds;
(function () {
// A read: the rebuilt canary's copy stays current.
Holder.held.get(0).probeRebuiltList.size();
})();
canaryRebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds - rebuildsBefore;
Holder.held = null;
(function () {
// A JS property referencing its own object.
var selfReferencing = new java.lang.Runnable({ run: function () {} });
selfReferencing.probeSelf = selfReferencing;
planted.push(new WeakRef(selfReferencing));

var twin = new java.lang.Runnable({ run: function () {} });
twin.probeSelf = twin;
planted.push(new WeakRef(twin));

// A cycle through Java: the object's state holds a list that holds the object.
var listed = new java.lang.Runnable({ run: function () {} });
var list = new java.util.ArrayList();
list.add(listed);
listed.probeList = list;
planted.push(new WeakRef(listed));

// Held by a Java static: alive for a reason of its own, not a leak.
var held = new java.lang.Runnable({ run: function () {} });
held.probeHeld = held;
Holder.held = held;
planted.push(new WeakRef(held));

// A WeakMap value referencing its own key: in canary mode the key is the
// object's lifetime key, which its record holds.
var mapped = new java.lang.Runnable({ run: function () {} });
probeMap.set(mapped, { probeMapped: mapped });
planted.push(new WeakRef(mapped));

// A back reference through a WeakRef keeps nothing.
var weak = new java.lang.Runnable({ run: function () {} });
weak.probeWeak = new WeakRef(weak);
})();
(function () {
// A method closing over its own object: the cycle runs through the object's
// prototype, its implementation object. In a function of its own, so no other
// planted closure shares the context that holds it.
var probeClosed = new java.lang.Runnable({
run: function () {
return probeClosed;
}
});
planted.push(new WeakRef(probeClosed));
})();
setTimeout(function () {
report = runtime.findLeakCycles();
console.log("leak probe: " + JSON.stringify({
leaked: report.leaked,
leakedOutsideCycles: report.leakedOutsideCycles,
probed: report.probed,
cycles: report.cycles.length,
durationMs: report.durationMs,
dumpBytes: report.dumpBytes
}));
report.cycles.forEach(function (cycle) {
console.log("leak probe cycle: " + cycle.signature);
});
done();
}, 0);
}, 0);
}, 20000);

afterAll(function () {
Holder.held = null;
planted.forEach(function (ref) {
var object = ref.deref();
if (object !== undefined) {
__releaseNativeCounterpart(object);
}
});
planted = [];
report = null;
});

it("reports the heaps it joined (" + mode + ")", function () {
expect(report.mode).toBe(mode);
expect(Array.isArray(report.cycles)).toBe(true);
if (!canary) {
// Nothing to look for: no dump is taken.
expect(report.leaked).toBe(0);
expect(report.javaObjects).toBeUndefined();
return;
}
expect(report.javaObjects).toBeGreaterThan(0);
expect(report.jsNodes).toBeGreaterThan(0);
expect(report.probed).toBeGreaterThan(0);
expect(report.truncated).toBe(false);
expect(report.durationMs).toBeGreaterThan(0);
});

it("finds an object whose JS state references it", function () {
var cycles = cyclesThrough("probeSelf");
if (!canary) {
// Resurrection breaks it: nothing keeps the object once JS lets go.
expect(cycles.length).toBe(0);
return;
}
expect(cycles.length).toBe(2);
expect(cycles[0].path).toContain("--ns:kept-->");
expect(cycles[0].path).toContain("--ns:wrapper-->");
expect(cycles[0].members.length).toBe(1);
});

it("gives the same shape the same signature, free of ids", function () {
if (!canary) {
return;
}
var cycles = cyclesThrough("probeSelf");
expect(cycles[0].signature).toBe(cycles[1].signature);
});

it("finds a cycle through a Java collection", function () {
var cycles = cyclesThrough("probeList");
if (!canary) {
expect(cycles.length).toBe(0);
return;
}
expect(cycles.length).toBe(1);
expect(cycles[0].path).toContain("--java.util.ArrayList.elementData-->");
});

it("finds a cycle through a WeakMap value that references its key", function () {
var cycles = cyclesThrough("probeMapped");
if (!canary) {
expect(cycles.length).toBe(0);
return;
}
expect(cycles.length).toBe(1);
expect(cycles[0].path).toContain("--WeakMap value-->");
});

it("finds a cycle through a method that closes over its object", function () {
var cycles = cyclesThrough("probeClosed");
if (!canary) {
expect(cycles.length).toBe(0);
return;
}
expect(cycles.length).toBe(1);
expect(cycles[0].path).toContain("--ns:kept-->");
expect(cycles[0].path).toContain("--ns:wrapper-->");
});

it("finds a cycle through Java after the object's canary was rebuilt", function () {
var cycles = cyclesThrough("probeRebuiltList");
if (!canary) {
expect(cycles.length).toBe(0);
return;
}
expect(canaryRebuilds).toBeGreaterThan(0);
expect(cycles.length).toBe(1);
});

it("does not report an object Java holds for a reason of its own", function () {
expect(cyclesThrough("probeHeld").length).toBe(0);
});

it("does not report a back reference through a WeakRef", function () {
expect(cyclesThrough("probeWeak").length).toBe(0);
});

it("settles the wrappers that died since the last collection first", function () {
if (!canary) {
return;
}
(function () {
for (var i = 0; i < 50; i++) {
new java.lang.StringBuilder("probeGarbage");
}
})();
// Read as leaked if unsettled: their Java objects are still held for them.
expect(runtime.findLeakCycles().leaked).toBeLessThanOrEqual(report.leaked);
}, 20000);
});
9 changes: 9 additions & 0 deletions test-app/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,17 @@ if (NOT OPTIMIZED_BUILD OR OPTIMIZED_WITH_INSPECTOR_BUILD)
src/main/cpp/v8_inspector/ns-v8-tracing-agent-impl.cpp
src/main/cpp/v8_inspector/Utils.cpp
)

# ns:runtime findLeakCycles(); release builds keep a stub that throws.
set(
DEBUG_TOOL_SOURCES

src/main/cpp/LeakProbe.cpp
)
else ()
# When building in Release mode we do not include the V8 inspector sources
set(INSPECTOR_SOURCES)
set(DEBUG_TOOL_SOURCES)
endif ()

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

# V8 inspector source files will be included only in Release mode
${INSPECTOR_SOURCES}
${DEBUG_TOOL_SOURCES}

# Node-API test addons, local Debug builds only
${NAPI_TEST_SOURCES}
Expand Down
4 changes: 4 additions & 0 deletions test-app/runtime/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ android {

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

Expand Down
70 changes: 70 additions & 0 deletions test-app/runtime/src/debugTools/java/com/tns/LeakProbe.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package com.tns;

import java.io.File;

/**
* ns:runtime findLeakCycles()'s Java side, in debug runtimes only. During the heap dump,
* {@link #pinned} holds the Java objects the analysis maps to JS wrappers and states; the
* analysis finds that array through this static field by name and does not count it as a
* reference.
*/
final class LeakProbe {
static final String DUMP_PREFIX = "ns-leak-probe";

// Older than any dump a probe of this process or another one may still be parsing.
private static final long STALE_DUMP_AGE_MS = 10 * 60 * 1000;

static Object[] pinned;

private LeakProbe() {
}

// Before the probe takes strong references: objects only weak entries hold would
// otherwise read as leaked until Java collects them.
static void collectGarbage() {
for (int i = 0; i < 2; i++) {
java.lang.Runtime.getRuntime().gc();
}
}

// Writes an HPROF dump with objects pinned in order; returns its path, or null if it
// could not be written. The caller deletes the dump once parsed.
static String dump(Object[] objects) {
// pinned is shared by every runtime of the process.
synchronized (LeakProbe.class) {
deleteStaleDumps();
File file = null;
try {
file = File.createTempFile(DUMP_PREFIX, ".hprof");
pinned = objects;
android.os.Debug.dumpHprofData(file.getAbsolutePath());
return file.getAbsolutePath();
} catch (Throwable t) {
android.util.Log.w("JS", "findLeakCycles could not dump the Java heap", t);
if (file != null) {
file.delete();
}
return null;
} finally {
pinned = null;
}
}
}

// Dumps a killed process left behind.
private static void deleteStaleDumps() {
String tmp = System.getProperty("java.io.tmpdir");
File[] files = tmp != null ? new File(tmp).listFiles() : null;
if (files == null) {
return;
}
long staleBefore = System.currentTimeMillis() - STALE_DUMP_AGE_MS;
for (File file : files) {
String name = file.getName();
if (name.startsWith(DUMP_PREFIX) && name.endsWith(".hprof")
&& file.lastModified() < staleBefore) {
file.delete();
}
}
}
}
Loading