Skip to content

About

The 1.14d macOS Diablo II binary running natively on 32-bit Linux: Mach-O converted to ELF, Darwin/Carbon reimplemented in Zig, AGL translated to GLX. No wine, no emulation.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

d2mac-linux

The 1.14d macOS build of Diablo II — an i386 Mach-O — running natively on 32-bit Linux. No wine, no emulation, no virtualization: the same machine code, executed directly by the Linux kernel.

The container is statically converted from Mach-O to ELF. The ~641 Darwin/Carbon/AGL symbols the image dynamically binds against are reimplemented in Zig. AGL is translated to GLX, so the game draws through Mesa into Xvfb and can be watched over VNC.

Status

It boots to Diablo II's real main menu, takes mouse and keyboard input, and creates characters.

Known gaps:

  • Right-click is not yet distinguished from left-click. The engine carries the button kind in ECX/DL, which Ghidra's decompiler loses as phantom registers, so the classic-event path currently collapses both buttons onto one down/up pair.
  • Sound is not implemented.

Why this is possible at all

Three properties of the Mac binary, measured rather than assumed, are what make a native port tractable where a Windows build would not be:

property value consequence
LC_SYMTAB nsyms=643 against 641 imports the symbol table is only the imports; all game code is in the image
%fs/%gs operands 0 across 33,413 instructions no Darwin TLS to fake, and nothing that clashes with glibc's
flags 0x01200085 (MH_PIE) rebase opcodes are present, so the image can be slid anywhere

Darwin's stable ABI is libSystem, not the syscall layer. A statically linked Mach-O therefore touches the OS only through its bind table — which means the bind table, not the code, is the thing that has to be understood.

The two halves

src/machoelf — the converter

A host tool. It builds for whatever machine you are sitting on and never executes game code. It parses LC_SEGMENT, LC_DYLD_INFO_ONLY, LC_SYMTAB and LC_UNIXTHREAD, and emits a 32-bit Linux ELF:

  • ET_EXEC at a fixed base of 0x10000000, with rebase opcodes pre-applied. ET_DYN would let ld.so pick its own base and invalidate those fixups; fixing the load address means the image needs zero runtime relocations.
  • Dynamic binds become ordinary undefined ELF symbols, satisfied by the shim.
  • __mod_init_func becomes .init_array, __eh_frame becomes .eh_frame.
  • Ghidra's function names are emitted into .symtab, so gdb and perf show real names instead of +0x1a2b3c.

It also generates libd2stub.so from the import list: one return 0 stub per import that no real system library answers, plus a zeroed data object for imports that are addresses rather than call targets. A 13,661-name denylist built from the real i386 system libraries (src/machoelf/data/system_symbols.txt) keeps it from ever shadowing something glibc or libstdc++ should own.

src/shim — libd2mac.so

The imports themselves: Darwin libc, Carbon, the File Manager, Storm (MPQ) detours, a pthread ABI translation layer, BSD sockets, AGL→GLX, and an X11 backend. The shim runs from .init_array, which gives it a foothold after ld.so has mapped and relocated everything but before the game's entry point — the same position DllMain occupies in the Windows build.

Findings

The parts worth reading if you are doing something similar.

1. DT_NEEDED ordering is load-bearing

The emitted order is libd2mac.so, libc.so.6, libstdc++.so.6, libm.so.6, libgcc_s.so.1, libGL.so.1, libGLU.so.1, libd2stub.so. ld.so builds the global scope left to right, so whichever library appears first wins every symbol it defines.

The shim goes first deliberately: it has to intercept a handful of calls (notably sigaction, since the game installs its own fault handlers and would otherwise displace ours). It only exports what it actually implements, so everything it stays silent about — malloc, memcpy, the POSIX core — falls through to glibc behind it. Only what Darwin has and Linux does not has to be written.

The real libraries occupy their slots before libd2stub.so gets a look. Without that, something later in the process (Mesa dlopening its own libstdc++ through swrast_dri.so, for instance) binds those symbols to the stub, and a __cxa_begin_catch ends up executing whatever bytes follow xor eax,eax; ret.

2. Symbol versioning is a trap

The converted image carries no version references, and glibc's rule for an unversioned reference is deliberately to bind the oldest definition — the "old unversioned application" case in dl-lookup.c. For every pthread symbol whose ABI ever changed, that is the pre-2.3.2 LinuxThreads entry point, not the NPTL one anything modern expects.

pthread_cond_broadcast@GLIBC_2.0 reads its object as struct { pthread_cond_t *cond; } and dereferences word zero as a pointer. The game's cond had __wseq's low half sitting there, value 2 after two waits — hence a fault at 0x26, which is 2 plus the modern layout's __wrefs offset of 0x24. pthread_create@GLIBC_2.0 and pthread_attr_init@GLIBC_2.0 are the same trap for pthread_attr_t, and are why passing the game's attributes through ever returned EINVAL. Nothing about those objects was wrong: the callee was twenty years too old.

3. The pthread translation layer

The second, independent mismatch is layout. Darwin's pthread_cond_t is 28 bytes, glibc's is 48; Darwin's pthread_mutex_t is 44, glibc's is 24. Storm's event record pins the Darwin numbers exactly: 184 bytes, mutex at +0x08, cond at +0x34 (0x08 + 44), next field at +0x50 (0x34 + 28). Letting glibc initialise a cond in place there would run to +0x64 and scribble over the record's free-list link.

So the game's memory is never handed to glibc. Each Darwin object gets an 8-byte header written over its first two words — a tag plus a pointer to a lazily CAS-allocated, properly sized glibc object — and every operation forwards to that. An inline header rather than a side table, because the header travels with the bytes if the game's allocator copies or moves a record, and because a side table would need a lock on pthread_mutex_lock itself. A caller-range gate lets objects belonging to Mesa and libX11 pass through untouched.

4. The dominant failure class: stubs that return something plausible

By a wide margin the most expensive category. noErr, "not equal", "wait succeeded", null. Five separate multi-hour debugging sessions all bottomed out here:

  • mach_timebase_info returned 0 without writing its out-parameter, leaving denom at zero from BSS. The nanosecond conversion became a division by zero, the tick count could never advance, and every elapsed-time spin in the engine hung outright.
  • WaitNextEvent returned 0 without writing the EventRecord, so the launcher's do { } while (evt.what != 0) never exited and no frame was ever drawn.
  • sleep() returning 0 immediately turned Storm's async signal thread — parked in while (true) sleep(0xffffffff) — into a spinning core writing 14 million log lines a minute.
  • __error() returning null meant every errno access dereferenced null, which killed the accept thread the moment a client connected.
  • __cxa_guard_acquire returning 0 means "already initialised", so every C++ function-local static was silently skipped and left zeroed.

The lesson the repo now carries: a generated stub should log and abort by default, with an explicit allowlist for the ones that are genuinely safe to no-op. A return-value policy alone is not enough — several of these failed through an out-parameter that was never written, where the return value itself was fine.

5. A crash that looked like symbol interposition and wasn't

libd2stub.so was shadowing libstdc++'s RTTI vtables. They are version-suffixed exports (@@CXXABI_1.3), which is why raw-string nm diffs against the stub kept missing the overlap; a dynamic_cast jumped through code bytes read as a vtable. The interposition theory was disproved with LD_DEBUG=bindings, and the fix was the denylist above.

6. Indirect GLX renders nothing here

Direct contexts are required, which means Xvfb has to be started with +iglx.

7. Carbon's ABI is from 1984

  • The File Manager's ParamBlock is mac68k 2-byte packed (#pragma options align=mac68k); the union variants overlay the same bytes with different meanings.
  • EventRecord is 16 bytes with message at offset 2 and where as a Point{v, h} — v before h.
  • btnState (0x0080) in the modifiers field is set when the button is UP. That is the opposite of what everyone assumes on first read.

The BSD socket layer is a smaller version of the same problem: sockaddr_in begins with a length byte on Darwin, so Linux reads sin_len as the low half of the address family and answers EAFNOSUPPORT; SO_REUSEADDR is 4 here against 2 there, SOL_SOCKET 1 against 0xffff, FIONBIO 0x5421 against 0x8004667e. Only the calls that hit one of those are translated; socket, gethostbyname, inet_addr and inet_ntoa mean the same thing on both and resolve to glibc.

8. An app-mode inversion

Forcing app mode 1 on the belief that it meant "the client" was wrong. Mode 1 is D2Client::ClientModeInGame — an already joined game — which is why the client kept diving straight into gameplay. The launcher is mode 4.

The defect underneath: geD2DefaultApplicationMode (0x005c8a30) is only ever written by MACSETUP_CheckSystemRequirementsAndInitializeCDKey at 0x19c1fe, behind Gestalt OS-version, physical-memory, disk-space and DrawSprocket probes that cannot pass on Linux. The function returns false long before that write, so the global stayed 0 from BSS, and mode 0 indexes a {NULL, NULL} pair in the bootstrap table at 0x3e0eb8. ApplicationMain had nothing to dispatch and returned immediately: the process came up, opened its archives, brought up GL, and shut straight back down. The fix supplies the constant the skipped function was carrying, ahead of every reader, which leaves -client/-server on the command line still able to override it.

9. Input needed three separate fixes

  • An X server round-trip per query produced roughly ten seconds of lag. Pointer and keymap polls are now cached and re-query at most every 8 ms (125 Hz), above what any caller needs.
  • Polling drops button transitions: a press and release both completing between two polls reads as "no change" on both sides. Buttons now come from queued ButtonPress/ButtonRelease edges. Keys cannot use the same path — X routes key events by input focus, and Xvfb has no window manager to give any window focus — so keys stay polled.
  • A viewer disconnecting mid-gesture leaves the X server's own keymap latched with a key held. A snapshot with more keys down than a hand can manage is discarded, and a burst of changes after a long idle gap is adopted as a new baseline rather than replayed as phantom presses.

10. std.c.lseek silently returned 0

For a 4 MB file, on this target. That read as "empty archive" and made Storm reject a perfectly good MPQ. The 32-bit off_t ABI is easy to get wrong in a wrapper, so the file primitives now go to the kernel directly through int $0x80. (On i386, %ebx is the PIC GOT register, so the first syscall argument is swapped in and out rather than clobbered.)

11. A TOCTOU race made visible by real archives

SFILE_AsyncIOWorkerThread runs on a real pthread and walks the File Manager surface concurrently with the main thread. The shim's slots[256] / files[64] tables used the classic "scan for an unused entry, then claim it" pattern, which is a TOCTOU race the moment two threads run it. Stub reads returned instantly and never opened the window; real archives, with real disk I/O, did. The lock is held across the whole lookup-seek-read-writeback sequence so a refnum cannot be closed and its slot reused underneath an in-flight read.

Build

zig build machoelf -- dump    <DiabloII_macho>              # parse and report
zig build machoelf -- convert <DiabloII_macho> d2game.elf   # emit the 32-bit Linux ELF
zig build machoelf -- genstub <DiabloII_macho> stub.zig     # emit libd2stub.so's source

zig build shim                       # libd2mac.so (always x86-linux-gnu)
D2MAC_BIN=... zig build stub         # regenerate + build libd2stub.so
D2MAC_BIN=... zig build test         # snapshot tests over the real binary

machoelf builds for the host; the shim and stub are always 32-bit Linux, because they have to match the game. The tests are snapshots that assert the parser's full output byte-for-byte against the real binary, which is the only meaningful fixture — hence D2MAC_BIN rather than a path baked into the repo. convert and genstub only need re-running when the game binary or the exclusion rules change; the normal loop is shim-only.

Run

run.sh builds the shim, ships it over ssh to a Linux host that can execute 32-bit ELFs, and runs it there. Configuration comes from the environment or from a gitignored .env beside the script:

variable meaning
D2MAC_HOST ssh destination that runs i386 binaries
D2MAC_DIR directory there holding d2game.elf and the Mac data files
D2MAC_KEY ssh identity, if the agent does not already hold one
D2MAC_BIN local path to the Mach-O, only needed with --convert
./run.sh --convert      # rebuild + ship the ELF too, then run
./run.sh                # shim-only loop

Runtime knobs read by the shim: D2MAC_CMDLINE (the command line MAC_GetCommandLine hands the engine — this is how you select an app mode, the way argv does on Windows; default -w -nosound), D2MAC_GLX_INDIRECT, and D2MAC_X11_TEST for the standalone window self-test.

The display and container side

scripts/ holds the bringup:

  • scripts/Dockerfile — Debian bookworm with dpkg --add-architecture i386 and the 32-bit runtime the converted ELF needs (libc6, libgl1, libglu1-mesa, libx11-6, libxext6, libstdc++6, all :i386). The 32-bit Mesa DRI/GLX stack has to be present, not just the 64-bit one apt pulls in by default. mesa-utils and x11-utils are not needed at runtime but are the fastest way to confirm a direct GLX context exists before blaming the game. The game and its data are bind-mounted at /d2; the image ships no game code and no Blizzard assets.
  • scripts/start-display.sh — idempotent Xvfb + x11vnc bringup. Xvfb :0 -screen 0 1024x768x24 **+iglx**, deliberately larger than the game's own 800x600 render. VNC_PASSWORD sets the x11vnc password (default d2mac).
  • scripts/run-game.sh — container-side entrypoint: DISPLAY=:0, LD_LIBRARY_PATH=., then ./d2game.elf. The converted ELF has no rpath baked in, so the shim and stub are found next to the image rather than through a search path recorded in a generated artifact.

What you supply

The game binary and the Mac data files. No Blizzard code or data is in this repository, and none will be distributed with it. Point D2MAC_BIN at your own copy of DiabloII_macho and put your own MPQs in D2MAC_DIR.

Reading the source

The reasoning lives in the file header comments, not in a separate document. In order of what is worth reading first:

  • src/shim/pthread.zig — the two independent pthread mismatches, and why the inline header won over the alternatives.
  • src/shim/x11.zig — GLX setup, the runtime dlopen/dlsym approach, input polling and the button-edge queue.
  • src/shim/storm.zig — the MPQ detours and the thread trampoline that must not touch Darwin's pthread_t internals.
  • src/machoelf/elf.zig — the ELF shape, the DT_NEEDED ordering argument, and locally backed imports.

Then src/machoelf/stub.zig (the denylist), src/shim/filemanager.zig (FSSpec/FSRef as handles, and the lock), src/shim/sockets.zig, and src/shim/patches.zig (the patch set and the app-mode fix).

License

MIT, for the code in this repository. It covers none of the game binary or data, which are Blizzard's and are not distributed here.

About

The 1.14d macOS Diablo II binary running natively on 32-bit Linux: Mach-O converted to ELF, Darwin/Carbon reimplemented in Zig, AGL translated to GLX. No wine, no emulation.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages