Skip to content

Commit 73e16d5

Browse files
authored
[monodroid] Attach current thread to MonoVM when registering a type (#7560)
Fixes: #7532 Whenever any MonoVM APIs are called, the current thread of execution must be attached to the runtime or we risk native code crashes, e.g.: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x40 in tid 1860 (jg_fr_pool_thre), pid 1792 (yname.sampleapp) backtrace: 00 pc 0011588e /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonosgen-2.0.so 01 pc 001156ae /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonosgen-2.0.so 02 pc 00115575 /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonosgen-2.0.so (mono_threads_enter_gc_unsafe_region_internal+53) 03 pc 000973c3 /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonosgen-2.0.so (mono_runtime_invoke+51) (BuildId: c54662bbf82dbdadd595ca9d3e31dce29735885f) 04 pc 00027ace /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonodroid.so (xamarin::android::internal::MonodroidRuntime::Java_mono_android_Runtime_register(_JNIEnv*, _jstring*, _jclass*, _jstring*)+286) 05 pc 000279a0 /data/app/~~lwgdvtQhIfK0II0Nd0mtag==/com.companyname.sampleapp-8yF54k9YuWCWpsuGRJvVQw==/lib/x86/libmonodroid.so (Java_mono_android_Runtime_register+48) The above trace translates to the following locations in the Mono runtime: copy_stack_data_internal /__w/1/s/src/mono/mono/utils/mono-threads-coop.c:191 copy_stack_data /__w/1/s/src/mono/mono/utils/mono-threads-coop.c:246 mono_threads_enter_gc_unsafe_region_unbalanced_with_info /__w/1/s/src/mono/mono/utils/mono-threads-coop.c:476 mono_runtime_invoke /__w/1/s/src/mono/mono/metadata/object.c:2442 In this case, a pointer to Mono thread information structure (`MonoThreadInfo*`) is null in `copy_stack_data()` which, in turn, causes the segfault when the pointer is dereferenced. In the case of issue #7532, `Java_mono_android_Runtime_register()` is called on behalf of a 3rd party library on a thread that is, most likely, created by that library and thus not (yet) attached to the runtime by the time the registration attempt is made. Attach thread to the runtime by calling `mono_jit_thread_attach(nullptr)` in .NET builds to fix the issue. `nullptr` is used because .NET only has a single AppDomain and there's no need to pass around pointers to it. TODO: Try to create a test case. Our attempted unit tests don't cause an app crash when the fix isn't applied -- i.e. when `mono_jit_thread_attach(nullptr)` *isn't* called -- which suggests that we don't fully understand the reported bug report.
1 parent b4ef3dc commit 73e16d5

File tree

3 files changed

+162
-3
lines changed

3 files changed

+162
-3
lines changed

src/monodroid/jni/monodroid-glue.cc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2537,6 +2537,8 @@ MonodroidRuntime::Java_mono_android_Runtime_register (JNIEnv *env, jstring manag
25372537

25382538
utils.monodroid_runtime_invoke (domain, register_jni_natives, nullptr, args, nullptr);
25392539
#else // ndef NET
2540+
mono_jit_thread_attach (nullptr); // There's just one domain in .net
2541+
25402542
#if !defined (ANDROID)
25412543
mono_runtime_invoke (register_jni_natives, nullptr, args, nullptr);
25422544
#else

tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,31 @@ public void TestMyPaintColor ()
3232
}
3333
}
3434

35+
[DllImport ("reuse-threads")]
36+
static extern int rt_register_type_on_new_thread (string java_type_namem, IntPtr class_loader);
37+
3538
delegate void CB (IntPtr jnienv, IntPtr java_instance);
3639

3740
[DllImport ("reuse-threads")]
3841
static extern int rt_invoke_callback_on_new_thread (CB cb);
3942

43+
[Test]
44+
public void RegisterTypeOnNewNativeThread ()
45+
{
46+
Java.Lang.JavaSystem.LoadLibrary ("reuse-threads");
47+
int ret = rt_register_type_on_new_thread ("from.NewThreadOne", Application.Context.ClassLoader.Handle);
48+
Assert.AreEqual (0, ret, $"Java type registration on a new thread failed with code {ret}");
49+
}
50+
51+
[Test]
52+
public void RegisterTypeOnNewJavaThread ()
53+
{
54+
var thread = new MyRegistrationThread ();
55+
thread.Start ();
56+
thread.Join (5000);
57+
Assert.AreNotEqual (null, thread.Instance, "Failed to register instance of a class on new thread");
58+
}
59+
4060
[Test]
4161
public void ThreadReuse ()
4262
{
@@ -434,6 +454,24 @@ public void DoNotLeakWeakReferences ()
434454
}
435455
}
436456

