Skip to content
systemcoding.dev
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.

A Linux program enters the kernel through one table of system calls. A macOS program enters through the same kind of instruction and lands in one of several tables, depending on a class encoded in the call number. Two of those tables matter in practice: BSD system calls, which implement POSIX, and Mach traps, which implement the primitive operations of the Mach layer, such as sending a message or asking for the task port. This post explains how the kernel tells them apart on Apple silicon and Intel, what each table holds, how to observe both from user space, and why the supported interface is the C library and not the numbers. It sits under the macOS kernel internals guide, and the tables belong to the two layers described in XNU architecture.

One entry instruction, several dispatch tables

On Apple silicon (arm64), user code enters the kernel with svc #0x80, and the system call number goes in register x16. On Intel (x86-64) it uses the syscall instruction, with the number in rax. The arguments follow the ordinary calling convention of the architecture, in x0 to x5 on arm64 and rdi, rsi, rdx, r10, r8, r9 on x86-64.

The kernel's trap handler examines the number. On arm64, the sign of x16 selects the class directly: a negative number is a Mach trap and a positive number is a BSD system call. On x86-64, the high byte of the 32-bit number encodes the class, defined in the kernel's SYSCALL_CLASS_* constants:

ClassValueDispatch to
None0Invalid
Mach1mach_trap_table
Unix (BSD)2sysent
Machine-dependent3Architecture-specific calls
Diagnostic4Diagnostic calls, normally unavailable

On x86-64 a Unix call number is 0x2000000 | number, so write, which is call 4, is 0x2000004. That constant appears in assembly on Intel Macs, and it is why code ported from Linux, which uses plain numbers, fails with the wrong results until the class is added. The same call on arm64 is plain positive 4.

The details differ by architecture, but the structure is the same on both: one gate, a class, and a table per class.

The BSD table

BSD system calls are the ones documented in section 2 of the manual pages. The kernel's table, sysent, is generated at build time from bsd/kern/syscalls.master in the XNU source, a text file where each line gives the call number, the audit event, the argument structure and the C prototype. Reading that file is the fastest way to see what the kernel offers: every open, read, mmap, ioctl and fork is there, along with calls with no Linux equivalent such as getattrlist, fsgetpath and necp_open.

Each entry names the kernel function that implements it, for instance sys_write or read_nocancel. The _nocancel variants exist because POSIX makes some calls cancellation points for threads, and the library chooses the plain or the no-cancel entry depending on the thread's cancellation state. The result convention is the BSD one: the kernel function returns an errno value, and the trap handler converts it into a flag and a value that the library stub turns into -1 plus errno. On arm64 the carry flag in the condition register signals an error and x0 holds the errno; on x86-64 the carry flag in rflags does the same job with rax.

BSD calls are the stable, documented surface in the sense that their semantics are specified by POSIX and by Apple's man pages. The numbers behind them are not stable.

The Mach table

Mach traps are a much smaller set, and each is a primitive for the Mach abstractions. The table, mach_trap_table, is in osfmk/kern/syscall_sw.c of the XNU source. Its entries include:

TrapPurpose
mach_reply_portAllocate a reply port for the thread
thread_self_trapReturn the send right to the calling thread's port
task_self_trapReturn the send right to the calling task's port
host_self_trapReturn the host port
mach_msg_trapSend and receive a message
mach_msg_overwrite_trapThe same, with a receive buffer you supply
semaphore_signal_trap, semaphore_wait_trapMach semaphore operations
_kernelrpc_mach_vm_allocate_trap and friendsFast paths for the most common VM calls
swtch, swtch_pri, thread_switchYield the processor

The list is short because most Mach operations are not traps at all. They are messages. When you call mach_vm_allocate, the library packs a request, sends it with mach_msg_trap to the task's port and waits for the reply. The kernel handles it as an RPC to a kernel object, with the routine dispatch generated by MIG. Traps exist for the few operations that are too frequent or too fundamental to go through that path: sending and receiving messages themselves, getting your own ports and, in newer releases, direct traps for the hottest VM routines such as mach_vm_allocate so that allocation need not pay for a message.

Mach traps return kern_return_t values directly in x0 or rax, with KERN_SUCCESS as zero. They do not use the carry-flag convention and they do not set errno.

Seeing both from user space

The easiest way to watch the split is to trace a small program. dtruss, a DTrace wrapper, shows both kinds, subject to System Integrity Protection for protected binaries. For your own compiled program it works with sudo:

hello.cc
#include <stdio.h>
#include <unistd.h>

int
main(void)
{
	write(1, "hi\n", 3);
	return 0;
}
Shell
cc hello.c -o hello
sudo dtruss -f ./hello 2>&1 | grep -E 'write|mach_|task_'
Text
write(0x1, "hi\n\0", 0x3)		 = 3 0

The listing is trimmed to what the filter keeps, and the exact lines vary by release. dtruss reports BSD system calls by name. For the Mach side, trace with sudo dtrace -n 'mach_trap*:::entry' where the provider is available, or use the -n options of tools such as Instruments' system trace. On a current release, restrictions on tracing mean you often cannot observe Apple's own binaries at all, so practice on programs you built.

A second way to see the class is to look at the calling stubs in the C library. Disassemble write in the system library, and you find a short routine that loads the number into x16 and executes svc #0x80:

Shell
otool -tv /usr/lib/system/libsystem_kernel.dylib | grep -A6 '^_write:'
Text
_write:
	mov	x16, #0x4
	svc	#0x80
	b.lo	0x...
	stp	x29, x30, [sp, #-0x10]!
	...
	b	_cerror
	ret

On the shared cache the library is not a separate file on disk on recent releases, so use dyld_info or load the library into a debugger to see the same stub. The pattern is the useful part: mov x16, #4 and svc #0x80 is a BSD write, the conditional branch on the carry flag handles the error, and _cerror stores errno. A Mach trap stub, such as mach_reply_port, has mov x16, #-26 instead, the negative number.

Why you should not issue them yourself

On Linux, calling syscall(SYS_write, ...) or writing raw assembly works and is a supported technique. On macOS it is neither. Apple's position is that the interface to the kernel is the C library, libSystem, and that the numbers can change between releases. Three concrete facts follow from that.

The syscall(2) function is deprecated and marked so in the SDK headers, and calling it produces a compiler warning. The man page directs you to the wrapper functions.

Static linking of the C library is not supported. A binary built that way would embed system call numbers that the next release may renumber or remove, which is why macOS provides no static libSystem.

Direct traps from your own assembly bypass behavior that the library adds around the call, such as the errno conversion, cancellation handling and the versioned entry points that keep old binaries working. Go's runtime hit this directly: it used raw system calls on macOS, and after incompatible changes in a release it moved to calling libSystem through the dynamic linker, a change documented in the Go release notes for Go 1.12. The lesson generalizes. A language runtime that must run on macOS links libSystem and calls its functions.

If you need an operation that has no wrapper, the supported path is to ask Apple for a public API, or to use the Mach and IOKit interfaces that are documented. Do not hard-code numbers from syscalls.master.

A closer look at the cost difference

The two tables differ in what they do per call. A BSD call such as getpid is a short path: the trap handler fetches the proc, reads the PID and returns. A message-based Mach call, such as an RPC to a task port, costs a send, a kernel-side routine dispatch, a receive of the reply and an unmarshal, several steps instead of one. This is why Apple added direct traps for hot Mach operations, and why a loop that calls mach_vm_allocate a million times is slower than the equivalent loop of mmap calls, which is a direct BSD call that then calls into the VM layer.

We deliberately state this as design, not as a measurement. The specific cost depends on the chip, the release and whether the call hits a fast path, so if the difference matters to your program, measure it on the hardware you target, and prefer the high-level API that Apple recommends for the operation, because it is the one they keep fast.

Reading the source

Both tables are visible in the open-source tree and make a good first exercise. Open bsd/kern/syscalls.master and find a call you know, such as getpid. Note the number, the function name and the argument structure. Then search bsd/kern for that function to see its implementation. Open osfmk/kern/syscall_sw.c for the Mach table and compare the shape: Mach entries list the number of arguments and the function pointer, with no audit event, since they belong to a different part of the kernel. Check the tag that matches your release, because the tables change from one to the next, and assume the numbers in your copy are not the numbers on your machine.

Where this does not fit

This post describes how XNU dispatches calls, which is useful for reading kernel source, writing debuggers and understanding traces. It is not a recipe for bypassing the C library. If your aim is portability, remember that the other BSDs and Linux each have different tables, numbers and conventions, and that macOS is the only one of the group to also carry Mach. And on iOS and the other Apple platforms the same dispatch exists, with a stricter policy: apps may not use private calls, and the App Store review rejects binaries that do.

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.