diff --git a/Package.swift b/Package.swift index a431ef8..b3200dc 100644 --- a/Package.swift +++ b/Package.swift @@ -99,7 +99,8 @@ let package = Package( .library(name: "GraphiteCacaoHost", targets: ["GraphiteCacaoHost"]), .library(name: "GraphiteCacaoRenderer", targets: ["GraphiteCacaoRenderer"]), .library(name: "GraphiteEvents", targets: ["GraphiteEvents"]), - .library(name: "GraphiteMemory", targets: ["GraphiteMemory"]) + .library(name: "GraphiteMemory", targets: ["GraphiteMemory"]), + .library(name: "GraphiteMixedMode", targets: ["GraphiteMixedMode"]) ], // FreeType reads outline fonts; builds without it keep the bitmap font. traits: [ @@ -176,6 +177,7 @@ let package = Package( .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: "GraphiteMixedMode", dependencies: ["GraphiteCore", "GraphiteMemory"]), .target( name: "Graphite", dependencies: ["GraphiteCore", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAutomation", "Graphite2D", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls", "GraphiteDialogs", "GraphiteEvents"] @@ -230,6 +232,7 @@ let package = Package( ), .testTarget(name: "GraphiteCacaoHostTests", dependencies: ["GraphiteCacaoHost", "GraphiteCore", "GraphiteDialogs", "GraphiteWindows", "Graphite2D", .product(name: "CacaoHost", package: "Cacao")]), .testTarget(name: "GraphiteEventsTests", dependencies: ["GraphiteEvents"]), - .testTarget(name: "GraphiteMemoryTests", dependencies: ["GraphiteMemory"]) + .testTarget(name: "GraphiteMemoryTests", dependencies: ["GraphiteMemory"]), + .testTarget(name: "GraphiteMixedModeTests", dependencies: ["GraphiteMixedMode", "GraphiteMemory"]) ] ) diff --git a/ReferenceTests/Retro68/CMakeLists.txt b/ReferenceTests/Retro68/CMakeLists.txt index 11b900d..332dd7a 100644 --- a/ReferenceTests/Retro68/CMakeLists.txt +++ b/ReferenceTests/Retro68/CMakeLists.txt @@ -7,3 +7,4 @@ add_application(RelStringCapture RelStringCapture.c) add_application(CatalogOrderCapture CatalogOrderCapture.c) add_application(HighLevelEventCapture HighLevelEventCapture.c HighLevelEventCapture.r) add_application(MemoryManagerCapture MemoryManagerCapture.c) +add_application(MixedModeCapture MixedModeCapture.c) diff --git a/ReferenceTests/Retro68/MixedMode-macos-9.2.2-ppc.txt b/ReferenceTests/Retro68/MixedMode-macos-9.2.2-ppc.txt new file mode 100644 index 0000000..ee72a3b --- /dev/null +++ b/ReferenceTests/Retro68/MixedMode-macos-9.2.2-ppc.txt @@ -0,0 +1 @@ +# NewRoutineDescriptor NewRoutineDescriptor(12345678, 00000000, PowerPC) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000000 00010004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, PowerPC) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00010004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 000003F1, PowerPC) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 000003F1 00010004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, FFFFFFFF, PowerPC) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 FFFFFFFF 00010004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, ISA 00) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00000004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, ISA 01) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00010004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, ISA 02) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00020004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, ISA 10) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00100004 12345678 00000000 00000000 NewRoutineDescriptor(12345678, 00000FD0, ISA 11) -> descriptor, MemError 0, GetPtrSize 32 bytes: AAFE0700 00000000 00000000 00000FD0 00110004 12345678 00000000 00000000 NewRoutineDescriptor(nil, 00000FD0, PowerPC) -> nil, MemError 0, GetPtrSize 0 NewFatRoutineDescriptor(11111110, 22222220, 00000FD0) -> descriptor, MemError 0, GetPtrSize 52 bytes: AAFE0700 00000000 00000001 00000FD0 00000000 11111110 00000000 00000000 00000FD0 00010000 22222220 00000000 00000000 DisposeRoutineDescriptor(nil): MemError 0 # Plain calls PowerPC descriptor -> A; arguments 11 22 68k code without a descriptor -> 7; arguments 0 0 68k descriptor -> 7; arguments 0 0 # Fat NewFatRoutineDescriptor(68k 7, PowerPC A) -> A; arguments 11 22 records 68k 7, PowerPC A -> A; arguments 11 22 records PowerPC A, 68k 7 -> 7; arguments 0 0 records PowerPC A, PowerPC B -> B; arguments 11 22 records 68k 7, 68k 8 -> 8; arguments 0 0 records PowerPC A, B, C -> B; arguments 11 22 records 68k 7, PowerPC A, PowerPC B -> A; arguments 11 22 records PowerPC A, PowerPC B, 68k 7 -> B; arguments 11 22 records PowerPC A, PowerPC B, routineCount 0 -> A; arguments 11 22 # Routine flags records PowerPC A kUseNativeISA, 68k 7 -> 7; arguments 0 0 records 68k 7 kUseNativeISA, PowerPC A -> A; arguments 11 22 records PowerPC A kUseNativeISA, PowerPC B -> B; arguments 11 22 records PowerPC A, PowerPC B kUseNativeISA -> B; arguments 11 22 # Reuse records PowerPC A, 68k 7 -> 7; arguments 0 0 same block rewritten to 68k 7, PowerPC B -> B; arguments 11 22 new block at the address of the disposed one: records PowerPC C, PowerPC B -> B; arguments 11 22 # Dispatched, selectors not indexable selector 5 (A) -> B; arguments 5 11 selector 9 (B, kDontPassSelector) -> B; arguments 9 11 selector 7 (none; C is the default) -> B; arguments 7 11 selector 1 (C's own) -> B; arguments 1 11 plain procedure information -> B; arguments 11 22 A 0, B 1, C 2, 68k 6 3: selector 0 -> B; arguments 0 11 A 0, B 1, C 2, 68k 6 3: selector 1 -> B; arguments 1 11 A 0, B 1, C 2, 68k 6 3: selector 2 -> B; arguments 2 11 A 0, B 1, C 2, 68k 6 3: selector 3 -> B; arguments 3 11 two records with selector 3 (A, B) -> B; arguments 3 11 selector 4 in 68k 7 and PowerPC A -> A; arguments 4 11 # Dispatched, selectors indexable A 100, B 101, C 102: selector 0 -> B; arguments 0 11 A 100, B 101, C 102: selector 1 -> B; arguments 1 11 A 100, B 101, C 102: selector 2 -> B; arguments 2 11 selector 101 (B's own) -> B; arguments 65 11 # Stack dispatched A 0, B 1, C 2: selector 0 -> B; arguments 0 11 A 0, B 1, C 2: selector 1 -> B; arguments 1 11 A 0, B 1, C 2: selector 2 -> B; arguments 2 11 # Relative 68k 68k, relative 64 to 68k 9 -> 9; arguments 0 0 # Not found selector 6, no default -> A; arguments 6 11 # Relative PowerPC, not needing preparation \ No newline at end of file diff --git a/ReferenceTests/Retro68/MixedModeCapture.c b/ReferenceTests/Retro68/MixedModeCapture.c new file mode 100644 index 0000000..30fcb3f --- /dev/null +++ b/ReferenceTests/Retro68/MixedModeCapture.c @@ -0,0 +1,340 @@ +/* + * Captures how the Mixed Mode Manager lays out routine descriptors and + * which routine record CallUniversalProc runs, writing "MixedMode.txt" next + * to itself. It refuses to run if that file is already there. The file is + * flushed after every line, so a call that crashes leaves the lines before + * it; the calls most likely to crash come last. Descriptors called are + * never disposed, so that no two share an address, except in "Reuse". + * + * It records the bytes NewRoutineDescriptor and NewFatRoutineDescriptor + * write, then calls descriptors built by hand: plain and fat ones, 68k code + * given without a descriptor, dispatched sets with and without indexable + * selectors, a default routine and kDontPassSelector, and relative targets. + * Its 68k code is "moveq #n,d0; rts", so a 68k routine returns n. + */ +#include +#include +#include +#include +#include + +/* Retro68's Multiversal headers leave these out; the values are Apple's, + from Inside Macintosh: PowerPC System Software. */ +enum { + kProcDescriptorIsRelative = 0x01, + kDontPassSelector = 0x08, + kRoutineIsDispatchedDefaultRoutine = 0x10, + kSelectorsAreIndexable = 0x01 +}; + +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 dump(const char *label, const void *bytes, long count) +{ + char text[400]; + int used = snprintf(text, sizeof text, "%s:", label); + long i; + for (i = 0; i < count && used < (int)sizeof text - 4; i++) + used += snprintf(text + used, sizeof text - used, "%s%02X", i % 4 ? "" : " ", ((const unsigned char *)bytes)[i]); + line(text); +} + +/* A descriptor from NewRoutineDescriptor or NewFatRoutineDescriptor. */ +static void described(const char *call, UniversalProcPtr upp) +{ + char text[160]; + snprintf(text, sizeof text, "%s -> %s, MemError %d, GetPtrSize %ld", + call, upp ? "descriptor" : "nil", MemError(), upp ? GetPtrSize((Ptr)upp) : 0L); + line(text); + if (upp) dump(" bytes", upp, GetPtrSize((Ptr)upp)); +} + +/* PowerPC targets: each returns its letter and keeps its arguments. */ +static long seen[3]; + +static long targetA(long a, long b, long c) { seen[0] = a; seen[1] = b; seen[2] = c; return 0xA; } +static long targetB(long a, long b, long c) { seen[0] = a; seen[1] = b; seen[2] = c; return 0xB; } +static long targetC(long a, long b, long c) { seen[0] = a; seen[1] = b; seen[2] = c; return 0xC; } + +/* C, a 4-byte result and two 4-byte parameters. */ +enum { kPlainInfo = kCStackBased | (kFourByteCode << 4) | (kFourByteCode << 6) | (kFourByteCode << 8) }; + +/* Pascal with a 2-byte selector on the stack, a 4-byte result and two 4-byte parameters. */ +enum { kStackDispatchedInfo = kStackDispatchedPascalStackBased | (kFourByteCode << 4) | (kTwoByteCode << 6) + | (kFourByteCode << 8) | (kFourByteCode << 10) }; + +/* C with a 2-byte selector in D0, a 4-byte result and two 4-byte parameters. */ +enum { kDispatchedInfo = kD0DispatchedCStackBased | (kFourByteCode << 4) | (kTwoByteCode << 6) + | (kFourByteCode << 8) | (kFourByteCode << 10) }; + +/* "moveq #n,d0; rts" in its own block. */ +static Ptr code68k(int n) +{ + Ptr p = NewPtr(4); + p[0] = 0x70; p[1] = (char)n; p[2] = 0x4E; p[3] = 0x75; + return p; +} + +typedef struct { unsigned char isa; unsigned short flags; long target; unsigned long selector; unsigned long info; } Record; + +/* A descriptor of count records, in a block with extra bytes after it. */ +static RoutineDescriptor *build(unsigned char rdFlags, int count, const Record *records, long extra) +{ + long size = offsetof(RoutineDescriptor, routineRecords) + count * sizeof(RoutineRecord) + extra; + RoutineDescriptor *rd = (RoutineDescriptor *)NewPtrClear(size); + int i; + rd->goMixedModeTrap = 0xAAFE; + rd->version = kRoutineDescriptorVersion; + rd->routineDescriptorFlags = rdFlags; + rd->routineCount = count - 1; + for (i = 0; i < count; i++) { + rd->routineRecords[i].procInfo = records[i].info; + rd->routineRecords[i].ISA = records[i].isa; + rd->routineRecords[i].routineFlags = records[i].flags; + rd->routineRecords[i].procDescriptor = (ProcPtr)records[i].target; + rd->routineRecords[i].selector = records[i].selector; + } + return rd; +} + +static void called(const char *call, long result) +{ + char text[200]; + snprintf(text, sizeof text, "%s -> %lX; arguments %lX %lX", call, result, seen[0], seen[1]); + line(text); + seen[0] = seen[1] = seen[2] = 0; +} + +static long plain(void *upp) { return CallUniversalProc((UniversalProcPtr)upp, kPlainInfo, 0x11L, 0x22L); } + +static long dispatched(void *upp, short selector) +{ + return CallUniversalProc((UniversalProcPtr)upp, kDispatchedInfo, selector, 0x11L, 0x22L); +} + +int main(void) +{ + static const unsigned char name[] = { 13, 'M','i','x','e','d','M','o','d','e','.','t','x','t' }; + static const unsigned long infos[] = { 0, 0x00000FD0, kPlainInfo, 0xFFFFFFFF }; + static const unsigned char isas[] = { kM68kISA, kPowerPCISA, 2, 0x10, 0x11 }; + char label[120]; + UniversalProcPtr upp; + RoutineDescriptor *rd; + Ptr code; + int i; + + if (Create(name, 0, 'Grph', 'TEXT') != noErr) return 1; + if (FSOpen(name, 0, &out) != noErr) return 2; + + line("# NewRoutineDescriptor"); + for (i = 0; i < (int)(sizeof infos / sizeof *infos); i++) { + snprintf(label, sizeof label, "NewRoutineDescriptor(12345678, %08lX, PowerPC)", infos[i]); + upp = NewRoutineDescriptor((ProcPtr)0x12345678, infos[i], kPowerPCISA); + described(label, upp); + if (upp) DisposeRoutineDescriptor(upp); + } + for (i = 0; i < (int)sizeof isas; i++) { + snprintf(label, sizeof label, "NewRoutineDescriptor(12345678, 00000FD0, ISA %02X)", isas[i]); + upp = NewRoutineDescriptor((ProcPtr)0x12345678, 0xFD0, isas[i]); + described(label, upp); + if (upp) DisposeRoutineDescriptor(upp); + } + upp = NewRoutineDescriptor(nil, 0xFD0, kPowerPCISA); + described("NewRoutineDescriptor(nil, 00000FD0, PowerPC)", upp); + if (upp) DisposeRoutineDescriptor(upp); + upp = NewFatRoutineDescriptor((ProcPtr)0x11111110, (ProcPtr)0x22222220, 0xFD0); + described("NewFatRoutineDescriptor(11111110, 22222220, 00000FD0)", upp); + if (upp) DisposeRoutineDescriptor(upp); + DisposeRoutineDescriptor(nil); + snprintf(label, sizeof label, "DisposeRoutineDescriptor(nil): MemError %d", MemError()); + line(label); + + line("# Plain calls"); + upp = NewRoutineDescriptor((ProcPtr)targetA, kPlainInfo, kPowerPCISA); + called("PowerPC descriptor", plain(upp)); + DisposeRoutineDescriptor(upp); + code = code68k(7); + called("68k code without a descriptor", plain(code)); + upp = NewRoutineDescriptor((ProcPtr)code, kPlainInfo, kM68kISA); + called("68k descriptor", plain(upp)); + DisposeRoutineDescriptor(upp); + + line("# Fat"); + upp = NewFatRoutineDescriptor((ProcPtr)code, (ProcPtr)targetA, kPlainInfo); + called("NewFatRoutineDescriptor(68k 7, PowerPC A)", plain(upp)); + { + Record r[2] = { { kM68kISA, 0, (long)code, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo } }; + called("records 68k 7, PowerPC A", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kM68kISA, 0, (long)code, 0, kPlainInfo } }; + called("records PowerPC A, 68k 7", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo } }; + called("records PowerPC A, PowerPC B", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kM68kISA, 0, (long)code, 0, kPlainInfo }, { kM68kISA, 0, (long)code68k(8), 0, kPlainInfo } }; + called("records 68k 7, 68k 8", plain(build(0, 2, r, 0))); + } + { + Record r[3] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo }, + { kPowerPCISA, 0, (long)targetC, 0, kPlainInfo } }; + called("records PowerPC A, B, C", plain(build(0, 3, r, 0))); + } + { + Record r[3] = { { kM68kISA, 0, (long)code, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, + { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo } }; + called("records 68k 7, PowerPC A, PowerPC B", plain(build(0, 3, r, 0))); + } + { + Record r[3] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo }, + { kM68kISA, 0, (long)code, 0, kPlainInfo } }; + called("records PowerPC A, PowerPC B, 68k 7", plain(build(0, 3, r, 0))); + } + { + Record r[2] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo } }; + rd = build(0, 2, r, 0); + rd->routineCount = 0; + called("records PowerPC A, PowerPC B, routineCount 0", plain(rd)); + } + + line("# Routine flags"); + { + Record r[2] = { { kPowerPCISA, 4, (long)targetA, 0, kPlainInfo }, { kM68kISA, 0, (long)code, 0, kPlainInfo } }; + called("records PowerPC A kUseNativeISA, 68k 7", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kM68kISA, 4, (long)code, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo } }; + called("records 68k 7 kUseNativeISA, PowerPC A", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kPowerPCISA, 4, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo } }; + called("records PowerPC A kUseNativeISA, PowerPC B", plain(build(0, 2, r, 0))); + } + { + Record r[2] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kPowerPCISA, 4, (long)targetB, 0, kPlainInfo } }; + called("records PowerPC A, PowerPC B kUseNativeISA", plain(build(0, 2, r, 0))); + } + + line("# Reuse"); + { + /* One block, called, then rewritten in place and called again. */ + Record r[2] = { { kPowerPCISA, 0, (long)targetA, 0, kPlainInfo }, { kM68kISA, 0, (long)code, 0, kPlainInfo } }; + rd = build(0, 2, r, 0); + called("records PowerPC A, 68k 7", plain(rd)); + rd->routineRecords[0].ISA = kM68kISA; rd->routineRecords[0].procDescriptor = (ProcPtr)code; + rd->routineRecords[1].ISA = kPowerPCISA; rd->routineRecords[1].procDescriptor = (ProcPtr)targetB; + called("same block rewritten to 68k 7, PowerPC B", plain(rd)); + DisposePtr((Ptr)rd); + { + Record s[2] = { { kPowerPCISA, 0, (long)targetC, 0, kPlainInfo }, { kPowerPCISA, 0, (long)targetB, 0, kPlainInfo } }; + RoutineDescriptor *again = build(0, 2, s, 0); + snprintf(label, sizeof label, "new block %s the disposed one: records PowerPC C, PowerPC B", + again == rd ? "at the address of" : "not at"); + called(label, plain(again)); + } + } + + line("# Dispatched, selectors not indexable"); + { + Record r[3] = { + { kPowerPCISA, 0, (long)targetA, 5, kDispatchedInfo }, + { kPowerPCISA, kDontPassSelector, (long)targetB, 9, kDispatchedInfo }, + { kPowerPCISA, kRoutineIsDispatchedDefaultRoutine, (long)targetC, 1, kDispatchedInfo } }; + rd = build(kSelectorsAreNotIndexable, 3, r, 0); + called("selector 5 (A)", dispatched(rd, 5)); + called("selector 9 (B, kDontPassSelector)", dispatched(rd, 9)); + called("selector 7 (none; C is the default)", dispatched(rd, 7)); + called("selector 1 (C's own)", dispatched(rd, 1)); + called("plain procedure information", plain(rd)); + } + { + Record r[4] = { + { kPowerPCISA, 0, (long)targetA, 0, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetB, 1, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetC, 2, kDispatchedInfo }, + { kM68kISA, 0, (long)code68k(6), 3, kDispatchedInfo } }; + for (i = 0; i < 4; i++) { + rd = build(kSelectorsAreNotIndexable, 4, r, 0); + snprintf(label, sizeof label, "A 0, B 1, C 2, 68k 6 3: selector %d", i); + called(label, dispatched(rd, i)); + } + } + { + Record r[2] = { + { kPowerPCISA, 0, (long)targetA, 3, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetB, 3, kDispatchedInfo } }; + called("two records with selector 3 (A, B)", dispatched(build(kSelectorsAreNotIndexable, 2, r, 0), 3)); + } + { + Record r[2] = { + { kM68kISA, 0, (long)code, 4, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetA, 4, kDispatchedInfo } }; + called("selector 4 in 68k 7 and PowerPC A", dispatched(build(kSelectorsAreNotIndexable, 2, r, 0), 4)); + } + + line("# Dispatched, selectors indexable"); + { + Record r[3] = { + { kPowerPCISA, 0, (long)targetA, 100, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetB, 101, kDispatchedInfo }, + { kPowerPCISA, 0, (long)targetC, 102, kDispatchedInfo } }; + for (i = 0; i < 3; i++) { + rd = build(kSelectorsAreIndexable, 3, r, 0); + snprintf(label, sizeof label, "A 100, B 101, C 102: selector %d", i); + called(label, dispatched(rd, i)); + } + called("selector 101 (B's own)", dispatched(build(kSelectorsAreIndexable, 3, r, 0), 101)); + } + + line("# Stack dispatched"); + { + Record r[3] = { + { kPowerPCISA, 0, (long)targetA, 0, kStackDispatchedInfo }, + { kPowerPCISA, 0, (long)targetB, 1, kStackDispatchedInfo }, + { kPowerPCISA, 0, (long)targetC, 2, kStackDispatchedInfo } }; + for (i = 0; i < 3; i++) { + rd = build(kSelectorsAreNotIndexable, 3, r, 0); + snprintf(label, sizeof label, "A 0, B 1, C 2: selector %d", i); + seen[0] = seen[1] = 0; + called(label, CallUniversalProc((UniversalProcPtr)rd, kStackDispatchedInfo, (short)i, 0x11L, 0x22L)); + } + } + + line("# Relative 68k"); + { + Record r[1] = { { kM68kISA, kProcDescriptorIsRelative, 64, 0, kPlainInfo } }; + rd = build(0, 1, r, 64); + BlockMoveData(code68k(9), (Ptr)rd + 64, 4); + called("68k, relative 64 to 68k 9", plain(rd)); + } + + line("# Not found"); + { + Record r[1] = { { kPowerPCISA, 0, (long)targetA, 5, kDispatchedInfo } }; + called("selector 6, no default", dispatched(build(kSelectorsAreNotIndexable, 1, r, 0), 6)); + } + + line("# Relative PowerPC, not needing preparation"); + { + /* A copy of targetB's transition vector 64 bytes after the descriptor's start. */ + Record r[1] = { { kPowerPCISA, kProcDescriptorIsRelative, 64, 0, kPlainInfo } }; + rd = build(0, 1, r, 64); + BlockMoveData((Ptr)targetB, (Ptr)rd + 64, 8); + called("PowerPC, relative 64 to B's transition vector", plain(rd)); + } + line("# Done"); + FSClose(out); + return 0; +} diff --git a/ReferenceTests/Retro68/README.md b/ReferenceTests/Retro68/README.md index 9a9024b..6b33abc 100644 --- a/ReferenceTests/Retro68/README.md +++ b/ReferenceTests/Retro68/README.md @@ -196,3 +196,36 @@ every line. Its output on Mac OS 9.2.2 is `GetPtrSize(nil)` gave memAZErr (-113). `HeapZoneTests` checks `HeapZone` against these. + +## Mixed Mode + +`MixedModeCapture.c` records the routine descriptors `NewRoutineDescriptor` +and `NewFatRoutineDescriptor` write, then calls descriptors it builds itself +with `CallUniversalProc` from PowerPC code. Its PowerPC targets return a +letter and keep their arguments; its 68k code is `moveq #n,d0; rts`, so a +68k routine returns n. It never disposes a descriptor it has called, so that +no two share an address. Its output on Mac OS 9.2.2 is +`MixedMode-macos-9.2.2-ppc.txt` (CR line endings). Its last case crashed +with a type 3 error, as it did in an earlier run, so the file ends with that +case's heading. + +- Descriptors: `NewRoutineDescriptor` wrote 32 bytes, one record with + kUseNativeISA (0x0004) and the ISA byte as given, even 02, 10 and 11. With + a nil procedure it returned nil, MemError 0. `NewFatRoutineDescriptor` + wrote 52 bytes: a 68k record, then a PowerPC one, with no flags. + `DisposeRoutineDescriptor(nil)` gave noErr. +- Choice of record: with routineCount 0, record 0 ran. Otherwise record 1 + ran, whatever the records' ISAs, flags and selectors and the descriptor's + flags: [PowerPC, 68k] ran the 68k code. Rewriting a descriptor in place + changed what ran, so nothing was cached by address. +- Selectors: none of the dispatched calls dispatched. The selector reached + the target as its first argument, kDontPassSelector or not, and a + selector no record had, with no default, ran record 0. +- Targets: 68k code given without a descriptor ran as 68k code, and a + relative 68k target was an offset from the descriptor's start. A relative + PowerPC target that didn't need preparing crashed. + +The capture doesn't cover 68k callers, which reach a descriptor through its +trap word, or PowerPC fragments that need preparing. `MixedModeTests` checks +`GraphiteMixedMode` against the capture; Graphite throws for the cases that +crashed or weren't run. diff --git a/Sources/GraphiteMixedMode/MixedMode.swift b/Sources/GraphiteMixedMode/MixedMode.swift new file mode 100644 index 0000000..9c78c30 --- /dev/null +++ b/Sources/GraphiteMixedMode/MixedMode.swift @@ -0,0 +1,188 @@ +// The Mixed Mode Manager's policy, as data: which routine a universal +// procedure pointer calls and where its code is, for the host to run. The +// host runs the code; Graphite decides what code it is. +// +// The rules are Mac OS 9.2.2's, from ReferenceTests/Retro68/ +// MixedMode-macos-9.2.2-ppc.txt, for CallUniversalProc from PowerPC code. +// Where Mac OS 9 crashed, or the capture didn't go, Graphite throws rather +// than guess. + +import GraphiteCore +import GraphiteMemory + +/// The code a universal procedure pointer reaches. +public enum RoutineTarget: Hashable, Sendable { + + /// A 68k entry point. Graphite never treats one as PowerPC code. + case m68k(entry: UInt32) + + /// A PowerPC transition vector: code and TOC addresses. + case powerPC(transitionVector: UInt32) + + /// A PowerPC fragment the Code Fragment Manager must prepare first; its + /// main symbol is the routine. + case unpreparedFragment(container: UInt32) +} + +/// What the host runs for a call through a universal procedure pointer. +public struct MixedModeInvocation: Hashable, Sendable { + + public var target: RoutineTarget + + /// The record that was chosen, or nil for 68k code given without a + /// descriptor. + public var record: RoutineRecord? + + public var recordIndex: Int? + + /// The caller's procedure information, which describes the arguments + /// as the caller passes them. On Mac OS 9 a PowerPC target got them as + /// given: a dispatched call's selector first, whatever the record's + /// flags said. + public var procedureInformation: ProcedureInformation + + public init(target: RoutineTarget, record: RoutineRecord?, recordIndex: Int?, + procedureInformation: ProcedureInformation) { + self.target = target + self.record = record + self.recordIndex = recordIndex + self.procedureInformation = procedureInformation + } +} + +/// A universal procedure pointer that Graphite won't resolve. +public enum MixedModeError: Error, Hashable, Sendable { + + case descriptor(RoutineDescriptorError) + + /// The chosen record names an instruction set or runtime Graphite + /// doesn't run: CFM-68k, or one NewRoutineDescriptor took as given. + case unsupportedISA(InstructionSetArchitecture) + + /// A PowerPC record with a relative target that doesn't need + /// preparing: Mac OS 9.2.2 jumped to the offset itself and crashed. + case relativePreparedPowerPC(offset: UInt32) + + /// A record that needs preparing with an absolute target, or a 68k one + /// that needs preparing: Inside Macintosh allows neither. + case preparationWithoutRelativeTarget(RoutineFlags) + + /// A nil universal procedure pointer. + case nilProcedure +} + +public enum MixedMode { + + /// The record CallUniversalProc runs for a PowerPC caller on Mac OS + /// 9.2.2: record 0 when there's one, and otherwise record 1, whatever + /// the records' instruction sets, flags and selectors and the + /// descriptor's flags. That's where a fat descriptor keeps its PowerPC + /// routine. Mac OS 9 did no dispatching on a selector there. + public static func recordIndex(forPowerPCCaller descriptor: RoutineDescriptor) -> Int { + descriptor.records.count > 1 ? 1 : 0 + } + + /// Where a record's code is, for a descriptor at `base`. + public static func target(of record: RoutineRecord, descriptorAt base: UInt32) throws(MixedModeError) -> RoutineTarget { + let relative = record.flags.contains(.procDescriptorIsRelative) + let preparing = record.flags.contains(.fragmentNeedsPreparing) + let address = relative ? base &+ record.procDescriptor : record.procDescriptor + switch record.isa { + case .m68k: + guard !preparing else { throw .preparationWithoutRelativeTarget(record.flags) } + return .m68k(entry: address) + case .powerPC: + switch (relative, preparing) { + case (false, false): return .powerPC(transitionVector: address) + case (true, true): return .unpreparedFragment(container: address) + case (true, false): throw .relativePreparedPowerPC(offset: record.procDescriptor) + case (false, true): throw .preparationWithoutRelativeTarget(record.flags) + } + default: + throw .unsupportedISA(record.isa) + } + } + + /// What CallUniversalProc from PowerPC code runs for a descriptor at + /// `base`. + public static func invocation(of descriptor: RoutineDescriptor, at base: UInt32, + procedureInformation: ProcedureInformation) throws(MixedModeError) -> MixedModeInvocation { + let index = recordIndex(forPowerPCCaller: descriptor) + let record = descriptor.records[index] + return MixedModeInvocation(target: try target(of: record, descriptorAt: base), record: record, + recordIndex: index, procedureInformation: procedureInformation) + } + + /// What CallUniversalProc from PowerPC code runs for a universal + /// procedure pointer in guest memory. One that doesn't start with the + /// Mixed Mode trap is 68k code, as on Mac OS 9. + public static func invocation(of procedure: UInt32, in memory: any GuestMemory, + procedureInformation: ProcedureInformation) throws(MixedModeError) -> MixedModeInvocation { + guard procedure != 0 else { throw .nilProcedure } + let descriptor: RoutineDescriptor + do { + descriptor = try read(at: procedure, from: memory) + } catch .notADescriptor { + return MixedModeInvocation(target: .m68k(entry: procedure), record: nil, recordIndex: nil, + procedureInformation: procedureInformation) + } catch { + throw .descriptor(error) + } + return try invocation(of: descriptor, at: procedure, procedureInformation: procedureInformation) + } + + /// Reads a routine descriptor from guest memory. + public static func read(at address: UInt32, from memory: any GuestMemory) throws(RoutineDescriptorError) -> RoutineDescriptor { + let header: [UInt8] + do { + let trap = try memory.read(address, count: 2) + guard trap == [0xAA, 0xFE] else { throw RoutineDescriptorError.notADescriptor(UInt16(trap[0]) << 8 | UInt16(trap[1])) } + header = try memory.read(address, count: RoutineDescriptor.headerSize) + } catch let error as RoutineDescriptorError { + throw error + } catch let error as MacError { + throw .memory(error) + } catch { + preconditionFailure("\(error)") + } + let last = Int16(bitPattern: UInt16(header[10]) << 8 | UInt16(header[11])) + guard last >= 0 else { throw .noRecords(last) } + do { + return try RoutineDescriptor(memory.read(address, count: RoutineDescriptor.size(records: Int(last) + 1))) + } catch let error as RoutineDescriptorError { + throw error + } catch let error as MacError { + throw .memory(error) + } catch { + preconditionFailure("\(error)") + } + } + + /// NewRoutineDescriptor: a nonrelocatable block in `zone` holding a + /// one-record descriptor with kUseNativeISA and the ISA as given. A nil + /// procedure gives nil, with no error, as on Mac OS 9.2.2. + public static func newRoutineDescriptor(_ procedure: UInt32, _ information: ProcedureInformation, + _ isa: InstructionSetArchitecture, in zone: HeapZone) throws(MacError) -> UInt32 { + guard procedure != 0 else { return 0 } + return try place(RoutineDescriptor(procedure: procedure, procedureInformation: information, isa: isa), in: zone) + } + + /// NewFatRoutineDescriptor: a 68k record and a PowerPC one, no flags. + public static func newFatRoutineDescriptor(m68k: UInt32, powerPC: UInt32, _ information: ProcedureInformation, + in zone: HeapZone) throws(MacError) -> UInt32 { + try place(RoutineDescriptor(m68k: m68k, powerPC: powerPC, procedureInformation: information), in: zone) + } + + /// DisposeRoutineDescriptor: DisposePtr, so nil is fine. + public static func disposeRoutineDescriptor(_ descriptor: UInt32, in zone: HeapZone) throws(MacError) { + guard descriptor != 0 else { return } + try zone.disposePointer(descriptor) + } + + private static func place(_ descriptor: RoutineDescriptor, in zone: HeapZone) throws(MacError) -> UInt32 { + let bytes = descriptor.bytes + let address = try zone.newPointer(Int32(bytes.count)) + try zone.memory.write(bytes, at: address) + return address + } +} diff --git a/Sources/GraphiteMixedMode/ProcedureInformation.swift b/Sources/GraphiteMixedMode/ProcedureInformation.swift new file mode 100644 index 0000000..84a7e81 --- /dev/null +++ b/Sources/GraphiteMixedMode/ProcedureInformation.swift @@ -0,0 +1,211 @@ +// A routine's procedure information: the 32-bit ProcInfoType that tells +// the Mixed Mode Manager how a routine takes its parameters and gives its +// result. The layout is Inside Macintosh: PowerPC System Software's, +// "Procedure Information": a calling convention in bits 0-3, then a result +// size in bits 4-5, then fields that depend on the convention. + +/// How many bytes a parameter, result or selector takes. +public enum ValueSize: UInt8, CaseIterable, Hashable, Sendable { + + case none = 0, one = 1, two = 2, four = 3 + + public var byteCount: Int { + switch self { + case .none: 0 + case .one: 1 + case .two: 2 + case .four: 4 + } + } +} + +/// The calling conventions a procedure information names. +public enum CallingConvention: UInt8, CaseIterable, Hashable, Sendable { + case pascalStackBased = 0 + case cStackBased = 1 + case registerBased = 2 + case thinkCStackBased = 5 + case d0DispatchedPascalStackBased = 8 + case d0DispatchedCStackBased = 9 + case d1DispatchedPascalStackBased = 12 + case stackDispatchedPascalStackBased = 14 + case specialCase = 15 +} + +/// A 680x0 register, or a condition code bit, as procedure information +/// encodes it. +public enum M68kRegister: UInt8, CaseIterable, Hashable, Sendable { + case d0 = 0, d1 = 1, d2 = 2, d3 = 3 + case a0 = 4, a1 = 5, a2 = 6, a3 = 7 + case d4 = 8, d5 = 9, d6 = 10, d7 = 11 + case a4 = 12, a5 = 13, a6 = 14 + case conditionC = 16, conditionV = 17, conditionZ = 18, conditionN = 19, conditionX = 20 +} + +/// The routines whose conventions no procedure information can spell out, +/// which the Mixed Mode Manager knows by number. +public enum SpecialCase: UInt8, CaseIterable, Hashable, Sendable { + /// Also the caret hook. + case highHook = 0 + case eolHook = 1 + /// Also the TextWidth hook. + case widthHook = 2 + case nWidthHook = 3 + case drawHook = 4 + case hitTestHook = 5 + case teFindWord = 6 + case protocolHandler = 7 + case socketListener = 8 + case teRecalc = 9 + case teDoText = 10 + case gneFilterProc = 11 + case mBarHook = 12 +} + +/// Where a dispatched routine's selector comes from. +public enum SelectorLocation: Hashable, Sendable { + case d0, d1, stack +} + +/// A register-based routine's parameter. +public struct RegisterParameter: Hashable, Sendable { + + public var size: ValueSize + + public var register: M68kRegister + + public init(size: ValueSize, register: M68kRegister) { + self.size = size + self.register = register + } +} + +/// Procedure information that Graphite won't take as it stands. +public enum ProcedureInformationError: Error, Hashable, Sendable { + + /// Bits 0-3 name no calling convention. + case unknownCallingConvention(UInt8) + + /// Special case bits that name no special case. + case unknownSpecialCase(UInt8) + + /// Bits set past the last parameter: after a parameter of no size, or + /// above a special case's number. The Mixed Mode Manager reads up to + /// the first parameter of no size, so it would ignore them. + case bitsAfterParameters(UInt32) + + /// A register-based result of no size in a register that isn't D0, or + /// a result in a condition code bit given a size. + case resultLocation(M68kRegister) + + /// A result register code that names no register. + case unknownRegister(UInt8) +} + +/// A routine's procedure information, as Mixed Mode encodes it. +public struct ProcedureInformation: RawRepresentable, Hashable, Sendable { + + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// What the bits say, laid out. + public enum Layout: Hashable, Sendable { + + /// Parameters on the stack, in the order they're declared: Pascal, + /// C or THINK C. + case stack(CallingConvention, result: ValueSize, parameters: [ValueSize]) + + /// Parameters in registers D0-D3 and A0-A3, and the result in any + /// register or condition code bit. + case registers(result: ValueSize, resultRegister: M68kRegister, parameters: [RegisterParameter]) + + /// A selector, then parameters on the stack. + case dispatched(CallingConvention, selector: SelectorLocation, selectorSize: ValueSize, + result: ValueSize, parameters: [ValueSize]) + + case specialCase(SpecialCase) + } + + public static let maximumStackParameters = 13 + public static let maximumDispatchedParameters = 12 + public static let maximumRegisterParameters = 4 + + /// The layout, if the bits make one. + public func layout() throws(ProcedureInformationError) -> Layout { + let code = UInt8(rawValue & 0xF) + guard let convention = CallingConvention(rawValue: code) else { + throw .unknownCallingConvention(code) + } + let result = ValueSize(rawValue: UInt8(rawValue >> 4 & 3))! + switch convention { + case .pascalStackBased, .cStackBased, .thinkCStackBased: + return .stack(convention, result: result, parameters: try Self.sizes(rawValue, from: 6)) + case .d0DispatchedPascalStackBased, .d0DispatchedCStackBased, + .d1DispatchedPascalStackBased, .stackDispatchedPascalStackBased: + let location: SelectorLocation = switch convention { + case .d1DispatchedPascalStackBased: .d1 + case .stackDispatchedPascalStackBased: .stack + default: .d0 + } + return .dispatched(convention, selector: location, + selectorSize: ValueSize(rawValue: UInt8(rawValue >> 6 & 3))!, + result: result, parameters: try Self.sizes(rawValue, from: 8)) + case .registerBased: + let code = UInt8(rawValue >> 6 & 0x1F) + guard let register = M68kRegister(rawValue: code) else { throw .unknownRegister(code) } + let isCondition = register.rawValue >= M68kRegister.conditionC.rawValue + // Apple: a result in a condition code bit has size 0; otherwise + // a routine with no result leaves the location 0. + if isCondition ? result != .none : (result == .none && register != .d0) { + throw .resultLocation(register) + } + var parameters: [RegisterParameter] = [] + var shift: UInt32 = 11 + while shift + 5 <= 32 { + let field = rawValue >> shift & 0x1F + guard let size = ValueSize(rawValue: UInt8(field & 3)), size != .none else { break } + parameters.append(RegisterParameter(size: size, register: M68kRegister(rawValue: UInt8(field >> 2))!)) + shift += 5 + } + let rest = shift >= 32 ? 0 : rawValue >> shift + guard rest == 0 else { throw .bitsAfterParameters(rest << shift) } + return .registers(result: result, resultRegister: register, parameters: parameters) + case .specialCase: + let number = UInt8(rawValue >> 4 & 0x3F) + guard let special = SpecialCase(rawValue: number) else { throw .unknownSpecialCase(number) } + let rest = rawValue >> 10 + guard rest == 0 else { throw .bitsAfterParameters(rest << 10) } + return .specialCase(special) + } + } + + /// Two-bit sizes from a bit up, to the first of no size. + private static func sizes(_ value: UInt32, from start: UInt32) throws(ProcedureInformationError) -> [ValueSize] { + var sizes: [ValueSize] = [] + var shift = start + while shift < 32 { + let size = ValueSize(rawValue: UInt8(value >> shift & 3))! + if size == .none { break } + sizes.append(size) + shift += 2 + } + let rest = shift >= 32 ? 0 : value >> shift + guard rest == 0 else { throw .bitsAfterParameters(rest << shift) } + return sizes + } + + /// Procedure information for a stack-based routine. + public static func stack(_ convention: CallingConvention = .cStackBased, result: ValueSize = .none, + parameters: [ValueSize] = []) -> ProcedureInformation { + precondition([.pascalStackBased, .cStackBased, .thinkCStackBased].contains(convention)) + precondition(parameters.count <= maximumStackParameters && !parameters.contains(.none)) + var value = UInt32(convention.rawValue) | UInt32(result.rawValue) << 4 + for (index, size) in parameters.enumerated() { + value |= UInt32(size.rawValue) << (6 + 2 * UInt32(index)) + } + return ProcedureInformation(rawValue: value) + } +} diff --git a/Sources/GraphiteMixedMode/RoutineDescriptor.swift b/Sources/GraphiteMixedMode/RoutineDescriptor.swift new file mode 100644 index 0000000..db6b3e5 --- /dev/null +++ b/Sources/GraphiteMixedMode/RoutineDescriptor.swift @@ -0,0 +1,238 @@ +// Routine descriptors as the guest keeps them: a 12-byte header that starts +// with the Mixed Mode trap word, then 20-byte routine records, big-endian +// and two-byte aligned. A universal procedure pointer points at one, or, on +// a PowerPC Mac, straight at 68k code. + +import GraphiteCore + +/// An instruction set and the runtime its code expects: the architecture in +/// the low four bits and the runtime in the high four. +public struct InstructionSetArchitecture: RawRepresentable, Hashable, Sendable { + + public var rawValue: UInt8 + + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + /// 68k code with the classic runtime. + public static let m68k = InstructionSetArchitecture(rawValue: 0x00) + + /// PowerPC code. + public static let powerPC = InstructionSetArchitecture(rawValue: 0x01) + + /// 68k code with CFM-68k's runtime. + public static let cfm68k = InstructionSetArchitecture(rawValue: 0x10) +} + +/// A routine record's flags. +public struct RoutineFlags: OptionSet, Hashable, Sendable { + + public var rawValue: UInt16 + + public init(rawValue: UInt16) { + self.rawValue = rawValue + } + + /// The target is an offset from the descriptor's start. + public static let procDescriptorIsRelative = RoutineFlags(rawValue: 0x01) + + /// The target is a PowerPC fragment the Code Fragment Manager has yet + /// to prepare. + public static let fragmentNeedsPreparing = RoutineFlags(rawValue: 0x02) + + /// Run the routine in the native instruction set: what + /// NewRoutineDescriptor sets on Mac OS 9. + public static let useNativeISA = RoutineFlags(rawValue: 0x04) + + /// A dispatched routine isn't given its selector. + public static let dontPassSelector = RoutineFlags(rawValue: 0x08) + + /// The routine a dispatched call goes to when no record has its selector. + public static let isDispatchedDefaultRoutine = RoutineFlags(rawValue: 0x10) + + /// The flags Inside Macintosh defines. + public static let known: RoutineFlags = [.procDescriptorIsRelative, .fragmentNeedsPreparing, .useNativeISA, + .dontPassSelector, .isDispatchedDefaultRoutine] +} + +/// One routine of a descriptor. +public struct RoutineRecord: Hashable, Sendable { + + public static let size = 20 + + public var procedureInformation: ProcedureInformation + + public var reserved1: UInt8 + + public var isa: InstructionSetArchitecture + + public var flags: RoutineFlags + + /// An address, or an offset from the descriptor's start: of 68k code, + /// a PowerPC transition vector, or a fragment to prepare. + public var procDescriptor: UInt32 + + public var reserved2: UInt32 + + /// A dispatched routine's selector. + public var selector: UInt32 + + public init(procedureInformation: ProcedureInformation, isa: InstructionSetArchitecture, + flags: RoutineFlags = [], procDescriptor: UInt32, selector: UInt32 = 0, + reserved1: UInt8 = 0, reserved2: UInt32 = 0) { + self.procedureInformation = procedureInformation + self.reserved1 = reserved1 + self.isa = isa + self.flags = flags + self.procDescriptor = procDescriptor + self.reserved2 = reserved2 + self.selector = selector + } +} + +/// A routine descriptor's own flags. +public struct RoutineDescriptorFlags: OptionSet, Hashable, Sendable { + + public var rawValue: UInt8 + + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + /// A dispatched call's selector is the index of its record. + public static let selectorsAreIndexable = RoutineDescriptorFlags(rawValue: 0x01) +} + +/// Bytes that aren't a routine descriptor Graphite takes. +public enum RoutineDescriptorError: Error, Hashable, Sendable { + + /// The first two bytes aren't the Mixed Mode trap, 0xAAFE: on a PowerPC + /// Mac, a pointer to 68k code. + case notADescriptor(UInt16) + + /// A version other than 7, the only one there is. + case unsupportedVersion(UInt8) + + /// A negative routineCount, the index of the last record. + case noRecords(Int16) + + /// Fewer bytes than the header and records need. + case truncated(needed: Int, available: Int) + + /// The guest's memory refused a read. + case memory(MacError) +} + +/// A routine descriptor: the target of a universal procedure pointer. +public struct RoutineDescriptor: Hashable, Sendable { + + public static let trapWord: UInt16 = 0xAAFE + + public static let currentVersion: UInt8 = 7 + + public static let headerSize = 12 + + public var version: UInt8 + + public var flags: RoutineDescriptorFlags + + public var reserved1: UInt32 + + public var reserved2: UInt8 + + public var selectorInfo: UInt8 + + /// At least one; the header stores the last one's index. + public var records: [RoutineRecord] + + public init(records: [RoutineRecord], flags: RoutineDescriptorFlags = [], + version: UInt8 = currentVersion, reserved1: UInt32 = 0, reserved2: UInt8 = 0, selectorInfo: UInt8 = 0) { + precondition(!records.isEmpty && records.count <= Int(Int16.max) + 1) + self.version = version + self.flags = flags + self.reserved1 = reserved1 + self.reserved2 = reserved2 + self.selectorInfo = selectorInfo + self.records = records + } + + /// What NewRoutineDescriptor gives on Mac OS 9.2.2: one record with + /// the ISA as passed and kUseNativeISA. + public init(procedure: UInt32, procedureInformation: ProcedureInformation, isa: InstructionSetArchitecture) { + self.init(records: [RoutineRecord(procedureInformation: procedureInformation, isa: isa, + flags: .useNativeISA, procDescriptor: procedure)]) + } + + /// What NewFatRoutineDescriptor gives on Mac OS 9.2.2: a 68k record, + /// then a PowerPC one, neither with any flags. + public init(m68k: UInt32, powerPC: UInt32, procedureInformation: ProcedureInformation) { + self.init(records: [ + RoutineRecord(procedureInformation: procedureInformation, isa: .m68k, procDescriptor: m68k), + RoutineRecord(procedureInformation: procedureInformation, isa: .powerPC, procDescriptor: powerPC), + ]) + } + + /// The bytes one of `count` records takes. + public static func size(records count: Int) -> Int { + headerSize + count * RoutineRecord.size + } + + public var size: Int { Self.size(records: records.count) } + + /// The header's routineCount: the index of the last record. + private static func routineCount(_ bytes: [UInt8]) -> Int16 { + Int16(bitPattern: UInt16(bytes[10]) << 8 | UInt16(bytes[11])) + } + + /// Reads a descriptor from bytes: at least its header and records. + public init(_ bytes: [UInt8]) throws(RoutineDescriptorError) { + guard bytes.count >= 4 else { throw .truncated(needed: Self.headerSize, available: bytes.count) } + let trap = UInt16(bytes[0]) << 8 | UInt16(bytes[1]) + guard trap == Self.trapWord else { throw .notADescriptor(trap) } + guard bytes[2] == Self.currentVersion else { throw .unsupportedVersion(bytes[2]) } + guard bytes.count >= Self.headerSize else { throw .truncated(needed: Self.headerSize, available: bytes.count) } + let last = Self.routineCount(bytes) + guard last >= 0 else { throw .noRecords(last) } + let needed = Self.size(records: Int(last) + 1) + guard bytes.count >= needed else { throw .truncated(needed: needed, available: bytes.count) } + func u32(_ offset: Int) -> UInt32 { + bytes[offset ..< offset + 4].reduce(0) { $0 << 8 | UInt32($1) } + } + version = bytes[2] + flags = RoutineDescriptorFlags(rawValue: bytes[3]) + reserved1 = u32(4) + reserved2 = bytes[8] + selectorInfo = bytes[9] + records = (0 ... Int(last)).map { index in + let at = Self.headerSize + index * RoutineRecord.size + return RoutineRecord(procedureInformation: ProcedureInformation(rawValue: u32(at)), + isa: InstructionSetArchitecture(rawValue: bytes[at + 5]), + flags: RoutineFlags(rawValue: UInt16(bytes[at + 6]) << 8 | UInt16(bytes[at + 7])), + procDescriptor: u32(at + 8), selector: u32(at + 16), + reserved1: bytes[at + 4], reserved2: u32(at + 12)) + } + } + + /// The descriptor's bytes, as the guest keeps them. + public var bytes: [UInt8] { + var out: [UInt8] = [] + out.reserveCapacity(size) + func u16(_ value: UInt16) { out += [UInt8(value >> 8), UInt8(truncatingIfNeeded: value)] } + func u32(_ value: UInt32) { u16(UInt16(value >> 16)); u16(UInt16(truncatingIfNeeded: value)) } + u16(Self.trapWord) + out += [version, flags.rawValue] + u32(reserved1) + out += [reserved2, selectorInfo] + u16(UInt16(records.count - 1)) + for record in records { + u32(record.procedureInformation.rawValue) + out += [record.reserved1, record.isa.rawValue] + u16(record.flags.rawValue) + u32(record.procDescriptor) + u32(record.reserved2) + u32(record.selector) + } + return out + } +} diff --git a/Tests/GraphiteMixedModeTests/MixedModeTests.swift b/Tests/GraphiteMixedModeTests/MixedModeTests.swift new file mode 100644 index 0000000..4e146ab --- /dev/null +++ b/Tests/GraphiteMixedModeTests/MixedModeTests.swift @@ -0,0 +1,267 @@ +import Foundation +import Testing +import GraphiteCore +import GraphiteMemory +import GraphiteMixedMode + +/// Lines of the Mac OS 9.2.2 capture (ReferenceTests/Retro68, +/// MixedMode-macos-9.2.2-ppc.txt). +private let capture: [String] = { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let data = try! Data(contentsOf: root.appendingPathComponent("ReferenceTests/Retro68/MixedMode-macos-9.2.2-ppc.txt")) + return String(decoding: data, as: UTF8.self).split(separator: "\r").map(String.init) +}() + +/// The bytes the capture shows after a call's line. +private func capturedBytes(after call: String) -> [UInt8]? { + guard let index = capture.firstIndex(where: { $0.hasPrefix(call + " ->") }), + capture[index + 1].hasPrefix(" bytes:") else { return nil } + let hex = capture[index + 1].dropFirst(" bytes:".count).filter { !$0.isWhitespace } + return stride(from: 0, to: hex.count, by: 2).map { offset in + let start = hex.index(hex.startIndex, offsetBy: offset) + return UInt8(hex[start ..< hex.index(start, offsetBy: 2)], radix: 16)! + } +} + +/// What the capture says a call returned: the letter of a PowerPC target, +/// or the number a 68k one gave. +private func capturedResult(_ call: String) -> String? { + guard let line = capture.first(where: { $0.hasPrefix(call + " ->") }) else { return nil } + return line.split(separator: " -> ")[1].split(separator: ";")[0].trimmingCharacters(in: .whitespaces) +} + +@Suite struct ProcedureInformationTests { + + @Test func stackBased() throws { + // uppModalFilterProcInfo: Pascal, a Boolean, three pointers. + #expect(try ProcedureInformation(rawValue: 0xFD0).layout() + == .stack(.pascalStackBased, result: .one, parameters: [.four, .four, .four])) + #expect(try ProcedureInformation(rawValue: 0x3F1).layout() + == .stack(.cStackBased, result: .four, parameters: [.four, .four])) + // uppAECoercePtrProcInfo: six parameters and an OSErr. + #expect(try ProcedureInformation(rawValue: 0x3FFE0).layout() + == .stack(.pascalStackBased, result: .two, parameters: Array(repeating: .four, count: 6))) + #expect(try ProcedureInformation(rawValue: 0).layout() == .stack(.pascalStackBased, result: .none, parameters: [])) + #expect(ProcedureInformation.stack(.cStackBased, result: .four, parameters: [.four, .four]).rawValue == 0x3F1) + let thirteen = ProcedureInformation.stack(parameters: Array(repeating: .two, count: 13)) + #expect(try thirteen.layout() == .stack(.cStackBased, result: .none, parameters: Array(repeating: .two, count: 13))) + } + + @Test func dispatched() throws { + #expect(try ProcedureInformation(rawValue: 0xFB9).layout() + == .dispatched(.d0DispatchedCStackBased, selector: .d0, selectorSize: .two, result: .four, parameters: [.four, .four])) + #expect(try ProcedureInformation(rawValue: 0xFBE).layout() + == .dispatched(.stackDispatchedPascalStackBased, selector: .stack, selectorSize: .two, + result: .four, parameters: [.four, .four])) + #expect(try ProcedureInformation(rawValue: 0x7C).layout() + == .dispatched(.d1DispatchedPascalStackBased, selector: .d1, selectorSize: .one, result: .four, parameters: [])) + } + + @Test func registerBased() throws { + // A 4-byte result in D1, a long in A0 and a word in D2. + let value: UInt32 = 2 | 3 << 4 | 1 << 6 | (3 | 4 << 2) << 11 | (2 | 2 << 2) << 16 + #expect(try ProcedureInformation(rawValue: value).layout() + == .registers(result: .four, resultRegister: .d1, parameters: [ + RegisterParameter(size: .four, register: .a0), RegisterParameter(size: .two, register: .d2)])) + // A result in the Z bit, of no size. + #expect(try ProcedureInformation(rawValue: 2 | 18 << 6).layout() + == .registers(result: .none, resultRegister: .conditionZ, parameters: [])) + #expect(throws: ProcedureInformationError.resultLocation(.conditionZ)) { + try ProcedureInformation(rawValue: 2 | 1 << 4 | 18 << 6).layout() + } + #expect(throws: ProcedureInformationError.unknownRegister(15)) { + try ProcedureInformation(rawValue: 2 | 3 << 4 | 15 << 6).layout() + } + } + + @Test func specialCases() throws { + #expect(try ProcedureInformation(rawValue: 15 | 11 << 4).layout() == .specialCase(.gneFilterProc)) + #expect(try ProcedureInformation(rawValue: 15).layout() == .specialCase(.highHook)) + // Mac OS 9.2.2 copied FFFFFFFF into a descriptor; Graphite can't + // say how to call it. + #expect(throws: ProcedureInformationError.unknownSpecialCase(0x3F)) { + try ProcedureInformation(rawValue: 0xFFFF_FFFF).layout() + } + } + + @Test func malformed() { + #expect(throws: ProcedureInformationError.unknownCallingConvention(3)) { + try ProcedureInformation(rawValue: 3).layout() + } + // A parameter after one of no size. + #expect(throws: ProcedureInformationError.bitsAfterParameters(3 << 8)) { + try ProcedureInformation(rawValue: 1 | 3 << 8).layout() + } + #expect(throws: ProcedureInformationError.bitsAfterParameters(1 << 10)) { + try ProcedureInformation(rawValue: 15 | 1 << 10).layout() + } + } +} + +@Suite struct RoutineDescriptorTests { + + /// Graphite writes the bytes Mac OS 9.2.2's NewRoutineDescriptor did, + /// whatever the procedure information and ISA. + @Test(arguments: [(UInt32(0), UInt8(1)), (0xFD0, 1), (0x3F1, 1), (0xFFFF_FFFF, 1), + (0xFD0, 0), (0xFD0, 2), (0xFD0, 0x10), (0xFD0, 0x11)]) + func newRoutineDescriptorBytes(information: UInt32, isa: UInt8) throws { + let hex = String(format: "%08X", information) + let call = isa == 1 + ? "NewRoutineDescriptor(12345678, \(hex), PowerPC)" + : "NewRoutineDescriptor(12345678, \(hex), ISA \(String(format: "%02X", isa)))" + let expected = try #require(capturedBytes(after: call)) + let descriptor = RoutineDescriptor(procedure: 0x1234_5678, procedureInformation: ProcedureInformation(rawValue: information), + isa: InstructionSetArchitecture(rawValue: isa)) + #expect(descriptor.bytes == expected) + #expect(try RoutineDescriptor(expected) == descriptor) + } + + @Test func newFatRoutineDescriptorBytes() throws { + let expected = try #require(capturedBytes(after: "NewFatRoutineDescriptor(11111110, 22222220, 00000FD0)")) + let descriptor = RoutineDescriptor(m68k: 0x1111_1110, powerPC: 0x2222_2220, + procedureInformation: ProcedureInformation(rawValue: 0xFD0)) + #expect(descriptor.bytes == expected) + #expect(descriptor.size == 52) + #expect(try RoutineDescriptor(expected) == descriptor) + } + + @Test func malformed() { + let good = RoutineDescriptor(procedure: 0x2000, procedureInformation: ProcedureInformation(rawValue: 0), isa: .powerPC).bytes + #expect(throws: RoutineDescriptorError.notADescriptor(0x7007)) { try RoutineDescriptor([0x70, 0x07, 0x4E, 0x75]) } + var version = good + version[2] = 6 + #expect(throws: RoutineDescriptorError.unsupportedVersion(6)) { try RoutineDescriptor(version) } + var negative = good + negative[10] = 0xFF; negative[11] = 0xFF + #expect(throws: RoutineDescriptorError.noRecords(-1)) { try RoutineDescriptor(negative) } + var two = good + two[11] = 1 + #expect(throws: RoutineDescriptorError.truncated(needed: 52, available: 32)) { try RoutineDescriptor(two) } + #expect(throws: RoutineDescriptorError.truncated(needed: 12, available: 2)) { try RoutineDescriptor([0xAA, 0xFE]) } + } +} + +@Suite struct MixedModeTests { + + private let plain = ProcedureInformation(rawValue: 0x3F1) + private let base: UInt32 = 0x8000 + + private func record(_ isa: InstructionSetArchitecture, _ target: UInt32, flags: RoutineFlags = [], + selector: UInt32 = 0) -> RoutineRecord { + RoutineRecord(procedureInformation: plain, isa: isa, flags: flags, procDescriptor: target, selector: selector) + } + + /// The routine the capture's call ran, from the records it built: + /// PowerPC targets by letter and 68k ones by the number they return. + private func ran(_ records: [(InstructionSetArchitecture, String)], flags: [RoutineFlags]? = nil, + descriptorFlags: RoutineDescriptorFlags = []) throws -> String { + let built = records.enumerated().map { index, entry in + record(entry.0, UInt32(0x1000 + index * 0x10), flags: flags?[index] ?? [], selector: UInt32(index)) + } + let descriptor = RoutineDescriptor(records: built, flags: descriptorFlags) + let invocation = try MixedMode.invocation(of: descriptor, at: base, procedureInformation: plain) + return records[try #require(invocation.recordIndex)].1 + } + + /// The records each captured call built, and Graphite's choice against + /// what Mac OS 9.2.2 ran. + @Test func recordSelectionMatchesTheCapture() throws { + let a = (InstructionSetArchitecture.powerPC, "A"), b = (InstructionSetArchitecture.powerPC, "B") + let c = (InstructionSetArchitecture.powerPC, "C") + let m7 = (InstructionSetArchitecture.m68k, "7"), m8 = (InstructionSetArchitecture.m68k, "8") + let m6 = (InstructionSetArchitecture.m68k, "6") + let cases: [(String, [(InstructionSetArchitecture, String)], [RoutineFlags]?, RoutineDescriptorFlags)] = [ + ("records 68k 7, PowerPC A", [m7, a], nil, []), + ("records PowerPC A, 68k 7", [a, m7], nil, []), + ("records PowerPC A, PowerPC B", [a, b], nil, []), + ("records 68k 7, 68k 8", [m7, m8], nil, []), + ("records PowerPC A, B, C", [a, b, c], nil, []), + ("records 68k 7, PowerPC A, PowerPC B", [m7, a, b], nil, []), + ("records PowerPC A, PowerPC B, 68k 7", [a, b, m7], nil, []), + ("records PowerPC A kUseNativeISA, 68k 7", [a, m7], [.useNativeISA, []], []), + ("records 68k 7 kUseNativeISA, PowerPC A", [m7, a], [.useNativeISA, []], []), + ("records PowerPC A kUseNativeISA, PowerPC B", [a, b], [.useNativeISA, []], []), + ("records PowerPC A, PowerPC B kUseNativeISA", [a, b], [[], .useNativeISA], []), + ("selector 5 (A)", [a, b, c], [[], .dontPassSelector, .isDispatchedDefaultRoutine], []), + ("selector 7 (none; C is the default)", [a, b, c], [[], .dontPassSelector, .isDispatchedDefaultRoutine], []), + ("A 0, B 1, C 2, 68k 6 3: selector 3", [a, b, c, m6], nil, []), + ("selector 4 in 68k 7 and PowerPC A", [m7, a], nil, []), + ("A 100, B 101, C 102: selector 0", [a, b, c], nil, .selectorsAreIndexable), + ("A 100, B 101, C 102: selector 2", [a, b, c], nil, .selectorsAreIndexable), + ("A 0, B 1, C 2: selector 0", [a, b, c], nil, []), + ("selector 6, no default", [a], nil, []), + ] + for (call, records, flags, descriptorFlags) in cases { + let expected = try #require(capturedResult(call), "\(call) isn't in the capture") + #expect(try ran(records, flags: flags, descriptorFlags: descriptorFlags) == expected, "\(call)") + } + // routineCount 0 with a second record after it: only record 0 counts. + #expect(capturedResult("records PowerPC A, PowerPC B, routineCount 0") == "A") + #expect(try ran([a]) == "A") + } + + @Test func targets() throws { + #expect(try MixedMode.target(of: record(.m68k, 0x40, flags: .procDescriptorIsRelative), descriptorAt: base) + == .m68k(entry: base + 0x40)) + #expect(try MixedMode.target(of: record(.m68k, 0x4000), descriptorAt: base) == .m68k(entry: 0x4000)) + #expect(try MixedMode.target(of: record(.powerPC, 0x4000), descriptorAt: base) == .powerPC(transitionVector: 0x4000)) + #expect(try MixedMode.target(of: record(.powerPC, 0x40, flags: [.procDescriptorIsRelative, .fragmentNeedsPreparing]), + descriptorAt: base) == .unpreparedFragment(container: base + 0x40)) + // Mac OS 9.2.2 crashed on this one: the capture stops before its line. + #expect(capture.last == "# Relative PowerPC, not needing preparation") + #expect(throws: MixedModeError.relativePreparedPowerPC(offset: 0x40)) { + try MixedMode.target(of: record(.powerPC, 0x40, flags: .procDescriptorIsRelative), descriptorAt: base) + } + #expect(throws: MixedModeError.preparationWithoutRelativeTarget(.fragmentNeedsPreparing)) { + try MixedMode.target(of: record(.powerPC, 0x4000, flags: .fragmentNeedsPreparing), descriptorAt: base) + } + #expect(throws: MixedModeError.unsupportedISA(.cfm68k)) { + try MixedMode.target(of: record(.cfm68k, 0x4000), descriptorAt: base) + } + #expect(throws: MixedModeError.unsupportedISA(InstructionSetArchitecture(rawValue: 2))) { + try MixedMode.target(of: record(InstructionSetArchitecture(rawValue: 2), 0x4000), descriptorAt: base) + } + } + + @Test func guestMemory() throws { + let memory = ByteGuestMemory(base: 0x1000, count: 4096) + let zone = HeapZone(memory: memory, range: 0x1000 ..< 0x2000) + let upp = try MixedMode.newRoutineDescriptor(0x3000, plain, .powerPC, in: zone) + #expect(try zone.pointerSize(upp) == 32) + let invocation = try MixedMode.invocation(of: upp, in: memory, procedureInformation: plain) + #expect(invocation.target == .powerPC(transitionVector: 0x3000)) + #expect(invocation.record?.flags == .useNativeISA) + #expect(invocation.recordIndex == 0) + try MixedMode.disposeRoutineDescriptor(upp, in: zone) + + let fat = try MixedMode.newFatRoutineDescriptor(m68k: 0x1800, powerPC: 0x3000, plain, in: zone) + #expect(try zone.pointerSize(fat) == 52) + #expect(try MixedMode.invocation(of: fat, in: memory, procedureInformation: plain).target + == .powerPC(transitionVector: 0x3000)) + + // As on Mac OS 9.2.2: no descriptor for a nil procedure, and nil is + // fine to dispose. + #expect(try MixedMode.newRoutineDescriptor(0, plain, .powerPC, in: zone) == 0) + try MixedMode.disposeRoutineDescriptor(0, in: zone) + #expect(zone.memError == 0) + + // 68k code given without a descriptor ran as 68k code. + #expect(capturedResult("68k code without a descriptor") == "7") + let code = try zone.newPointer(4) + try memory.write([0x70, 0x07, 0x4E, 0x75], at: code) + let m68k = try MixedMode.invocation(of: code, in: memory, procedureInformation: plain) + #expect(m68k.target == .m68k(entry: code)) + #expect(m68k.record == nil) + + #expect(throws: MixedModeError.nilProcedure) { try MixedMode.invocation(of: 0, in: memory, procedureInformation: plain) } + #expect(throws: MixedModeError.descriptor(.memory(.memoryAddress))) { + try MixedMode.invocation(of: 0x9000, in: memory, procedureInformation: plain) + } + // A header whose records run past the guest's memory. + try memory.write(Array(RoutineDescriptor(m68k: 0, powerPC: 0, procedureInformation: plain).bytes.prefix(12)), at: 0x1FF0) + #expect(throws: MixedModeError.descriptor(.memory(.memoryAddress))) { + try MixedMode.invocation(of: 0x1FF0, in: memory, procedureInformation: plain) + } + } +}