A shared-memory object can own references before it has backing storage. A historical XNU POSIX shared-memory path incorrectly coupled those states: the close callback returned early for an unallocated object, while its per-open node was still freed and the object count remained unchanged.
Tracking the name cache, independent open descriptions, and backing storage separates two stages: a reference leak on the first close, and premature-release conditions after a fixed-width counter wraps. Wraparound amplifies the problem; the first missing decrement breaks the original invariant.
Pin source snapshots, not an inferred release range
This analysis uses Apple's public xnu-4903.221.2 source for the old path and xnu-4903.270.47 for comparison. Their commit prefixes are cc9a63552421 and 494ffe1c29d3. The intermediate xnu-4903.241.1 snapshot also retains the early return.
| Item | xnu-4903.221.2 | xnu-4903.270.47 |
|---|---|---|
| Object counter | unsigned int pshm_usecount | Managed through explicit reference helpers |
| Count after successful creation | One existence reference, then one increment | Initialized to 2 |
| Close callback | pshm_close(pinfo, 0) | pshm_deref(pinfo) |
| Unallocated object | Early EINVAL return | Allocation state does not block dereference |
| Increment limit | Direct increment on the discussed cache hit | pshm_ref returns EMFILE at UINT_MAX |
These are behavioral observations about source snapshots. An open-source import date is not the first patch date, and the comparison does not establish a complete affected iOS/macOS release range. No historical kernel was booted, billions of syscalls executed, or privilege-escalation chain reproduced here. Old implementation
Names, open descriptions, and backing storage
After successful creation, pshminfo already exists. ftruncate enters the length-setting and backing-allocation path. The case of interest has no PSHM_ALLOCATED flag, uses no mmap, and introduces no additional mapping lifetime.
flowchart TB
N["Name cache"] --> P["pshminfo management object"]
F["fileglob from independent shm_open"] --> W["pshmnode"]
W --> P
P -. "ftruncate establishes allocation" .-> M["Backing memory objects"]
N -. "shm_unlink drops name reference" .-> U["Name removed"]
F -. "Final close callback drops reference" .-> C["Open description released"]
“Descriptor reference” is shorthand here. An independent shm_open and a descriptor produced by dup occupy different layers. Generic file code invokes the type-specific close callback when the last fileglob reference is dropped. The model below excludes dup, fork, mappings, and concurrent operations.
The old creation path starts pshm_usecount at 1 and increments after successful cache insertion, reaching 2 on the first successful open. Reopening an existing name increments in pshm_cache_search(..., addref=1). Both execution points matter more than a comment asserting an initial count.
Cleanup continues after the error
The old pshm_closefile holds the shared-memory subsystem lock and calls pshm_close with dropref=0. Without PSHM_ALLOCATED, the latter returns EINVAL before decrementing the reference.
This compressed control-flow model omits locking, MAC labels, and backing-object iteration. It is not a drop-in kernel patch:
# Control-flow model, not kernel source.
def close_reference(pinfo, dropref):
if not dropref and not pinfo.allocated:
return "EINVAL"
pinfo.usecount -= 1
if pinfo.removed and pinfo.usecount == 0:
release(pinfo)
return "OK"
def close_open_description(node):
result = close_reference(node.pinfo, dropref=False)
release(node) # independent of result
return resultFreeing the management object also requires PSHM_REMOVED, not just a zero count. The immediate mismatch occurs outside that function: pshm_closefile frees the pshmnode regardless of the inner result.
Generic close code does not interpret the error as a request to restore the fd. close_internal_locked releases the slot, runs close processing, and frees the fileproc; closef_locked calls fo_close and then frees the fileglob. EINVAL and the end of descriptor lifetime can therefore coexist. Generic close path
Failure cleanup has a different branch: an unsuccessful open returns its cache-lookup reference using dropref=1, which skips the allocation requirement. The finding concerns the close path after a successful open, not every error path.
From one leaked reference to counter wraparound
Retain the name and the original open description, then repeatedly open and close a temporary one. Each real temporary reference disappears while the recorded count gains one. After 255 iterations, only two holders remain, but the counter reads 2 + 0xff = 0x101.
The field is unsigned int: 32 bits in the Darwin data model discussed here. A 64-bit kernel does not make every integer 64 bits. Apple's data-model documentation
| Temporary open/close cycles | Recorded count | Real holders |
|---|---|---|
| 0 | 2 | Name and original open |
| 0xff | 0x101 | Name and original open |
| 0xfffffffe | 0 | Name and original open |
| 0xffffffff | 1 | Name and original open |
| Subsequent shm_unlink | 0 | Original open remains |
Reaching zero midway does not automatically free the object: temporary closes still return before dereference, and the named object remains discoverable. Another increment produces 1; shm_unlink then drops the name reference.
The old unlink path accepts PSHM_DEFINED, removes the cache entry, and frees pshminfo when the count reaches zero. The original pshmnode still points to it, establishing a dangling management-object pointer. This concerns a kernel management structure, not a previously mapped userspace data page.
Shrink the counter and compare behaviors
An 8-bit counter exposes the same invariant in 255 iterations. The test covers an unallocated old object, an allocated old object, repaired close behavior, and saturation rejection. Its 32-bit checks perform arithmetic only.
MASK32 = (1 << 32) - 1
assert 2 + 0xff == 0x101
assert (2 + MASK32) & MASK32 == 1
assert (((2 + MASK32) & MASK32) - 1) == 0
def cycle(count, allocated, fixed, bits=8):
limit = (1 << bits) - 1
if fixed and count == limit:
return count, "EMFILE"
count = (count + 1) & limit
if allocated or fixed:
return count - 1, "OK"
return count, "EINVAL"
def run_case(allocated, fixed):
count = 2
real_refs = {"name", "original_open"}
for _ in range(255):
count, status = cycle(count, allocated, fixed)
before_unlink = count
real_refs.remove("name")
count -= 1
return before_unlink, count, count == 0, real_refs
bug = run_case(allocated=False, fixed=False)
fixed = run_case(allocated=False, fixed=True)
allocated = run_case(allocated=True, fixed=False)
assert bug == (1, 0, True, {"original_open"})
assert fixed == allocated == (2, 1, False, {"original_open"})
assert cycle(255, False, True) == (255, "EMFILE")
print("32-bit arithmetic: PASS")
print("8-bit unallocated bug: 1 -> 0; original_open remains")
print("8-bit repaired / allocated: 2 -> 1; object retained")
print("saturation guard: 255 -> 255; EMFILE")
Actual output:
32-bit arithmetic: PASS
8-bit unallocated bug: 1 -> 0; original_open remains
8-bit repaired / allocated: 2 -> 1; object retained
saturation guard: 255 -> 255; EMFILEThe model treats zero after name removal as a release condition. It does not simulate allocators, locks, MAC checks, or address reuse. It verifies that the recorded count reaches zero while the real reference set is nonempty—not arbitrary read/write capability or reliable exploitation.
The repair enforces two different invariants
The later snapshot centralizes increments and decrements in pshm_ref and pshm_deref. Close and unlink both use the latter. Backing-storage allocation no longer decides whether an acquired reference is returned. Later implementation
- 1
Return every acquired reference
Unallocated objects are dereferenced too. Reaching zero releases backing objects and the management structure through one path.
- 2
Reject counter overflow
pshm_ref returns EMFILE at UINT_MAX. The caller does not treat failure as a successfully acquired reference.
- 3
Keep locking and lifetime consistent
Reference helpers require the subsystem lock. Backing-resource release drops it and restores the lock state afterward.
- 4
Clear outer pointers
The close callback clears fg_data and, after dereference, pnode->pinfo before freeing the node.
An overflow guard constrains wraparound but does not fix a missing decrement on each close. Repairing that close branch does not replace saturation policy at reference-acquisition sites. The two changes protect different invariants.
Regression cases should separately cover immediate close before allocation, repeated opens after allocation, unlink before final close, failed-open cleanup, counter saturation, and the additional lifetimes introduced by mappings and concurrency. Adding ftruncate to a caller only avoids one branch; it is not a kernel repair.