Two files, 48 inits: overlays and the rebuild

Start Pool of Radiance with too little memory and it asks for 82,320 more bytes, whatever memory you give it. We take the program apart to see why.

12 min read Pool of RadianceTurbo Pascaloverlays

Our emulator running the original game with a little less memory than it needs (434,176 bytes free): a black screen, and on the bottom row, in yellow, WARNING: INSUFFICIENT MEMORY

This is Pool of Radiance in our emulator, started with a little less memory than it needs: 434,176 bytes free. It says Loading, please wait. Then, on the bottom row in yellow: WARNING: Insufficient Memory. A key, and it's Insufficient Memory. Exiting Program. Another key, and you're back at DOS.

Start it with a lot less memory and it catches the problem up front: Not enough memory to run game. You need 82320 more bytes. Give it 71,440 bytes more, and the message is the same, word for word, 82320 included. It always says 82,320.

The DOS message at 131,328 and at 202,768 bytes free: You need 82320 more bytes, both times

Between those two messages there's a band of more than 200 kilobytes where the game passes its own memory check and then falls over. Both screenshots are staged: we changed only how much memory the emulator gives the program.1

This is the second article of the engine series, after the overview. It covers how the program is put together: the two files, the 50 units inside them, the 48 calls that run at start-up, the overlay manager, and what our rebuild from source had to get right to be the same program. Along the way it explains that 82,320. The video covers the same ground; this written version adds the listings, the tables and links into the repository.

Every episode in the playlist

Two files, fifty units

The game is two files of code. START.EXE is 65,231 bytes, packed with Microsoft's EXEPACK, so the first thing it does is unpack itself in memory, into a 68,592-byte program image. GAME.OVR is 206,105 bytes. It starts with the four letters FBOV and a 32-bit length, then the code of 35 overlay units, back to back: 197,641 bytes of code, 8,456 bytes of fixup lists and 406 entry points.2

Pool of Radiance is written in Turbo Pascal, in units: Pascal's modules. A unit has an interface, which is what other units can see, an implementation, and an optional initialisation part that runs at start-up.

Units Count Where
Borland's library: System, Crt, Dos, Overlay 4 START.EXE, linked from the compiler, never decompiled
Resident game units, res02 to res12 11 START.EXE, in memory the whole time
Overlay units, ovl00 to ovl34 35 GAME.OVR, loaded when needed

That leaves 46 units of game, and 35 of them aren't in the program you start.3

Calling code that isn't there

Overlay zero's stub segment, fields coloured: INT 3F, the offset in GAME.OVR, the code size, the fixup list size, the entry count, then the five-byte entry stubs

So how do you call code that isn't in memory? For every overlay unit, START.EXE holds a small stub segment. Here are the first 48 bytes of overlay zero's stub segment, at segment 0016:

Output
+00  CD 3F 00 00 08 00 00 00 BE 00 0E 00 02 00 00 00
+10  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+20  CD 3F AC 00 00 CD 3F 42 00 00 00 00 00 00 00 00

It starts with CD 3F, the instruction INT 3F, a software interrupt: a jump into a handler the program set up when it started. Then, after a two-byte word that is zero on disk, come the unit's offset in GAME.OVR (08 00 00 00: 8, right after the file's header), its code size (BE, 190 bytes), the size of its fixup list (0E, 14 bytes) and the number of entry points (2). Sixteen more bytes follow that are zero on disk, apart from a word at 0E we come back to at the end. From offset 20 hex there's a five-byte stub per entry point: the interrupt again, the routine's offset in the unit, and a zero. Entry 0, at 00AC, is the unit's initialisation; entry 1, at 0042, is the out-of-memory handler we'll meet below.4

When the game calls one of these stubs, the interrupt lands in Borland's overlay manager. It reads the unit's code and fixups from GAME.OVR into the overlay buffer and patches the code for where it landed. Then it rewrites the unit's stubs: CD 3F becomes EA, a far jump, followed by the address of the loaded code, so the next call goes straight in. When a unit is pushed out of the buffer, its stubs go back to CD 3F. We read them in the emulator right after OvrInit and again when StartGame is called (abridged: two of the four units we read):

