~/posts/phigros-plus-plus-ipa-patcher

Patching a 2.3 GB iPhone game in the browser, in 2.7 seconds

17 min read 3394 words
reverse-engineeringphigrosiosjavascriptproject

tl;dr

Phigros++'s iOS patcher went from a Python script that needed an il2cpp dump to 701 lines of TypeScript with no dependency, which finds the game's 164,954 methods on its own, reads the 2.3 GB IPA in place with Blob.slice and writes 600 hooks into it. On phigros.tools it runs in 2.7 s, checks the release's Ed25519 signature itself, and gives the same UnityFramework, byte for byte, as the Python did.

Phigros++ ran on my iPhone, and the last line of that post was the problem: “Building it needs a decrypted IPA and its il2cpp dump”. In practice, an iPhone player who wanted it had to clone the repo, install Nix (or Docker, which I added the same day), and run make ipa, which dumped the game with a .NET tool, cross-compiled a library with clang and patched the IPA with Python. That’s a lot to ask from someone who just wants replays in a rhythm game.

Getting a decrypted IPA is already the hard part, and I can’t make it easier: it takes a jailbroken device, TrollStore or a Mac with SIP turned off. My friend Maren had the idea for everything after that: build what doesn’t come from the game once, and let a page on phigros.tools patch the IPA with it, right in the browser, so nobody has to upload 2.3 GB anywhere. Now it’s one step: you open phigros.tools/phigrospp, drop the IPA on the page, and a few seconds later you download Phigros++.ipa, to install with SideStore or AltStore.

The patcher on phigros.tools after a run: "Phigros++.ipa is ready, patched in 2.7 s", a download button, and the patching details opened on the IPA (2,980 entries, 2,333,943,545 bytes in, 2,331,185,833 out, 25 entries left out) and UnityFramework (cryptid 0, the LC_LOAD_DYLIB at 0x2218, and its four segments with their addresses, sizes and chained pointers)

The IPA never leaves the device. Your browser reads it, patches it and hands the result back, and phigros.tools never sees a byte of it.

What patching needs, and from where

The last post has the details. In short, turning the game’s IPA into Phigros++‘s takes five things:

  1. one LC_LOAD_DYLIB load command in UnityFramework, the Mach-O file holding the game’s code, so it loads libphigrospp.dylib,
  2. the hooks baked into UnityFramework: every method Phigros++ might hook gets its first instruction replaced by a jump to a 24-byte stub, which reads an 8-byte slot that Phigros++ fills at runtime,
  3. a renamed app in Info.plist,
  4. the ”++” tab drawn on the home screen icon,
  5. the App Store’s files left out, since the sideloading tool signs the app again.

Some of it comes from Phigros++ and some from the game:

NeededComes from
libphigrospp.dylib, built for that game versionPhigros++
which methods the sources might hook, by namePhigros++
where each of those methods is in UnityFrameworkthe game
UnityFramework, Info.plist, the icon’s artworkthe game

The third row was the trouble. The Python patcher got method addresses from an Il2CppDumper dump of the game, which only exists on a machine that has the IPA. So nothing built in CI or on my machine could be shipped to players without either shipping a dump of the game or making them run Il2CppDumper. The plan only works if the browser can find the methods by itself, straight from the IPA. Which means doing Il2CppDumper’s job in JavaScript.

The pack, built without the game

Everything that doesn’t come from the game goes into one file, phigrospp.ios, which scripts/build-ios.ts writes in 27 seconds (make ios). Its format is about as simple as a format gets:

phigros++ ios 1 0.3.0-beta.12
hooks
91688
{"strings":[...],"names":[...]}
4.0.3
926460
<libphigrospp.dylib for 4.0.3>
4.0.4
926460
<libphigrospp.dylib for 4.0.4>

A first line says what it is, which patcher format it needs (the 1) and the Phigros++ version. Then each file is its name, its size and its bytes. hooks holds every string and every identifier found in the Lua and C sources: the strings name the methods (hook(CS.SEPlayer, "Start", ...)), and the identifiers name their classes. The last post explains why it’s done that way, and how a stray '"' or a Lua table key once hid real hooks. It’s about 1.9 MB in all.

The versions are the ones the IPA’s Info.plist gives (CFBundleShortVersionString), which is what the patcher can read. They’re not the version the game shows: as in the last post, the 4.0.3 IPA says 4.0.1.2 in its settings.

The release script signs it with Phigros++‘s release key (Ed25519, the same key that signs the mod bundles), and it’s published as a GitHub release file: 64 bytes of signature, then the pack.

Then I learned that a page can’t download a release file from GitHub. Release downloads come without CORS headers, so the browser refuses to let phigros.tools read them. So the site’s worker fetches the latest release’s pack every 15 minutes, keeps it only if the signature checks out, and serves it from /ios/phigrospp.ios. The page doesn’t trust that copy either: it checks the signature again with WebCrypto, against the public key written in the page’s code. A bad copy on the server, or one changed on the way, gets refused.

Phigros++ sourcesLua, C, mods/no game filephigrospp.ioshook names + onedylib per versionGitHub releasethe pack behind a64 B signaturephigros.toolschecks it, keeps acopy (for CORS)your browserchecks it again,then patchesPhigros++.ipaa Blob, savedon your deviceyour IPA2.33 GB, readwhere it isevery 15 minnever uploaded
Where each part comes from. The top row never touches the game, which is what lets it be built in CI and published. The browser is the only place where the pack and the IPA meet, and the IPA only goes in one direction.

Reading 2.3 GB without reading it

An IPA is a zip file, and this one is 2,333,943,545 bytes with 2,980 entries. Loading it into memory in a browser tab is a bad idea, and also unnecessary, because a zip is built to be read in pieces:

[local header][data] [local header][data] ... (2,980 times)
[central directory: name, size, offset of every entry]
[end record: where the central directory is]

The end record is the last 22 bytes of the file, give or take a comment of up to 65,535 bytes. So the patcher reads the last 65,557 bytes, finds the end record’s signature, and reads the 357,109-byte central directory it points to. That’s every entry’s name, size and position, out of 0.015% of the file.

The tool for this is Blob.slice(). The file you drop on a page is a File, which is a Blob, and slicing one doesn’t read anything: it’s a promise to read those bytes later, if someone asks. Reading an entry is then a slice through DecompressionStream, which the browser already ships:

const data = (await stored(ipa, entry)).stream();
return bytes(new Response(entry.fields[2]
  ? data.pipeThrough(new DecompressionStream("deflate-raw"))
  : data));

Only four entries ever get read that way: Info.plist (4,085 bytes), the store’s artwork for the icons (724 KB), global-metadata.dat (11 MB once inflated) and UnityFramework (81 MB once inflated). Everything else, 2.3 GB of it, stays on the disk.

One catch: zip stores offsets in 4 bytes, which caps them at 4 GiB, and the tool that made this IPA switches to Zip64’s 8-byte fields as soon as an entry starts past 2 GiB. 227 entries of this IPA have their real offset in a Zip64 extra field, with 0xffffffff in the usual place. A patcher that skipped that would work on the first 2 GiB and then read garbage.

Doing Il2CppDumper’s job

The game is written in C# and compiled to native code by Unity’s IL2CPP. The result is split in two:

  • global-metadata.dat holds the names: every type, every method, every string. It knows a method is called SEPlayer.Start, but not where its code is.
  • UnityFramework holds the compiled code, and somewhere in its data, two structures that tie the two together: Il2CppCodeRegistration and Il2CppMetadataRegistration. Those hold the tables of method pointers, one per assembly.

The structures have no symbol, so nothing in the file says where they are. Il2CppDumper finds them by searching for values only they would hold, and the patcher does the same:

  • Il2CppMetadataRegistration is 16 words, and the 11th and the 13th are both the count of type definitions, which the metadata says is 13,342 (not to be confused with its typesCount, a different number). The patcher looks for a word equal to 13,342 that has another 13,342 two words later, and steps back 80 bytes.
  • Il2CppCodeRegistration takes three hops. The first assembly’s name, Assembly-CSharp-firstpass.dll, is a string in UnityFramework. Its code module is the only thing pointing at that string, the module is listed in a table of modules, and the code registration ends with the count of modules and a pointer to that table, 128 bytes in.

