Debugging

RSS for tag

Discover and resolve issues with your app.

Posts under Debugging tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Posting a Crash Report
If you need help investigating a crash, please include a crash report in your post. To smooth things along, follow these guidelines: For information on how to get a crash report, see Acquiring crash reports and diagnostic logs. Include the whole crash report as a text attachment (click the paperclip icon and then choose Add File). This avoids clogging up the timeline while also preserving the wealth of information in the crash report. If you’re not able to post your crash report as an attachment, see Can’t Post Crash Report as Attachment below. If you want to highlight a section of the report, include it in the main body of your post. Put the snippet in a code block so that it renders nicely. To create a code block, add a delimiter line containing triple backquotes before and after the block, or just click the Code Block button. If possible, post an Apple crash report. Third-party crash reporters are often missing critical information and have general reliability problems (for an explanation as to why, see Implementing Your Own Crash Reporter). Symbolicate your crash report before posting it. For information on how to do this, see Adding identifiable symbol names to a crash report. If you need to redact the crash report, do so consistently. Imagine you’re building the WaffleVarnish app whose bundle ID is com.example.wafflevarnish but you want to keep your new waffle varnishing technology secret. Replace WaffleVarnish with WwwwwwVvvvvvv and com.example.wafflevarnish with com.eeeeeee.wwwwwwvvvvvvv. This keeps the text in the crash report aligned while making it possible to distinguish the human-readible name of the app (WaffleVarnish) from the bundle ID (com.example.wafflevarnish). Finally, for information on how to use a crash report to debug your own problems, see Diagnosing issues using crash reports and device logs. Can’t Post Crash Report as Attachment Crash reports have two common extensions: .crash and .ips. If you have an .ips file, please post that [1]. DevForums lets you attach a .crash file but not an .ips file (r. 117468172). To work around this, change the extension to .txt. If DevForums complains that your crash report “contains sensitive language”, leave it out of your initial post and attach it to a reply. That often avoids this roadblock. If you still can’t post your crash report, upload it to a file sharing service and include the URL in your post. Post the URL in the clear, per tip 14 in Quinn’s Top Ten DevForums Tips. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] Because it’s easy to go from an .ips file to a .crash file. I usually do this by choosing File > Quick Look in the Finder. For more info about these file formats, see this post. Revision History: 2024-11-21 Added a recommendation to post the .ips format if possible. 2024-05-21 Added some advice regarding the “contains sensitive language” message. 2023-10-25 Added the Can’t Post Crash Report as Attachment section. Made other minor editorial changes. 2021-08-26 First posted.
0
0
8.1k
Nov ’24
Debugging Resources
General: DevForums tags: Debugging, LLDB, Graphical Debugger Xcode > Debugging documentation Diagnosing memory, thread, and crash issues early documentation Diagnosing issues using crash reports and device logs documentation Choosing a Network Debugging Tool documentation Testing a release build documentation Isolating Code Signing Problems from Build Problems DevForums post What is an exception? DevForums post Language Exception from RCTFatal DevForums post Standard Memory Debugging Tools DevForums post Using a Sysdiagnose Log to Debug a Hard-to-Reproduce Problem DevForums post Posting a Crash Report DevForums post Creating a test project DevForums post Implementing Your Own Crash Reporter DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
4.5k
Aug ’24
The Xcode project keeps crashing on launch
Hello, I need a little bit of help. My game keeps crashing on launch no matter what I do. I’ve tried running it in Xcode on my Mac, on my iPhone, and through TestFlight, but I get the same result every time. I’ve tried everything I could find on the internet, and nothing worked. Asking here is my last resort because I’m completely stuck. The game runs fine in Unity, but not so much in Xcode. Can someone help me figure out what I’m doing wrong?Any help would be greatly appreciated. Here is the error log I found by connecting my iPhone to my Mac. To view the logs, I used the Console in the Devices and Simulators section of Xcode. ➤ SecKeyVerifySignature failed: Error Domain=NSOSStatusErrorDomain Code=-50 "rsa_pub_crypt failed" [10:27:36.034791+0200] kernel ➤ Sandbox: [App] deny(1) sysctl-read kern.bootargs [10:27:36.043389+0200] SpringBoard ➤ Live host view super view[(null)] not matching container view ➤ Frame not updated [10:27:36.050473+0200] backboardd ➤ Cycle detected [10:27:36.100799+0200] SpringBoard ➤ Live host view super view[(null)] not matching container view [10:27:36.538361+0200] akd ➤ Error fetching keychain item - Error Domain=NSOSStatusErrorDomain Code=-25300 "no matching items found" [10:27:36.545734+0200] akd ➤ Failed to set last known MID with error (Error Domain=NSOSStatusErrorDomain Code=-25300) [10:27:36.603384+0200] rtcreportingd ➤ Gap in hierarchy: [10:27:36.604536+0200] cloudd ➤ TCP input flags=[R.] state=LAST_ACK [10:27:36.613317+0200] cloudd ➤ TCP input flags=[R] state=CLOSED [10:27:36.648449+0200] kernel ➤ 1 duplicate report for Sandbox: [App] deny(1) sysctl-read kern.bootargs [10:27:36.648484+0200] kernel ➤ Sandbox: [App] deny(1) file-test-existence /private/var/Managed Preferences/mobile/com.apple.CoreMotion.plist [10:27:36.900275+0200] CommCenter ➤ Client is not entitled for request [10:27:37.131555+0200] storekitd ➤ AMSURLSession: Session decoder failed. Error = Error Domain=AMSErrorDomain Code=301 "Invalid Status Code" [10:27:37.131761+0200] storekitd ➤ AMSURLSession: Task completed with error = Error Domain=AMSErrorDomain Code=301 "Invalid Status Code" [10:27:38.137847+0200] kernel ➤ System Policy: [Process] deny(1) file-read-metadata /private/var/mobile/Library/Biome/FlexibleStorage [10:27:38.779536+0200] kernel ➤ Sandbox: [App] deny(2) file-test-existence /private/etc/localtime [10:27:38.942342+0200] mobileassetd ➤ TCP input flags=[R] state=LAST_ACK [10:27:38.963596+0200] kernel ➤ Sandbox: [App] deny(2) file-test-existence /bin/bash [10:27:40.152019+0200] mobileassetd ➤ TCP input flags=[R] state=LAST_ACK [10:27:40.280661+0200] assetsd ➤ Warning: cache_handle_memory_pressure invokedPreformatted text```
2
0
50
1d
App Crashes on TestFlight but Works in Simulator (Expo React Native App)
Hi, I’m experiencing an issue where my React Native (Expo) app crashes immediately in TestFlight after launching, but it works fine in Expo Go and the iOS Simulator. This is my first time building an IOS app, so I'm not sure where I'm going wrong. Are there known issues with JS bundle loading, native module compatibility, or API entitlements that could be causing this? What tools or logs should I use to track the exact source of failure? Any guidance would be greatly appreciated! Thank you. Steps Taken: The app runs fine in Expo Go (npx expo start --no-dev --minify) and in the iOS Simulator (npx expo run:ios --clean). I also did (npx expo-doctor) and it passed all 15 checks. After building with EAS (eas build --platform ios --profile production), the TestFlight build crashes on launch. I checked Xcode logs (Devices & Simulators > View Device Logs) and found this error: `Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Terminating Process: LoungeNavigator [4666] Triggered by Thread: 6 Thread 6 name: Thread 6 Crashed: Thread 6 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x0000000000000000 My app.json file: "expo": { "name": "appname", "slug": "app", "owner": "baint", "version": "0.5.2", "orientation": "portrait", "icon": "./assets/images/IOS-App-Icon.png", "scheme": "myapp", "userInterfaceStyle": "automatic", "newArchEnabled": true, "ios": { "supportsTablet": true, "bundleIdentifier": "bundleIdentifier", "icon": "./assets/images/IOS-App-Icon.png", "buildNumber": "7", "infoPlist": { "NSLocationAlwaysAndWhenInUseUsageDescription": "This app requires access to your location at all times.", "NSLocationAlwaysUsageDescription": "This app needs your location even when the app is in the background.", "NSLocationWhenInUseUsageDescription": "We need your location.", "ITSAppUsesNonExemptEncryption": false } }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/images/IOS-App-Icon.png", "backgroundColor": "#ffffff" }, "package": "identifier" }, "web": { "bundler": "metro", "output": "static", "favicon": "./assets/images/favicon.png" }, "plugins": [ "expo-router", [ "expo-splash-screen", { "image": "./assets/images/IOS-App-Icon.png", "imageWidth": 200, "resizeMode": "contain", "backgroundColor": "#ffffff" } ], "expo-asset", [ "@rnmapbox/maps", { "RNMapboxMapsImpl": "mapbox", "ios": { "RNMapboxMapsDownloadToken": "token", "RNMapboxMapsAccessToken": "token", "NSLocationAlwaysAndWhenInUseUsageDescription": "This app requires access to your location at all times.", "NSLocationAlwaysUsageDescription": "This app needs your location even when the app is in the background.", "NSLocationWhenInUseUsageDescription": "We need your location." } } ], [ "expo-build-properties", { "ios": { "useFrameworks": "static", "useModularHeaders": true } } ] ], "experiments": { "typedRoutes": true }, "extra": { "router": { "origin": false }, "eas": { "projectId": "projectid" } } } } My eas.json file: "cli": { "version": ">= 14.7.1", "appVersionSource": "remote" }, "build": { "development": { "developmentClient": true, "distribution": "internal" }, "preview": { "distribution": "internal" }, "internal": { "distribution": "store", "ios": { "credentialsSource": "remote" }, "autoIncrement": true, "env": { "EXPO_PUBLIC_NODE_ENV": "production" } }, "production": { "autoIncrement": true, "distribution": "store", "env": { "EXPO_PUBLIC_NODE_ENV": "production" } } }, "submit": { "production": { "ios": { "ascAppId": "ascAppId", "appleId": "appleId", "ascApiKeyPath": "ascApiKeyPath" } } } }
3
0
59
6d
NSString initWithFormat crash on ios18
var format = "%7B%22sign%22%3Anull%2C%22company%22%3A%22%E5%85%84%E5%BC%9F%E6%B5%B7%E6%B4%8B%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%2C%22businessNo%22%3Anull%2C%22scene%22%3Anull%2C%22interviewCode%22%3A%22767676%22%7D" let message = withVaList([]) { args in let msg = NSString(format: format, arguments: args) print(msg) }
6
0
79
3d
Unable to open mach-O at path - metallib Error:2
When I toggle a panel like navigationsidebar, I get a message in the console. I guess it's not a big issue, but is there a way to fix this message? because it appears in every project. Unable to open mach-O at path: /AppleInternal/Library/BuildRoots/d187757d-b9a3-11ef-83e5-aabfac210453/Library/Caches/com.apple.xbs/Binaries/RenderBox/install/TempContent/Root/System/Library/PrivateFrameworks/RenderBox.framework/Versions/A/Resources/default.metallib Error:2
0
0
153
1w
A static lib/framework with dwarf info. Will leaking your private info?
When you build a static library that includes DWARF information, you may encounter error messages in the binary package generated by Xcodebuild. Upon examining the DWARF information with dwarfdump, you will find that any entries containing keywords like dir are all absolute paths specific to the publisher's computer. This is quite alarming, as it poses a risk of leaking private information. Additionally, when debugging an app, you can encounter consistent warning notes indicating that the referenced path addresses cannot be found. This is because the absolute path addresses generated during the 'xcodebuild' process reflect the paths from the computer used to build it. When distributing this to others, how can anyone access these paths? Has the design of the secondary linking process for DWARF considered the issues related to binary distribution? Are there existing solutions to address and handle privacy concerns? Is there a solution to allow the distributed DWARF files to be correctly recognized during compilation and debugging of the app? BTW: Incorrect paths can indeed affect LLDB's ability to load and debug the application effectively?
1
0
160
1w
Using ARKit Replay hangs forever on "Attaching to App"...
Hello, I'm trying to use Xcode's ARKit Session replay functionality. I have a capture I made using Reality Composer and when trying to use it with Xcode's replay functionality the installation and debugging process seems stalled forever. I've gotten it to work once so I know the capture file is functional but I have never gotten it to work a second time, even though I didn't change any settings. No amount of restarting Xcode, the Mac, or the iPhone seem to work. I have also tried cleaning build folders, reinstalling the app, and clearing DerivedData. I can confirm from the Xcode logs that the app installs correctly but the app never launches. If I unselect the checkbox for "ARKit Replay Data", the app launches and debugs nearly instantly. I have tried letting it "attach" for up to 10 minutes to no avail.
2
0
256
2w
TestFlight app crashes on launch when minimum supported iOS version is set to iOS 14
Hi All, I have an App on AppStore, recently the minimum supported version of the app was changed from iOS 12 to iOS 14. Post that the TestFlight builds are crashing on launch. If we revert the minimum supported iOS version to 12, the crash no longer happens. This project is using cocoapods, and from the crash logs it seems the issue with with PLCrashReporter framework. "EXC_CRASH" Termination reason: DYLD 9 weak-def symbol not found '__ZN7plcrash3PL_5async15dwarf_cfa_stateljiE10push_stateEv'. This issue is happening only on TestFlight builds where the minimum supported version is 14.0 Any pointer to a solution is welcome.
1
0
255
2w
Crash reports downloaded by Xcode contain impossible call hierarchy
I was just having a look at some crash reports downloaded by Xcode, and I noticed the same wrong pattern I already mentioned here: the crash reports indicate that method A calls method B, which is impossible. In the first crash report below, method MainViewController.showSettings seems to be called by ConfirmMoveViewController.openSourceInFinder, which is impossible. ConfirmMoveViewController.openSourceInFinder is a context menu action in a modal window, and MainViewController.showSettings is in a completely different window and the two methods have no relation whatsoever. In the second crash report below, MainViewController.setSortMode is triggered by the press of a button (and nothing else) but seems to be called by OtherViewController.copy that can be triggered by a context menu (or keyboard shortcut). The two methods have no relation whatsoever. The rest of the stack trace confirm that it's indeed the button that was pressed. This seems to me like a quite serious bug in how macOS creates crash reports. 1.crash 2.crash
6
0
229
5d
Question about using @Previewable
This is an issue that occurred while using SwiftUI. Cannot find '$state' in scope The other view finds properties normally. May I know why the error is occurring? The following code is the full text of the code that causes problems. import SwiftUI @Observable class HomeState { var title: String = "Home" } struct HomeView: View { @Binding var state: HomeState var body: some View { Text(state.title) } } #Preview { @Previewable @State var state: HomeState = .init() HomeView(state: $state) /// Error: Cannot find '$state' in scope } The same error occurs when using the String type rather than the object. What did I do wrong?
2
1
183
2w
App Freezing at Launch and Unexpected Termination
We are experiencing an issue where our app gets stuck during launch. The splash screen appears for some time, and then the app either becomes unresponsive or closes unexpectedly. However, there are no crash logs captured in Xcode or Firebase Crashlytics, indicating that the app is not crashing but rather being terminated. This issue is preventing affected users from properly launching the app. Additionally, some users have reported occasional lag and slow performance when using the app. The issue occurs only for a specific subset of users and appears to be related to other Electronic Logging Device (ELD) apps running in the background. When these apps are active, our app struggles to launch and sometimes becomes unresponsive. We suspect that this behavior could be related to system resource allocation, such as high memory consumption by background apps, which might be affecting our app's ability to launch correctly. However, we have been unable to reproduce the issue on our end despite multiple attempts. Actions Performed During App Launch: Firebase configuration API requests, including: Fetching account details Registering the FCM token with the server Asynchronous background requests to fetch POI details Creating a local database and storing POI data in local storage We would like guidance from Apple regarding potential causes and debugging strategies, especially in scenarios where the app does not produce crash logs but still fails to launch properly. Any insights into memory management, conflicts with background applications, or system resource constraints would be highly appreciated. Steps to Reproduce: Install and launch the app on an affected device. Observe that the app gets stuck on the launch screen. After some time, the app terminates unexpectedly. Issue is inconsistent and occurs only for certain users. Presence of other ELD apps running in the background appears to influence the issue.
3
0
184
6d
Memory leak in WebKit caused by KVO and @StateObject
Hi! My SwiftUI app is a rather complex browser app. Starting with iOS 18, the app crashes due to repeted reloads of the WkWebView. I’ve tracked the issue as far as I can, but I still haven’t found the root cause. My app is structured like this: MainView holds a cuple of subviews. It also holds a @StateObject called viewModel that holds a lot of @Published vars. The viewModel is passed as a enivormentObject. Example from ViewModel: @MainActor class ViewModel: NSObject, ObservableObject { @Published public var isLoading: Bool = false @Published public var loadProgress: Double? = 0 public func setIsLoading(_ value: Bool) async { self.isLoading = value } public func setLoadProgress(_ value: Double?) async { self.loadProgress = value } } WebView is a subview of MainView, which holds a navigation bar, and a UIViewRepresentable, which is a WkWebView. The WkWebView pushes some states to the ViewModel as the underlying values of the WkWebView changes, i.e. estimaedProgress, and isLoading. This is done via KVO and works like this: estimatedProgressObservation = self.parent.webView.observe(\.estimatedProgress) { webView, progress in Task { await parent.viewModel.setLoadProgress(webView.estimatedProgress) } } isLoadingObservation = self.parent.webView.observe(\.isLoading) { webView, value in Task { await parent.viewModel.setIsLoading(webView.isLoading) } } By using a timer in WkWebViews Coordinator, i trigger a load after a configurable amount of time :
 func loadUrl(url: URL) { DispatchQueue.main.async { console.info("Load URL: ...", sensitive: "Load URL: \(url.absoluteString)") let policy: NSURLRequest.CachePolicy if self.parent.settings.noCache { policy = .reloadIgnoringLocalAndRemoteCacheData } else { policy = .useProtocolCachePolicy } let request = URLRequest(url: url, cachePolicy: policy) self.parent.webView.load(request) } } Running the app with the automatic reload enabled freezes the app after a couple of hours. It also seems to freeze Safari on the device. The device needs to be rebooted. If I inspect the device's running processes, hundreds of ”com.apple.webkit. web content " processes are running. Removing await parent.viewModel.setLoadProgress(webView.estimatedProgress) and await parent.viewModel.setIsLoading(webView.isLoading) fixes the issue, but it is necessary for other app functions. Therefore, is suspect that the viewModel somehow causes the bug. The issue arises after a couple of loads 5-10. The debugger shows a message when the processes start to pile up. I suspect its related. Failed to terminate process: Error Domain=com.apple.extensionKit.errorDomain Code=18 "(null)" UserInfo={NSUnderlyingError=0x12d0e7f60 {Error Domain=RBSServiceErrorDomain Code=1 "Client not entitled" UserInfo={RBSEntitlement=com.apple.runningboard.terminateprocess, NSLocalizedFailureReason=Client not entitled, RBSPermanent=true}}} How can I find out what causes the suspected memory leak? Instruments gives me nothing of value. The memory leak wasn't present in iOS 17. Is this a bug in iOS 18, or was something intentionally changed?
0
0
318
2w
Instrument Recording Failure - CPU counter failed
Hi, I’m encountering an issue while using xctrace & instruments to profile an application on macOS. Specifically, when trying to record a trace using the CPU Profiler template, I get the following errors: Failed to start the recording: configureHardwareCounters: Failed set kpc configuration: Operation not permitted. Unexpected failure: Couriers have returned unexpectedly. macOS Version: 15.3.1 Chip: Apple M4 Pro Xcode Version: Xcode 16.2
2
2
339
2w
Understanding Mach-O Symbols
This posts collects together a bunch of information about the symbols found in a Mach-O file. It assumes the terminology defined in An Apple Library Primer. If you’re unfamiliar with a term used here, look there for the definition. If you have any questions or comments about this, start a new thread in the Developer Tools & Services > General topic area and tag it with Linker. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Understanding Mach-O Symbols Every Mach-O file has a symbol table. This symbol table has many different uses: During development, it’s written by the compiler. And both read and written by the linker. And various other tools. During execution, it’s read by the dynamic linker. And also by various APIs, most notably dlsym. The symbol table is an array of entries. The format of each entry is very simple, but they have been used and combined in various creative ways to achieve a wide range of goals. For example: In a Mach-O object file, there’s an entry for each symbol exported to the linker. In a Mach-O image, there’s an entry for each symbol exported to the dynamic linker. And an entry for each symbol imported from dynamic libraries. Some entries hold information used by the debugger. See Debug Symbols, below. Examining the Symbol Table There are numerous tools to view and manipulate the symbol table, including nm, dyld_info, symbols, strip, and nmedit. Each of these has its own man page. A good place to start is nm: % nm Products/Debug/TestSymTab U ___stdoutp 0000000100000000 T __mh_execute_header U _fprintf U _getpid 0000000100003f44 T _main 0000000100008000 d _tDefault 0000000100003ecc T _test 0000000100003f04 t _testHelper Note In the examples in this post, TestSymTab is a Mach-O executable that’s formed by linking two Mach-O object files, main.o and TestCore.o. There are three columns here, and the second is the most important. It’s a single letter indicating the type of the entry. For example, T is a code symbol (in Unix parlance, code is in the text segment), D is a data symbol, and so on. An uppercase letter indicates that the symbol is visible to the linker; a lowercase letter indicates that it’s internal. An undefined (U) symbol has two potential meanings: In a Mach-O image, the symbol is typically imported from a specific dynamic library. The dynamic linker connects this import to the corresponding exported symbol of the dynamic library at load time. In a Mach-O object file, the symbol is undefined. In most cases the linker will try to resolve this symbol at link time. Note The above is a bit vague because there are numerous edge cases in how the system handles undefined symbols. For more on this, see Undefined Symbols, below. The first column in the nm output is the address associated with the entry, or blank if an address is not relevant for this type of entry. For a Mach-O image, this address is based on the load address, so the actual address at runtime is offset by the slide. See An Apple Library Primer for more about those concepts. The third column is the name for this entry. These names have a leading underscore because that’s the standard name mangling for C. See An Apple Library Primer for more about name mangling. The nm tool has a lot of formatting options. The ones I use the most are: -m — This prints more information about each symbol table entry. For example, if a symbol is imported from a dynamic library, this prints the library name. For a concrete example, see A Deeper Examination below. -a — This prints all the entries, including debug symbols. We’ll come back to that in the Debug Symbols section, below. -p — By default nm sorts entries by their address. This disables that sort, causing nm to print the entries in the order in which they occur in the symbol table. -x — This outputs entries in a raw format, which is great when you’re trying to understand what’s really going on. See Raw Symbol Information, below, for an example of this. A Deeper Examination To get more information about each symbol table, run nm with the -m option: % nm -m Products/Debug/TestSymTab (undefined) external ___stdoutp (from libSystem) 0000000100000000 (__TEXT,__text) [referenced dynamically] external __mh_execute_header (undefined) external _fprintf (from libSystem) (undefined) external _getpid (from libSystem) 0000000100003f44 (__TEXT,__text) external _main 0000000100008000 (__DATA,__data) non-external _tDefault 0000000100003ecc (__TEXT,__text) external _test 0000000100003f04 (__TEXT,__text) non-external _testHelper This contains a world of extra information about each entry. For example: You no longer have to remember cryptic single letter codes. Instead of U, you get undefined. If the symbol is imported from a dynamic library, it gives the name of that dynamic library. Here we see that _fprintf is imported from the libSystem library. It surfaces additional, more obscure information. For example, the referenced dynamically flag is a flag used by the linker to indicate that a symbol is… well… referenced dynamically, and thus shouldn’t be dead stripped. Undefined Symbols Mach-O’s handling of undefined symbols is quite complex. To start, you need to draw a distinction between the linker (aka the static linker) and the dynamic linker. Undefined Symbols at Link Time The linker takes a set of files as its input and produces a single file as its output. The input files can be Mach-O images or dynamic libraries [1]. The output file is typically a Mach-O image [2]. The goal of the linker is to merge the object files, resolving any undefined symbols used by those object files, and create the Mach-O image. There are two standard ways to resolve an undefined symbol: To a symbol exported by another Mach-O object file To a symbol exported by a dynamic library In the first case, the undefined symbol disappears in a puff of linker magic. In the second case, it records that the generated Mach-O image depends on that dynamic library [3] and adds a symbol table entry for that specific symbol. That entry is also shown as undefined, but it now indicates the library that the symbol is being imported from. This is the core of the two-level namespace. A Mach-O image that imports a symbol records both the symbol name and the library that exports the symbol. The above describes the standard ways used by the linker to resolve symbols. However, there are many subtleties here. The most radical is the flat namespace. That’s out of scope for this post, because it’s a really bad option for the vast majority of products. However, if you’re curious, the ld man page has some info about how symbol resolution works in that case. A more interesting case is the -undefined dynamic_lookup option. This represents a halfway house between the two-level namespace and the flat namespace. When you link a Mach-O image with this option, the linker resolves any undefined symbols by adding a dynamic lookup undefined entry to the symbol table. At load time, the dynamic linker attempts to resolve that symbol by searching all loaded images. This is useful if your software works on other Unix-y platforms, where a flat namespace is the norm. It can simplify your build system without going all the way to the flat namespace. Of course, if you use this facility and there are multiple libraries that export that symbol, you might be in for a surprise! [1] These days it’s more common for the build system to pass a stub library (.tbd) to the linker. The effect is much the same as passing in a dynamic library. In this discussion I’m sticking with the old mechanism, so just assume that I mean dynamic library or stub library. If you’re unfamiliar with the concept of a stub library, see An Apple Library Primer. [2] The linker can also merge the object files together into a single object file, but that’s relatively uncommon operation. For more on that, see the discussion of the -r option in the ld man page. [3] It adds an LC_LOAD_DYLIB load command with the install name from the dynamic library. See Dynamic Library Identification for more on that. Undefined Symbols at Load Time When you load a Mach-O image the dynamic linker is responsible for finding all the libraries it depends on, loading them, and connecting your imports to their exports. In the typical case the undefined entry in your symbol table records the symbol name and the library that exports the symbol. This allows the dynamic linker to quickly and unambiguously find the correct symbol. However, if the entry is marked as dynamic lookup [1], the dynamic linker will search all loaded images for the symbol and connect your library to the first one it finds. If the dynamic linker is unable to find a symbol, its default behaviour is to fail the load of the Mach-O image. This changes if the symbol is a weak reference. In that case, the dynamic linking continues to load the image but sets the address of the symbol to NULL. See Weak vs Weak vs Weak, below, for more about this. [1] In this case nm shows the library name as dynamically looked up. Weak vs Weak vs Weak Mach-O supports two different types of weak symbols: Weak references (aka weak imports) Weak definitions IMPORTANT If you use the term weak without qualification, the meaning depends on your audience. App developers tend to assume that you mean a weak reference whereas folks with a C++ background tend to assume that you mean a weak definition. It’s best to be specific. Weak References Weak references support the availability mechanism on Apple platforms. Most developers build their apps with the latest SDK and specify a deployment target, that is, the oldest OS version on which their app runs. Within the SDK, each declaration is annotated with the OS version that introduced that symbol [1]. If the app uses a symbol introduced later than its deployment target, the compiler flags that import as a weak reference. The app is then responsible for not using the symbol if it’s run on an OS release where it’s not available. For example, consider this snippet: #include <xpc/xpc.h> void testWeakReference(void) { printf("%p\n", xpc_listener_set_peer_code_signing_requirement); } The xpc_listener_set_peer_code_signing_requirement function is declared like so: API_AVAILABLE(macos(14.4)) … int xpc_listener_set_peer_code_signing_requirement(…); The API_AVAILABLE macro indicates that the symbol was introduced in macOS 14.4. If you build this code with the deployment target set to macOS 13, the symbol is marked as a weak reference: % nm -m Products/Debug/TestWeakRefC … (undefined) weak external _xpc_listener_set_peer_code_signing_requirement (from libSystem) If you run the above program on macOS 13, it’ll print NULL (actually 0x0). Without support for weak references, the dynamic linker on macOS 13 would fail to load the program because the _xpc_listener_set_peer_code_signing_requirement symbol is unavailable. [1] In practice most of the SDK’s declarations don’t have availability annotations because they were introduced before the minimum deployment target supported by that SDK. Weak definitions Weak references are about imports. Weak definitions are about exports. A weak definition allows you to export a symbol from multiple images. The dynamic linker coalesces these symbol definitions. Specifically: The first time it loads a library with a given weak definition, the dynamic linker makes it the primary. It registers that definition such that all references to the symbol resolve to it. This registration occurs in a namespace dedicated to weak definitions. That namespace is flat. Any subsequent definitions of that symbol are ignored. Weak definitions are weird, but they’re necessary to support C++’s One Definition Rule in a dynamically linked environment. IMPORTANT Weak definitions are not just weird, but also inefficient. Avoid them where you can. To flush out any unexpected weak definitions, pass the -warn_weak_exports option to the static linker. The easiest way to create a weak definition is with the weak attribute: __attribute__((weak)) void testWeakDefinition(void) { } IMPORTANT The C++ compiler can generate weak definitions without weak ever appearing in your code. This shows up in nm like so: % nm -m Products/Debug/TestWeakDefC … 0000000100003f40 (__TEXT,__text) weak external _testWeakDefinition … The output is quite subtle. A symbol flagged as weak external is either a weak reference or a weak definition depending on whether it’s undefined or not. For clarity, use dyld_info instead: % dyld_info -imports -exports Products/Debug/TestWeakRefC Products/Debug/TestWeakDefC [arm64]: … -imports: … 0x0001 _xpc_listener_set_peer_code_signing_requirement [weak-import] (from libSystem) % dyld_info -imports -exports Products/Debug/TestWeakDefC Products/Debug/TestWeakDefC [arm64]: -exports: offset symbol … 0x00003F40 _testWeakDefinition [weak-def] … … Here, weak-import indicates a weak reference and weak-def a weak definition. Weak Library There’s one final confusing use of the term weak, that is, weak libraries. A Mach-O image includes a list of imported libraries and a list of symbols along with the libraries they’re imported from. If an image references a library that’s not present, the dynamic linker will fail to load the library even if all the symbols it references in that library are weak references. To get around this you need to mark the library itself as weak. If you’re using Xcode it will often do this for your automatically. If it doesn’t, mark the library as optional in the Link Binary with Libraries build phase. Use otool to see whether a library is required or optional. For example, this shows an optional library: % otool -L Products/Debug/TestWeakRefC Products/Debug/TestWeakRefC: /usr/lib/libEndpointSecurity.dylib (… 511.60.5, weak) … In the non-optional case, there’s no weak indicator: % otool -L Products/Debug/TestWeakRefC Products/Debug/TestWeakRefC: /usr/lib/libEndpointSecurity.dylib (… 511.60.5) … Debug Symbols or Why the DWARF still stabs. (-: Historically, all debug information was stored in symbol table entries, using a format knows as stabs. This format is now obsolete, having been largely replaced by DWARF. However, stabs symbols are still used for some specific roles. Note See <mach-o/stab.h> and the stab man page for more about stabs on Apple platforms. See stabs and DWARF for general information about these formats. In DWARF, debug symbols aren’t stored in the symbol table. Rather, debug information is stored in various __DWARF sections. For example: % otool -l Intermediates.noindex/TestSymTab.build/Debug/TestSymTab.build/Objects-normal/arm64/TestCore.o | grep __DWARF -B 1 sectname __debug_abbrev segname __DWARF … The compiler inserts this debug information into the Mach-O object file that it creates. Eventually this Mach-O object file is linked into a Mach-O image. At that point one of two things happens, depending on the Debug Information Format build setting. During day-to-day development, set Debug Information Format to DWARF. When the linker creates a Mach-O image from a bunch of Mach-O object files, it doesn’t do anything with the DWARF information in those objects. Rather, it records references to the source objects files into the final image. This is super quick. When you debug that Mach-O image, the debugger finds those references and uses them to locate the DWARF information in the original Mach-O object files. Each reference is stored in a stabs OSO symbol table entry. To see them, run nm with the -a option: % nm -a Products/Debug/TestSymTab … 0000000000000000 - 00 0001 OSO …/Intermediates.noindex/TestSymTab.build/Debug/TestSymTab.build/Objects-normal/arm64/TestCore.o 0000000000000000 - 00 0001 OSO …/Intermediates.noindex/TestSymTab.build/Debug/TestSymTab.build/Objects-normal/arm64/main.o … Given the above, the debugger knows to look for DWARF information in TestCore.o and main.o. And notably, the executable does not contain any DWARF sections: % otool -l Products/Debug/TestSymTab | grep __DWARF -B 1 % When you build your app for distribution, set Debug Information Format to DWARF with dSYM File. The executable now contains no DWARF information: % otool -l Products/Release/TestSymTab | grep __DWARF -B 1 % Xcode runs dsymutil tool to collect the DWARF information, organise it, and export a .dSYM file. This is actually a document package, within which is a Mach-O dSYM companion file: % find Products/Release/TestSymTab.dSYM Products/Release/TestSymTab.dSYM Products/Release/TestSymTab.dSYM/Contents … Products/Release/TestSymTab.dSYM/Contents/Resources/DWARF Products/Release/TestSymTab.dSYM/Contents/Resources/DWARF/TestSymTab … % file Products/Release/TestSymTab.dSYM/Contents/Resources/DWARF/TestSymTab Products/Release/TestSymTab.dSYM/Contents/Resources/DWARF/TestSymTab: Mach-O 64-bit dSYM companion file arm64 That file contains a copy of the the DWARF information from all the original Mach-O object files, optimised for use by the debugger: % otool -l Products/Release/TestSymTab.dSYM/Contents/Resources/DWARF/TestSymTab | grep __DWARF -B 1 … sectname __debug_line segname __DWARF … Raw Symbol Information As described above, each Mach-O file has a symbol table that’s an array of symbol table entries. The structure of each entry is defined by the declarations in <mach-o/nlist.h> [1]. While there is an nlist man page, the best documentation for this format is the the comments in the header itself. Note The terms nlist stands for name list and dates back to truly ancient versions of Unix. Each entry is represented by an nlist_64 structure (nlist for 32-bit Mach-O files) with five fields: n_strx ‘points’ to the string for this entry. n_type encodes the entry type. This is actually split up into four subfields, as discussed below. n_sect is the section number for this entry. n_desc is additional information. n_value is the address of the symbol. The four fields within n_type are N_STAB (3 bits), N_PEXT (1 bit), N_TYPE (3 bits), and N_EXT (1 bit). To see these raw values, run nm with the -x option: % nm -a -x Products/Debug/TestSymTab … 0000000000000000 01 00 0300 00000036 _getpid 0000000100003f44 24 01 0000 00000016 _main 0000000100003f44 0f 01 0000 00000016 _main … This prints a column for n_value, n_type, n_sect, n_desc, and n_strx. The last column is the string you get when you follow the ‘pointer’ in n_strx. The mechanism used to encode all the necessary info into these fields is both complex and arcane. For the details, see the comments in <mach-o/nlist.h> and <mach-o/stab.h>. However, just to give you a taste: The entry for getpid has an n_type field with just the N_EXT flag set, indicating that this is an external symbol. The n_sect field is 0, indicating a text symbol. And n_desc is 0x0300, with the top byte indicating that the symbol is imported from the third dynamic library. The first entry for _main has an n_type field set to N_FUN, indicating a stabs function symbol. The n_desc field is the line number, that is, line 22. The second entry for _main has an n_type field with N_TYPE set to N_SECT and the N_EXT flag set, indicating a symbol exported from a section. In this case the section number is 1, that is, the text section. [1] There is also an <nlist.h> header that defines an API that returns the symbol table. The difference between <nlist.h> and <mach-o/nlist.h> is that the former defines an API whereas the latter defines the Mach-O on-disk format. Don’t include both; that won’t end well!
0
0
419
3w
Analyzing crash report
Hello, I'm doing an update to my app already IN the app store. The app is built using .Net Maui targeting iOS, Windows and Android. All works fine in debug and in release on Android and Windows. However, the app launches on my iOS devices and crashes immediately. I really have no idea what the crash report on the device is telling me. Attached is the .ips file if anyone can at least point me in the right direction... Thanks MyApp-2025-03-01-202630.ips
2
0
220
3w
Issue with TabView in Split Screen
Below is a basic test app to resemble an actual app I am working on to hopefully better describe an issue I am having with tab view. It seems only in split screen when I am triggering something onAppear that would cause another view to update, or another view updates on its own, the focus gets pulled to that newly updated view instead of staying on the view you are currently on. This seems to only happen with views that are listed in the more tab. In any other orientation other than 50/50 split this does not happen. Any help would be appreciated. struct ContentView: View { @State var selectedTab = 0 var body: some View { NavigationStack { NavigationLink(value: 0) { Text("ENTER") }.navigationDestination(for: Int.self) { num in TabsView(selectedTab: $selectedTab) } } } } struct TabsView: View { @Binding var selectedTab: Int @State var yikes: Int = 0 var body: some View { if #available(iOS 18.0, *) { TabView(selection: $selectedTab) { MyFlightsView(yikes: $yikes) .tabItem { Label("My Flights", systemImage: "airplane.circle") }.tag(0) FlightplanView() .tabItem { Label("Flight Plan", systemImage: "doc.plaintext") }.tag(1) PreFlightView() .tabItem { Label("Pre Flight", systemImage: "airplane.departure") }.tag(2) CruiseView(yikes: $yikes) .tabItem { Label("Cruise", systemImage: "airplane") }.tag(3) PostFlightView() .tabItem { Label("Post Flight", systemImage: "airplane.arrival") }.tag(4) MoreView() .tabItem { Label("More", systemImage: "ellipsis") }.tag(5) NotificationsView() .tabItem { Label("Notifications", systemImage: "bell") }.tag(6) }.tabViewStyle(.sidebarAdaptable) } } }
1
0
282
3w
Debug Failed in Xcode Simulator
I can‘t use breakpoints on the simulator after updating Xcode and the simulator. I can use breakpoints on a physical iPhone. I tired to download other iOS simulator version, but still not working. Both SwiftUI and UIKit not working. Xcode version: 16.2 SDK version: 18.2 (22C146) Simulator version: 18.3.1 (22D8075) Mac OS version: 15.4 Beta Couldn't find the Objective-C runtime library in loaded images. Message from debugger: The LLDB RPC server has crashed. You may need to manually terminate your process. The crash log is located in ~/Library/Logs/DiagnosticReports and has a prefix 'lldb-rpc-server'. Please file a bug and attach the most recent crash log.
10
2
736
1w