Skip to content

Roll back the heap zone when the guest's memory refuses a write - #50

Merged
colemancda merged 2 commits into
masterfrom
fix/heapzone-fault-rollback
Dec 1, 2026
Merged

colemancda merged 2 commits into
masterfrom
fix/heapzone-fault-rollback

Conversation

@colemancda

Copy link
Copy Markdown
Member

HeapZone leaked blocks and master pointers when its GuestMemory refused a write. On a real Mac a heap write can't fault, but BlueBox's checked guest memory can refuse one, and BlueBox now uses HeapZone as its application heap.

The leaks

  • newPointer(clear:) kept the block when clearing it failed.
  • newHandle released its master pointer, but not the block it had placed, when clearing the block or setting the master pointer failed.
  • takeMaster kept a new block of master pointers when zeroing it failed.
  • newEmptyHandle kept its master pointer live when writing it failed.
  • disposeHandle and freeBlock, used by emptyHandle, reallocateHandle and purging, forgot the block before writing the nil master pointer. A refused write left the guest's master pointer pointing at a block the zone had freed. disposeHandle had also already called resourceDisposed.
  • setHandleSize dropped the old block before copying the bytes and repointing the master pointer. A refused write lost the block's place.

The fix

Each path either writes to guest memory before changing the zone's records, or undoes the records if the write fails. Two outcomes differ from "nothing changed":

  • reallocateHandle: if the new block's address can't be written, the handle is left empty. The old block was already freed and its master pointer set to nil, so the zone and guest memory still agree.
  • Compaction: once a block's bytes have moved, a refused master-pointer write can't be undone. The zone keeps recording the block where its bytes are, so nothing is lost from its accounting, but that handle's master pointer in guest memory may be stale. This is documented on compactBlocks.

The failing call reports memAdrErr (-110), as before.

Testing

HeapZoneFaultTests uses a GuestMemory that refuses chosen writes. For each path it checks that freeBytes and largestBlock are unchanged, that the next handle or pointer is the one that would have come anyway, and that the handle's size, state and contents are intact. All eight of these tests fail without the fix.

swift test passes: all 16 test runs.

Follow-up in swift-pef

BlueBox's GuestHeap currently works around the clearing case itself. That workaround can go once this is merged.

@colemancda
colemancda merged commit 6b16336 into master Dec 1, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant