diff --git a/runtime/trampolines.m b/runtime/trampolines.m index f04b5989e0fc..5b70296cd58e 100644 --- a/runtime/trampolines.m +++ b/runtime/trampolines.m @@ -43,6 +43,29 @@ static pthread_mutex_t refcount_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; +// We try to use the associated object API as little as possible, because the API does +// not like recursion (see bug #35017), and it calls retain/release, which we might +// have overridden with our own code that calls these functions. So in addition to +// keeping the gchandle inside the associated object, we also keep it in a hash +// table, so that xamarin_get_gchandle_trampoline does not have to call any +// associated object API to get the gchandle. +// Also cache NSObjectData: looking it up with associated-object APIs from +// retainWeakReference would invert Objective-C's lock order during fork (see bug #26844). +static CFMutableDictionaryRef gchandle_hash = NULL; +static pthread_mutex_t gchandle_hash_lock = PTHREAD_MUTEX_INITIALIZER; + +struct gchandle_dictionary_entry { + GCHandle gc_handle; + enum XamarinGCHandleFlags gchandle_flags; + struct NSObjectData *data; +}; + +static void +release_gchandle_dictionary_entry (CFAllocatorRef allocator, const void *value) +{ + free ((void *) value); +} + size_t xamarin_get_primitive_size (char type) { @@ -777,6 +800,15 @@ xamarin_unregister_nsobject (self, gchandle, &exception_gchandle); xamarin_free_gchandle (self, gchandle); +#if SUPPORTS_DYNAMIC_REGISTRATION + if (xamarin_supports_dynamic_registration) { + pthread_mutex_lock (&gchandle_hash_lock); + if (gchandle_hash != NULL) + CFDictionaryRemoveValue (gchandle_hash, self); + pthread_mutex_unlock (&gchandle_hash_lock); + } +#endif + MONO_THREAD_DETACH; xamarin_process_managed_exception_gchandle (exception_gchandle); @@ -842,8 +874,8 @@ #if defined(DEBUG_REF_COUNTING) struct NSObjectData *data = xamarin_get_nsobject_data (self); // Don't use PRINT/NSLog/os_log here, because the process can end up aborting due to recursive locks inside the ObjC runtime. Luckily fprintf works fine. - fprintf (stderr, "xamarin_retainWeakReference_trampoline (%s Handle=%p) flags: %x isInFinalizerQueue: %i data: %p data->flags: %x data->handle: %p\n", - class_getName ([self class]), self, flags, isInFinalizerQueue, data, (unsigned int) (data ? data->flags : 0), data ? data->handle : NULL); + fprintf (stderr, "xamarin_retainWeakReference_trampoline (Handle=%p) flags: %x isInFinalizerQueue: %i data: %p data->flags: %x data->handle: %p\n", + self, flags, isInFinalizerQueue, data, (unsigned int) (data ? data->flags : 0), data ? data->handle : NULL); #endif // Do not allow any weak references to be resolved if the managed wrapper has been scheduled for finalization, @@ -855,26 +887,6 @@ return xamarin_invoke_objc_method_implementation_BOOL (self, sel, (IMP) xamarin_retainWeakReference_trampoline); } -// We try to use the associated object API as little as possible, because the API does -// not like recursion (see bug #35017), and it calls retain/release, which we might -// have overridden with our own code that calls these functions. So in addition to -// keeping the gchandle inside the associated object, we also keep it in a hash -// table, so that xamarin_get_gchandle_trampoline does not have to call any -// associated object API to get the gchandle. -static CFMutableDictionaryRef gchandle_hash = NULL; -static pthread_mutex_t gchandle_hash_lock = PTHREAD_MUTEX_INITIALIZER; - -struct gchandle_dictionary_entry { - GCHandle gc_handle; - enum XamarinGCHandleFlags gchandle_flags; -}; - -static void -release_gchandle_dictionary_entry (CFAllocatorRef allocator, const void *value) -{ - free ((void *) value); -} - static const char *associated_key = "x"; // the string value doesn't matter, only the pointer value. bool xamarin_set_gchandle_trampoline (id self, SEL sel, GCHandle gc_handle, enum XamarinGCHandleFlags gchandle_flags, struct NSObjectData *data) @@ -904,23 +916,27 @@ if (data != NULL) obj->data = data; obj->gchandle_flags = gchandle_flags; - } - - pthread_mutex_lock (&gchandle_hash_lock); - if (gchandle_hash == NULL) { - CFDictionaryValueCallBacks value_callbacks = { }; - value_callbacks.release = release_gchandle_dictionary_entry; - gchandle_hash = CFDictionaryCreateMutable (kCFAllocatorDefault, 0, NULL, &value_callbacks); - } - if (gc_handle == INVALID_GCHANDLE) { - CFDictionaryRemoveValue (gchandle_hash, self); - } else { - struct gchandle_dictionary_entry *entry = (struct gchandle_dictionary_entry *) calloc (1, sizeof (struct gchandle_dictionary_entry)); + + pthread_mutex_lock (&gchandle_hash_lock); + if (gchandle_hash == NULL) { + CFDictionaryValueCallBacks value_callbacks = { }; + value_callbacks.release = release_gchandle_dictionary_entry; + gchandle_hash = CFDictionaryCreateMutable (kCFAllocatorDefault, 0, NULL, &value_callbacks); + } + + struct gchandle_dictionary_entry *entry = (struct gchandle_dictionary_entry *) CFDictionaryGetValue (gchandle_hash, self); + if (entry == NULL) { + entry = (struct gchandle_dictionary_entry *) calloc (1, sizeof (struct gchandle_dictionary_entry)); + CFDictionarySetValue (gchandle_hash, self, entry); + } entry->gc_handle = gc_handle; entry->gchandle_flags = gchandle_flags; - CFDictionarySetValue (gchandle_hash, self, entry); + // A GCHandle can be cleared temporarily (for example by copyWithZone). + // Keep the data until native deallocation, just like the associated object. + entry->data = obj->data; + + pthread_mutex_unlock (&gchandle_hash_lock); } - pthread_mutex_unlock (&gchandle_hash_lock); return true; } @@ -975,16 +991,18 @@ xamarin_get_nsobject_data_trampoline (id self, SEL sel) { /* This is for types registered using the dynamic registrar */ - XamarinAssociatedObject *obj; - obj = objc_getAssociatedObject (self, associated_key); - struct NSObjectData *data = NULL; - if (obj != NULL) - data = obj->data; + pthread_mutex_lock (&gchandle_hash_lock); + if (gchandle_hash != NULL) { + struct gchandle_dictionary_entry *entry = (struct gchandle_dictionary_entry *) CFDictionaryGetValue (gchandle_hash, self); + if (entry != NULL) + data = entry->data; + } + pthread_mutex_unlock (&gchandle_hash_lock); #if defined(DEBUG_REF_COUNTING) - PRINT ("xamarin_get_nsobject_data_trampoline (%s = %p) obj: %p data: %p data->flags: %x data->handle: %p\n", - class_getName ([self class]), self, obj, data ? data->flags : NULL, data ? data->handle : NULL); + fprintf (stderr, "xamarin_get_nsobject_data_trampoline (Handle=%p) data: %p data->flags: %x data->handle: %p\n", + self, data, (unsigned int) (data ? data->flags : 0), data ? data->handle : NULL); #endif return data; diff --git a/tests/monotouch-test/ObjCRuntime/NativeRuntimeTest.cs b/tests/monotouch-test/ObjCRuntime/NativeRuntimeTest.cs index 2ddf38c2c659..8b1acfda7234 100644 --- a/tests/monotouch-test/ObjCRuntime/NativeRuntimeTest.cs +++ b/tests/monotouch-test/ObjCRuntime/NativeRuntimeTest.cs @@ -28,5 +28,65 @@ void AssertCollapsed (string input, string expected, string message) Assert.That (exception_gchandle, Is.EqualTo (IntPtr.Zero), $"exc/{message}"); Assert.That (sb.ToString (), Is.EqualTo (expected), $"actual/{message}"); } + + [DllImport ("__Internal")] + static extern int x_get_nsobject_data_with_association_lock (IntPtr handle, out IntPtr data); + + [DllImport ("__Internal")] + static extern IntPtr xamarin_get_nsobject_data_trampoline (IntPtr handle, IntPtr selector); + + [DllImport ("__Internal")] + static extern IntPtr xamarin_get_gchandle_with_flags (IntPtr handle, out uint flags); + + [DllImport ("__Internal")] + static extern byte xamarin_set_gchandle_trampoline (IntPtr handle, IntPtr selector, IntPtr gchandle, uint flags, IntPtr data); + + [Test] + public void NSObjectDataWithoutAssociationLock () + { + if (!Runtime.DynamicRegistrationSupported || global::XamarinTests.ObjCRuntime.Registrar.IsStaticRegistrar) + Assert.Ignore ("This test requires the dynamic registrar."); + + using var obj = new DynamicNSObjectData (); + var expected = xamarin_get_nsobject_data_trampoline (obj.Handle, IntPtr.Zero); + Assert.That (expected, Is.Not.EqualTo (IntPtr.Zero), "Initial data"); + + var result = x_get_nsobject_data_with_association_lock (obj.Handle, out var actual); + Assert.That (result, Is.EqualTo (0), "Data lookup must complete while another thread holds the association lock (1: lock not acquired, 2: lookup timed out)"); + Assert.That (actual, Is.EqualTo (expected), "Data"); + } + + [Test] + public void NSObjectDataGCHandleUpdates () + { + if (!Runtime.DynamicRegistrationSupported || global::XamarinTests.ObjCRuntime.Registrar.IsStaticRegistrar) + Assert.Ignore ("This test requires the dynamic registrar."); + + var obj = new DynamicNSObjectData (); + var handle = obj.Handle; + var expected = xamarin_get_nsobject_data_trampoline (handle, IntPtr.Zero); + Assert.That (expected, Is.Not.EqualTo (IntPtr.Zero), "Initial data"); + var gchandle = xamarin_get_gchandle_with_flags (handle, out var flags); + Assert.That (gchandle, Is.Not.EqualTo (IntPtr.Zero), "GCHandle"); + + try { + Assert.That (xamarin_set_gchandle_trampoline (handle, IntPtr.Zero, gchandle, flags, IntPtr.Zero), Is.Not.EqualTo (0), "Update GCHandle"); + Assert.That (xamarin_get_nsobject_data_trampoline (handle, IntPtr.Zero), Is.EqualTo (expected), "Null data must preserve existing data"); + + Assert.That (xamarin_set_gchandle_trampoline (handle, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero), Is.Not.EqualTo (0), "Clear GCHandle"); + Assert.That (xamarin_get_gchandle_with_flags (handle, out var clearedFlags), Is.EqualTo (IntPtr.Zero), "Cleared GCHandle"); + Assert.That (clearedFlags, Is.EqualTo (0), "Cleared flags"); + Assert.That (xamarin_get_nsobject_data_trampoline (handle, IntPtr.Zero), Is.EqualTo (expected), "Clearing a GCHandle must preserve data"); + } finally { + xamarin_set_gchandle_trampoline (handle, IntPtr.Zero, gchandle, flags, expected); + obj.Dispose (); + } + + Assert.That (xamarin_get_nsobject_data_trampoline (handle, IntPtr.Zero), Is.EqualTo (IntPtr.Zero), "Data must be removed before the native pointer can be reused"); + } + + [Register ("NativeRuntimeTest_NSObjectData")] + class DynamicNSObjectData : NSObject { + } } } diff --git a/tests/test-libraries/libtest.h b/tests/test-libraries/libtest.h index 0b2822a47e1f..348e2656865e 100644 --- a/tests/test-libraries/libtest.h +++ b/tests/test-libraries/libtest.h @@ -23,6 +23,7 @@ __attribute__ ((used)) unsigned long long x_native_field = 0xAABBCCDDEEFF8899; typedef void (^x_block_callback)(); void x_call_block (x_block_callback block); void* x_call_func_3 (void* (*fptr)(void*, void*, void*), void* p1, void* p2, void* p3); +int x_get_nsobject_data_with_association_lock (id object, void **data); // Helper for the issue #25861 design work: a C callback invoked from // InitSurfacesSelfToManaged's 'init' with the 'self' pointer, used to verify that diff --git a/tests/test-libraries/libtest.m b/tests/test-libraries/libtest.m index 566dbdca0782..8971c1db8a15 100644 --- a/tests/test-libraries/libtest.m +++ b/tests/test-libraries/libtest.m @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include #include "libtest.h" @@ -1500,6 +1502,72 @@ -(int) doSomething } @end +@interface AssociatedObjectLockHolder : NSObject { +@public + dispatch_semaphore_t entered; + dispatch_semaphore_t unlock; +} +@end + +@implementation AssociatedObjectLockHolder +-(id) retain +{ + id result = [super retain]; + if (entered != NULL) { + dispatch_semaphore_signal (entered); + dispatch_semaphore_wait (unlock, DISPATCH_TIME_FOREVER); + } + return result; +} +@end + +int +x_get_nsobject_data_with_association_lock (id object, void **data) +{ + static char key; + *data = NULL; + NSObject *lock_object = [[NSObject alloc] init]; + AssociatedObjectLockHolder *holder = [[AssociatedObjectLockHolder alloc] init]; + dispatch_semaphore_t entered = dispatch_semaphore_create (0); + dispatch_semaphore_t unlock = dispatch_semaphore_create (0); + dispatch_semaphore_t completed = dispatch_semaphore_create (0); + dispatch_group_t group = dispatch_group_create (); + dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + // The atomic getter retains its value while holding AssociationsManagerLock. + objc_setAssociatedObject (lock_object, &key, holder, OBJC_ASSOCIATION_RETAIN); + holder->entered = entered; + holder->unlock = unlock; + dispatch_group_async (group, queue, ^{ + @autoreleasepool { + objc_getAssociatedObject (lock_object, &key); + } + }); + + int result = 1; + if (dispatch_semaphore_wait (entered, dispatch_time (DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0) { + // Do not capture the managed object's native peer as an Objective-C object: + // copying the block would retain it while the association lock is held. + void *native_object = object; + dispatch_group_async (group, queue, ^{ + *data = ((void *(*)(id, SEL)) objc_msgSend) ((id) native_object, @selector(xamarinGetNSObjectData)); + dispatch_semaphore_signal (completed); + }); + result = dispatch_semaphore_wait (completed, dispatch_time (DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0 ? 0 : 2; + } + + dispatch_semaphore_signal (unlock); + dispatch_group_wait (group, DISPATCH_TIME_FOREVER); + holder->entered = NULL; + [lock_object release]; + [holder release]; + dispatch_release (group); + dispatch_release (completed); + dispatch_release (unlock); + dispatch_release (entered); + return result; +} + @implementation WeakReferenceHolder : NSObject -(id) init {