Output
ovl00 after OvrInit      CD 3F AC 00 00  CD 3F 42 00 00
ovl00 at StartGame       EA AC 00 65 41  EA 42 00 65 41
ovl16 at StartGame       CD 3F 54 44 00  CD 3F 61 01 00

The 4165 in the jumps is where our emulator happened to load overlay zero; another machine would load it elsewhere.5

The buffer starts out exactly the size of the largest overlay, character creation (ovl16): 17,497 bytes of code plus 526 of fixups is 18,023, rounded up to a 16-byte paragraph, 18,032. At start-up one of the game's own units grows it to 100,352 bytes, about half the overlay code, so the units take turns as you play.6

Forty-eight calls, two that matter

GAME.OVR as a bar, filled by the 70 reads the overlay manager makes before StartGame

Before the main program runs a single line of its own, it makes 48 far calls in a row, one to the initialisation part of every unit that has one. Borland's System and Crt come first; Dos and Overlay have no initialisation part and get no call. Only two of the 46 game units do anything there: res08, the ninth call, and overlay zero, the 48th and last. The other 44 are just begin end.

Why call them at all? We compiled a two-unit test with the same Turbo Pascal 6.0 (abridged: the two units without their comments, and the first two lines of the compiled entry):

Output
unit UNOINIT; ... procedure A; begin end;  end.
unit UEMPTY;  ... procedure B; begin end;  begin end.

0000:0000  9A 00 00 05 00   lcall 5:0000   ; System's initialisation
0000:0005  9A 0C 00 02 00   lcall 2:000C   ; UEMPTY's initialisation

A unit that ends with end. gets no call. A unit with an empty begin end. gets one. So the 44 empty initialisation parts are what make most of the 48 calls.7

And 34 of those empty calls go through overlay stubs, so each one loads its unit. We logged every read of GAME.OVR in the emulator: before StartGame runs, the overlay manager has made 70 reads, the file's 8-byte header and then the code and fixups of all 35 units, every one of its 206,105 bytes, mostly to run procedures that do nothing. It reads the file from the end: the chain starts with ovl34, the last unit in the file, and ends with overlay zero, the first. How long that took from real floppies we haven't measured: the emulator's disk is instant.8

The memory check

src/RES08.PAS, lines 67 to 75, with the arithmetic: 100,352 minus 18,032 is 82,320

The first unit that does something is res08, the ninth call. It waits for GAME.OVR, asking for the overlay disk until the file is there, starts Borland's overlay manager, and reads POOL.CFG: five lines, the video card, the sound, the game directory, the save directory, and a last line, an F, whose meaning we still can't name. Then it sizes the overlay buffer. That's the memory check from the opening:

Pascal
if $18800 - OvrGetBuf <= MemAvail then
  OvrSetBuf($18800)
else
begin
  RestoreVideoMode;
  WriteLn(Output, 'Not enough memory to run game.  You need ', $18800 - OvrGetBuf,
    ' more bytes.');
  Halt;
end;

It asks for 100,352 bytes ($18800) minus what the buffer already has, 18,032. That's 82,320, at any memory size. If that's more than the free memory, it prints it and halts. So the number is how much the buffer has to grow, not how much you're short.9

And that's all it checks. The game needs far more than the buffer: StartGame's heap blocks and screen buffers, the font and the pictures. We cut the emulator's memory down and searched for the edges to the paragraph, and found four outcomes:

Free memory (our emulator) What happens
120,448 bytes and less "Overlay error, program abort!"
120,464 to 202,768 bytes "Not enough memory to run game. You need 82320 more bytes."
202,784 to 434,416 bytes passes the check; WARNING: Insufficient Memory, then Exiting Program
434,432 bytes and more boots; all 17 recorded sessions play to the end
The free-memory ruler: 118 KB, 198 KB and 424 KB, with the red band where the game gets past the check and then fails

So in our emulator the game needs 434,432 bytes free to reach the title screen, but the check lets it through from 202,784. Anywhere in those 231,648 bytes it gets past the check and dies in its heap error handler. On a real PC, DOS and resident programs take their share of the 640 KB first, so how much memory a machine needs moves with them; the window, measured in free memory, should stay the same.10

The safety net

That safety net is overlay zero, installed by the 48th and last call. Its initialisation stores the address of its handler in HeapError, the hook that Borland's heap manager calls when it needs help (src/OVL00.PAS, lines 20 to 48, comments left out):