“Pointing at” needed one more detail. Pointers in a Mach-O file on disk aren’t plain addresses. The loader rewrites them when the app starts, and this file uses chained fixups: each 8-byte pointer packs the target’s offset in its low 36 bits, a link to the next pointer to fix, and a flag for imports in its top bit. UnityFramework uses format 6 (DYLD_CHAINED_PTR_64_OFFSET) in its two data segments, 215 and 184 pages of them. So a pointer is read like this:

const high = d.getUint32(at + 4, true);
return high >>> 31 ? -1
  : d.getUint32(at, true) + (high & 15) * 2 ** 32;

From there it’s walking tables: for each of the 97 assemblies, each type, each method, look up the method’s index in its module’s pointer table. Generic methods (List<T>.Add built for one T) live in a separate table, and the patcher names those too.

I wanted the names to be exactly Il2CppDumper’s, like GetCollectionControl.<>c__DisplayClass15_0$$.ctor, so I could check the result against a real dump. On both 4.0.3 and 4.0.4, the patcher lists the same 164,954 methods as Il2CppDumper’s script.json, same names, same addresses, same order. Listing them and matching them (below) takes 422 ms in the browser.

Then matching is the same rule as the Python one: a method is kept when its name is one of the sources’ strings and its class is made of the sources’ identifiers (a coroutine like LevelControl.<Start>d__4 counts as LevelControl). That keeps 600 of the game’s methods, and the patcher adds il2cpp_init, which isn’t one of the 164,954, so 601 in all. One of the game’s methods starts with an instruction that can’t be moved out of place, so only JIT can hook it. The other 599 and il2cpp_init get a stub, which makes the 600 stubs (and the “600 of 164954 methods” in the log, which counts il2cpp_init too).

Writing the rest

UnityFramework gets its new load command at 0x2218, right after its 67 load commands, in the padding before its first section. Then the 600 stubs go at the free end of __TEXT and the 600 slots at the free end of __DATA, as in the last post, 32 bytes per hook (a 24-byte stub and an 8-byte slot). On 4.0.4 there’s room for 629 stubs, so that’s 29 to spare.

The Hooks panel: 600 methods without JIT, 1 with JIT only, stubs from 0x4490500 to 0x4493d40 (600 of the 629 that fit), slots from 0x4e290b8 to 0x4e2a378, a grid of 629 small squares with 600 filled in pink, and the start of the table, from il2cpp_init to GetCollectionControl's methods

Info.plist turned out to be XML, not the binary format I expected, in both IPAs (the first run stopped at “Info.plist isn’t a binary plist”). So there’s a small XML reader, which only knows the five kinds of value the game’s 140 tags use, and a binary writer that sorts keys and shares repeated values the way Python’s plistlib does. Same order means same bytes, which made comparing with the Python patcher trivial.

The icons are drawn on an OffscreenCanvas (the 600 px store artwork, resized, with the ”++” tab on top) at the four sizes iOS asks for.

A zip without a zip library

New entries have to be compressed, and a zip entry needs the CRC-32 of its data. Browsers have no CRC function, but they do have CompressionStream("gzip"), and a gzip file is a 10-byte header, a raw deflate stream, then the CRC-32 and the size of the data. That’s exactly what a zip entry holds, with a different wrapping. So the patcher gzips, keeps the middle as the entry’s data, and reads the CRC from the last 8 bytes:

const crc = view(gzip).getUint32(gzip.length - 8, true);
return [entry, gzip.subarray(10, gzip.length - 8)];

(It also checks that byte 3 of the header is 0, meaning gzip didn’t add a file name or anything else after the 10 bytes.)

The output is never assembled in memory either. patch() returns a list of parts: new headers, new entries, and for everything else, the slice of your IPA that holds that entry’s compressed data, as it is. The page wraps that list in a Blob and gives it a download link, and the browser only reads the slices while it saves the file.

slices of your IPA: 2,301,622,420 bytesnew: 29,563,413 bytesPhigros++.ipa, 2,331,185,833 bytesslices of your IPA: 2,301,622,420 B (98.7%)new: 29.6 MBhdrslice...hdrUnityFrameworkhdrslice...dylibiconsdirectoryin order, not to scale:
What Phigros++.ipa is made of, for Phigros 4.0.4. 98.7% of it is 2,953 entries copied from your IPA as they are, without inflating or recompressing them. The 29.6 MB that are new are mostly UnityFramework compressed again (81 MB before), then Info.plist, the 926 KB library, the four icons, and every header and the central directory.

How it went

I kept the Python patcher’s output as the reference the whole time, and diffed against it after every change:

StepResult
method list vs Il2CppDumper’s script.json164,954 of 164,954, same order
first full runstopped, Info.plist is XML
after the XML readerlog said 599 hooks, Python said 600
counting il2cpp_init like Python600, same set
full IPA from the command line, both versionsidentical UnityFramework, Info.plist, dylib
full IPA from Chromiumidentical too, except the 4 icons

The 599 wasn’t a missing hook. The log subtracted il2cpp_init from the count, which the patcher always adds and which the Python’s 600 included. The icons differ because a canvas draws in RGBA and Pillow in RGB, with resampling that’s close but not identical (4 levels out of 255 on average, per channel). iOS doesn’t care.

The same ipa.ts runs both in the browser and from the command line, where scripts/patch_ipa.ts is a 14-line wrapper using Node’s openAsBlob. phigros.tools has a copy of the file, checked identical. The old Python patcher is gone, and make ipa doesn’t need Il2CppDumper or .NET anymore.

All three ran on my desktop (a Ryzen 9 7950X), and each time includes writing the patched IPA to disk:

PatcherTime
patch_ipa.py6.5 s
patch_ipa.ts, Node4.8 s
phigros.tools, Chromiumabout 4.4 s

On the page, that’s 2.7 s until “ready” and about 1.7 s more while the browser saves the file, since that’s when it actually reads the slices.

The patcher is its own chunk of the site, loaded when you drop a file: 13.64 kB, 6.35 kB gzipped.

Then it broke on my own computer

The first real run, in my everyday Chrome on the live site, stopped at 0.736 s, right after “600 of 164954 methods hookable without JIT”, with Chrome’s NotReadableError. In the headless Chromium I’d tested with, it had worked every time.

The last step was the culprit. It got each entry’s slice with a small read of its local header (the lengths of its name and its extra field decide where the data starts), and it did all of those at once:

const kept = entries
  .filter((entry) => !dropped.includes(entry))
  .map(async (entry) => [entry, await stored(ipa, entry)]);

That’s about 2,950 reads of the same file started in the same instant. My best guess is that it’s more than Chrome is willing to have in flight at once, but I couldn’t prove it: the headless Chromium never failed this way, which is also why the tests never saw it. Reading one entry at a time fixed it, and the output stayed byte for byte the same. Each read is 4 bytes, so doing them in a row is still fast.

The page

I wanted the page to show what it does rather than a spinner, so under “Patching details” it lays out everything it found as it goes: the IPA’s entries, UnityFramework’s segments as a bar to scale, the il2cpp structures and the 97 assemblies with their method counts, the 600 hooks with their stubs and slots, and a log with the time of every step:

The log of a run on Phigros 4.0.4: the pack read in 2 ms, 2980 entries in 13 ms, UnityFramework (81244928 bytes, cryptid 0) inflated in 215 ms, the load command at 0x2218 in 1 ms, the il2cpp structures found in 64 ms, 600 of 164954 methods hookable in 422 ms, and Phigros++.ipa written in 2017 ms, 2.733 s in all

The last 2 seconds are the 2,950 header reads one after the other, deflating the new UnityFramework again, and drawing four icons. The details stay folded unless the patch fails, in which case they open on their own, since that’s when someone (me) will want to read them.

A wrong file fails early and says why: something that isn’t a zip (“not an IPA: it isn’t a zip file”, after 0.2 s), an IPA that’s still encrypted (cryptid isn’t 0), a game version the pack has no library for, or a pack whose signature doesn’t check out.

If you have a decrypted IPA of Phigros whose Info.plist says 4.0.3 or 4.0.4, phigros.tools/phigrospp turns it into Phigros++‘s while you watch, and sends nothing anywhere.

hash: b59
EOF