XPC is a a low-level (libSystem) interprocess communication mechanism that is based on serialized property lists.

Posts under XPC tag

200 Posts

Post

Replies

Boosts

Views

Activity

XPC to communicate Swift with C++
Hello! I'm new here, and probably this will sound weird but, I'm trying to write a C++ program using an XPC service to attempt to communicate with a macOS app I'm developing in Swift. At the macOS app side I think I'm successfully registering and connecting to the service, as launchd reports the following in its log: 2023-05-31 17:20:21.898621 (pid/15637 [On Air]) <Notice>: Service stub created for com.ruieduardolopes.onaird-join At the C++ side I'm trying to get a simple example working, as follows, but currently without any success... #include <xpc/xpc.h> int main(int argc, const char* argv[]) { xpc_connection_t conn = xpc_connection_create_mach_service("com.ruieduardolopes.onaird.join", NULL, 0); xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); xpc_connection_set_event_handler(conn, ^(xpc_object_t object) {}); xpc_connection_resume(conn); xpc_dictionary_set_string(message, "SS", "AAAAAA\n"); xpc_connection_send_message_with_reply(conn, message, dispatch_get_main_queue(), ^(xpc_object_t object) {}); return (EXIT_SUCCESS); } I get the following error in the logs: 2023-05-31 17:27:45.636894 (system/com.ruieduardolopes.onaird) <Notice>: internal event: WILL_SPAWN, code = 0 2023-05-31 17:27:45.636903 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawn scheduled 2023-05-31 17:27:45.636904 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawning 2023-05-31 17:27:45.637017 (system/com.ruieduardolopes.onaird) <Notice>: launching: ipc (mach) 2023-05-31 17:27:45.637256 (system/com.ruieduardolopes.onaird [15908]) <Notice>: xpcproxy spawned with pid 15908 2023-05-31 17:27:45.637264 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: SPAWNED, code = 0 2023-05-31 17:27:45.637265 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: xpcproxy 2023-05-31 17:27:45.637269 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: SOURCE_ATTACH, code = 0 2023-05-31 17:27:45.648927 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: running 2023-05-31 17:27:45.648940 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: INIT, code = 0 2023-05-31 17:27:45.648948 (system/com.ruieduardolopes.onaird [15908]) <Notice>: Successfully spawned onaird-join[15908] because ipc (mach) 2023-05-31 17:27:45.687251 (system/com.ruieduardolopes.onaird [15908]) <Notice>: exited due to SIGTRAP | sent by exc handler[15908] 2023-05-31 17:27:45.687261 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service has crashed 1 times in a row 2023-05-31 17:27:45.687263 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: exited 2023-05-31 17:27:45.687267 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: EXITED, code = 0 2023-05-31 17:27:45.687269 (system) <Notice>: service inactive: com.ruieduardolopes.onaird 2023-05-31 17:27:45.687281 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: not running 2023-05-31 17:27:45.687290 (system/com.ruieduardolopes.onaird) <Notice>: Service only ran for 0 seconds. Pushing respawn out by 10 seconds. 2023-05-31 17:27:45.687339 (system/com.ruieduardolopes.onaird) <Notice>: internal event: WILL_SPAWN, code = 0 2023-05-31 17:27:45.687343 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawn scheduled 2023-05-31 17:27:45.687344 (system/com.ruieduardolopes.onaird) <Notice>: service throttled by 10 seconds The plist file I'm currently loading to /Library/LaunchDaemons is as follows: <?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.ruieduardolopes.onaird</string> <key>Program</key> <string>PATH_TO_ONAIR_JOIN_XPC_SERVICE_BINARY</string> <key>BuildMachineOSBuild</key> <string>22C65</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>onaird-join</string> <key>CFBundleExecutable</key> <string>onaird-join</string> <key>CFBundleIdentifier</key> <string>com.ruieduardolopes.onaird-join</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>onaird-join</string> <key>CFBundlePackageType</key> <string>XPC!</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string></string> <key>DTPlatformName</key> <string>macosx</string> <key>DTPlatformVersion</key> <string>13.3</string> <key>DTSDKBuild</key> <string>22E245</string> <key>DTSDKName</key> <string>macosx13.3</string> <key>DTXcode</key> <string>1430</string> <key>DTXcodeBuild</key> <string>14E222b</string> <key>LSMinimumSystemVersion</key> <string>13.1</string> <key>MachServices</key> <dict> <key>com.ruieduardolopes.onaird.join</key> <true/> </dict> <key>XPCService</key> <dict> <key>ServiceType</key> <string>Application</string> </dict> </dict> </plist> Can anybody help me? Thanks in advance, Rui
5
0
1.5k
Jun ’23
0xdead10cc prevention
Hello,Technical Note TN2151 describes the 0xdead10cc exception:&gt; The exception code 0xdead10cc indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension. If your application is performing operations on a locked file or sqlite database at suspension time, it must request additional background execution time to complete those operations and relinquish the lock before suspending.This is all pretty clear. After the additional background execution time has expired, all SQLite accesses that create a lock create a risk for sudden termination. An application which wants to avoid 0xdead10cc has thus to actively prevent such accesses... until the application wakes up from the suspended state. My questions are all about the end of this critical lapse of time in the app's life cycle.Eventually, the application may become active, and this clearly marks the end of the 0xdead10cc danger. This moment is notified by UIApplicationWillEnterForegroundNotification. After this notification is posted, it becomes possible again to access an SQLite database without risking any 0xdead10cc exception, until the next UIApplicationDidEnterBackgroundNotification, and the next notification of additional background execution time expiration.But what about cases when the application leaves the suspended state and reenters the background state? This may happen due to the various background modes supported by iOS.First question: Is there one way to be notified of this transition from suspended to background state, regardless of the reason for this background wake-up (core location, VoIP, background fetch, etc.) ?Second question: Is it then possible to start another request for additional background execution time and be reliably notified when accessing the SQLite database creates a 0xdead10cc threat again?Third question: do you have any other advice regarding 0xdead10cc prevention?For the context, I'm the author of GRDB, and I'm looking for a way to package 0xdead10cc prevention in a way that reduces to a minimum the amount of code users have to write in order to protect their app from this exception. Ideally, it would be reduced to a simple boolean flag targetted at users who store their database in an App Group container.Thank you very much!
9
2
8.5k
May ’23
NSXPCConnection fails to transport IOSurfaceRef
I'm trying to send an IOSurfaceRef across an NSXPCConnection on osx 10.13 and I'm having trouble with the solution that was provided in the forum thread "Efficiently sending data from an XPC process to the host application." https://developer.apple.com/forums/thread/126716 From that thread: > However, that specific problem got resolved on 10.12 where we introduced a new Objective-C IOSurface object, and that object is transportable directly over NSXPCConnection . So double yay! But it doesn’t seem to work. I have a very simple service protocol that includes (void)sendFrame:(IOSurfaceRef)frame; along with some basic NSString sending methods that successfully transfer across my NSXPCConnection. I have a valid (non-NULL) IOSurface in my app that I send to my helper app with sendFrame, and when the call is executed in the helper, the resulting frame is always NULL. On the other hand, I’ve also tried creating an IOSurface with the (deprecated) kIOSurfaceIsGlobal property and sending the IOSurface’s ID instead with: (void)sendFrameID:(uint32_t)frameID; and [_service sendFrameID:IOSurfaceGetID(surface)]; And on the helper app side, I look up the IO to get an IOSurfaceRef: IOSurfaceRef frame = IOSurfaceLookup(frameID); and it works correctly – I get a valid IOSurface which I can display and see the same pixel contents in both the app and the helper. So what is meant by the new IOSurface object in 10.12 is “transportable directly” over NSXPCConnection? How is it supposed to work? I’m specifically interested in no-copy transfer. Thanks!
4
0
3.0k
Apr ’23
XPC working fine for system extension but not for app extension
Hello, I'm working on an app that offers a VPN tunnel (NEPacketTunnelProvider) meant to be released both in Developer ID builds and App Store builds. I've implemented an IPC mechanism using IPCConnection from the filtering network traffic example code. For the system extension it works fine. For the app extension, I just can't connect to the mach service. In both cases the app is not sandboxed, but the extension is. I'm trying to figure out how to troubleshoot the issue. The plist file for the system extension has this key: <key>NetworkExtension</key> <dict> <key>NEMachServiceName</key> <string>$(TeamIdentifierPrefix)com.company.system.extension.bundle.id</string> <key>NEProviderClasses</key> <dict> <key>com.apple.networkextension.packet-tunnel</key> <string>$(PRODUCT_MODULE_NAME).PacketTunnelProvider</string> </dict> </dict> Would the app network extension use the same NetworkExtension dictionary with a NEMachServiceName key for the mach service name? Any hints to help me debug this issue? I've tried using launchctl list to see if the mach service is up, but I'm not exactly sure what's a good way to use it. I've considered using sendProviderMessage to communicate with the tunnel from the main App, but the problem is that sometimes NEVPNManager.shared.connection as? NETunnelProviderSession is just nil (due to the cast), and I'm not sure why that's the case.
3
0
2k
Apr ’23
No error handler for XPC error: Connection invalid
I am on Ventura 13.3.1 with the M2 and I was trying to set up a Linux VM, following the steps on your website, but after I chose the ISO the following Error in Xcode appeared: GUILinuxVirtualMachineSampleApp[5863:111794] [client] No error handler for XPC error: Connection invalid . There was already a question about the No error handler on this forum, but that still didn't help me fix my Problem. So now my question is how do I fix it, because I have almost no good idea where to start. I can give more informations if needed. Big thanks and regards in advance :). Sincerely, Bieber
1
0
1.7k
Apr ’23
XPC Errors when launching in simulator
I cannot debug any applications anymore since upgrading to latest Ventura (13.3) and XCode 14.3. First - None of the iOS 16.X simulators work AT ALL. When I choose an iOS 16 target simulator, the simulator window comes up but is completely blank and never starts. Pressing HOME button, resetting device data, restarting device do not fix the issue. I've deleted and re-installed the simulators multiple times and nothing works. Error detail when trying to launch 16.4 simulator: Domain: FBSOpenApplicationServiceErrorDomain Code: 5 Failure Reason: Unexpected error type. User Info: { BSErrorCodeDescription = InvalidResponse; DVTErrorCreationDateKey = "2023-04-04 03:47:36 +0000"; IDERunOperationFailingWorker = IDELaunchiPhoneSimulatorLauncher; SimCallingSelector = "launchApplicationWithID:options:pid:error:"; } -- The request to open "XXX.XXX.XXXXXX" failed. Domain: FBSOpenApplicationServiceErrorDomain Code: 5 Failure Reason: Unexpected error type. User Info: { BSErrorCodeDescription = InvalidResponse; } -- The operation couldn’t be completed. XPC error received on message reply handler Domain: BSServiceConnectionErrorDomain Code: 3 Failure Reason: XPC error received on message reply handler User Info: { BSErrorCodeDescription = OperationFailed; } -- Second - I can use iOS 15.2 simulators, but cannot attach debugger to them. XCode will launch my app but will not actually let me debug it or attach a debugger to it after launch. Error detail when launching 15.2 debuggable simulator: Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.) User Info: { DVTErrorCreationDateKey = "2023-04-04 03:41:19 +0000"; DVTRadarComponentKey = 855031; IDERunOperationFailingWorker = DBGLLDBLauncher; RawUnderlyingErrorMessage = "attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.)"; } I see no errors in any of the console or system logs that would indicate what the problem could be. I have deleted the DerivedData, wiped the cache clean from the Storage Settings section in the settings.app. XCode seems to get worse with every minor update, at this point I cannot debug my apps anymore and have found no solutions.
3
1
4.5k
Apr ’23
PHAssetCollection.requestAuthorization(for:handler:) gives .denied on ExtensionKit
I am making macOS app with ExtensionKit. When I call PHAssetCollection.requestAuthorization(for:handler:) on my extension, it always gives .denied without any prompts. I've added com.apple.security.personal-information.photos-library key into entitlements and NSPhotoLibraryUsageDescription key into Info.plist but has no effects. Also Security Policy of my MacBook is Reduced Security and my host app gets .authorized status but extension gives .denined. Does PhotoKit support ExtensionKit? Any ideas? void (^requestAuthorization)(void (^completion)(NSError * _Nullable)) = ^(void (^completion)(NSError * _Nullable)) { [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) { switch (status) { case PHAuthorizationStatusNotDetermined: requestAuthorization(completion); break; case PHAuthorizationStatusAuthorized: completion(nil); break; default: { NSLog(@"%lu", status); // gives 2, PHAuthorizationStatusDenied NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadNoPermissionError userInfo:nil]; completion(error); break; } } }]; };
0
0
797
Mar ’23
"[SDKPlayback] applicationController: xpc service connection interrupted" for MPMusicPlayerController.applicationMusicPlayer iOS 16.3.1
Hi! I'm having a problem that I cannot seem to figure out. I have not made any changes to my app, yet this suddenly started happening. I think it started happening after I upgraded my phone to iOS 16.3.1, but I am not entirely sure. Pseudocode: // (1) initialise player let player = MPMusicPlayerController.applicationMusicPlayer // (2) ..later, a button is pressed and we call play() player.play(myAlbumId) // (3) a background timer runs, which will ensure we are playing for 30 seconds, and pausing for 60 seconds (this is a workout app): self.timer = Timer(timeInterval: 1.0, target: self, selector: #selector(togglePauseIfNeeded), userInfo: nil, repeats: true) RunLoop.current.add(self.timer!, forMode: .common) // (4) Now, the problem occurs when the timer triggers play, the second time we are playing music (ie, it works the initial time, but in that case, play was triggered by a button press (step 2)). // So when the timer now calls player.play(), we see this error: "[SDKPlayback] applicationController: xpc service connection interrupted" player.play() Interestingly, if I manually hit play just a few seconds before the timer would have called "play" (at step 4), it works fine. Any thoughts or help on this would be highly appreciated! <3
0
0
786
Mar ’23
XPC connection invalidated when Background Processing task performs a network request
Hello, I'm developing an iOS app which has an ability to upload user photos, and I'm using a Background processing task to perform such an operation. The app also has File provider extension, which is involved in the process Whenever the background task is launched, the following actions are performed: Main app fetches new items from PHAsset library and copies them to our file storage File Provider extension uploads those items to a cloud storage Everything goes fine until Extension tries to perform a network request, at this point I'm getting the following error: (501) got error from remote proxy: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction.} App has all the required entitlements and extension and main app has also the same app group. What is wrong with this that causes this error?
0
1
1.7k
Feb ’23
xpc api misuse crash
To begin with: I know it's my code, because if I go back to our main branch and try it, I don't get this crash. But I can't figure out what it's unhappy about, so I'm not sure what changes I have to look for. (Also, this is macOS.) The daemon tries to communicate with a Network Extension over XPC. I have a class, with a shared instance, and I have a cached NSXPCConnection connection instance variable. So my code is something like id connection = [[ExtensionCommunication shared] connection], which is created by [[NSXPCConnection alloc] initWithMachServiceName:self.redirectorMachServiceName options:0]. With my changes (whatever they are), when it does [_connection resume], it crashes:   * frame #0: 0x00007ff8191ab20e libxpc.dylib`_xpc_api_misuse + 117     frame #1: 0x00007ff8191963a1 libxpc.dylib`xpc_connection_resume + 54 This happens whether the network extension is activated or not. The crash happens the second time this is called. (Hm, one thing I need to figure out then is why my cached connection object is being set to nil. It shouldn't be. hm.) Anyway! Any suggestions on how I can try to debug this?
2
0
1.5k
Feb ’23
Thread 1: signal SIGTERM error
Hello! I am using macOS Catalina, Xcode 11. I just started working on app development and this is my first project. Every time i try to simulate the code the program crashes and it gives me thread 1 signal SIGTERM error. My code is very simple, I don't think i have an error there. I am really stuck, I tried to run different projects but it doesn’t work on any of them. Please, can someone help me fix this error? Thanks in advance!
6
0
14k
Jan ’23
Stop LaunchAgent from restarting.
I have a Mac OS remote application that is made out of three parts. 1.- A LaunchDaemon that handles all of my network code and connects to my client 2.- A LaunchAgent to provides access to the window server to capture monitors, events, etc. 3.- A NSApplication to allow the user to control the LaunchDaemon I'm trying to get the LaunchAgent and LaunchDaemon to run only while my NSApp is running. LaunchDaemon - it uses machServices so I "control" it by starting an xpcConnection from my NSApplication. LaunchAgent - it uses QueueDirectories and I start it by having my NSApplication save a file to the QueueDirectories path. My NSApp and LaunchAgent both communicate with the LaunchDaemon via XPCConnection. Everything works as expected until I try quit my NSApp, LaunchDaemon and LaunchAgent. This is how I do it. User quits NSApp -> NSApp removes QueueDirectory file, sends a quit message to Daemon and it gets terminated -> Daemon sends a message to Agent then it terminates with exit(0) -> Agent receives the message and it terminates with exit(0) as well. Agent gets terminated and immediately launches again creating demand for my Daemon and starting it again. When I run launchctl blame on my Agent I get xpc event. which means that the xpc connection with my daemon is still creating demand somehow even after calling .invalidate() and deallocating the connection object.? Is there a specific way to terminated an XPCConnection? this is how I create my XPCConnectionListener: NSXPCListener(machServiceName: "myMachServiceName") and my connections let connection = NSXPCConnection("myMachServiceName", options: [.privileged]) connection.remoteObjectInterface = NSXPCInterface(with: myProtocol.self) connection.exportedInterface = NSXPCInterface(with: myProtocol.self) connection.exportedObject = exportedObject connection.interruptionHandler = interruptionHandler connection.invalidationHandler = invalidationHandler return connection So it seems that the issue is that my connections aren't fully terminated when I quit the processes? any pointers would be greatly appreciated.
2
0
1.5k
Jan ’23
dlclose will not unload library when using macOS Frameworks
Hello,I am encountering an unsual problem when linking a library to macOS Frameworks: as soon as I'm linking to some specific frameworks (detailed below), dlclose will no longer work, meaning that the said library will not be unloaded from process memory.This is causing problems, because the update functionality of my application will not work - calling dlopen again will load the "old" library.The build details are:macOS High Sierra (10.13.6)Xcode 9.4.1 C++ Language Dialect: C++14 [-std=c++14]C++ Standard Library: libc++ (LLVM C++ standard library with C++11 support)Steps to reproduce the problem:Library (dylib) is linked ("Link Binary with Libraries") to: CoreFoundation and IOKit, plus the following additional frameworks - OpenDirectory, SystemConfiguration, Security, CoreServices, ApplicationServicesCompiling works fine, of course, and then the library is loaded, using dlopen by another application (Unix / terminal app)After calling dlclose, the library is still reported as being loaded in the process memoryThe problem will only happen when:the terminal app is ran from a terminal window (it cannot be reproduced when using Xcode directly to run / debug it)the library is linked to CoreFoundation, IOKit plus any one of the other frameworks (OpenDirectory, SystemConfiguration, Security, CoreServices, ApplicationServices)Does anyone know what may be causing this problem?On Linux based systems, the "-fno-gnu-unique" flag will not fix the problem, but at least offer the option to use the new / updated library. Is there, maybe, a similar flag for macOS?Any help would be greatly appreciated.Code snippet below:// Returns the full path of the application executable file const char* getApplicationPath() { static char s_szDir[1024] = {0}; if (!*s_szDir) { char buffer[1024]; char *answer = getcwd(buffer, sizeof(buffer)); strncpy(s_szDir, answer, 1024); s_szDir[1024-1] = '\0'; } return s_szDir; } // prints all loaded modules in the process memory (address space) void printLoadedModules( ) { std::cout&lt;&lt;"\ndynamic libraries loaded in the process memory:"; int count = _dyld_image_count(); for(int i = 0; i &lt; count; i++ ) { const char * imageName = _dyld_get_image_name(i); if( !imageName ) continue; std::string strImageName = imageName; if( strImageName.find( "libwa" ) != std::string::npos ) std::cout&lt;&lt;"\n " &lt;&lt; strImageName; } } int main(int argc, const char * argv[]) { std::string lib_path = getApplicationPath(); lib_path += "/libtest.dylib"; // Step 1: Print loaded libraries in the process memory before dlopen() std::cout&lt;&lt;"\n### Before dlopen \n"; printLoadedModules(); // Step 2: Load libtest.dylib void * lib_handle = (void*) dlopen( lib_path.c_str() , RTLD_LOCAL ); if( !lib_handle ) { std::cout&lt;&lt;"\nFailed to load libtest.dylib with error \n"&lt;&lt;dlerror(); exit(1); } // Step 3: Print loaded libraries in the process memory after dlopen() std::cout&lt;&lt;"\n\n### After dlopen \n"; printLoadedModules(); // Step 4: Unload libtest.dylib int close_code = dlclose( lib_handle ); lib_handle = nullptr; // Step 5: Print loaded libraries in the process memory after dlclose() std::cout&lt;&lt;"\n\n### After dlclose (closed code: " &lt;&lt; close_code &lt;&lt; ")\n"; printLoadedModules(); std::cout&lt;&lt;"\n\n"; return 0; }Thank you.
5
2
3.6k
Jan ’23
[XPC] Are there errors that are only reported to a send message replyBlock?
Context The event handler of an xpc_connection_t object named myConnection is set and handles XPC_TYPE_ERROR objects: xpc_connection_set_event_handler(myConnection, ^(xpc_object_t object) { }); A message is sent using: xpc_connection_send_message_with_reply(myConnection, myMessage , myQueue, ^(xpc_object_t object) { }); The documentation for the well-known XPC_ERROR_ dictionaries and for xpc_connection_set_event_handler seems to suggest that all the errors received via the reply block will also be received by the event handler. Question Are there error cases where only the reply block of xpc_connection_send_message_with_reply will receive an XPC_ERROR*_ object?
1
0
1.5k
Jan ’23
Troubleshooting the launch of local user XPC Launch Agent
This is a follow up to the thread, Troubleshooting the launch of local user XPC Launch Agent, in the original (and now archived) Dev Forums.Based on further tests, I assume there must be some configuration that I'm not setting up correctly, as opposed to the code.I started from scratch again with a fresh Xcode Project. This time, I based the code mostly on the example code posted by Apple Engineer eskimo1 in this thread (which uses an privileged Launch Daemon) with a modification or two based on the code posted by Apple Engineer dsorresso in this thread. As I assume that their code can be expected to work (i.e.- to help rule out a coding error on my part). Except that I modified the code so that it works with/as an XPC Service Launch Agent without the privileged aspect and which resides inside of the user's home directory.The following was all done on OS X 10.10.3 (14D136) Yosemite and built with Xcode 6.3.2 (6D2105).* I first started off both the command line interface program and the XPC Service Launch Agent without Code Signing or Sandboxing. When the command line interface program was run at the command line, I got output such as the following. Which more or less resembles the behaviour I was seeing with my own test code.connection event error Connection invalid* Then I code signed both items. No change in the output.* Next, I Sandboxed both. While there was no change in the output at the command line, some entries containing 'deny mach-lookup' began to appear in the System Console logs -&gt; in asl -&gt; with the AUX prefix. e.g.CLIHelloToLaunch(6103) deny mach-lookup com.test.XPCLA* Later, I added a com.apple.security.temporary-exception.mach-lookup.global-name key of Type Array containing the Bundle Identifier of the XPC Service Launch Agent in the Entitlements files for both Targets. No change in the command line output and 'deny mach-lookup' entries still appeared in System Console logs -&gt; asl -&gt; AUX.* As well, I also added an App Group to the Entitlements files for both Targets. No change in the command line output and 'deny mach-lookup' entries still appeared in System Console logs -&gt; asl -&gt; AUX.What could be the cause of the XPC connection errors? I presume that the 'deny mach-lookup' entries are related. How can I fix this?This is the contents of the launchd plist file for the XPC Service Launch Agent. It resides in ~/Library/LaunchAgents:&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;key&gt;MachService&lt;/key&gt; &lt;dict&gt; &lt;key&gt;com.test.XPCLA&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;~/Library/Application Support/com.test.XPCLA.xpc&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;This is the code being used in the XPC Service Launch Agent. Specifically, in it's main.m file. After building, I put the .xpc Launch Agent in ~/Library/Application Support for testing.#import &lt;Foundation/Foundation.h&gt; #include &lt;xpc/xpc.h&gt; static void SetupConnection(xpc_connection_t connection) { xpc_connection_set_event_handler(connection, ^(xpc_object_t object) { if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "connection error %s\n", xpc_dictionary_get_string(object, XPC_ERROR_KEY_DESCRIPTION)); xpc_connection_cancel(connection); } else if ( xpc_get_type(object) == XPC_TYPE_DICTIONARY ) { const char * name; fprintf(stderr, "connection message\n"); name = xpc_dictionary_get_string(object, "name"); if (name == NULL) { fprintf(stderr, "no name\n"); xpc_connection_cancel(connection); } else { xpc_object_t response; char * responseStr; fprintf(stderr, "name is '%s'\n", name); (void) asprintf(&amp;responseStr, "hello %s", name); response = xpc_dictionary_create(NULL, NULL, 0); assert(response != NULL); xpc_dictionary_set_string(response, "greeting", responseStr); xpc_connection_send_message(connection, response); // xpc_release(response); } } else { assert(false); } }); xpc_connection_resume(connection); } int main(int argc, char** argv) { xpc_connection_t listener; fprintf(stderr, "XPC Helper start\n"); listener = xpc_connection_create_mach_service("com.test.XPCLA", NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER); assert(listener != NULL); xpc_connection_set_event_handler(listener, ^(xpc_object_t object) { if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "listener error\n"); // XPC_ERROR_KEY_DESCRIPTION } else if ( xpc_get_type(object) == XPC_TYPE_CONNECTION ) { fprintf(stderr, "listener connection\n"); SetupConnection(object); } else { assert(false); } }); xpc_connection_resume(listener); dispatch_main(); return EXIT_SUCCESS; }This is the code in the command line interface program's main.m file. After building, I put the program into ~/Applications.#import &lt;Foundation/Foundation.h&gt; #include &lt;xpc/xpc.h&gt; static BOOL Test(void) { BOOL success; xpc_connection_t connection; xpc_object_t request; xpc_object_t response; response = NULL; connection = xpc_connection_create_mach_service("com.test.XPCLA", NULL, 0); assert(connection != NULL); request = xpc_dictionary_create(NULL, NULL, 0); assert(request != NULL); xpc_dictionary_set_string(request, "name", "Hello service, this is the program speaking, are you out there?"); xpc_connection_set_event_handler(connection, ^(xpc_object_t object) { fprintf(stderr, "connection event\n"); if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "error %s\n", xpc_dictionary_get_string(object, XPC_ERROR_KEY_DESCRIPTION)); } else if ( xpc_get_type(object) == XPC_TYPE_DICTIONARY ) { const char * greeting; fprintf(stderr, "response\n"); greeting = xpc_dictionary_get_string(object, "greeting"); fprintf(stderr, "greeting is '%s'\n", greeting); } else { fprintf(stderr, "something else\n"); } }); xpc_connection_resume(connection); xpc_connection_send_message(connection, request); dispatch_main(); if (request != NULL) { xpc_release(request); } if (response != NULL) { xpc_release(response); } return success; } int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"%@", @"About to run test of XPC Service."); Test(); } return 0; }Here are the command line program's Entitlements.&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;true/&gt; &lt;key&gt;com.apple.security.temporary-exception.mach-lookup.global-name &lt;/key&gt; &lt;array&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.security.application-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;$(TeamIdentifierPrefix)IPC&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;The XPC Service Launch Agent's Entitlements.&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;true/&gt; &lt;key&gt;com.apple.security.application-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;$(TeamIdentifierPrefix)IPC&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.security.temporary-exception.mach-lookup.global-name &lt;/key&gt; &lt;array&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;Additional notes, if it's relevant:* The command line interface program has an embedded info.plist since it's a single file executable.* Command line interface program was created via Xcode 6.3.2's New Target -&gt; Command Line Tool template* XPC Service was created via Xcode 6.3.2's New Target -&gt; XPC Service template.
10
0
8.5k
Jan ’23
XPC and ARC?
xctrace --template Leaks identified this as a leak:         NSString *uuid = [NSString stringWithUTF8String:connectionID];         NSData *contentData = [NSData dataWithBytes:data length:length];         id<ConnexctionProtocol> proxy = [connection asyncConnectionProxy];         [proxy handleData:uuid data:contentData]; return; (Which is to say: a few thousand objects show up in the Leaks pane, the stack for them goes up to the NSData creation, and Leaks apparently thinks it's never released.) That doesn't look like it should be a leak, with ARC? Which probably means I'm doing something wrong?
0
0
707
Dec ’22
Need help resolving a nasty crash
Two Obj-C processes A and B, communicating via XPC, using NSXPCConnection (the connection is created from an endpoint, unnamed). The method signature is this: - (void)userAction:(NSString *)identifier             update:(OITNFWPreventionStage)stage          eventInfo:(NSDictionary * _Nonnull)actionInfo          withError:(NSError * _Nullable)error              reply:(void (^ _Nullable)(BOOL))reply; I'm using a normal asynchronous proxy id<myProtocol> monitorProxy = [self.monitorConnection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {         NSLog( @"Monitoring XPC proxy call failed: %@", error);     }]; Since the actionInfo I'm using is NSMutableDictionary the gets updated frequently from concurrent queues and thread - I synchronize ALL my calls from process A to process B on an NSOperationQueue     NSOperationQueue *monitorUpdateQueue = [[NSOperationQueue alloc] init];     monitorUpdateQueue.name = @"monitoring queue";     monitorUpdateQueue.maxConcurrentOperationCount = 1;     monitorUpdateQueue.qualityOfService = NSQualityOfServiceUtility; My calls typically look like this:     [monitorUpdateQueue addOperationWithBlock:^{         actionInfo[@"Files"] = [fileEvents valueForKeyPath:@"dictionary"]; // some NSArray of NSDictionaries         actionInfo[@"stage"] = ActionStagePreblocked;         [monitorProxy userAction:userActionIdentifier update:ActionStagePreblocked eventInfo:actionInfo withError:nil reply:^(BOOL reported) {             NSLog(@"Action reported");         }];     }]; Now every now and then, Process A (the caller) crashes inside this remote call... I Full crash log. Couldn't attach .ips file Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x00004c52f8b94400 Exception Codes: 0x0000000000000001, 0x00004c52f8b94400 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [83282] VM Region Info: 0x4c52f8b94400 is not in any region. Bytes after previous region: 83438207583233 Bytes before following region: 21633872346112 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL commpage (reserved) 1000000000-7000000000 [384.0G] ---/--- SM=NUL ...(unallocated) ---> GAP OF 0x5f9000000000 BYTES MALLOC_NANO 600000000000-600008000000 [128.0M] rw-/rwx SM=PRV and the thread's stack looks like this: Thread 10 Crashed:: Dispatch queue: monitoring queue (QOS: UTILITY) 0 libobjc.A.dylib 0x18a7e8310 objc_retain + 16 1 Foundation 0x18b8eb4a8 -[NSDictionary(NSDictionary) encodeWithCoder:] + 596 2 Foundation 0x18b8ba5f4 -[NSXPCEncoder _encodeObject:] + 520 3 Foundation 0x18b8b9ae4 _NSXPCSerializationAddInvocationArgumentsArray + 276 4 Foundation 0x18b8b95fc -[NSXPCEncoder _encodeInvocation:isReply:into:] + 256 5 Foundation 0x18b8b8798 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 1356 6 CoreFoundation 0x18aa08040 ___forwarding___ + 1088 7 CoreFoundation 0x18aa07b40 _CF_forwarding_prep_0 + 96 8 myproc 0x10041370c __84-[myproc scanContentOfFilesInEvents:userActionInfo:monitorProxy:monitoringQueue:]_block_invoke_2.1588 + 1064 (myproc.m:3690) 9 Foundation 0x18b8e0600 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 24 10 Foundation 0x18b8e04a8 -[NSBlockOperation main] + 104 11 Foundation 0x18b8e0438 __NSOPERATION_IS_INVOKING_MAIN__ + 24 12 Foundation 0x18b8df67c -[NSOperation start] + 804 13 Foundation 0x18b8df350 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 24 14 Foundation 0x18b8df204 __NSOQSchedule_f + 184 15 libdispatch.dylib 0x18a7ad990 _dispatch_block_async_invoke2 + 148 16 libdispatch.dylib 0x18a79ebac _dispatch_client_callout + 20 17 libdispatch.dylib 0x18a7a2080 _dispatch_continuation_pop + 504 18 libdispatch.dylib 0x18a7a16dc _dispatch_async_redirect_invoke + 596 19 libdispatch.dylib 0x18a7b031c _dispatch_root_queue_drain + 396 20 libdispatch.dylib 0x18a7b0b58 _dispatch_worker_thread2 + 164 21 libsystem_pthread.dylib 0x18a959574 _pthread_wqthread + 228 22 libsystem_pthread.dylib 0x18a9582c4 start_wqthread + 8 Sorry for the terrible formatting, I could not attach the .ips file, but I attached its full text. My question: When I'm passing an NSMutableDictionary to the remote proxy. Is it received "mutable" on the other side? and while it is being worked in on the receiving side, what happens if I modify it on the calling side (process A) ? How do Mutable objects behave on XPC calls? The Dictionary I'm moving only contains basic "plist approved" entries - NSString, NSNumber, NSDate, and collections (NSArray, NSDictionary). That's all. No custom classes there. I will be most grateful for any idea or hint.
3
0
3.6k
Dec ’22
XPC to communicate Swift with C++
Hello! I'm new here, and probably this will sound weird but, I'm trying to write a C++ program using an XPC service to attempt to communicate with a macOS app I'm developing in Swift. At the macOS app side I think I'm successfully registering and connecting to the service, as launchd reports the following in its log: 2023-05-31 17:20:21.898621 (pid/15637 [On Air]) <Notice>: Service stub created for com.ruieduardolopes.onaird-join At the C++ side I'm trying to get a simple example working, as follows, but currently without any success... #include <xpc/xpc.h> int main(int argc, const char* argv[]) { xpc_connection_t conn = xpc_connection_create_mach_service("com.ruieduardolopes.onaird.join", NULL, 0); xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); xpc_connection_set_event_handler(conn, ^(xpc_object_t object) {}); xpc_connection_resume(conn); xpc_dictionary_set_string(message, "SS", "AAAAAA\n"); xpc_connection_send_message_with_reply(conn, message, dispatch_get_main_queue(), ^(xpc_object_t object) {}); return (EXIT_SUCCESS); } I get the following error in the logs: 2023-05-31 17:27:45.636894 (system/com.ruieduardolopes.onaird) <Notice>: internal event: WILL_SPAWN, code = 0 2023-05-31 17:27:45.636903 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawn scheduled 2023-05-31 17:27:45.636904 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawning 2023-05-31 17:27:45.637017 (system/com.ruieduardolopes.onaird) <Notice>: launching: ipc (mach) 2023-05-31 17:27:45.637256 (system/com.ruieduardolopes.onaird [15908]) <Notice>: xpcproxy spawned with pid 15908 2023-05-31 17:27:45.637264 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: SPAWNED, code = 0 2023-05-31 17:27:45.637265 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: xpcproxy 2023-05-31 17:27:45.637269 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: SOURCE_ATTACH, code = 0 2023-05-31 17:27:45.648927 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: running 2023-05-31 17:27:45.648940 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: INIT, code = 0 2023-05-31 17:27:45.648948 (system/com.ruieduardolopes.onaird [15908]) <Notice>: Successfully spawned onaird-join[15908] because ipc (mach) 2023-05-31 17:27:45.687251 (system/com.ruieduardolopes.onaird [15908]) <Notice>: exited due to SIGTRAP | sent by exc handler[15908] 2023-05-31 17:27:45.687261 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service has crashed 1 times in a row 2023-05-31 17:27:45.687263 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: exited 2023-05-31 17:27:45.687267 (system/com.ruieduardolopes.onaird [15908]) <Notice>: internal event: EXITED, code = 0 2023-05-31 17:27:45.687269 (system) <Notice>: service inactive: com.ruieduardolopes.onaird 2023-05-31 17:27:45.687281 (system/com.ruieduardolopes.onaird [15908]) <Notice>: service state: not running 2023-05-31 17:27:45.687290 (system/com.ruieduardolopes.onaird) <Notice>: Service only ran for 0 seconds. Pushing respawn out by 10 seconds. 2023-05-31 17:27:45.687339 (system/com.ruieduardolopes.onaird) <Notice>: internal event: WILL_SPAWN, code = 0 2023-05-31 17:27:45.687343 (system/com.ruieduardolopes.onaird) <Notice>: service state: spawn scheduled 2023-05-31 17:27:45.687344 (system/com.ruieduardolopes.onaird) <Notice>: service throttled by 10 seconds The plist file I'm currently loading to /Library/LaunchDaemons is as follows: <?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.ruieduardolopes.onaird</string> <key>Program</key> <string>PATH_TO_ONAIR_JOIN_XPC_SERVICE_BINARY</string> <key>BuildMachineOSBuild</key> <string>22C65</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>onaird-join</string> <key>CFBundleExecutable</key> <string>onaird-join</string> <key>CFBundleIdentifier</key> <string>com.ruieduardolopes.onaird-join</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>onaird-join</string> <key>CFBundlePackageType</key> <string>XPC!</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string></string> <key>DTPlatformName</key> <string>macosx</string> <key>DTPlatformVersion</key> <string>13.3</string> <key>DTSDKBuild</key> <string>22E245</string> <key>DTSDKName</key> <string>macosx13.3</string> <key>DTXcode</key> <string>1430</string> <key>DTXcodeBuild</key> <string>14E222b</string> <key>LSMinimumSystemVersion</key> <string>13.1</string> <key>MachServices</key> <dict> <key>com.ruieduardolopes.onaird.join</key> <true/> </dict> <key>XPCService</key> <dict> <key>ServiceType</key> <string>Application</string> </dict> </dict> </plist> Can anybody help me? Thanks in advance, Rui
Replies
5
Boosts
0
Views
1.5k
Activity
Jun ’23
[MADService] Client XPC connection invalidated
I am working as an iOS Developer since 2 years. I am getting log on console like: [MADService] Client XPC connection invalidated sometimes. I am unable to get when and for what reason i am getting this. need some help. Thank you
Replies
1
Boosts
0
Views
2.0k
Activity
May ’23
How can I have launchd execute a script when a certain kind of usb device is connected?
I need launchd to execute a script when a certain kind of usb device is connected. Specifically, an iOS device.is this possible? If so, what should the launchd plist look like?
Replies
6
Boosts
0
Views
4.2k
Activity
May ’23
0xdead10cc prevention
Hello,Technical Note TN2151 describes the 0xdead10cc exception:&gt; The exception code 0xdead10cc indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension. If your application is performing operations on a locked file or sqlite database at suspension time, it must request additional background execution time to complete those operations and relinquish the lock before suspending.This is all pretty clear. After the additional background execution time has expired, all SQLite accesses that create a lock create a risk for sudden termination. An application which wants to avoid 0xdead10cc has thus to actively prevent such accesses... until the application wakes up from the suspended state. My questions are all about the end of this critical lapse of time in the app's life cycle.Eventually, the application may become active, and this clearly marks the end of the 0xdead10cc danger. This moment is notified by UIApplicationWillEnterForegroundNotification. After this notification is posted, it becomes possible again to access an SQLite database without risking any 0xdead10cc exception, until the next UIApplicationDidEnterBackgroundNotification, and the next notification of additional background execution time expiration.But what about cases when the application leaves the suspended state and reenters the background state? This may happen due to the various background modes supported by iOS.First question: Is there one way to be notified of this transition from suspended to background state, regardless of the reason for this background wake-up (core location, VoIP, background fetch, etc.) ?Second question: Is it then possible to start another request for additional background execution time and be reliably notified when accessing the SQLite database creates a 0xdead10cc threat again?Third question: do you have any other advice regarding 0xdead10cc prevention?For the context, I'm the author of GRDB, and I'm looking for a way to package 0xdead10cc prevention in a way that reduces to a minimum the amount of code users have to write in order to protect their app from this exception. Ideally, it would be reduced to a simple boolean flag targetted at users who store their database in an App Group container.Thank you very much!
Replies
9
Boosts
2
Views
8.5k
Activity
May ’23
NSXPCConnection fails to transport IOSurfaceRef
I'm trying to send an IOSurfaceRef across an NSXPCConnection on osx 10.13 and I'm having trouble with the solution that was provided in the forum thread "Efficiently sending data from an XPC process to the host application." https://developer.apple.com/forums/thread/126716 From that thread: > However, that specific problem got resolved on 10.12 where we introduced a new Objective-C IOSurface object, and that object is transportable directly over NSXPCConnection . So double yay! But it doesn’t seem to work. I have a very simple service protocol that includes (void)sendFrame:(IOSurfaceRef)frame; along with some basic NSString sending methods that successfully transfer across my NSXPCConnection. I have a valid (non-NULL) IOSurface in my app that I send to my helper app with sendFrame, and when the call is executed in the helper, the resulting frame is always NULL. On the other hand, I’ve also tried creating an IOSurface with the (deprecated) kIOSurfaceIsGlobal property and sending the IOSurface’s ID instead with: (void)sendFrameID:(uint32_t)frameID; and [_service sendFrameID:IOSurfaceGetID(surface)]; And on the helper app side, I look up the IO to get an IOSurfaceRef: IOSurfaceRef frame = IOSurfaceLookup(frameID); and it works correctly – I get a valid IOSurface which I can display and see the same pixel contents in both the app and the helper. So what is meant by the new IOSurface object in 10.12 is “transportable directly” over NSXPCConnection? How is it supposed to work? I’m specifically interested in no-copy transfer. Thanks!
Replies
4
Boosts
0
Views
3.0k
Activity
Apr ’23
XPC working fine for system extension but not for app extension
Hello, I'm working on an app that offers a VPN tunnel (NEPacketTunnelProvider) meant to be released both in Developer ID builds and App Store builds. I've implemented an IPC mechanism using IPCConnection from the filtering network traffic example code. For the system extension it works fine. For the app extension, I just can't connect to the mach service. In both cases the app is not sandboxed, but the extension is. I'm trying to figure out how to troubleshoot the issue. The plist file for the system extension has this key: <key>NetworkExtension</key> <dict> <key>NEMachServiceName</key> <string>$(TeamIdentifierPrefix)com.company.system.extension.bundle.id</string> <key>NEProviderClasses</key> <dict> <key>com.apple.networkextension.packet-tunnel</key> <string>$(PRODUCT_MODULE_NAME).PacketTunnelProvider</string> </dict> </dict> Would the app network extension use the same NetworkExtension dictionary with a NEMachServiceName key for the mach service name? Any hints to help me debug this issue? I've tried using launchctl list to see if the mach service is up, but I'm not exactly sure what's a good way to use it. I've considered using sendProviderMessage to communicate with the tunnel from the main App, but the problem is that sometimes NEVPNManager.shared.connection as? NETunnelProviderSession is just nil (due to the cast), and I'm not sure why that's the case.
Replies
3
Boosts
0
Views
2k
Activity
Apr ’23
No error handler for XPC error: Connection invalid
I am on Ventura 13.3.1 with the M2 and I was trying to set up a Linux VM, following the steps on your website, but after I chose the ISO the following Error in Xcode appeared: GUILinuxVirtualMachineSampleApp[5863:111794] [client] No error handler for XPC error: Connection invalid . There was already a question about the No error handler on this forum, but that still didn't help me fix my Problem. So now my question is how do I fix it, because I have almost no good idea where to start. I can give more informations if needed. Big thanks and regards in advance :). Sincerely, Bieber
Replies
1
Boosts
0
Views
1.7k
Activity
Apr ’23
XPC Errors when launching in simulator
I cannot debug any applications anymore since upgrading to latest Ventura (13.3) and XCode 14.3. First - None of the iOS 16.X simulators work AT ALL. When I choose an iOS 16 target simulator, the simulator window comes up but is completely blank and never starts. Pressing HOME button, resetting device data, restarting device do not fix the issue. I've deleted and re-installed the simulators multiple times and nothing works. Error detail when trying to launch 16.4 simulator: Domain: FBSOpenApplicationServiceErrorDomain Code: 5 Failure Reason: Unexpected error type. User Info: { BSErrorCodeDescription = InvalidResponse; DVTErrorCreationDateKey = "2023-04-04 03:47:36 +0000"; IDERunOperationFailingWorker = IDELaunchiPhoneSimulatorLauncher; SimCallingSelector = "launchApplicationWithID:options:pid:error:"; } -- The request to open "XXX.XXX.XXXXXX" failed. Domain: FBSOpenApplicationServiceErrorDomain Code: 5 Failure Reason: Unexpected error type. User Info: { BSErrorCodeDescription = InvalidResponse; } -- The operation couldn’t be completed. XPC error received on message reply handler Domain: BSServiceConnectionErrorDomain Code: 3 Failure Reason: XPC error received on message reply handler User Info: { BSErrorCodeDescription = OperationFailed; } -- Second - I can use iOS 15.2 simulators, but cannot attach debugger to them. XCode will launch my app but will not actually let me debug it or attach a debugger to it after launch. Error detail when launching 15.2 debuggable simulator: Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.) User Info: { DVTErrorCreationDateKey = "2023-04-04 03:41:19 +0000"; DVTRadarComponentKey = 855031; IDERunOperationFailingWorker = DBGLLDBLauncher; RawUnderlyingErrorMessage = "attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.)"; } I see no errors in any of the console or system logs that would indicate what the problem could be. I have deleted the DerivedData, wiped the cache clean from the Storage Settings section in the settings.app. XCode seems to get worse with every minor update, at this point I cannot debug my apps anymore and have found no solutions.
Replies
3
Boosts
1
Views
4.5k
Activity
Apr ’23
PHAssetCollection.requestAuthorization(for:handler:) gives .denied on ExtensionKit
I am making macOS app with ExtensionKit. When I call PHAssetCollection.requestAuthorization(for:handler:) on my extension, it always gives .denied without any prompts. I've added com.apple.security.personal-information.photos-library key into entitlements and NSPhotoLibraryUsageDescription key into Info.plist but has no effects. Also Security Policy of my MacBook is Reduced Security and my host app gets .authorized status but extension gives .denined. Does PhotoKit support ExtensionKit? Any ideas? void (^requestAuthorization)(void (^completion)(NSError * _Nullable)) = ^(void (^completion)(NSError * _Nullable)) { [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) { switch (status) { case PHAuthorizationStatusNotDetermined: requestAuthorization(completion); break; case PHAuthorizationStatusAuthorized: completion(nil); break; default: { NSLog(@"%lu", status); // gives 2, PHAuthorizationStatusDenied NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadNoPermissionError userInfo:nil]; completion(error); break; } } }]; };
Replies
0
Boosts
0
Views
797
Activity
Mar ’23
"[SDKPlayback] applicationController: xpc service connection interrupted" for MPMusicPlayerController.applicationMusicPlayer iOS 16.3.1
Hi! I'm having a problem that I cannot seem to figure out. I have not made any changes to my app, yet this suddenly started happening. I think it started happening after I upgraded my phone to iOS 16.3.1, but I am not entirely sure. Pseudocode: // (1) initialise player let player = MPMusicPlayerController.applicationMusicPlayer // (2) ..later, a button is pressed and we call play() player.play(myAlbumId) // (3) a background timer runs, which will ensure we are playing for 30 seconds, and pausing for 60 seconds (this is a workout app): self.timer = Timer(timeInterval: 1.0, target: self, selector: #selector(togglePauseIfNeeded), userInfo: nil, repeats: true) RunLoop.current.add(self.timer!, forMode: .common) // (4) Now, the problem occurs when the timer triggers play, the second time we are playing music (ie, it works the initial time, but in that case, play was triggered by a button press (step 2)). // So when the timer now calls player.play(), we see this error: "[SDKPlayback] applicationController: xpc service connection interrupted" player.play() Interestingly, if I manually hit play just a few seconds before the timer would have called "play" (at step 4), it works fine. Any thoughts or help on this would be highly appreciated! <3
Replies
0
Boosts
0
Views
786
Activity
Mar ’23
XPC connection invalidated when Background Processing task performs a network request
Hello, I'm developing an iOS app which has an ability to upload user photos, and I'm using a Background processing task to perform such an operation. The app also has File provider extension, which is involved in the process Whenever the background task is launched, the following actions are performed: Main app fetches new items from PHAsset library and copies them to our file storage File Provider extension uploads those items to a cloud storage Everything goes fine until Extension tries to perform a network request, at this point I'm getting the following error: (501) got error from remote proxy: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction.} App has all the required entitlements and extension and main app has also the same app group. What is wrong with this that causes this error?
Replies
0
Boosts
1
Views
1.7k
Activity
Feb ’23
xpc api misuse crash
To begin with: I know it's my code, because if I go back to our main branch and try it, I don't get this crash. But I can't figure out what it's unhappy about, so I'm not sure what changes I have to look for. (Also, this is macOS.) The daemon tries to communicate with a Network Extension over XPC. I have a class, with a shared instance, and I have a cached NSXPCConnection connection instance variable. So my code is something like id connection = [[ExtensionCommunication shared] connection], which is created by [[NSXPCConnection alloc] initWithMachServiceName:self.redirectorMachServiceName options:0]. With my changes (whatever they are), when it does [_connection resume], it crashes:   * frame #0: 0x00007ff8191ab20e libxpc.dylib`_xpc_api_misuse + 117     frame #1: 0x00007ff8191963a1 libxpc.dylib`xpc_connection_resume + 54 This happens whether the network extension is activated or not. The crash happens the second time this is called. (Hm, one thing I need to figure out then is why my cached connection object is being set to nil. It shouldn't be. hm.) Anyway! Any suggestions on how I can try to debug this?
Replies
2
Boosts
0
Views
1.5k
Activity
Feb ’23
Thread 1: signal SIGTERM error
Hello! I am using macOS Catalina, Xcode 11. I just started working on app development and this is my first project. Every time i try to simulate the code the program crashes and it gives me thread 1 signal SIGTERM error. My code is very simple, I don't think i have an error there. I am really stuck, I tried to run different projects but it doesn’t work on any of them. Please, can someone help me fix this error? Thanks in advance!
Replies
6
Boosts
0
Views
14k
Activity
Jan ’23
Stop LaunchAgent from restarting.
I have a Mac OS remote application that is made out of three parts. 1.- A LaunchDaemon that handles all of my network code and connects to my client 2.- A LaunchAgent to provides access to the window server to capture monitors, events, etc. 3.- A NSApplication to allow the user to control the LaunchDaemon I'm trying to get the LaunchAgent and LaunchDaemon to run only while my NSApp is running. LaunchDaemon - it uses machServices so I "control" it by starting an xpcConnection from my NSApplication. LaunchAgent - it uses QueueDirectories and I start it by having my NSApplication save a file to the QueueDirectories path. My NSApp and LaunchAgent both communicate with the LaunchDaemon via XPCConnection. Everything works as expected until I try quit my NSApp, LaunchDaemon and LaunchAgent. This is how I do it. User quits NSApp -> NSApp removes QueueDirectory file, sends a quit message to Daemon and it gets terminated -> Daemon sends a message to Agent then it terminates with exit(0) -> Agent receives the message and it terminates with exit(0) as well. Agent gets terminated and immediately launches again creating demand for my Daemon and starting it again. When I run launchctl blame on my Agent I get xpc event. which means that the xpc connection with my daemon is still creating demand somehow even after calling .invalidate() and deallocating the connection object.? Is there a specific way to terminated an XPCConnection? this is how I create my XPCConnectionListener: NSXPCListener(machServiceName: "myMachServiceName") and my connections let connection = NSXPCConnection("myMachServiceName", options: [.privileged]) connection.remoteObjectInterface = NSXPCInterface(with: myProtocol.self) connection.exportedInterface = NSXPCInterface(with: myProtocol.self) connection.exportedObject = exportedObject connection.interruptionHandler = interruptionHandler connection.invalidationHandler = invalidationHandler return connection So it seems that the issue is that my connections aren't fully terminated when I quit the processes? any pointers would be greatly appreciated.
Replies
2
Boosts
0
Views
1.5k
Activity
Jan ’23
dlclose will not unload library when using macOS Frameworks
Hello,I am encountering an unsual problem when linking a library to macOS Frameworks: as soon as I'm linking to some specific frameworks (detailed below), dlclose will no longer work, meaning that the said library will not be unloaded from process memory.This is causing problems, because the update functionality of my application will not work - calling dlopen again will load the "old" library.The build details are:macOS High Sierra (10.13.6)Xcode 9.4.1 C++ Language Dialect: C++14 [-std=c++14]C++ Standard Library: libc++ (LLVM C++ standard library with C++11 support)Steps to reproduce the problem:Library (dylib) is linked ("Link Binary with Libraries") to: CoreFoundation and IOKit, plus the following additional frameworks - OpenDirectory, SystemConfiguration, Security, CoreServices, ApplicationServicesCompiling works fine, of course, and then the library is loaded, using dlopen by another application (Unix / terminal app)After calling dlclose, the library is still reported as being loaded in the process memoryThe problem will only happen when:the terminal app is ran from a terminal window (it cannot be reproduced when using Xcode directly to run / debug it)the library is linked to CoreFoundation, IOKit plus any one of the other frameworks (OpenDirectory, SystemConfiguration, Security, CoreServices, ApplicationServices)Does anyone know what may be causing this problem?On Linux based systems, the "-fno-gnu-unique" flag will not fix the problem, but at least offer the option to use the new / updated library. Is there, maybe, a similar flag for macOS?Any help would be greatly appreciated.Code snippet below:// Returns the full path of the application executable file const char* getApplicationPath() { static char s_szDir[1024] = {0}; if (!*s_szDir) { char buffer[1024]; char *answer = getcwd(buffer, sizeof(buffer)); strncpy(s_szDir, answer, 1024); s_szDir[1024-1] = '\0'; } return s_szDir; } // prints all loaded modules in the process memory (address space) void printLoadedModules( ) { std::cout&lt;&lt;"\ndynamic libraries loaded in the process memory:"; int count = _dyld_image_count(); for(int i = 0; i &lt; count; i++ ) { const char * imageName = _dyld_get_image_name(i); if( !imageName ) continue; std::string strImageName = imageName; if( strImageName.find( "libwa" ) != std::string::npos ) std::cout&lt;&lt;"\n " &lt;&lt; strImageName; } } int main(int argc, const char * argv[]) { std::string lib_path = getApplicationPath(); lib_path += "/libtest.dylib"; // Step 1: Print loaded libraries in the process memory before dlopen() std::cout&lt;&lt;"\n### Before dlopen \n"; printLoadedModules(); // Step 2: Load libtest.dylib void * lib_handle = (void*) dlopen( lib_path.c_str() , RTLD_LOCAL ); if( !lib_handle ) { std::cout&lt;&lt;"\nFailed to load libtest.dylib with error \n"&lt;&lt;dlerror(); exit(1); } // Step 3: Print loaded libraries in the process memory after dlopen() std::cout&lt;&lt;"\n\n### After dlopen \n"; printLoadedModules(); // Step 4: Unload libtest.dylib int close_code = dlclose( lib_handle ); lib_handle = nullptr; // Step 5: Print loaded libraries in the process memory after dlclose() std::cout&lt;&lt;"\n\n### After dlclose (closed code: " &lt;&lt; close_code &lt;&lt; ")\n"; printLoadedModules(); std::cout&lt;&lt;"\n\n"; return 0; }Thank you.
Replies
5
Boosts
2
Views
3.6k
Activity
Jan ’23
[XPC] Are there errors that are only reported to a send message replyBlock?
Context The event handler of an xpc_connection_t object named myConnection is set and handles XPC_TYPE_ERROR objects: xpc_connection_set_event_handler(myConnection, ^(xpc_object_t object) { }); A message is sent using: xpc_connection_send_message_with_reply(myConnection, myMessage , myQueue, ^(xpc_object_t object) { }); The documentation for the well-known XPC_ERROR_ dictionaries and for xpc_connection_set_event_handler seems to suggest that all the errors received via the reply block will also be received by the event handler. Question Are there error cases where only the reply block of xpc_connection_send_message_with_reply will receive an XPC_ERROR*_ object?
Replies
1
Boosts
0
Views
1.5k
Activity
Jan ’23
Troubleshooting the launch of local user XPC Launch Agent
This is a follow up to the thread, Troubleshooting the launch of local user XPC Launch Agent, in the original (and now archived) Dev Forums.Based on further tests, I assume there must be some configuration that I'm not setting up correctly, as opposed to the code.I started from scratch again with a fresh Xcode Project. This time, I based the code mostly on the example code posted by Apple Engineer eskimo1 in this thread (which uses an privileged Launch Daemon) with a modification or two based on the code posted by Apple Engineer dsorresso in this thread. As I assume that their code can be expected to work (i.e.- to help rule out a coding error on my part). Except that I modified the code so that it works with/as an XPC Service Launch Agent without the privileged aspect and which resides inside of the user's home directory.The following was all done on OS X 10.10.3 (14D136) Yosemite and built with Xcode 6.3.2 (6D2105).* I first started off both the command line interface program and the XPC Service Launch Agent without Code Signing or Sandboxing. When the command line interface program was run at the command line, I got output such as the following. Which more or less resembles the behaviour I was seeing with my own test code.connection event error Connection invalid* Then I code signed both items. No change in the output.* Next, I Sandboxed both. While there was no change in the output at the command line, some entries containing 'deny mach-lookup' began to appear in the System Console logs -&gt; in asl -&gt; with the AUX prefix. e.g.CLIHelloToLaunch(6103) deny mach-lookup com.test.XPCLA* Later, I added a com.apple.security.temporary-exception.mach-lookup.global-name key of Type Array containing the Bundle Identifier of the XPC Service Launch Agent in the Entitlements files for both Targets. No change in the command line output and 'deny mach-lookup' entries still appeared in System Console logs -&gt; asl -&gt; AUX.* As well, I also added an App Group to the Entitlements files for both Targets. No change in the command line output and 'deny mach-lookup' entries still appeared in System Console logs -&gt; asl -&gt; AUX.What could be the cause of the XPC connection errors? I presume that the 'deny mach-lookup' entries are related. How can I fix this?This is the contents of the launchd plist file for the XPC Service Launch Agent. It resides in ~/Library/LaunchAgents:&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;key&gt;MachService&lt;/key&gt; &lt;dict&gt; &lt;key&gt;com.test.XPCLA&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;~/Library/Application Support/com.test.XPCLA.xpc&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;This is the code being used in the XPC Service Launch Agent. Specifically, in it's main.m file. After building, I put the .xpc Launch Agent in ~/Library/Application Support for testing.#import &lt;Foundation/Foundation.h&gt; #include &lt;xpc/xpc.h&gt; static void SetupConnection(xpc_connection_t connection) { xpc_connection_set_event_handler(connection, ^(xpc_object_t object) { if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "connection error %s\n", xpc_dictionary_get_string(object, XPC_ERROR_KEY_DESCRIPTION)); xpc_connection_cancel(connection); } else if ( xpc_get_type(object) == XPC_TYPE_DICTIONARY ) { const char * name; fprintf(stderr, "connection message\n"); name = xpc_dictionary_get_string(object, "name"); if (name == NULL) { fprintf(stderr, "no name\n"); xpc_connection_cancel(connection); } else { xpc_object_t response; char * responseStr; fprintf(stderr, "name is '%s'\n", name); (void) asprintf(&amp;responseStr, "hello %s", name); response = xpc_dictionary_create(NULL, NULL, 0); assert(response != NULL); xpc_dictionary_set_string(response, "greeting", responseStr); xpc_connection_send_message(connection, response); // xpc_release(response); } } else { assert(false); } }); xpc_connection_resume(connection); } int main(int argc, char** argv) { xpc_connection_t listener; fprintf(stderr, "XPC Helper start\n"); listener = xpc_connection_create_mach_service("com.test.XPCLA", NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER); assert(listener != NULL); xpc_connection_set_event_handler(listener, ^(xpc_object_t object) { if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "listener error\n"); // XPC_ERROR_KEY_DESCRIPTION } else if ( xpc_get_type(object) == XPC_TYPE_CONNECTION ) { fprintf(stderr, "listener connection\n"); SetupConnection(object); } else { assert(false); } }); xpc_connection_resume(listener); dispatch_main(); return EXIT_SUCCESS; }This is the code in the command line interface program's main.m file. After building, I put the program into ~/Applications.#import &lt;Foundation/Foundation.h&gt; #include &lt;xpc/xpc.h&gt; static BOOL Test(void) { BOOL success; xpc_connection_t connection; xpc_object_t request; xpc_object_t response; response = NULL; connection = xpc_connection_create_mach_service("com.test.XPCLA", NULL, 0); assert(connection != NULL); request = xpc_dictionary_create(NULL, NULL, 0); assert(request != NULL); xpc_dictionary_set_string(request, "name", "Hello service, this is the program speaking, are you out there?"); xpc_connection_set_event_handler(connection, ^(xpc_object_t object) { fprintf(stderr, "connection event\n"); if ( xpc_get_type(object) == XPC_TYPE_ERROR ) { fprintf(stderr, "error %s\n", xpc_dictionary_get_string(object, XPC_ERROR_KEY_DESCRIPTION)); } else if ( xpc_get_type(object) == XPC_TYPE_DICTIONARY ) { const char * greeting; fprintf(stderr, "response\n"); greeting = xpc_dictionary_get_string(object, "greeting"); fprintf(stderr, "greeting is '%s'\n", greeting); } else { fprintf(stderr, "something else\n"); } }); xpc_connection_resume(connection); xpc_connection_send_message(connection, request); dispatch_main(); if (request != NULL) { xpc_release(request); } if (response != NULL) { xpc_release(response); } return success; } int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"%@", @"About to run test of XPC Service."); Test(); } return 0; }Here are the command line program's Entitlements.&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;true/&gt; &lt;key&gt;com.apple.security.temporary-exception.mach-lookup.global-name &lt;/key&gt; &lt;array&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.security.application-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;$(TeamIdentifierPrefix)IPC&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;The XPC Service Launch Agent's Entitlements.&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;com.apple.security.app-sandbox&lt;/key&gt; &lt;true/&gt; &lt;key&gt;com.apple.security.application-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;$(TeamIdentifierPrefix)IPC&lt;/string&gt; &lt;/array&gt; &lt;key&gt;com.apple.security.temporary-exception.mach-lookup.global-name &lt;/key&gt; &lt;array&gt; &lt;string&gt;com.test.XPCLA&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt;Additional notes, if it's relevant:* The command line interface program has an embedded info.plist since it's a single file executable.* Command line interface program was created via Xcode 6.3.2's New Target -&gt; Command Line Tool template* XPC Service was created via Xcode 6.3.2's New Target -&gt; XPC Service template.
Replies
10
Boosts
0
Views
8.5k
Activity
Jan ’23
XPC and ARC?
xctrace --template Leaks identified this as a leak:         NSString *uuid = [NSString stringWithUTF8String:connectionID];         NSData *contentData = [NSData dataWithBytes:data length:length];         id<ConnexctionProtocol> proxy = [connection asyncConnectionProxy];         [proxy handleData:uuid data:contentData]; return; (Which is to say: a few thousand objects show up in the Leaks pane, the stack for them goes up to the NSData creation, and Leaks apparently thinks it's never released.) That doesn't look like it should be a leak, with ARC? Which probably means I'm doing something wrong?
Replies
0
Boosts
0
Views
707
Activity
Dec ’22
NSXPCConnection Data Communication Security
I have two processes that talk to each other using an NSXPCConnection. If I want to pass sensitive data over the connection, should I be worried about it being intercepted or read by other processes? Should I encrypt any sensitive data before sending it over the connection and have the other process have to decrypt it?
Replies
6
Boosts
0
Views
2.0k
Activity
Dec ’22
Need help resolving a nasty crash
Two Obj-C processes A and B, communicating via XPC, using NSXPCConnection (the connection is created from an endpoint, unnamed). The method signature is this: - (void)userAction:(NSString *)identifier             update:(OITNFWPreventionStage)stage          eventInfo:(NSDictionary * _Nonnull)actionInfo          withError:(NSError * _Nullable)error              reply:(void (^ _Nullable)(BOOL))reply; I'm using a normal asynchronous proxy id<myProtocol> monitorProxy = [self.monitorConnection remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {         NSLog( @"Monitoring XPC proxy call failed: %@", error);     }]; Since the actionInfo I'm using is NSMutableDictionary the gets updated frequently from concurrent queues and thread - I synchronize ALL my calls from process A to process B on an NSOperationQueue     NSOperationQueue *monitorUpdateQueue = [[NSOperationQueue alloc] init];     monitorUpdateQueue.name = @"monitoring queue";     monitorUpdateQueue.maxConcurrentOperationCount = 1;     monitorUpdateQueue.qualityOfService = NSQualityOfServiceUtility; My calls typically look like this:     [monitorUpdateQueue addOperationWithBlock:^{         actionInfo[@"Files"] = [fileEvents valueForKeyPath:@"dictionary"]; // some NSArray of NSDictionaries         actionInfo[@"stage"] = ActionStagePreblocked;         [monitorProxy userAction:userActionIdentifier update:ActionStagePreblocked eventInfo:actionInfo withError:nil reply:^(BOOL reported) {             NSLog(@"Action reported");         }];     }]; Now every now and then, Process A (the caller) crashes inside this remote call... I Full crash log. Couldn't attach .ips file Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x00004c52f8b94400 Exception Codes: 0x0000000000000001, 0x00004c52f8b94400 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [83282] VM Region Info: 0x4c52f8b94400 is not in any region. Bytes after previous region: 83438207583233 Bytes before following region: 21633872346112 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL commpage (reserved) 1000000000-7000000000 [384.0G] ---/--- SM=NUL ...(unallocated) ---> GAP OF 0x5f9000000000 BYTES MALLOC_NANO 600000000000-600008000000 [128.0M] rw-/rwx SM=PRV and the thread's stack looks like this: Thread 10 Crashed:: Dispatch queue: monitoring queue (QOS: UTILITY) 0 libobjc.A.dylib 0x18a7e8310 objc_retain + 16 1 Foundation 0x18b8eb4a8 -[NSDictionary(NSDictionary) encodeWithCoder:] + 596 2 Foundation 0x18b8ba5f4 -[NSXPCEncoder _encodeObject:] + 520 3 Foundation 0x18b8b9ae4 _NSXPCSerializationAddInvocationArgumentsArray + 276 4 Foundation 0x18b8b95fc -[NSXPCEncoder _encodeInvocation:isReply:into:] + 256 5 Foundation 0x18b8b8798 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 1356 6 CoreFoundation 0x18aa08040 ___forwarding___ + 1088 7 CoreFoundation 0x18aa07b40 _CF_forwarding_prep_0 + 96 8 myproc 0x10041370c __84-[myproc scanContentOfFilesInEvents:userActionInfo:monitorProxy:monitoringQueue:]_block_invoke_2.1588 + 1064 (myproc.m:3690) 9 Foundation 0x18b8e0600 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 24 10 Foundation 0x18b8e04a8 -[NSBlockOperation main] + 104 11 Foundation 0x18b8e0438 __NSOPERATION_IS_INVOKING_MAIN__ + 24 12 Foundation 0x18b8df67c -[NSOperation start] + 804 13 Foundation 0x18b8df350 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 24 14 Foundation 0x18b8df204 __NSOQSchedule_f + 184 15 libdispatch.dylib 0x18a7ad990 _dispatch_block_async_invoke2 + 148 16 libdispatch.dylib 0x18a79ebac _dispatch_client_callout + 20 17 libdispatch.dylib 0x18a7a2080 _dispatch_continuation_pop + 504 18 libdispatch.dylib 0x18a7a16dc _dispatch_async_redirect_invoke + 596 19 libdispatch.dylib 0x18a7b031c _dispatch_root_queue_drain + 396 20 libdispatch.dylib 0x18a7b0b58 _dispatch_worker_thread2 + 164 21 libsystem_pthread.dylib 0x18a959574 _pthread_wqthread + 228 22 libsystem_pthread.dylib 0x18a9582c4 start_wqthread + 8 Sorry for the terrible formatting, I could not attach the .ips file, but I attached its full text. My question: When I'm passing an NSMutableDictionary to the remote proxy. Is it received "mutable" on the other side? and while it is being worked in on the receiving side, what happens if I modify it on the calling side (process A) ? How do Mutable objects behave on XPC calls? The Dictionary I'm moving only contains basic "plist approved" entries - NSString, NSNumber, NSDate, and collections (NSArray, NSDictionary). That's all. No custom classes there. I will be most grateful for any idea or hint.
Replies
3
Boosts
0
Views
3.6k
Activity
Dec ’22