Skip to content

Commit a5c973b

Browse files
committed
fix: let only the instance JS is constructing take its object id
While JS constructs a Java object, the native side publishes the id it reserved in Runtime.currentObjectId, and the binding's initInstance takes it. Any other binding instance whose initInstance ran in that window took the same id: an instance Java created there (by reflection, or a custom view inflated by the constructor) was registered under the outer id, and since bindings now carry their id, its callbacks ran on the outer object's JS. The class being constructed is now published with the id, and only an instance of exactly that class takes it, once; others get their own JS object as Java-created instances do. The scope also restored -1 instead of the enclosing construction's id when a callback made by a constructor constructed another object. It now restores the enclosing id and class. The class is written only when it changes, so constructing one class repeatedly costs the same two field writes as before.
1 parent cde9b0f commit a5c973b

6 files changed

Lines changed: 112 additions & 20 deletions

File tree

‎test-app/app/src/main/assets/app/tests/testMetadata.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,30 @@ describe("Java object wrappers", function () {
8585
expect(function () { return impl.super; }).not.toThrow();
8686
});
8787

88+
it("leave an extended instance Java creates during a JS construction its own JS object", function () {
89+
var Inner = java.lang.Object.extend({ toString: function () { return "inner"; } });
90+
var Outer = com.tns.tests.NestedConstruction.extend({ toString: function () { return "outer"; } });
91+
var outer = new Outer(new Inner().getClass(), null);
92+
93+
expect(String(outer.toString())).toBe("outer");
94+
expect(String(outer.getCreated().toString())).toBe("inner");
95+
});
96+
97+
it("keep a JS construction's instance when a callback constructs another during it", function () {
98+
var Inner = java.lang.Object.extend({ toString: function () { return "inner"; } });
99+
var Outer = com.tns.tests.NestedConstruction.extend({ toString: function () { return "outer:" + this.tag; } });
100+
var made = null;
101+
var outer = new Outer(null, new java.lang.Runnable({
102+
run: function () {
103+
made = new Inner();
104+
}
105+
}));
106+
outer.tag = "mine";
107+
108+
expect(String(outer.toString())).toBe("outer:mine");
109+
expect(String(made.toString())).toBe("inner");
110+
});
111+
88112
it("hand back the same wrapper for the same Java object", function () {
89113
var builder = new java.lang.StringBuilder();
90114

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.tns.tests;
2+
3+
/** Creates objects while its own constructor runs, for the construction-window specs. */
4+
public class NestedConstruction {
5+
private final Object created;
6+
7+
public NestedConstruction(Class<?> toCreate, Runnable during) throws Exception {
8+
created = toCreate == null ? null : toCreate.newInstance();
9+
if (during != null) {
10+
during.run();
11+
}
12+
}
13+
14+
public Object getCreated() {
15+
return created;
16+
}
17+
}

‎test-app/runtime/src/main/cpp/CallbackHandlers.cpp‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ void CallbackHandlers::Init(Isolate *isolate) {
5656
CURRENT_OBJECTID_FIELD_ID = env.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I");
5757
NS_CHECK(CURRENT_OBJECTID_FIELD_ID != nullptr);
5858

59+
CURRENT_OBJECTCLASS_FIELD_ID = env.GetFieldID(RUNTIME_CLASS, "currentObjectClass", "Ljava/lang/Class;");
60+
NS_CHECK(CURRENT_OBJECTCLASS_FIELD_ID != nullptr);
61+
5962
REGISTER_CONSTRUCTED_INSTANCE_ID = env.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance",
6063
"(Ljava/lang/Object;I)J");
6164
NS_CHECK(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr);
@@ -98,6 +101,41 @@ struct JavaCallScope {
98101
};
99102
} // namespace
100103

104+
// Publishes the instance JS is constructing to Runtime.initInstance for the duration of the
105+
// Java constructor, and restores the enclosing construction afterwards: JS run by a
106+
// callback the constructor makes may construct another instance. Raw JNI, so that the
107+
// destructor never throws.
108+
class CallbackHandlers::ConstructionScope {
109+
public:
110+
ConstructionScope(Runtime* runtime, int javaObjectId, jclass clazz)
111+
: _runtime(runtime), _previous(runtime->CurrentConstruction()) {
112+
Publish({javaObjectId, clazz});
113+
}
114+
115+
~ConstructionScope() {
116+
Publish(_previous);
117+
}
118+
119+
private:
120+
// The class is written only when it changes: initInstance reads it only while an id is
121+
// published, so a stale one is harmless, and repeated constructions of one class then
122+
// cost a single field write each way.
123+
void Publish(const Runtime::Construction& construction) {
124+
_runtime->CurrentConstruction() = construction;
125+
JNIEnv* env = JEnv();
126+
jobject javaRuntime = _runtime->GetJavaRuntime();
127+
jclass& published = _runtime->PublishedConstructionClass();
128+
if (construction.id != -1 && construction.clazz != published) {
129+
env->SetObjectField(javaRuntime, CURRENT_OBJECTCLASS_FIELD_ID, construction.clazz);
130+
published = construction.clazz;
131+
}
132+
env->SetIntField(javaRuntime, CURRENT_OBJECTID_FIELD_ID, construction.id);
133+
}
134+
135+
Runtime* _runtime;
136+
Runtime::Construction _previous;
137+
};
138+
101139
bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &jsObject,
102140
const std::string &fullClassName,
103141
const ArgsWrapper &argWrapper,
@@ -129,12 +167,9 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
129167
const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName,
130168
generatedJavaClass, isInterface);
131169

