From 99e3c204c7c2e86a54c682d496326c0419b2c941 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:43 -0500 Subject: [PATCH 1/9] Add Mac OS 9 Memory Manager probe --- ReferenceTests/Retro68/MemoryManagerCapture.c | 223 ++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 ReferenceTests/Retro68/MemoryManagerCapture.c diff --git a/ReferenceTests/Retro68/MemoryManagerCapture.c b/ReferenceTests/Retro68/MemoryManagerCapture.c new file mode 100644 index 0000000..282d5b0 --- /dev/null +++ b/ReferenceTests/Retro68/MemoryManagerCapture.c @@ -0,0 +1,223 @@ +/* + * Captures the Memory Manager's rules for handles and pointers in the + * application heap, writing "MemoryManager.txt" next to itself. It refuses + * to run if that file is already there. Each line is a call, what it + * returned and MemError after it; the file is flushed after every line, so + * a call that crashes leaves the lines before it. + * + * It records sizes and their errors, empty and purged handles, the state + * bits HGetState gives, locking and purging, growing a locked block that + * another block follows, master pointer reuse, and the same calls on nil. + */ +#include +#include +#include +#include + +static short out; + +static void line(const char *text) +{ + long count = strlen(text); + FSWrite(out, &count, text); + count = 1; + FSWrite(out, &count, "\r"); + FlushVol(0, 0); +} + +static void note(const char *call, long value) +{ + char text[160]; + snprintf(text, sizeof text, "%s -> %ld (%08lX) MemError %d", call, value, (unsigned long)value, MemError()); + line(text); +} + +/* A call's own MemError, then the handle's size and GetHandleSize's. */ +static void sized(const char *call, Handle h) +{ + char text[160]; + short error = MemError(); + long size = GetHandleSize(h); + snprintf(text, sizeof text, "%s: MemError %d; GetHandleSize -> %ld", call, error, size); + line(text); +} + +static void pointerSized(const char *call, Ptr p) +{ + char text[160]; + short error = MemError(); + long size = GetPtrSize(p); + snprintf(text, sizeof text, "%s: MemError %d; GetPtrSize -> %ld", call, error, size); + line(text); +} + +static void state(const char *label, Handle h) +{ + char text[160]; + snprintf(text, sizeof text, "%s: master %s, HGetState %02X, size %ld", + label, *h ? "set" : "nil", (unsigned char)HGetState(h), (long)GetHandleSize(h)); + line(text); +} + +int main(void) +{ + static const unsigned char name[] = { 17, 'M','e','m','o','r','y','M','a','n','a','g','e','r','.','t','x','t' }; + Handle h, g, blocker, empty, a, b; + Ptr p; + long before; + int i; + + if (Create(name, 0, 'Grph', 'TEXT') != noErr) return 1; + if (FSOpen(name, 0, &out) != noErr) return 2; + + line("# Sizes"); + h = NewHandle(0); + note("NewHandle(0)", (long)h); + if (h) { state(" NewHandle(0)", h); DisposeHandle(h); } + h = NewHandle(-1); + note("NewHandle(-1)", (long)h); + h = NewHandle(0x7FFFFFFF); + note("NewHandle(0x7FFFFFFF)", (long)h); + h = NewHandle(0x00FFFFFF); + note("NewHandle(16 MB)", (long)h); + if (h) DisposeHandle(h); + h = NewHandleClear(7); + note("NewHandleClear(7)", (long)h); + note(" bytes zero", h && (*h)[0] == 0 && (*h)[6] == 0); + note(" GetHandleSize", GetHandleSize(h)); + SetHandleSize(h, -1); + sized("SetHandleSize(h, -1)", h); + SetHandleSize(h, 5); + sized("SetHandleSize(h, 5)", h); + SetHandleSize(h, -2); + sized("SetHandleSize(h, -2)", h); + SetHandleSize(h, 0); + sized("SetHandleSize(h, 0)", h); + note(" master pointer set", *h != 0); + SetHandleSize(h, 0x7FFFFFFF); + sized("SetHandleSize(h, 0x7FFFFFFF)", h); + DisposeHandle(h); + note("DisposeHandle(h)", 0); + + line("# State"); + h = NewHandle(16); + state("new", h); + HLock(h); state("HLock", h); + HPurge(h); state("HPurge", h); + HSetRBit(h); state("HSetRBit", h); + HUnlock(h); state("HUnlock", h); + HNoPurge(h); state("HNoPurge", h); + HClrRBit(h); state("HClrRBit", h); + HSetState(h, (SignedByte)0xFF); state("HSetState(FF)", h); + note(" MemError", 0); + HSetState(h, 0); state("HSetState(00)", h); + note("RecoverHandle(*h) == h", RecoverHandle(*h) == h); + + line("# Empty and purged"); + empty = NewEmptyHandle(); + note("NewEmptyHandle", (long)empty); + state(" empty", empty); + note(" GetHandleSize", GetHandleSize(empty)); + HLock(empty); note(" HLock", 0); state(" locked empty", empty); + HUnlock(empty); + HUnlock(empty); note(" HUnlock", 0); + HPurge(empty); note(" HPurge", 0); + HGetState(empty); note(" HGetState", 0); + SetHandleSize(empty, 10); + sized(" SetHandleSize(empty, 10)", empty); + state(" after", empty); + HPurge(h); HLock(h); + EmptyHandle(h); note("EmptyHandle(locked, purgeable)", 0); state(" after", h); + HUnlock(h); + EmptyHandle(h); note("EmptyHandle(unlocked, purgeable)", 0); state(" after", h); + ReallocateHandle(h, 12); note("ReallocateHandle(empty, 12)", 0); state(" after", h); + HNoPurge(h); + EmptyHandle(h); note("EmptyHandle(unpurgeable)", 0); state(" after", h); + ReallocateHandle(h, 12); + HLock(h); + ReallocateHandle(h, 20); note("ReallocateHandle(locked, 20)", 0); state(" after", h); + HUnlock(h); + ReallocateHandle(h, 20); note("ReallocateHandle(unlocked, 20)", 0); state(" after", h); + DisposeHandle(h); + DisposeHandle(empty); + note("DisposeHandle(empty)", 0); + + line("# Purging"); + a = NewHandle(1000); + HPurge(a); + before = (long)*a; + PurgeMem(0x7FFFFFFF); + note("PurgeMem(max)", 0); + note(" purgeable master pointer nil", *a == 0); + note(" GetHandleSize(purged)", GetHandleSize(a)); + DisposeHandle(a); + + line("# Growing a locked block"); + h = NewHandle(16); + blocker = NewHandle(16); + before = (long)*h; + HLock(h); + HLock(blocker); + SetHandleSize(h, 200000); + sized("SetHandleSize(locked, 200000)", h); + note(" moved", (long)*h != before); + HUnlock(h); + SetHandleSize(h, 200000); + sized("SetHandleSize(unlocked, 200000)", h); + note(" moved", (long)*h != before); + SetHandleSize(h, 8); + sized("SetHandleSize(shrink, 8)", h); + DisposeHandle(h); + HUnlock(blocker); + DisposeHandle(blocker); + + line("# Master pointer reuse"); + a = NewHandle(4); + DisposeHandle(a); + b = NewHandle(4); + note("NewHandle after DisposeHandle reuses the master pointer", a == b); + g = NewHandle(4); + for (i = 0; i < 3; ++i) { + Handle c = NewHandle(4); + DisposeHandle(c); + } + note(" again", 0); + DisposeHandle(b); + DisposeHandle(g); + + line("# Pointers"); + p = NewPtr(0); + note("NewPtr(0)", (long)p); + if (p) { note(" GetPtrSize", GetPtrSize(p)); DisposePtr(p); } + p = NewPtr(-1); + note("NewPtr(-1)", (long)p); + p = NewPtrClear(9); + note("NewPtrClear(9) GetPtrSize", GetPtrSize(p)); + SetPtrSize(p, 3); + pointerSized("SetPtrSize(3)", p); + SetPtrSize(p, -1); + pointerSized("SetPtrSize(-1)", p); + SetPtrSize(p, 5); + blocker = (Handle)NewPtr(16); + SetPtrSize(p, 200000); + pointerSized("SetPtrSize(200000) with a pointer after", p); + DisposePtr((Ptr)blocker); + DisposePtr(p); + note("DisposePtr", 0); + + line("# Nil"); + note("GetHandleSize(nil)", GetHandleSize(0)); + HLock(0); note("HLock(nil)", 0); + HUnlock(0); note("HUnlock(nil)", 0); + HPurge(0); note("HPurge(nil)", 0); + note("HGetState(nil)", (unsigned char)HGetState(0)); + SetHandleSize(0, 4); note("SetHandleSize(nil, 4)", 0); + EmptyHandle(0); note("EmptyHandle(nil)", 0); + DisposeHandle(0); note("DisposeHandle(nil)", 0); + DisposePtr(0); note("DisposePtr(nil)", 0); + note("GetPtrSize(nil)", GetPtrSize(0)); + + line("# Done"); + FSClose(out); + return 0; +} From 841b795b0cad94f202c27d949b89b47a5b3d46c7 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:43 -0500 Subject: [PATCH 2/9] Build the Memory Manager probe with Retro68 --- ReferenceTests/Retro68/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/ReferenceTests/Retro68/CMakeLists.txt b/ReferenceTests/Retro68/CMakeLists.txt index b09a680..11b900d 100644 --- a/ReferenceTests/Retro68/CMakeLists.txt +++ b/ReferenceTests/Retro68/CMakeLists.txt @@ -6,3 +6,4 @@ add_application(FileManagerCapture FileManagerCapture.c) add_application(RelStringCapture RelStringCapture.c) add_application(CatalogOrderCapture CatalogOrderCapture.c) add_application(HighLevelEventCapture HighLevelEventCapture.c HighLevelEventCapture.r) +add_application(MemoryManagerCapture MemoryManagerCapture.c) From c28f68b98a2f5131a2942f9151c0a1480ae6a1c2 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:43 -0500 Subject: [PATCH 3/9] Add Mac OS 9.2.2 Memory Manager capture --- ReferenceTests/Retro68/MemoryManager-macos-9.2.2-ppc.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 ReferenceTests/Retro68/MemoryManager-macos-9.2.2-ppc.txt diff --git a/ReferenceTests/Retro68/MemoryManager-macos-9.2.2-ppc.txt b/ReferenceTests/Retro68/MemoryManager-macos-9.2.2-ppc.txt new file mode 100644 index 0000000..3e6d0d3 --- /dev/null +++ b/ReferenceTests/Retro68/MemoryManager-macos-9.2.2-ppc.txt @@ -0,0 +1 @@ +# Sizes NewHandle(0) -> 522248032 (1F20DF60) MemError 0 NewHandle(0): master set, HGetState 00, size 0 NewHandle(-1) -> 0 (00000000) MemError -116 NewHandle(0x7FFFFFFF) -> 0 (00000000) MemError -108 NewHandle(16 MB) -> 0 (00000000) MemError -108 NewHandleClear(7) -> 522248032 (1F20DF60) MemError 0 bytes zero -> 1 (00000001) MemError 0 GetHandleSize -> 7 (00000007) MemError 0 SetHandleSize(h, -1): MemError 0; GetHandleSize -> 0 SetHandleSize(h, 5): MemError 0; GetHandleSize -> 5 SetHandleSize(h, -2): MemError 0; GetHandleSize -> 0 SetHandleSize(h, 0): MemError 0; GetHandleSize -> 0 master pointer set -> 1 (00000001) MemError 0 SetHandleSize(h, 0x7FFFFFFF): MemError -108; GetHandleSize -> 0 DisposeHandle(h) -> 0 (00000000) MemError 0 # State new: master set, HGetState 00, size 16 HLock: master set, HGetState 80, size 16 HPurge: master set, HGetState C0, size 16 HSetRBit: master set, HGetState E0, size 16 HUnlock: master set, HGetState 60, size 16 HNoPurge: master set, HGetState 20, size 16 HClrRBit: master set, HGetState 00, size 16 HSetState(FF): master set, HGetState E0, size 16 MemError -> 0 (00000000) MemError 0 HSetState(00): master set, HGetState 00, size 16 RecoverHandle(*h) == h -> 1 (00000001) MemError 0 # Empty and purged NewEmptyHandle -> 522248028 (1F20DF5C) MemError 0 empty: master nil, HGetState 93, size 0 GetHandleSize -> 0 (00000000) MemError -109 HLock -> 0 (00000000) MemError -109 locked empty: master nil, HGetState 93, size 0 HUnlock -> 0 (00000000) MemError -109 HPurge -> 0 (00000000) MemError -109 HGetState -> 0 (00000000) MemError -109 SetHandleSize(empty, 10): MemError -109; GetHandleSize -> 0 after: master nil, HGetState 93, size 0 EmptyHandle(locked, purgeable) -> 0 (00000000) MemError -112 after: master set, HGetState C0, size 16 EmptyHandle(unlocked, purgeable) -> 0 (00000000) MemError 0 after: master nil, HGetState 93, size 0 ReallocateHandle(empty, 12) -> 0 (00000000) MemError 0 after: master set, HGetState 00, size 12 EmptyHandle(unpurgeable) -> 0 (00000000) MemError 0 after: master nil, HGetState 93, size 0 ReallocateHandle(locked, 20) -> 0 (00000000) MemError -112 after: master set, HGetState 80, size 12 ReallocateHandle(unlocked, 20) -> 0 (00000000) MemError 0 after: master set, HGetState 00, size 20 DisposeHandle(empty) -> 0 (00000000) MemError 0 # Purging PurgeMem(max) -> 0 (00000000) MemError -108 purgeable master pointer nil -> 1 (00000001) MemError -108 GetHandleSize(purged) -> 0 (00000000) MemError -109 # Growing a locked block SetHandleSize(locked, 200000): MemError -108; GetHandleSize -> 16 moved -> 0 (00000000) MemError 0 SetHandleSize(unlocked, 200000): MemError 0; GetHandleSize -> 200000 moved -> 1 (00000001) MemError 0 SetHandleSize(shrink, 8): MemError 0; GetHandleSize -> 8 # Master pointer reuse NewHandle after DisposeHandle reuses the master pointer -> 1 (00000001) MemError 0 again -> 0 (00000000) MemError 0 # Pointers NewPtr(0) -> 522269872 (1F2134B0) MemError 0 GetPtrSize -> 0 (00000000) MemError 0 NewPtr(-1) -> 0 (00000000) MemError -116 NewPtrClear(9) GetPtrSize -> 9 (00000009) MemError 0 SetPtrSize(3): MemError 0; GetPtrSize -> 3 SetPtrSize(-1): MemError 0; GetPtrSize -> 0 SetPtrSize(200000) with a pointer after: MemError -108; GetPtrSize -> 5 DisposePtr -> 0 (00000000) MemError 0 # Nil GetHandleSize(nil) -> 0 (00000000) MemError -109 HLock(nil) -> 0 (00000000) MemError -109 HUnlock(nil) -> 0 (00000000) MemError -109 HPurge(nil) -> 0 (00000000) MemError -109 HGetState(nil) -> 147 (00000093) MemError -109 SetHandleSize(nil, 4) -> 0 (00000000) MemError -109 EmptyHandle(nil) -> 0 (00000000) MemError 0 DisposeHandle(nil) -> 0 (00000000) MemError 0 DisposePtr(nil) -> 0 (00000000) MemError 0 GetPtrSize(nil) -> 0 (00000000) MemError -113 # Done \ No newline at end of file From dfff127583504eefde6aaf64cea7656853b10c6b Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:43 -0500 Subject: [PATCH 4/9] Document the Memory Manager capture --- ReferenceTests/Retro68/README.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/ReferenceTests/Retro68/README.md b/ReferenceTests/Retro68/README.md index 7af8e20..9a9024b 100644 --- a/ReferenceTests/Retro68/README.md +++ b/ReferenceTests/Retro68/README.md @@ -168,3 +168,31 @@ OS 9.2.2 is `HighLevelEvents-macos-9.2.2-ppc.txt` (CR line endings). `EventTests.classicHighLevelEventsStayApart` and `AppleEventInboxTests` check `ClassicEventQueue` and `AppleEventInbox` against these. + +## Memory Manager + +`MemoryManagerCapture.c` calls the Memory Manager in its application heap +and writes each call's result and its own MemError, flushing the volume after +every line. Its output on Mac OS 9.2.2 is +`MemoryManager-macos-9.2.2-ppc.txt` (CR line endings). + +- Sizes: `NewHandle(-1)` and `NewPtr(-1)` gave memSCErr (-116); one too + large, memFullErr (-108). `SetHandleSize` and `SetPtrSize` took a negative + size as 0, without an error. `NewHandle(0)` and `NewPtr(0)` gave blocks of + no bytes, and `SetHandleSize(h, 0)` kept the master pointer set. +- State: `HGetState` gave the locked (0x80), purgeable (0x40) and resource + (0x20) bits, and `HSetState(0xFF)` set only those. +- A handle's state went with its block. For a handle with no block, an empty + or purged one, `HGetState`, `HLock`, `HUnlock`, `HPurge`, `GetHandleSize` + and `SetHandleSize` gave nilHandleErr (-109); `HGetState` returned 0x93, + that error's low byte. `ReallocateHandle` gave the handle a block with no + bits set. +- `EmptyHandle` and `ReallocateHandle` of a locked handle gave memPurErr + (-112) and left it as it was. A locked block that couldn't grow where it + was gave memFullErr and kept its size; an unlocked one moved. +- `PurgeMem` purged a purgeable block, its master pointer then nil. +- A disposed handle's master pointer was the next `NewHandle` gave. +- Nil: `DisposeHandle`, `EmptyHandle` and `DisposePtr` gave noErr; + `GetPtrSize(nil)` gave memAZErr (-113). + +`HeapZoneTests` checks `HeapZone` against these. From ff0d37e31b3298e3fe678afd66557a0677f5cd3c Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:44 -0500 Subject: [PATCH 5/9] Add the Memory Manager's errors --- Sources/GraphiteCore/MacError.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Sources/GraphiteCore/MacError.swift b/Sources/GraphiteCore/MacError.swift index 7cc438c..e7cd8ca 100644 --- a/Sources/GraphiteCore/MacError.swift +++ b/Sources/GraphiteCore/MacError.swift @@ -49,6 +49,18 @@ public extension MacError { static var memoryFull: MacError { MacError(-108) } /// nilHandleErr: a handle that is nil. static var nilHandle: MacError { MacError(-109) } + /// memAdrErr: an address outside the heap, or not a block's. + static var memoryAddress: MacError { MacError(-110) } + /// memWZErr: a block that is free. + static var memoryFreeBlock: MacError { MacError(-111) } + /// memPurErr: purging a locked block. + static var memoryPurgeLocked: MacError { MacError(-112) } + /// memAZErr: an address not in the zone. + static var memoryZone: MacError { MacError(-113) } + /// memSCErr: a size that can't be. + static var memorySize: MacError { MacError(-116) } + /// memLockedErr: moving a locked block. + static var memoryLocked: MacError { MacError(-117) } // Gestalt @@ -180,7 +192,7 @@ extension MacError: CustomStringConvertible { /// "paramErr (-50)". public var description: String { let names: [Int32: String] = [ - 0: "noErr", -1: "qErr", -4: "unimpErr", -50: "paramErr", -108: "memFullErr", -109: "nilHandleErr", + 0: "noErr", -1: "qErr", -4: "unimpErr", -50: "paramErr", -108: "memFullErr", -109: "nilHandleErr", -110: "memAdrErr", -111: "memWZErr", -112: "memPurErr", -113: "memAZErr", -116: "memSCErr", -117: "memLockedErr", -128: "userCanceledErr", -5551: "gestaltUndefSelectorErr", -5552: "gestaltDupSelectorErr", -5553: "gestaltLocationErr", -29299: "kMPInvalidIDErr", -29298: "kMPInsufficientResourcesErr", -29297: "kMPTaskAbortedErr", -29296: "kMPTimeoutErr", -29295: "kMPDeletedErr", From 10790dcedab03e02a0b31313623214573e492f1b Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:44 -0500 Subject: [PATCH 6/9] Add the GraphiteMemory target --- Package.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index b94a858..a431ef8 100644 --- a/Package.swift +++ b/Package.swift @@ -98,7 +98,8 @@ let package = Package( ), .library(name: "GraphiteCacaoHost", targets: ["GraphiteCacaoHost"]), .library(name: "GraphiteCacaoRenderer", targets: ["GraphiteCacaoRenderer"]), - .library(name: "GraphiteEvents", targets: ["GraphiteEvents"]) + .library(name: "GraphiteEvents", targets: ["GraphiteEvents"]), + .library(name: "GraphiteMemory", targets: ["GraphiteMemory"]) ], // FreeType reads outline fonts; builds without it keep the bitmap font. traits: [ @@ -174,6 +175,7 @@ let package = Package( .target(name: "GraphiteCacaoHost", dependencies: ["GraphiteCore", "GraphiteWindows", "GraphiteDialogs", "GraphiteEvents", "GraphiteCacaoRenderer", .product(name: "CacaoHost", package: "Cacao"), .product(name: "CacaoRender", package: "Cacao")]), .target(name: "GraphiteCacaoRenderer", dependencies: ["GraphiteCore", "Graphite2D", "GraphiteWindows", "GraphiteControls", "GraphiteDialogs", .product(name: "CacaoRender", package: "Cacao")]), .target(name: "GraphiteEvents", dependencies: ["GraphiteCore"]), + .target(name: "GraphiteMemory", dependencies: ["GraphiteCore"]), .target( name: "Graphite", dependencies: ["GraphiteCore", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAutomation", "Graphite2D", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls", "GraphiteDialogs", "GraphiteEvents"] @@ -227,6 +229,7 @@ let package = Package( dependencies: ["GraphiteDialogs"] ), .testTarget(name: "GraphiteCacaoHostTests", dependencies: ["GraphiteCacaoHost", "GraphiteCore", "GraphiteDialogs", "GraphiteWindows", "Graphite2D", .product(name: "CacaoHost", package: "Cacao")]), - .testTarget(name: "GraphiteEventsTests", dependencies: ["GraphiteEvents"]) + .testTarget(name: "GraphiteEventsTests", dependencies: ["GraphiteEvents"]), + .testTarget(name: "GraphiteMemoryTests", dependencies: ["GraphiteMemory"]) ] ) From cf16ed912a7142d3ad3d4fbf3df83b5064dfd6c5 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:44 -0500 Subject: [PATCH 7/9] Give the Memory Manager checked access to guest memory --- Sources/GraphiteMemory/GuestMemory.swift | 75 ++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Sources/GraphiteMemory/GuestMemory.swift diff --git a/Sources/GraphiteMemory/GuestMemory.swift b/Sources/GraphiteMemory/GuestMemory.swift new file mode 100644 index 0000000..7411e14 --- /dev/null +++ b/Sources/GraphiteMemory/GuestMemory.swift @@ -0,0 +1,75 @@ +// The guest's memory, as the host gives it to the Memory Manager: checked +// reads and writes of bytes at guest addresses. A heap zone keeps its +// blocks and master pointers in it, so that the guest's own code can follow +// a handle to its block, and keeps everything else about them itself. + +import GraphiteCore + +public protocol GuestMemory: AnyObject { + + /// The bytes at an address: a fault for addresses the guest can't use. + func read(_ address: UInt32, count: Int) throws(MacError) -> [UInt8] + + /// Writes bytes at an address: a fault for addresses the guest can't + /// use. + func write(_ bytes: [UInt8], at address: UInt32) throws(MacError) + + /// Copies bytes from one place to another, the two maybe overlapping. + func move(from source: UInt32, to destination: UInt32, count: Int) throws(MacError) +} + +public extension GuestMemory { + + func move(from source: UInt32, to destination: UInt32, count: Int) throws(MacError) { + guard count > 0, source != destination else { return } + try write(read(source, count: count), at: destination) + } + + /// Writes zeros. + func zero(_ address: UInt32, count: Int) throws(MacError) { + guard count > 0 else { return } + try write([UInt8](repeating: 0, count: count), at: address) + } + + /// A big-endian 32-bit value, as a master pointer is. + func load32(_ address: UInt32) throws(MacError) -> UInt32 { + try read(address, count: 4).reduce(0) { $0 << 8 | UInt32($1) } + } + + /// Stores a big-endian 32-bit value. + func store32(_ value: UInt32, at address: UInt32) throws(MacError) { + try write([UInt8(value >> 24), UInt8(truncatingIfNeeded: value >> 16), + UInt8(truncatingIfNeeded: value >> 8), UInt8(truncatingIfNeeded: value)], at: address) + } +} + +/// Guest memory in a byte array, from a base address: for tests, and hosts +/// that keep the guest's memory so. Addresses outside it are memAdrErr. +public final class ByteGuestMemory: GuestMemory { + + public let base: UInt32 + + public private(set) var bytes: [UInt8] + + public init(base: UInt32, count: Int) { + self.base = base + self.bytes = [UInt8](repeating: 0, count: count) + } + + private func offset(_ address: UInt32, _ count: Int) throws(MacError) -> Int { + guard address >= base, count >= 0 else { throw .memoryAddress } + let offset = Int(address - base) + guard offset + count <= bytes.count else { throw .memoryAddress } + return offset + } + + public func read(_ address: UInt32, count: Int) throws(MacError) -> [UInt8] { + let start = try offset(address, count) + return Array(bytes[start ..< start + count]) + } + + public func write(_ bytes: [UInt8], at address: UInt32) throws(MacError) { + let start = try offset(address, bytes.count) + self.bytes.replaceSubrange(start ..< start + bytes.count, with: bytes) + } +} From 4afc3b683ffdb0027bef38a782f4eef966fc8e60 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:44 -0500 Subject: [PATCH 8/9] Manage handles and pointers in a guest heap zone --- Sources/GraphiteMemory/HeapZone.swift | 493 ++++++++++++++++++++++++++ 1 file changed, 493 insertions(+) create mode 100644 Sources/GraphiteMemory/HeapZone.swift diff --git a/Sources/GraphiteMemory/HeapZone.swift b/Sources/GraphiteMemory/HeapZone.swift new file mode 100644 index 0000000..2f752e2 --- /dev/null +++ b/Sources/GraphiteMemory/HeapZone.swift @@ -0,0 +1,493 @@ +// A heap zone: the Memory Manager's blocks in one range of guest memory, +// which the host gives it. Graphite decides where each block goes and when +// it moves; the guest sees only its bytes and the master pointers. +// +// A handle is the guest address of a master pointer, which holds its +// block's address, or nil for an empty or purged handle. Master pointers +// come 64 at a time, in a nonrelocatable block of their own, and a +// disposed handle's master pointer is the next one given out, so the guest +// can be handed the same handle again. Each master pointer counts its +// generations: a HandleID kept past its handle's disposal names nothing, +// rather than the handle that took its master pointer. +// +// A handle's state, its locked, purgeable and resource bits, belongs to its +// block, as it did in Mac OS 9.2.2's block headers: a handle with no block +// has none, and the calls that read or change it give nilHandleErr, and a +// handle given a block again starts with none set +// (ReferenceTests/Retro68, MemoryManagerCapture.c). +// +// When no free space fits a block, the zone slides relocatable blocks that +// aren't locked down over the free space, then purges purgeable blocks that +// aren't locked, lowest first, telling `purgeProc` before each, as the +// Resource Manager learns its resources were purged. + +import GraphiteCore + +/// A handle's identity: its master pointer, and that master pointer's +/// generation. +public struct HandleID: Hashable, Sendable, CustomStringConvertible { + + public var handle: UInt32 + + public var generation: UInt32 + + public init(handle: UInt32, generation: UInt32) { + self.handle = handle + self.generation = generation + } + + public var description: String { String(handle, radix: 16) + ".\(generation)" } +} + +public final class HeapZone { + + /// A handle's state, as HGetState gives it. + public struct State: OptionSet, Hashable, Sendable { + public var rawValue: UInt8 + public init(rawValue: UInt8) { self.rawValue = rawValue } + + public static var locked: State { State(rawValue: 0x80) } + public static var purgeable: State { State(rawValue: 0x40) } + public static var resource: State { State(rawValue: 0x20) } + + /// The bits HSetState sets. + public static var all: State { [.locked, .purgeable, .resource] } + } + + /// Blocks start on multiples of this, and take at least this much. + public static let alignment: UInt32 = 8 + + /// Master pointers in each block of them. + public static let mastersPerBlock = 64 + + public let memory: any GuestMemory + + /// The zone's addresses. + public let range: Range + + /// MemError: the result of the last call. + public private(set) var memError: Int16 = 0 + + /// Called before the zone purges a handle's block, with the handle. + public var purgeProc: ((HandleID) -> Void)? + + /// Called before DisposeHandle disposes of a resource's handle, so its + /// owner can forget it. + public var resourceDisposed: ((HandleID) -> Void)? + + private enum Owner: Equatable { + case handle(UInt32) + case pointer + case masters + } + + private struct Block { + var address: UInt32 + var physical: UInt32 + var logical: UInt32 + var owner: Owner + } + + private struct Master { + var generation: UInt32 = 0 + var isLive = false + var state: State = [] + } + + /// The blocks, by address. + private var blocks: [Block] = [] + + private var masters: [UInt32: Master] = [:] + + /// Free master pointers, the next to give out last. + private var freeMasters: [UInt32] = [] + + public init(memory: any GuestMemory, range: Range) { + self.memory = memory + self.range = range.lowerBound.aligned ..< range.upperBound + } + + // MARK: Handles + + /// NewHandle and NewHandleClear. + public func newHandle(_ size: Int32, clear: Bool = false) throws(MacError) -> UInt32 { + try record { () throws(MacError) -> UInt32 in + guard size >= 0 else { throw .memorySize } + let handle = try takeMaster() + do throws(MacError) { + let address = try allocate(Self.physical(size), owner: .handle(handle), logical: UInt32(size)) + if clear { try memory.zero(address, count: Int(size)) } + try memory.store32(address, at: handle) + } catch { + releaseMaster(handle) + throw error + } + return handle + } + } + + /// NewEmptyHandle: a handle with no block. + public func newEmptyHandle() throws(MacError) -> UInt32 { + try record { () throws(MacError) -> UInt32 in + let handle = try takeMaster() + try memory.store32(0, at: handle) + return handle + } + } + + /// DisposeHandle: nil is noErr. + public func disposeHandle(_ handle: UInt32) throws(MacError) { + try record { () throws(MacError) in + guard handle != 0 else { return } + let master = try live(handle) + if master.state.contains(.resource) { resourceDisposed?(HandleID(handle: handle, generation: master.generation)) } + if let index = index(of: .handle(handle)) { blocks.remove(at: index) } + try memory.store32(0, at: handle) + releaseMaster(handle) + } + } + + /// GetHandleSize: nilHandleErr for an empty or purged handle. + public func handleSize(_ handle: UInt32) throws(MacError) -> Int32 { + try record { () throws(MacError) -> Int32 in + _ = try live(handle) + guard let index = index(of: .handle(handle)) else { throw .nilHandle } + return Int32(blocks[index].logical) + } + } + + /// SetHandleSize: grows or shrinks the block, moving it if it isn't + /// locked and can't grow where it is. memFullErr if there is no room, + /// the size kept. A negative size is 0, as Mac OS 9.2.2 took it. + public func setHandleSize(_ handle: UInt32, _ requested: Int32) throws(MacError) { + try record { () throws(MacError) in + let master = try live(handle) + let size = max(requested, 0) + guard var index = index(of: .handle(handle)) else { throw .nilHandle } + let physical = Self.physical(size) + if physical <= blocks[index].physical || physical <= room(at: index) { + blocks[index].physical = physical + blocks[index].logical = UInt32(size) + return + } + guard !master.state.contains(.locked) else { throw .memoryFull } + let address = try allocate(physical, owner: .pointer, logical: UInt32(size), keeping: handle) + index = self.index(of: .handle(handle))! + let old = blocks[index] + try memory.move(from: old.address, to: address, count: Int(old.logical)) + blocks.remove(at: index) + let moved = self.index(at: address)! + blocks[moved].owner = .handle(handle) + try memory.store32(address, at: handle) + } + } + + /// EmptyHandle: frees the block, leaving the handle. memPurErr for a + /// locked handle; nil is noErr. + public func emptyHandle(_ handle: UInt32) throws(MacError) { + try record { () throws(MacError) in + guard handle != 0 else { return } + let master = try live(handle) + guard let index = index(of: .handle(handle)) else { return } + guard !master.state.contains(.locked) else { throw .memoryPurgeLocked } + try freeBlock(at: index, of: handle) + } + } + + /// ReallocateHandle: a new block of a size for the handle, its old one, + /// if any, freed. memPurErr for a locked handle with a block. + public func reallocateHandle(_ handle: UInt32, _ size: Int32) throws(MacError) { + try record { () throws(MacError) in + let master = try live(handle) + guard size >= 0 else { throw .memorySize } + if let index = index(of: .handle(handle)) { + guard !master.state.contains(.locked) else { throw .memoryPurgeLocked } + try freeBlock(at: index, of: handle) + } + let address = try allocate(Self.physical(size), owner: .handle(handle), logical: UInt32(size)) + try memory.store32(address, at: handle) + } + } + + /// RecoverHandle: the handle whose block starts at an address. + public func recoverHandle(_ address: UInt32) throws(MacError) -> UInt32 { + try record { () throws(MacError) -> UInt32 in + guard let index = index(at: address), case .handle(let handle) = blocks[index].owner else { throw .memoryAddress } + return handle + } + } + + // MARK: State + + /// HGetState: nilHandleErr for a handle with no block, for which Mac + /// OS 9.2.2's HGetState returned the error's low byte, 0x93. + public func state(_ handle: UInt32) throws(MacError) -> State { + try record { () throws(MacError) -> State in try withBlock(handle).state } + } + + /// HSetState: the locked, purgeable and resource bits of a state. + public func setState(_ handle: UInt32, _ state: State) throws(MacError) { + try record { () throws(MacError) in + _ = try withBlock(handle) + masters[handle]!.state = state.intersection(.all) + } + } + + /// HLock, HUnlock, HPurge, HNoPurge, HSetRBit and HClrRBit: + /// nilHandleErr for a handle with no block. + public func update(_ handle: UInt32, setting set: State = [], clearing clear: State = []) throws(MacError) { + try record { () throws(MacError) in + _ = try withBlock(handle) + masters[handle]!.state.subtract(clear) + masters[handle]!.state.formUnion(set) + } + } + + // MARK: Identity + + /// The identity of a handle given out and not disposed of. + public func handleID(_ handle: UInt32) -> HandleID? { + guard let master = masters[handle], master.isLive else { return nil } + return HandleID(handle: handle, generation: master.generation) + } + + /// Whether an identity names a handle not disposed of. + public func contains(_ id: HandleID) -> Bool { handleID(id.handle) == id } + + // MARK: Pointers + + /// NewPtr and NewPtrClear: a block that doesn't move. + public func newPointer(_ size: Int32, clear: Bool = false) throws(MacError) -> UInt32 { + try record { () throws(MacError) -> UInt32 in + guard size >= 0 else { throw .memorySize } + let address = try allocate(Self.physical(size), owner: .pointer, logical: UInt32(size)) + if clear { try memory.zero(address, count: Int(size)) } + return address + } + } + + /// DisposePtr: nil is noErr. + public func disposePointer(_ address: UInt32) throws(MacError) { + try record { () throws(MacError) in + guard address != 0 else { return } + blocks.remove(at: try pointer(address)) + } + } + + /// GetPtrSize: memAZErr for nil, as Mac OS 9.2.2 gave. + public func pointerSize(_ address: UInt32) throws(MacError) -> Int32 { + try record { () throws(MacError) -> Int32 in + guard address != 0 else { throw .memoryZone } + return Int32(blocks[try pointer(address)].logical) + } + } + + /// SetPtrSize: grows or shrinks a pointer's block where it is; + /// memFullErr if it can't grow there. A negative size is 0. + public func setPointerSize(_ address: UInt32, _ requested: Int32) throws(MacError) { + try record { () throws(MacError) in + let index = try pointer(address) + let size = max(requested, 0) + let physical = Self.physical(size) + guard physical <= blocks[index].physical || physical <= room(at: index) else { throw .memoryFull } + blocks[index].physical = physical + blocks[index].logical = UInt32(size) + } + } + + // MARK: The zone + + /// FreeMem: the free bytes, together. + public var freeBytes: UInt32 { + UInt32(range.count) - blocks.reduce(0) { $0 + $1.physical } + } + + /// MaxBlock: the largest block compacting the zone would make room for. + public var largestBlock: UInt32 { + var largest: UInt32 = 0 + var start = range.lowerBound + var movable: UInt32 = 0 + for block in blocks { + if isMovable(block) { + movable += block.physical + } else { + largest = max(largest, (block.address - start) - min(movable, block.address - start)) + start = block.address + block.physical + movable = 0 + } + } + return max(largest, (range.upperBound - start) - min(movable, range.upperBound - start)) + } + + /// CompactMem: slides unlocked relocatable blocks down, giving the + /// largest free block. + @discardableResult + public func compact() throws(MacError) -> UInt32 { + try record { () throws(MacError) -> UInt32 in + try compactBlocks() + return UInt32(gaps().map(\.count).max() ?? 0) + } + } + + /// PurgeMem: purges purgeable, unlocked blocks, lowest first, until a + /// free block of a size is there; memFullErr if one isn't after all. + public func purge(needing size: Int32) throws(MacError) { + try record { () throws(MacError) in + let needed = Self.physical(max(size, 0)) + while firstFit(needed) == nil { + guard try purgeOne(keeping: nil) else { throw .memoryFull } + } + } + } + + // MARK: Blocks + + private static func physical(_ size: Int32) -> UInt32 { max(UInt32(size).aligned, alignment) } + + private func isMovable(_ block: Block) -> Bool { + guard case .handle(let handle) = block.owner else { return false } + return masters[handle].map { !$0.state.contains(.locked) } ?? false + } + + private func index(of owner: Owner) -> Int? { blocks.firstIndex { $0.owner == owner } } + + private func index(at address: UInt32) -> Int? { blocks.firstIndex { $0.address == address } } + + private func pointer(_ address: UInt32) throws(MacError) -> Int { + guard address != 0 else { throw .nilHandle } + guard let index = index(at: address), blocks[index].owner == .pointer else { throw .memoryAddress } + return index + } + + /// The bytes a block could grow to where it is. + private func room(at index: Int) -> UInt32 { + let end = index + 1 < blocks.count ? blocks[index + 1].address : range.upperBound + return end - blocks[index].address + } + + /// The free ranges, by address. + private func gaps() -> [Range] { + var gaps: [Range] = [] + var cursor = range.lowerBound + for block in blocks { + if block.address > cursor { gaps.append(cursor ..< block.address) } + cursor = block.address + block.physical + } + if range.upperBound > cursor { gaps.append(cursor ..< range.upperBound) } + return gaps + } + + private func firstFit(_ physical: UInt32) -> UInt32? { + gaps().first { $0.count >= Int(physical) }?.lowerBound + } + + /// Places a block: where it fits, else after compacting, else after + /// purging. A handle being kept is not purged. + private func allocate(_ physical: UInt32, owner: Owner, logical: UInt32, keeping kept: UInt32? = nil) throws(MacError) -> UInt32 { + var compacted = false + while true { + if let address = firstFit(physical) { + let block = Block(address: address, physical: physical, logical: logical, owner: owner) + blocks.insert(block, at: blocks.firstIndex { $0.address > address } ?? blocks.endIndex) + return address + } + if !compacted { + try compactBlocks() + compacted = true + continue + } + guard try purgeOne(keeping: kept) else { throw .memoryFull } + try compactBlocks() + } + } + + private func compactBlocks() throws(MacError) { + var cursor = range.lowerBound + for index in blocks.indices { + let block = blocks[index] + if isMovable(block), block.address > cursor, case .handle(let handle) = block.owner { + try memory.move(from: block.address, to: cursor, count: Int(block.logical)) + blocks[index].address = cursor + try memory.store32(cursor, at: handle) + } + cursor = blocks[index].address + blocks[index].physical + } + } + + /// Purges the lowest purgeable, unlocked block: false if there is none. + private func purgeOne(keeping kept: UInt32?) throws(MacError) -> Bool { + guard let index = blocks.firstIndex(where: { block in + guard case .handle(let handle) = block.owner, handle != kept, let master = masters[handle] else { return false } + return master.state.contains(.purgeable) && !master.state.contains(.locked) + }), case .handle(let handle) = blocks[index].owner else { return false } + purgeProc?(HandleID(handle: handle, generation: masters[handle]!.generation)) + // The proc may have changed the zone. + guard let current = self.index(of: .handle(handle)) else { return true } + try freeBlock(at: current, of: handle) + return true + } + + /// Frees a handle's block, and the state that went with it. + private func freeBlock(at index: Int, of handle: UInt32) throws(MacError) { + blocks.remove(at: index) + masters[handle]?.state = [] + try memory.store32(0, at: handle) + } + + /// A handle's master, if the handle has a block: nilHandleErr if not. + private func withBlock(_ handle: UInt32) throws(MacError) -> Master { + let master = try live(handle) + guard index(of: .handle(handle)) != nil else { throw .nilHandle } + return master + } + + // MARK: Master pointers + + private func live(_ handle: UInt32) throws(MacError) -> Master { + guard handle != 0 else { throw .nilHandle } + guard let master = masters[handle] else { throw .memoryAddress } + guard master.isLive else { throw .memoryFreeBlock } + return master + } + + private func takeMaster() throws(MacError) -> UInt32 { + if freeMasters.isEmpty { + let count = Self.mastersPerBlock + let address = try allocate(UInt32(count * 4), owner: .masters, logical: UInt32(count * 4)) + try memory.zero(address, count: count * 4) + for slot in (0 ..< count).reversed() { + let handle = address + UInt32(slot * 4) + masters[handle] = Master() + freeMasters.append(handle) + } + } + let handle = freeMasters.removeLast() + masters[handle]!.isLive = true + masters[handle]!.state = [] + return handle + } + + private func releaseMaster(_ handle: UInt32) { + masters[handle]!.isLive = false + masters[handle]!.state = [] + masters[handle]!.generation &+= 1 + freeMasters.append(handle) + } + + /// Runs a call, keeping its result as MemError. + private func record(_ body: () throws(MacError) -> Result) throws(MacError) -> Result { + do { + let result = try body() + memError = 0 + return result + } catch { + memError = Int16(truncatingIfNeeded: error.code) + throw error + } + } +} + +private extension UInt32 { + /// Rounded up to the zone's alignment. + var aligned: UInt32 { (self &+ HeapZone.alignment - 1) & ~(HeapZone.alignment - 1) } +} From f8ff9dea496e6867bf350460f58046fffdc57af9 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Tue, 1 Dec 2026 01:38:44 -0500 Subject: [PATCH 9/9] Test the heap zone against the Mac OS 9 capture --- Tests/GraphiteMemoryTests/HeapZoneTests.swift | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 Tests/GraphiteMemoryTests/HeapZoneTests.swift diff --git a/Tests/GraphiteMemoryTests/HeapZoneTests.swift b/Tests/GraphiteMemoryTests/HeapZoneTests.swift new file mode 100644 index 0000000..4e74496 --- /dev/null +++ b/Tests/GraphiteMemoryTests/HeapZoneTests.swift @@ -0,0 +1,193 @@ +import Testing +import GraphiteCore +import GraphiteMemory + +@Suite struct HeapZoneTests { + + /// A 4 KB zone at 0x1000. + private func zone(size: Int = 4096) -> (HeapZone, ByteGuestMemory) { + let memory = ByteGuestMemory(base: 0x1000, count: size) + return (HeapZone(memory: memory, range: 0x1000 ..< 0x1000 + UInt32(size)), memory) + } + + @Test func handlesPointToTheirBlocks() throws { + let (zone, memory) = zone() + let handle = try zone.newHandle(10, clear: true) + let block = try memory.load32(handle) + #expect(block != 0 && block % HeapZone.alignment == 0) + #expect(try zone.handleSize(handle) == 10) + #expect(try memory.read(block, count: 10) == [UInt8](repeating: 0, count: 10)) + #expect(try zone.recoverHandle(block) == handle) + #expect(zone.memError == 0) + // The master pointers' own block, and the handle's. + #expect(zone.freeBytes == 4096 - 256 - 16) + } + + @Test func sizesAndErrors() throws { + let (zone, _) = zone() + #expect(throws: MacError.memorySize) { try zone.newHandle(-1) } + #expect(zone.memError == -116) + #expect(throws: MacError.memoryFull) { try zone.newHandle(5000) } + #expect(zone.memError == -108) + #expect(throws: MacError.nilHandle) { try zone.handleSize(0) } + #expect(throws: MacError.memoryAddress) { try zone.handleSize(0x1234) } + let handle = try zone.newHandle(0) + #expect(try zone.handleSize(handle) == 0) + try zone.disposeHandle(handle) + #expect(throws: MacError.memoryFreeBlock) { try zone.handleSize(handle) } + } + + @Test func emptyHandlesHaveNoBlock() throws { + let (zone, memory) = zone() + let handle = try zone.newEmptyHandle() + #expect(try memory.load32(handle) == 0) + #expect(throws: MacError.nilHandle) { try zone.handleSize(handle) } + try zone.reallocateHandle(handle, 12) + #expect(try memory.load32(handle) != 0 && zone.handleSize(handle) == 12) + try zone.update(handle, setting: .locked) + #expect(throws: MacError.memoryPurgeLocked) { try zone.emptyHandle(handle) } + #expect(throws: MacError.memoryPurgeLocked) { try zone.reallocateHandle(handle, 4) } + try zone.update(handle, clearing: .locked) + try zone.emptyHandle(handle) + #expect(try memory.load32(handle) == 0) + } + + @Test func statesKeepTheirBits() throws { + let (zone, _) = zone() + let handle = try zone.newHandle(4) + try zone.update(handle, setting: [.locked, .purgeable, .resource]) + #expect(try zone.state(handle).rawValue == 0xE0) + try zone.setState(handle, HeapZone.State(rawValue: 0xFF)) + #expect(try zone.state(handle).rawValue == 0xE0) + try zone.update(handle, clearing: .locked) + #expect(try zone.state(handle) == [.purgeable, .resource]) + } + + @Test func growingMovesOnlyUnlockedBlocks() throws { + let (zone, memory) = zone() + let handle = try zone.newHandle(8) + try memory.write(Array(1 ... 8), at: memory.load32(handle)) + let blocker = try zone.newPointer(8) + try zone.update(handle, setting: .locked) + #expect(throws: MacError.memoryFull) { try zone.setHandleSize(handle, 100) } + try zone.update(handle, clearing: .locked) + let before = try memory.load32(handle) + try zone.setHandleSize(handle, 100) + let after = try memory.load32(handle) + #expect(after != before && after > blocker) + #expect(try memory.read(after, count: 8) == Array(1 ... 8)) + // Shrinking stays put. + try zone.setHandleSize(handle, 4) + #expect(try memory.load32(handle) == after && zone.handleSize(handle) == 4) + } + + @Test func compactionSlidesUnlockedBlocksDown() throws { + let (zone, memory) = zone(size: 1024) + // 256 bytes of master pointers, then three 200-byte handles. + let handles = try (0 ..< 3).map { _ in try zone.newHandle(200) } + try memory.write([7], at: memory.load32(handles[2])) + try zone.disposeHandle(handles[0]) + try zone.disposeHandle(handles[1]) + #expect(zone.largestBlock == 400 + 168) + // No free run is 500 bytes long until the last handle moves down. + let big = try zone.newHandle(500) + #expect(try memory.load32(handles[2]) == 0x1000 + 256) + #expect(try memory.read(memory.load32(handles[2]), count: 1) == [7]) + #expect(try zone.handleSize(big) == 500) + } + + @Test func purgingMakesRoomAndTellsTheOwner() throws { + let (zone, memory) = zone(size: 1024) + let cache = try zone.newHandle(600) + try zone.update(cache, setting: [.purgeable, .resource]) + var purged: [HandleID] = [] + zone.purgeProc = { purged.append($0) } + let handle = try zone.newHandle(400) + #expect(purged == [zone.handleID(cache)]) + #expect(try memory.load32(cache) == 0) + #expect(throws: MacError.nilHandle) { try zone.handleSize(cache) } + // A locked purgeable block stays. + try zone.reallocateHandle(cache, 300) + try zone.update(cache, setting: .locked) + #expect(throws: MacError.memoryFull) { try zone.purge(needing: 600) } + try zone.disposeHandle(handle) + } + + @Test func masterPointersAreReusedInLaterGenerations() throws { + let (zone, _) = zone() + let first = try zone.newHandle(4) + let id = try #require(zone.handleID(first)) + try zone.disposeHandle(first) + #expect(!zone.contains(id)) + let second = try zone.newHandle(4) + #expect(second == first) + #expect(zone.handleID(second)?.generation == id.generation + 1) + #expect(!zone.contains(id)) + // A full block of master pointers brings another. + let more = try (0 ..< HeapZone.mastersPerBlock).map { _ in try zone.newEmptyHandle() } + #expect(Set(more).count == HeapZone.mastersPerBlock && !more.contains(second)) + } + + @Test func disposingAResourceTellsItsOwner() throws { + let (zone, _) = zone() + let handle = try zone.newHandle(4) + try zone.update(handle, setting: .resource) + var disposed: [HandleID] = [] + zone.resourceDisposed = { disposed.append($0) } + let id = zone.handleID(handle) + try zone.disposeHandle(handle) + #expect(disposed == [id]) + } + + @Test func pointersStayPut() throws { + let (zone, _) = zone() + let pointer = try zone.newPointer(9, clear: true) + #expect(try zone.pointerSize(pointer) == 9) + try zone.setPointerSize(pointer, 3) + #expect(try zone.pointerSize(pointer) == 3) + _ = try zone.newPointer(8) + #expect(throws: MacError.memoryFull) { try zone.setPointerSize(pointer, 100) } + #expect(try zone.pointerSize(pointer) == 3) + try zone.setPointerSize(pointer, -1) + #expect(try zone.pointerSize(pointer) == 0) + #expect(throws: MacError.memoryAddress) { try zone.recoverHandle(pointer) } + try zone.disposePointer(pointer) + #expect(throws: MacError.memoryAddress) { try zone.pointerSize(pointer) } + #expect(throws: MacError.memorySize) { try zone.newPointer(-1) } + } + + /// As Mac OS 9.2.2 did (ReferenceTests/Retro68, + /// MemoryManager-macos-9.2.2-ppc.txt). + @Test func matchesMacOS9() throws { + let (zone, memory) = zone() + // A negative size is 0 to SetHandleSize, but memSCErr to NewHandle. + let handle = try zone.newHandle(7) + try zone.setHandleSize(handle, -1) + #expect(try zone.handleSize(handle) == 0 && memory.load32(handle) != 0) + #expect(throws: MacError.memoryFull) { try zone.setHandleSize(handle, .max) } + #expect(try zone.handleSize(handle) == 0) + // A handle with no block has no state. + try zone.update(handle, setting: [.purgeable, .resource]) + try zone.emptyHandle(handle) + #expect(throws: MacError.nilHandle) { try zone.state(handle) } + #expect(throws: MacError.nilHandle) { try zone.update(handle, setting: .locked) } + #expect(throws: MacError.nilHandle) { try zone.update(handle, clearing: .locked) } + #expect(throws: MacError.nilHandle) { try zone.setHandleSize(handle, 10) } + #expect(zone.memError == -109) + // Given a block again, it starts with none set. + try zone.reallocateHandle(handle, 12) + #expect(try zone.state(handle) == []) + // Nil. + #expect(throws: MacError.nilHandle) { try zone.handleSize(0) } + #expect(throws: MacError.nilHandle) { try zone.update(0, setting: .locked) } + #expect(throws: MacError.nilHandle) { try zone.state(0) } + #expect(throws: MacError.nilHandle) { try zone.setHandleSize(0, 4) } + try zone.emptyHandle(0) + try zone.disposeHandle(0) + try zone.disposePointer(0) + #expect(zone.memError == 0) + #expect(throws: MacError.memoryZone) { try zone.pointerSize(0) } + // Pointers of no bytes. + #expect(try zone.pointerSize(zone.newPointer(0)) == 0) + } +}