NFSU.cc / Guides

Static recompilation: how a 2003 x86 .exe runs as WebAssembly

There is no source code for Need for Speed Underground. There is one Windows program, Speed.exe, and a translator that turns it, function by function, into code a browser runs.

Olympic City at night, drawn by the recompiled game
Every frame here comes from functions translated out of the 2003 executable.

Translate once instead of emulating forever

An emulator reads each x86 instruction while you play and imitates it, on every frame. Static recompilation pays once: before the page exists, a tool reads the whole program and writes the same logic in another language. When you open the site, the translation is already done, and the browser runs it at close to native speed.

The translator

The translator is a Python program (tools/recomp/lift.py). It opens the executable with pefile, disassembles it with Capstone and writes every function of the game as one C function:

The list of functions comes from a census of the executable. The translator writes all 13,764 of them into 160 files of C, and emcc (Emscripten) compiles them with -O2 into one WebAssembly program. The same C also builds natively with clang, for tests.

Code that hides in the data

Not all of the game's code lives in Speed.exe. Its sound engine loads small x86 modules out of the .abk sound banks and relocates them in memory. A static translator never sees that code in the executable, so a second pass reads all 106 sound banks, finds 79 code modules (28 distinct functions) and translates them ahead of time. When the game loads one, the host recognizes it by its header and calls the translated version.

Checked bit for bit

A translation is only useful if it is exact. difftest.py runs each translated function next to Unicorn, a reference x86 CPU, on random inputs. Both stop at the first Windows call or at the return, and every register, the x87 floating point stack and all of memory are compared. Of the 5,805 functions it reaches, 5,802 match on every case; the three that differ are listed by address. Unicorn is only the judge: it never ships in the game.

Changing the game without editing the game

Fixes and options are patches applied while translating: small files such as patches_render.py or patches_input.py, one line per patch, each with the address it changes and the reason. The executable's bytes stay as they are, and the Original 2003 version plays as the game shipped.

Read the code

The translator, the tests and the patch files are on GitHub. The next piece is what answers the game when it calls Windows: DirectX 9 and Windows rebuilt for the browser.

In the repo: tools/recomp · tools/recomp/lift.py · tools/recomp/difftest.py · tools/recomp/patches.py · tools/recomp/abk.py

More guides