Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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() });
};
227 changes: 227 additions & 0 deletions test-app/app/src/main/assets/app/tests/testJavaIterators.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ["<init>", "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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public static Iterable<String> 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)
Expand Down
95 changes: 94 additions & 1 deletion test-app/runtime/src/main/cpp/MetadataNode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<FunctionTemplate>& baseFuncTemplate, MetadataTreeNode* treeNode) {
NS_DCHECK(treeNode->metadata != nullptr);

vector<string> 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<Object> basePrototype;
if (!baseFuncTemplate.IsEmpty()) {
Local<Function> baseFunc;
Local<Value> prototype;
if (baseFuncTemplate->GetFunction(context).ToLocal(&baseFunc) &&
baseFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocal(&prototype) &&
prototype->IsObject()) {
basePrototype = prototype.As<Object>();
}
}

for (const auto& interfaceName : interfaceNames) {
auto interfaceTreeNode = s_metadataReader.FindStaticTreeNodeByName(interfaceName);
if (interfaceTreeNode == nullptr) {
continue;
}

vector<MethodCallbackData*> 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<Function>& ctorFunction, MetadataTreeNode* treeNode, uint8_t* &curPtr) {
auto hasCustomMetadata = treeNode->metadata != nullptr;
Expand Down Expand Up @@ -1234,6 +1322,7 @@ Local<FunctionTemplate> MetadataNode::GetConstructorFunctionTemplate(Isolate* is
ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast<int>(ObjectManager::MetadataNodeKeys::END));

Local<Function> baseCtorFunc;
Local<FunctionTemplate> baseFuncTemplate;
std::vector<MethodCallbackData*> baseInstanceMethodsCallbackData;
auto tmpTreeNode = treeNode;
while (true) {
Expand All @@ -1243,7 +1332,7 @@ Local<FunctionTemplate> 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<Function>::New(isolate, *GetOrCreateInternal(baseTreeNode)->GetPersistentConstructorFunction(isolate));
Expand All @@ -1260,6 +1349,10 @@ Local<FunctionTemplate> 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();

Expand Down
4 changes: 4 additions & 0 deletions test-app/runtime/src/main/cpp/MetadataNode.h
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ class MetadataNode {
std::vector<MethodCallbackData*>& instanceMethodsCallbackData,
const std::vector<MethodCallbackData*>& baseInstanceMethodsCallbackData,
MetadataTreeNode* treeNode);
void SetInterfaceMethodsFromRuntimeMetadata(
v8::Isolate* isolate, PrototypeTemplateFiller& protoFiller,
const v8::Local<v8::FunctionTemplate>& baseFuncTemplate,
MetadataTreeNode* treeNode);

void SetStaticMembers(v8::Isolate* isolate, v8::Local<v8::Function>& ctorFunction, MetadataTreeNode* treeNode, uint8_t* &curPtr);
static void InnerTypeAccessorGetterCallback(v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8::Value>& info);
Expand Down
Loading
Loading