Skip to content

fix(runtime): convert Java char values as UTF-16 code units - #2140

Merged
edusperoni merged 3 commits into
mainfrom
fix/char-conversion-and-field-handle
Nov 21, 2026
Merged

edusperoni merged 3 commits into
mainfrom
fix/char-conversion-and-field-handle

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Fixes Java char conversion for non-ASCII values, and escapes one un-escaped handle in FieldAccessor::GetJavaField.

Bug 1: char values went through UTF-8

Several JS→Java char conversions turned the JS string into UTF-8 and kept a single byte, so any non-ASCII value reached Java wrong. Observed on main with the new specs:

Path Input Java got (before)
char("é") / char("€") method argument (JsArgConverter, CastType::Char) U+00E9 / U+20AC 195 / 226
char field set, instance and static (FieldAccessor::SetJavaField) U+00E9 / U+20AC 195 / 226
char() returned from a JS callback (JsArgToArrayConverter, CastType::Char) U+00E9 / U+20AC sent in via char() 195 / 195 (the callback already received à / â from the argument bug, and the returned char() again kept the first UTF-8 byte)
JS array → char[] argument (JsArgConverter::ConvertJavaScriptArray) ["é", "€", "中", "\ud83d"] 234, 232, 235, 235
char[] element set (ArrayElementAccessor::SetArrayElement) same 234, 232, 235, 235
char[] element get (ArrayElementAccessor::GetArrayElement) Java 'é', '€' JS got U+FFFD
Plain JS string to a non-overloaded char parameter (JsArgConverter::ConvertJavaScriptString) "x", "é", "" 4141, 4133, 4137 (the low bits of the jstring local reference, read through jvalue.c)

The array paths reinterpreted the first two UTF-8 bytes as one UTF-16 unit and then took a byte of its modified UTF-8. The element get handed V8 one UTF-8 byte.

Fix. All of these now go through a new ArgConverter::ToJavaChar, which takes the first UTF-16 code unit of the JS string. An empty string gives U+0000, which is what the field setter already gave. A character outside the BMP gives its high surrogate. The char[] element get uses jcharToV8String. No new errors are thrown.

Checked and already correct, so unchanged:

  • char method return values
  • char field get
  • char arguments of Java→JS callbacks
  • a raw one-character string returned from a callback for a char return type (TryGetPrimitiveReturnBits)
  • Uint16Array → char[]

Behaviour change to review. A plain string passed to a non-overloaded char parameter now yields its first code unit, where it used to pass an arbitrary value. Overloaded methods are unaffected because overload resolution never matches a String to char. If a "Cannot convert string to C" error is preferred instead, that is a small change in ConvertJavaScriptString.

Bug 2: boolean field read returned an un-escaped handle

GetJavaField escapes every result from its EscapableHandleScope except the boolean branch, which returned a handle created inside the closed scope. V8's Boolean::New currently returns a root-table slot (v8-primitive.h: True() / False() use GetRootSlot), so this does not dangle in practice. It is now escaped like the sibling branches, because the API does not guarantee root slots. The boolean field spec passes before and after, so it is coverage rather than a regression test.

Does your commit message include the wording below to reference a specific issue in this repo?

No linked issue; found by a code audit.

Related Pull Requests

None.

Does your pull request have unit tests?

Yes. There is a new describe in testPrimitiveTypeConversion.js with Java helpers added to com.tns.tests.CharConversionTest.

What the specs cover

  • Inputs: U+00E9, U+20AC, U+4E2D, a lone high surrogate, an ASCII control and ASCII.
  • Paths: char() and plain-string arguments, char return values, JS array → char[], char[] element get and set, instance and static char fields, and a char() returned from a JS callback.
  • Java-side values are read back as ints, and the element get uses a Java-created char[], so a broken direction cannot be masked by the opposite one.
  • They pin the empty-string (U+0000) and multi-unit (first code unit) behaviour.
  • They read instance and static boolean fields.

Results (full suite, runtestsAndVerifyResults, arm64 emulator):

  • Unfixed main with the new specs: 9 new specs failed (41 expectations), and nothing else failed. The plain-string path was probed separately; the values are in the table above.
  • With the fix: 1785 specs, 0 failures, 6 pending.

Summary by CodeRabbit

  • Bug Fixes
    • Java char values now convert consistently using UTF-16 code units, including non-ASCII characters and surrogate pairs. Empty strings map to NUL, and longer strings use their first code unit.
    • Improved character conversion across method calls, arrays, fields, and callbacks.
    • Fixed reading boolean fields from Java objects.

