Alamofire: EXC_BAD_ACCESS crash in withTaskCancellationHandler on Mac app designed for iPad and Xcode 16

What did you do?

Started experiencing crashes with Swift concurrency functions running Xcode 16 on macOS 14.x (not able to update to Sequoia yet to test that) for an app that supports iOS, iPadOS, and macOS (designed for iPad). Only the macOS app is crashing and iOS/iPadOS still run normally. These all worked normally before the Xcode 16 update.

What did you expect to happen?

Data to be retrieved normally with Swift concurrency and Alamofire.

What happened instead?

A crash occurs at withTaskCancellationHandler<A>(operation:onCancel:isolation:) + 240 every time we call Alamofire serializingData() on the macOS app (designed for iPad).

Sample crash:

Thread 1 Crashed:
0   NetworkBugTest.debug.dylib    	       0x10134e55c withTaskCancellationHandler<A>(operation:onCancel:isolation:) + 240
1   NetworkBugTest.debug.dylib    	       0x10134dee9 DataTask.response.getter + 1 (Concurrency.swift:120)
2   NetworkBugTest.debug.dylib    	       0x10134e82d DataTask.result.getter + 1 (Concurrency.swift:133)
3   NetworkBugTest.debug.dylib    	       0x10134eabd DataTask.value.getter + 1 (Concurrency.swift:139)
4   NetworkBugTest.debug.dylib    	       0x101242559 ContentViewModel.callApiUsingResponseDataAsync() + 1 (ContentViewModel.swift:39)
5   NetworkBugTest.debug.dylib    	       0x10124181d closure #1 in ContentViewModel.getData() + 1 (ContentViewModel.swift:16)
6   NetworkBugTest.debug.dylib    	       0x101241d69 partial apply for closure #1 in ContentViewModel.getData() + 1
7   NetworkBugTest.debug.dylib    	       0x1012430fd $sxIeAgHr_xs5Error_pIegHrzo_s8SendableRzs5NeverORs_r0_lTRTQ0_ + 1
8   NetworkBugTest.debug.dylib    	       0x101243325 $sxIeAgHr_xs5Error_pIegHrzo_s8SendableRzs5NeverORs_r0_lTRTATQ0_ + 1
9   libswift_Concurrency.dylib    	       0x2483a30f9 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1

This is the sample method that is failing. Just using the Chuck Norris joke db for testing. See attached sample minimal project.

/// Call API using Alamofire w/Swift concurrency.  Failing sample on macOS designed for iPad
/// - Returns: Joke object
func callApiUsingResponseDataAsync() async throws -> Joke {
    let url = URL(string: "https://api.chucknorris.io/jokes/random")!
    let request = Session.default.request(url, method: .get)
    do {
        let dataTask = request
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .serializingData()
        
        let data = try await dataTask.value
        return try JSONDecoder().decode(Joke.self, from: data)
    } catch {
        throw error
    }
}

Failing in Concurrency.swift on the await withTaskCancellationHandler line:

private func dataTask<Value>(automaticallyCancelling shouldAutomaticallyCancel: Bool,
                             forResponse onResponse: @escaping (@escaping (DataResponse<Value, AFError>) -> Void) -> Void)
    -> DataTask<Value> {
    let task = Task {
        await withTaskCancellationHandler {
            await withCheckedContinuation { continuation in
                onResponse {
                    continuation.resume(returning: $0)
                }
            }
        } onCancel: {
            self.cancel()
        }
    }

    return DataTask<Value>(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel)
}

Alamofire Environment

Alamofire Version: 5.9.1 Dependency Manager: SPM Xcode Version: 16.0 Swift Version: 5.10 Platform(s) Running Alamofire: iOS, iPadOS, macOS (designed for iPad) macOS Version Running Xcode: 14.7

Demo Project

