Notes6 min

Giving Pivot a modding API

A favour, a stick figure animator and a lot of access violations. Then the reason for it left.

AskChatGPTClaude

A friend asked me to build a modding scene for an animation program I had never opened. I said yes.

Pivot Animator is a stick figure animator. My friend had a group of friends who all used it, and he had told them he could make mods for it. Then he asked me to make that possible.

So we struck a deal. He would make the mods and tell me what the fuck he needed. I would make the thing the mods ran on.

I didn’t use Pivot and I didn’t care about Pivot. It was a reverse engineering problem with no source and no plugin system, and that was enough.

The first night

Pivot 5.2.11 is a 32-bit Windows program written in Delphi, with a FireMonkey (FMX) interface. To get code inside it, PivotKit is two pieces: a small loader and a DLL.

The loader starts pivot.exe suspended, so nothing has run yet. It writes the path of the DLL into Pivot’s memory, then makes Pivot call LoadLibraryA on it from a remote thread.

src/injector.c
static int inject_dll(HANDLE hProc, const char* dllPath)
{
    size_t len = strlen(dllPath) + 1;
    void* remote = VirtualAllocEx(hProc, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!remote) return 0;
    /* ...write the path into the new allocation... */
    HMODULE k32 = GetModuleHandleA("kernel32.dll");
    FARPROC loadLib = GetProcAddress(k32, "LoadLibraryA");
    HANDLE hThread = CreateRemoteThread(hProc, NULL, 0,
                        (LPTHREAD_START_ROUTINE)loadLib, remote, 0, NULL);

The DLL embeds Lua and loads whatever it finds in pivotkit/mods/. That gave me a language for mods and a place to put them.

Then I needed a test. I had a picture of a silly cat, so the test was the DVD logo: press a new menu button, and the cat spawns and bounces off the window edges. It wasn’t a feature. It just touches everything at once: a menu, an image, a loop, the window size.

First it wasn’t there. Then it was there, but outside the window, ignoring the borders. Then it worked, and an access violation showed up to celebrate. All the cat logic was also hardcoded in the C++, which defeats the point of a mod loader. So the cat logic moved out behind reusable APIs and the cat became a Lua file, bouncy_cat.lua.

That was 9 August. v0.1.0 went up that night, marked heavy beta.

What a mod could do

The public releases moved fast. Within a week pivotlib wrapped the raw API in helpers for frames, playback, figures, overlays, commands and timers. Mods could hook published Delphi methods and get arguments back as Lua values. A console opened with -console, and a loopback TCP bridge on 127.0.0.1:50077 let outside tools drive a running Pivot.

pivotkit/mods/10_first_mod.lua
local pivotlib = require("pivotlib")

pivotlib.log("hello from PivotKit")
pivotlib.on_update(function()
    pivotlib.frame_status("Lua is running")
end)

Write of access 000000

On 15 August, dialogs started appearing: Write of access 000000. Sometimes just one. Sometimes a bunch, on the second test. There were no crash dumps, because Delphi catches the exception and shows a box. The process carries on with whatever is left of its state.

The first cause was my hooks. I had patched inline hooks over Pivot’s own FMX input handlers: EditPaintBoxMouseDown, MouseUp, MouseMove, FormKeyDown, FormKeyUp. Every real mouse event ran Lua and then the original method, and now and then that method wrote through a nil pointer. So those hooks came out. Input became polling, which is less elegant and doesn’t crash.

That stopped that wave. It wasn’t the last one.

Injection kept me stuck for a really long time after that. Calling into Pivot worked until it didn’t, and the crashes landed far from their cause: a write to some garbage address like FC5D89D8, inside my own DLL, long after the call that caused it had returned.

The cause was six instructions that weren’t there.

Delphi’s register convention passes Self in EAX and the first two arguments in EDX and ECX. To load everything, my call helper used EBX, ESI and EDI as scratch. Those three are callee-saved: whoever uses them must put them back. It didn’t. Short calls usually got away with it. Long constructors did not, and whatever called the helper then wrote through a pointer that was no longer a pointer.

src/pivotkit.cpp
__declspec(naked) static void* __cdecl delphi_call_n(void* self, void* fn,
        void* a1, void* a2, const uint32_t* more, int nMore)
{
    __asm {
        /* callee-saved regs MUST survive the Delphi call */
        push ebx
        push esi
        push edi
        mov  eax, [esp+16]   /* self  */
        mov  ebx, [esp+20]   /* fn    */
        mov  edx, [esp+24]   /* a1    */
        mov  ecx, [esp+28]   /* a2    */
        mov  esi, [esp+32]   /* more  */
        mov  edi, [esp+36]   /* nMore */
        test edi, edi
        jz   push_done
        lea  esi, [esi + edi*4]
    push_loop:
        sub  esi, 4
        push dword ptr [esi]
        dec  edi
        jnz  push_loop
    push_done:
        call ebx             /* the callee cleans stack args */
        pop  edi
        pop  esi
        pop  ebx
        ret
    }
}

Three pushes and three pops. After that, the button, label and rectangle constructors ran clean, and everything I’d blamed on FMX being haunted stopped being haunted.

Delphi tells on itself

The reason any of this was possible is that Delphi keeps a lot of its type information in the binary. Published classes, methods and fields come with names attached, and class tables sit at predictable offsets from each other.

So the rewrite began as a proper reverse engineering pass, with Ghidra on one side and live memory on the other. Ghidra’s auto-analysis only found around 1,600 functions, because most Delphi code isn’t reached by plain control flow. The type data did the rest.

Classes recovered
2,516 validated
Record types
280, with full field lists
Private field maps
490 classes, 2,535 typed fields
Generated C header
296 structs, 659+ offsets and addresses
TMainForm table
0xB14D68, instance size 0x724
TFigure table
0x93AA04, instance size 0x64

That covered the whole figure model, down to the 48-byte TSegment and its 16 fields. It also covered the .piv file format.

Actually native

The goal of the rewrite was simple to say. A button on an external window sitting on top of Pivot isn’t native. That counts as a fail. I wanted a real PivotKit entry in Pivot’s own menu bar, made of the same objects as File and Edit.

It took several wrong answers.

The overlay came first: a separate window drawing a button. It was invisible at first, because I’d never called ShowWindow on it. Then it was visible and still a fake.

Next, real FMX controls. FMX control classes carry almost no metadata, so I found their constructors statically, by scanning the class tables for the byte pattern every inlined class-create gate shares, 84 D2 74 08 83 C4 F0 E8. Calling those from my tick deadlocked, because FMX needs the message pump alive to talk to its render thread. So UI work moved into a subclassed window procedure, running inside a real DispatchMessage.

Now the buttons existed and didn’t paint properly, because a freshly constructed control has no applied style. The funniest fix in the project was not to construct one at all. PivotKit copies the raw bytes of a live button that already paints, then patches its parent, text and position.

mods/00_pivotlib2.lua
-- Byte-clone a live control: the copy inherits applied styles/resources,
-- so it paints exactly like the template.
function FMX.clone_of(src, parent)
    local a = pivot.address(src)

The answer that finally felt right went one level earlier. Delphi stores each form’s layout as a binary resource inside the EXE, and at startup its own TReader streams that resource into live components. So PivotKit hooks the kernel32 resource functions (FindResourceW, SizeofResource, LoadResource, LockResource) and hands back a patched TMAINFORM with extra menu items in it. Pivot then builds my menu itself, believing it was always there.

Clicks are the last piece. Delphi stores a click handler as a code pointer and a Self pointer, at +0xA0 and +0xA4 on the item. PivotKit writes small stubs with the right calling convention into those slots, and Delphi’s own click dispatch does the rest.

Pivot Animator with PivotKit and Random Color entries in its menu bar, beside File, Edit, View and Help.
Native menu entries, sitting next to File and Help.
An About PivotKit window inside Pivot Animator, showing the logo, version details and a GitHub button.
The About window, opened from inside Pivot.

All of this worked.1

Scrapped

Then my friend had a falling out with that group of friends.

He doesn’t use Pivot. He was only making mods for them. I don’t use Pivot either. Without that group, nobody in the deal had any reason left to keep going, so the whole thing got scrapped.

The repository is archived now. main still carries a banner announcing a major rewrite in progress. That rewrite is real, it sits on its own branch, and the docs and research notes went with it.

It only ever supported one exact build of Pivot, 32-bit 5.2.11, and it could crash the program and lose your work. Nobody should treat it as a product.2

The rewrite branchThe native menu work and the reverse engineering notes live here, not on main.github.com

Go further into Delphi internalsChatGPTClaude

Footnotes

  1. The About window says Lua 5.4.6. The Lua actually embedded is 5.4.8. Nobody is going to fix that now. ↩

  1. I tried building Steam6 min
  2. Teaching Minecraft to fight back9 min
  3. I hacked my school4 min