XNU, launchd & XPC — how macOS runs your code

macos · folio

In one line: XNU is a hybrid kernel: CMU’s Mach (tasks, threads, ports, VM, scheduler), BSD code from FreeBSD (processes, POSIX, VFS, sockets, signals) and IOKit (C++ drivers) in one address space. The kernel starts launchd as the first process; launchd owns every service name, holds its port, and starts the job when the first message arrives. XPC is launchd-managed IPC on top — how an app splits into small, separately sandboxed, crash-isolated helpers.

Download PDF Print view LaTeX source

XNU, launchd & XPC — how macOS runs your code — figure 1

Mach vs BSD — one process, two views

Mach (osfmk/)BSD (bsd/)
unittask: VM map + port spaceproc: pid, credentials, fds — 1:1 with its task
runsthreada pthread is a Mach thread
talksports + mach_msgpipes, sockets, signals
namesport name, local to one taskpid — reused; audit token adds a version
faultsexception → thread, then task, then host exception portsignal: BAD_ACCESS → SEGV (bad address) or BUS · BAD_INSTRUCTION → ILL · ARITHMETIC → FPE · BREAKPOINT → TRAP

Ports, rights, messages

A port is a kernel message queue; tasks hold rights to it under task-local names: receive (one holder, who dequeues) · send (many) · send-once (one message — replies) · port set (wait on many, like select) · dead name.

XNU, launchd & XPC — how macOS runs your code — figure 2
  • Task ports, capability strictly decreasing: control → read → inspect → name; also bootstrap (launchd), host, exception. Control ports are pinned. task_for_pid: debugger entitlement (admin dialog, 10-hour session) + a target with get-task-allow; SIP-protected processes refuse.
  • Hardened (platform binaries): service ports’ receive right is immovable; a reply port’s send-once right lets exactly one reply back, from that peer. Breach = guard exception.
  • MIG generates RPC stubs; XNU’s docs discourage new raw Mach code — use XPC.

IOKit, kexts, DriverKit

Devices and drivers sit in the IORegistry (ioreg). “Kexts are no longer recommended”: since macOS 11 third-party kexts load only at boot, from an Auxiliary Kernel Collection — on Apple silicon only in Reduced Security (1TR + admin password). DriverKit (macOS 10.15; M-series iPads, iPadOS 16): .dext drivers in user space, shipped inside an app — on the Mac installed as system extensions.

Memory pressure — macOS vs iOS

XNU, launchd & XPC — how macOS runs your code — figure 3
  • normal · warning · critical reach code via DispatchSource.makeMemoryPressureSource: relax caching / drop all caches. PROC_LIMIT_WARN fires at 80 % of a process’s limit.
  • Idle exit takes only opted-in (EnablePressuredExit), idle (no open transaction) daemons. Compressor full: kill the largest process if it holds > ½ of compressed pages, else a pcontrol action (kill, suspend, throttle); then “Out of Application Memory”.
  • Past a hard footprint limit: killed at once; past a soft one: a simulated crash.
  • Jetsam is the same subsystem everywhere: 210 priority levels, every process but launchd has one (0 idle · 100 foreground); RunningBoard moves apps between bands; most kills climb from the bottom. iOS swap is the freezer (suspended apps’ dirty memory to flash, band 75), plus app swap on M1-and-later iPads.

Traps

  • “XNU is a microkernel” — Mach, BSD and IOKit run in one kernel address space.
  • Daemonizing (daemon(3), fork + parent exits): launchd sees the job die.
  • KeepAlive true + a crashing binary = a respawn every 10 s.
  • setuid() in a root daemon is not “being the user”: bootstrap subset and audit session stay — use an agent.

launchd — first process (OS X 10.4)

The kernel execs /sbin/launchd. Daemon: one instance for all clients, system/, root, no UI. Agent: one per logged-in user, gui/<uid> (= login/<asid>), may show UI. pid/<pid> = the XPC services that process sees. <Label>.plist lives in ~/Library/LaunchAgents · /Library/LaunchAgents|Daemons (admin) · /System/Library/… (Apple).

Labelrequired; the unique job name
ProgramArgumentsargv for execvp — no shell
BundleProgrampath inside the app bundle (SMAppService only)
RunAtLoadstart once when loaded
KeepAlivetrue, or SuccessfulExit · Crashed · PathState… ORed
MachServicesbootstrap names; the job must check in
Socketslaunchd listens; launch_activate_socket hands over fds
StartIntervalevery N s — a firing during sleep is missed
StartCalendarIntervalcron-like — missed in sleep → once at wake
ThrottleIntervalspawn at most every N s (default 10)
ProcessTypeBackground · Standard · Adaptive · Interactive
EnablePressuredExitreclaimable when idle under pressure; ignored with KeepAlive true

Stop: SIGTERM, SIGKILL after ExitTimeOut — at once if no transaction is open (a message expecting a reply holds one). macOS 27: launchd refuses quarantined plists.

XPC — three kinds of service

launch agentlaunch daemonXPC service (bundled)
instances1 per logged-in user1 system-wide1 per client, dies with it
runs asthat userrootthe app’s user; sandboxed by default; never root
lives inLaunchAgents plistLaunchDaemons plistContents/XPCServices/X.xpc
reachmachServiceName:+ .privilegedserviceName: — that app only

  • A daemon cannot open a connection to a user process — it only answers. launchd SIGKILLs an idle XPC service: keep it stateless.
  • APIs: C libxpc (10.7) · NSXPCConnection (10.8): @objc protocol, void methods, one reply block, NSSecureCoding arguments · Swift XPCSession / XPCListener (macOS 14): Codable. The wire encoding is no ABI — never persist it.
  • Interruption: the peer exited or crashed — the connection still works, the next message relaunches it, state is gone. Invalidation: never connected, or invalidated — always the last handler; build a new connection.
  • Check the peer, not its pid — pids are reused and pid-then-lookup races; the audit token carries the pid version. Code requirement: C API (macOS 12), setCodeSigningRequirement (13), lightweight requirement (14.4), XPCPeerRequirement .isFromSameTeam() · .hasEntitlement(_:) (26).
struct Job: Codable { let png: Data; let px: Int }
struct Thumb: Codable { let data: Data }
// bundled service, main.swift
let l = try XPCListener(service: "com.example.app.Resizer") { req in
  req.accept { (job: Job) in Thumb(data: render(job)) } }
dispatchMain()
// app: the first message launches the service
let s = try XPCSession(xpcService: "com.example.app.Resizer")
let t: Thumb = try s.sendSync(Job(png: png, px: 512))

SMAppService — shipping a helper

macOS 13+; replaces SMJobBless (deprecated in 13) and SMLoginItemSetEnabled. The plist stays in the bundle — Contents/Library/LaunchDaemons/ (or LaunchAgents) with BundleProgram — and SMAppService.daemon(plistName: "com.example.helper.plist").register(). status: notRegistered · enabled · requiresApproval · notFound. A daemon needs the user’s authentication; approving it approves the bundle’s other helpers. One switch per app in Login Items; a plist outside the bundle joins its app’s switch with AssociatedBundleIdentifiers; sfltool dumpbtm lists them all. macOS 26+: tasks still running after the app quits trigger an allow / don’t-allow prompt.

Remember

Mach moves messages, BSD owns processes, launchd owns names — helpers start when called, die when idle, and trust audit tokens, not pids.

Report a problem ·Discuss this folio