Pascal
function HeapErrorHandler(Size: Word): Integer;
var
  Quit: Boolean;
begin
  if Size > 0 then
  begin
    Quit := False;
    repeat
      ShowMessageLine(Yellow, 'WARNING: Insufficient Memory');
      if OfferSaveOnHeapError then
      begin
        SaveGame;
        Quit := HeapErrorStop;
      end
      else
      begin
        Quit := True;
        ShowMessageLine(Yellow, 'Insufficient Memory. Exiting Program');
      end;
    until Quit;
    QuitGame;
  end;
end;

begin
  HeapError := @HeapErrorHandler;
end.

There are only two calls through HeapError in the whole program, and both are in Borland's heap manager. One runs when the manager grows the heap: it passes a size of zero and throws the answer away (xor ax,ax; push ax; call far [HeapError]; pop ax; pop dx at 0AF8:03B4). The other runs when a request doesn't fit.

The counter: 23 calls with size 0 at every start, the same in all 17 recorded sessions

We put a hook on each of the two call instructions in our emulator. Every start of the game makes 23 calls, all with a size of zero, all before the title screens are over, the same 23 in all 17 recorded sessions. With a size of zero the handler returns at once and never sets its result. Nobody reads it.11

When an allocation really fails, the handler shows WARNING: Insufficient Memory and tests a flag that we call OfferSaveOnHeapError. If the flag is set, you get to save your game first. If not, it shows Insufficient Memory. Exiting Program. Either way the game quits.

The flag's address searched in the load image and the 35 overlays: one instruction, the test at ovl00:0069

We can't find anything that sets that flag. In START.EXE and all 35 overlays exactly one instruction mentions its address, and that instruction is the test, cmp byte ptr [49D0h],0 at ovl00:0069. We also put a write watch on that byte through all 17 recorded sessions, and the CPU never wrote it. Its starting value is zero: our emulator's memory starts at zero, and on a real PC the EXEPACK unpacker leaves a zero there. So, as far as we can tell, the offer to save never comes. This safety net can only say goodbye.12

Two more from res08

On a Tandy, res08's video branch lowers the top of the heap by 16 kilobytes. Then, right after the sound line of POOL.CFG, it lowers it by another 16 kilobytes on every machine. So every PC gives up 16 kilobytes and a Tandy gives up 32. We put read and write watches on those 16 kilobytes through all 17 recorded sessions, on EGA: nothing reads or writes them.13

And right after it reads the game directory from POOL.CFG, the code says GameDir := GameDir: it copies the string onto itself. The same goes for the save directory. It does nothing, but the copy is in the original's bytes, so our source says it too. A matching decompilation keeps the odd lines along with the rest.14

The rebuild

make rebuild: the last segment rows marked same, then 51 of 51 segments, the program image, the relocations and the overlay file identical

Our source matches the original routine by routine, but each routine is matched on its own. Four things only show up when the whole program is linked:

  1. Where every global lives. Turbo Pascal lays out the data segment, the one block of memory that holds every global, in declaration order. So we declare every global of the game in one file, src/POOLVARS.PAS, in offset order, with the starting values of its constants.
  2. The order of the overlay stubs. A unit's stub entries follow its interface, but only for routines other units call. In 14 units that isn't the order of the code, so we reordered those interfaces from the original's stubs.
  3. Link order. The main program's uses clause decides where every segment lands, so ours lists the units in the original's order, Borland's first.
  4. The sound driver. It was never Pascal: it was assembled separately and linked in. Its source, src/RES03.ASM, is built with a small 8086 assembler we wrote for it (tools/re/asm86.py), which picks the same instruction encodings as the original.

Then make rebuild compares all 51 segments, the 68,592-byte program image and the overlay file byte for byte, and the 561 relocations as a set: 51 of 51, identical. And all 17 of our recorded play sessions run on the rebuilt program exactly as on the original: same screens, same random numbers, same memory.15

Where it plugs in, and what we still don't know

The overview's map of the subsystems, with architecture as the floor under all of them

On the overview's map, architecture is the floor everything sits on. Every arrow between overlay units is a far call through a stub, and the resident units are the shared services everyone leans on: files and the game's DAX archives, text, pictures, windows, character panels and sound.