ℹ Please link to or upload a project we can download that reproduces the issue. [NetworkBugTest.zip Crash report.log ](https://github.com/user-attachments/files/17045617/NetworkBugTest.zip)

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 15 (7 by maintainers)

Most upvoted comments

I’ve pushed a bug/xcode16-cancellation-handler-crash branch which remove the cancellation handler in that call altogether, so that, in combination with passing automaticallyCancelling: false to any async serializing* methods, should avoid the issue. Of course, that means all cancellation of async requests just won’t work, which probably isn’t a good idea.

Alternatively, you can wrap Alamofire’s completion handler API yourself using withUnsafeContinuation (withCheckedContinuation seems to have the same crash) and cancel the request directly when needed.

Hopefully Apple ships a fix for this quickly.

Do we know if Xcode 16.1 (releasing 10/28 I think) includes the fix for this issue?

Not fixed yet… I downgraded to Xcode 15.4 to avoid this crash.

Looks like this is a known issue and is already fixed for what will hopefully be the upcoming Swift 6.0.1 release. They haven’t announced anything but hopefully the release won’t be long. I suggest staying on Xcode 15.4 until they do.

Offhand I’d say this is some sort of runtime issue when compiled with the new compiler. It runs fine on Sequoia, so it’s possible this is some sort of back deployment issue. I’ll have to set up a macOS 14 environment to keep testing this, but I’m not sure what a workaround would look like for now.

I am seeing what looks like a similar crash on iOS 18/iOS 18.1 devices. I have not been able to reproduce locally but seeing the reports come through the organizer.

Incident Identifier: C5331198-3922-471F-8E39-57186BBB962B
Distributor ID:      com.apple.AppStore
Hardware Model:      iPhone16,2
Process:             MyApp [866]
Path:                /private/var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp
Identifier:          com.MyApp.release
Version:             10.0.1 (1)
AppStoreTools:       16A242b
AppVariant:          1:iPhone16,2:18
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.MyApp.release [989]

Date/Time:           2024-09-21 06:30:38.3210 -0500
Launch Time:         2024-09-21 06:18:03.0691 -0500
OS Version:          iPhone OS 18.1 (22B5007p)
Release Type:        Beta
Baseband Version:    2.15.01
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000004
Exception Codes: 0x0000000000000001, 0x0000000000000004
VM Region Info: 0x4 is not in any region.  Bytes before following region: 4340908028
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->  
      __TEXT                   102bd0000-102be0000 [   64K] r-x/r-x SM=COW  /var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [866]

Triggered by Thread:  3

Thread 3 Crashed:
0   MyApp                        	0x0000000103b00b8c withTaskCancellationHandler<A>(operation:onCancel:isolation:) + 108 (/<compiler-generated>:0)
1   MyApp                        	0x0000000103b0284d closure #1 in DataRequest.dataTask<A>(automaticallyCancelling:forResponse:) + 1 (Concurrency.swift:352)
2   MyApp                        	0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1
3   MyApp                        	0x0000000102f80841 closure #1 in DataTask.response.getter + 1
4   MyApp                        	0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1
5   libswift_Concurrency.dylib    	0x000000019164e689 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:471)

Also asking about it in an Apple forum: https://developer.apple.com/forums/thread/764413

concurrency_crash_report.txt.log

Does anyone know if the aforementioned fix will also address the problem in iOS or is it just a fix for macOS/iPadOS?

One other thing to check: make sure you’re compiling in Release mode (or a configuration with Release in the name, Xcode uses name matching to turn on release optimizations in packages), as the crash seems to only appear when built in debug mode. I was able to run the provided example in Release mode just fine, without any of the workarounds.

Edit: that is to say, if you have an “AppStore” build configuration you use to ship to the store, it won’t compile the included packages in release mode (optimized), even if you’ve set your project to use optimizations. You need to include the word “release” somewhere in the configuration name for Xcode to build it properly, so “AppStoreRelease” would properly line things up. Otherwise it defaults to debug (I think, this is all undocumented).