132-
// while the "instance" is being created, if an exception is thrown during the construction
133-
// this scope will guarantee the "javaObjectID" will be set to -1 and won't have an invalid value
134170
jobject instance;
135171
{
136-
JavaObjectIdScope objIdScope(env, CURRENT_OBJECTID_FIELD_ID, runtime->GetJavaRuntime(),
137-
javaObjectID);
172+
ConstructionScope construction(runtime, javaObjectID, generatedJavaClass);
138173

139174
if (argWrapper.type == ArgType::Interface) {
140175
instance = env.NewObject(generatedJavaClass, mi.mid);
@@ -1948,6 +1983,7 @@ short CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH = 100;
19481983
jclass CallbackHandlers::RUNTIME_CLASS = nullptr;
19491984
jclass CallbackHandlers::JAVA_LANG_STRING = nullptr;
19501985
jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr;
1986+
jfieldID CallbackHandlers::CURRENT_OBJECTCLASS_FIELD_ID = nullptr;
19511987
jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr;
19521988
jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr;
19531989
jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr;

‎test-app/runtime/src/main/cpp/CallbackHandlers.h‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,10 @@ namespace tns {
187187

188188
static jfieldID CURRENT_OBJECTID_FIELD_ID;
189189

190+
static jfieldID CURRENT_OBJECTCLASS_FIELD_ID;
191+
192+
class ConstructionScope;
193+
190194
static jmethodID REGISTER_CONSTRUCTED_INSTANCE_ID;
191195

192196
static jmethodID GET_TYPE_METADATA;
@@ -201,21 +205,6 @@ namespace tns {
201205

202206
static FieldAccessor fieldAccessor;
203207

204-
struct JavaObjectIdScope {
205-
JavaObjectIdScope(JEnv &env, jfieldID fieldId, jobject runtime, int javaObjectId)
206-
: _env(env), _fieldID(fieldId), _runtime(runtime) {
207-
_env.SetIntField(_runtime, _fieldID, javaObjectId);
208-
}
209-
210-
~JavaObjectIdScope() {
211-
_env.SetIntField(_runtime, _fieldID, -1);
212-
}
213-
214-
private:
215-
JEnv _env;
216-
jfieldID _fieldID;
217-
jobject _runtime;
218-
};
219208

220209
static std::atomic_int64_t count_;
221210

‎test-app/runtime/src/main/cpp/Runtime.h‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,22 @@ class Runtime {
173173
return m_admissionGate;
174174
}
175175

176+
// The instance JS is constructing, as last published to the Java runtime's
177+
// currentObjectId and currentObjectClass.
178+
struct Construction {
179+
int id = -1;
180+
jclass clazz = nullptr;
181+
};
182+
183+
Construction& CurrentConstruction() {
184+
return m_construction;
185+
}
186+
187+
// What the Java runtime's currentObjectClass holds; only native code writes it.
188+
jclass& PublishedConstructionClass() {
189+
return m_publishedConstructionClass;
190+
}
191+
176192
void RunModule(JNIEnv* _env, jobject obj, jstring scriptFile);
177193
void RunModule(const char *moduleName);
178194
void RunWorker(const std::string& filePath);
@@ -340,6 +356,10 @@ class Runtime {
340356

341357
AdmissionGate m_admissionGate;
342358

359+
Construction m_construction;
360+
361+
jclass m_publishedConstructionClass = nullptr;
362+
343363
ModuleInternal m_module;
344364

345365
ArrayBufferHelper m_arrayBufferHelper;

‎test-app/runtime/src/main/java/com/tns/Runtime.java‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,12 @@ public int newId() {
202202
private final java.lang.Runtime dalvikRuntime = java.lang.Runtime.getRuntime();
203203

204204
private final Object keyNotFoundObject = new Object();
205+
// The id and class of the instance JS is constructing, set by the native side around
206+
// the Java constructor call. Only an instance of exactly that class may take the id: any
207+
// other binding instance created while that constructor runs was created by Java. The
208+
// class is only meaningful while the id is set, and only native code writes it.
205209
private int currentObjectId = -1;
210+
private Class<?> currentObjectClass;
206211

207212
private ExtractPolicy extractPolicy;
208213

@@ -930,7 +935,8 @@ public static void initInstance(Object instance) {
930935

931936
int objectId = runtime.currentObjectId;
932937

933-
if (objectId != -1) {
938+
if (objectId != -1 && instance.getClass() == runtime.currentObjectClass) {
939+
runtime.currentObjectId = -1;
934940
runtime.makeInstanceStrong(instance, objectId);
935941
} else {
936942
objectId = runtime.createJSInstance(instance);

0 commit comments

Comments
 (0)