Processes & Concurrency

RSS for tag

Discover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.

Concurrency Documentation

Post

Replies

Boosts

Views

Activity

SIGABRT Signal 6 Abort trap
I got crash report for my mobile application private var _timedEvents: SynchronizedBarrier<[String: TimeInterval]> private var timedEvents: [String: TimeInterval] { get { _timedEvents.value } set { _timedEvents.value { $0 = newValue } } } func time(event: String) { let startTime = Date.now.timeIntervalSince1970 trackingQueue.async { [weak self, startTime, event] in guard let self else { return } var timedEvents = self.timedEvents timedEvents[event] = startTime self.timedEvents = timedEvents } } From the report, the crash is happening at _timedEvents.value { $0 = newValue } struct ReadWriteLock { private let concurentQueue: DispatchQueue init(label: String, qos: DispatchQoS = .utility) { let queue = DispatchQueue(label: label, qos: qos, attributes: .concurrent) self.init(queue: queue) } init(queue: DispatchQueue) { self.concurentQueue = queue } func read<T>(closure: () -> T) -> T { concurentQueue.sync { closure() } } func write<T>(closure: () throws -> T) rethrows -> T { try concurentQueue.sync(flags: .barrier) { try closure() } } } struct SynchronizedBarrier<Value> { private let lock: ReadWriteLock private var _value: Value init(_ value: Value, lock: ReadWriteLock = ReadWriteLock(queue: DispatchQueue(label: "com.example.SynchronizedBarrier", attributes: .concurrent))) { self.lock = lock self._value = value } var value: Value { lock.read { _value } } mutating func value<T>(execute task: (inout Value) throws -> T) rethrows -> T { try lock.write { try task(&_value) } } } What could be the reason for the crash? I have attached the crash report. Masked.crash
4
0
116
4d
Crash objc_retain_x0
Attaching several crash traces: 2024-02-29_22-48-33.6864_-0600-3f948243e21b4c68d77a38d9cf1cecfdfe2c1565.crash 2024-03-04_15-00-02.9335_-0600-75000cd5acd63ba1434f2ffb3648b97259dddb88.crash 2024-03-05_08-55-47.2097_-0500-f682b25663107ad46f091d65f402f2be31f3f3c6.crash 2024-03-11_08-09-00.4057_-0400-e37d1a635d51afbb67ac38b42dd79c1718a408e8.crash 2024-03-15_16-20-22.6446_-0600-d4ebccf455e8305038ca564a39a5661a1dce6231.crash The final code: - (NSObject*)objectAtIndex:(NSUInteger)index { if (index < self.count) { return [self.embeddedArray objectAtIndex:index]; } else { [PNDErrorReporting reportError:PNDErrorReasonTypeSafeCollectionCrashPrevented message:@"Error msg"]; return nil; } } We subclass NSMutableArray to prevent potential crashes. but we encounter a new crash in our sdk for one of the clients. Also we noticed the stack trace skipped one of the frames (stack calls) in the crash report, in which cases the stack trace wont be identical to the actual code (beside inline)?
8
0
123
6d
Crashes after exceeding limit of 150 wakeups per second over 300 seconds
my macOS process is crashing when i keep my mac sleep for about 1 hour. Under Crash Reports, Console app shows two type of file. .diag type .ips type ips file doesn't shows exact line of crash as you can see below sample. Thread 67 Crashed: 0 libsystem_kernel.dylib 0x19a4aea60 __pthread_kill + 8 1 libsystem_pthread.dylib 0x19a4e6c20 pthread_kill + 288 2 libsystem_c.dylib 0x19a3f3a30 abort + 180 3 libsystem_malloc.dylib 0x19a303dc4 malloc_vreport + 896 4 libsystem_malloc.dylib 0x19a307430 malloc_report + 64 5 libsystem_malloc.dylib 0x19a321494 find_zone_and_free + 528 6 Firewall.so 0x103c8a744 TunnelSendQueue::ResumeSend() + 460 resource.diag file sgowing warning about exceeding limit of 150 wakeups per second over 300 seconds. attached here. reasource_consumptions_W36RNW09G.wakeups_resource_diag.txt is this something macOS stopping app because of some resource consumptions?
2
0
168
1w
How do you allow an XPC service to create a new file based on an NSURL that the user selected from an NSSavePanel?
How do you send an NSURL representing a new file, as returned from an NSSavePanel, to an XPC service such that the service is granted permission to create the file? I can successfully pass an NSURL to the XPC process if the NSURL represents an existing file. This is documented in Apple's Documentation: Share file access between processes with URL bookmarks This involves creating bookmark date while passing 0 in as the options. However, if you try to create bookmark data for an NSURL that represents a file that is not yet created, you do not get any bookmark data back and an error is returned instead: Error Domain=NSCocoaErrorDomain Code=260 "The file couldn’t be opened because it doesn’t exist." Simply passing the file path to the XPC process, by way of: xpc_dictionary_set_string(message, "file_path", url.fileSystemRepresentation); Does not grant the XPC create/write permissions. Is there an API or trick I'm missing? Note that the user should be allowed to save and create new files anywhere of their choosing, thus restricting URLs to only those within a group or container shared between the app and service isn't really viable. Using the latest of everything on macOS with the xpc_session API...
1
0
144
1w
Best Practice for Scheduling EASession Input and Output Streams
My company builds an application using the External Accessory framework to communicate with our hardware. We have followed the documentation and example here and use the stream delegate pattern for scheduling the handling of the EASession's InputStream and OutputStream: https://developer.apple.com/library/archive/featuredarticles/ExternalAccessoryPT/Articles/Connecting.html Our application works, however we have had some issues that cause us to doubt our implementation of the Stream handling for our EASession. All the examples I can find for how to set up this RunLoop based implementation for managing and using the streams associated with the EASession seem to use RunLoop.current to schedule the InputStream and OutputStream. What is not clear to me is what thread the processing of these streams is actually getting scheduled upon. We have occasionally observed our app "freezing" when our connected accessory disconnects, which makes me worry that we have our Stream processing on the main thread of the application. We want these streams to be processed on a background thread and never cause problems locking up our main thread or UI. How exactly do we achieve this? If we are indeed supposed to only use RunLoop.current, how can we make sure we're opening the EASession and scheduling its streams on a non-main thread? On what thread will we receive EAAccessoryDidConnect and EAAccessoryDidDisconnect notifications? Is it safe to schedule streams using RunLoop.current from that thread? What about when the app returns from the background, how are we meant to reconnect to an accessory that the iOS device is already connected to? Hopefully someone here can help guide us and shed some light on how to achieve our desired behavior here.
12
0
227
2w
NSarray crashes with different exceptions from the same place
It seems that that all the crashes are coming from the same place BUT the error is slightly different. Attaching the code that responsible for the crash: static NSString * const kDelimiter = @"#$@"; + (PNDArray *)getObjectsFromData:(NSData *)data { NSString *dataStr = [[NSString alloc] initWithData:data encoding:encoding]; dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\\u0000" withString:@""]; NSArray *components = [dataStr componentsSeparatedByString:kDelimiter]; NSMutableArray *result = [NSMutableArray array]; for (NSString *jsonStr in components) { if (jsonStr != nil && jsonStr.length != 0 && ![jsonStr hasPrefix:kBatchUUID]) { [result addObject:jsonStr]; } } return [PNDArray arrayWithArray:result]; } 2024-04-16_17-15-34.1922_-0600-dfa2faecf702f23e3f6558bea986de4f62851761.crash 2024-04-24_04-56-53.4664_-0500-6b125d3d03b7e497b6be339c2abb52f29658824b.crash 2024-04-25_11-13-53.1326_-0700-bfe370be3eae8d65f465eac714905dd3d13aa665.crash 2024-05-03_11-47-36.6085_-0500-2793587e7ed1c02b0e4334bbc3aa0bd7f7a0cf3d.crash 2024-05-05_10-49-40.5969_-0700-4d86636b0877fceb8c0cdb9586ee16dfb0a9c934.crash
15
0
326
2w
identify app modifying screen share
MacBook Pro M1 with an external monitor. For years, the external as Main and the built-in monitor was Extended. After 14.5 update, when a specific user logs on, the built-in monitor "disappears" from Displays and the two monitors show the same desktop. That is as if the external monitor is the only one. If the monitor cable is unplugged, the MacBook boots normally. Plugging in the external monitor following normal boot results in the external becoming Main and built-in Extended. I suspect some launch item install with an app is affecting the display config. I first removed zoom, but no change. There are about 110 apps installed on this machine. How to determine which module or app is doing this? That is, is there a tool or log setting that would note a change in the display settings? I would like to narrow the likely candidates.
0
0
125
2w
Can helper application launch XPCService that embedded in its bundle?
Hi, I have an application, it has a helper application in its bundle. After the application starts to run, it will launch the helper application process. The helper application process will load a XPCService embedded in its bundle by launchd. But I got an error which is Error Domain=NSOSStatusErrorDomain Code=-10811 "kLSNotAnApplicationErr: Item needs to be an application, but is not" UserInfo={_LSLine=175, _LSFunction=_LSFindBundleWithInfo_NoIOFiltered} How can the helper application launch a XPCService embedded in its bundle? Or the XPCService can only be launched in main application? Thanks
3
0
162
2w
Non-sendable type ModelContext on MainActor
Hi, just trying to learn how to work with mainActor. I am in a need of analyzing users data with API service one a background. Whenever user saves a post into SwiftData, I need to analyze that posts asynchronously. Here is my current code, which by the way works, but I am getting warning here; actor DatabaseInteractor { let networkInteractor: any NetworkInteractor = NetworkInteractorImpl() func loadUserProfile() async -&gt; String { do { let objects = try await modelContainer.mainContext.fetch(FetchDescriptor&lt;ProfileSwiftData&gt;()) if let profileTest = objects.first?.profile { return profileTest } } catch { } return "" } I get a warning on let objects line. Warning: Non-sendable type 'ModelContext' in implicitly asynchronous access to main actor-isolated property 'mainContext' cannot cross actor boundary
1
0
425
Apr ’24
Callback is not invoked when a closure callback-style call is executed in XPC
I noticed a problem while writing a program using XPC on macOS. When I write it in the form of a closure that receives the result of an XPC call, I can't receive it forever. I add an XPC target in Xcode, the sample code is used in the pass closure format, but can't I use closure passing with XPC? My Environment: Xcode 15.3 macOS 14.4.1 caller (closure version) struct ContentView: View { @State var callbackResult: String = "Waiting…" var body: some View { Form { Section("Run XPC Call with no argument and no return value using callback") { Button("Run…") { callbackResult = "Running…" let service = NSXPCConnection(serviceName: "net.mtgto.example-nsxpc-throws-error.ExampleXpc") service.remoteObjectInterface = NSXPCInterface(with: ExampleXpcProtocol.self) service.activate() guard let proxy = service.remoteObjectProxy as? any ExampleXpcProtocol else { return } defer { service.invalidate() } proxy.performCallback { callbackResult = "Done" } } Text(callbackResult) ... } } } callee (closure version) @objc protocol ExampleXpcProtocol { func performCallback(with reply: @escaping () -> Void) } class ExampleXpc: NSObject, ExampleXpcProtocol { @objc func performCallback(with reply: @escaping () -> Void) { reply() } } I found this problem can be solved by receiving asynchronous using Swift Concurrency. caller (async version) struct ContentView: View { @State var callbackResult: String = "Waiting…" var body: some View { Form { Section("Run XPC Call with no argument and no return value using callback") { Button("Run…") { simpleAsyncResult = "Running…" Task { let service = NSXPCConnection(serviceName: "net.mtgto.example-nsxpc-throws-error.ExampleXpc") service.remoteObjectInterface = NSXPCInterface(with: ExampleXpcProtocol.self) service.activate() guard let proxy = service.remoteObjectProxy as? any ExampleXpcProtocol else { return } defer { service.invalidate() } await proxy.performNothingAsync() simpleAsyncResult = "DONE" } Text(simpleAsyncResult) ... } } } callee (async version) @objc protocol ExampleXpcProtocol { func performNothingAsync() async } class ExampleXpc: NSObject, ExampleXpcProtocol { @objc func performNothingAsync() async {} } To simplify matters, I write source code that omits the arguments and return value, but it is not also invoked by using callback style. All sample codes are available in https://github.com/mtgto/example-nsxpc-throws-error
2
0
308
Apr ’24
Error 159 - Sandbox restriction when connecting to XPC service
Hello Apple Developer Community, I'm encountering an issue with my macOS application where I'm receiving the following error message: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.FxPlugTestXPC was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.FxPlugTestXPC was invalidated: failed at lookup with error 159 - Sandbox restriction.} This error occurs when my application tries to establish a connection to an XPC service named com.FxPlugTestXPC. It appears to be related to a sandbox restriction, but I'm unsure how to resolve it. I've checked the sandboxing entitlements and ensured that the necessary permissions are in place. However, the issue persists. Has anyone encountered a similar error before? If so, could you please provide guidance on how to troubleshoot and resolve this issue? Any help or insights would be greatly appreciated. Thank you. this is some photos about my entitlements :
16
0
1.1k
Apr ’24
What is the difference between OSAllocatedUnfairLock's withLock and withLockUnchecked functions?
OSAllocatedUnfairLock has two different methods for executing a block of code with the lock held: withLock() and withLockUnchecked(). The only difference between the two is that the former has the closure and return type marked as Sendable. withLockUnchecked() has a comment (that is for reasons I do not understand not visible in the documentation) saying: /// This method does not enforce sendability requirement /// on closure body and its return type. /// The caller of this method is responsible for ensuring references /// to non-sendables from closure uphold the Sendability contract. What I do not understand here is why Sendable conformance would be needed. These function should call this block synchronously in the same context, and return the return value through a normal function return. None of this should require the types to be Sendable. This seems to be supported by this paragraph of the documentation for OSAllocatedUnfairLock: /// This lock must be unlocked from the same thread that locked it. As such, it /// is unsafe to use `lock()` / `unlock()` across an `await` suspension point. /// Instead, use `withLock` to enforce that the lock is only held within /// a synchronous scope. So, why does this Sendable requirement exist, and in practice, if I did want to use withLockUnchecked, how would I "uphold the Sendability contract"? To summarise the question in a more concise way: Is there an example where using withLockUnchecked() would actually cause a problem, and using withLock() instead would catch that problem?
7
0
436
Apr ’24
Unsandboxed XPCService launches sandboxed child processes
I have an application, it has main process and some child processes. As we want those child processes to have their own minimum sandbox privilege, not inheriting from parent process, we plan to use XPCService which uses a NSTask to launch those child processes, so those child processes can have its own sandbox privilege. We plan to deliver the application to Mac App Store, so process mode is: the sandboxed main process builds connections to the unsandboxed XPCService, the unsandboxed XPCService launch those sandboxed child processes. Can this process mode pass the Mac App Store rules? I see, there is a rule that all processes must be sandboxed, including XPCService. But I tested locally, the Application downloaded from Mac apple store also launches unsandboxed XPCService, like OneDrive. Do you have any suggestions for my application scenario, sandboxed child processes having its own privilege not inheriting from parent?
2
0
361
Apr ’24
Are XPCSession and XPCListener incomplete(ly documented)?
I've been experimenting with the new low-level Swift API for XPC (XPCSession and XPCListener). The ability to send and receive Codable messages is an appealing alternative to making an @objc protocol in order to use NSXPCConnection from Swift — I can easily create an enum type whose cases map onto the protocol's methods. But our current XPC code validates the incoming connection using techniques similar to those described in Quinn's "Apple Recommended" response to the "Validating Signature Of XPC Process" thread. I haven't been able to determine how to do this with XPCListener; neither the documentation nor the Swift interface have yielded any insight. The Creating XPC Services article suggests using Xcode's XPC Service template, which contains this code: let listener = try XPCListener(service: serviceName) { request in request.accept { message in performCalculation(with: message) } } The apparent intent is to inspect the incoming request and decide whether to accept it or reject it, but there aren't any properties on IncomingSessionRequest that would allow the service to make that decision. Ideally, there would be a way to evaluate a code signing requirement, or at least obtain the audit token of the requesting process. (I did notice that a function xpc_listener_set_peer_code_signing_requirement was added in macOS 14.4, but it takes an xpc_listener_t argument and I can't tell whether XPCListener is bridged to that type.) Am I missing something obvious, or is there a gap in the functionality of XPCListener and IncomingSessionRequest?
2
0
336
Apr ’24
Compile XPC service with a different architecture than the client
I'm working on a macOS application that deals with a few external dependencies that can only be compiled for intel (x86_64) but I want the app to run natively on both arm and x86_64. One idea I have been playing with is to move the x86_64 dependencies to an xpc service compiled only as x86_64 and use the service only the intel machine. However, I can't figure out how to setup my project to compile everything at once... Any ideas? Is this even possible? If not, I'm open to suggestions... Thanks
2
0
314
Mar ’24