Several JS-to-Java char conversions went through UTF-8 and kept a single
byte, so a non-ASCII value reached Java wrong: char("é") as a method
argument arrived as 195 and char("€") as 226, the same happened for char
fields and for char() values returned from JS callbacks, and a JS array
converted to char[] or a char[] element set reinterpreted the first two
UTF-8 bytes as one UTF-16 unit before taking a byte of it ("é" became
234, "€" 232). Reading a char[] element handed V8 one UTF-8 byte and
produced U+FFFD.

A plain JS string passed to a non-overloaded char parameter was
converted to a java.lang.String whose local reference was then read
through the jvalue's char member, so even "x" arrived as an arbitrary
value.

These paths now share ArgConverter::ToJavaChar, which takes the first
UTF-16 code unit of the JS string (U+0000 for an empty string, the high
surrogate for a character outside the BMP), and the char[] element read
uses jcharToV8String like the method-return, field-get and callback
argument paths already did. Affected: char() cast arguments, plain
string arguments to char parameters, JS array to char[], char[] element
get and set, char field set, and char() values returned from JS
callbacks.
GetJavaField escapes every result from its EscapableHandleScope except
the boolean one, which it returned as a handle created inside the
closed scope. V8's Boolean::New returns a root-table slot today, so the
handle stays valid in practice, but the API does not promise that;
escape it like the other branches.
…d reads

Specs pass U+00E9, U+20AC, U+4E2D, a lone high surrogate, an ASCII
control and ASCII through every char path: char() and plain string
arguments, char return values, JS array to char[], char[] element get
and set, instance and static char fields, and a char() value returned
from a JS callback. Java-side values are read back as ints and the
element read uses a Java-created char[], so a broken direction cannot
be masked by the opposite one. They also pin the empty-string (U+0000)
and multi-unit (first code unit) behaviour, and read instance and static
boolean fields.
@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The runtime now converts Java char values using UTF-16 code units across argument, array, and field access. Java test helpers and JavaScript tests cover scalar values, arrays, fields, callbacks, and boolean field access.

Changes: Java char conversion

Layer / File(s) Summary
String-to-char argument conversion
test-app/runtime/src/main/cpp/ArgConverter.h, test-app/runtime/src/main/cpp/JsArgConverter.cpp, test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp
ToJavaChar returns zero for an empty string or the first UTF-16 code unit otherwise. Argument conversion uses it for char casts, scalar strings, and char arrays.
Array and field access
test-app/runtime/src/main/cpp/ArrayElementAccessor.cpp, test-app/runtime/src/main/cpp/FieldAccessor.cpp
Character array and field access use UTF-16 code units. Boolean field reads escape the converted value into the V8 handle scope.
Java test bridge and conversion tests
test-app/app/src/main/java/com/tns/tests/CharConversionTest.java, test-app/app/src/main/assets/app/tests/testPrimitiveTypeConversion.js
Java helpers expose char values, arrays, fields, and callbacks. JavaScript tests cover UTF-16 code units, empty and longer strings, boxed strings, and boolean fields.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: darind

Merge Risk: Minimal · up to a13cd

This change fixes JavaScript-to-Java char conversion so it uses UTF-16 code units and escapes the boolean field-read result. It adds tests for these cases. No actionable merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: Java char values are now converted as UTF-16 code units instead of through UTF-8. The changed files (ArgConverter.h ToJavaChar, JsArgConverter, JsArgToArrayConverter, …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: Java char values are now converted as UTF-16 code units instead of through UTF-8. The changed files (ArgConverter.h ToJavaChar, JsArgConverter, JsArgToArrayConverter, ArrayElementAccessor, FieldAccessor) and the objectives all match this. The title also uses the conventional fix(runtime) prefix. It does not mention the GetJavaField boolean escape fix or the new tests, which is expected for a single-sentence title.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b96e522 and a13cd83.

Files selected for processing: 7

  • test-app/app/src/main/assets/app/tests/testPrimitiveTypeConversion.js
  • test-app/app/src/main/java/com/tns/tests/CharConversionTest.java
  • test-app/runtime/src/main/cpp/ArgConverter.h
  • test-app/runtime/src/main/cpp/ArrayElementAccessor.cpp
  • test-app/runtime/src/main/cpp/FieldAccessor.cpp
  • test-app/runtime/src/main/cpp/JsArgConverter.cpp
  • test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@edusperoni
edusperoni marked this pull request as ready for review November 21, 2026 18:41
@edusperoni
edusperoni merged commit 48d1fb1 into main Nov 21, 2026
8 checks passed
@edusperoni
edusperoni deleted the fix/char-conversion-and-field-handle branch November 21, 2026 18:53
edusperoni added a commit that referenced this pull request Nov 21, 2026
### Description

A batch of small, mechanical cuts to per-call work on the JS ↔ Java
bridge: heap allocations, string copies, thread-local reads, out-of-line
trivial calls and lookups repeated within one call. No locks, copies or
process-wide `Isolate*`-keyed state are added; the new per-isolate state
goes through `V8StringConstants` and `MetadataNodeCache` like the
existing keys.

**Allocations and copies** (`perf(runtime): drop per-call copies and
dead work on the call paths`)
- `JsArgConverter::ConvertArg` zero-filled a 1 KB error buffer for every
argument; it is now only NUL-terminated (every reader uses the C
string).
- The object/cast branch of `ConvertArg` created an unused `JEnv` and
looked up the runtime for every object argument. The object manager is
now resolved once per converter, and only for a plain object argument.
The destructor skips its `JEnv` when no local refs were recorded.
- `instrumentation::Frame` copied its name into a `std::string`, so
every `TNSPERF()` frame heap-allocated for names longer than the SSO
buffer, even with instrumentation off. These frames cover the class,
extended-class and interface constructors and `GetImplementationObject`.
Literal and `__func__` names are now kept as pointers; dynamic names
still own a copy.
- The class, extended-class and interface constructor callbacks copied
their class names on every `new`. They now pass the stored names by
reference, and build the `-defaults` name only when it is needed.

**TLS / isolate passing** (`perf(runtime): pass the isolate instead of
reading it from TLS`)
- `ArgConverter::ConvertToJavaString`, `NumericCasts::GetCastValue`,
`MetadataNode::GetNodeFromHandle`, the single-value
`JsArgToArrayConverter` and the array element accessors now take the
isolate from their callers instead of calling `Isolate::GetCurrent()`
(emulated TLS below API 29).
- `CallJavaMethod` looked the runtime up twice per call; it reuses the
first lookup.
- The instance field getter and setter looked up the runtime only to
call the static `ObjectManager::IsJsRuntimeObject`.

**Inlining** (`perf(runtime): inline trivial accessors used on every
bridge call`)
- `Runtime::GetIsolate/GetJavaRuntime/GetObjectManager/GetContext/GetId`
and `JEnv`'s `JNIEnv*` conversion are now inline. The `Runtime`
definitions sit after the class body, and its declarations are
unchanged.
- The `MetadataEntry` getters now inline only the check for an
already-read value; reading the metadata stays out of line.

**Return values and array elements** (`perf(runtime): cheaper JS -> Java
return values and array element access`)
- Returning a JS value to Java used to cost a `new jobject[1]`, a vector
push, a `DeleteGlobalRef(nullptr)`, and a `NewLocalRef` +
`DeleteLocalRef` pair. The single-value converter now writes into an
inline slot. `ConvertJsValueToJavaObject` takes the converted local ref
over through `ReleaseConvertedArg()`; a borrowed (global/weak) ref is
still copied into a new local, as before.
- `CreateJSInstanceNative` no longer reads the instance's class name
back through `GetObjectClass` + `Class.getName()`. Java already passes
`instance.getClass().getName()`, which is the same name.
- Java array element access copied the element signature and compared it
against up to nine strings per access. It now switches on the element
type.
- Object elements go through `ObjectManager::GetOrCreateJSWrapper`, as
method results and field reads do. This replaces `GetOrCreateObjectId` +
`GetClassName` + a node lookup under the global node mutex.

**Caching** (`perf(runtime): cache per-isolate keys and names used per
access`)
- The implementation-object, `supervalue` and `typemetadata` private
keys were rebuilt from strings, and resolved through V8's private-symbol
registry, on every constructor call, `super` read and `GetTypeMetadata`.
They are now created once per isolate in `V8StringConstants`.
`Private::ForApi` on the same names returns the same symbols.
- Kotlin property accessors copied the accessor's method name and
created a new V8 string on every get and set. `PropertyCallbackData` now
holds the internalized names. **No spec reaches this path:** the Kotlin
property specs in `tests/kotlin/properties/testPropertiesSupport.js` are
commented out. I re-enabled "Test Kotlin public properties should work"
locally, and it fails here the same way it is expected to fail on
`main`: the property reads as `undefined`, because no accessor is
installed in the test app. The `@get:JvmName` spec calls methods, not
properties.
- `CreateArrayWrapper` took the global node mutex to look up
`java/lang/Object` for every Java array it wrapped. Nodes are
process-wide and never freed, so the pointer is resolved once.
- `MethodCallback` decoded its `External` twice.

#### Not changed (from the audit list)
- `CanBeJavaString` (6 compares per object-returning call) and the `==
"java/lang/String"` per object field access: libc++ compares against a
literal by length first, and the length is constant-folded. That leaves
a handful of integer compares next to a JNI call, so precomputing them
is not worth a new field on
`MetadataEntry`/`CacheMethodInfo`/`FieldCallbackData`.

#### Benchmark rows added
`test(bench): ...` adds `array get int[i]`, `array set int[i]`, `array
get Object[i]` and `callback.objectReturn() -> Object` to the #2092
harness. The base APK below includes them.

#### Measurements

Samsung SM-G780G (Android 13). Optimized release APKs (`-Poptimized
-Prelease -Pabis=arm64-v8a`). The #2092 JNI harness ran with
`debug.ns.jnibench`.
- **Labels:** `base` = `main` plus the bench-row commit; `new` = this
branch; `base2` = the `base` APK under a second label, as an A/A
control.
- **Procedure:** labels interleaved base → new → base2 for 4 rounds.
Every label was reinstalled and speed-compiled each round, and the first
launch after each install was discarded; only the relaunch is measured.
All 12 measured launches were in the same clock state (sentinel row
7.4–8.6 ns).
- **Columns:** each cell is the median over launches of the per-launch
median, in ns/op. "new vs base+base2" compares against the pooled 8 base
launches.

The phone runs predate the rebase onto #2140 and #2143. Neither touches
the measured paths, except `array get Object[i]`: #2143 changes only the
branch for elements that are themselves arrays.

Rows below are **beyond A/A noise**: `new`'s range does not overlap the
pooled base range, and the change is more than twice the A/A delta.

| row | base | base2 (A/A) | new | A/A | new vs base+base2 | new range |
base+base2 range |
|---|---:|---:|---:|---:|---:|---:|---:|
| static.noop() | 104.5 | 104.8 | 90.0 | +0.3% | **-14.0%** | 89.8–90.4
| 104.2–105.1 |
| static.add(int,int) | 186.9 | 187.9 | 146.2 | +0.5% | **-21.8%** |
145.2–146.5 | 186.4–188.8 |
| static.addDouble(double,double) | 230.7 | 233.8 | 198.1 | +1.3% |
**-14.3%** | 197.5–198.6 | 230.1–236.1 |
| static.addLong(long,long) | 195.3 | 194.9 | 155.5 | -0.2% | **-20.2%**
| 155.0–156.5 | 194.6–199.0 |
| instance.noop() | 238.1 | 238.6 | 228.9 | +0.2% | **-3.9%** |
228.5–229.3 | 237.7–239.2 |
| instance.getAlpha() [android.view.View] | 245.3 | 244.2 | 234.9 |
-0.4% | **-4.0%** | 234.3–238.7 | 243.7–246.9 |
| instance.getInt() | 240.1 | 239.2 | 230.0 | -0.4% | **-3.9%** |
228.5–231.1 | 238.7–241.5 |
| instance.getChar() | 253.7 | 252.1 | 242.1 | -0.6% | **-4.1%** |
240.6–243.5 | 251.6–254.5 |
| instance.getString() | 425.6 | 424.8 | 416.4 | -0.2% | **-2.0%** |
412.1–417.6 | 423.7–426.8 |
| instance.self() [wrapped return] | 414.7 | 419.8 | 404.9 | +1.2% |
**-2.5%** | 402.1–407.0 | 412.7–421.9 |
| instance.getOther() [wrapped return] | 412.9 | 416.8 | 403.4 | +0.9% |
**-2.3%** | 400.5–410.5 | 411.4–421.0 |
| instance.takeObject(Object) | 513.6 | 511.0 | 487.1 | -0.5% |
**-4.9%** | 483.9–492.8 | 509.9–519.3 |
| instance.takeObjects(Object x3) | 1078.7 | 1077.8 | 1013.5 | -0.1% |
**-6.0%** | 1008.8–1019.9 | 1074.0–1083.1 |
| static.bufferCapacity(ArrayBuffer) | 443.8 | 444.5 | 412.1 | +0.2% |
**-7.2%** | 401.0–412.3 | 439.1–456.5 |
| static field get int [small class] | 70.9 | 70.9 | 62.3 | +0.1% |
**-12.1%** | 62.1–62.5 | 70.4–71.2 |
| static field get final int [small class] | 70.8 | 70.9 | 62.0 | +0.2%
| **-12.5%** | 61.8–62.3 | 70.5–71.4 |
| static field set int [small class] | 73.5 | 73.3 | 65.2 | -0.3% |
**-11.0%** | 65.1–65.7 | 73.2–74.0 |
| field.get int | 162.6 | 162.1 | 153.1 | -0.3% | **-5.7%** |
151.4–153.6 | 161.5–163.6 |
| field.set int | 162.0 | 162.3 | 152.8 | +0.2% | **-5.8%** |
152.6–153.5 | 161.8–162.5 |
| field.get Object | 333.3 | 331.6 | 321.1 | -0.5% | **-3.4%** |
318.9–324.6 | 327.3–336.9 |
| field.get String | 361.6 | 361.2 | 350.6 | -0.1% | **-3.1%** |
350.1–352.0 | 358.9–364.0 |
| array get int[i] | 231.9 | 233.3 | 215.0 | +0.6% | **-7.4%** |
214.2–215.9 | 230.9–236.5 |
| array set int[i] | 267.2 | 266.4 | 257.5 | -0.3% | **-3.5%** |
256.7–258.7 | 266.1–269.7 |
| array get Object[i] | 408.1 | 405.3 | 363.6 | -0.7% | **-10.7%** |
360.2–369.1 | 401.4–409.8 |
| instance.self() [50k live wrappers] | 417.0 | 422.4 | 406.8 | +1.3% |
**-2.8%** | 403.4–407.1 | 414.8–430.4 |
| contention 1 thread(s), 3 new objects | 8851.6 | 8924.8 | 8308.3 |
+0.8% | **-6.2%** | 8146.3–8474.8 | 8582.3–9704.9 |


Static calls get the most out of the 1 KB `memset` per argument and the
inlined `MetadataEntry` getters. The array rows show the element-type
switch and the `GetOrCreateJSWrapper` path.

**Within noise:**
- The first-access rows: one sample per launch, with A/A up to ±20%.
- Object creation and lifecycle rows.
- `instance.echo(String 1KB)`, which is bimodal in all three labels.
- Contention rows other than the one above.
- **Callbacks: the harness cannot resolve them.** Callback rows divided
by the reference callback show A/A of 15–24%, and raw callback medians
and the raw reference itself show A/A up to ±27–38%. So the Java → JS
return-value change (`callback.objectReturn() -> Object`: −1.7% raw,
−3.9% normalized) is not measured by this harness. Note too that the
reference callback goes through the same code, so normalizing by it
would cancel out any change that speeds up every callback.

### Does your commit message include the wording below to reference a
specific issue in this repo?
No.

### Related Pull Requests
- **Stacked on #2143** (`fix/nested-object-array-element`), which fixes
the crash reading elements of nested object arrays. This PR's base is
that branch, so the diff here shows only the perf changes. Once #2143
lands I'll rebase this branch onto `main` and retarget it.
- #2137 also touches `Runtime.h` and `MethodCache.cpp`. This branch
leaves the `Runtime.h` declarations alone, puts its inline definitions
after the class, and merges cleanly with #2137 (`git merge-tree`).
- Rebased onto `main` after #2140. #2140's char conversions
(`ArgConverter::ToJavaChar`, `jcharToV8String` for element reads) and
the boolean-field `Escape` are kept as they are.

### Does your pull request have [unit
tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)?
No new specs: these are behavior-preserving changes, covered by the
existing suite. The full suite (`./gradlew runtestsAndVerifyResults`,
arm64 emulator, android-36.1 google_apis image) passes on the rebased
branch: 1788 specs, 0 failures.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Added Java array benchmarks for indexed integer reads and writes,
object reads, and callbacks returning objects.
* **Bug Fixes**
* Improved Java array access and value conversion, including handling
primitive values and null references.
* Improved management of converted Java references during calls between
JavaScript and Java.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant