Skip to content
systemcoding.dev
Kernels

Mach Ports and Messages Explained for macOS Developers

How Mach ports, port rights and mach_msg work on macOS 15, with a complete client and server in C using the bootstrap server, plus where XPC sits on top.

10 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the macOS, Linux and C logos.

Everything on macOS that crosses a process boundary, from a window server request to a launch daemon call to a debugger reading memory, ends up as a message sent to a Mach port. Most developers never see one, because Foundation, XPC and Dispatch hide them, but the behavior of those layers is the behavior of ports: why a service starts on demand, why a crashed server wakes its clients and why a debugger needs a special right to touch another process. This post explains ports and port rights on macOS 15, the structure of a message, and then builds a working server and client in C that find each other through the bootstrap server. It deepens the section on ports in the macOS kernel internals guide, and it complements the older, application-focused Mach IPC post on using ports from a program.

A port is a queue, a right is a capability

A port is a kernel object: a bounded queue of messages. Exactly one task holds the receive right for a port and may dequeue its messages. Any number of tasks may hold send rights and enqueue. A third kind, the send-once right, allows one message and then disappears, and is how a server gives a client the ability to reply.

A task never sees the port itself. It sees a port name, a small integer of type mach_port_t that indexes the task's own port name space. The same port has a different name in each task that holds a right to it, and a name has meaning only inside the task that owns it. When a message carries a right from one task to another, the kernel translates it: it removes or copies the right from the sender's name space and inserts it into the receiver's, assigning a new name there.

Because rights are the only way to reach a port, they are capabilities in the strict sense. You cannot guess a port, and you cannot forge a right. A task has the authority it was given and the kernel enforces it. Two system-wide consequences follow. A dead name appears when the receive right is destroyed, for instance when the server exits, and every holder of a send right is converted to a dead name that returns MACH_SEND_INVALID_DEST on use, which is the notification clients use to detect a crash. And no-more-senders notifications let a server learn that every client has gone, so it can clean up.

Anatomy of a message

A message begins with a fixed header, mach_msg_header_t, in <mach/message.h>:

FieldPurpose
msgh_bitsRights disposition for the destination and the reply port, plus flags such as the complex-message bit
msgh_sizeTotal size in bytes
msgh_remote_portDestination, on send. The reply port, after receive
msgh_local_portReply port, on send. The port received on, on receive
msgh_voucher_portAttribute and accounting voucher, usually null
msgh_idA number the sender chooses to say what the message means

A simple message has only data after the header. A complex message sets MACH_MSGH_BITS_COMPLEX and is followed by a descriptor count and descriptors: port descriptors that carry rights, out-of-line memory descriptors that move whole pages by remapping instead of copying, and others. On receive, the kernel appends a trailer after the body, whose format you choose with an option flag. The audit trailer, mach_msg_audit_trailer_t, contains the sender's audit token, which identifies the sender's user, process and, through audit_token_to_pid, its PID. That is how a server can check who it is talking to without trusting a field the client filled in.

The single call that moves messages is mach_msg, and its options choose among send, receive and send-then-receive:

c
mach_msg_return_t mach_msg(mach_msg_header_t *msg,
    mach_msg_option_t option,
    mach_msg_size_t send_size,
    mach_msg_size_t rcv_size,
    mach_port_name_t rcv_name,
    mach_msg_timeout_t timeout,
    mach_port_name_t notify);

MACH_SEND_MSG sends, MACH_RCV_MSG receives, and both together send a request and wait for the reply in one trap, which is what generated client stubs use. MACH_SEND_TIMEOUT and MACH_RCV_TIMEOUT bound the wait, with the timeout in milliseconds.

The bootstrap server

Two unrelated tasks need a way to obtain a send right to each other's ports. The answer is a port everyone inherits: when a task starts, it receives a send right to its bootstrap port, a port served by launchd. A server registers a service name with the bootstrap server and hands it a send right, and a client looks the name up and receives a send right in return. The functions are in <servers/bootstrap.h>: bootstrap_check_in for a server that was launched on demand and has its receive right waiting, and bootstrap_look_up for a client.

A launch daemon or agent declares its Mach service names in its property list under the MachServices key. launchd then creates the receive right itself and holds it. When a client's first message arrives for that name, launchd starts the process and the process claims its port with bootstrap_check_in. Messages sent before the server finished starting wait in the queue. This is the reason services start lazily and why a request never fails because the daemon was not running yet.

For a small experiment you can also register a name from a normal process with bootstrap_register, but that function is deprecated for ordinary use and the check-in route through a launchd job is the supported way. The example below uses a launchd job description for the server.

A server and a client

The pair below implements a service named com.example.adder that adds two integers. First the shared message definitions:

adder.hc
#include <mach/mach.h>

#define ADDER_SERVICE "com.example.adder"
#define ADDER_ID_REQUEST 3000

typedef struct {
	mach_msg_header_t header;
	int32_t           a;
	int32_t           b;
} adder_request_t;

typedef struct {
	mach_msg_header_t header;
	int32_t           sum;
} adder_reply_t;

typedef struct {
	mach_msg_header_t  header;
	int32_t            a;
	int32_t            b;
	mach_msg_trailer_t trailer;
} adder_request_rcv_t;

The server checks in with the bootstrap server, receives requests and replies on the reply port that came with each:

server.cc
#include <servers/bootstrap.h>
#include <stdio.h>
#include <string.h>
#include "adder.h"

int
main(void)
{
	mach_port_t port;
	kern_return_t kr;

	kr = bootstrap_check_in(bootstrap_port, ADDER_SERVICE, &port);
	if (kr != KERN_SUCCESS) {
		fprintf(stderr, "check_in: %s\n", bootstrap_strerror(kr));
		return 1;
	}

	for (;;) {
		adder_request_rcv_t req;
		adder_reply_t rep;

		memset(&req, 0, sizeof(req));
		kr = mach_msg(&req.header, MACH_RCV_MSG, 0, sizeof(req),
		    port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
		if (kr != MACH_MSG_SUCCESS)
			continue;
		if (req.header.msgh_id != ADDER_ID_REQUEST)
			continue;

		memset(&rep, 0, sizeof(rep));
		rep.header.msgh_bits =
		    MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0);
		rep.header.msgh_size = sizeof(rep);
		rep.header.msgh_remote_port = req.header.msgh_remote_port;
		rep.header.msgh_id = req.header.msgh_id + 100;
		rep.sum = req.a + req.b;
		mach_msg(&rep.header, MACH_SEND_MSG, sizeof(rep), 0,
		    MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
	}
}

The reply uses the right the client sent. When the client sets its reply port with MACH_MSG_TYPE_MAKE_SEND_ONCE, the kernel delivers it to the server as a send-once right in msgh_remote_port, and the server answers with MACH_MSG_TYPE_MOVE_SEND_ONCE, which spends that right. The client looks up the service, creates a reply port and sends a request with a combined send-and-receive:

client.cc
#include <servers/bootstrap.h>
#include <stdio.h>
#include <string.h>
#include "adder.h"

int
main(void)
{
	mach_port_t server, reply;
	kern_return_t kr;
	struct {
		adder_request_t   req;
	} out;
	struct {
		adder_reply_t      rep;
		mach_msg_trailer_t trailer;
	} in;

	kr = bootstrap_look_up(bootstrap_port, ADDER_SERVICE, &server);
	if (kr != KERN_SUCCESS) {
		fprintf(stderr, "look_up: %s\n", bootstrap_strerror(kr));
		return 1;
	}
	mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &reply);

	memset(&out, 0, sizeof(out));
	out.req.header.msgh_bits =
	    MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE);
	out.req.header.msgh_size = sizeof(out.req);
	out.req.header.msgh_remote_port = server;
	out.req.header.msgh_local_port = reply;
	out.req.header.msgh_id = ADDER_ID_REQUEST;
	out.req.a = 40;
	out.req.b = 2;

	kr = mach_msg(&out.req.header, MACH_SEND_MSG | MACH_RCV_MSG,
	    sizeof(out.req), sizeof(in), reply,
	    MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
	if (kr != MACH_MSG_SUCCESS) {
		fprintf(stderr, "mach_msg: %s\n", mach_error_string(kr));
		return 1;
	}
	printf("40 + 2 = %d\n", in.rep.sum);
	return 0;
}

To run it, describe the server to launchd with a property list placed in ~/Library/LaunchAgents/com.example.adder.plist:

XML
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>com.example.adder</string>
	<key>ProgramArguments</key>
	<array>
		<string>/Users/you/adder/server</string>
	</array>
	<key>MachServices</key>
	<dict>
		<key>com.example.adder</key>
		<true/>
	</dict>
</dict>
</plist>

Compile with cc server.c -o server and cc client.c -o client, load the agent with launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.adder.plist, and run the client. The server is started the first time the client looks up the name.

Text
40 + 2 = 42

A few details in that code deserve a note. The receive structure carries a trailer, so its size is larger than the request that was sent, and rcv_size must account for it or the call fails with MACH_RCV_TOO_LARGE. The reply id, the request id plus one hundred, follows a MIG convention where replies are numbered 100 above requests. The msgh_bits pair names the right the destination needs (COPY_SEND for a right the client keeps) and the right to give for the reply port (MAKE_SEND_ONCE, the kernel makes one from the receive right). And nothing here validates the client: a real server would read the audit trailer's token and decide whether to answer, which is the check that matters for anything privileged.

Generated stubs and where XPC fits

Hand-written messages do not scale. For many years Apple used MIG, the Mach Interface Generator, which reads a .defs description of routines and produces client and server stubs that pack and unpack messages, with the server dispatch loop. Kernel interfaces such as the Mach VM and task calls are MIG routines, which is why mach_vm_allocate looks like a normal function call and travels as a message to a task port.

Application code today mostly uses XPC, built on Mach ports and launchd. An XPC service name is a Mach service name, xpc_connection_create_mach_service looks it up through the bootstrap server, and messages are serialized dictionaries that carry file descriptors and shared memory, with the audit token available for credential checks. XPC adds connection lifecycle, automatic restart handling and code-signing requirements. When you debug an XPC connection that does not connect, think in port terms: is the name registered, is the service allowed in this bootstrap namespace and is the right still alive?

Task ports and why debuggers need them

A task port, obtained from task_for_pid, mach_task_self or a message, is a send right to the kernel object representing a process. Holding it lets you call mach_vm_read, mach_vm_write, thread_get_state and the other functions that debuggers use. That power is why the kernel guards task_for_pid with policy: the caller must be root or the same user and, more importantly, the target must permit it. Processes protected by System Integrity Protection, hardened-runtime processes without the com.apple.security.get-task-allow entitlement, and Apple platform binaries refuse it, and a debugger needs its own entitlement to attach to a process. On a current system you will meet this as task_for_pid returning KERN_FAILURE with no explanation. The policy is by design, not a bug in your code.

Where this does not fit

Raw Mach messaging is a niche skill. For application IPC, use XPC, or Distributed Objects equivalents, since they handle serialization, lifecycle and code-signing checks that a hand-built protocol will omit. Apple documents the Mach interfaces as unstable: many of the <mach/*.h> functions are marked deprecated in the SDK, bootstrap_register has been discouraged for years, and the message formats of system services change without notice. Use ports directly when you are building a debugger, profiler or low-level tool that has to work with the kernel's own interfaces, and expect to revisit the code with each major release. Never depend on another vendor's undocumented Mach message ids.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.