Bug 17664 - Possible race condition when garbage collecting Views containing CALayers that have custom Delegates
Summary: Possible race condition when garbage collecting Views containing CALayers tha...
Alias: None
Product: iOS
Classification: Xamarin
Component: General ()
Version: 7.0.6.x
Hardware: PC Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
Depends on:
Reported: 2014-02-07 21:22 UTC by Brendan Zagaeski (Xamarin Team, assistant)
Modified: 2014-04-01 04:09 UTC (History)
3 users (show)

Is this bug a regression?: ---
Last known good build:

Test case (7.91 KB, application/zip)
2014-02-07 21:22 UTC, Brendan Zagaeski (Xamarin Team, assistant)

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description Brendan Zagaeski (Xamarin Team, assistant) 2014-02-07 21:22:37 UTC
Created attachment 6004 [details]
Test case

## Steps to reproduce

1. Build and run the attached test case on simulator or device.
2. Push the "Run Test" button.

## Result

The app crashes with a SIGSEGV when the `MyView` instance is garbage collected.

### Instruments "Zombies" template

Running the test case using the "Zombies" template in the "Xcode -> Open Developer Tool -> Instruments" application produces the following message:

An Objective-C message was sent to a deallocated 'TestApp.TestAppViewController+MyView+MyCALayerDelegate' object (zombie) at address: 0x145d0bb0.

## Additional information

Reducing the number of `CALayers` added during the `MyView.MovedToSuperview()` method decreases the chances of getting a SIGSEGV.

## Partial workaround

One option that avoids the problem is to subclass `CALayer` instead of using the `CALayer.Delegate` property.

## Application output

> 2014-02-07 20:59:18.558 TestApp[26319:2803] MyView destroyed
> mono-rt: Stacktrace:
> mono-rt:   at <unknown> <0xffffffff>
> mono-rt:   at (wrapper managed-to-native) MonoTouch.Foundation.NSObject.monotouch_release_managed_ref (intptr) <IL 0x00023, 0xffffffff>
> mono-rt:   at MonoTouch.Foundation.NSObject.ReleaseManagedRef () [0x00000] in /Developer/MonoTouch/Source/monotouch/src/Foundation/NSObject.cs:99
> mono-rt:   at MonoTouch.Foundation.NSObject/NSObject_Disposer.Drain (MonoTouch.Foundation.NSObject) [0x00062] in /Developer/MonoTouch/Source/maccore/src/Foundation/NSObject2.cs:665
> mono-rt:   at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object (object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>
> mono-rt:   at <unknown> <0xffffffff>
> mono-rt:   at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <IL 0x0009f, 0xffffffff>
> mono-rt:   at MonoTouch.UIKit.UIApplication.Main (string[],string,string) [0x0004c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:38
> mono-rt:   at TestApp.Application.Main (string[]) [0x00008] in /Users/username/Projects/CALayerBadAccess/TestApp/Main.cs:16
> mono-rt:   at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object (object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>
> mono-rt: 
> Native stacktrace:
> mono-rt: 
> =================================================================
> Got a SIGSEGV while executing native code. This usually indicates
> a fatal error in the mono runtime or one of the native libraries 
> used by your application.
> =================================================================
Comment 2 Rolf Bjarne Kvinge [MSFT] 2014-02-10 13:16:05 UTC
What happens is that Obj-C requires objects to be destroyed in a specific order, while the managed GC will free objects in any order.

In particular MyCALayerDelegate must be freed after MyView, because MyView tries to access the CALayer's Delegate property in its native destructor, which crashes when MyCALayerDelegate has been freed.

The solution is to null out the Delegate property in MyView's Dispose method [1]:

	protected override void Dispose (bool disposing)
		var layers = Layer.Sublayers;
		foreach (var l in layers)
			l.Delegate = null;

		base.Dispose (disposing);

There are also other solutions which may or may not be viable depending on your codebase (have one MyCALayerDelegaten singleton and store it in a static field, so that it's never freed and/or freed when the last MyView instance is freed).

[1] Even with the Dispose fix I get a rare crash now and then with Xamarin.iOS 7.0.6. I've found a separate issue and fixed it, so it should not crash at all in the next Xamarin.iOS release (monotouch/master: 313756076e9749ee7ed8963d9d4fb7506928405b)).
Comment 3 Brendan Zagaeski (Xamarin Team, assistant) 2014-02-10 13:39:58 UTC
Sounds great! Thanks for the extra information and the additional fix for the rare crash.
Comment 4 Sadik Ali 2014-04-01 04:09:29 UTC
I have verified this issue, I debug attached application on Simulator and noticed that exception is not generated.

Screen cast: http://screencast.com/t/EjnHxLYjF

Hence marking status as verified. 

Build Info: 

=== Xamarin Studio ===
Version 4.2.4 (build 266)

=== Apple Developer Tools ===
Xcode 5.0 (3332.22)
Build 5A1412

=== Xamarin.iOS ===
Version: (Enterprise Edition)

=== Build Information ===
Release ID: 402040266
Git revision: 57fa6b7639703775ae1d5c46536e42ab424cb177
Xamarin addins: eee141c29724a19529e77b8e743086d95b29f5ba

=== Operating System ===
Mac OS X 10.8.5