Weird crashes when accessing Swift Array

For some time now Xcode has been downloading crash reports from users of my app about crashes related to arrays. One of them looks like this:

...
Code Type:             ARM-64
Parent Process:        launchd [1]
User ID:               501

Date/Time:             2024-07-18 14:59:40.4375 +0800
OS Version:            macOS 15.0 (24A5289h)
...

Crashed Thread:        0

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000001, 0x00000001045048b8

Termination Reason:    Namespace SIGNAL, Code 5 Trace/BPT trap: 5
Terminating Process:   exc handler [1771]


Thread 0 Crashed:
0   MyApp                      	0x00000001045048b8 specialized Collection.map<A>(_:) + 596
1   MyApp                      	0x00000001045011e4 MyViewController.validateToolbarButtons() + 648 (MyViewController.swift:742)
...

The relevant code looks like this:

class MyViewController {
    func validateToolbarButtons() {
        let indexes = tableView.clickedRow == -1 || tableView.selectedRowIndexes.contains(tableView.clickedRow) ? tableView.selectedRowIndexes : IndexSet(integer: tableView.clickedRow)
        let items = indexes.map({ myArray[$0] })
        ...
    }
}

The second crash looks like this:

...
Code Type:             X86-64 (Native)
Parent Process:        launchd [1]
User ID:               502

Date/Time:             2024-07-15 15:53:35.2229 -0400
OS Version:            macOS 15.0 (24A5289h)
...

Crashed Thread:        0

Exception Type:        EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes:       0x0000000000000001, 0x0000000000000000

Termination Reason:    Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process:   exc handler [13244]


Thread 0 Crashed:
0   libswiftCore.dylib              	0x00007ff812904fc0 _assertionFailure(_:_:flags:) + 288
1   MyApp                            	0x0000000101a31e04 specialized _ArrayBuffer._getElementSlowPath(_:) + 516
2   MyApp                            	0x00000001019d04eb MyObject.myProperty.setter + 203 (MyObject.swift:706)
3   MyApp                            	0x000000010192f66e MyViewController.controlTextDidChange(_:) + 190 (MyViewController.swift:166)
...

And the relevant code looks like this:

class MyObject {
    var myProperty: [MyObject] {
        get {
            ...
        }
        set {
            let items = newValue.map({ $0.id })
            ...
        }
    }
}

