Skip to content
Open
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
40 changes: 40 additions & 0 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ wrapper.
|---|---|
| `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. |
| `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. |
| `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 All @@ -117,6 +118,8 @@ Config keys:
| key | values | scope | default |
|---|---|---|---|
| `debug` | comma-separated category list, e.g. `"esm,fetch"` | process-wide (main-isolate writes only; read live by every isolate) | the `NS_DEBUG` environment variable, or `""` |
| `wrapperLifetimeMode` | `"resurrecting"` | process-wide, read-only | the app config `"wrapperLifetime": { "mode": … }`, or `"resurrecting"` |
| `wrapperLifetimeScope` | `"extended"` \| `"all"` | process-wide, read-only | the app config `"wrapperLifetime": { "scope": … }`, or `"extended"` |

iOS additionally registers `releasedObjectPolicy`, which governs access to a
wrapper whose native counterpart has already been released. Android does not
Expand Down Expand Up @@ -145,10 +148,47 @@ The `TypeError` messages are part of the contract:
| bad `getConfig` arity or non-string key | `getConfig expects (key: string)` |
| process-wide key written from a worker | `'<key>' is process-wide and can only be set from the main isolate` |
| non-string `debug` value | `'debug' must be a comma-separated category string (<categories>), or '' to disable tracing` |
| `setConfig` of `wrapperLifetimeMode` or `wrapperLifetimeScope` | `'<key>' is read-only; set "wrapperLifetime" in the app config` |

`<categories>` is the runtime's own list of valid category names, which on
Android expands to `esm,fetch,registry`.

#### Wrapper lifetime

How the JS wrappers of Java objects live is chosen once per process by the
top-level `"wrapperLifetime"` object of the app's `package.json`, the same key
iOS reads:

```json
{ "wrapperLifetime": { "mode": "resurrecting", "scope": "extended" } }
```

A value that is not an object, or an unknown `mode` or `scope`, logs a warning
and keeps the default. `"rooted"` is iOS-only: it reads native retain counts,
which Java does not have. `scope` chooses which wrappers a mode other than
`"resurrecting"` applies to, `"extended"` the instances of JS-extended classes
and `"all"` every wrapper; `"resurrecting"` applies to every wrapper whatever
the scope.

`"resurrecting"` (the default) keeps a collected wrapper while Java may still
hold its object. The first collection resurrects it and makes the Java side
weak; a later collection releases the wrapper only once Java has collected the
object. The JS properties of a wrapper whose object Java holds therefore
survive, but the Java objects those properties reference were made weak in
the same collection, and Java may collect them under the wrapper: touching one
then throws `Attempt to use cleared object reference`.

`getWrapperLifetimeStats()` returns counters for the calling isolate, kept in
every build on cold paths only:

| counter | counts |
|---|---|
| `resurrections` | finalizer passes that kept a collected wrapper until the Java side says whether its object is still alive. Every pass counts, so a wrapper JS dropped counts at least twice (once to weaken the Java side, once more to check whether Java collected the object) and one whose object Java holds counts again on every major GC. Unlike iOS's counter of the same name, it is not a number of wrappers native code kept alive |
| `weakened` | Java objects held weakly because their wrapper was collected |
| `collected` | wrappers released because Java had collected their object |
| `releasedExplicitly` | links released through `__releaseNativeCounterpart` |
| `releasedAccesses` | lookups of the Java object of a wrapper whose link was released or whose Java object Java had already collected: calling its methods, using its fields or passing it to Java. Resolving an overloaded method looks its arguments up too, so one call can count more than once |

Remote-module security (`security.allowRemoteModules`,
`security.remoteModuleAllowlist`) is **not** part of this surface. Those
values are read once from nativescript.config / package.json the first time
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 @@ -60,6 +60,7 @@ require("./tests/dispatchCallbacksOnUiThreadTests");
require("./tests/stringConversionTests");
require("./tests/testsForTypescript");
require("./tests/testGC");
require("./tests/testWrapperLifetime");
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", "setConfig"]);
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperLifetimeStats", "setConfig"]);
});

it("rejects unknown keys", function () {
Expand Down
141 changes: 141 additions & 0 deletions test-app/app/src/main/assets/app/tests/testWrapperLifetime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
describe("Wrapper lifetime", function () {
var runtime = require("ns:runtime");
var mode = runtime.getConfig("wrapperLifetimeMode");
var scope = runtime.getConfig("wrapperLifetimeScope");
var Holder = com.tns.tests.WrapperHolder;

function collectJava() {
for (var i = 0; i < 3; i++) {
java.lang.Runtime.getRuntime().gc();
java.lang.System.runFinalization();
}
}

// A JS->Java call: settles the wrappers the last collection queued.
function crossIntoJava() {
java.lang.System.nanoTime();
}

afterEach(function () {
Holder.held = null;
});

it("reports the configured mode and scope (" + mode + "/" + scope + ")", function () {
expect(["resurrecting"]).toContain(mode);
expect(["extended", "all"]).toContain(scope);
});

it("rejects writes to the mode and scope", function () {
expect(function () {
runtime.setConfig("wrapperLifetimeMode", "resurrecting");
}).toThrowError(TypeError, "'wrapperLifetimeMode' is read-only; set \"wrapperLifetime\" in the app config");
expect(function () {
runtime.setConfig("wrapperLifetimeScope", "all");
}).toThrowError(TypeError, "'wrapperLifetimeScope' is read-only; set \"wrapperLifetime\" in the app config");
});

it("exposes numeric counters", function () {
var stats = runtime.getWrapperLifetimeStats();
expect(Object.keys(stats).sort()).toEqual(
["collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]);
Object.keys(stats).forEach(function (key) {
expect(typeof stats[key]).toBe("number");
});
expect(runtime.getWrapperLifetimeStats()).not.toBe(stats);
});

it("counts explicit releases, and calls on a released wrapper", function () {
var before = runtime.getWrapperLifetimeStats();
var released = new java.lang.Object();
__releaseNativeCounterpart(released);
expect(runtime.getWrapperLifetimeStats().releasedExplicitly).toBe(before.releasedExplicitly + 1);
expect(function () {
released.hashCode();
}).toThrowError(/no longer has available Java instance counterpart/);
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1);

// Not a wrapper at all: not a released access.
var hashCode = new java.lang.Object().hashCode;
[{}, new ArrayBuffer(8), new Int8Array(8)].forEach(function (receiver) {
expect(function () {
hashCode.call(receiver);
}).toThrow();
});
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1);
});

it("counts field accesses on, and arguments of, a released wrapper", function () {
var point = new android.graphics.Point(1, 2);
__releaseNativeCounterpart(point);
var before = runtime.getWrapperLifetimeStats().releasedAccesses;
expect(function () {
return point.x;
}).toThrowError(/no corresponding Java object/);
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before + 1);

// Resolving an overload looks the argument up too, so one call can count more than once.
expect(function () {
java.lang.String.valueOf(point);
}).toThrow();
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBeGreaterThan(before + 1);
});

it("reports counters as own properties whatever Object.prototype defines", function () {
Object.defineProperty(Object.prototype, "collected", {
set: function () {},
configurable: true
});
try {
var stats = runtime.getWrapperLifetimeStats();
expect(Object.prototype.hasOwnProperty.call(stats, "collected")).toBe(true);
expect(typeof stats.collected).toBe("number");
} finally {
delete Object.prototype.collected;
}
});

if (mode !== "resurrecting") {
return;
}

it("keeps a collected wrapper until Java has collected its object", function () {
var before = runtime.getWrapperLifetimeStats();
(function () {
for (var i = 0; i < 20; i++) {
new java.lang.Object();
}
})();
gc();
crossIntoJava();
var weakened = runtime.getWrapperLifetimeStats();
expect(weakened.resurrections).toBeGreaterThan(before.resurrections);
expect(weakened.weakened).toBeGreaterThan(before.weakened);

collectJava();
gc();
crossIntoJava();
expect(runtime.getWrapperLifetimeStats().collected).toBeGreaterThan(before.collected);
});

// The shape the "canary" mode removes: a wrapper resurrected because Java holds its
// object keeps its JS properties, but the Java objects those properties reference
// were weakened in the same collection, and Java is free to collect them.
it("lets Java collect an object only a resurrected wrapper's JS property references", function () {
(function () {
var holder = new java.lang.StringBuilder("holder");
holder.child = new java.lang.StringBuilder("child");
Holder.held = holder;
})();
gc();
crossIntoJava();
collectJava();

var holder = Holder.held;
expect(holder.toString()).toBe("holder");
var before = runtime.getWrapperLifetimeStats().releasedAccesses;
expect(function () {
holder.child.toString();
}).toThrowError(/Attempt to use cleared object reference/);
expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before + 1);
});
});
1 change: 1 addition & 0 deletions test-app/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ add_library(
src/main/cpp/V8GlobalHelpers.cpp
src/main/cpp/V8StringConstants.cpp
src/main/cpp/WeakRef.cpp
src/main/cpp/WrapperLifetime.cpp
src/main/cpp/WorkerEvents.cpp
src/main/cpp/WorkerWrapper.cpp
src/main/cpp/Timers.cpp
Expand Down
41 changes: 40 additions & 1 deletion test-app/runtime/src/main/cpp/NsBuiltinModules.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "StructuredSerialization.h"
#include "TextEncoding.h"
#include "TraceLog.h"
#include "WrapperLifetime.h"
#include "console/Console.h"
#include "robin_hood.h"

Expand Down Expand Up @@ -79,6 +80,8 @@ constexpr Registration kRegistry[] = {
};

constexpr const char* kDebugKey = "debug";
constexpr const char* kWrapperLifetimeModeKey = "wrapperLifetimeMode";
constexpr const char* kWrapperLifetimeScopeKey = "wrapperLifetimeScope";

void ThrowTypeError(Isolate* isolate, const std::string& message) {
isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String(isolate, message)));
Expand Down Expand Up @@ -126,6 +129,10 @@ void SetConfigCallback(const FunctionCallbackInfo<Value>& info) {
}
return;
}
if (key == kWrapperLifetimeModeKey || key == kWrapperLifetimeScopeKey) {
ThrowTypeError(isolate, "'" + key + "' is read-only; set \"wrapperLifetime\" in the app config");
return;
}
ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'");
}

Expand All @@ -141,9 +148,36 @@ void GetConfigCallback(const FunctionCallbackInfo<Value>& info) {
ArgConverter::ConvertToV8String(isolate, tns::EnabledLogCategoryNames()));
return;
}
if (key == kWrapperLifetimeModeKey) {
info.GetReturnValue().Set(ArgConverter::ConvertToV8String(
isolate, WrapperLifetimeModeName(GetWrapperLifetimeMode())));
return;
}
if (key == kWrapperLifetimeScopeKey) {
info.GetReturnValue().Set(ArgConverter::ConvertToV8String(
isolate, WrapperLifetimeScopeName(GetWrapperLifetimeScope())));
return;
}
ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'");
}

void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
const WrapperLifetimeStats& stats = Runtime::GetObjectManager(isolate)->GetLifetimeStats();
Local<Context> context = isolate->GetCurrentContext();
Local<Object> result = Object::New(isolate);
auto set = [&](const char* name, uint64_t value) {
(void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name),
Number::New(isolate, static_cast<double>(value)));
};
set("resurrections", stats.resurrections);
set("weakened", stats.weakened);
set("collected", stats.collected);
set("releasedExplicitly", stats.releasedExplicitly);
set("releasedAccesses", stats.releasedAccesses);
info.GetReturnValue().Set(result);
}

const Registration* Find(const std::string& specifier) {
for (const Registration& registration : kRegistry) {
if (specifier == registration.specifier) {
Expand Down Expand Up @@ -217,16 +251,21 @@ MaybeLocal<Object> NsModuleBinding(Local<Context> context) {
MaybeLocal<Object> NsRuntimeBinding(Local<Context> context) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Object> binding = Object::New(isolate);
Local<v8::Function> setConfig, getConfig, escapeException;
Local<v8::Function> setConfig, getConfig, escapeException, getWrapperLifetimeStats;
if (!v8::Function::New(context, SetConfigCallback).ToLocal(&setConfig) ||
!v8::Function::New(context, GetConfigCallback).ToLocal(&getConfig) ||
!v8::Function::New(context, GetWrapperLifetimeStatsCallback)
.ToLocal(&getWrapperLifetimeStats) ||
!Interop::CreateEscapeException(context).ToLocal(&escapeException) ||
!binding->Set(context, ArgConverter::ConvertToV8String(isolate, "setConfig"), setConfig)
.FromMaybe(false) ||
!binding->Set(context, ArgConverter::ConvertToV8String(isolate, "getConfig"), getConfig)
.FromMaybe(false) ||
!binding->Set(context, ArgConverter::ConvertToV8String(isolate, "escapeException"),
escapeException)
.FromMaybe(false) ||
!binding->Set(context, ArgConverter::ConvertToV8String(isolate, "getWrapperLifetimeStats"),
getWrapperLifetimeStats)
.FromMaybe(false)) {
return MaybeLocal<Object>();
}
Expand Down
Loading