Bug 16439

Summary: Exception thrown in async call is bypassing catch block
Product: iOS Reporter: Greg Shackles <gshackles>
Component: XI runtimeAssignee: Zoltan Varga <vargaz>
Status: RESOLVED FIXED    
Severity: normal CC: atinc, fabien.molinet, gouri.kumari, james.montemagno, jon.goldberger, me, mono-bugs+monotouch, pj.beaman, rolf, sebastien, tajinders, tj, udhams
Priority: Normal    
Version: 7.0.4.x   
Target Milestone: 7.2.1   
Hardware: Macintosh   
OS: Mac OS   
Tags: Is this bug a regression?: ---
Last known good build:
Attachments: Repro app

Description Greg Shackles 2013-11-25 12:14:56 UTC
Created attachment 5531 [details]
Repro app

I'm hitting a scenario in my apps where an exception is thrown inside of an async call, and the app is crashing due to the exception not being trapped in the try/catch block around it. I'm attaching a sample that reproduces this crash. The easiest way to repro it is to run this on a device with no network connection, so it fails immediately.

To make things even stranger, I also discovered that commenting out a line that never actually gets called at runtime actually changes this behavior, and results in the exception being caught. You can try this by commenting out line 48 of JsonClient.cs, which is wrapped in a conditional that is never true in this app. 

---

