Post

Replies

Boosts

Views

Activity

Creating file bookmarks doesn't work anymore on macOS 15 Sequoia
Before updating to macOS 15 Sequoia, I used to be able to create file bookmarks with this code: let openPanel = NSOpenPanel() openPanel.runModal() let url = openPanel.urls[0] do { let _ = try url.bookmarkData(options: [.withSecurityScope]) } catch { print(error) } Now I get an error Error Domain=NSCocoaErrorDomain Code=256 "Failed to retrieve app-scope key" These are the entitlements: com.apple.security.app-sandbox com.apple.security.files.user-selected.read-write com.apple.security.files.bookmarks.app-scope Strangely, my own apps continued working, after updating to macOS 15 some days ago, until a few moments ago. Then it seems that all of a sudden my existing bookmarks couldn't be resolved anymore, and no new bookmarks could be created. What could be the problem?
28
3
3.4k
Feb ’25
getattrlistbulk lists same files over and over on macOS 15 Sequoia
A customer of mine reported that since updating to macOS 15 they aren't able to use my app anymore, which performs a deep scan of selected folders by recursively calling getattrlistbulk. The problem is that the app apparently keeps scanning forever, with the number of scanned files linearly increasing to infinity. This happens for some folders on a SMB volume. The customer confirmed that they can reproduce the issue with a small sample app that I attach below. At first, I created a sample app that only scans the contents of the selected folder without recursively scanning the subcontents, but the issue didn't happen anymore, so it seems to be related to recursively calling getattrlistbulk. The output of the sample app on the customer's Mac is similar to this: start scan /Volumes/shares/Backup/Documents level 0 fileManagerCount 2847 continue scan /Volumes/shares/Backup/Documents new items 8, sum 8, errno 34 /Volumes/shares/Backup/Documents/A.doc /Volumes/shares/Backup/Documents/B.doc ... continue scan /Volumes/shares/Backup/Documents new items 7, sum 1903, errno 0 /Volumes/shares/Backup/Documents/FKV.pdf /Volumes/shares/Backup/Documents/KFW.doc /Volumes/shares/Backup/Documents/A.doc /Volumes/shares/Backup/Documents/B.doc ... which shows that counting the number of files in the root folder by using try FileManager.default.contentsOfDirectory(atPath: path).count returns 2847, while getattrlistbulk lists about 1903 files and then starts listing the files from the beginning, not even between repeated calls, but within a single call. What could this issue be caused by? (The website won't let me attach .swift files, so I include the source code of the sample app as a text attachment.) ViewController.swift
18
0
1.2k
Dec ’24
NSDocument doesn't autosave last changes
I had noticed an unsettling behaviour about NSDocument some years ago and created FB7392851, but the feedback didn't go forward, so I just updated it and hopefully here or there someone can explain what's going on. When running a simple document-based app with a text view, what I type before closing the app may be discarded without notice. To reproduce it, you can use the code below, then: Type "asdf" in the text view. Wait until the Xcode console logs "saving". You can trigger it by switching to another app and back again. Type something else in the text view, such as "asdf" on a new line. Quit the app. Relaunch the app. The second line has been discarded. Am I doing something wrong or is this a bug? Is there a workaround? class ViewController: NSViewController { @IBOutlet var textView: NSTextView! } class Document: NSDocument { private(set) var text = "" override class var autosavesInPlace: Bool { return true } override func makeWindowControllers() { let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController (windowController.contentViewController as? ViewController)?.textView.string = text self.addWindowController(windowController) } override func data(ofType typeName: String) throws -> Data { Swift.print("saving") text = (windowControllers.first?.contentViewController as? ViewController)?.textView.string ?? "" return Data(text.utf8) } override func read(from data: Data, ofType typeName: String) throws { text = String(decoding: data, as: UTF8.self) (windowControllers.first?.contentViewController as? ViewController)?.textView.string = text } }
Topic: UI Frameworks SubTopic: AppKit Tags:
17
0
452
Oct ’25
Weird crashes when accessing Swift Array
For some time now Xcode has been downloading crash reports from users of my app about crashes related to arrays. One of them looks like this: ... Code Type: ARM-64 Parent Process: launchd [1] User ID: 501 Date/Time: 2024-07-18 14:59:40.4375 +0800 OS Version: macOS 15.0 (24A5289h) ... Crashed Thread: 0 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001045048b8 Termination Reason: Namespace SIGNAL, Code 5 Trace/BPT trap: 5 Terminating Process: exc handler [1771] Thread 0 Crashed: 0 MyApp 0x00000001045048b8 specialized Collection.map<A>(_:) + 596 1 MyApp 0x00000001045011e4 MyViewController.validateToolbarButtons() + 648 (MyViewController.swift:742) ... The relevant code looks like this: class MyViewController { func validateToolbarButtons() { let indexes = tableView.clickedRow == -1 || tableView.selectedRowIndexes.contains(tableView.clickedRow) ? tableView.selectedRowIndexes : IndexSet(integer: tableView.clickedRow) let items = indexes.map({ myArray[$0] }) ... } } The second crash looks like this: ... Code Type: X86-64 (Native) Parent Process: launchd [1] User ID: 502 Date/Time: 2024-07-15 15:53:35.2229 -0400 OS Version: macOS 15.0 (24A5289h) ... Crashed Thread: 0 Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [13244] Thread 0 Crashed: 0 libswiftCore.dylib 0x00007ff812904fc0 _assertionFailure(_:_:flags:) + 288 1 MyApp 0x0000000101a31e04 specialized _ArrayBuffer._getElementSlowPath(_:) + 516 2 MyApp 0x00000001019d04eb MyObject.myProperty.setter + 203 (MyObject.swift:706) 3 MyApp 0x000000010192f66e MyViewController.controlTextDidChange(_:) + 190 (MyViewController.swift:166) ... And the relevant code looks like this: class MyObject { var myProperty: [MyObject] { get { ... } set { let items = newValue.map({ $0.id }) ... } } } What could cause such crashes? Could they be caused by anything other than concurrent access from multiple threads (which I'm quite sure is not the case here, as I only access these arrays from the main thread)?
16
0
2.3k
Mar ’25
Making filecopy faster by changing block size
I'm using the filecopy function to copy many files and I noticed that it always takes longer than similar tools like cp or a Finder copy (I already did a comparison in my other post). What I didn't know before was that I can set the block size which apparently can have a big influence on how fast the file copy operation is. The question now is: what should I consider before manually setting the block size? Does it make sense to have a block size that is not a power of 2? Can certain block sizes cause an error, such as a value that is too large (for the Mac the code is running on, or for the source and target devices)? When should or shouldn't I deviate from the default? Is there a way to find out the optimal block size for given source and target devices, or at least one that performs better than the default? In the following sample code I tried to measure the average time for varying block sizes, but I'm not sure it's the best way to measure it, since each loop iteration can have wildly different durations. class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { let openPanel = NSOpenPanel() openPanel.runModal() let source = openPanel.urls[0] openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.runModal() let destination = openPanel.urls[0].appendingPathComponent(source.lastPathComponent) let date = Date() let count = 10 for _ in 0..&lt;count { try? FileManager.default.removeItem(at: destination) do { try copy(source: source, destination: destination) } catch { preconditionFailure(error.localizedDescription) } } print(-date.timeIntervalSinceNow / Double(count)) } func copy(source: URL, destination: URL) throws { try source.withUnsafeFileSystemRepresentation { sourcePath in try destination.withUnsafeFileSystemRepresentation { destinationPath in let state = copyfile_state_alloc() defer { copyfile_state_free(state) } // var bsize = Int32(16_777_216) var bsize = Int32(1_048_576) if copyfile_state_set(state, UInt32(COPYFILE_STATE_BSIZE), &amp;bsize) != 0 || copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CB), unsafeBitCast(copyfileCallback, to: UnsafeRawPointer.self)) != 0 || copyfile_state_set(state, UInt32(COPYFILE_STATE_STATUS_CTX), unsafeBitCast(self, to: UnsafeRawPointer.self)) != 0 || copyfile(sourcePath, destinationPath, state, copyfile_flags_t(COPYFILE_ALL | COPYFILE_NOFOLLOW | COPYFILE_EXCL)) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } } } } private let copyfileCallback: copyfile_callback_t = { what, stage, state, src, dst, ctx in if what == COPYFILE_COPY_DATA { if stage == COPYFILE_ERR { return COPYFILE_QUIT } var size: off_t = 0 copyfile_state_get(state, UInt32(COPYFILE_STATE_COPIED), &amp;size) let appDelegate = unsafeBitCast(ctx, to: AppDelegate.self) if !appDelegate.setCopyFileProgress(Int64(size)) { return COPYFILE_QUIT } } return COPYFILE_CONTINUE } private func setCopyFileProgress(_ progress: Int64) -&gt; Bool { return true } }
14
1
1.5k
Jan ’24
Finder shows warning "Apple could not verify file is free of malware" when setting my app as "Always open with"
A user of my AppKit, document-based app brought to my attention that when setting it as the default app to open a certain file with extension .md (by choosing in the Finder "File &gt; Open With &gt; Other", then selecting my app and enabling "Always open with"), trying to open it with a double-click displays the warning "Apple could not verify [file] is free of malware that may harm your mac or compromise your privacy". This is what happens for me: When keeping the default app for a .md file (Xcode in my case), the file opens just fine. When choosing my app in the "File &gt; Open With" menu, the file opens just fine in my app. But when setting my app as the default app (see above), the warning is displayed. From that moment on, choosing my app in the "File &gt; Open With" menu doesn't work anymore. Selecting Xcode doesn't work either. Only setting Xcode again as the default app allows me to open it in Xcode, but my app still isn't allowed to open it. Is this a macOS issue, or can I do anything in my app to prevent it? Where should I start looking for the issue in my code?
14
0
351
Aug ’25
Detect and wait until a file has been unzipped to avoid permission errors
In my app the user can select a source folder to be synced with a destination folder. The sync can also happen in response to a change in the source folder detected with FSEventStreamCreate. If the user unzips an archive in the source folder and the sync process begins before the unzip operation has completed, the sync can fail because of a "Permission denied" error. I assume this is related to the posix permissions of the extracted folder being 420 during the unzip operation and (in my case) 511 afterwards. Is there a way to detect than an unzip operation is in progress and wait until it has completed? I thought that using NSFileCoordinator would solve this issue, but unfortunately it's not the case. Since an unzip operation can last any amount of time, it's not ideal to just delay a sync by a fixed number of seconds and let the user deal with any error if the unzip operation takes longer. let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true if openPanel.runModal() == .cancel { return } let url = openPanel.urls[0].appendingPathComponent("extracted", isDirectory: false) var error: NSError? NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: url, error: &error) { url in do { print(try FileManager.default.attributesOfItem(atPath: url.path).sorted(by: { $0.key.rawValue < $1.key.rawValue }).map({ ($0.key.rawValue, $0.value) })) try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) } catch { print(error) } } if let error = error { print("file coordinator error:", error) }
13
0
168
Jun ’25
How to create file system snapshots with fs_snapshot_create?
The online documentation for fs_snapshot_create, which is on a website which apparently I'm not allowed to link to on this forum, mentions that some entitlement is necessary, but doesn't specify which one. Searching online I found someone mentioning com.apple.developer.vfs.snapshot, but when adding this to my entitlement file and building my Xcode project, I get the error Provisioning profile "Mac Team Provisioning Profile: com.example.myApp" doesn't include the com.apple.developer.vfs.snapshot entitlement. Searching some more online, I found someone mentioning that one has to request this entitlement from DTS. Is this true? I couldn't find any official documentation. I actually want to make a snapshot of a user-selected directory so that my app can sync it to another volume while avoiding that the user makes changes during the sync process that would make the copy inconsistent. Would fs_snapshot_create be faster than traversing the chosen directory and creating clones of each nested file with filecopy and the flag COPYFILE_CLONE? Although I have the impression that only fs_snapshot_create could make a truly consistent snapshot.
13
0
228
Jul ’25
Resizing text to fit available space
My app displays some text that should appear the same regardless of the container view or window size, i.e. it should grow and shrink with the container view or window. On iOS there is UILabel.adjustsFontSizeToFitWidth but I couldn't find any equivalent API on macOS. On the internet some people suggest to iteratively set a smaller font size until the text fits the available space, but I thought there must be a more efficient solution. How does UILabel.adjustsFontSizeToFitWidth do it? My expectation was that setting a font's size to a fraction of the window width or height would do the trick, but when resizing the window I can see a slightly different portion of it. class ViewController: NSViewController { override func loadView() { view = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) NSLayoutConstraint.activate([view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 3), view.heightAnchor.constraint(greaterThanOrEqualToConstant: 100)]) } } class MyView: NSView { let textField = NSTextField(labelWithString: String(repeating: "a b c d e f g h i j k l m n o p q r s t u v w x y z ", count: 2)) override init(frame frameRect: NSRect) { super.init(frame: frameRect) textField.translatesAutoresizingMaskIntoConstraints = false textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) addSubview(textField) NSLayoutConstraint.activate([textField.topAnchor.constraint(equalTo: topAnchor), textField.leadingAnchor.constraint(equalTo: leadingAnchor), textField.trailingAnchor.constraint(equalTo: trailingAnchor)]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func resize(withOldSuperviewSize oldSize: NSSize) { // textField.font = .systemFont(ofSize: frame.width * 0.05) textField.font = .systemFont(ofSize: frame.height * 0.1) } }
Topic: UI Frameworks SubTopic: AppKit Tags:
13
0
355
Nov ’25
SceneKit app randomly crashes with EXC_BAD_ACCESS in jet_context::set_fragment_texture
Every now and then my SceneKit game app crashes and I have no idea why. The SCNView has a overlaySKScene, so it might also be SpriteKit's fault. The stack trace is #0 0x0000000241c1470c in jet_context::set_fragment_texture(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> const&, jet_texture*) () #27 0x000000010572fd40 in _pthread_wqthread () Does anyone have an idea where I could start debugging this, without being able to consistently reproduce it?
12
0
1.3k
Nov ’24
Crash when assigning NSImage to `@objc dynamic var` property
Xcode downloaded a crash report for my app which I don't quite understand. It seems the following line caused the crash: myEntity.image = newImage where myEntity is of type MyEntity: class MyEntity: NSObject, Identifiable { @objc dynamic var image: NSImage! ... } The code is called on the main thread. According to the crash report, thread 0 makes that assignment, and at the same time thread 16 is calling [NSImageView asynchronousPreparation:prepareResultUsingParameters:]. What could cause such a crash? Could I be doing something wrong or is this a bug in macOS? crash.crash
11
0
202
Aug ’25
Xcode crashes when distributing product for App Store Connect
After building the Product Archive, the Organizer window opens, I click Distribute App. Next. Next. Next. Next. Crash. The crash happens before I'm able to export anything, so I cannot even use the Application Loader. The last message above the indeterminate progress indicator I can read before it crashes is "Packaging MyApp ...". It would be really nice if an Apple engineer could help sort this out, because I already contacted the App Store Connect support and they told me that the only way I can get help is by writing on this forum, searching the Xcode documentation, or using one of the 2 free TSIs I get each year (which I have already used). Stacktrace (I tried to paste the whole crash report, but I get an error that the message is too long and that I should click on the icon to attach a file instead, but I don't see such an icon): Process:&#9;&#9;&#9;&#9;&#9;&#9;&#9; Xcode [834] Path:&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;/Applications/Xcode.app/Contents/MacOS/Xcode Identifier:&#9;&#9;&#9;&#9;&#9;&#9;com.apple.dt.Xcode Version:&#9;&#9;&#9;&#9;&#9;&#9;&#9; 12.2 (17535) Build Info:&#9;&#9;&#9;&#9;&#9;&#9;IDEFrameworks-17535000000000000~23 (12B45b) App Item ID:&#9;&#9;&#9;&#9;&#9; 497799835 App External ID:&#9;&#9;&#9; 838360538 Code Type:&#9;&#9;&#9;&#9;&#9;&#9; X86-64 (Native) Parent Process:&#9;&#9;&#9;&#9;??? [1] Responsible:&#9;&#9;&#9;&#9;&#9; Xcode [834] User ID:&#9;&#9;&#9;&#9;&#9;&#9;&#9; 501 Date/Time:&#9;&#9;&#9;&#9;&#9;&#9; 2020-12-07 17:22:11.231 +0100 OS Version:&#9;&#9;&#9;&#9;&#9;&#9;macOS 11.0.1 (20B29) Report Version:&#9;&#9;&#9;&#9;12 Bridge OS Version:&#9;&#9; 3.0 (14Y908) Anonymous UUID:&#9;&#9;&#9;&#9;7A3F67B1-D68A-4230-40B2-B7EE13B51792 Sleep/Wake UUID:&#9;&#9;&#9; 4913FE52-7DB5-45E0-9396-EFBA2ADD0B5C Time Awake Since Boot: 47000 seconds Time Since Wake:&#9;&#9;&#9; 5900 seconds System Integrity Protection: enabled Crashed Thread:&#9;&#9;&#9;&#9;17&#9;Dispatch queue: ConcurrentQueue: -[IDEDistributionPackagingStepViewController viewDidInstall]_block_invoke Exception Type:&#9;&#9;&#9;&#9;EXC_CRASH (SIGABRT) Exception Codes:&#9;&#9;&#9; 0x0000000000000000, 0x0000000000000000 Exception Note:&#9;&#9;&#9;&#9;EXC_CORPSE_NOTIFY Application Specific Information: Possibly stale failure hints from 2020-12-07 16:21:03 +0000: &#9;0: Calling block provided by: &#9;0&#9; DVTDispatchAsync (in DVTFoundation) &#9;1&#9; __56-[IDEArchiveProductSource updateArchivesWithCompletion:]_block_invoke_2 (in IDEProducts) &#9;2&#9; DVT_CALLING_CLIENT_BLOCK (in DVTFoundation) &#9;3&#9; __DVTDispatchAsync_block_invoke (in DVTFoundation) &#9;4&#9; _dispatch_call_block_and_release (in libdispatch.dylib) &#9;5&#9; _dispatch_client_callout (in libdispatch.dylib) &#9;6&#9; _dispatch_continuation_pop (in libdispatch.dylib) &#9;7&#9; _dispatch_async_redirect_invoke (in libdispatch.dylib) &#9;8&#9; _dispatch_root_queue_drain (in libdispatch.dylib) &#9;9&#9; _dispatch_worker_thread2 (in libdispatch.dylib) 10&#9; _pthread_wqthread (in libsystem_pthread.dylib) 11&#9; start_wqthread (in libsystem_pthread.dylib) ProductBuildVersion: 12B45b ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-17518/DVTFoundation/FilePaths/DVTFilePath.m:912 Details:&#9;url should be an instance inheriting from NSURL, but it is nil Object:&#9; <DVTFilePath> Method:&#9; +filePathForFileURL: Thread:&#9; <NSThread: 0x7fa6c43458e0>{number = 4468, name = (null)} Open FDs: 115/7168 Hints:&#9; &#9;0: Calling block provided by: &#9;0&#9; DVTDispatchAsync (in DVTFoundation) &#9;1&#9; DVTAsyncPerformBlock (in DVTFoundation) &#9;2&#9; -[IDEDistributionPackagingStepViewController viewDidInstall] (in IDEKit) &#9;3&#9; -[DVTViewController _viewDidInstall] (in DVTViewControllerKit) &#9;4&#9; -[_DVTViewController_ViewLifecycleInterpositions viewDidMoveToWindow] (in DVTViewControllerKit) &#9;5&#9; -[NSView _setWindow:] (in AppKit) &#9;6&#9; -[NSView addSubview:] (in AppKit) &#9;7&#9; -[NSView setSubviews:] (in AppKit) &#9;8&#9; -[DVTBorderedView setContentView:] (in DVTUserInterfaceKit) &#9;9&#9; -[IDEDistributionAssistantWindowController setDistributionStepViewController:] (in IDEKit) 10&#9; -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] (in Foundation) 11&#9; -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] (in Foundation) 12&#9; _NSSetObjectValueAndNotify (in Foundation) 13&#9; -[IDEDistributionAssistantWindowController next:] (in IDEKit) 14&#9; __79-[IDEDistributionAutomaticSigningAssetsStepViewController _locateSigningAssets]_block_invoke_2 (in IDEKit) 15&#9; DVT_CALLING_CLIENT_BLOCK (in DVTFoundation) 16&#9; ___DVTAsyncPerformBlockOnMainRunLoop_block_invoke (in DVTFoundation) 17&#9; CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK (in CoreFoundation) 18&#9; __CFRunLoopDoBlocks (in CoreFoundation) 19&#9; __CFRunLoopRun (in CoreFoundation) 20&#9; CFRunLoopRunSpecific (in CoreFoundation) 21&#9; RunCurrentEventLoopInMode (in HIToolbox) 22&#9; ReceiveNextEventCommon (in HIToolbox) 23&#9; _BlockUntilNextEventMatchingListInModeWithFilter (in HIToolbox) 24&#9; _DPSNextEvent (in AppKit) 25&#9; -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] (in AppKit) 26&#9; -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] (in DVTKit) 27&#9; -[NSApplication run] (in AppKit) 28&#9; NSApplicationMain (in AppKit) 29&#9; start (in libdyld.dylib) Backtrace: &#9;0&#9; -[IDEAssertionHandler handleFailureInMethod:object:fileName:lineNumber:assertionSignature:messageFormat:arguments:] (in IDEKit) &#9;1&#9; _DVTAssertionHandler (in DVTFoundation) &#9;2&#9; _DVTAssertionFailureHandler (in DVTFoundation) &#9;3&#9; +[DVTFilePath filePathForFileURL:] (in DVTFoundation) &#9;4&#9; -[IDEDistributionSymbolsStep runWithError:] (in IDEFoundation) &#9;5&#9; -[IDEDistributionProcessingPipeline process:] (in IDEFoundation) &#9;6&#9; -[IDEDistributionPackagingStepViewController _runPipeline] (in IDEKit) &#9;7&#9; __60-[IDEDistributionPackagingStepViewController viewDidInstall]_block_invoke_2 (in IDEKit) &#9;8&#9; DVT_CALLING_CLIENT_BLOCK (in DVTFoundation) &#9;9&#9; __DVTDispatchAsync_block_invoke (in DVTFoundation) 10&#9; _dispatch_call_block_and_release (in libdispatch.dylib) 11&#9; _dispatch_client_callout (in libdispatch.dylib) 12&#9; _dispatch_continuation_pop (in libdispatch.dylib) 13&#9; _dispatch_async_redirect_invoke (in libdispatch.dylib) 14&#9; _dispatch_root_queue_drain (in libdispatch.dylib) 15&#9; _dispatch_worker_thread2 (in libdispatch.dylib) 16&#9; _pthread_wqthread (in libsystem_pthread.dylib) 17&#9; start_wqthread (in libsystem_pthread.dylib) abort() called Application Specific Signatures: (url) != nil ...
10
0
3.4k
Apr ’21
Audit token provided by NEFilterDataProvider sometimes fails to provide code object with SecCodeCopyGuestWithAttributes
I'm using this code to get the path of an executable from the audit token provided in NEFilterDataProvider.handleNewFlow(_:), forwarded from the Network Extension to the main app via IPC: private func securePathFromAuditToken(_ auditToken: Data) throws -> String { let secFlags = SecCSFlags() var secCode: SecCode? var status = SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributeAudit: auditToken] as CFDictionary, secFlags, &secCode) guard let secCode = secCode else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } var secStaticCode: SecStaticCode? status = SecCodeCopyStaticCode(secCode, secFlags, &secStaticCode) guard let secStaticCode = secStaticCode else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } var url: CFURL? status = SecCodeCopyPath(secStaticCode, secFlags, &url) guard let url = url as URL? else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } return url.path } This code sometimes returns paths like /System/Library/PrivateFrameworks/HelpData.framework/Versions/A/Resources/helpd or /Library/Developer/CoreSimulator/Volumes/iOS_21A328/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime/Contents/Resources/RuntimeRoot/usr/libexec/mobileassetd. But sometimes the SecCodeCopyGuestWithAttributes fails with status 100001 which is defined in MacErrors.h as kPOSIXErrorEPERM = 100001, /* Operation not permitted */. In these cases I resort to this code, which I have read is not as secure: private func insecurePathFromAuditToken(_ auditToken: Data) throws -> String? { if auditToken.count == MemoryLayout<audit_token_t>.size { let pid = auditToken.withUnsafeBytes { buffer in audit_token_to_pid(buffer.baseAddress!.assumingMemoryBound(to: audit_token_t.self).pointee) } let pathbuf = UnsafeMutablePointer<Int8>.allocate(capacity: Int(PROC_PIDPATHINFO_SIZE)) defer { pathbuf.deallocate() } let ret = proc_pidpath(pid, pathbuf, UInt32(PROC_PIDPATHINFO_SIZE)) if ret <= 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } return String(cString: pathbuf) } return nil } This insecure code then returns paths like /usr/libexec/trustd, /usr/libexec/rapportd, /usr/libexec/nsurlsessiond and /usr/libexec/timed. From what I can see, SecCodeCopyGuestWithAttributes fails for all processes in /usr/libexec. Some of these processes have executables with the same name placed in another directory, like /Library/Developer/CoreSimulator/Volumes/iOS_21A328/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.0.simruntime/Contents/Resources/RuntimeRoot/usr/libexec/mobileassetd for which it succeeds, while for /usr/libexec/mobileassetd it fails. Occasionally, both the secure and the insecure methods fail and in these cases the secure one returns status code 100003, which is defined as kPOSIXErrorESRCH = 100003, /* No such process */. When can this happen? This seems to happen with both NEFilterFlow.sourceAppAuditToken and sourceProcessAuditToken. What is the problem?
10
0
1.4k
Oct ’23
App Intent title and other localized strings not showing correctly in Shortcuts app on macOS 15
I rarely use the Shortcuts app, so it took me a while to notice that my app's app intents all show incorrectly on macOS 15. On macOS 14 and 13, they used to show correctly, but now it seems that all localized strings show the key rather than the localized value. @available(iOS 16.0, macOS 13.0, *) struct MyAppIntent: AppIntent { static let title = LocalizedStringResource("key1", comment: "") static let description = IntentDescription(LocalizedStringResource("key2", comment: "")) ... } In Localizable.xcstrings file I have defined all the strings, for instance I have associated key1 with the value Title, but while the Shortcuts app used to display Title, it now displays key1. Is this a known issue or did something change in macOS 15 that would require me to update something?
10
0
1.2k
Feb ’25