What could cause such crashes? Could they be caused by anything other than concurrent access from multiple threads (which I'm quite sure is not the case here, as I only access these arrays from the main thread)?

Answered by DTS Engineer in 796453022

While these crashes have different codes, they’re likely to be caused by the some immediate issue: a Swift runtime trap. See EXC_BREAKPOINT (SIGTRAP) and EXC_BAD_INSTRUCTION (SIGILL). You get different exception codes because the first crash is on Apple silicon and the second on Intel.


Regarding the first crash, the most likely cause is this: myArray[$0]. If $0 is out of bounds, the array access will trap.


The second trap is trickier. Note how frame is _getElementSlowPath(…). This suggests that you’re working with a non-native array, like an NSArray. Those do lazy type enforcement, so the setter will check that the element type is correct and trap if it’s not. I think that’s what you’re hitting here.

Consider this program:

import Foundation

class MyElement {
    let myProperty: Int
    init(myProperty: Int) {
        self.myProperty = myProperty
    }
}

func printElements(ns: NSArray) {
    print("before cast")
    let a = ns as! [MyElement]
    print("after cast")
    for e in a {
        print(e.myProperty)
    }
}

func main() {
    let ns = NSMutableArray()
    ns.add(MyElement(myProperty: 42))
    ns.add(MyElement(myProperty: 6))
    ns.add("Hello Cruel World!" as NSString)
    ns.add(MyElement(myProperty: 7))
    printElements(ns: ns)
}

main()

When I run it on my Mac (Xcode 16.0b3 on macOS 14.5) I see this output:

before cast
after cast
42
6
Fatal error: NSArray element failed to match the Swift Array Element type
Expected MyElement but found __NSCFString

This shows how the ns as! [MyElement] cast is done lazily, only triggering a trap when you try to access the element that’s the wrong type.

Notably, the crashing thread backtrace looks like this:

(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = Fatal error: NSArray element failed to match the Swift Array Element type
Expected MyElement but found __NSCFString
    frame #0: 0x00000001a53f9890 libswiftCore.dylib`_swift_runtime_on_report
    frame #1: 0x00000001a54b8c74 libswiftCore.dylib`_swift_stdlib_reportFatalError + 176
    frame #2: 0x00000001a508b114 libswiftCore.dylib`function signature specialization <Arg[1] = [Closure Propagated : closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, flags: Swift.UInt32) -> Swift.Never, Argument Types : [Swift.UnsafeBufferPointer<Swift.UInt8>Swift.UInt32]> of generic specialization <()> of Swift.String.withUTF8<τ_0_0>((Swift.UnsafeBufferPointer<Swift.UInt8>) throws -> τ_0_0) throws -> τ_0_0 + 156
    frame #3: 0x00000001a5062c84 libswiftCore.dylib`Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, flags: Swift.UInt32) -> Swift.Never + 180
    frame #4: 0x00000001a5064c38 libswiftCore.dylib`Swift._ArrayBuffer._getElementSlowPath(Swift.Int) -> Swift.AnyObject + 2056
    frame #5: 0x00000001a506b6d8 libswiftCore.dylib`Swift.Array.subscript.read : (Swift.Int) -> τ_0_0 + 304
    frame #6: 0x00000001a506b574 libswiftCore.dylib`protocol witness for Swift.Collection.subscript.read : (τ_0_0.Index) -> τ_0_0.Element in conformance Swift.Array<τ_0_0> : Swift.Collection in Swift + 68
    frame #7: 0x00000001a5055e4c libswiftCore.dylib`Swift.IndexingIterator.next() -> Swift.Optional<τ_0_0.Element> + 668
  * frame #8: 0x0000000100001a64 Test`printElements(ns=4 elements) at main.swift:14:5
    frame #9: 0x00000001000016d0 Test`main() at main.swift:25:5
    frame #10: 0x000000010000159c Test`main at main.swift:28:1
    frame #11: 0x0000000194ffe0e0 dyld`start + 2360

Frames 4 and 3 should ring some bells.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

While these crashes have different codes, they’re likely to be caused by the some immediate issue: a Swift runtime trap. See EXC_BREAKPOINT (SIGTRAP) and EXC_BAD_INSTRUCTION (SIGILL). You get different exception codes because the first crash is on Apple silicon and the second on Intel.


Regarding the first crash, the most likely cause is this: myArray[$0]. If $0 is out of bounds, the array access will trap.


The second trap is trickier. Note how frame is _getElementSlowPath(…). This suggests that you’re working with a non-native array, like an NSArray. Those do lazy type enforcement, so the setter will check that the element type is correct and trap if it’s not. I think that’s what you’re hitting here.

Consider this program:

import Foundation

class MyElement {
    let myProperty: Int
    init(myProperty: Int) {
        self.myProperty = myProperty
    }
}

func printElements(ns: NSArray) {
    print("before cast")
    let a = ns as! [MyElement]
    print("after cast")
    for e in a {
        print(e.myProperty)
    }
}

func main() {
    let ns = NSMutableArray()
    ns.add(MyElement(myProperty: 42))
    ns.add(MyElement(myProperty: 6))
    ns.add("Hello Cruel World!" as NSString)
    ns.add(MyElement(myProperty: 7))
    printElements(ns: ns)
}

main()

When I run it on my Mac (Xcode 16.0b3 on macOS 14.5) I see this output:

before cast
after cast
42
6
Fatal error: NSArray element failed to match the Swift Array Element type
Expected MyElement but found __NSCFString

This shows how the ns as! [MyElement] cast is done lazily, only triggering a trap when you try to access the element that’s the wrong type.

Notably, the crashing thread backtrace looks like this:

(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = Fatal error: NSArray element failed to match the Swift Array Element type
Expected MyElement but found __NSCFString
    frame #0: 0x00000001a53f9890 libswiftCore.dylib`_swift_runtime_on_report
    frame #1: 0x00000001a54b8c74 libswiftCore.dylib`_swift_stdlib_reportFatalError + 176
    frame #2: 0x00000001a508b114 libswiftCore.dylib`function signature specialization <Arg[1] = [Closure Propagated : closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, flags: Swift.UInt32) -> Swift.Never, Argument Types : [Swift.UnsafeBufferPointer<Swift.UInt8>Swift.UInt32]> of generic specialization <()> of Swift.String.withUTF8<τ_0_0>((Swift.UnsafeBufferPointer<Swift.UInt8>) throws -> τ_0_0) throws -> τ_0_0 + 156
    frame #3: 0x00000001a5062c84 libswiftCore.dylib`Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, flags: Swift.UInt32) -> Swift.Never + 180
    frame #4: 0x00000001a5064c38 libswiftCore.dylib`Swift._ArrayBuffer._getElementSlowPath(Swift.Int) -> Swift.AnyObject + 2056
    frame #5: 0x00000001a506b6d8 libswiftCore.dylib`Swift.Array.subscript.read : (Swift.Int) -> τ_0_0 + 304
    frame #6: 0x00000001a506b574 libswiftCore.dylib`protocol witness for Swift.Collection.subscript.read : (τ_0_0.Index) -> τ_0_0.Element in conformance Swift.Array<τ_0_0> : Swift.Collection in Swift + 68
    frame #7: 0x00000001a5055e4c libswiftCore.dylib`Swift.IndexingIterator.next() -> Swift.Optional<τ_0_0.Element> + 668
  * frame #8: 0x0000000100001a64 Test`printElements(ns=4 elements) at main.swift:14:5
    frame #9: 0x00000001000016d0 Test`main() at main.swift:25:5
    frame #10: 0x000000010000159c Test`main at main.swift:28:1
    frame #11: 0x0000000194ffe0e0 dyld`start + 2360

Frames 4 and 3 should ring some bells.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

This shows how the ns as! [MyElement] cast is done lazily

Thanks, this already helped me reproduce and fix the second crash. The array was coming from a token field's objectValue.

Regarding the first crash, I noticed something strange. The crash report seems to imply that a particular method called another one, which is impossible. Let me show and explain to you the rest of the stacktrace:

...
Code Type:             ARM-64
Parent Process:        launchd [1]
User ID:               501

Date/Time:             2024-07-18 14:59:40.4375 +0800
OS Version:            macOS 15.0 (24A5289h)
...

Crashed Thread:        0

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000001, 0x00000001045048b8

Termination Reason:    Namespace SIGNAL, Code 5 Trace/BPT trap: 5
Terminating Process:   exc handler [1771]


Thread 0 Crashed:
0   MyApp                         	0x00000001045048b8 specialized Collection.map<A>(_:) + 596
1   MyApp                         	0x00000001045011e4 MyViewController.validateToolbarButtons() + 648 (MyViewController.swift:742)
...
12  MyApp                         	0x00000001044fcef4 MyViewController.myOtherAction(_:) + 184 (MyViewController.swift:455)
13  MyApp                         	0x00000001044fff28 @objc MyViewController.myModalAction(_:) + 80
14  AppKit                        	0x000000019e2ae13c -[NSApplication(NSResponder) sendAction:to:from:] + 460
15  AppKit                        	0x000000019e375b08 -[NSMenuItem _corePerformAction] + 372
16  AppKit                        	0x000000019ea4be30 _NSMenuPerformActionWithHighlighting + 152
17  AppKit                        	0x000000019e3ad5d0 -[NSMenu performActionForItemAtIndex:] + 200
18  AppKit                        	0x000000019e3ad4f0 -[NSMenu _internalPerformActionForItemAtIndex:] + 76
19  AppKit                        	0x000000019ea4204c +[NSCocoaMenuImpl _performActionForMenuItem:] + 176
20  AppKit                        	0x000000019e84ff58 -[NSMenuTrackingSession _performPostTrackingDismissalActions] + 268
21  AppKit                        	0x000000019e84fc60 -[NSMenuTrackingSession startRunningMenuEventLoop:] + 1332
22  AppKit                        	0x000000019e84f6d0 -[NSMenuTrackingSession startMonitoringEvents:] + 256
23  AppKit                        	0x000000019efe5d78 -[NSContextMenuTrackingSession startMonitoringEvents:] + 144
24  AppKit                        	0x000000019e8048f8 +[NSContextMenuImpl presentPopup:fromView:withContext:animated:] + 848
25  AppKit                        	0x000000019ea4d5ec _NSPopUpMenu + 2128
26  AppKit                        	0x000000019ea51cbc -[NSCocoaMenuImpl _popUpContextMenu:withEvent:forView:withFont:] + 304
27  AppKit                        	0x000000019e429acc -[NSMenu _popUpContextMenu:withEvent:forView:withFont:] + 208
28  AppKit                        	0x000000019ece4658 -[NSView _showMenuForEvent:] + 72
29  AppKit                        	0x000000019e425ff4 -[NSView rightMouseDown:] + 76
30  AppKit                        	0x000000019e7225e0 -[NSControl _rightMouseUpOrDown:] + 352
31  AppKit                        	0x000000019ed81ec4 _routeRightMouseDownEvent + 264
32  AppKit                        	0x000000019e2348f8 -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 420
33  AppKit                        	0x000000019e234584 -[NSWindow(NSEventRouting) sendEvent:] + 284
34  AppKit                        	0x000000019ea1f568 -[NSApplication(NSEventRouting) sendEvent:] + 1656
35  AppKit                        	0x000000019e632b78 -[NSApplication _handleEvent:] + 60
36  AppKit                        	0x000000019e100914 -[NSApplication run] + 520
37  AppKit                        	0x000000019e0d7094 NSApplicationMain + 888
38  MyApp                         	0x000000010446ca80 main + 128 (main.swift:12)
39  dyld                          	0x000000019a16b274 start + 2840

The ellipsis only hides methods from my own classes. Directly below it, it would seem that @objc MyViewController.myModalAction(_:), which shows an app modal window, somehow calls MyViewController.myOtherAction(_:), but myOtherAction can only be called by a menu or the press of a toolbar button which are both disabled by the modal window shown by myModalAction. Does this mean that myOtherAction is called somehow when the modal window opened by myModalAction is closed?

Another interesting point: I don't know why myModalAction is prefixed with @objc, since both are declared as @IBAction func methodName(_ sender: Any). The only difference is that myModalAction is set as a table view's doubleAction, but from the rest of the stacktrace it seems like myModalAction is called by a menu.

this already helped me reproduce and fix the second crash.

Yay!

I don't know why myModalAction is prefixed with @objc, since both are declared as @IBAction func methodName(_ sender: Any).

This is a critical point, so lemme explain that and then come back to your backtrace.

Consider an IBAction like this:

@IBAction
private func testAction(_ sender: Any) {
    print("AppDelegate.testAction(_:)")
}    

If I set a breakpoint on the print(…) line and then run the app and click the button, I see this backtrace:

* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: … Test.debug.dylib`AppDelegate.testAction(…) at AppDelegate.swift:14:15
    frame #1: … Test.debug.dylib`@objc AppDelegate.testAction(_:) at <compiler-generated>:0
    frame #2: … AppKit`-[NSApplication(NSResponder) sendAction:to:from:] + 460

Frame 2 is AppKit doing its target/action thing. Frame 0 is my code, written in Swift. Between those is frame 1, a thunk created by the Swift compiler to adapt the Objective-C calling conventions of the caller to the Swift calling conventions of the callee.

This is, for example, why my Swift method can use Any rather than AnyObject. Or, if I declared my Swift method to take an NSButton, the thunk would insert a dynamic type check to ensure that it is actually a button and not some other type.

Note that frame 0 has a source file and line in its symbolication, but frame 1 says <compiler-generated>:0.

In your backtrace, the obvious reading is that the thunk in frame 13 has called the wrong original method. That seems… well… unlikely. My best guess is that there’s something wonky with the symbolication.

I usually investigate issues like this at the assembly level. For example, you can use a link map to work out exactly which bit of code came from where. And then disassemble the code pointed to be the backtrace to make sure it’s the thunk that you expect it to be.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I usually investigate issues like this at the assembly level

Thanks. I never did this before and I wasn't able to find anything helpful on the internet. otool can disassemble, but of course the addresses are different than those in the crash report. Is there a way to easily map the addresses, or are there better Terminal tools for this?

Is there a way to easily map the addresses … ?

That depends on what you mean by “easily” (-:

The value you need to calculate is the image’s slide, that is, the actual load address minus the expected load address. Once you have this value, you can subtract it from the address of the symbol in the crash report to get the address of the symbol within your Mach-O.

Modern Mach-O images are position independent, and thus have an expected load address of 0. Thus, the slide it just the actual load address of the image.

I just updated An Apple Library Primer to define these terms. It’s full of lots of other useful info about this stuff.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks, I just tried that. Then I realized that I can barely see any of my app's symbol names in the disassembly (which I created with otool -vt /path/to/executable). For instance I cannot find any of the method names mentioned in the crash reports. The disassembly looks like this:

~/Library/Developer/Xcode/Archives/2024-07-12/MyApp macOS 12.07.2024, 20.43.xcarchive/Products/Applications/MyApp.app/Contents/MacOS/MyApp (architecture arm64):
(__TEXT,__text) section
0000000100004a00	stp	x20, x19, [sp, #-0x20]!
0000000100004a04	stp	x29, x30, [sp, #0x10]
0000000100004a08	add	x29, sp, #0x10
0000000100004a0c	adrp	x8, 567 ; 0x10023b000
0000000100004a10	ldr	x0, [x8, #0xc30] ; Objc class ref: bad class ref
0000000100004a14	bl	0x1001d664c ; symbol stub for: _objc_opt_self
0000000100004a18	adrp	x8, 567 ; 0x10023b000
0000000100004a1c	ldr	x1, [x8, #0x588] ; Objc selector ref: sharedApplication
0000000100004a20	bl	0x1001d6634 ; Objc message: -[x0 sharedApplication]
0000000100004a24	mov	x29, x29
0000000100004a28	bl	0x1001d667c ; symbol stub for: _objc_retainAutoreleasedReturnValue
0000000100004a2c	adrp	x19, 587 ; 0x10024f000
0000000100004a30	str	x0, [x19, #0xb30]
0000000100004a34	mov	x0, #0x0
0000000100004a38	bl	0x1000e6c04
0000000100004a3c	bl	0x1001d6604 ; symbol stub for: _objc_allocWithZone
...

When you wrote

disassemble the code pointed to be the backtrace to make sure it’s the thunk that you expect it to be

were you thinking of a particular command that creates disassemblies with symbol names, or how would you "make sure it's the thunk that you expect it to be"?

were you thinking of a particular command that creates disassemblies with symbol names

I generally do this stuff in LLDB.

The trick there is to make sure you’re debugging the right build. You’re on the Mac, and it’s actually pretty straightforward here: Just run LLDB from the command line and target your built binary:

% lldb /path/to/your.app
…
(lldb) r
…

Alternatively, run the app from Finder and then, in Xcode, choose Debug > Attach to Process.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I was looking forward to using lldb, but both when running the Terminal command or trying to attach from my running app in Xcode I get an error

process exited with status -1 (attach failed (Not allowed to attach to process.  Look in the console messages (Console.app), near the debugserver entries, when the attach failed.  The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.))

And the Console shows these messages:

3898	debugserver	default	13:45:23.707652+0200	debugserver will use os_log for internal logging.
3898	debugserver	default	13:45:23.708012+0200	debugserver-@(#)PROGRAM:LLDB  PROJECT:lldb-1500.0.404.7
 for arm64.
3898	debugserver	default	13:45:23.708050+0200	Got a connection, waiting for process information for launching or attaching.
3898	debugserver	default	13:45:23.708297+0200	[LaunchAttach] START 3898 vAttach to pid 605
3898	debugserver	default	13:45:23.708436+0200	[LaunchAttach] (3898) about to task_for_pid(605)
3898	debugserver	errore	13:45:23.708472+0200	error: [LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(605) failed: ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure)
3898	debugserver	default	13:45:23.708484+0200	1 +0.000000 sec [0f3a/0103]: error: ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure) err = ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure) (0x00000005)
3898	debugserver	default	13:45:23.719499+0200	[LaunchAttach] (3898) about to task_for_pid(605)
3898	debugserver	errore	13:45:23.719532+0200	error: [LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(605) failed: ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure)
3898	debugserver	default	13:45:23.719543+0200	2 +0.011059 sec [0f3a/0103]: error: ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure) err = ::task_for_pid ( target_tport = 0x0203, pid = 605, &task ) => err = 0x00000005 ((os/kern) failure) (0x00000005)

and so on. The rest is attached as a text file, putting it inline in this reply shows a validation error "Your reply must include text in the body." (for which I created FB14466890).

At first I tried 3 times from the Terminal, but each time the Mac stopped responding after a couple seconds and after a couple minutes restarted automatically (after the third time I created FB14466119). Xcode didn't freeze the Mac, but instead showed a button "report issue", which I clicked and automatically generated FB14466745.

The most likely cause of this problem is that your app isn’t signed with the get-task-allow entitlement.

This is one of the many places where using Xcode’s Product > Archive is a huge benefit. If you have an Xcode archive of the app that you shipped, you can use the Xcode organiser to export a development-signed version of your app. That’ll have the same code as the original app — including the same LC_UUID values — but with the code signing set up for development. You’ll then be able to attach to that from LLDB.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

you can use the Xcode organiser to export a development-signed version of your app

I selected the archive in the Xcode Organizer, clicked Distribute App > Custom > Debugging > Automatically Manage Signing > Export. Then launched the exported app from the Finder and in Xcode selected Debug > Attach to Process. It still gives me the exact same error as before, with the exact same Console messages.

That’ll have the same code as the original app — including the same LC_UUID values — but with the code signing set up for development

Does that mean that the entitlements file is actually modified when creating the archive? I ran the Terminal command

codesign -d --entitlements - --xml /path/to/exported/app

but it has the same entitlements as before.

Well, blat! Xcode seems to be doing the wrong thing here. In my defence, I’ve done this many times for iOS and Xcode does do the right thing for iOS apps )-:

Pasted in below is a detailed explanation of the issue, taken from the bug I just filed about this (r. 132479265).

There are two ways around it:

  • If you only want to look at the app, rather than run it, you can ignoer the whole thing:

    % lldb Test760029.app
    …
    (lldb) disas -n '$s10Test76002914ViewControllerC11viewDidLoadyyFTo'
    Test760029`@objc ViewController.viewDidLoad():
    Test760029[0x100002814] <+0>:  sub    sp, sp, #0x30
    Test760029[0x100002818] <+4>:  stp    x20, x19, [sp, #0x10]
    Test760029[0x10000281c] <+8>:  stp    x29, x30, [sp, #0x20]
    Test760029[0x100002820] <+12>: add    x29, sp, #0x20
    Test760029[0x100002824] <+16>: mov    x19, x0
    Test760029[0x100002828] <+20>: bl     0x100002c04               ; type metadata accessor for Test760029.ViewController at <compiler-generated>
    …
    
    

    LLDB’s static inspection doesn’t care about the get-task-allow limitation.

  • If want to run the app, you’ll have to re-sign it and apply the get-task-allow entitlement:

    % codesign -d --ent tmp.entitlements --xml Test760029.app
    …
    % /usr/libexec/PlistBuddy -c "Add :com.apple.security.get-task-allow bool true" tmp.entitlements  
    % codesign -s "Apple Development: Quinn Quinn (7XFU7D52S4)" -f -o runtime --ent tmp.entitlements Test760029.app
    …
    

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"


Consider an iOS app created from the iOS > App template. If you choose Product > Build you get this:

% codesign -d --ent - Test760029i.app 
…
[Dict]
    …
    [Key] get-task-allow
    [Value]
        [Bool] true

If you choose Product > Archive you get this:

% codesign -d --ent - Test760029i.app 
…
[Dict]
    …
	[Key] get-task-allow
	[Value]
		[Bool] true

If you export the archive using Distribute App > Custom > App Store Connect > Export, you get this:

% codesign -d --ent - Test760029i.app
…
[Dict]
    …
	[Key] get-task-allow
	[Value]
		[Bool] false

But if you export using Distribute App > Custom > Debugging > Export, you get this:

% codesign -d --ent - Test760029i.app
…
[Dict]
    …
	[Key] get-task-allow
	[Value]
		[Bool] true

This all makes sense. The get-task-allow entitlement is enabled on the App Store Connect build and nowhere else.


Now repeat this process for a macOS app. Product > Build looks like this:

% codesign -d --ent - Test760029.app 
…
[Dict]
    …
	[Key] com.apple.security.get-task-allow
	[Value]
		[Bool] true

So for so good. Note that the specific entitlement is different, but that’s expected on macOS.

Now try Product > Archive:

% codesign -d --ent - Test760029.app
…
[Dict]
    [Key] com.apple.security.app-sandbox
    [Value]
        [Bool] true
    [Key] com.apple.security.files.user-selected.read-only
    [Value]
        [Bool] true

This is probably not good. Xcode hasn’t included the entitlement in the Xcode archive. However, you’re not supposed to run an app from Xcode archive, so it’s not fatal.

The issue arise when you export using Distribute App > Custom > Debugging > Export:

% codesign -d -v --ent - Test760029.app
…
CodeDirectory v=20500 size=787 flags=0x10000(runtime) …
…
[Dict]
    [Key] com.apple.security.app-sandbox
    [Value]
        [Bool] true
    [Key] com.apple.security.files.user-selected.read-only
    [Value]
        [Bool] true

This is just wrong. The app has the hardened runtime enabled (runtime), so you won’t be able to debug it without setting get-task-allow. However, Xcode hasn’t added that entitlement back in.


If you only want to look at the app, rather than run it, you can ignoer the whole thing:

So I ran

lldb ~/Library/Developer/Xcode/Archives/2024-07-12/MyApp\ macOS\ 12.07.2024\,\ 20.43.xcarchive/Products/Applications/MyApp.app

To translate the addresses from the crash report to lldb, it wasn't sufficient to subtract the binary image base address, but I found some help at Symbolicating with LLDB. By running

lldb image list

which outputs

[  0] 2521131E-2080-387D-B96E-8DB6AA18E011 0x0000000100000000 ~/Library/Developer/Xcode/Archives/2024-07-12/MyApp macOS 12.07.2024, 20.43.xcarchive/Products/Applications/MyApp.app/Contents/MacOS/MyApp 
      /System/Volumes/Data/~/Library/Developer/Xcode/Archives/2024-07-12/MyApp macOS 12.07.2024, 20.43.xcarchive/dSYMs/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp
[  1] 37BBC384-0755-31C7-A808-0ED49E44DD8E 0x00000001800b8000 /usr/lib/dyld 
...

I found out that there is another base address here 0x0000000100000000 (which almost looks like 0x0) that I also have to subtract. So the real offset is

0x104468000 - 0x0000000100000000 = 0x004468000

which I could set with

lldb target modules load --file MyApp --slide 0x004468000

So now I can disassemble by directly providing the addresses from the crash report, and I confirm that all crash report addresses point to the correct symbol names.

But when I run

lldb disas -a 0x00000001044fff28

(where 0x00000001044fff28 is the address for the call to MyViewController.myModalAction in the crash report), I get this relatively short and rather obscure output:

MyApp`merged @objc MyApp.MyViewController.myModalAction(Any) -> ():
0x1044ffed8 <+0>:   sub    sp, sp, #0x50
0x1044ffedc <+4>:   stp    x22, x21, [sp, #0x20]
0x1044ffee0 <+8>:   stp    x20, x19, [sp, #0x30]
0x1044ffee4 <+12>:  stp    x29, x30, [sp, #0x40]
0x1044ffee8 <+16>:  add    x29, sp, #0x40
0x1044ffeec <+20>:  mov    x19, x3
0x1044ffef0 <+24>:  mov    x20, x2
0x1044ffef4 <+28>:  mov    x21, x0
0x1044ffef8 <+32>:  mov    x0, x2
0x1044ffefc <+36>:  bl     0x1001d6a60               ; symbol stub for: swift_unknownObjectRetain
0x1044fff00 <+40>:  mov    x0, x21
0x1044fff04 <+44>:  bl     0x1001d6664               ; symbol stub for: objc_retain
0x1044fff08 <+48>:  mov    x21, x0
0x1044fff0c <+52>:  mov    x8, sp
0x1044fff10 <+56>:  mov    x0, x20
0x1044fff14 <+60>:  bl     0x1001d5ee4               ; symbol stub for: Swift._bridgeAnyObjectToAny(Swift.Optional<Swift.AnyObject>) -> Any
0x1044fff18 <+64>:  mov    x0, x20
0x1044fff1c <+68>:  bl     0x1001d6a54               ; symbol stub for: swift_unknownObjectRelease
0x1044fff20 <+72>:  mov    x20, x21
0x1044fff24 <+76>:  blr    x19
0x1044fff28 <+80>:  mov    x0, sp
0x1044fff2c <+84>:  bl     0x100008ce4               ; __swift_destroy_boxed_opaque_existential_0 at <compiler-generated>
0x1044fff30 <+88>:  mov    x0, x21
0x1044fff34 <+92>:  bl     0x1001d6658               ; symbol stub for: objc_release
0x1044fff38 <+96>:  ldp    x29, x30, [sp, #0x40]
0x1044fff3c <+100>: ldp    x20, x19, [sp, #0x30]
0x1044fff40 <+104>: ldp    x22, x21, [sp, #0x20]
0x1044fff44 <+108>: add    sp, sp, #0x50
0x1044fff48 <+112>: ret    

Whereas if I run

lldb disas -n myModalAction

I get a way longer output which contains the expected calls to my own other methods, starting with

MyApp`MyViewController.myModalAction(_:):
0x1044f9578 <+0>:    stp    x28, x27, [sp, #-0x60]!
...

Notice how the first lines of these two outputs differ:

MyApp`merged @objc MyApp.MyViewController.myModalAction(Any) -> ()

vs

MyApp`MyViewController.myModalAction(_:)

What does this difference mean? The line in the crash report

13  MyApp                      	0x00000001044fff28 @objc MyViewController.myModalAction(_:) + 80

is the only one that doesn't make sense and couldn't possibly call the line above it.

[quote='797124022, Nickkk, /thread/760029?answerId=797124022#797124022, /profile/Nickkk'] I found out that there is another base address here 0x0000000100000000 (which almost looks like 0x0) that I also have to subtract. [/quote]

Right, yeah, I should’ve mentioned that. A Mach-O executable starts with a 4 GiB zero page segment, so the load address of the __TEXT segment is 0x0000000100000000. Consider:

% otool -l Test760029.app/Contents/MacOS/Test760029 
Test760029.app/Contents/MacOS/Test760029 (architecture x86_64):
Load command 0
      cmd LC_SEGMENT_64
  cmdsize 72
  segname __PAGEZERO
   vmaddr 0x0000000000000000
   vmsize 0x0000000100000000
        …
Load command 1
      cmd LC_SEGMENT_64
  cmdsize 1192
  segname __TEXT
   vmaddr 0x0000000100000000
   vmsize 0x0000000000003000
        …

This segment is not present for other Mach-O images, so they have a load address of 0.

I’m glad you were able to figure that out on your own!

[quote='797124022, Nickkk, /thread/760029?answerId=797124022#797124022, /profile/Nickkk'] I get this relatively short and rather obscure output: [/quote]

Right. There’s a lot to unpack here, and it’s hard to explain the details without having your code, so lemme show you an example based on this code:

import Cocoa

class ViewController: NSViewController {

    @IBAction func testQQQ1Action(_ sender: Any) {
        print("QQQ1", sender)
    }

    @IBAction func testQQQ2Action(_ sender: Any) {
        print("QQQ2", sender)
    }
}

I’ve pasted the disassembly in below; you’ll probably want to copy that into a different window so you can view it side-by-side with this explanation.

The first thing to note is that the compiler is really frikkin’ clever when you turn on optimisations. I have two Objective-C methods, -testQQQ1Action: and -testQQQ2Action:, that share a bunch of code. The compiler has noticed that and merged the implementations. So, the disassembly starts out with two short function stubs that put the string value into a register and jump into the actual implementation.

Setting a breakpoint at one of those stubs, I see that the registers are set up the way you’d expect:

(lldb) settings set target.language objc
(lldb) po $x0
<Test760029.ViewController: 0x60000278c780>

(lldb) p (char *)$x1
(char *) 0x00000001000032db "testQQQ1Action:"
(lldb) po $x2
<NSButton: 0x129f10290>

Note The target language defaults to Swift, which can’t cope with register variables like $x0, so I force it to Objective-C. That’s generally a good idea when debugging at the assembly language level.

The first two are self and SEL, and the second one is sender.

Now these stubs set up an extra register, w3, or the 32-bit variant of x3, to hold either 'QQQ1' or 'QQQ2'. So, at the entry point to the merged function we have:

  • x0 is self
  • x1 is SEL
  • x2 is sender
  • x3 is four ASCII bytes of the string to print

With that in mind, let’s look at this function.

The first thing to note is the name:

  • It starts with merged. I’ve not seen that before but the meaning seems pretty obvious. It’s the result of the merger of two similar routines, in my test testQQQ1(_:) and ``testQQQ2(_😃 `.

  • It has @objc, indicating that it follows Objective-C calling conventions.

  • Finally, there’s the Swift signature, which LLDB has helpfully demangled for us.

Next let’s walk through the instructions:

  • +0 through +16 are the function prologue, setting up the stack frame.

  • +20 through +28 save the parameters into preserved registers. We now have:

    • x21 is self
    • x20 is sender
    • x19 is four ASCII bytes of the string to print
  • +32 through +48 are retaining sender and self respectively. AFAICT swift_unknownObjectRetain is a routine that detects whether the object is Swift or Objective-C and retains the value accordingly. Honestly, I’m not sure why that’s necessary here. I suspect it’s because it allows this routine to be called directly from Swift.

  • +52 through +68 are converting the incoming sender value from AnyObject to AnyValue. This Any value now holds the retain count, so +68 balances the retain at +36.

  • +72 through +96 is Swift allocating the storage for the array that’s gonna be passed to print(…). Note that the object pointer gets stored in x20, which replacing the sender object that was previously there. This is fine because we’ve released our reference to that object at +68. The real sender value is an Any, which is stored on the stack at at +60 via the address set up at +52.

  • +100 through +164 is the rest of the call to print(…), populating the array and the various other parameters. The only thing I want to highlight is +128, which stores x19, the ASCII bytes of the string, into the string value.

  • +168 through +172 balances the retain at +44.

  • +176 through +180 balances the allocation at +92

  • +184 through +188 release the reference to sender held in our Any box. Note how its argument, in x0, is set up from the stack pointer.

  • +192 through +204 are the function epilogue, tearing down the stack frame.

So, in this case the thunk that I described in my earlier post isn’t a separate thing. The Swift compiler has inlined the Swift method into the Objective-C thunk. However, the thunk is actually a real thing because, in the non-optimised build, where the compiler inlines a lot less, the Swift method and the Objective-C thunk get their own stack frames:

(lldb) bt 
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x00000001053c9420 Test760029.debug.dylib`ViewController.testQQQ1Action(sender=0x00000001277145e0) at ViewController.swift:6:15
    frame #1: 0x00000001053c95e8 Test760029.debug.dylib`@objc ViewController.testQQQ1Action(_:) at <compiler-generated>:0
    frame #2: 0x0000000198e6a0e8 AppKit`-[NSApplication(NSResponder) sendAction:to:from:] + 460
    …

Anyway, I’m not sure this answers all of your questions but it should give you something to chew on.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

(lldb) disas -s 0x100002aec -e 0x100002bd4
Test760029`@objc Test760029.ViewController.testQQQ1Action(Any) -> ():
    0x100002aec <+0>:   mov    w3, #0x5151
    0x100002af0 <+4>:   movk   w3, #0x3151, lsl #16
    0x100002af4 <+8>:   b      0x100002b04               ; merged @objc Test760029.ViewController.testQQQ1Action(Any) -> ()

Test760029`@objc Test760029.ViewController.testQQQ2Action(Any) -> ():
    0x100002af8 <+0>:   mov    w3, #0x5151
    0x100002afc <+4>:   movk   w3, #0x3251, lsl #16
    0x100002b00 <+8>:   b      0x100002b04               ; merged @objc Test760029.ViewController.testQQQ1Action(Any) -> ()

Test760029`merged @objc Test760029.ViewController.testQQQ1Action(Any) -> ():
    0x100002b04 <+0>:   sub    sp, sp, #0x50
    0x100002b08 <+4>:   stp    x22, x21, [sp, #0x20]
    0x100002b0c <+8>:   stp    x20, x19, [sp, #0x30]
    0x100002b10 <+12>:  stp    x29, x30, [sp, #0x40]
    0x100002b14 <+16>:  add    x29, sp, #0x40
    0x100002b18 <+20>:  mov    x19, x3
    0x100002b1c <+24>:  mov    x20, x2
    0x100002b20 <+28>:  mov    x21, x0
    0x100002b24 <+32>:  mov    x0, x2
    0x100002b28 <+36>:  bl     0x100003014               ; symbol stub for: swift_unknownObjectRetain
    0x100002b2c <+40>:  mov    x0, x21
    0x100002b30 <+44>:  bl     0x100002fc0               ; symbol stub for: objc_retain
    0x100002b34 <+48>:  mov    x21, x0
    0x100002b38 <+52>:  mov    x8, sp
    0x100002b3c <+56>:  mov    x0, x20
    0x100002b40 <+60>:  bl     0x100002f60               ; symbol stub for: Swift._bridgeAnyObjectToAny(Swift.Optional<Swift.AnyObject>) -> Any
    0x100002b44 <+64>:  mov    x0, x20
    0x100002b48 <+68>:  bl     0x100003008               ; symbol stub for: swift_unknownObjectRelease
    0x100002b4c <+72>:  adrp   x0, 6
    0x100002b50 <+76>:  add    x0, x0, #0xbd8
    0x100002b54 <+80>:  bl     0x100002d18               ; __swift_instantiateConcreteTypeFromMangledName at <compiler-generated>
    0x100002b58 <+84>:  mov    w1, #0x60
    0x100002b5c <+88>:  mov    w2, #0x7
    0x100002b60 <+92>:  bl     0x100002fcc               ; symbol stub for: swift_allocObject
    0x100002b64 <+96>:  mov    x20, x0
    0x100002b68 <+100>: adrp   x8, 1
    0x100002b6c <+104>: ldr    q0, [x8, #0x90]
    0x100002b70 <+108>: adrp   x8, 2
    0x100002b74 <+112>: ldr    x8, [x8, #0x28]
    0x100002b78 <+116>: str    q0, [x0, #0x10]
    0x100002b7c <+120>: str    x8, [x0, #0x38]
    0x100002b80 <+124>: mov    x8, #-0x1c00000000000000
    0x100002b84 <+128>: stp    x19, x8, [x0, #0x20]
    0x100002b88 <+132>: add    x1, x0, #0x40
    0x100002b8c <+136>: mov    x0, sp
    0x100002b90 <+140>: bl     0x100002d58               ; outlined init with copy of Any at <compiler-generated>
    0x100002b94 <+144>: mov    x0, x20
    0x100002b98 <+148>: mov    w1, #0x20
    0x100002b9c <+152>: mov    x2, #-0x1f00000000000000
    0x100002ba0 <+156>: mov    w3, #0xa
    0x100002ba4 <+160>: mov    x4, #-0x1f00000000000000
    0x100002ba8 <+164>: bl     0x100002f84               ; symbol stub for: Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> ()
    0x100002bac <+168>: mov    x0, x21
    0x100002bb0 <+172>: bl     0x100002fb4               ; symbol stub for: objc_release
    0x100002bb4 <+176>: mov    x0, x20
    0x100002bb8 <+180>: bl     0x100002fd8               ; symbol stub for: swift_bridgeObjectRelease
    0x100002bbc <+184>: mov    x0, sp
    0x100002bc0 <+188>: bl     0x100002d94               ; __swift_destroy_boxed_opaque_existential_0 at <compiler-generated>
    0x100002bc4 <+192>: ldp    x29, x30, [sp, #0x40]
    0x100002bc8 <+196>: ldp    x20, x19, [sp, #0x30]
    0x100002bcc <+200>: ldp    x22, x21, [sp, #0x20]
    0x100002bd0 <+204>: add    sp, sp, #0x50
Weird crashes when accessing Swift Array
 
 
Q