Xamarin Studio 4.1.13 (build 17)
Mono 3.2.5 ((no/964e8f0)
Xamarin.iOS 7.0.4.209 (Business Edition)

---

The stacktrace when the app crashes is:

2013-11-25 12:02:00.935 AsyncExceptionHell[3695:60b] Unhandled managed exception: Error: NameResolutionFailure (System.Net.WebException)
  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:951 
  at System.Threading.Tasks.TaskFactory`1[System.Net.WebResponse].InnerInvoke (System.Threading.Tasks.TaskCompletionSource`1 tcs, System.Func`2 endMethod, IAsyncResult l) [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62 
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[System.Net.WebResponse].GetResult () [0x00000] in <filename unknown>:0 
  at System.Net.Http.HttpClientHandler+<SendAsync>c__async0.MoveNext () [0x00245] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs:319 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62 
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[System.Net.Http.HttpResponseMessage].GetResult () [0x00000] in <filename unknown>:0 
  at System.Net.Http.HttpClient+<SendAsyncWorker>c__async0.MoveNext () [0x000a9] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:273 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62 
  at System.Runtime.CompilerServices.TaskAwaiter`1[System.Net.Http.HttpResponseMessage].GetResult () [0x00000] in <filename unknown>:0 
  at AsyncExceptionHell.AsyncExceptionHellViewController+JsonRestClient+<makeRequestAsync>c__async1`1[AsyncExceptionHell.AsyncExceptionHellViewController+Response].MoveNext () [0x00000] in <filename unknown>:0 
  at System.Threading.Tasks.SynchronizationContextContinuation.<Execute>m__0 (System.Object l) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Threading.Tasks/TaskContinuation.cs:141 
  at MonoTouch.UIKit.UIKitSynchronizationContext+<Post>c__AnonStorey88.<>m__A7 () [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/.pp-UIKitSynchronizationContext.cs:24 
  at MonoTouch.Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Developer/MonoTouch/Source/maccore/src/Foundation/.pp-NSAction.cs:87 
  at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
  at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0004c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/.pp-UIApplication.cs:38 
  at AsyncExceptionHell.Application.Main (System.String[] args) [0x00008] in /Users/greg/Projects/AsyncExceptionHell/AsyncExceptionHell/Main.cs:16
Comment 1 James Montemagno [MSFT] 2013-11-25 19:23:34 UTC
If I remove the "using" around the HTTPClient it is working just fine. I do not believe the using is necessary as it causes dispose to be called at incorrect times if there is an exception thrown.
Comment 2 Rolf Bjarne Kvinge [MSFT] 2013-11-26 07:45:14 UTC
Marek, this looks like your area.
Comment 3 Marek Safar 2013-11-26 09:02:04 UTC
I cannot reproduce this with master. Are you running this on simulator or device?
Comment 4 Greg Shackles 2013-11-26 09:14:53 UTC
I'm running this on a device
Comment 5 James Montemagno [MSFT] 2013-11-26 13:49:20 UTC
I was originally able to re-produce if I had my device in airplane mode. that was the key.
Comment 6 Marek Safar 2013-12-12 09:00:07 UTC
This looks like some runtime (LLVM) issue. Removing using (or manually written try/finally) in JsonClient.cs at line 39 fixes the issue for me. Simulator works fine too.

Note: easiest repro is to simply change url to something non-existent.
Comment 7 Zoltan Varga 2013-12-12 18:48:14 UTC
I can repro it by turning the wifi off. Its not an LLVM issue since it happens in debug mode too.
Comment 8 Zoltan Varga 2013-12-12 19:06:11 UTC
Testcase:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
		private async Task<object> foo<T>() {
			throw new Exception ();
		}

		public override async void ViewDidLoad()
		{
			base.ViewDidLoad();
		
			try
			{
				var response = await foo<object> ();
			}
			catch (Exception ex)
			{
				Console.WriteLine("EX!");
			}
		}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Make 'foo' non-generic makes the problem go away.
Comment 9 Zoltan Varga 2013-12-14 16:16:52 UTC
Fixed in mono master 5b6c4ceb6877a694ecc295467bc5eac6604af81e/mt master 7ddcc5e87d1bfe21127518249fce57334a06cabe.
Comment 10 T.J. Purtell 2014-01-26 16:34:46 UTC
I see this issue exhibited in Xamarin.Android 4.12.0 with my own similar generic based json web request utility functions.  I can't find 7ddcc5e87d1bfe21127518249fce57334a06cabe in github.com/mono/mono.  Did this not make it up to mono?  Or is there another bug here that needs to be filed?
Comment 11 Zoltan Varga 2014-01-26 19:39:02 UTC
This bug is for ios, it shouldn't happen on android.
Comment 12 Fabien Molinet 2014-01-30 06:54:38 UTC
Hi Zoltan

I expérience a similar bug in Xamarin iOS stable.
Is this issue fixed now in stable channel ?

Thanks
Fabien
Comment 13 Zoltan Varga 2014-01-30 10:31:04 UTC
No, the fix didn't make 7.0.x.
Comment 14 Fabien Molinet 2014-01-30 15:56:40 UTC
Hi Zoltan
Is it already in alpha?
If not do you have any date?
Cheers
Fabien
Comment 15 Zoltan Varga 2014-01-30 21:39:13 UTC
The fix is in the current xamarin.ios alpha I think.
Comment 16 Fabien Molinet 2014-01-31 02:01:46 UTC
Currently between Stable and Alpha the only difference is Xamarin Studio version and Mono Framework MDK version. So I guess it is also not in Alpha yet.

Could you ask your colleagues for a date? This is urgent for us since it's a major issue.
Comment 17 Rolf Bjarne Kvinge [MSFT] 2014-01-31 03:16:38 UTC
At the moment we've just released 7.0.6, and we don't have an exact date when the next release will be rolled out, since we haven't started the process yet (my very rough guess would be 4-6 weeks until any alpha release, but that's based on history instead of any future plans).

We do provide hotfix releases for Enterprise customers, if this interests you please contact sales@xamarin.com.
Comment 18 Fabien Molinet 2014-01-31 06:38:12 UTC
Thanks Rolf but we are business customers and will keep being.
If the fix won't be delivered soon is there a workaround at least? We go in production with an app in 2 weeks, this is more than important for us as it crashes the app when something goes wrong.

Thanks.
Comment 19 Fabien Molinet 2014-01-31 08:31:48 UTC
Ok we managed to "work around" the issue by removing all our generic async methods/generic async lambdas and added plenty of casts.
Comment 21 Sebastien Pouliot 2014-04-03 16:27:54 UTC
Your attached project worked on my device (iPhone5S) with 7.2.1.31
Comment 24 Udham Singh 2014-04-07 14:28:13 UTC
I have checked this issue and able to reproduce it on both Xamarin.iOS 7.2.1.20 and 7.2.1.31 with project name "Repro app". In both cases I am able to reproduce the issue on device when it's Wi-Fi is "Off", either it's AirPlane mode is "ON" or "OFF".

Screencast : http://screencast.com/t/icICLBSXfmg
Exception Log : https://gist.github.com/anonymous/45abd735f65bd28c68d2
Ide Log : https://gist.github.com/anonymous/90cf3b106a6efe14aea6

Environment Info :

Mac OS X 10.9.2
Xamarin Studio : 4.2.4 (build 32)
Xamarin.iOS : 7.2.1.20/ 7.2.1.31


I have tried to reproduce this issue with devices have iOS version 6.0.2 and 7.1 and able to reproduce with iOS version 7.1 only.

Note : The project named "Test App" which I have attached into comment 20 contains the test case mentioned into comment 8,  which makes the problem go away, so we can reproduce the issue with same.
Comment 27 T.J. Purtell 2014-06-13 23:25:26 UTC
i made my comment private and i still don't see it when logged in.  perhaps there is a forum bug as welll.
Comment 28 Zoltan Varga 2014-06-23 20:02:35 UTC
So it looks like the testcase in comment #8 is fixed, but the original issue is not. -> REOPEN.
Comment 29 Zoltan Varga 2014-06-24 18:51:09 UTC
Fixed in mono master 39d07051cf9bcbeef30610533f1e4d5a66671018/x.ios master c1916fb2e09cdd079729896290acd6c1cf67e6ba.
Comment 30 T.J. Purtell 2014-06-25 21:03:26 UTC
What release can I expect to see this land in?  These crashes have been a thorn in my side for some time now.  Thanks so much for tracking it down.
Comment 31 Zoltan Varga 2014-06-25 21:42:56 UTC
Can somebody answer this ?
Comment 32 Rolf Bjarne Kvinge [MSFT] 2014-06-26 13:39:54 UTC
T.J.: most likely in Xamarin.iOS 7.2.6, which will be released in July.
Comment 33 RandallTo 2014-07-05 09:44:00 UTC
I am having same issue. Any work around for this?
Comment 34 Tajinder Singh 2014-08-05 07:23:25 UTC
I have checked this issue with attached project 'Repro App' on iOS device when Wi-Fi is disable and observed that Exception does not occurs but I am getting System.Net.WebException in Application Output. Please let me know is it correct behavior now or not?

Application Output: https://gist.github.com/saurabh360/3f99ef01ea42dff32ea9
http://www.screencast.com/t/tAtJUrekcOfR

Environment details:
=== Xamarin Studio ===

Version 5.3 (build 412)
Installation UUID: 2591d519-875d-4afe-a3d9-5fcf391bbd2d
Runtime:
	Mono 3.8.0 ((no/9ffca33)
	GTK+ 2.24.23 (Raleigh theme)

	Package version: 308000002

=== Xamarin.Android ===

Version: 4.16.0 (Business Edition)
Android SDK: /Users/nischal/Desktop/android-sdk-macosx
	Supported Android versions:
		2.1    (API level 7)
		2.2    (API level 8)
		2.3    (API level 10)
		3.1    (API level 12)
		3.2    (API level 13)
		4.0    (API level 14)
		4.0.3  (API level 15)
		4.1    (API level 16)
		4.2    (API level 17)
		4.3    (API level 18)
		4.4    (API level 19)
		4.4.87 (API level 20)
		4.5    (API level 21)
Java SDK: /usr
java version "1.6.0_35"
Java(TM) SE Runtime Environment (build 1.6.0_35-b10-428-11M3811)
Java HotSpot(TM) 64-Bit Server VM (build 20.10-b01-428, mixed mode)

=== Apple Developer Tools ===

Xcode 4.6.3 (2068)
Build 4H1503

=== Xamarin.iOS ===

Version: 7.2.6.28 (Business Edition)
Hash: 606f31a
Branch: 
Build date: 2014-08-01 15:27:48-0400

=== Xamarin.Mac ===

Version: 1.10.0.4 (Business Edition)

=== Build Information ===

Release ID: 503000412
Git revision: 77e042831804079a649ee83092ed36c7c10773a2
Build date: 2014-08-01 06:32:22-04
Xamarin addins: 57e379e6a9454a1c0d97aa3f770e7ae7cc16c522

=== Operating System ===

Mac OS X 10.7.4
Darwin nischals-Mac-mini.local 11.4.0 Darwin Kernel Version 11.4.0
    Mon Apr  9 19:32:15 PDT 2012
    root:xnu-1699.26.8~1/RELEASE_X86_64 x86_64