From 9225bae6f162ebda32492ea09703e870fefe75a7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 17:24:43 -0300 Subject: [PATCH 1/2] fix(metadata): give runtime-resolved interfaces no base class A type resolved at run time is described by a string whose second line names its superclass. An interface has none, so the line is just "B ", and reading the name out of it left the variable holding the previous token: "I" for a top-level interface, "S" for a nested one. The interface was then linked to whatever that name resolved to. The metadata generator names the primitive int and short nodes "I" and "S", and materializing the "I" node as a class read garbage and crashed (SIGSEGV in MetadataReader::ReadName). An interface is resolved at run time when the metadata lacks it and it is the element type of an array that reaches JS, or the enclosing type of a nested class resolved at run time. The base class name is now read into its own variable, and an empty one leaves the type without a base class. --- test-app/runtime/src/main/cpp/MetadataReader.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test-app/runtime/src/main/cpp/MetadataReader.cpp b/test-app/runtime/src/main/cpp/MetadataReader.cpp index bd6ae10c3..bb92e870a 100644 --- a/test-app/runtime/src/main/cpp/MetadataReader.cpp +++ b/test-app/runtime/src/main/cpp/MetadataReader.cpp @@ -466,11 +466,15 @@ MetadataTreeNode *MetadataReader::GetOrCreateTreeNodeByName(const string &classN getline(s, line); stringstream baseClassLine(line); - baseClassLine >> kind >> name; + // Empty for an interface, which has no superclass. + string baseClassName; + baseClassLine >> kind >> baseClassName; cKind = kind[0]; NS_DCHECK(cKind == 'B'); - baseClass = GetOrCreateTreeNodeByName(name); + if (!baseClassName.empty()) { + baseClass = GetOrCreateTreeNodeByName(baseClassName); + } } // Resolving the base class can release the state lock, so another From 51f10aaa0a11c584965881b3a6596be5075b308c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 17 Nov 2026 17:24:51 -0300 Subject: [PATCH 2/2] fix(metadata): add interface methods to runtime-resolved boot classes A class missing from the build-time metadata, such as the non-public class behind a JDK iterator, is described at run time from the declared methods of each class in its chain. On Android 9, getDeclaredMethods() silently leaves out the members of a boot class that the platform's hidden API lists restrict for apps targeting API 28 or later, even public methods that implement a public interface. ConcurrentHashMap's key, value and entry iterators therefore had no hasNext() or remove() in JS (both are declared on the non-public BaseIterator), and spliterators such as ArrayList's and HashMap's lacked tryAdvance(), forEachRemaining() and estimateSize(). Android 10 and later treat such methods as public API, so the gap was specific to Android 9. For a boot class path class resolved at run time, getTypeMetadata now also lists the public interfaces the class implements, with their super-interfaces, each after its sub-interfaces. Native code installs the instance methods of those interfaces that the build-time metadata has on the class's prototype, under every name its class chain does not already have, reusing each interface's own method entries. A call then looks the method up on the interface, which is public API: looking it up on the concrete class is what Android 9 denies, both to reflection and to JNI lookups made with app code on the stack. An interface the build-time metadata lacks is skipped without being resolved, so no member of a non-SDK interface is exposed. Only names missing from the class chain are added, so nothing that resolved before resolves differently. On every API level a runtime-resolved boot class now also has the interfaces' default methods it does not override, such as Iterator.forEachRemaining() on ConcurrentHashMap's iterators and Comparator.reversed() on String.CASE_INSENSITIVE_ORDER. App and library classes are unchanged: their reflection results are complete. --- .../runtimeTypeInterfaceMethodsWorker.js | 15 ++ .../assets/app/tests/testJavaIterators.js | 227 ++++++++++++++++++ .../java/com/tns/tests/IteratorFixtures.java | 5 + .../runtime/src/main/cpp/MetadataNode.cpp | 95 +++++++- test-app/runtime/src/main/cpp/MetadataNode.h | 4 + .../runtime/src/main/cpp/MetadataReader.cpp | 22 ++ .../runtime/src/main/cpp/MetadataReader.h | 4 + .../src/main/java/com/tns/Runtime.java | 65 ++++- .../java/com/tns/RuntimeTypeMetadataTest.java | 74 ++++++ 9 files changed, 509 insertions(+), 2 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/runtimeTypeInterfaceMethodsWorker.js create mode 100644 test-app/runtime/src/test/java/com/tns/RuntimeTypeMetadataTest.java diff --git a/test-app/app/src/main/assets/app/tests/runtimeTypeInterfaceMethodsWorker.js b/test-app/app/src/main/assets/app/tests/runtimeTypeInterfaceMethodsWorker.js new file mode 100644 index 000000000..2912d0495 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/runtimeTypeInterfaceMethodsWorker.js @@ -0,0 +1,15 @@ +// Drains a ConcurrentHashMap through its non-public key iterator inside a worker, +// whose isolate builds its own prototypes for the runtime-resolved class. +onmessage = function () { + var map = new java.util.concurrent.ConcurrentHashMap(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + var iterator = map.keySet().iterator(); + var drained = []; + while (iterator.hasNext()) { + drained.push(String(iterator.next())); + iterator.remove(); + } + postMessage({ drained: drained.sort(), sizeAfter: map.size() }); +}; diff --git a/test-app/app/src/main/assets/app/tests/testJavaIterators.js b/test-app/app/src/main/assets/app/tests/testJavaIterators.js index 836363884..7b1473440 100644 --- a/test-app/app/src/main/assets/app/tests/testJavaIterators.js +++ b/test-app/app/src/main/assets/app/tests/testJavaIterators.js @@ -186,3 +186,230 @@ describe("Tests Java iterators", function () { expect(items.sort()).toEqual(["a", "b", "c"]); }); }); + +// Non-public JDK classes are described at run time. Android 9 hides some of their +// members from reflection, so the methods of their public interfaces fill the gaps. +describe("Tests interface methods of runtime-resolved JDK types", function () { + var sdk = android.os.Build.VERSION.SDK_INT; + + function concurrentMap() { + var map = new java.util.concurrent.ConcurrentHashMap(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + return map; + } + + function collector(items) { + return new java.util.function.Consumer({ + accept: function (item) { + items.push(String(item)); + } + }); + } + + function ownNames(object) { + return Object.getOwnPropertyNames(object).sort(); + } + + function own(object, name) { + return Object.prototype.hasOwnProperty.call(object, name); + } + + it("removes through the keySet iterator of a ConcurrentHashMap", function () { + var map = concurrentMap(); + var iterator = map.keySet().iterator(); + var removed = []; + while (iterator.hasNext()) { + removed.push(String(iterator.next())); + iterator.remove(); + } + expect(removed.sort()).toEqual(["a", "b", "c"]); + expect(map.size()).toBe(0); + }); + + it("removes through the values iterator of a ConcurrentHashMap", function () { + var map = concurrentMap(); + var iterator = map.values().iterator(); + while (iterator.hasNext()) { + if (String(iterator.next()) === "2") { + iterator.remove(); + } + } + expect(map.size()).toBe(2); + expect(map.containsKey("b")).toBe(false); + }); + + it("advances an ArrayList spliterator with tryAdvance and forEachRemaining", function () { + if (sdk < 24) { + pending("spliterators need API 24"); + return; + } + var list = new java.util.ArrayList(); + list.add("a"); + list.add("b"); + list.add("c"); + var spliterator = list.spliterator(); + var items = []; + var consumer = collector(items); + expect(spliterator.tryAdvance(consumer)).toBe(true); + spliterator.forEachRemaining(consumer); + expect(items).toEqual(["a", "b", "c"]); + }); + + it("sizes and advances a HashMap keySet spliterator", function () { + if (sdk < 24) { + pending("spliterators need API 24"); + return; + } + var map = new java.util.HashMap(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + var spliterator = map.keySet().spliterator(); + expect(spliterator.estimateSize()).toBe(3); + var items = []; + expect(spliterator.tryAdvance(collector(items))).toBe(true); + expect(items.length).toBe(1); + }); + + it("drains a TreeMap sub-map key iterator with forEachRemaining", function () { + if (sdk < 24) { + pending("Iterator.forEachRemaining needs API 24"); + return; + } + var map = new java.util.TreeMap(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + map.put("d", "4"); + var iterator = map.subMap("a", true, "c", true).keySet().iterator(); + expect(String(iterator.next())).toBe("a"); + var items = []; + iterator.forEachRemaining(collector(items)); + expect(items).toEqual(["b", "c"]); + }); + + it("has the default forEachRemaining on the keySet iterator of a ConcurrentHashMap", function () { + if (sdk < 24) { + pending("Iterator.forEachRemaining needs API 24"); + return; + } + var items = []; + concurrentMap().keySet().iterator().forEachRemaining(collector(items)); + expect(items.sort()).toEqual(["a", "b", "c"]); + }); + + it("has the default reversed on the private comparator behind String.CASE_INSENSITIVE_ORDER", function () { + if (sdk < 24) { + pending("Comparator.reversed needs API 24"); + return; + } + var order = java.lang.String.CASE_INSENSITIVE_ORDER; + expect(order.getClass().getName()).toBe("java.lang.String$CaseInsensitiveComparator"); + expect(order.compare("a", "B")).toBeLessThan(0); + expect(order.reversed().compare("a", "B")).toBeGreaterThan(0); + }); + + // With app code as the Java caller, Android 9 denies a JNI lookup of a hidden + // member, so the first lookup of these methods has to go to the interface. Nothing + // else in the suite uses a HashMap values spliterator, so the lookup happens here. + it("calls the hidden methods of a HashMap values spliterator first from a callback that app Java code invokes", function () { + if (sdk < 24) { + pending("spliterators need API 24"); + return; + } + var size = -1; + var advanced = false; + var items = []; + com.tns.tests.IteratorFixtures.run(new java.lang.Runnable({ + run: function () { + var map = new java.util.HashMap(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + var spliterator = map.values().spliterator(); + size = spliterator.estimateSize(); + advanced = spliterator.tryAdvance(collector(items)); + } + })); + expect(size).toBe(3); + expect(advanced).toBe(true); + expect(items.length).toBe(1); + }); + + it("has the interface methods of a ConcurrentHashMap iterator in a worker", function (done) { + var worker = new Worker("./runtimeTypeInterfaceMethodsWorker.js"); + worker.onmessage = function (msg) { + expect(msg.data).toEqual({ drained: ["a", "b", "c"], sizeAfter: 0 }); + worker.terminate(); + done(); + }; + worker.onerror = function (error) { + fail("worker failed: " + error.message); + worker.terminate(); + done(); + }; + worker.postMessage("go"); + }, 30000); + + it("keeps the methods the class chain declares on the prototype that declares them", function () { + var hashMap = new java.util.HashMap(); + hashMap.put("a", "1"); + var hashMapKeys = Object.getPrototypeOf(hashMap.keySet().iterator()); + var hashIterator = Object.getPrototypeOf(hashMapKeys); + expect(own(hashMapKeys, "next")).toBe(true); + expect(own(hashMapKeys, "hasNext")).toBe(false); + expect(own(hashMapKeys, "remove")).toBe(false); + expect(own(hashIterator, "hasNext")).toBe(true); + expect(own(hashIterator, "remove")).toBe(true); + + // Android 9 hides these from reflection, so there they come from Iterator. + if (sdk !== 28) { + var concurrentKeys = Object.getPrototypeOf(concurrentMap().keySet().iterator()); + var baseIterator = Object.getPrototypeOf(concurrentKeys); + expect(own(concurrentKeys, "hasNext")).toBe(false); + expect(own(concurrentKeys, "remove")).toBe(false); + expect(own(baseIterator, "hasNext")).toBe(true); + expect(own(baseIterator, "remove")).toBe(true); + } + }); + + it("leaves the members of app-module iterator classes unchanged", function () { + var fixtures = com.tns.tests.IteratorFixtures; + // These two are in the build-time metadata, the others are resolved at run time. + var described = ["", "constructor", "forEachRemaining", "hasNext", "next", "remove"]; + expect(ownNames(Object.getPrototypeOf(fixtures.packagePrivateIterator()))).toEqual(described); + expect(ownNames(Object.getPrototypeOf(fixtures.anonymousIterator()))).toEqual(described); + expect(ownNames(Object.getPrototypeOf(fixtures.privateNestedIterator()))).toEqual(["constructor", "hasNext", "next"]); + var keyCursor = Object.getPrototypeOf(fixtures.inheritedHasNextIterator()); + expect(ownNames(keyCursor)).toEqual(["constructor", "next"]); + expect(ownNames(Object.getPrototypeOf(keyCursor))).toEqual(["constructor", "hasNext"]); + }); + + it("wraps a direct ByteBuffer without the members of its non-SDK interface", function () { + var buffer = java.nio.ByteBuffer.allocateDirect(4); + expect(buffer.capacity()).toBe(4); + expect(buffer.isDirect()).toBe(true); + // sun.nio.ch.DirectBuffer.address() is allowed for apps, while DirectByteBuffer's + // own address() is blocked from API 29 on, so there it could only come from the + // interface. Before API 29 the class's own method is visible. + if (sdk >= 29) { + expect(typeof buffer.address).toBe("undefined"); + } + expect(typeof buffer.compact).toBe("function"); + }); + + it("keeps overload resolution on a runtime-resolved sub-list", function () { + var list = new java.util.ArrayList(); + list.add("a"); + list.add("b"); + list.add("c"); + list.add("d"); + var sub = list.subList(0, 3); + expect(String(sub.remove(0))).toBe("a"); + expect(sub.remove("c")).toBe(true); + expect(sub.size()).toBe(1); + expect(list.size()).toBe(2); + }); +}); diff --git a/test-app/app/src/main/java/com/tns/tests/IteratorFixtures.java b/test-app/app/src/main/java/com/tns/tests/IteratorFixtures.java index 8feb326ff..4e2544913 100644 --- a/test-app/app/src/main/java/com/tns/tests/IteratorFixtures.java +++ b/test-app/app/src/main/java/com/tns/tests/IteratorFixtures.java @@ -40,6 +40,11 @@ public static Iterable lambdaIterable() { return () -> new PackagePrivateIterator(ITEMS); } + // Runs a JS callback with this app class, not the event loop, as its Java caller. + public static void run(Runnable callback) { + callback.run(); + } + public static Object[] privateNestedIteratorArray() { return new PrivateNestedIterator[] { new PrivateNestedIterator(ITEMS), new PrivateNestedIterator(ITEMS) diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 41e0e797e..6a7387b03 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -996,6 +996,11 @@ void MetadataNode::SetInstanceMembersFromRuntimeMetadata( auto cache = GetMetadataNodeCache(isolate); while (getline(s, line)) { + // Implemented interfaces; SetInterfaceMethodsFromRuntimeMetadata reads them. + if (!line.empty() && line[0] == 'N') { + continue; + } + stringstream tmp(line); tmp >> kind >> name >> signature >> paramCount; @@ -1036,6 +1041,89 @@ void MetadataNode::SetInstanceMembersFromRuntimeMetadata( } } +/* + * Adds to a runtime-resolved class the methods of its public interfaces (the + * `N` lines, most specific first) under every name the class chain does not + * already have. The interface's own callback data is installed, so a call + * resolves the method on the interface, never on the class: Android 9 hides + * some boot classes' members from reflection and from JNI lookups made with app + * code on the stack, while the interface method is public API. + * + * Only interfaces in the build-time metadata count: the point is the public API + * the platform hides, not the members of non-SDK interfaces, and those are never + * resolved at run time for this. An interface that fails to materialize is + * skipped; the class's wrapper does not depend on it. + */ +void MetadataNode::SetInterfaceMethodsFromRuntimeMetadata( + Isolate* isolate, PrototypeTemplateFiller& protoFiller, + const Local& baseFuncTemplate, MetadataTreeNode* treeNode) { + NS_DCHECK(treeNode->metadata != nullptr); + + vector interfaceNames; + { + stringstream s(*treeNode->metadata); + string line; + while (getline(s, line)) { + if (line.size() > 2 && line[0] == 'N' && line[1] == ' ') { + interfaceNames.push_back(line.substr(2)); + } + } + } + if (interfaceNames.empty()) { + return; + } + + auto context = isolate->GetCurrentContext(); + + Local basePrototype; + if (!baseFuncTemplate.IsEmpty()) { + Local baseFunc; + Local prototype; + if (baseFuncTemplate->GetFunction(context).ToLocal(&baseFunc) && + baseFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocal(&prototype) && + prototype->IsObject()) { + basePrototype = prototype.As(); + } + } + + for (const auto& interfaceName : interfaceNames) { + auto interfaceTreeNode = s_metadataReader.FindStaticTreeNodeByName(interfaceName); + if (interfaceTreeNode == nullptr) { + continue; + } + + vector interfaceMethods; + try { + auto interfaceNode = GetOrCreateInternal(interfaceTreeNode); + if (!interfaceNode->IsNodeTypeInterface()) { + continue; + } + auto interfaceTemplate = interfaceNode->GetConstructorFunctionTemplate( + isolate, interfaceNode->m_treeNode, interfaceMethods); + if (interfaceTemplate.IsEmpty()) { + continue; + } + } catch (NativeScriptException&) { + DEBUG_WRITE("Skipping interface %s of %s: it cannot be materialized", + interfaceName.c_str(), m_name.c_str()); + continue; + } + + for (auto* methodData : interfaceMethods) { + if (methodData->candidates.empty()) { + continue; + } + const auto& methodName = methodData->candidates.front().name; + if (!basePrototype.IsEmpty() && + basePrototype->Has(context, NewMemberName(isolate, methodName)).FromMaybe(true)) { + continue; + } + // A name the class itself declares, or an earlier interface added, is kept. + protoFiller.FillPrototypeMethod(isolate, methodName, methodData); + } + } +} + void MetadataNode::SetStaticMembers(Isolate* isolate, Local& ctorFunction, MetadataTreeNode* treeNode, uint8_t* &curPtr) { auto hasCustomMetadata = treeNode->metadata != nullptr; @@ -1234,6 +1322,7 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); Local baseCtorFunc; + Local baseFuncTemplate; std::vector baseInstanceMethodsCallbackData; auto tmpTreeNode = treeNode; while (true) { @@ -1243,7 +1332,7 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is continue; } if ((baseTreeNode != treeNode) && (baseTreeNode != nullptr) && (baseTreeNode->offsetValue > 0)) { - auto baseFuncTemplate = GetConstructorFunctionTemplate(isolate, baseTreeNode, baseInstanceMethodsCallbackData); + baseFuncTemplate = GetConstructorFunctionTemplate(isolate, baseTreeNode, baseInstanceMethodsCallbackData); if (!baseFuncTemplate.IsEmpty()) { ctorFuncTemplate->Inherit(baseFuncTemplate); baseCtorFunc = Local::New(isolate, *GetOrCreateInternal(baseTreeNode)->GetPersistentConstructorFunction(isolate)); @@ -1260,6 +1349,10 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is isolate, ctorFuncTemplate, protoFiller, instanceMethodsCallbackData, baseInstanceMethodsCallbackData, treeNode, curPtr); + if (treeNode->metadata != nullptr && !isInterface) { + node->SetInterfaceMethodsFromRuntimeMetadata(isolate, protoFiller, baseFuncTemplate, treeNode); + } + auto context = isolate->GetCurrentContext(); auto ctorFunc = ctorFuncTemplate->GetFunction(context).ToLocalChecked(); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index 6437b9932..71199b020 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -124,6 +124,10 @@ class MetadataNode { std::vector& instanceMethodsCallbackData, const std::vector& baseInstanceMethodsCallbackData, MetadataTreeNode* treeNode); + void SetInterfaceMethodsFromRuntimeMetadata( + v8::Isolate* isolate, PrototypeTemplateFiller& protoFiller, + const v8::Local& baseFuncTemplate, + MetadataTreeNode* treeNode); void SetStaticMembers(v8::Isolate* isolate, v8::Local& ctorFunction, MetadataTreeNode* treeNode, uint8_t* &curPtr); static void InnerTypeAccessorGetterCallback(v8::Local property, const v8::PropertyCallbackInfo& info); diff --git a/test-app/runtime/src/main/cpp/MetadataReader.cpp b/test-app/runtime/src/main/cpp/MetadataReader.cpp index bb92e870a..347dc7ec2 100644 --- a/test-app/runtime/src/main/cpp/MetadataReader.cpp +++ b/test-app/runtime/src/main/cpp/MetadataReader.cpp @@ -290,6 +290,28 @@ MetadataTreeNode *MetadataReader::GetRoot() const { return m_root; } +MetadataTreeNode *MetadataReader::FindStaticTreeNodeByName(const string &className) const { + vector names; + Util::SplitString(className, "/$", names); + + MetadataTreeNode *treeNode = m_root; + for (const auto &name: names) { + if (treeNode == nullptr || treeNode->children == nullptr) { + return nullptr; + } + MetadataTreeNode *found = nullptr; + for (auto child: *treeNode->children) { + if (child->name == name) { + found = child; + break; + } + } + treeNode = found; + } + + return names.empty() ? nullptr : treeNode; +} + uint8_t MetadataReader::GetNodeType(MetadataTreeNode *treeNode) { uint8_t memoized = treeNode->type.load(std::memory_order_relaxed); if (memoized != MetadataTreeNode::INVALID_TYPE) { diff --git a/test-app/runtime/src/main/cpp/MetadataReader.h b/test-app/runtime/src/main/cpp/MetadataReader.h index 0644fd6cc..fb8611427 100644 --- a/test-app/runtime/src/main/cpp/MetadataReader.h +++ b/test-app/runtime/src/main/cpp/MetadataReader.h @@ -239,6 +239,10 @@ namespace tns { MetadataTreeNode *GetOrCreateTreeNodeByName(const std::string &className); + // The node of a type in the build-time metadata, or null. Never resolves a type + // at run time; reads only the static tree, which needs no lock. + MetadataTreeNode *FindStaticTreeNodeByName(const std::string &className) const; + MetadataTreeNode *GetBaseClassNode(MetadataTreeNode *treeNode); MetadataTreeNode *GetNodeById(uint32_t nodeId); diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index 75ec2758c..29ed40eef 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -17,11 +17,13 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; @@ -1034,7 +1036,7 @@ private static String[] getTypeMetadata(Class clazz, int index) { return result; } - private static String getTypeMetadata(Class clazz) { + static String getTypeMetadata(Class clazz) { StringBuilder sb = new StringBuilder(); if (clazz.isInterface()) { @@ -1052,6 +1054,16 @@ private static String getTypeMetadata(Class clazz) { Class baseClass = clazz.getSuperclass(); sb.append("B " + ((baseClass != null) ? baseClass.getName() : "").replace('.', '/') + "\n"); + // Android 9 drops the members it hides from a boot class's reflection results, + // even public methods that implement a public interface; native installs the + // methods of those interfaces the build-time metadata has, under names the class + // chain does not already provide. + if (!clazz.isInterface() && isBootClass(clazz)) { + for (Class implemented : publicInterfacesOf(clazz)) { + sb.append("N ").append(implemented.getName().replace('.', '/')).append('\n'); + } + } + Method[] methods = clazz.getDeclaredMethods(); Arrays.sort(methods, methodComparator); @@ -1089,6 +1101,57 @@ private static String getTypeMetadata(Class clazz) { return ret; } + static boolean isBootClass(Class clazz) { + ClassLoader loader = clazz.getClassLoader(); + return loader == null || loader == Object.class.getClassLoader(); + } + + /** + * The public interfaces {@code clazz} itself implements, with their super-interfaces, + * each listed after every sub-interface of it in the set, so a name an interface and + * its sub-interface both declare comes from the sub-interface and keeps its overloads. + * Non-public interfaces are walked through but not listed. + */ + static List> publicInterfacesOf(Class clazz) { + ArrayList> all = new ArrayList>(); + ArrayDeque> pending = new ArrayDeque>(Arrays.asList(clazz.getInterfaces())); + while (!pending.isEmpty()) { + Class next = pending.removeFirst(); + if (!all.contains(next)) { + all.add(next); + pending.addAll(Arrays.asList(next.getInterfaces())); + } + } + + ArrayList> ordered = new ArrayList>(all.size()); + while (!all.isEmpty()) { + int pick = 0; + for (int i = 0; i < all.size(); i++) { + Class candidate = all.get(i); + boolean hasPendingSubInterface = false; + for (Class other : all) { + if (other != candidate && candidate.isAssignableFrom(other)) { + hasPendingSubInterface = true; + break; + } + } + if (!hasPendingSubInterface) { + pick = i; + break; + } + } + ordered.add(all.remove(pick)); + } + + ArrayList> result = new ArrayList>(ordered.size()); + for (Class implemented : ordered) { + if (Modifier.isPublic(implemented.getModifiers())) { + result.add(implemented); + } + } + return result; + } + // One upcall for what native needs after constructing an object from JS. @RuntimeCallable private long registerConstructedInstance(Object instance, int objectId) { diff --git a/test-app/runtime/src/test/java/com/tns/RuntimeTypeMetadataTest.java b/test-app/runtime/src/test/java/com/tns/RuntimeTypeMetadataTest.java new file mode 100644 index 000000000..986d3e9bc --- /dev/null +++ b/test-app/runtime/src/test/java/com/tns/RuntimeTypeMetadataTest.java @@ -0,0 +1,74 @@ +package com.tns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.ListIterator; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.Test; + +public class RuntimeTypeMetadataTest { + + interface PackagePrivateIterator extends Iterator { + } + + abstract static class ImplementsPackagePrivate implements PackagePrivateIterator { + } + + abstract static class ImplementsBothListedSuperFirst implements Iterator, ListIterator { + } + + private static Class concurrentKeyIteratorClass() { + return new ConcurrentHashMap().keySet().iterator().getClass(); + } + + @Test + public void listsTheDirectPublicInterfacesInDeclarationOrder() { + assertEquals(Arrays.>asList(Iterator.class, Enumeration.class), + Runtime.publicInterfacesOf(concurrentKeyIteratorClass())); + } + + @Test + public void listsASubInterfaceBeforeItsSuperInterface() { + assertEquals(Arrays.>asList(ListIterator.class, Iterator.class), + Runtime.publicInterfacesOf(ImplementsBothListedSuperFirst.class)); + } + + @Test + public void walksThroughANonPublicInterfaceWithoutListingIt() { + assertEquals(Arrays.>asList(Iterator.class), + Runtime.publicInterfacesOf(ImplementsPackagePrivate.class)); + } + + @Test + public void listsNothingForAClassThatImplementsNoInterface() { + assertEquals(Arrays.>asList(), Runtime.publicInterfacesOf(Object.class)); + } + + @Test + public void describesTheInterfacesOfABootClass() { + String metadata = Runtime.getTypeMetadata(concurrentKeyIteratorClass()); + + assertTrue(metadata, metadata.contains("\nN java/util/Iterator\nN java/util/Enumeration\n")); + } + + @Test + public void doesNotDescribeTheInterfacesOfAnAppClass() { + assertFalse(Runtime.isBootClass(ImplementsPackagePrivate.class)); + String metadata = Runtime.getTypeMetadata(ImplementsPackagePrivate.class); + + assertFalse(metadata, metadata.contains("\nN ")); + } + + @Test + public void doesNotDescribeTheSuperInterfacesOfAnInterface() { + String metadata = Runtime.getTypeMetadata(ListIterator.class); + + assertFalse(metadata, metadata.contains("\nN ")); + } +}