PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Translate the code windows a game rewrites
Riccardo Giorato457308c7f679
diff --git a/README.md b/README.mdindex 005df72..285c250 100644--- a/README.md+++ b/README.md@@ -63,6 +63,8 @@ python3 scripts/serve.py build/web-mygame games/mygame/disc.iso # http://locaThe exploring runs press start and then cross every five seconds, which gets most games through their title screens, and put an empty memory card in slot 1 the way the page does, so they follow the path a player takes. `--press 900:cross` replaces that with your own inputs and `--frames` sets how long each run lasts. Frames from the last run land in `games/mygame/shots`, which is the quickest way to see how far a new game gets. `scripts/build_web.sh mygame` rebuilds only the page.+A game may also rewrite its own code: its executable declares an executable segment with no file contents and unpacks a different image into it as the game goes, the way Kingdom Hearts II swaps the module running its boot and menus. No single translation of such a segment can be right, so the exploring runs capture each image the game puts there, translate one per distinct code, and the runtime serves a call into the window from the image whose code is actually in place, checking it word by word. Data in the window the game rewrites freely never matches wrong, and a recapture of a known image folds into the image of the same code.+Set your expectations accordingly: two games have been brought up so far. Another game will most likely stop at a system call or an IOP library function nobody implemented yet, which the runner logs as `[sys] unhandled syscall` or `[iop] missing <library> #<n>`, or use a GS feature the renderer does not handle yet.## Browsersdiff --git a/recomp/codegen.cpp b/recomp/codegen.cppindex 3ed6fe4..4cd8fe5 100644--- a/recomp/codegen.cpp+++ b/recomp/codegen.cpp@@ -798,17 +798,18 @@ void generate(const std::vector<Translation> &translations, const CodegenOptionsheader << "void " << r.function << "(ps2::Cpu &c, std::uint32_t entry, std::uint32_t depth);\n";header << "extern const std::uint16_t " << r.table << "[];\n";}- table << "const ps2::UnitInfo " << (t.relocatable ? t.prefix + "units" : "kUnits") << "[] = {\n";- for (const UnitRow &r : rows) table << std::format(" {{{}, {}u, &{}, {}}},\n", hex(r.base), r.size, r.function, r.table);+ table << "const ps2::UnitInfo " << (t.relocatable || t.fixed_module ? t.prefix + "units" : "kUnits") << "[] = {\n";+ for (const UnitRow &r : rows)+ table << std::format(" {{{}, {}u, &{}, {}}},\n", hex(t.fixed_module ? r.base - t.fixed_base : r.base), r.size, r.function, r.table);table << "};\n\n";- if (!t.relocatable) {+ if (!t.relocatable && !t.fixed_module) {main_units = rows.size();continue;}table << "const std::uint32_t " << t.prefix << "checks[] = {";for (const auto &[at, value] : t.checks) table << std::format("{}, {}, ", hex(at), hex(value));table << "};\n\n";- modules << std::format(" {{\"{}\", {}, {}checks, {}u, {}units, {}u}},\n", t.name, hex(t.size), t.prefix, t.checks.size(), t.prefix, rows.size());+ modules << std::format(" {{\"{}\", {}, {}, {}checks, {}u, {}units, {}u}},\n", t.name, hex(t.fixed_base), hex(t.size), t.prefix, t.checks.size(), t.prefix, rows.size());++module_count;}header << "}\n";diff --git a/recomp/codegen.hpp b/recomp/codegen.hppindex 26e71b8..e54ee19 100644--- a/recomp/codegen.hpp+++ b/recomp/codegen.hpp@@ -27,6 +27,12 @@ struct Translation {std::string name;std::uint32_t size{};std::vector<std::pair<std::uint32_t, std::uint32_t>> checks;+ // A translation of a code window the game itself rewrites. It is emitted+ // into the module table like a relocatable module's, but its addresses are+ // absolute: every image of that window is precompiled for the one base it+ // occupies.+ bool fixed_module{};+ std::uint32_t fixed_base{};};void generate(const std::vector<Translation> &translations, const CodegenOptions &options);diff --git a/recomp/elf.cpp b/recomp/elf.cppindex d46fd36..c751142 100644--- a/recomp/elf.cpp+++ b/recomp/elf.cpp@@ -40,6 +40,10 @@ Image Image::load(const std::string &path) {const auto filesz = read<std::uint32_t>(data, ph + 16), memsz = read<std::uint32_t>(data, ph + 20);const auto flags = read<std::uint32_t>(data, ph + 24);if (offset + filesz > data.size()) throw std::runtime_error("segment outside the file");+ // An executable segment with no file contents is a code window: the+ // game rewrites it at runtime, so it holds no code to translate here+ // and any call into it walks to the images the game puts there.+ if (!filesz && (flags & 1u)) continue;Segment segment{vaddr, std::vector<std::uint8_t>(memsz), (flags & 1u) != 0};std::memcpy(segment.bytes.data(), data.data() + offset, filesz);image.segments_.push_back(std::move(segment));diff --git a/recomp/main.cpp b/recomp/main.cppindex a448dee..311b673 100644--- a/recomp/main.cpp+++ b/recomp/main.cpp@@ -90,8 +90,67 @@ std::vector<Snr2Module> read_modules(const std::string &dir) {return modules;}+// A code window the game rewrites at runtime is a segment of the executable+// with no file contents. The pipeline captures what the game unpacks into it+// as files named <base>_<name>.bin, one content per file, and this reads them+// all as images of the one window, each a module to translate for that base.+std::vector<Snr2Module> read_overlays(const std::string &dir) {+ std::vector<Snr2Module> overlays;+ for (const auto &path : std::filesystem::directory_iterator(dir)) {+ if (!path.is_regular_file() || path.path().extension() != ".bin") continue;+ const std::string stem = path.path().stem().string();+ const auto split = stem.find('_');+ if (split == std::string::npos) continue;+ const std::string base = stem.substr(0, split);+ if (base.empty() || base.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos) continue;+ Snr2Module o;+ std::ifstream file(path.path(), std::ios::binary);+ o.bytes = std::vector<std::uint8_t>{std::istreambuf_iterator<char>(file), {}};+ if (o.bytes.size() < 0x400u || o.bytes.size() & 3u) continue;+ o.size = static_cast<std::uint32_t>(o.bytes.size());+ o.base = static_cast<std::uint32_t>(std::stoul(base, nullptr, 16));+ o.code_begin = 0;+ o.code_end = o.size;+ o.name = stem;+ if (std::any_of(overlays.begin(), overlays.end(), [&](const Snr2Module &m) { return m.base == o.base && m.bytes == o.bytes; })) continue;+ overlays.push_back(std::move(o));+ }+ std::sort(overlays.begin(), overlays.end(), [](const Snr2Module &a, const Snr2Module &b) { return a.name < b.name; });+ return overlays;+}++// Calls the static program makes into the window seed every image of it, so+// each is translated from those entry points whether or not it has been seen.+std::vector<std::uint32_t> window_entries(const Image &image, const Program &program, std::uint32_t base, std::uint32_t size) {+ std::vector<std::uint32_t> seeds;+ for (std::uint32_t pc = program.base; pc < program.end; pc += 4) {+ if (!program.is_code(pc)) continue;+ const Insn i = decode(*image.word(pc), pc);+ const Flow f = flow(i.op);+ if (f != Flow::Jump && f != Flow::Call) continue;+ const std::uint32_t t = i.jump_target();+ if (t - base < size) seeds.push_back(t);+ }+ return seeds;+}++// A window image is served only while every word of it the game runs as code+// is in place, so the checks are all the translated code words: the game+// writes the window's data freely, and a change any translation covers is a+// different image and a call into it must pick the other module.+std::vector<std::pair<std::uint32_t, std::uint32_t>> checks_for_window(const Snr2Module &o, const Program &program) {+ std::vector<std::pair<std::uint32_t, std::uint32_t>> checks;+ for (std::uint32_t at = 0; at + 4 <= o.size; at += 4) {+ if (!program.is_code(o.base + at)) continue;+ std::uint32_t word = 0;+ std::memcpy(&word, o.bytes.data() + at, 4);+ checks.emplace_back(at, word);+ }+ return checks;+}+int usage() {- std::fprintf(stderr, "usage: eerecomp <elf> [--entries file] [--modules dir] [--probes file] [--out dir] [--stats]\n");+ std::fprintf(stderr, "usage: eerecomp <elf> [--entries file] [--modules dir] [--overlays dir] [--probes file] [--out dir] [--stats]\n");return 2;}@@ -99,7 +158,7 @@ int usage() {int main(int argc, char **argv) {if (argc < 2) return usage();- std::string elf_path = argv[1], entries_path, out, probes_path, modules_dir;+ std::string elf_path = argv[1], entries_path, out, probes_path, modules_dir, overlays_dir;bool stats = false;for (int i = 2; i < argc; ++i) {const std::string arg = argv[i];@@ -108,6 +167,7 @@ int main(int argc, char **argv) {else if (arg == "--out" && i + 1 < argc) out = argv[++i];else if (arg == "--probes" && i + 1 < argc) probes_path = argv[++i];else if (arg == "--modules" && i + 1 < argc) modules_dir = argv[++i];+ else if (arg == "--overlays" && i + 1 < argc) overlays_dir = argv[++i];else return usage();}@@ -141,6 +201,68 @@ int main(int argc, char **argv) {if (!modules.empty())std::printf("%zu modules, code %zu instructions (%zu KiB), %zu sites in the program linked at run time\n", modules.size(), module_code,module_code * 4 / 1024, imports.size());+ const std::vector<Snr2Module> overlays =+ overlays_dir.empty() || !std::filesystem::exists(overlays_dir) ? std::vector<Snr2Module>{} : read_overlays(overlays_dir);+ // Data in a window lives and dies with the game, so captures of one+ // image differ in bytes it wrote since. The code identifies the image:+ // analyse every capture with the same seeds, group the ones answering+ // to one code, and translate one image per group, so a re-captured+ // image is never served by a translation that has not seen its entry+ // points.+ std::size_t overlay_code = 0;+ std::map<std::uint32_t, std::vector<std::uint32_t>> window_seeds;+ std::map<std::uint32_t, std::set<std::uint32_t>> window_tokens;+ std::map<std::string, std::string> variant_of;+ std::map<std::string, std::set<std::uint32_t>> window_offsets;+ std::map<std::uint32_t, std::vector<std::pair<std::string, std::vector<std::pair<std::uint32_t, std::uint32_t>>>>> code_signatures;+ std::set<std::string> representatives;+ for (const Snr2Module &o : overlays) {+ if (!window_seeds.count(o.base)) window_seeds[o.base] = window_entries(image, program, o.base, o.size);+ if (const auto it = entries.modules.find(o.name); it != entries.modules.end())+ for (const std::uint32_t entry : it->second) window_tokens[o.base].insert(entry);+ }+ for (const Snr2Module &o : overlays) {+ Image candidate = Image::raw(o.base, o.bytes, {0, o.size});+ std::vector<std::uint32_t> seeds = window_seeds[o.base];+ for (const std::uint32_t entry : window_tokens[o.base]) seeds.push_back(o.base + entry);+ const Program signature_program = analyse(candidate, seeds, {});+ std::vector<std::pair<std::uint32_t, std::uint32_t>> signature;+ for (std::uint32_t at = 0; at + 4 <= o.size; at += 4)+ if (signature_program.is_code(o.base + at)) {+ std::uint32_t word = 0;+ std::memcpy(&word, o.bytes.data() + at, 4);+ signature.emplace_back(at, word);+ }+ bool found = false;+ for (const auto &[name, sig] : code_signatures[o.base])+ if (sig == signature) { found = true; variant_of[o.name] = name; break; }+ if (!found) {+ code_signatures[o.base].push_back({o.name, signature});+ variant_of[o.name] = o.name;+ representatives.insert(o.name);+ }+ if (const auto it = entries.modules.find(o.name); it != entries.modules.end())+ for (const std::uint32_t entry : it->second) window_offsets[variant_of[o.name]].insert(entry);+ }+ for (const Snr2Module &o : overlays) {+ if (!representatives.count(o.name)) continue;+ images.push_back(Image::raw(o.base, o.bytes, {0, o.size}));+ std::vector<std::uint32_t> seeds = window_seeds[o.base];+ // Entry tokens name module positions, and unlike a relocatable+ // module this image occupies a real address.+ for (const std::uint32_t entry : window_offsets[o.name]) seeds.push_back(o.base + entry);+ programs.push_back(analyse(images.back(), seeds, {}));+ overlay_code += code_size(programs.back());+ translations.push_back({&images.back(), &programs.back(), nullptr, "m_" + o.name + "_", false, o.name, o.size,+ checks_for_window(o, programs.back()), true, o.base});+ }+ if (!overlays.empty()) {+ std::size_t called_entries = 0;+ for (const auto &[base, seeds] : window_seeds) called_entries += seeds.size();+ std::printf("%zu distinct code window images of %zu captured, code %zu instructions (%zu KiB), %zu entry points called from the program\n",+ std::count_if(overlays.begin(), overlays.end(), [&](const Snr2Module &o) { return representatives.count(o.name) != 0; }),+ overlays.size(), overlay_code, overlay_code * 4 / 1024, called_entries);+ }if (!out.empty()) {CodegenOptions options;diff --git a/recomp/snr2.hpp b/recomp/snr2.hppindex c05eb9c..bbc1c68 100644--- a/recomp/snr2.hpp+++ b/recomp/snr2.hpp@@ -24,6 +24,7 @@ struct Snr2Module {std::string name;std::vector<std::uint8_t> bytes;std::uint32_t size{};+ std::uint32_t base{};std::uint32_t code_begin{};std::uint32_t code_end{};Links links;diff --git a/runtime/include/ps2/generated.hpp b/runtime/include/ps2/generated.hppindex 3d473fb..45ff208 100644--- a/runtime/include/ps2/generated.hpp+++ b/runtime/include/ps2/generated.hpp@@ -23,6 +23,11 @@ struct UnitInfo {struct ModuleInfo {const char *name;+ // Zero for relocatable modules, which are found in memory by their header.+ // A fixed base is a code window the game itself rewrites: the module is a+ // precompiled image of one content that can occupy it, and the checks say+ // whether it is the one in place now.+ std::uint32_t fixed_base;std::uint32_t size;const std::uint32_t *checks;std::uint32_t check_count;diff --git a/runtime/src/dispatch.cpp b/runtime/src/dispatch.cppindex 654a6da..3dd1b2f 100644--- a/runtime/src/dispatch.cpp+++ b/runtime/src/dispatch.cpp@@ -32,7 +32,11 @@ std::uint32_t g_module_span = 0;std::vector<Instance> g_instances;bool loaded_at(const ModuleInfo &m, std::uint32_t base) {- if (ld32(base + 0x2Cu) != m.size) return false;+ if (m.fixed_base) {+ if (base != m.fixed_base) return false;+ } else if (ld32(base + 0x2Cu) != m.size) {+ return false;+ }for (std::uint32_t k = 0; k < m.check_count; ++k)if (ld32(base + m.checks[2 * k]) != m.checks[2 * k + 1]) return false;return true;@@ -47,6 +51,15 @@ const Instance *instance_for(std::uint32_t pc) {break;}if (!g_module_count || pc >= kRamSize) return nullptr;+ // A code window rewritten by the game holds fixed base modules, each an+ // image of one content. The one whose check words are in place serves it.+ for (std::uint32_t k = 0; k < g_module_count; ++k) {+ const ModuleInfo &m = g_modules[k];+ if (m.fixed_base && pc - m.fixed_base < m.size && loaded_at(m, m.fixed_base)) {+ g_instances.push_back({m.fixed_base, &m});+ return &g_instances.back();+ }+ }for (std::uint32_t at = pc & ~15u; pc - at < g_module_span; at -= 16) {if (ld32(at) == kModuleMagic) {for (std::uint32_t k = 0; k < g_module_count; ++k)diff --git a/scripts/port.sh b/scripts/port.shindex 161d3bb..a2005e3 100755--- a/scripts/port.sh+++ b/scripts/port.sh@@ -97,8 +97,14 @@ if grep -q SNR2 "$elf"; thenpython3 -I "$here/disc.py" modules "$iso" "$game/modules"modules=(--modules "$game/modules")fi+overlays=()+if windows=$(python3 -I "$here/windows.py" list "$elf") && [ -n "$windows" ]; then+ mkdir -p "$game/overlays"+ overlays=(--overlays "$game/overlays")+ echo "code windows the game rewrites: $(echo "$windows" | tr '\n' ' ')"+fi-translate() { "$tools/eerecomp" "$elf" --entries "$game/entries.txt" "${modules[@]}" --out "$generated" | tail -1; }+translate() { "$tools/eerecomp" "$elf" --entries "$game/entries.txt" "${modules[@]}" "${overlays[@]}" --out "$generated" | tail -1; }echo "== [3/6] machine code to C++"touch "$game/entries.txt"@@ -116,9 +122,13 @@ echo "== [4/6] exploring"if [ "$explore" = 1 ]; thenfor ((round = 1; round <= rounds; round++)); dobuild_native- rm -f "$game/misses.txt" "$game/explore.ps2"- PS2_GPU_LOW_POWER=1 PS2_VU_RECORD="$game/vu1" "$native/ps2run" "$elf" --disc "$iso" --misses "$game/misses.txt" --memcard "$game/explore.ps2" \+ rm -f "$game/misses.txt" "$game/explore.ps2" "$game/explore_ram.bin"+ PS2_DUMP="$game/explore_ram.bin" PS2_GPU_LOW_POWER=1 PS2_VU_RECORD="$game/vu1" "$native/ps2run" "$elf" --disc "$iso" --misses "$game/misses.txt" --memcard "$game/explore.ps2" \--frames "$frames" "${presses[@]}" --frames-dir "$game/shots" --frame-every 300 > "$game/explore.log" 2>&1 || true+ captured=0+ if [ ${#overlays[@]} -gt 0 ] && [ -f "$game/explore_ram.bin" ]; then+ captured=$(python3 -I "$here/windows.py" capture "$elf" "$game/explore_ram.bin" "$game/overlays" "$game/misses.txt" | grep -c '^captured' || true)+ fireason=$(sed -n 's/^\[ee\] halted: //p' "$game/explore.log" | head -1)added=$(python3 -I - "$game/entries.txt" "$game/misses.txt" <<'EOF'import os, sys@@ -135,8 +145,8 @@ with open(entries, 'a') as out:print(len(new))EOF)- echo "round $round: ${reason:-ran to the end}, $added new entry points"- [ "$added" -gt 0 ] || break+ echo "round $round: ${reason:-ran to the end}, $added new entry points, $captured new window images"+ [ "$added" -gt 0 ] || [ "$captured" -gt 0 ] || breaktranslatedoneecho "frames of the last run are in games/$name/shots, its log in games/$name/explore.log"diff --git a/scripts/windows.py b/scripts/windows.pynew file mode 100644index 0000000..542fc09--- /dev/null+++ b/scripts/windows.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Code window support: the segments a game rewrites at runtime.++An executable LOAD segment with no file contents is a code window: the game+unpacks a different image into it as it goes, so no single translation of the+area can be right. The recompiler instead takes one module per image of the+window, and the runtime picks the image in place by its check words.++ windows.py list <elf> print "base size" per window, one per line+ windows.py capture <elf> <dump> <dir> [<misses file>]+ save the image of every window found in+ the RAM dump to <dir>/<base>_<crc>.bin,+ and rewrite plain entry misses inside a+ window as <base>_<crc>:<offset>, naming+ the image the dump holds++The RAM dump is the one the runner writes with PS2_DUMP, so at a halt it holds+exactly the image the game was running when it called the missing entry.+"""+import binascii+import os+import struct+import sys++UNIT = 0x4000+++def load_phdrs(elf):+ phoff, = struct.unpack_from('<I', elf, 28)+ phentsize, phnum = struct.unpack_from('<HH', elf, 42)+ for i in range(phnum):+ yield struct.unpack_from('<8I', elf, phoff + i * phentsize)+++def windows(elf):+ out = []+ for v in load_phdrs(elf):+ if v[0] != 1 or v[4] or not (v[6] & 1): # no PT_LOAD, has contents, not executable+ continue+ base = v[2] & ~(UNIT - 1)+ while base in [b for b, _ in out]:+ base += UNIT+ out.append((base, UNIT))+ return out+++def extent(dump, base, cap=0x40000):+ # The ELF only says the window begins here; what the game unpacks decides+ # how far it reaches, so the image covers the units it wrote, stopping at+ # the first entirely empty one.+ size = 0+ while size < cap and size + UNIT <= len(dump) - base:+ if dump[base + size:base + size + UNIT] == b'\0' * UNIT:+ break+ size += UNIT+ return size or UNIT+++def main() -> None:+ if len(sys.argv) not in (3, 5, 6) or sys.argv[1] not in ('list', 'capture'):+ sys.exit(__doc__)+ mode = sys.argv[1]+ elf = open(sys.argv[2], 'rb').read()+ wins = windows(elf)+ if mode == 'list':+ for base, size in wins:+ print('%08x %x' % (base, size))+ return++ dump = open(sys.argv[3], 'rb').read()+ outdir = sys.argv[4]+ misses = sys.argv[5] if len(sys.argv) > 5 else None+ for base, _ in wins:+ size = extent(dump, base)+ blob = dump[base:base + size]+ if not any(blob):+ continue+ crc = binascii.crc32(blob) & 0xFFFFFFFF+ stem = '%08X_%08X' % (base, crc)+ path = os.path.join(outdir, stem + '.bin')+ if not os.path.exists(path):+ os.makedirs(outdir, exist_ok=True)+ open(path, 'wb').write(blob)+ print('captured %s, %d bytes' % (stem, size))+ if misses and os.path.exists(misses) and blob == open(path, 'rb').read():+ lines = open(misses).read().split()+ names = {}+ for k, token in enumerate(lines):+ if ':' in token:+ continue+ pc = int(token, 16)+ if base <= pc < base + size:+ names[token] = '%s:%x' % (stem, pc - base)+ if names:+ open(misses, 'w').write('\n'.join(names.get(t, t) for t in lines) + '\n')+++if __name__ == '__main__':+ main()\ No newline at end of file