From 3b1f8c808344c172ea0119f1ae21d6d65d7c829f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:04:43 -0300 Subject: [PATCH 1/7] fix(DexFactory): derive the jar path by replacing only the .dex suffix The jar path was built with getPath().replace(".dex", ".jar"), which rewrites every ".dex" in the absolute path, not just the extension. The path starts with the app's data directory, so an application id with a segment beginning with "dex" (com.example.dexter) pointed every jar into a directory that does not exist and no class could be generated at runtime. A named proxy whose package segment begins with "dex" got a jar name that another class could also map to. Replace only the trailing ".dex". --- test-app/runtime/src/main/java/com/tns/DexFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-app/runtime/src/main/java/com/tns/DexFactory.java b/test-app/runtime/src/main/java/com/tns/DexFactory.java index d913a023b..8e5215cb6 100644 --- a/test-app/runtime/src/main/java/com/tns/DexFactory.java +++ b/test-app/runtime/src/main/java/com/tns/DexFactory.java @@ -155,7 +155,7 @@ public Class resolveClass(String baseClassName, String name, String className } // creates jar file from already generated dex file - String jarFilePath = dexFile.getPath().replace(".dex", ".jar"); + String jarFilePath = dexFile.getPath().replaceFirst("\\.dex$", ".jar"); File jarFile = new File(jarFilePath); if (!jarFile.exists()) { From d49d86bc460a955089ec9f8d5059bbe5033cf8e3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:08:08 -0300 Subject: [PATCH 2/7] fix(JEnv): do not cache a class that failed to resolve When JNI FindClass and Runtime.getCachedClass both missed, FindClass stored nullptr in the process-wide class cache. Lookups treat a cached nullptr as a miss, so the name crossed JNI on every later lookup, and a class that appeared afterwards (generated at runtime or injected) could never be cached: emplace found the null entry, so InsertClassIntoCache returned a fresh global reference that it neither stored nor freed, leaking one global reference per lookup. Return before creating a global reference when there is no class. The cache hit path is unchanged, and callers already handle a null result. --- test-app/runtime/src/main/cpp/JEnv.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test-app/runtime/src/main/cpp/JEnv.cpp b/test-app/runtime/src/main/cpp/JEnv.cpp index f7104c3d8..42ec92444 100644 --- a/test-app/runtime/src/main/cpp/JEnv.cpp +++ b/test-app/runtime/src/main/cpp/JEnv.cpp @@ -776,6 +776,11 @@ jclass JEnv::CheckForClassInCache(const string &className) { } jclass JEnv::InsertClassIntoCache(const string &className, jclass &tmp) { + // A class missing now can still be generated or injected later, so a miss is never cached. + if (tmp == nullptr) { + return nullptr; + } + auto global_class = reinterpret_cast(m_env->NewGlobalRef(tmp)); m_env->DeleteLocalRef(tmp); From 24fad7492b41934cd72840257a9bd159302b4f75 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:11:09 -0300 Subject: [PATCH 3/7] fix(bindings): keep proxy generator scratch state per call Every runtime (main and each worker) has its own DexFactory, ProxyGenerator and Dump and can generate a proxy on its own thread, but Dump kept its scratch state in statics shared by all of them: - methodDescriptorBuilder, a static StringBuffer reset with setLength(0) and read back with toString() for every method and constructor descriptor. Two generations at once interleave and bake another method's descriptor into the class. - interfaceImplementedInterfaces, a static array whose last slot was overwritten with the interface being implemented and then iterated, so an interface proxy could implement another thread's interface. Neither raises an error at generation time: the dex is written, cached and reused, and only behaves wrongly when called. With the new JVM test, 8 threads generating 13 proxies concurrently failed on every run of the old code (an asmdex NullPointerException from a duplicated method, or a hang); with the fix the output is byte-identical to sequential generation. Build the descriptors in a local buffer and add the implemented interface to the per-call list directly. Nothing else reachable from Dump holds mutable static state: asmdex's static Label counter only feeds toString(), and its static instruction pool and shared empty annotation set are never reached by the proxy generator. --- .../src/main/java/com/tns/bindings/Dump.java | 17 +-- .../com/tns/bindings/DumpConcurrencyTest.java | 120 ++++++++++++++++++ 2 files changed, 125 insertions(+), 12 deletions(-) create mode 100644 test-app/runtime/src/test/java/com/tns/bindings/DumpConcurrencyTest.java diff --git a/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java b/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java index d2c253cdf..79d959b23 100644 --- a/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java +++ b/test-app/runtime-binding-generator/src/main/java/com/tns/bindings/Dump.java @@ -26,9 +26,6 @@ public class Dump { static final String RUNTIME_TAG_FIELD_NAME = "runtimeTag__ns"; static final String OBJECT_ID_FIELD_NAME = "objectId__ns"; - static final StringBuffer methodDescriptorBuilder = new StringBuffer(); - - /** * Returns the dex descriptor corresponding to the given method. * @@ -38,7 +35,7 @@ public class Dump { */ public String getDexMethodDescriptor(final MethodDescriptor method) { ClassDescriptor[] parameters = method.getParameterTypes(); - methodDescriptorBuilder.setLength(0); + StringBuffer methodDescriptorBuilder = new StringBuffer(); getDexDescriptor(methodDescriptorBuilder, method.getReturnType()); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); @@ -55,7 +52,7 @@ public String getDexMethodDescriptor(final MethodDescriptor method) { */ public String getMethodOverloadDescriptor(final MethodDescriptor method) { ClassDescriptor[] parameters = method.getParameterTypes(); - methodDescriptorBuilder.setLength(0); + StringBuffer methodDescriptorBuilder = new StringBuffer(); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); } @@ -71,7 +68,7 @@ public String getMethodOverloadDescriptor(final MethodDescriptor method) { */ public String getDexConstructorDescriptor(final MethodDescriptor constructor) { ClassDescriptor[] parameters = constructor.getParameterTypes(); - methodDescriptorBuilder.setLength(0); + StringBuffer methodDescriptorBuilder = new StringBuffer(); getDexDescriptor(methodDescriptorBuilder, ClassDescriptor.VOID); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); @@ -841,7 +838,6 @@ private void generateFields(ClassVisitor cv) { } static final String[] classImplentedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;" }; - static final String[] interfaceImplementedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;", "" }; private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo, String classSignature, String tnsClassSignature, HashSet implementedInterfaces, AnnotationDescriptor[] annotations) { ClassVisitor cv; @@ -851,11 +847,8 @@ private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo ArrayList interfacesToImplement = new ArrayList(Arrays.asList(classImplentedInterfaces)); if (classTo.isInterface()) { - interfaceImplementedInterfaces[interfaceImplementedInterfaces.length - 1] = classSignature; - for (String interfaceToImpl : interfaceImplementedInterfaces) { - if (!interfacesToImplement.contains(interfaceToImpl)) { - interfacesToImplement.add(interfaceToImpl); - } + if (!interfacesToImplement.contains(classSignature)) { + interfacesToImplement.add(classSignature); } classSignature = objectClass; diff --git a/test-app/runtime/src/test/java/com/tns/bindings/DumpConcurrencyTest.java b/test-app/runtime/src/test/java/com/tns/bindings/DumpConcurrencyTest.java new file mode 100644 index 000000000..65a81033f --- /dev/null +++ b/test-app/runtime/src/test/java/com/tns/bindings/DumpConcurrencyTest.java @@ -0,0 +1,120 @@ +package com.tns.bindings; + +import com.tns.bindings.desc.ClassDescriptor; +import com.tns.bindings.desc.reflection.ClassInfo; + +import org.junit.Test; +import org.ow2.asmdex.ApplicationWriter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +/** + * Every runtime (main and each worker) owns a Dump and can generate on its own + * thread, so concurrent generations must produce exactly the bytes a lone one does. + */ +public class DumpConcurrencyTest { + + private static final Class[] SUBJECTS = { + Runnable.class, + Callable.class, + java.util.Comparator.class, + java.util.Iterator.class, + java.io.Closeable.class, + CharSequence.class, + java.util.function.BiFunction.class, + Object.class, + java.util.AbstractList.class, + java.io.InputStream.class, + java.util.TimerTask.class, + java.io.Writer.class, + java.util.AbstractMap.class, + }; + + private static final int THREADS = 8; + private static final int ROUNDS = 150; + + private static byte[] generate(Dump dump, Class subject) { + ApplicationWriter aw = new ApplicationWriter(); + aw.visit(); + ClassDescriptor descriptor = new ClassInfo(subject); + dump.generateProxy(aw, "DumpConcurrencyTest", descriptor, null, new HashSet(), null); + aw.visitEnd(); + return aw.toByteArray(); + } + + private static byte[][] generateAll(Dump dump) { + byte[][] result = new byte[SUBJECTS.length][]; + for (int i = 0; i < SUBJECTS.length; i++) { + result[i] = generate(dump, SUBJECTS[i]); + } + return result; + } + + @Test + public void sequentialGenerationIsByteStable() { + byte[][] first = generateAll(new Dump()); + byte[][] second = generateAll(new Dump()); + for (int i = 0; i < SUBJECTS.length; i++) { + assertArrayEquals(SUBJECTS[i].getName(), first[i], second[i]); + } + } + + @Test + public void concurrentGenerationMatchesSequentialGeneration() throws Exception { + final byte[][] expected = generateAll(new Dump()); + + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + final CountDownLatch start = new CountDownLatch(1); + List>> results = new ArrayList>>(); + for (int t = 0; t < THREADS; t++) { + final long seed = t; + results.add(pool.submit(new Callable>() { + @Override + public List call() throws Exception { + Dump dump = new Dump(); + Random random = new Random(seed); + List order = new ArrayList(); + for (int i = 0; i < SUBJECTS.length; i++) { + order.add(i); + } + List mismatches = new ArrayList(); + start.await(); + for (int round = 0; round < ROUNDS; round++) { + Collections.shuffle(order, random); + for (int i : order) { + if (!Arrays.equals(expected[i], generate(dump, SUBJECTS[i]))) { + mismatches.add(SUBJECTS[i].getName()); + } + } + } + return mismatches; + } + })); + } + start.countDown(); + + List mismatches = new ArrayList(); + for (Future> result : results) { + mismatches.addAll(result.get(5, TimeUnit.MINUTES)); + } + assertEquals("proxies generated concurrently differ from sequential ones: " + mismatches, 0, mismatches.size()); + } finally { + pool.shutdownNow(); + } + } +} From 7b7e1aede9a319d237dc61de709c9fba1a9eeb86 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:11:36 -0300 Subject: [PATCH 4/7] fix(classloading): iterate class loaders without racing their registration ClassStorageServiceImpl.retrieveClass walks the registered class loaders on every lookup miss, through an unmodifiable view of a Collections.synchronizedSet, without holding the set's lock. Every class a runtime generates registers its loader through storeClass, from that runtime's thread, so a worker generating a proxy while another runtime missed a lookup could throw ConcurrentModificationException out of class resolution. Back the collection with a CopyOnWriteArraySet: iteration walks a snapshot, so no lock is held across loadClass calls on arbitrary loaders, and registering a loader that is already present (the app loader, for every injected class) does not copy. The new test, which iterates while another thread registers loaders, failed with ConcurrentModificationException before this change. --- .../impl/ClassLoadersCollectionImpl.java | 6 ++-- .../impl/ClassLoadersCollectionImplTest.java | 35 ++++++++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/test-app/runtime/src/main/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImpl.java b/test-app/runtime/src/main/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImpl.java index f7007b723..0d5e67503 100644 --- a/test-app/runtime/src/main/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImpl.java +++ b/test-app/runtime/src/main/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImpl.java @@ -4,14 +4,16 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; public enum ClassLoadersCollectionImpl implements ClassLoadersCollection { INSTANCE; - private Set classLoaders = Collections.synchronizedSet(new HashSet()); + // Iterated on every class lookup miss by any runtime's thread while another may be adding a + // loader; loaders are added rarely, so iteration works on a snapshot instead of a lock. + private final Set classLoaders = new CopyOnWriteArraySet(); @Override public void addClassLoader(ClassLoader classLoader) { diff --git a/test-app/runtime/src/test/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImplTest.java b/test-app/runtime/src/test/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImplTest.java index 685db5335..4856c5bb2 100644 --- a/test-app/runtime/src/test/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImplTest.java +++ b/test-app/runtime/src/test/java/com/tns/system/classloaders/impl/ClassLoadersCollectionImplTest.java @@ -5,6 +5,8 @@ import org.junit.Test; import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -30,4 +32,35 @@ public void testGetClassLoadersCollectionIsImmutable() { assertEquals("Unexpected collection type", "UnmodifiableCollection", classLoaders.getClass().getSimpleName()); } -} \ No newline at end of file + + @Test + public void testIteratingWhileAnotherThreadAddsClassLoaders() throws InterruptedException { + final AtomicBoolean adding = new AtomicBoolean(true); + Thread writer = new Thread(new Runnable() { + @Override + public void run() { + try { + for (int i = 0; i < 2000; i++) { + classLoadersCollection.addClassLoader(new ClassLoader(null) { + }); + } + } finally { + adding.set(false); + } + } + }); + writer.start(); + + try { + while (adding.get()) { + for (ClassLoader classLoader : classLoadersCollection.getClassLoadersCollection()) { + classLoader.getParent(); + } + } + } catch (ConcurrentModificationException e) { + fail("Iterating the class loaders failed while another thread added one: " + e); + } finally { + writer.join(); + } + } +} From 1149832811fc6c3c88cd34a33d1b6c434e38a7a3 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:11:50 -0300 Subject: [PATCH 5/7] fix(ClassResolver): test binding class names with DexFactory's prefix ClassResolver treated a name as a binding class when it started with "com.tns.gen", without the trailing dot DexFactory uses, so a name such as com.tns.generated.Foo was a binding class to one and a named proxy to the other. Use DexFactory's COM_TNS_GEN_PREFIX in both places. Such a name is now looked up like any other named proxy (class cache and known class loaders first, then the "not precompiled" warning and runtime generation); DexFactory already generated it as a named proxy, so the class that results is the same. The "&& !startsWith(\"com.tns.tests.\")" clause is removed with it. It has been dead since the binding prefix changed from "com.tns." to "com.tns.gen" in 2015: no name can start with both. A missing com.tns.tests.* class follows the same named-proxy path as any other missing dotted name, with or without the clause. --- test-app/runtime/src/main/java/com/tns/ClassResolver.java | 2 +- test-app/runtime/src/main/java/com/tns/DexFactory.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test-app/runtime/src/main/java/com/tns/ClassResolver.java b/test-app/runtime/src/main/java/com/tns/ClassResolver.java index 538a69739..bad335319 100644 --- a/test-app/runtime/src/main/java/com/tns/ClassResolver.java +++ b/test-app/runtime/src/main/java/com/tns/ClassResolver.java @@ -21,7 +21,7 @@ Class resolveClass(String baseClassName, String fullClassName, DexFactory dex String className = canonicalClassName; Class clazz = null; - boolean isBindingClass = canonicalClassName.startsWith("com.tns.gen") && !canonicalClassName.startsWith("com.tns.tests."); + boolean isBindingClass = canonicalClassName.startsWith(DexFactory.COM_TNS_GEN_PREFIX); // if binding generate proxy or load pregenerated if (isBindingClass) { diff --git a/test-app/runtime/src/main/java/com/tns/DexFactory.java b/test-app/runtime/src/main/java/com/tns/DexFactory.java index 8e5215cb6..285c21928 100644 --- a/test-app/runtime/src/main/java/com/tns/DexFactory.java +++ b/test-app/runtime/src/main/java/com/tns/DexFactory.java @@ -33,7 +33,7 @@ import dalvik.system.DexClassLoader; public class DexFactory { - private static final String COM_TNS_GEN_PREFIX = "com.tns.gen."; + static final String COM_TNS_GEN_PREFIX = "com.tns.gen."; private final Logger logger; private final File dexDir; From e939ce1b25cd8f7b591ba8367dc4e187dfac9903 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:20:16 -0300 Subject: [PATCH 6/7] fix(MetadataNode): validate dotted extend() names extend("a.b.C", {...}) and @JavaProxy("a.b.C") skipped name validation entirely: ValidateExtendArguments only runs for undotted names. A name no class can have (an empty part, or a character a dex class name cannot contain) went on to proxy generation and failed later with an unrelated error, or produced a class that could not be loaded. Check dotted names against the dex 035 SimpleName rules the proxy generator writes: every part must be non-empty and contain only ASCII letters, digits, '$', '-', '_', or code points in U+00A1-U+1FFF, U+2010-U+2027, U+2030-U+D7FF, U+E000-U+FFEF or U+10000-U+10FFFF. Anything else throws a JS error naming the name and the offending character. Parts are split on '/' as well as '.', since ClassResolver already resolves "a.b/C" as a.b.C. A part that is a valid dex name but not a Java identifier (it starts with a digit or contains '-') still works when the class is generated at runtime, so it only logs a warning that the static binding generator cannot compile it. Reserved words are accepted silently. The extend-name specs had been commented out, and their require disabled, because the static binding generator failed the build on their invalid names. They now call extend() through a computed member, which the generator does not scan, and cover the rejected shapes and the accepted ones that work today (digit-leading, dashed, reserved-word, non-ASCII and '/'-separated parts). --- test-app/app/src/main/assets/app/mainpage.js | 2 +- .../assets/app/tests/extendClassNameTests.js | 131 ++++++++++++------ .../runtime/src/main/cpp/MetadataNode.cpp | 76 ++++++++++ 3 files changed, 167 insertions(+), 42 deletions(-) diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 8227c792e..e5577e226 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -61,7 +61,7 @@ require("./tests/testGC"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); -//require("./tests/extendClassNameTests"); // as tests now run with SBG, this test fails the whole build process +require("./tests/extendClassNameTests"); require("./tests/testJniReferenceLeak"); require("./tests/testNativeModules"); require("./tests/requireExceptionTests"); diff --git a/test-app/app/src/main/assets/app/tests/extendClassNameTests.js b/test-app/app/src/main/assets/app/tests/extendClassNameTests.js index 215edd9f0..f40d97144 100644 --- a/test-app/app/src/main/assets/app/tests/extendClassNameTests.js +++ b/test-app/app/src/main/assets/app/tests/extendClassNameTests.js @@ -1,43 +1,92 @@ +// extend() is called through a computed member so the static binding generator skips +// these call sites: it would try, and fail, to compile a class for each name. describe("Tests extend class name ", function () { - var myCustomEquality = function(first, second) { - return first == second; - }; - - beforeEach(function() { - jasmine.addCustomEqualityTester(myCustomEquality); - }); - - //the class name valid symbols are [a-z , A-Z , 0-9, _] -// it("When_naming_extension_class_user_should_give_valid_name", function () { -// -// var exceptionCaught = false; -// try -// { -// var O = java.lang.Object.extend("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", {}); -// } -// catch(e) -// { -// exceptionCaught = true; -// __log("Validation is wrong"); -// } -// -// expect(exceptionCaught).toBe(false); -// }); -// -// it("When_naming_extension_contains_invalid_symbols_should_throw_exception", function () { -// -// var exceptionCaught = false; -// try -// { -// var O = java.lang.Object.extend("1235!", {}); //[!] is invalid symbol -// } -// catch(e) -// { -// __log('message: ' + e.message); -// exceptionCaught = true; -// } -// -// expect(exceptionCaught).toBe(true); -// }); -}); \ No newline at end of file + function extendObject(name, implementation) { + return java.lang.Object["extend"](name, implementation); + } + + function expectRejected(name) { + var message = null; + try { + extendObject(name, {}); + } catch (e) { + message = e.message; + } + expect(message).not.toBeNull(); + expect(message).toContain(name); + } + + // the class name valid symbols are [a-z , A-Z , 0-9, _] + it("When_naming_extension_class_user_should_give_valid_name", function () { + expect(function () { + extendObject("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", {}); + }).not.toThrow(); + }); + + it("When_naming_extension_contains_invalid_symbols_should_throw_exception", function () { + expect(function () { + extendObject("1235!", {}); + }).toThrowError(/invalid symbols/); + }); + + it("rejects a dotted name with an empty part", function () { + expectRejected("com.tns.tests.extendname..Empty"); + expectRejected(".com.tns.tests.extendname.Leading"); + expectRejected("com.tns.tests.extendname/.Slash"); + expectRejected("com.tns.tests.extendname.Trailing."); + }); + + it("rejects a dotted name with a character no class name can contain", function () { + expectRejected("com.tns.tests.extendname.Has Space"); + expectRejected("com.tns.tests.extendname.Has;Semicolon"); + expectRejected("com.tns.tests.extendname.Has[Bracket"); + expectRejected("com.tns.tests.extendname.Has"); + expectRejected("com.tns.tests.extendname.No\u00A0Break"); + expectRejected("com.tns.tests.extendname.Zero\u200BWidth"); + }); + + function expectWorkingClass(name, className) { + className = className || name; + var Extended = extendObject(name, { + toString: function () { + return "from " + name; + } + }); + var instance = new Extended(); + + expect(instance.getClass().getName()).toBe(className); + // Objects.toString calls toString() from Java, through the generated class. + expect(java.util.Objects.toString(instance)).toBe("from " + name); + } + + it("generates a class for a dotted name whose part starts with a digit", function () { + expectWorkingClass("com.tns.tests.extendname.1LeadingDigit"); + }); + + it("generates a class for a dotted name whose part contains a dash", function () { + expectWorkingClass("com.tns.tests.extend-name.Dashed"); + }); + + it("generates a class for a dotted name whose part is a Java reserved word", function () { + expectWorkingClass("com.tns.tests.extendname.int"); + }); + + it("generates a class for a dotted name with a non-ASCII letter", function () { + expectWorkingClass("com.tns.tests.extendname.Caf\u00E9"); + }); + + it("does not reject a dotted name with a supplementary-plane letter", function () { + var message = null; + try { + extendObject("com.tns.tests.extendname.Script\uD835\uDC9C", {}); + } catch (e) { + message = e.message; + } + expect(message === null ? "" : message).not.toContain("Invalid extend() name"); + }); + + it("reads a '/' in a dotted name as a package separator", function () { + expectWorkingClass("com.tns.tests.extendname/Slashed", "com.tns.tests.extendname.Slashed"); + }); +}); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 41e0e797e..c8f9b84ba 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -1788,6 +1788,79 @@ void MetadataNode::PackageGetterCallback(Local property, const PropertyCal } } +// SimpleNameChar of the dex 035 format the proxy generator writes. Later formats add only +// space characters, which no Java identifier can contain either. +static bool IsDexSimpleNameChar(uint32_t c) { + if (c < 0x80) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '$' || c == '-' || c == '_'; + } + return (c >= 0xA1 && c <= 0x1FFF) || (c >= 0x2010 && c <= 0x2027) || + (c >= 0x2030 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFEF) || + (c >= 0x10000 && c <= 0x10FFFF); +} + +// Rejects only names no class can have. A part that is a dex name but not a Java +// identifier still generates at runtime; the static binding generator cannot compile it. +static void ValidateDottedExtendName(const string& name) { + bool isJavaName = true; + size_t partStart = 0; + while (true) { + // ClassResolver reads '/' as '.'. + size_t partEnd = name.find_first_of("./", partStart); + if (partEnd == string::npos) { + partEnd = name.size(); + } + if (partEnd == partStart) { + throw NativeScriptException("Invalid extend() name \"" + name + "\": a class name cannot have an empty part between dots."); + } + + string part = name.substr(partStart, partEnd - partStart); + for (size_t i = 0; i < part.size();) { + unsigned char lead = part[i]; + uint32_t c; + size_t length; + if (lead < 0x80) { + c = lead; + length = 1; + } else if ((lead & 0xE0) == 0xC0) { + c = lead & 0x1F; + length = 2; + } else if ((lead & 0xF0) == 0xE0) { + c = lead & 0x0F; + length = 3; + } else { + c = lead & 0x07; + length = 4; + } + for (size_t k = 1; k < length && i + k < part.size(); k++) { + c = (c << 6) | (static_cast(part[i + k]) & 0x3F); + } + if (!IsDexSimpleNameChar(c)) { + char codePoint[16]; + snprintf(codePoint, sizeof(codePoint), "U+%04X", c); + throw NativeScriptException("Invalid extend() name \"" + name + "\": \"" + part + "\" contains a character a class name cannot contain (" + codePoint + ")."); + } + i += length; + } + + if ((part[0] >= '0' && part[0] <= '9') || part.find('-') != string::npos) { + isJavaName = false; + } + + if (partEnd == name.size()) { + break; + } + partStart = partEnd + 1; + } + + if (!isJavaName) { + __android_log_print(ANDROID_LOG_WARN, "JS", + "extend() name \"%s\" is not a Java class name (a part starts with a digit or contains '-'). The static binding generator cannot compile it, so the class is only ever generated at runtime.", + name.c_str()); + } +} + bool MetadataNode::ValidateExtendArguments(const FunctionCallbackInfo& info, bool extendLocationFound, string& extendLocation, v8::Local& extendName, Local& implementationObject, bool isTypeScriptExtend) { auto isolate = info.GetIsolate(); @@ -1908,6 +1981,9 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfo()); hasDot = strName.find('.') != string::npos; + if (hasDot) { + ValidateDottedExtendName(strName); + } } else if (info.Length() == 3) { auto context = isolate->GetCurrentContext(); if (info[2]->IsBoolean() && info[2]->BooleanValue(isolate)) { From 95dc96711227b5809788ef0801bc6a054efaccaf Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 01:20:16 -0300 Subject: [PATCH 7/7] test: generate proxies in several runtimes at once Three workers and the main runtime each generate six named proxies at the same moment (interfaces and classes, with int, long, Object, boolean and void signatures) and have Java call every overridden method through the generated classes, so a class baked with another generation's descriptors or interface fails the spec. The names are per runtime and extend() is called through a computed member, so every class is generated at runtime by the runtime that asks for it. --- test-app/app/src/main/assets/app/mainpage.js | 1 + .../assets/app/tests/proxyGenerationJob.js | 104 ++++++++++++++++++ .../assets/app/tests/proxyGenerationWorker.js | 9 ++ .../tests/testConcurrentProxyGeneration.js | 64 +++++++++++ 4 files changed, 178 insertions(+) create mode 100644 test-app/app/src/main/assets/app/tests/proxyGenerationJob.js create mode 100644 test-app/app/src/main/assets/app/tests/proxyGenerationWorker.js create mode 100644 test-app/app/src/main/assets/app/tests/testConcurrentProxyGeneration.js diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index e5577e226..6c8d5c2db 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -125,6 +125,7 @@ require('./tests/testWorkerEsmEntry'); require('./tests/testWorkerLifetime'); // Java->JS calls route to the runtime that created the object require('./tests/testRuntimeBoundDispatch'); +require('./tests/testConcurrentProxyGeneration'); // Fetches from the in-app loopback fixture server, so it goes last require('./tests/testEsmHttpLoader'); // Node-API addon surface diff --git a/test-app/app/src/main/assets/app/tests/proxyGenerationJob.js b/test-app/app/src/main/assets/app/tests/proxyGenerationJob.js new file mode 100644 index 000000000..8dee96d0e --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/proxyGenerationJob.js @@ -0,0 +1,104 @@ +// Generates a set of named proxies unique to `tag` and has Java call every overridden +// method through each generated class. Returns a description of every check that failed. +// +// extend() is called through a computed member so the static binding generator does not +// precompile these classes: they must be generated at runtime by the calling runtime. +module.exports = function generateAndCallProxies(tag) { + var failures = []; + var prefix = "com.tns.tests.proxygen." + tag + "."; + + function check(what, actual, expected) { + if (actual !== expected) { + failures.push(tag + " " + what + ": expected " + expected + ", got " + actual); + } + } + + function attempt(what, body) { + try { + body(); + } catch (e) { + failures.push(tag + " " + what + " threw: " + e); + } + } + + attempt("Comparator", function () { + var ByLength = java.util.Comparator["extend"](prefix + "ByLength", { + compare: function (a, b) { + return a.length - b.length; + } + }); + var list = java.util.Arrays.asList(["aa", "a", "aaaa", "aaa"]); + check("Collections.max(compare)", java.util.Collections.max(list, new ByLength()), "aaaa"); + }); + + attempt("Callable", function () { + var Answer = java.util.concurrent.Callable["extend"](prefix + "Answer", { + call: function () { + return "called " + tag; + } + }); + var task = new java.util.concurrent.FutureTask(new Answer()); + task.run(); + check("FutureTask.get(call)", task.get(), "called " + tag); + }); + + attempt("Runnable", function () { + var ran = false; + var Task = java.lang.Runnable["extend"](prefix + "Task", { + run: function () { + ran = true; + } + }); + new java.lang.Thread(new Task()).run(); + check("Thread.run(run)", ran, true); + }); + + attempt("InputStream", function () { + var Stream = java.io.InputStream["extend"](prefix + "Stream", { + read: function () { + return 42; + }, + skip: function (n) { + return n * 2; + }, + available: function () { + return 5; + } + }); + var stream = new java.io.PushbackInputStream(new Stream()); + check("read()", stream.read(), 42); + check("skip(long)", stream.skip(21), 42); + check("available()", stream.available(), 5); + }); + + attempt("OutputStream", function () { + var written = []; + var Sink = java.io.OutputStream["extend"](prefix + "Sink", { + write: function (b) { + written.push(b); + } + }); + new java.io.DataOutputStream(new Sink()).writeShort(0x0102); + check("DataOutputStream.writeShort(write)", written.join(","), "1,2"); + }); + + attempt("Object", function () { + var Value = java.lang.Object["extend"](prefix + "Value", { + toString: function () { + return "value " + tag; + }, + hashCode: function () { + return 1234; + }, + equals: function (other) { + return other === "same"; + } + }); + var value = new Value(); + check("Objects.toString(toString)", java.util.Objects.toString(value), "value " + tag); + check("Objects.hashCode(hashCode)", java.util.Objects.hashCode(value), 1234); + check("Objects.equals(equals)", java.util.Objects.equals(value, "same"), true); + }); + + return failures; +}; diff --git a/test-app/app/src/main/assets/app/tests/proxyGenerationWorker.js b/test-app/app/src/main/assets/app/tests/proxyGenerationWorker.js new file mode 100644 index 000000000..3147c1c2c --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/proxyGenerationWorker.js @@ -0,0 +1,9 @@ +// Entry for testConcurrentProxyGeneration: waits for "go", then generates and calls +// this worker's proxies. +var generateAndCallProxies = require("./proxyGenerationJob"); + +onmessage = function (msg) { + postMessage(generateAndCallProxies(msg.data)); +}; + +postMessage("ready"); diff --git a/test-app/app/src/main/assets/app/tests/testConcurrentProxyGeneration.js b/test-app/app/src/main/assets/app/tests/testConcurrentProxyGeneration.js new file mode 100644 index 000000000..3e8ec62e6 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testConcurrentProxyGeneration.js @@ -0,0 +1,64 @@ +// Every runtime generates proxies with its own generator, on its own thread. Several +// workers and this runtime generate different classes at once; each class must come +// out intact, which Java proves by calling every overridden method through it. +describe("Concurrent runtime proxy generation", function () { + var generateAndCallProxies = require("./proxyGenerationJob"); + var WORKERS = 3; + var DEADLINE_MS = 60000; + + it("generates intact classes in several runtimes at once", function (done) { + var workers = []; + var ready = 0; + var pending = WORKERS; + var failures = []; + var finished = false; + + function finish() { + if (finished) { + return; + } + finished = true; + clearTimeout(timer); + workers.forEach(function (worker) { + worker.terminate(); + }); + expect(failures).toEqual([]); + done(); + } + + var timer = setTimeout(function () { + failures.push(pending + " worker(s) did not report within " + DEADLINE_MS + "ms"); + finish(); + }, DEADLINE_MS); + + function start() { + workers.forEach(function (worker, index) { + worker.postMessage("w" + index); + }); + failures = failures.concat(generateAndCallProxies("main")); + } + + for (var i = 0; i < WORKERS; i++) { + var worker = new Worker("./proxyGenerationWorker.js"); + worker.onmessage = function (msg) { + if (msg.data === "ready") { + if (++ready === WORKERS) { + start(); + } + return; + } + failures = failures.concat(msg.data); + if (--pending === 0) { + finish(); + } + }; + worker.onerror = function (e) { + failures.push("worker error: " + (e && e.message)); + if (--pending === 0) { + finish(); + } + }; + workers.push(worker); + } + }, 90000); +});