Post

Replies

Boosts

Views

Activity

Apple Multi-peer connectivity problems with 8+ connections
Apple multi-peer with 12 devices is unstable. Dear All, Has anyone tried Apple multi-peer with 12 devices connected? We are building an application relying on multi-peer where 12 Ipads will be updating data and each device needs to share data between. Can anyone tell me if we can use multi-peer framework for connecting 12 devices in the multi-peer network? We are facing stability problems in the connection when we connect 12 devices in the network.
0
0
21
12h
Still possible to use XCode for local MacOS development without a bundle identifier?
I have used XCode for decades as my default C/C++ programming IDE. I write code that I run locally on my Mac, via "Sign to run locally". Typically this has always "just worked". I am now using MacOS 14.7 Sonoma, and I suddenly find I cannot run my code projects because I cannot dynamically load unsigned libraries. "not valid for use in process: library load disallowed by system policy" BUT - it appears that to allow my local MacOS code to bypass this requires I have a bundle identifier to modify entitlements. Which in turn requires a developer account which I don't have. Is this all correct? Is there any way to have code run locally and use dynamic libraries as I've done previously? Any advice is much appreciated.
2
0
134
1d
Add static c library to xcode/swift
Hi, I want to build an ios app that uses static c libraries. For reference, i did the following as a test: Compiled a simple c date and time program with clang -c -arch arm64 -sysroot <iPhoneOSSDK_path> date.c -o date_arm64.o Created the static lib ar rcs libdatetime_arm64.a date_arm64.o Added the lib in my Xcode project. Added the (.a) file in Build Rules -> Link Binary With Libraries Included the (.a) and (.h) file path in Build Settings -> Search Paths -> Header and Library Search Path Created a Bridging-Header.h file where I added #import "date.h" In my App.swift file, I called the function for getting the date and time let dateTimeStr = String(cString: get_current_datetime()) print("Current Date and Time: \(dateTimeStr)") After doing all the steps above, I am met with the error - Cannot find 'get_current_datetime' in scope Is there any other method to use static c libraries in xcode?
1
1
63
1d
Fresh Project Using Insecure APIs (_sscanf, _strlen, _fopen, malloc) in Binary
Hello Apple Developer Community, I recently created a fresh project with: No dependencies No additional written code After generating the iOS build, I navigated to the build folder:"build/ios/iphoneos/Runner.app" Then, I ran the following otool commands to inspect the binary: otool -Iv Runner | grep -w _strlen otool -Iv Runner | grep -w _malloc Surprisingly, I received positive results, meaning these functions are present in the binary. My Questions: Why is a fresh project (with no extra dependencies & No additional written code) including these APIs in the binary?
2
0
78
3d
An Apple Library Primer
Apple’s library technology has a long and glorious history, dating all the way back to the origins of Unix. This does, however, mean that it can be a bit confusing to newcomers. This is my attempt to clarify some terminology. If you have any questions or comments about this, start a new thread and tag it with Linker so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" An Apple Library Primer Apple’s tools support two related concepts: Platform — This is the platform itself; macOS, iOS, iOS Simulator, and Mac Catalyst are all platforms. Architecture — This is a specific CPU architecture used by a platform. arm64 and x86_64 are both architectures. A given architecture might be used by multiple platforms. The most obvious example of this arm64, which is used by all of the platforms listed above. Code built for one platform will not work on another platform, even if both platforms use the same architecture. Code is usually packaged in either a Mach-O file or a static library. Mach-O is used for executables, dynamic libraries, bundles, and object files. These can have a variety of different extensions; the only constant is that .o is always used for a Mach-O containing an object file. Use otool and nm to examine a Mach-O file. Use vtool to quickly determine the platform for which it was built. Use size to get a summary of its size. Use dyld_info to get more details about a dynamic library. IMPORTANT All the tools mentioned here are documented in man pages. For information on how to access that documentation, see Reading UNIX Manual Pages. There’s also a Mach-O man page, with basic information about the file format. Many of these tools have old and new variants, using the -classic suffix or llvm- prefix, respectively. For example, there’s nm-classic and llvm-nm. If you run the original name for the tool, you’ll get either the old or new variant depending on the version of the currently selected tools. To explicitly request the old or new variants, use xcrun. The term Mach-O image refers to a Mach-O that can be loaded and executed without further processing. That includes executables, dynamic libraries, and bundles, but not object files. A dynamic library has the extension .dylib. You may also see this called a shared library. A framework is a bundle structure with the .framework extension that has both compile-time and run-time roles: At compile time, the framework combines the library’s headers and its stub library (stub libraries are explained below). At run time, the framework combines the library’s code, as a Mach-O dynamic library, and its associated resources. The exact structure of a framework varies by platform. For the details, see Placing Content in a Bundle. macOS supports both frameworks and standalone dynamic libraries. Other Apple platforms support frameworks but not standalone dynamic libraries. Historically these two roles were combined, that is, the framework included the headers, the dynamic library, and its resources. These days Apple ships different frameworks for each role. That is, the macOS SDK includes the compile-time framework and macOS itself includes the run-time one. Most third-party frameworks continue to combine these roles. A static library is an archive of one or more object files. It has the extension .a. Use ar, libtool, and ranlib to inspect and manipulate these archives. The static linker, or just the linker, runs at build time. It combines various inputs into a single output. Typically these inputs are object files, static libraries, dynamic libraries, and various configuration items. The output is most commonly a Mach-O image, although it’s also possible to output an object file. The linker may also output metadata, such as a link map (see Using a Link Map to Track Down a Symbol’s Origin). The linker has seen three major implementations: ld — This dates from the dawn of Mac OS X. ld64 — This was a rewrite started in the 2005 timeframe. Eventually it replaced ld completely. If you type ld, you get ld64. ld_prime — This was introduced with Xcode 15. This isn’t a separate tool. Rather, ld now supports the -ld_classic and -ld_new options to select a specific implementation. Note During the Xcode 15 beta cycle these options were -ld64 and -ld_prime. I continue to use those names because the definition of new changes over time (some of us still think of ld64 as the new linker ;–). The dynamic linker loads Mach-O images at runtime. Its path is /usr/lib/dyld, so it’s often referred to as dyld, dyld, or DYLD. Personally I pronounced that dee-lid, but some folks say di-lid and others say dee-why-el-dee. IMPORTANT Third-party executables must use the standard dynamic linker. Other Unix-y platforms support the notion of a statically linked executable, one that makes system calls directly. This is not supported on Apple platforms. Apple platforms provide binary compatibility via system dynamic libraries and frameworks, not at the system call level. Note Apple platforms have vestigial support for custom dynamic linkers (your executable tells the system which dynamic linker to use via the LC_LOAD_DYLINKER load command). This facility originated on macOS’s ancestor platform and has never been a supported option on any Apple platform. The dynamic linker has seen 4 major revisions. See WWDC 2017 Session 413 (referenced below) for a discussion of versions 1 through 3. Version 4 is basically a merging of versions 2 and 3. The dyld man page is chock-full of useful info, including a discussion of how it finds images at runtime. Every dynamic library has an install name, which is how the dynamic linker identifies the library. Historically that was the path where you installed the library. That’s still true for most system libraries, but nowadays a third-party library should use an rpath-relative install name. For more about this, see Dynamic Library Identification. Mach-O images are position independent, that is, they can be loaded at any location within the process’s address space. Historically, Mach-O supported the concept of position-dependent images, ones that could only be loaded at a specific address. While it may still be possible to create such an image, it’s no longer a good life choice. Mach-O images have a default load address, also known as the base address. For modern position-independent images this is 0 for library images and 4 GiB for executables (leaving the bottom 32 bits of the process’s address space unmapped). When the dynamic linker loads an image, it chooses an address for the image and then rebases the image to that address. If you take that address and subtract the image’s load address, you get a value known as the slide. Xcode 15 introduced the concept of a mergeable library. This a dynamic library with extra metadata that allows the linker to embed it into the output Mach-O image, much like a static library. Mergeable libraries have many benefits. For all the backstory, see WWDC 2023 Session 10268 Meet mergeable libraries. For instructions on how to set this up, see Configuring your project to use mergeable libraries. If you put a mergeable library into a framework structure you get a mergeable framework. Xcode 15 also introduced the concept of a static framework. This is a framework structure where the framework’s dynamic library is replaced by a static library. Note It’s not clear to me whether this offers any benefit over creating a mergeable framework. Earlier versions of Xcode did not have proper static framework support. That didn’t stop folks trying to use them, which caused all sorts of weird build problems. A universal binary is a file that contains multiple architectures for the same platform. Universal binaries always use the universal binary format. Use the file command to learn what architectures are within a universal binary. Use the lipo command to manipulate universal binaries. A universal binary’s architectures are either all in Mach-O format or all in the static library archive format. The latter is called a universal static library. A universal binary has the same extension as its non-universal equivalent. That means a .a file might be a static library or a universal static library. Most tools work on a single architecture within a universal binary. They default to the architecture of the current machine. To override this, pass the architecture in using a command-line option, typically -arch or --arch. An XCFramework is a single document package that includes libraries for any combination of platforms and architectures. It has the extension .xcframework. An XCFramework holds either a framework, a dynamic library, or a static library. All the elements must be the same type. Use xcodebuild to create an XCFramework. For specific instructions, see Xcode Help > Distribute binary frameworks > Create an XCFramework. Historically there was no need to code sign libraries in SDKs. If you shipped an SDK to another developer, they were responsible for re-signing all the code as part of their distribution process. Xcode 15 changes this. You should sign your SDK so that a developer using it can verify this dependency. For more details, see WWDC 2023 Session 10061 Verify app dependencies with digital signatures and Verifying the origin of your XCFrameworks. A stub library is a compact description of the contents of a dynamic library. It has the extension .tbd, which stands for text-based description (TBD). Apple’s SDKs include stub libraries to minimise their size; for the backstory, read this post. Stub libraries currently use YAML format, a fact that’s relevant when you try to interpret linker errors. Use the tapi tool to create and manipulate these files. In this context TAPI stands for a text-based API, an alternative name for TBD. Oh, and on the subject of tapi, I’d be remiss if I didn’t mention tapi-analyze! Historically, the system maintained a dynamic linker shared cache, built at runtime from its working set of dynamic libraries. In macOS 11 and later this cache is included in the OS itself. Libraries in the cache are no longer present in their original locations on disk: % ls -lh /usr/lib/libSystem.B.dylib ls: /usr/lib/libSystem.B.dylib: No such file or directory Apple APIs, most notably dlopen, understand this and do the right thing if you supply the path of a library that moved into the cache. That’s true for some, but not all, command-line tools, for example: % dyld_info -exports /usr/lib/libSystem.B.dylib /usr/lib/libSystem.B.dylib [arm64e]: -exports: offset symbol … 0x5B827FE8 _mach_init_routine % nm /usr/lib/libSystem.B.dylib …/nm: error: /usr/lib/libSystem.B.dylib: No such file or directory When the linker creates a Mach-O image, it adds a bunch of helpful information to that image, including: The target platform The deployment target, that is, the minimum supported version of that platform Information about the tools used to build the image, most notably, the SDK version A build UUID For more information about the build UUID, see TN3178 Checking for and resolving build UUID problems. To dump the other information, run vtool. In some cases the OS uses the SDK version of the main executable to determine whether to enable new behaviour or retain old behaviour for compatibility purposes. You might see this referred to as compiled against SDK X. I typically refer to this as a linked-on-or-later check. Mach-O uses a two-level namespace. When a Mach-O image imports a symbol, it references the symbol name and the library where it expects to find that symbol. This improves both performance and reliability but it precludes certain techniques that might work on other platforms. For example, you can’t define a function called printf and expect it to ‘see’ calls from other dynamic libraries because those libraries import the version of printf from libSystem. To help folks who rely on techniques like this, macOS supports a flat namespace compatibility mode. This has numerous sharp edges — for an example, see the posts on this thread — and it’s best to avoid it where you can. If you’re enabling the flat namespace as part of a developer tool, search the ’net for dyld interpose to learn about an alternative technique. WARNING Dynamic linker interposing is not documented as API. While it’s a useful technique for developer tools, do not use it in products you ship to end users. Apple platforms use DWARF. When you compile a file, the compiler puts the debug info into the resulting object file. When you link a set of object files into a executable, dynamic library, or bundle for distribution, the linker does not include this debug info. Rather, debug info is stored in a separate debug symbols document package. This has the extension .dSYM and is created using dsymutil. Use symbols to learn about the symbols in a file. Use dwarfdump to get detailed information about DWARF debug info. Use atos to map an address to its corresponding symbol name. Different languages use different name mangling schemes: C, and all later languages, add a leading underscore (_) to distinguish their symbols from assembly language symbols. C++ uses a complex name mangling scheme. Use the c++filt tool to undo this mangling. Likewise, for Swift. Use swift demangle to undo this mangling. For a bunch more info about symbols in Mach-O, see Understanding Mach-O Symbols. This includes a discussion of weak references and weak definition. To remove symbols from a Mach-O file, run strip. To hide symbols, run nmedit. It’s common for linkers to divide an object file into sections. You might find data in the data section and code in the text section (text is an old Unix term for code). Mach-O uses segments and sections. For example, there is a text segment (__TEXT) and within that various sections for code (__TEXT > __text), constant C strings (__TEXT > __cstring), and so on. Over the years there have been some really good talks about linking and libraries at WWDC, including: WWDC 2023 Session 10268 Meet mergeable libraries WWDC 2022 Session 110362 Link fast: Improve build and launch times WWDC 2022 Session 110370 Debug Swift debugging with LLDB WWDC 2021 Session 10211 Symbolication: Beyond the basics WWDC 2019 Session 416 Binary Frameworks in Swift — Despite the name, this covers XCFrameworks in depth. WWDC 2018 Session 415 Behind the Scenes of the Xcode Build Process WWDC 2017 Session 413 App Startup Time: Past, Present, and Future WWDC 2016 Session 406 Optimizing App Startup Time Note The older talks are no longer available from Apple, but you may be able to find transcripts out there on the ’net. Historically Apple published a document, Mac OS X ABI Mach-O File Format Reference, or some variant thereof, that acted as the definitive reference to the Mach-O file format. This document is no longer available from Apple. If you’re doing serious work with Mach-O, I recommend that you find an old copy. It’s definitely out of date, but there’s no better place to get a high-level introduction to the concepts. The Mach-O Wikipedia page has a link to an archived version of the document. For the most up-to-date information about Mach-O, see the declarations and doc comments in <mach-o/loader.h>. Revision History 2025-03-01 Added a link to Understanding Mach-O Symbols. Added a link to TN3178 Checking for and resolving build UUID problems. Added a summary of the information available via vtool. Discussed linked-on-or-later checks. Explained how Mach-O uses segments and sections. Explained the old (-classic) and new (llvm-) tool variants. Referenced the Mach-O man page. Added basic info about the strip and nmedit tools. 2025-02-17 Expanded the discussion of dynamic library identification. 2024-10-07 Added some basic information about the dynamic linker shared cache. 2024-07-26 Clarified the description of the expected load address for Mach-O images. 2024-07-23 Added a discussion of position-independent images and the image slide. 2024-05-08 Added links to the demangling tools. 2024-04-30 Clarified the requirement to use the standard dynamic linker. 2024-03-02 Updated the discussion of static frameworks to account for Xcode 15 changes. Removed the link to WWDC 2018 Session 415 because it no longer works )-: 2024-03-01 Added the WWDC 2023 session to the list of sessions to make it easier to find. Added a reference to Using a Link Map to Track Down a Symbol’s Origin. Made other minor editorial changes. 2023-09-20 Added a link to Dynamic Library Identification. Updated the names for the static linker implementations (-ld_prime is no more!). Removed the beta epithet from Xcode 15. 2023-06-13 Defined the term Mach-O image. Added sections for both the static and dynamic linkers. Described the two big new features in Xcode 15: mergeable libraries and dependency verification. 2023-06-01 Add a reference to tapi-analyze. 2023-05-29 Added a discussion of the two-level namespace. 2023-04-27 Added a mention of the size tool. 2023-01-23 Explained the compile-time and run-time roles of a framework. Made other minor editorial changes. 2022-11-17 Added an explanation of TAPI. 2022-10-12 Added links to Mach-O documentation. 2022-09-29 Added info about .dSYM files. Added a few more links to WWDC sessions. 2022-09-21 First posted.
0
0
8.5k
Sep ’22
Not Sandbox App, Working on SMAppService as root
I am currently developing a No-Sandbox application. What I want to achieve is to use AuthorizationCopyRights in a No-Sandbox application to elevate to root, then register SMAppService.daemon after elevation, and finally call the registered daemon from within the No-Sandbox application. Implementation Details Here is the Plist that I am registering with SMAppService: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.example.agent</string> <key>BundleProgram</key> <string>/usr/local/bin/test</string> <key>ProgramArguments</key> <array> <string>/usr/local/bin/test</string> <string>login</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> Code that successfully performs privilege escalation (a helper tool popup appears) private func registerSMAppServiceDaemon() -> Bool { let service = SMAppService.daemon(plistName: "com.example.plist") do { try service.register() print("Successfully registered \(service)") return true } catch { print("Unable to register \(error)") return false } } private func levelUpRoot() -> Bool { var authRef: AuthorizationRef? let status = AuthorizationCreate(nil, nil, [], &authRef) if status != errAuthorizationSuccess { return false } let rightName = kSMRightBlessPrivilegedHelper return rightName.withCString { cStringName -> Bool in var authItem = AuthorizationItem( name: cStringName, valueLength: 0, value: nil, flags: 0 ) return withUnsafeMutablePointer(to: &authItem) { authItemPointer -> Bool in var authRights = AuthorizationRights(count: 1, items: authItemPointer) let authFlags: AuthorizationFlags = [.interactionAllowed, .preAuthorize, .extendRights] let status = AuthorizationCopyRights(authRef!, &authRights, nil, authFlags, nil) if status == errAuthorizationSuccess { if !registerSMAppServiceDaemon() { return false } return true } return false } } } Error Details Unable to register Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted} The likely cause of this error is that /usr/local/bin/test is being bundled. However, based on my understanding, since this is a non-sandboxed application, the binary should be accessible as long as it is run as root. Trying post as mentioned in the response, placing the test binary under Contents/Resources/ allows SMAppService to successfully register it. However, executing the binary results in a different error. Here is the plist at that time. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.example.agent</string> <key>BundleProgram</key> <string>Contents/Resources/test</string> <key>ProgramArguments</key> <array> <string>Contents/Resources/test</string> <string>login</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> Here is the function at that time. private func executeBin() { let bundle = Bundle.main if let binaryPath = bundle.path(forResource: "test", ofType: nil) { print(binaryPath) let task = Process() task.executableURL = URL(fileURLWithPath: binaryPath) task.arguments = ["login"] let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe do { try task.run() let outputData = pipe.fileHandleForReading.readDataToEndOfFile() if let output = String(data: outputData, encoding: .utf8) { print("Binary output: \(output)") } task.waitUntilExit() if task.terminationStatus == 0 { print("Binary executed successfully") } else { print("Binary execution failed with status: \(task.terminationStatus)") } } catch { print("Error executing binary: \(error)") } } else { print("Binary not found in the app bundle") } } Executed After Error Binary output: Binary execution failed with status: 5 Are there any other ways to execute a specific binary as root when using AuthorizationCopyRights? For example, by preparing a Helper Tool?
1
0
83
3d
Adding ‘Test diamonds’ to Xcode with a macro
I'm currently writing a macro which outputs Swift Testing code: // Macro code ... @MainActor @SnapshotSuite struct MySuite { func makeView() -&gt; some View { Text("a view") } } which expands to... // Expanded macro code ... @MainActor @Suite struct _GeneratedSnapshotSuite { @MainActor @Test(.tags(.snapshots)) func assertSnapshotMakeView() async throws { let generator = SnapshotGenerator( testName: "makeView", traits: [ .theme(.all), .sizes(devices: .iPhoneX, fitting: .widthAndHeight), .record(false), ], configuration: .none, makeValue: { MySuite().makeView() }, fileID: #fileID, filePath: #filePath, line: 108, column: 5 ) await __assertSnapshot(generator: generator) } } In short, this macro creates snapshot tests from a function. This all works but I'm finding a couple of limitations, potentially with how Macros are expanded in Swift. Xcode diamonds are not visible The snapshots tag isn't discovered There are a couple of things worth noting though: The suites and tests are discovered in Xcode's Test Navigator each time Xcode runs tests (cmd + u) - although they need to rerun to be updated. I manually add a @Suite in my code as well as my @SnapshotSuite to all of the suites. (The tags never seem to be available though) Couple of questions on this: Is this a known issue? Are there any workarounds? I do wonder if there's a workaround for showing the diamonds with XCTest APIs such as: https://github.com/swiftlang/swift-corelibs-xctest/tree/main https://developer.apple.com/documentation/xctest
1
0
144
2d
Fresh Project Using Insecure APIs (_sscanf, _strlen, _fopen, malloc) in Binary
Hello Apple Developer Community, I recently created a fresh project with: No dependencies No additional written code After generating the iOS build, I navigated to the build folder: cd build/ios/iphoneos/Runner.app Then, I ran the following commands to inspect the binary: otool -Iv Runner | grep -w _strlen otool -Iv Runner | grep -w _malloc Surprisingly, I received positive results, meaning these functions are present in the binary. My Questions: Why is a fresh Flutter project (with no extra dependencies) including these APIs in the binary?
1
0
62
3d
Issue with Apple Developer Enrollment – Stuck in Pending State
Hello, I've noticed that many people on the forum are experiencing issues enrolling in the Apple Developer Program. I’m facing the same problem—I can't complete my enrollment using my MacBook Pro. When I try to enroll through the Apple Developer app, I get an error saying, "Enrollment through the Apple Developer app is not available for this Apple ID." So, I tried using Safari instead. I submitted all my personal information and credit card details and initiated the order. However, no transaction was processed from my bank account, and I received an email stating that I would be notified when my order and items are ready. When I check the Apple Developer portal, my enrollment status is Pending, and I see a message prompting me to complete the purchase, as if I need to make a new payment. I don’t understand why Apple makes it so complicated just to subscribe to the Developer Program. Why can’t I use my MacBook Pro for enrollment? Why does the Developer portal ask me to complete the purchase even though I already submitted my payment details? Why is the process so confusing? Any help or clarification would be greatly appreciated. Thanks!
0
0
63
3d
How to identify apps in FamilyActivitySelection?
Questions I am developing a social screen time application that enables users to create “sprints” and set sprint goals—essentially time limits on usage for selected applications. For this functionality, users select the apps they wish to manage using the FamilyActivitySelection interface (from the FamilyControls framework). However, our backend needs to distinguish each application uniquely (for example, via the app’s bundle identifier) in order to correctly map and enforce user-defined sprint goals. Unfortunately, we are encountering an issue where retrieving the bundle identifier directly from the FamilyActivitySelection is returning nil. As a result, we are unable to globally identify the selected apps. Could you please advise if there is an alternative method or property available in the FamilyControls API that would allow us to uniquely identify the apps? Alternatively, is there another approach recommended by Apple for obtaining a global identifier for applications selected via FamilyActivitySelection? Thank you for your time and assistance. I look forward to your guidance on how to resolve this issue. Code The following is the print statement I used to check if bundleIdentifier is nil after I stored user's selections to the variable selection using familyActivityPicker: for app in selection!.applications { let bundleId = app.bundleIdentifier ?? "Unknown Bundle ID" let token = app.token let localizedDisplayName = app.localizedDisplayName ?? "Unknown Localized Display Name" print("Selected app bundle identifier: \(bundleId)") print("localizedDisplayName: \(localizedDisplayName)") } Console log result I received from the print statement above: Selected app bundle identifier: Unknown Bundle ID localizedDisplayName: Unknown Localized Display Name
1
0
96
1d
LLDB error: type for self cannot be reconstructed: type for typename
All is fine in Xcode15, no LLDB errors whatsoever, but in Xcode16 I can't get any variable displayed in the console because of the following error: error: type for self cannot be reconstructed: type for typename "$......." was not found (cached) error: Couldn't realize Swift AST type of self. Hint: using `v` to directly inspect variables and fields may still work. I've checked the output of swift-healthcheck and there are several messages like this: SwiftASTContextForExpressions(module: "ROA", cu: "ROA+ViewLayer.swift")::LoadOneModule() -- Missing Swift module or Clang module found for "UIKit", "imported" via SwiftDWARFImporterDelegate. Hint: Register Swift modules with the linker using -add_ast_path. I added -add_ast_path to the OTHER_LDFLAGS in the faulty module's build settings but no luck. How can I debug my project in Xcode16?
9
1
809
Jan ’25
devicectl copy directory recursively
I can use devicectl to copy single files from a device fine using: xcrun devicectl --verbose device copy from --user mobile --domain-identifier <BUNDLE_ID> --domain-type appDataContainer --device <DEVICE_ID> --source Documents/Screenshots/0001.png --destination Screeshots/0001.png but when there are many files this can get pretty slow. Is there a way of recursively copying an entire directory? I've tried this: xcrun devicectl --verbose device copy from --user mobile --domain-identifier <BUNDLE_ID> --domain-type appDataContainer --device <DEVICE_ID> --source Documents/Screenshots --destination Screeshots but nothing is transferred and it times out eventually with the error: ERROR: The specified file could not be transferred. (com.apple.dt.CoreDeviceError error 7000 (0x1B58)) ERROR: The operation couldn’t be completed. The file service client failed to read data from the network socket because we timed out when waiting for data to become available. (NSPOSIXErrorDomain error 60 (0x3C)) NSLocalizedFailureReason = The file service client failed to read data from the network socket because we timed out when waiting for data to become available. Xcode itself can do it with the "download container..." option, but I'd like to be able to automate it.
0
0
75
19h
Content Blocker Disappears from Mac Safari Settings
I have had content blockers in the Mac App Store for years. Ever since moving to Sonoma, doing a clean build or archive in XCode deletes the extension from Safari settings since it never gets into the built app. The only way for me to get it back is to remove the DerivedData and target, reboot, and create a target with a different name. That works and stays around in Safari settings as long as I only build and don't clean. However, a clean or an archive removes it again. Restoring a version of the project from Time Machine that was posted to the App Store weeks or months ago doesn't work. However I can download the version of the app in the App Store, and it works, but I can't build it now from the source code that was used to build that version without going through the above process. Moving from Sonoma 14.7.1 to 14.7.2 didn't work. I would move to Sequoia if I had reason to believe that would work, but I don't. Safari 18.2, Sonoma 14.7.2, 32GB, 2.2 GHz 6-Core Intel Core i7
0
0
110
21h
Weather Authentication Failed
I'm pretty new on this platform and also developing IOS mobile apps. I've been struggling for using the data of the api weather kit apple. I have an acount of apple developer, downloaded the certificate... i follow all the necessaries steps in the portal and also in my project and i keep having this error message when i try to use it. I don't know what else should i do for having working it. I would absolutely appreciate that someone could help me with this. Thank you very much!!!!! Encountered an error when fetching weather data subset; location=<+41.38268070,+2.17702390> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2/3/25, 22:54:03 Central European Standard Time, error=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors 2 Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)"
0
0
86
22h
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
120
23h
Previews due to SwiftData Predicates in Xcode 16.3
My preview crashes whenever I compare my model's value to a constant's stored value. I use struct constants with a stored value as alternatives to enums, (IIRC ever since the beginning) enums never worked at all with .rawValue or computed properties. This crashes when it runs on Xcode 16.3 beta and iOS 18.4 in previews. It doesn't appear to crash in simulator. @Model class Media { @Attribute(.unique) var id: UUID = UUID() @Attribute var type: MediaType init(type: MediaType) { self.type = type } static var predicate: (Predicate<Media>) { let image = MediaType.image.value let predicate = #Predicate<Media> { media in media.type.value == image } return predicate } } struct MediaType: Codable, Equatable, Hashable { static let image: MediaType = .init(value: 0) static let video: MediaType = .init(value: 1) static let audio: MediaType = .init(value: 2) var value: Int } My application crashes with "Application crashed due to fatalError in Schema.swift at line 320." KeyPath \Media.<computed 0x000000034082a33c (MediaType)>.value points to a field (<computed 0x000000034082a33c (MediaType)>) that is unknown to Media and cannot be used. This appears to also occur if I am using a generic/any func and use protocols to access a property which is a simple String, such as id or name, despite it being a stored SwiftData attribute. I filed a bug report, but looking to hear workarounds.
3
0
72
1d
Xcode 16 „forgetting“ package in subfolder to root package
Xcode 16 seems to „forget“ a swift package within a subfolder of a root package after restart or shut-down. I have the following project structure, which also resembles the directory structure on disc: MyPackage - Package.swift - README.md - Sources - MyPackage - Tests - MyPackageTests - Tools - MyGenerator // <- after restart this folder is not visible in the Xcode project navigator - Package.swift - Sources - main.swift - Tests MyGenerator is a standalone package which is used during development of MyPackage to generate source code files for MyPackage based on text file input. Essentially an executable target script which I can run within its folder with: swift run MyGenerator someInputFile.txt MyPackage does NOT use MyGenerator as a dependency, nor do I want this tool listed as a dependency in MyPackage Package.swift file. Yet MyGenerator is part of the same Git repo, as it documents the changes to the tool on how to generate source code for MyPackage. Both packages are developed in tandem. MyGenerator itself defines dependencies in its Package.swift file, which are unrelated to the functionality of MyPackage. After restart of Xcode or even just a longer shut-down period the MyGenerator subfolder is not visible in the Xcode project navigator, the /Tools folder is empty. I have to manually add the sub package via Add files to "MyPackage" -> Move files to destination every time. How can I solve that Xcode remembers the sub package unter /Tools? Edit: I am using Xcode 16.2
0
0
86
1d