Why the game gives up those 16 kilobytes at the top of the heap on every machine. What the F on the last line of POOL.CFG means: we know what it does, it gates part of the title sequence and the credits, but not what SSI called it. Why three units, res02, res10 and res11, hold nothing but an empty begin end., 16 bytes each. And one field in every overlay stub, at offset 0E: it holds the stub segment of the overlay before it, a chain all the way back to overlay zero. We watched it through two sessions and nothing ever read it. What it was for, we haven't found.16

Next in the series: the DAX archives, where the maps, scripts, pictures and monsters come from, and a decompressor with two codes that would loop forever.

Notes and sources

  1. Staged runs of the original program in our emulator, with only the memory top lowered by a script of the episode's (not in the repository): 79F0h for the warning, 3000h and 4171h for the two messages. Free memory is the memory top minus the program's PSP at 0FF0h, in paragraphs of 16 bytes. The emulator is tools/oracle/run.py. ↩︎

  2. wc -c and xxd -l 8 of the game's GAME.OVR read 46 42 4F 56 11 25 03 00, FBOV and 206,097, the file size minus 8. The game's files are not in the repository. Overlay totals from re/units.toml; 8 + 197,641 + 8,456 = 206,105. ↩︎

  3. re/units.toml: 15 resident units (four of them Borland's, byte-matched against Turbo Pascal 6.0's library) and 35 overlays. docs/design/WHITEPAPER.md, sections 2.2 and 3.2. ↩︎

  4. xxd -s 0xB60 -l 48 poolrad/start-unpack.exe, after make unexepack has unpacked your own START.EXE; the field layout is in the whitepaper, section 3.3. Entry 1 is HeapErrorHandler, ovl00:0042 in re/symbols.toml. ↩︎

  5. An episode capture (not in the repository), read in our emulator during the boot-title session, after OvrInit (042B:00C3) and at the StartGame call (0000:00FD), for ovl00, ovl11, ovl16 and ovl34. The Overlay unit writes the EA at 0AA2:045F. ↩︎

  6. OvrGetBuf returns 18,032 at res08's check, read in the emulator; OvrSetBuf($18800) is src/RES08.PAS, line 68. ↩︎

  7. The probe's files are not in the repository: two units of a few lines each, shown above without their comments, and a program that uses both and calls A and B. Compiled with the pinned compiler (tools/re/tp_toolchain.py tpc INITPRB.PAS --disasm, tools/re/tp_toolchain.py); the entry's other seven lines are left out. ↩︎

  8. Every read of GAME.OVR logged by an episode script (not in the repository) through the emulator's file hook, tools/oracle/run.py; 70 reads and 206,105 bytes before StartGame in all 17 sessions. ↩︎

  9. src/RES08.PAS, lines 67 to 75. ↩︎

  10. Edges found by binary search on the memory top, to the paragraph: 2D58h/2D59h, 4171h/4172h and 79FFh/7A00h. All 17 sessions were played at 7A00h. ↩︎

  11. One hook on each call far [4414h] (0AF8:03B7 and 0AF8:03C3), the only two in the program, through the emulator's breakpoints; the handler is src/OVL00.PAS. ↩︎

  12. Byte search of the program image and the 35 overlays; a write hook on DS:49D0 through the 17 sessions. Data the emulator's DOS copies into memory for file reads would not trigger the hook, but no file buffer covers that byte. On a real PC, DS:49D0 is byte 1,440 of the block the EXEPACK stub copies past the program image, and it is zero (docs/design/WHITEPAPER.md, section 3.1.1). ↩︎

  13. src/RES08.PAS, lines 57 and 89 to 90; HeapEnd reads 9C00:0000 after res08 on EGA, and the watch covered 9C000h to 9FFFFh. ↩︎

  14. src/RES08.PAS, lines 92 to 98, QUIRK 042B:032D and 042B:0358. ↩︎

  15. The comparison is written by make rebuild; the sessions were re-run with make rebuild-golden's check (tools/oracle/golden.py --check --rebuilt --strict-state), 17 of 17 equal. docs/process/playbooks/50-rebuild.md describes each of the four steps. ↩︎

  16. Field +0E of every stub read from the program image; read and write hooks on it through two recorded sessions saw no access. ↩︎

Related