Title: fix(runtime): route Java->JS calls to the runtime that created the binding by edusperoni · Pull Request #2015 · NativeScript/android · GitHub
Open Graph Title: fix(runtime): route Java->JS calls to the runtime that created the binding by edusperoni · Pull Request #2015 · NativeScript/android
X Title: fix(runtime): route Java->JS calls to the runtime that created the binding by edusperoni · Pull Request #2015 · NativeScript/android
Description: Description SBG generates real Java classes for JS code, but those classes carried no record of which runtime they belong to. com.tns.Runtime therefore re-derived the target of every Java→JS call from the calling thread: the currentRuntime thread-local, then the entered V8 isolate, then getObjectRuntime(), a linear scan probing every live runtime's object→id maps until one contained the instance. That had four problems: Ownership was inferred from the wrong signal. "This runtime has an id for the object" only means the instance crossed into that isolate, not that the isolate implements it. An instance created by a worker and later wrapped by main lived in both maps, and a call on main dispatched into main's plain wrapper. Main resolved the method to the Java override, which called back into callJSMethod, and the call recursed. Cross-thread calls mutated another runtime's maps. With enableMultithreadedJavascript off (the default) the object maps are a plain NativeScriptHashMap/NativeScriptWeakHashMap. Every cross-thread call looked the object up on the calling thread, and NativeScriptWeakHashMap.get() isn't read-only: it expunges stale entries. So a callback arriving on an OkHttp, executor or Binder thread changed main's map with no lock while main mutated it too. The owner scan did the same to every runtime. A worker ending could hang the caller. WorkerWrapper stops a worker with Looper.quit(), which discards queued messages. A call posted just before that never ran and nothing woke the caller, so the caller blocked in wait() forever (an ANR if it was the main thread). A post that failed outright returned null with no log. initInstance off a runtime thread dereferenced a null runtime and threw a bare NPE. What this changes Bindings carry their owner. Both generators now emit com.tns.NativeScriptRuntimeBound, a volatile int tag with an accessor pair: the static binding generator, in Java source; the runtime binding generator (Dump.java), which dexes the proxies behind new java.lang.Runnable({...}), in asmdex alongside the existing __initialized field and equals__super. initInstance writes the tag once, after the instance is registered. Later registrations by other runtimes (getOrCreateJavaObjectID, when the instance crosses isolates) never overwrite it, because only the creating runtime holds the JS implementation. Runtime ids are monotonic and never reused, so a stale tag can't match a newer runtime. The tag is the runtime id plus one, encoded and decoded only inside Runtime. That way the field's zero default means "no owner yet": nothing has to seed it, and the field still reads "no owner" while the superclass constructor runs, before initInstance can record anything. Runtime id 0 is main's and stays load-bearing; JsV8InspectorClient hard-codes GetRuntime(0). Routing. callJSMethod dispatches to the tagged runtime. An untagged instance is still being constructed or registered: a generated method called from the superclass constructor, or re-entered from JS during initInstance. Those go to the calling thread's runtime, which is the only one that can be registering it. getObjectRuntime() and its scan are removed. Bindings are always regenerated by the SBG that ships with the runtime, so no untagged binding outlives a build. The object id is resolved on the owner's thread. The lookup moved from the caller into the posted Runnable, next to the argument packaging that already ran there. With multithreaded JS off, nothing outside a runtime's thread touches its object maps any more. A missing id is still reported to the caller as a NativeScriptException, now naming the class instead of calling a possibly JS-overridden toString(). Calls with nowhere left to run are dropped and logged, not thrown or left waiting. These calls arrive on Android callbacks (lifecycle, listeners, draw), so throwing would take down the process just because a worker ended. Primitive returns get the existing default-value substitution so the generated cast can still unbox. This covers: a call against a terminated owner; a failed post() to a quitting looper; a call that was queued when the worker quit. The caller re-checks every 100 ms whether the owner is still running and gives up once it has left runtimeCache (or its thread has died); with multithreaded JS, an owner torn down between the routing check and the native call. TryGetRuntime then throws Cannot find runtime for id:N, which is dropped once the owner is confirmed gone. Two cases still throw, because they are programming errors rather than lifecycle races: an untagged instance called from a thread with no runtime, and an instance its owner has no object id for. initInstance with no runtime on the thread is the one case that throws, with a message that says what to do. It was already a crash (the NPE), and dropping there would leave an unregistered instance whose later calls all fail further from the cause. Suppressed exceptions go to the owner. passSuppressedExceptionToJs reported to the calling thread's runtime, and the message it built was never used. The generated code now passes the instance, and the report goes to the owner on the owner's own thread without blocking. If the owner has terminated, the report is logged and dropped instead of surfacing in an unrelated runtime. The two-argument overload remains for callers with no instance. Cost: two methods and one int field per generated binding class. Notes for review The hand-written asmdex in Dump.java is now just the field declaration and the two accessors. The constructor emits nothing new. The accessors follow the register conventions of equals__super/hashCode__super (parameters occupy the last registers). Mistakes here show up as dex verification failures at runtime, which the device suite would hit, since nearly every listener in the specs is one of these proxies. The native side is unchanged. With multithreaded JS, a teardown that lands after TryGetRuntime succeeds but before the v8::Locker is taken is still a native race; this PR doesn't touch it. Routing calls to the real owner means a call to another runtime's object now blocks until that runtime runs it, where before it ran (wrongly) in the caller's isolate. Two live runtimes making synchronous calls on each other's objects at the same time can therefore deadlock. The bounded wait only covers an owner that terminates, not one that is busy waiting on the caller. A call to an object owned by a terminated worker no-ops with a log. Falling back to main would run main's wrapper rather than the worker's implementation, so it would run the wrong code instead of none. Related Pull Requests None yet. iOS has the same static-binding shape and would want a matching change. Does your pull request have unit tests? Yes. testRuntimeBoundDispatch.js (device, new). A worker creates JS-implemented Runnable and Comparable objects and hands them to main through a Java holder (com.tns.tests.RuntimeBoundHolder). Main then checks that: calls from main JS (with main also holding a wrapper), from main via Java, and from a plain Java thread all run on the worker; after terminate(), calls are dropped and a primitive return comes back as 0, with no throw; a call queued on the worker's looper while the worker sleeps and then close()s returns 0 instead of hanging the caller. GeneratorTest checks that a generated binding implements NativeScriptRuntimeBound, that its tag defaults to 0 and round-trips, that the field is volatile, and that the exception-suppressing variant compiles and passes this to passSuppressedExceptionToJs. That path had no compile coverage before; it needed an android.util.Log test stub, added here. testsForRuntimeBindingGenerator.js asserts the exact interface list of a runtime-generated proxy; updated for the added interface. Verification (Pixel 3a, API 36, arm64 emulator): The full Jasmine suite as committed (the test app enables enableMultithreadedJavascript): 1483 specs, 0 failures, 4 skipped. The full suite again with enableMultithreadedJavascript temporarily set to false, which is the runtime's default. The test app's own setting never exercises the post-to-looper path that most of this changes. All four new specs pass, including the queued-call/close() case. The only failures were the two specs that require multithreaded JS (testEventLoop.js:114 and testMultithreadedJavascript.js:7 expect a JS Runnable to run off the main thread). :static-binding-generator:test: 19 tests pass. The new specs read the flag from the app's package.json. With multithreaded JS on, a Java→JS call runs on the calling thread under the owner isolate's lock, so they assert which isolate ran the call rather than which thread. The queued-call spec runs only when the flag is off, since that is the only mode with a queue. Summary by CodeRabbit New Features Java-to-JavaScript calls now run on the runtime that created the object, including calls originating from other threads. Calls targeting a runtime that has stopped are discarded safely, with appropriate default return values. Waiting calls can also finish when the runtime stops accepting work. Generated bindings now track their creating runtime. Tests Added coverage for runtime-bound dispatch across worker modes, thread calls, comparisons, and worker shutdown.
Open Graph Description: Description SBG generates real Java classes for JS code, but those classes carried no record of which runtime they belong to. com.tns.Runtime therefore re-derived the target of every Java→JS call f...
X Description: Description SBG generates real Java classes for JS code, but those classes carried no record of which runtime they belong to. com.tns.Runtime therefore re-derived the target of every Java→JS call f...
Opengraph URL: https://github.com/NativeScript/android/pull/2015
X: @github
Domain: github.com
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:fa794774-94fb-efe1-0db6-6bd5abf7cfeb |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | E78A:26ECEB:165DAE9:1C8DCE2:6B012291 |
| html-safe-nonce | a4f1a1e878c05e3b9c78c95dccb63ebfc3d11a2d64ed558e90fb63633408e23e |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNzhBOjI2RUNFQjoxNjVEQUU5OjFDOERDRTI6NkIwMTIyOTEiLCJ2aXNpdG9yX2lkIjoiNzk2NTI5MTg2MzI3ODE2NjY3MyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | d9d25755f057ff89eaef63bcf46c871575de87b6ffba1ddf3991e072e5e7e19e |
| hovercard-subject-tag | pull_request:4287580937 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/NativeScript/android/pull/2015/files |
| twitter:image | https://avatars.githubusercontent.com/u/4061767?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/4061767?s=400&v=4 |
| og:image:alt | Description SBG generates real Java classes for JS code, but those classes carried no record of which runtime they belong to. com.tns.Runtime therefore re-derived the target of every Java→JS call f... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/NativeScript/android git https://github.com/NativeScript/android.git |
| octolytics-dimension-user_id | 7392261 |
| octolytics-dimension-user_login | NativeScript |
| octolytics-dimension-repository_id | 29137950 |
| octolytics-dimension-repository_nwo | NativeScript/android |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 29137950 |
| octolytics-dimension-repository_network_root_nwo | NativeScript/android |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width