457+
[Register ("from/NewThreadOne")]
458+
class RegisterMeOnNewThreadOne : Java.Lang.Object
459+
{}
460+
461+
[Register ("from/NewThreadTwo")]
462+
class RegisterMeOnNewThreadTwo : Java.Lang.Object
463+
{}
464+
465+
class MyRegistrationThread : Java.Lang.Thread
466+
{
467+
public RegisterMeOnNewThreadTwo Instance { get; private set; }
468+
469+
public override void Run ()
470+
{
471+
Instance = new RegisterMeOnNewThreadTwo ();
472+
}
473+
}
474+
437475
class MyCb : Java.Lang.Object, Java.Lang.IRunnable {
438476
public void Run ()
439477
{

tests/Mono.Android-Tests/jni/reuse-threads.c

Lines changed: 122 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@
8181
#include <android/log.h>
8282
#include <jni.h>
8383

84+
typedef struct
85+
{
86+
const char *java_type_name;
87+
jobject class_loader;
88+
} RegisterFromThreadContext;
89+
8490
typedef void (*CB)(JNIEnv *env, jobject self);
8591

8692
static JavaVM *gvm;
@@ -113,9 +119,9 @@ _get_env (const char *where)
113119
}
114120

115121
static jobject
116-
_create_java_instance (JNIEnv *env)
122+
_create_java_instance (JNIEnv *env, const char *class_name)
117123
{
118-
jclass Object_class = (*env)->FindClass (env, "java/lang/Object");
124+
jclass Object_class = (*env)->FindClass (env, class_name);
119125
jmethodID Object_ctor = (*env)->GetMethodID (env, Object_class, "<init>", "()V");
120126

121127
jobject instance = (*env)->NewObject (env, Object_class, Object_ctor);
@@ -154,7 +160,7 @@ _call_cb_from_new_thread (void *cb)
154160
}
155161

156162
/* 5: Execution of T enters managed code... */
157-
jobject instance = _create_java_instance (env);
163+
jobject instance = _create_java_instance (env, "java/lang/Object");
158164
_cb (env, instance);
159165

160166
return NULL;
@@ -200,3 +206,116 @@ rt_invoke_callback_on_new_thread (CB cb)
200206
return 0;
201207
}
202208

209+
/* We return -2 for errors, because -1 is reserved for the pthreads PTHREAD_CANCELED special value, indicating that the
210+
* thread was canceled. */
211+
static int
212+
_register_type_from_new_thread (void *data)
213+
{
214+
RegisterFromThreadContext *context = (RegisterFromThreadContext*)data;
215+
216+
if (context == NULL) {
217+
return -100;
218+
}
219+
220+
JNIEnv *env = _get_env ("_register_type_from_new_thread");
221+
222+
if ((*env)->PushLocalFrame (env, 4) < 0) {
223+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: unable to create a local reference frame!");
224+
225+
if ((*env)->ExceptionOccurred (env)) {
226+
(*env)->ExceptionDescribe (env);
227+
(*env)->ExceptionClear (env);
228+
}
229+
230+
return -101;
231+
}
232+
233+
int ret = 0;
234+
jclass ClassLoader_class = (*env)->FindClass (env, "java/lang/ClassLoader");
235+
if (ClassLoader_class == NULL) {
236+
ret = -102;
237+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: unable to find the 'java/lang/ClassLoader' class!");
238+
goto cleanup;
239+
}
240+
241+
jmethodID loadClass = (*env)->GetMethodID (env, ClassLoader_class, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
242+
if (loadClass == NULL) {
243+
ret = -103;
244+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: unable to get id of method 'loadClass' in the 'java/lang/ClassLoader' class!");
245+
goto cleanup;
246+
}
247+
248+
jstring klass_name = (*env)->NewStringUTF (env, context->java_type_name);
249+
jobject loaded_class = (*env)->CallObjectMethod (env, context->class_loader, loadClass, klass_name);
250+
251+
if ((*env)->ExceptionOccurred (env) != NULL) {
252+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: class '%s' cannot be loaded, Java exception thrown!", context->java_type_name);
253+
(*env)->ExceptionDescribe (env);
254+
(*env)->ExceptionClear (env);
255+
ret = -104;
256+
goto cleanup;
257+
}
258+
259+
if (loaded_class == NULL) {
260+
ret = -105;
261+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: 'java/lang/ClassLoader' wasn't able to load the '%s' class!", context->java_type_name);
262+
goto cleanup;
263+
}
264+
265+
jmethodID Object_ctor = (*env)->GetMethodID (env, loaded_class, "<init>", "()V");
266+
if (Object_ctor == NULL) {
267+
ret = -106;
268+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: unable to find the '%s' class constructor!", context->java_type_name);
269+
goto cleanup;
270+
}
271+
272+
jobject instance = (*env)->NewObject (env, loaded_class, Object_ctor);
273+
274+
if ((*env)->ExceptionOccurred (env) != NULL || instance == NULL) {
275+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: instance of class '%s' wasn't created!", context->java_type_name);
276+
(*env)->ExceptionDescribe (env);
277+
(*env)->ExceptionClear (env);
278+
ret = -107;
279+
}
280+
281+
if (instance == NULL) {
282+
ret = -108;
283+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "FAILURE: unable to create instance of the '%s' class!", context->java_type_name);
284+
}
285+
286+
cleanup:
287+
(*env)->PopLocalFrame (env, NULL);
288+
289+
return ret;
290+
}
291+
292+
JNIEXPORT int JNICALL
293+
rt_register_type_on_new_thread (const char *java_type_name, jobject class_loader)
294+
{
295+
JNIEnv *env = _get_env ("rt_register_type_on_new_thread");
296+
pthread_t t;
297+
RegisterFromThreadContext context = {
298+
java_type_name,
299+
class_loader,
300+
};
301+
302+
int r = pthread_create (&t, NULL, _register_type_from_new_thread, &context);
303+
304+
if (r) {
305+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "RegisterOnNewThread: pthread_create() failed! %i: %s", r, strerror (r));
306+
return -200;
307+
}
308+
309+
void *tr;
310+
if (pthread_join (t, &tr) != 0) {
311+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "RegisterOnNewThread: pthread_join() failed! %i: %s", r, strerror (r));
312+
return -201;
313+
}
314+
315+
if ((int)tr == -1 /* PTHREAD_CANCELED - not defined in bionic */) {
316+
__android_log_print (ANDROID_LOG_INFO, "XA/RuntimeTest", "RegisterOnNewThread: worker thread was canceled");
317+
return -202;
318+
}
319+
320+
return (int)tr;
321+
}

0 commit comments

Comments
 (0)