I am using C APIs for XPC communication.
When my XPC server gets a xpc_dictionary as a message, I use xpc_dictionary_get_string to get the string which is of type const char*. Afterwards, when I try to free up the memory for the string, I get an error.
I could not find any details on why this happens.
Does XPC handle the lifecycle of these C strings ?
I did some tests to see the behaviour.
The following code snippet prints a string temp before and after releasing the dictionary memory.
char* string = "dummy-string";
xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string);
const char* temp = xpc_dictionary_get_string(reply, "str");
printf("temp before release: %s\n", temp);
xpc_release(reply);
printf("temp after release: %s\n", temp);
output:
# temp before release: dummy-string
# temp after release:
I tried to free the variable temp before and after releasing dict .
char* string = "dummy-string";
xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string);
const char* temp = xpc_dictionary_get_string(dict, "str");
printf("temp before release: %s\n", temp);
free((void *)temp); // case 1
xpc_release(dict);
// free((void *)temp); // case 2
printf("temp after release: %s\n", temp);
in both the cases i got the output:
# temp before release: dummy-string
# app(18502,0x1f02fc840) malloc: Double free of object 0x145004a20
# app(18502,0x1f02fc840) malloc: *** set a breakpoint in malloc_error_break to debug
# SIGABRT: abort
# PC=0x186953720 m=0 sigcode=0
# signal arrived during cgo execution
# ...
# ...
Processes & Concurrency
RSS for tagDiscover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.
Post
Replies
Boosts
Views
Activity
When I install my application, it installs fine and everything works alongwith all the system level daemons but when I reboot the system, none of my daemons are getting launched and this happens only on MacOS 15x, on older version it is working fine.
In the system logs, I see that my daemons have been detected as legacy daemons by backgroundtaskmanagementd with Disposition [enabled, allowed, visible, notified]
2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Type: legacy daemon (0x10010)
2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Flags: [ legacy ] (0x1)
2025-01-13 21:17:04.919129+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Disposition: [enabled, allowed, visible, notified] (0xb)
But later, it backgroundtaskmanagementd decides to disallow it.
2025-01-13 21:17:05.013202+0530 0x32d Default 0x4d6 89 0 smd: (BackgroundTaskManagement) [com.apple.backgroundtaskmanagement:main] getEffectiveDisposition: disposition=[enabled, disallowed, visible, notified], have LWCR=true
2025-01-13 21:17:05.013214+0530 0x32d Error 0x0 89 0 smd: [com.apple.xpc.smd:all] Legacy job is not allowed to launch: <private> status: 2
Is there anything changed in latest Mac OS which is causing this issue? Also what does this status 2 means. Can someone please help with this error?
The plist has is true
Purpose
I want to use launchd to run a shell script asynchronously every minute, but I'm encountering an issue where the job does not run, and I receive the error "Bootstrap failed: 5: Input/output error". I need help identifying the cause of this issue and how to configure launchd correctly.
What I've done
Created the shell script (test_ls_save.sh)
The script is designed to list the contents of the desktop and save the output to a specified directory.
#!/bin/bash
DATE=$(date +%Y-%m-%d_%H-%M-%S)
SAVE_DIR=/Users/test/Desktop/personal/log_gather
FILE_NAME="ls_output_$DATE.log"
ls ~/Desktop > "$SAVE_DIR/$FILE_NAME"
echo "ls output saved to $SAVE_DIR/$FILE_NAME"
File permissions (ls -l output): -rwxr-xr-x 1 test staff 1234 Feb 17 10:00 /Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh
Created the launchd plist file (com.test.logTest.plist)
The plist file is configured to execute the shell script every minute.
<key>Label</key>
<string>com.test.logTest</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>-c</string>
/Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh
</array>
<key>StartInterval</key>
<integer>60</integer> <!-- Run every minute -->
File permissions (ls -l output): -rwxr-xr-x 1 test staff 512 Feb 17 10:00 /Users/test/Library/LaunchAgents/com.test.logTest.plist
Ran the job with launchctl
I used the following command to load the plist file into launchd:
sudo launchctl bootstrap gui/$(id -u) /Users/test/Library/LaunchAgents/com.test.logTest.plist
pc spec
MacBook Pro
Apple M1
16 GB RAM
macOS 15.3 (Build 24D60)
what I know
The configuration has been set, but the launchd job is not running every minute as expected.
I don't believe there is a mistake with the path.
When I check the job using launchctl list, the job does not appear in the list.
I don't know where the error log files are supposed to be. I checked /var/log/system.log, but there are no error logs.
The .sh file runs fine by itself, but it cannot be executed via launchctl.
Want to ask
What could be the cause of the launchd job not running as expected?
Also, is there a way to check where the logs are being output?
If there is an error in the plist file configuration, which part should be modified?
Specifically, what improvements should be made regarding environment variables and path settings?
If my information is not enough, please tell me what is not enough!
I have an app that I'm using for my own purposes and is not in the app store. I would like to run an http server in the background for more than the allotted 3 minutes to allow persistent communications with a connected Bluetooth device. The Bluetooth device would poll the service at intervals. Is this possible to do? This app does not need app store approval since it's only for personal use.
When I run my app with XCode on my iPhone, and then moved into the background, I'm getting a EXC_BREAKPOINT exception after a few minutes, seemingly when iOS attempts to call my app with a BGAppRefreshTask:
Thread 23 Queue: com.apple.BGTaskScheduler (com.mycompany.MyApp.RefreshTask) (serial)
0 _dispatch_assert_queue_fail
12 _pthread_wqthread
Enqueued from com.apple.duet.activityscheduler.client.xpcqueue (Thread 23)
0 dispatch_async
20 start_wqthread
I can't quite understand the reason from this crash. In the background task, I'm attempting to update live activities. In the process, it might encounter code that calls MainActor and manipulate @Observable objects. Might that be the reason?
Hello,
I recently implemented a conditional debounce publisher using Swift's Combine.
If a string with a length less than 2 is passed, the event is sent downstream immediately without delay. If a string with a length of 2 or more is passed, the event is emitted downstream with a 0.2-second delay.
While writing test logic related to this, I noticed a strange phenomenon: sometimes the publisher, which should emit events with a 0.2-second delay, does not emit an event.
The test code below should have all indices from 1 to 100 in the array, but sometimes some indices are missing, causing the assertion to fail. Even after observing completion, cancel, and output events through handleEvents, I couldn't find any cause. Am I using Combine incorrectly, or is there a bug in Combine?
I would appreciate it if you could let me know.
import Foundation
import Combine
var cancellables: Set<AnyCancellable> = []
@MainActor func text(index: Int, completion: @escaping () -> Void) {
let subject = PassthroughSubject<String, Never>()
let textToSent = "textToSent"
subject
.map { text in
if text.count >= 2 {
return Just<String>(text)
.delay(for: .seconds(0.2), scheduler: RunLoop.main)
.eraseToAnyPublisher()
} else {
return Just<String>(text)
.eraseToAnyPublisher()
}
}
.switchToLatest()
.sink {
if $0.count >= 2 {
completion()
}
}.store(in: &cancellables)
for i in 0..<textToSent.count {
let stringIndex = textToSent.index(textToSent.startIndex, offsetBy: i)
let stringToSent = String(textToSent[textToSent.startIndex...stringIndex])
subject.send(stringToSent)
}
}
var array = [Int]()
for i in 1...100 {
text(index: i) {
array.append(i)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
for i in 1...100 {
assert(array.contains(i))
}
}
RunLoop.main.run(until: .now + 10)
I'm using libxpc in a C server and Swift client. I set up a code-signing requirement in the server using xpc_connection_set_peer_code_signing_requirement(). However, when the client doesn't meet the requirement, the server just closes the connection, and I get XPC_ERROR_CONNECTION_INTERRUPTED on the client side instead of XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT, making debugging harder.
What I want:
To receive XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT on the client when code-signing fails, for better debugging.
What I’ve tried:
Using xpc_connection_set_peer_code_signing_requirement(), but it causes the connection to be dropped immediately.
Questions:
Why does the server close the connection without sending the expected error?
How can I receive the correct error on the client side?
Are there any other methods for debugging code-signing failures with libxpc?
Thanks for any insights!
Hi,
I have received the following report after app termination. I have researched online but cannot determine the root cause. Any tips or ideas would help please.
Could it be Location Services, UserNotification Services, or Network Requests?
Thank you,
Brendan
Translated Report (Full Report Below)
Incident Identifier: 6CD59A17-15B1-4F4E-AE84-0286F22893A4
CrashReporter Key: 3d12fb7359053239708afd24c7eed0267a9cc601
Hardware Model: iPhone13,3
Process: AnchorNet3 [5605]
Path: /private/var/containers/Bundle/Application/5EA7F893-D562-45B8-8995-5EAB15F85A7E/AnchorNet3.app/AnchorNet3
Identifier: com.sailsecrets.AnchorNet3
Version: 3.17 (3.17)
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.sailsecrets.AnchorNet3 [1443]
Date/Time: 2025-02-06 00:12:03.6136 +0100
Launch Time: 2025-02-05 22:11:19.4220 +0100
OS Version: iPhone OS 18.2 (22C5131e)
Release Type: Beta
Baseband Version: 5.20.03
Report Version: 104
Exception Type: EXC_RESOURCE (SIGKILL)
Exception Codes: 0x0000000000020000, 0x0000000000000000
Termination Reason: PORT_SPACE 14123288431434006528 (Limit 131072 ports) Exceeded system-wide per-process Port Limit
Triggered by Thread: 3
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0:
0 libsystem_kernel.dylib 0x1e27414e4 kevent_id + 8
1 libdispatch.dylib 0x198f51b40 _dispatch_kq_poll + 228
2 libdispatch.dylib 0x198f51080 _dispatch_event_loop_poke + 340
3 QuartzCore 0x192d4631c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 17164
4 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648
5 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88
6 UIKitCore 0x193a3fd14 _UIApplicationFlushCATransaction + 52
7 UIKitCore 0x193a3d1e0 __setupUpdateSequence_block_invoke_2 + 332
8 UIKitCore 0x193a3d054 UIUpdateSequenceRun + 84
9 UIKitCore 0x193a3f984 schedulerStepScheduledMainSection + 172
10 UIKitCore 0x193a3d5a0 runloopSourceCallback + 92
11 CoreFoundation 0x1911f1f3c CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28
12 CoreFoundation 0x1911f1ed0 __CFRunLoopDoSource0 + 176
13 CoreFoundation 0x1911f4b30 __CFRunLoopDoSources0 + 244
14 CoreFoundation 0x1911f3d2c __CFRunLoopRun + 840
15 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
16 GraphicsServices 0x1de34d4c0 GSEventRunModal + 164
17 UIKitCore 0x193d8f480 -[UIApplication run] + 816
18 UIKitCore 0x1939b5410 UIApplicationMain + 340
19 SwiftUI 0x195b43e30 closure #1 in KitRendererCommon(:) + 168
20 SwiftUI 0x195b43d60 runApp(:) + 100
21 SwiftUI 0x195b43c44 static App.main() + 180
22 AnchorNet3.debug.dylib 0x1025e97bc static MainApp.$main() + 40
23 AnchorNet3.debug.dylib 0x1025eaacc __debug_main_executable_dylib_entry_point + 12
24 dyld 0x1b7352de8 start + 2724
Thread 1 name: com.apple.CoreMotion.MotionThread
Thread 1:
0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424
3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24
4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212
6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
7 CoreFoundation 0x191259814 CFRunLoopRun + 64
8 CoreMotion 0x19e89cc5c 0x19e88d000 + 64604
9 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136
10 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8
Thread 2 name: com.apple.uikit.eventfetch-thread
Thread 2:
0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424
3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24
4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212
6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588
7 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
8 Foundation 0x18ff24e24 -[NSRunLoop(NSRunLoop) runUntilDate:] + 64
9 UIKitCore 0x193e22a74 -[UIEventFetcher threadMain] + 420
10 Foundation 0x18feb4194 NSThread__start + 724
11 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136
12 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8
Thread 3 name: com.apple.SwiftUI.AsyncRenderer
Thread 3 Crashed:
0 libsystem_kernel.dylib 0x1e274162c _kernelrpc_mach_port_allocate_trap + 8
1 libsystem_kernel.dylib 0x1e2748478 mach_port_allocate + 36
2 QuartzCore 0x192d4552c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 13596
3 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648
4 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88
5 CoreFoundation 0x19119f894 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 36
6 CoreFoundation 0x19119f3e8 __CFRunLoopDoObservers + 552
7 CoreFoundation 0x1912462c0 CFRunLoopRunSpecific + 664
8 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
9 Foundation 0x18fdc4500 -[NSRunLoop(NSRunLoop) run] + 64
10 SwiftUI 0x195c276d8 specialized static DisplayLink.asyncThread(arg:) + 792
11 SwiftUI 0x195c273a8 @objc static DisplayLink.asyncThread(arg:) + 72
<>
Hi all,
Our company has an application that runs on several machines, this app is launched via a deamon that keeps it alive.
One of the feature of this app, is to start a headless electron application to run some tests. When spawning this electron application with the new arm64 OS, we are getting this issue:
Silent Test Agent Worker exited with code: 133
[ERROR] [75873:0205/135842.347044:ERROR:mach_port_rendezvous.cc(384)] bootstrap_look_up com.hivestreaming.silenttestagent.MachPortRendezvousServer.1: Permission denied (1100)
[ERROR] [75873:0205/135842.347417:ERROR:shared_memory_switch.cc(237)] No rendezvous client, terminating process (parent died?)
[ERROR] [75872:0205/135842.347634:ERROR:mach_port_rendezvous.cc(384)] bootstrap_look_up com.hivestreaming.silenttestagent.MachPortRendezvousServer.1: Permission denied (1100)
[ERROR] [75872:0205/135842.347976:ERROR:shared_memory_switch.cc(237)] No rendezvous client, terminating process (parent died?)
Both application (main app and electron one) are signed and notarized, but it seems that there is some other permission issue.
If we run the electron application manually, all runs as expected.
I added the crash report as attachment
CrashReport.log
I have a weird issue with our Endpoint Security extension.
A couple of the checks we do require calling into Apple frameworks (Security, Disk Arbitration) and these checks can happen early in the boot process. On macOS 13 (and possibly earlier), sometimes these calls get stuck and never return. When this happens, the kernel will kill the extension and this generates a crash log. This adds significant time to the boot, enough that people notice. In every case, the thread where the call into the Apple framework occurred shows that the thread is stuck in mach_msg2_trap(), which I now understand means it's likely waiting on an event or message.
Now here's where things get weird. I discovered that if I shunt the check off onto a Thread subclass and put it in a DispatchGroup (perhaps the wrong primitive), then wait() on that group with my own timeout, the thread will get unstuck within a couple hundred milliseconds of the timeout. The timeout can be a couple of seconds or longer. In every case, the thread unblocks, returns from mach_msg2_trap() and the original call finishes as expected.
Is there a rational explanation for this behavior? Am I crazy to even consider shipping this workaround?
MacOS Version: 14.7.2
macOS SDKs:
macOS 14.5 -sdk macosx14.5
I am working on a sample program for validation Against:
Team Identifier
Developer ID
I started with validating Team Identifier, but my validation is not working and it is allowing to launch programs which are not matching the team identifier in the signature.
Below is my code:
func verifyExecutableWithLCR(executablePath: String, arguments: [String]) -> Bool {
let task = Process()
task.launchPath = executablePath
task.arguments = arguments
if #available(macOS 14.4, *) {
print("launchRequirementData is available on this system.")
do {
let req = try OnDiskCodeRequirement.allOf {
TeamIdentifier("ABCDEFGHI")
//SigningIdentifier("com.***.client.***-Client.****")
}
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let requirementData = try encoder.encode(req)
task.launchRequirementData = requirementData
print("launchRequirementData is set.")
try task.run()
print("[SUCCESS] Executable passed the code signature verification.")
return true
} catch {
print("[ERROR] Code signature verification failed: \(error.localizedDescription)")
return false
}
} else {
print("[WARNING] launchRequirement is not available on this macOS version.")
return false
}
}
Could you please help me in identifying whay am I doing wrong here?
Hi! I've been developing iOS and macOS apps for many years, but now I am looking to dive into smth i have never touched before, namely privileged helpers, and i am struggling hard trying to find my footing.
Here’s my use case: I have a CLI tool that requires elevated privileges. I want to create a menu bar app that can interact with this tool, but I’m struggling to find solid documentation or examples of how to accomplish this using SMAppService. I might just be missing something obvious.
If anyone could point me toward relevant documentation, examples, articles, tutorials, or even a WWDC session that covers running privileged helpers with SMAppService, I would greatly appreciate it.
Thanks in advance!
This is the functionality I am trying to achieve with libxpc:
There's one xpc server and two xpc clients. When the xpc server receives a particular dictionary item from clientB, the server needs to send a response to both clientA and clientB.
This is the approach I am currently using:
First, clientA creates a dictionary item that indicates that this item is from clientA. Now, clientA sends this dictionary to server. When server receives this item, it stores the connection instance with clientA in a global variable. Next, when clientB sends a particular dictionary item, server uses this global variable where it perviously stored clientA's connection instance to send a response back to clientA, alongside clientB.
Only one edge case I can see is that when clientA closes this connection instance, server will be trying to send a response to an invalidated connection.
Question:
Is this approach recommended? Any edge cases I should be aware of? Is there any better way to achieve this functionality?
I’m currently porting a Chrome Extension to Safari and integrating it with native messaging in a Safari Web Extension. As part of this, I’m building a proxy to forward messages between the web extension and a socket in another application, both ways. Additionally, the socket occasionally broadcasts messages that also need to be sent to the web extension.
The issue I’m facing is that the app extension terminates whenever I call context.completeRequest(returningItems: nil), which prevents me from listening for incoming messages from the socket (I'm using the Network Framework). To work around this, I’ve tried not calling context.completeRequest(returningItems: nil), which keeps the app extension running. However, I’m unsure if this is the right approach—currently, I’m simply ignoring the response and relying entirely on SFSafariApplication.dispatchMessage.
According to the documentation, the app extension lifecycle ends when the system terminates it, but I need to keep the socket listener active.
Has anyone encountered a similar issue, or does anyone have suggestions for maintaining the socket connection while adhering to the app extension lifecycle?
Any insights would be greatly appreciated!
I have followed this post for creating a Launch Agent that provides an XPC service on macOS using Swift-
post link - https://rderik.com/blog/creating-a-launch-agent-that-provides-an-xpc-service-on-macos/
In the swift code the interface of the XPC service is defined by protocols which makes the code nice and neat. I want to implement the XPC service using C APIs for XPC, and C APIs send and receive messages using dictionaries, which need manual handling with conditional statements.
I want to know if its possible to go with the protocol based approach with C APIs.
How to execute code on main app when interacted with a live activity, given that they are already interactable.
is there a way without opening the app?
what are the best ways?
I have several processes maintaining NSXPConnection to an XPC service. The connections are bi-directional. Each side service and clients) of the connection exports an object, and an XPCInterface. The @protocols are different - to the service, and from the service to clients.
So long as all the "clients" fully implement their "call-back" @protocol, there's no problem. All works fine.
However - If a client does NOT implement a method in the "call back protocol", or completely neglects to export an object, or interface - and the service attempts to call back using the nonexistent method -- the XPC connection invalidates immediately.
So far - expected behaviour.
However, if I want the service to behave to the client a little like a "delegate" style -- and check first whether the client "respondsToSelector" or even - supports an interface BEFORE calling it, then this doesn't work.
When my XPC service tries the following on a client connection:
if (xpcConnection.remoteObjectInterface == nil)
os_log_error(myXPCLog, "client has no remote interface);
the condition is never met - i.e. the "remoteObjectInterface is never nil even when the client does NOT configure its NSXPCConnection with any incoming NSXPCInterface, and does not set an "exportedObject"
Furthermore, the next check:
if ([proxy respondsToSelector:@selector(downloadFiltersForCustomer:withReply:)]) {
}
will not only fail - but will drop the connection. The client side gets the invalidation with the following error:
<NSXPCConnection: 0x600000b20000> connection to service with pid 2477 named com.proofpoint.ecd: received an undecodable message for proxy 1 (no exported object to receive message). Dropping message.
I guess the "undecidable message" is the respondsToSelector - because the code doesn't get to attempt anything else afterwards, the connection drops.
Is there a way to do this check "quietly", or suffering only "interruption", but without losing the connection,
Hello, I'm developing a Mac application that uses a network extension. I'm trying to implement XPC to pass data between my main app and system extension and I'm using the SimpleFirewall demo app as a guide to do this. One thing I can't understand is how the ViewController in the SimpleFirewall main app has access to the class IPCConnection in the SimpleFirewallExtension without it being public and without SimpleFirewallExtension being imported in ViewController.
I am considering to use the BGAppRefreshTask mechanism, and while I think I have read and understood all documentation and hints in this forum about it (especially the limitations), the one thing I do not understand is: how can I debug it? I cannot find a way to trigger the BGAppRefreshTask execution reliably and immediately. I would have expected the Xcode Debug->Simulate Background Fetch menu to do this for me, but it only sends the app into the background.
I am working with the unmodified (except for a few added print()) ColorFeed sample code project from Apple, which schedules a task 15min into the future when it goes to the background. Using a real device, I have not managed to trigger execution of the BGAppRefreshTask more often than once a day so far.
Surely, there must be a way to trigger it much more often solely for debugging and development purposes (I am totally happy with all restrictions for the final app).
So what detail am I missing here?
Hi,
I'm trying to create a launch daemon that uses XPC to receive requests from an unprivileged app. Ultimately both components will be written in Go. For now I'm trying to write a PoC in Objective-C to make sure I get everything right, so I'm compiling / signing from the CLI, and writing plist files by hand -- I'm not using XCode.
My current daemon code is pretty much the same as the boilerplate code that XCode generates when creating a new 'XPC Service':
#import <stdio.h>
#include <xpc/xpc.h>
int main(int argc, char *argv[]) {
xpc_rich_error_t error;
dispatch_queue_t queue = dispatch_queue_create("com.foobar.daemon", DISPATCH_QUEUE_SERIAL);
xpc_listener_t listener = xpc_listener_create(
"com.foobar.daemon",
queue,
XPC_LISTENER_CREATE_NONE,
^(xpc_session_t _Nonnull peer) {
xpc_session_set_incoming_message_handler(peer, ^(xpc_object_t _Nonnull message) {
int64_t firstNumber = xpc_dictionary_get_int64(message, "firstNumber");
int64_t secondNumber = xpc_dictionary_get_int64(message, "secondNumber");
// Create a reply and send it back to the client.
xpc_object_t reply = xpc_dictionary_create_reply(message);
xpc_dictionary_set_int64(reply, "result", firstNumber + secondNumber);
xpc_rich_error_t replyError = xpc_session_send_message(peer, reply);
if (replyError) {
printf("Reply failed, error: %s", xpc_rich_error_copy_description(replyError));
}
});
},
&error);
if (error != NULL) {
printf("ERROR: %s\n", xpc_rich_error_copy_description(error));
exit(1);
}
printf("Created listener: %s", xpc_listener_copy_description(listener));
// Resuming the serviceListener starts this service. This method does not return.
dispatch_main();
return 0;
}
I'm compiling, signing and installing my daemon with the following commands:
build_foobar() {
clang -Wall -x objective-c -o com.foobar.daemon poc/main.m
codesign --force --verify --verbose --options=runtime \
--identifier="com.foobar.daemon" \
--sign="Mac Developer: Albin Kerouanton (XYZ)" \
--entitlements=poc/entitlements.plist \
com.foobar.daemon
}
install_foobar() {
sudo cp com.foobar.daemon /Library/PrivilegedHelperTools/com.foobar.daemon
sudo cp poc/com.foobar.daemon.plist /Library/LaunchDaemons/com.foobar.daemon.plist
sudo launchctl bootout system/com.foobar.daemon || true
sudo launchctl bootstrap system /Library/LaunchDaemons/com.foobar.daemon.plist
}
Here's the content of my entitlements.plist file:
<?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>com.apple.application-identifier</key>
<string>ABCD.com.foobar.daemon</string>
</dict>
</plist>
And finally, here's my launchd plist file:
<?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.foobar.daemon</string>
<key>Program</key>
<string>/Library/PrivilegedHelperTools/com.foobar.daemon</string>
<key>ProgramArguments</key>
<array>
<string>/Library/PrivilegedHelperTools/com.foobar.daemon</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>StandardOutPath</key>
<string>/tmp/com.foobar.daemon.out.log</string>
<key>StandardErrorPath</key>
<string>/tmp/com.foobar.daemon.err.log</string>
<key>Debug</key>
<true/>
</dict>
</plist>
Whenever I start my service using sudo launchctl start com.foobar.daemon, it exits with the following error message:
ERROR: Unable to activate listener: failed at listener activation with error 1 - Operation not permitted
System logs don't show anything interesting -- they're just repeating the same error message. I tried to add / remove some properties from both the entitlement and the launchd plist file but to no avail.
Any idea what's going wrong?