delphi-bpl
Skill2 starsChanged 12 days agoMITView on GitHub
Reverse engineer 32-bit Delphi binaries, especially BPL runtime packages, by going from exported names and string literals to the code that uses them and decompiling it with rz-ghidra or Ghidra (ReVa). Use when you need to know what a function in a .bpl, Delphi .dll or Delphi .exe does, which code reads a field or string, or how a value is calculated.
In this repository8 other files it gives its agents.
- binary-diffSkill
- binary-patchSkill
- dotnet-decompileSkill
- installer-triageSkill
- java-decompileSkill
- native-memory-tracingSkill
- unreal-engineSkill
- wine-debuggingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
19 rules. About 0 are common, 9 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈9
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 32
Go from a string to the code: when you know a field name, message, SQL fragment or key but not the function:
- Distinctive: line 62
Go from a screen to the code: when you know what the user clicks but not which method runs.
- Very specific: line 92
Only components with a field declared in the class show up.
- Very specific: line 129
Use the next export or the parent function's start as the end of the range, and give pD the size in bytes.
- Very specific: line 133
Always pass asm.comments=false to pd/pD on large files.
- Distinctive: line 155
Decompile one function with rz-ghidra: when the control flow is hard to follow in the disassembly.
- Very specific: line 186
Confirm in the disassembly: when a conclusion depends on a branch, an offset, a constant or the argument order, and always when the …
- Distinctive: line 190
Check the conclusion against what the program does: when it depends on a runtime value (a setting, a record, a mode flag) or when someone …
- Distinctive: line 205
Check this before reading any code.
- Distinctive: line 216
When both files hold the class, they share the logic, so a reading of one carries over to the other.
- Very specific: line 244
When the faulting function belongs to a library routine such as TStrings.IndexOfName, the bug is in the caller that passed nil.
- Very specific: line 278
try blocks: start with xor eax, eax; push ebp.
- Distinctive: line 370
A stored change that has no effect: When the program keeps ignoring a value that was changed where it is stored, look for a cache of the …
- Very specific: line 372
Search for format strings that build file names (bpl-xref str app.bpl '%s.') and for calls to the temporary directory helper, then read the …
- Very specific: line 416
Check that the lists are not empty before trusting an "equal".
- Distinctive: line 419
When a class gains fields, every method that touches the fields after the new ones changes its offsets, so almost the whole unit shows up …
- Very specific: line 427
When the code reads the same in every build and the behaviour still differs, look at the objects in memory.
- Very specific: line 550
Import headless and let Ghidra pick the borlanddelphi compiler spec on its own.
- Distinctive: line 590
Keep binaries, Ghidra projects and decompiled output out of git repositories.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Delphi BPL reverse engineering
A BPL (Borland Package Library) is a regular 32-bit PE DLL built by Delphi or C++Builder. It exports every symbol of every unit in the package with Borland name mangling, so most functions already have their real names. Start from those names and from string literals, not from a blank disassembly.
Decompiled Delphi code is rougher than decompiled Java. Delphi's register calling convention, Extended
floats and string helpers confuse every decompiler, so read the output as a lead and check anything
important in the disassembly.
Tools: bpl-xref (from this repo's bin/, needs python-pefile), rizin with the rz-ghidra
plugin, and Ghidra 12.1.3 or newer with the ReVa extension for long sessions.
Method
Read the exports and imports. They cost about a second even on a 30 MB package.
rz-bin -E app.bpl > exports.txt # vaddr in column 3, name last grep -i 'TOrder@' exports.txt | awk '{print $3, $NF}' rz-bin -l app.bpl # other packages and DLLs it importsThe imported packages tell you which BPLs hold the code it calls. Repeat step 1 on them when a call leaves the file.
Go from a string to the code when you know a field name, message, SQL fragment or key but not the function:
bpl-xref str app.bpl 'CustomerName' 'Invalid order'A fragment works too. It is reported as
'Customer' in 'CustomerName' at 0x..., with the references of the literal that holds it. For each match it prints the literal kind guessed from the bytes before it (AnsiString, UnicodeString, ShortString), every relocated pointer to it in code, the nearestpush ebp; mov ebp, espbefore each reference and the exports around it. Nested procedures are not exported and sit right before their parent, so when the reference is between two exports the "next" one is often the owner.A
ptrline instead ofrefmeans the pointer sits in a data section, usually a table (package names, resource strings, initialized records). The code reads the table slot, not the string, so runbpl-xref callson theptraddress to reach it.Messages declared as
resourcestringlive in the string table resource as UTF-16 without a terminator, and code never points at the text. It loads a record of a module handle pointer and the string ID (mov eax, offset rec; call LoadResString).stralso searches the string table, matching any string that contains the text, and prints(resourcestring ID), the record with its exported name when there is one (@Uorders@SInvalidOrder) and the code that references the record. A record without references in a package is usually loaded by other packages through that export.An EXE usually has no exports, so there are no "prev"/"next" lines. Start from the entry point (
rz-bin -e app.exe), from the import thunks, whichflagsnames, and from the event handlers thatdfm --eventsfinds through the VMTs (step 3).Go from a screen to the code when you know what the user clicks but not which method runs. Delphi stores each form as a binary DFM in an RCDATA resource named after the form class, and the form maps every event to a method name.
bpl-xref dfm app.bpl # every form, its class and number of events bpl-xref dfm app.bpl TFORDEREDIT # one form as text .dfm bpl-xref dfm --events app.bpl | grep -i -A1 'btnSave'Find the form by a caption or label in the text output, then take the component's
OnClick,OnChangeor other event.--eventsprints each handler with the exported method it names (@Unit@TForm@BtnSaveClick$qqrp14System@TObject), so the address is ready for steps 4 to 6. Events inside collection items show up asEdit1.Buttons[0].OnClick. Without an export, as in an EXE or for a handler an ancestor form declares, it looks the name up in the published method tables of the form's class and its ancestors and prints0x... TFOrderEdit.BtnSaveClick (published). When the ancestry continues in another package it names the imported ancestor instead, and the method is in that package's exports. A handler marked?was found neither way, and every exported method with that name is listed as a candidate. A form whose class has no VMT in the file is usually one the linker kept after dropping its class, so no code runs it.bpl-xref vmtreads the same VMTs without exports, in the layout of Delphi 2 to 2007 or of Delphi 2009 and later, which it picks from the file. Without a class it lists every class with its parent. With one it prints the published methods and the published fields with their offsets, somov eax, [ebx+0x3a0]in a form method isedtCustomer: TEdit:bpl-xref vmt app.exe | grep -i order # classes, parents, size of the published tables bpl-xref vmt app.exe TFOrderEdit # methods, then +offset name: type for each fieldOnly components with a field declared in the class show up. Pages of a
TNotebookand components of an ancestor form from another package don't.Find who calls a function, especially a nested procedure, which has no export and no name:
bpl-xref calls app.bpl 0x0045a1c0 '@Uorders@TOrder@Post$qqrv'It takes hex addresses or exact export names and lists
call/jmp rel32instructions plus relocated pointers (VMT slots, event handler tables). The rel32 hits come from a byte scan, not from disassembly, so treat them as candidates and check each one withpd 1 @ addr. Virtual and interface calls go throughcall dword [reg + offset]and don't show up. For those, find the VMT slot that points at the method (aptrhit) and search for its offset.A call on an interface pointer (
mov ebx, [eax]; call dword [ebx + 0x74]) doesn't use the class VMT. Its slot holds a stub that adjustsSelfand jumps to the method (add eax, -0x1c; jmp Method, oradd dword [esp+4], -0x18; jmp Methodfor a stdcall method), and the tables of all the interfaces of a class sit one after another. To name the method behind an offset, take a method you know the interface has, find its stub (thejmpthatbpl-xref callslists for the method), then the pointer to the stub (aptrhit), and walk back to the start of that table. The table starts with the stubs ofQueryInterface,AddRefandRelease, three in a row with one adjustment, and the offset in the call counts from the first of them. Walking back over everything that looks like a code pointer goes past it into the table of the previous interface and shifts every slot. One table read that way came out four entries off.Read the disassembly with names. Plain
pdshowscall 0x00401f30andmov edx, 0x0045c6fc. Generate rizin flags for the import thunks and for the string literals the range uses, then save the disassembly to a file:bpl-xref flags app.bpl 0x0045a1c0 0x0045b000 > flags.rz rizin -e scr.color=0 -e asm.comments=false -e asm.lines=false -e asm.bytes=false -q \ -i flags.rz -c 'pD 0xe40 @ 0x0045a1c0' app.bpl 2>rizin.err > func.asmThe same lines then read
call thunk.Uorders_TOrder_Post_qqrvandmov edx, str.CustomerName. Use the next export or the parent function's start as the end of the range, and givepDthe size in bytes. A 3.5 KB function is about a thousand lines, so grep the file (grep -n 'call\|0x4b8\]' func.asm) or read it in pieces instead of printing it whole.Always pass
asm.comments=falsetopd/pDon large files. The comments rizin computes for each instruction get slower the longer the listing: on a 60 MB package, 4 KB took 10 s, 16 KB didn't finish in 5 minutes, and with comments off 93 KB took 7 s, most of it startup.asm.lines=falsedrops the jump arrows, which only get in the way of grep. Flag names are cut at 48 characters, and a literal of one or two characters gets a name that doesn't show the character (str.for a space,str..for a dot,str.__1for an asterisk). When the reading depends on which separator aPosor a concatenation uses, print the bytes at the address instead of trusting the name. Print the full text of a literal withps ascii @ addr(AnsiString),psw @ addr(UnicodeString) orpsp @ addr(ShortString, from its length byte). Readfcomp dword [addr]style constants withpf f @ addr(Single) orpf F @ addr(Double).Without a range,
flagsnames every literal in the file. A large package has hundreds of thousands, which adds about 7 s to each rizin start. Every start also parses all the exports (around 5 s for 60k), so batch addresses with several-coptions or-i cmds.rzin one run. rizin warnsbin_file_strings: search interval size ... exceeds max region sizeon large files. That warning is harmless, but stderr also carries real errors (a flags file that fails to parse, a bad command), so send it to a file instead of/dev/nulland check it when the output is empty or the names are missing.For a quick look at a wide range without names,
objdump -d -M intel --no-show-raw-insn --start-address=0x0045a1c0 --stop-address=0x0045b000 app.bpltakes a fraction of a second.Decompile one function with rz-ghidra when the control flow is hard to follow in the disassembly. A small function takes a few seconds, a 2,000-instruction one around 20.
rizin -e scr.color=0 -e analysis.cc=borland -q \ -c 'af @ 0x0045a1c0' -c 'pdg @ 0x0045a1c0' app.bpl 2>rizin.erranalysis.cc=borlandonly changespdg.pdandpDignore it.Make register arguments visible. Calls to other Delphi functions come out as
Foo()with no arguments, because the arguments travel ineax,edxandecx. Give the callee a signature withafs, keeping-e analysis.cc=borlandon the command line:rizin -e scr.color=0 -e analysis.cc=borland -q \ -c 'af @ 0x00401f30' \ -c 'afs void set_value(int self, char *name, double v) @ 0x00401f30' \ -c 'af @ 0x0045a1c0' -c 'pdg @ 0x0045a1c0' app.bpl 2>rizin.errThe call then reads
set_value(self, "CustomerName"). Both settings are needed. Withoutafsthe arguments stay hidden, andafswithoutanalysis.cc=borlandreads them from the stack, which gives wrong values (set_value(iVar3, (char *)iVar2, ...)).afc borlandadds nothing. rz-ghidra warnsMatching calling convention borland ... failed, args may be inaccurate, which is expected.doublearguments are still shown as twouStack_*stores before the call.- Use Ghidra with ReVa for anything longer than a few functions: cross-references across the whole file, call graphs, renaming as you go. See the Ghidra section for import and the time it takes.
- Confirm in the disassembly when a conclusion depends on a branch, an offset, a constant or the
argument order, and always when the decompiled output has
unkfloat10,in_EAXor stack variables with no clear source. Quote the address and instruction for each conclusion. Check the conclusion against what the program does when it depends on a runtime value (a setting, a record, a mode flag) or when someone will act on it. Look for the effect in the data the program writes, or run the smallest input that takes the branch in question. When the reading and the observed behaviour disagree, one of the assumptions is wrong. Say so and find which one instead of reporting either result.
A branch that depends on a setting read by name needs two answers: where stored values come from and what the default is. The loader's query or file read gives the first. The default is usually an argument of the call that registers the setting, so search for the setting's name and read the arguments around that call. When no stored value exists, the default applies.
Which file actually runs
An EXE can contain the units of a package that it never imports. The package is then a copy built from the same source and loaded by something else, so analyzing or patching it changes nothing for the EXE. Check this before reading any code.
rz-bin -l app.exelists the packages the EXE imports. A package missing from that list is not loaded by it.bpl-xref vmt app.exe | grep -i ClassNameshows whether the classes you care about are inside the EXE. They then have their own VMT address in the EXE's range.- The module named in a crash log or a profiler is the file that ran. An exception address inside
app.exefor a class that you found inlib.bplmeans the EXE has its own copy. - On Linux or Wine,
/proc/PID/mapslists the images that the process loaded. On Windows,EnumProcessModulesExdoes (see "Inspecting a running process").
When both files hold the class, they share the logic, so a reading of one carries over to the other. The copies are separate builds, so addresses and thunk targets differ and small details can too. Find the same function in the file that runs and confirm the instructions there before patching.
From a crash log line to a function
A log often prints a module and an address, such as
Access violation at address 4A2F10C8 in module 'lib.bpl'. Read of address 00000000. To land on the code:
- Get the module's preferred base with
rz-bin -I lib.bpl | grep baddr. When the process loaded it at that base, the logged address is the file's virtual address. A module that loaded elsewhere needs the rebase delta, which/proc/PID/mapsor a debugger gives. - Sort the exports (
rz-bin -E lib.bpl) and take the last one at or before the logged address. The offset into the function is the difference. Nested procedures have no export and sit before their parent, so the owner can be the next export. - Disassemble a window around the address with
objdump -d -M intel --start-address=... --stop-address=... lib.bpl. In an EXE without exports, walk back from the address to the nearestpush ebp; mov ebp, espfor the start of the function and runbpl-xref callson it to find the callers.
What the instruction tells you:
mov reg, [ebp-4]followed bymov edx, [reg], with a read of address 0, is a method called on a nilSelf. The object was never created, or it was freed and its pointer cleared.- The same address repeated hundreds of times points to a deterministic nil, not to memory corruption.
A field freed with
FreeAndNiland used again behaves like this, because the pointer is zero and the read always faults at the same instruction. A real use after free usually shows varying addresses, garbage values or crashes that come and go. - When the faulting function belongs to a library routine such as
TStrings.IndexOfName, the bug is in the caller that passed nil. Read the caller, not the library.
Counting outcomes by message type in the same log shows how wide the failure is. Group the lines that report a result by type and by outcome. A type with no successes fails every time, and a type that mixes both depends on the data.
Reading Delphi code
- Mangled names.
@Unit@TClass@Method$qqr<params>.$qqris the register convention,$qqsstdcall (COM methods).$bctris a constructor,$bdtra destructor.@$xp$...is RTTI and@Unit@TClass@(ending in@) is the class VMT, both data even when they sit in the code section. The return type is not encoded. - Parameter codes.
xconst,rvar (by reference),ppointer,vno parameters,iInteger,oBoolean,usWord,ucByte,dDouble,gExtended, and a length-prefixed type name such as17System@AnsiString.$qqrx17System@AnsiStringdis(const s: AnsiString; d: Double). - Register convention. Self goes in
eaxfor methods. The first three integer, pointer or string parameters go ineax,edx,ecx, and the rest are pushed left to right.DoubleandExtendedalways go on the stack, so the decompiler numbers them in reverse (param_7is the first one). Ordinal results come back ineax, floats inST(0), and strings and records through a hidden lastvarparameter. - Strings. An AnsiString literal has a
-1reference count and a 32-bit length right before the first character, and code points at that character. A UnicodeString literal (Delphi 2009 and later) is UTF-16 with the same layout plus a code page and element size. ShortString constants and RTTI names are referenced through their length byte. Exports such as@System@@UStrCatmean Delphi 2009 or later,@System@@LStrCatalone means an older compiler. - Calls to other packages go through a
jmp dword [import]thunk. rizin names itsub.<package>.bpl__<Unit>_<Func>, so the thunk name is the callee. - Object fields are offsets from Self (
[eax + 0x480]). Ghidra may type Self as a pointer and scale the offset, so(ushort *)p + 0x240is byte offset0x480. Getter and setter exports (GetFoo/SetFoo) are a cheap way to map offsets to field names: decompile a few and read the offset each one touches. - Unit initialization is in
@Unit@initialization$qqrvand@Unit@Finalization$qqrv. Global registrations (class factories, lookup tables) often happen there. - try blocks start with
xor eax, eax; push ebp; push <handler>; push dword fs:[eax]; mov fs:[eax], espand end by restoringfs:[0]. The handler jumps to@System@@HandleFinallyfor try/finally and to@System@@HandleAnyExceptionor@System@@HandleOnExceptionfor try/except. When a literal shows up only in the except block, usually in an error message that names the operation, the code you want is the protected block right before it. Script interpreters embedded in Delphi programs often dispatch built-in functions this way, so the function's name leads to its error handler and the implementation sits just above. - Handlers outside the function in Ghidra. Ghidra doesn't follow the handler address that the
tryprologue pushes. The function body comes out as two ranges with the handler in the gap between them, the handler belongs to no function and its code isn't disassembled, so the decompiled code shows it only as&LAB_<handler>stored in a stack slot. An error message used only in the except block is missing from the decompiled code and Ghidra lists no references to it, whilebpl-xref strstill finds the reference. Disassemble from theLAB_address to read the handler. Foron E: EClass dothe handler isjmp @System@@HandleOnExceptionfollowed by a count and pairs of class cell and branch address, so each branch starts at the address in its pair, not after the jump. Checked with Ghidra 12.1.4 on packages. - Floating point width.
fld/fstpwithtbyteisExtended(10 bytes),qwordisDoubleanddwordisSingle. A value that passes through aDoubleparameter or result is no longer equal to the same decimal literal held asExtended. Compare against a small range when a test checks a computed float. - Class references. A
mov eax, [abs]before a constructor, anIsClassor a factory call loads a class pointer from a cell. For an imported class the cell is the import slot. For a class defined in the package the cell is thevmtSelfPtrat VMT minus 0x4C (0x58 from Delphi 2009 on), which holds the VMT's own address, and the class name is the ShortString just before the VMT. The class pointer is the VMT address.IsClass(obj, cls)takes the object ineaxand the class inedxand answers inal. - Library objects that the package doesn't import methods for. The fields of VCL classes sit at fixed
offsets for a given compiler, so code you inject can read them directly. In the Delphi 7 era layout a
TTreeNodehas the text at +8 andDataat +0xC, and aTStringsdescendant answersIndexOf,AddandDeletethrough virtual slots. Confirm each offset in code that already touches it (a handler that reads[node+0xC]before usingData) rather than trusting a table. - Creating a VCL control from injected code. Load the class pointer from the import slot of its VMT, call
the constructor (
mov dl, 1, owner inecx), thenSetParent,SetBounds,SetAnchorsandSetText, and keep the object in a state cell that the form'sOnDestroyhook clears. BothSetParentandSetBoundsare virtual, so call them through the object as described in thebinary-patchskill. With a nil owner nothing frees the control when the form goes away, so pass the form as owner when the control should die with it. - Editing a string literal in place. A shorter text fits if you write the new length and leave the total
size alone, padding with zeros after the new terminator. A longer one doesn't fit. To drop an argument from a
format string without touching the code, use an index:
'%1:s'prints the second argument of'Item %d: %s'and ignores the first. Runbpl-xref strfirst, because every reference to the literal gets the new text, including screens you didn't mean to change. When a text doesn't change on screen, it may come from a translation table and not from the literal. - Exceptions with extra fields. In an
on E: Exception dohandler the exception object is kept in a frame slot, saved right after the handler starts (mov [ebp-0x30], eax). A factory such asCreateDet(cls, message, details)stores the extra strings in fields after the standard ones. Code that logs onlyE.Messagediscards the rest, and@System@@DoneExceptfrees the object, so read the field before that call. Find its offset in the factory, where the extra argument is stored withLStrAsg. - Objects created in a loop and kept only under a condition. A loop that creates an object, hands it
to a routine that fills it and adds it to a parent only when it ended up non-empty (
Length > 0) leaks every empty one, because the path that skips theAddhas noFree. In the disassembly look for a constructor call, then a size test, then a conditional jump over the call that stores the object with nothing that releases it on the other side. Confirm with memory growth per iteration (see below), and after the fix compare the program's output before and after. - Reference counting bugs. Assigning a string goes through
@System@@LStrAsg(orUStrAsg), which adds a reference. A plainmov [obj + x], regof a string pointer does not. If the source is then released withLStrClrorLStrArrayClrbefore the field is used, the field points at freed memory and the result depends on whether that memory was reused. Interface variables are released with@System@@IntfClear.TObject.FreeorFreeAndNilon one calls through the wrong table and usually crashes. An object created and then overwritten without aFreeis a leak. - Which method a virtual call reaches.
call dword [ecx + 0x34]aftermov ecx, [eax]calls slot 0x34 of the object's VMT. To list what that slot runs in each class, search the file for the address of each candidate method as a dword. The match is the VMT slot, and its offset is the match address minus the class VMT export (@Unit@TClass@). Methods that are only reached through a slot show nocallreferences, so this is also how to find who runs them. TStringList.Objects. Up to Delphi 2007 aTStringListnever owns the objects stored withAddObject, and freeing the list leaves them alive. Code that hangs a freshly loaded collection on a list owned by a short-lived object leaks one collection per object. The same fact makes it safe to keep a pointer to such an object after the list is gone. Check theDestroyof the owner, and of the classes in the collection, before relying on it.TWriterandTReaderstreams. Component streams and many custom file formats are written value by value.ReadInteger,ReadBoolean,ReadString,ReadDateandReadListBeginread a one-byte type code first, andReadStr(a short string) does not. The codes up to Delphi 2007 are 0vaNull(end of list), 1vaList, 2vaInt8, 3vaInt16, 4vaInt32, 5vaExtended(10 bytes), 6vaString(length byte), 7vaIdent, 8vaFalse, 9vaTrue, 10vaBinary, 11vaSet, 12vaLString(32-bit length), 13vaNil, 14vaCollection, 15vaSingle, 16vaCurrency, 17vaDate(8-byte double), 18vaWString(32-bit length of UTF-16 units), 19vaInt64and 20vaUTF8String. With the reads of the loader in order, a field near the start of a file can be read without loading the rest. Find the loader by searching for the field's offset in the class (add eax, OFFSETbefore@LStrAsg, ormov [reg + OFFSET], eax) and follow the reads before it, including the version checks (cmp dword [eax + n], VERSION) that skip fields in old files.When something is loaded again. Code that loads data once (a list read from a database, a cached object) usually guards it with a field of the object. It tests the field (
cmp byte [eax+0x1c], 0), loads, and then sets it (mov byte [eax+0x1c], 1). To learn when the data is loaded again, find every write to that offset in the methods of the class. Take the address range of the class's exports and search the disassembly:objdump -d -M intel --no-show-raw-insn --start-address=0x... --stop-address=0x... app.bpl | grep -E 'mov +BYTE PTR \[e[a-z]+\+0x1c\]'Each write of zero is a place that invalidates the data. Run
bpl-xref callson the methods that hold them to see who triggers it. In one case only the destructor and an import routine of other subclasses cleared the flag, so the data stayed in memory until the program closed. The same offset is a different field in an unrelated class, so stay within the class and its descendants, which share the field layout.- A stored change that has no effect. When the program keeps ignoring a value that was changed where it is
stored, look for a cache of the processed result, often a file in the temporary directory or next to the data.
Search for format strings that build file names (
bpl-xref str app.bpl '%s.') and for calls to the temporary directory helper, then read the check that decides whether the cache is still valid. It often compares a version, a size and a hash of only part of the input. In one case the processed form of some data was cached under a hash of its text alone, so changing an option stored elsewhere did nothing until the cache file was deleted.
Comparing two builds
Export names stay the same between builds of a package and addresses don't. Match exported
functions by name, and nested procedures through the literals they reference (bpl-xref str on
both files). Then compare only the instructions the question depends on. A function that was
rewritten may also have been renamed or split, so when an export disappears, look for the same
literals in the new file before concluding the code is gone.
To see everything that changed between two builds, run ghidriff as described in the binary-diff
skill. On a BPL it matches most functions by their export names. Filter the JSON by unit
(test("@Unitname@")) to find what changed in the area you care about. The exported RTTI
(@$xp$...) and VMTs (@Unit@TClass@) come out as functions that fail to decompile or decompile
to nonsense, and many of them land in modified. Skip names that start with @$xp$.
ghidriff misses most changes in texts and forms of a Delphi binary, such as literals with accented
characters, messages used only in except blocks, resourcestrings and every form property. Compare
those with bpl-xref strings and bpl-xref dfm --all --no-geometry, as the binary-diff skill
shows. On an EXE, which has no exports, also name the published methods in the project with
bpl-xref vmt --names and ghidra_scripts/ApplyNames.java before trusting the report, or changed
event handlers can be missing from it.
For a first pass over one unit, before running ghidriff, compare its exported functions instruction by
instruction. Take each export of the unit and the next export as the range, so the nested procedures
that sit before the next export are included. Disassemble both builds with objdump, mask what moves
between builds, and compare the lists. It takes seconds for a few hundred functions.
import re, subprocess
def body(path, start, end):
out = subprocess.run(['objdump', '-d', '-M', 'intel', '--no-show-raw-insn',
f'--start-address={start}', f'--stop-address={end}', path],
capture_output=True, text=True).stdout
ins = [l.split('\t', 1)[1] for l in out.splitlines() if re.match(r'\s*[0-9a-f]+:\t', l)]
ins = [re.sub(r'0x[0-9a-f]{5,}', 'ADDR', i) for i in ins] # absolute addresses
ins = [re.sub(r'([+-])0x[0-9a-f]+\]', r'\1OFF]', i) for i in ins] # field offsets
return [re.sub(r'^(call|j\w+)\s+[0-9a-f]+\b.*', r'\1 X', i) for i in ins]- Check that the lists are not empty before trusting an "equal".
objdumpprints 8 digit addresses without leading spaces, and a pattern that required them matched nothing, so every function came out "equal" between two builds that had in fact changed. - When a class gains fields, every method that touches the fields after the new ones changes its offsets, so almost the whole unit shows up as different with the same function sizes. Masking the displacements removes most of that. What is left at the same size is usually small constants that also moved with the layout. Read the diff of the functions the question depends on before calling the change a logic change, and use ghidriff when you need the full picture.
Inspecting a running process
When the code reads the same in every build and the behaviour still differs, look at the objects in
memory. On Linux, including programs running under Wine, /proc/PID/mem can be read from Python
without attaching a debugger, and the process keeps running.
mem = open(f'/proc/{pid}/mem', 'rb', 0)
for line in open(f'/proc/{pid}/maps'):
lo, hi = (int(x, 16) for x in line.split()[0].split('-'))
if 'r' not in line.split()[1] or lo >= 0x80000000:
continue
try:
mem.seek(lo); data = mem.read(hi - lo)
except OSError:
continue # guard pages and unreadable mappings
...On Windows the same reads go through the Win32 API from 64-bit Python with ctypes, and the process
keeps running too. LIST_MODULES_ALL is what makes the 32-bit modules of a Delphi program visible from
64-bit Python, and each module handle is the image's load address:
import ctypes
from ctypes import wintypes as w
k32 = ctypes.WinDLL('kernel32', use_last_error=True)
k32.OpenProcess.restype = w.HANDLE
k32.VirtualQueryEx.argtypes = [w.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]
k32.ReadProcessMemory.argtypes = [w.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t,
ctypes.POINTER(ctypes.c_size_t)]
k32.K32EnumProcessModulesEx.argtypes = [w.HANDLE, ctypes.c_void_p, w.DWORD, ctypes.POINTER(w.DWORD), w.DWORD]
k32.K32GetModuleFileNameExW.argtypes = [w.HANDLE, ctypes.c_void_p, w.LPWSTR, w.DWORD]
class MBI(ctypes.Structure): # MEMORY_BASIC_INFORMATION
_fields_ = [('BaseAddress', ctypes.c_void_p), ('AllocationBase', ctypes.c_void_p),
('AllocationProtect', w.DWORD), ('PartitionId', w.WORD), ('RegionSize', ctypes.c_size_t),
('State', w.DWORD), ('Protect', w.DWORD), ('Type', w.DWORD)]
h = k32.OpenProcess(0x0400 | 0x0010, False, pid) # PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
mods, needed = (ctypes.c_void_p * 1024)(), w.DWORD()
k32.K32EnumProcessModulesEx(h, mods, ctypes.sizeof(mods), ctypes.byref(needed), 3) # LIST_MODULES_ALL
name = ctypes.create_unicode_buffer(260)
for base in mods[:needed.value // ctypes.sizeof(ctypes.c_void_p)]:
k32.K32GetModuleFileNameExW(h, base, name, 260)
print(hex(base), name.value)
READABLE = 0x02 | 0x04 | 0x08 | 0x20 | 0x40 | 0x80 # PAGE_READONLY to PAGE_EXECUTE_WRITECOPY
mbi, addr = MBI(), 0
while addr < 1 << 32 and k32.VirtualQueryEx(h, ctypes.c_void_p(addr), ctypes.byref(mbi), ctypes.sizeof(mbi)):
lo, size = mbi.BaseAddress or 0, mbi.RegionSize
addr = lo + size
if mbi.State != 0x1000 or mbi.Protect & 0x100 or not mbi.Protect & READABLE:
continue # not committed, guard page or no access
buf, got = ctypes.create_string_buffer(size), ctypes.c_size_t()
if not k32.ReadProcessMemory(h, ctypes.c_void_p(lo), buf, size, ctypes.byref(got)):
continue
data = buf.raw[:got.value]
...The module list also shows the WOW64 modules above 4 GB, which the scan skips. Reading a program that runs as administrator needs Python started as administrator too.
Reading another process needs ptrace permission. With
kernel.yama.ptrace_scope = 1(the usual default) only a parent can read its child, and the read fails withPermission denied. Set it to 0 withsudo sysctl kernel.yama.ptrace_scope=0for the session and back to 1 when done. Without sudo, a program you start yourself can allow it for its own process, which is useful withstrace -ponce it has settled, since starting it understraceslows down its startup. The exception ends with the process, but while it runs any program of the same user can trace it.python3 -I -c 'import ctypes, os, sys ctypes.CDLL(None).prctl(0x59616d61, ctypes.c_ulong(-1).value, 0, 0, 0) # PR_SET_PTRACER, any os.execv(sys.argv[1], sys.argv[1:])' ./program & sleep 15 strace -f -e trace=ioctl -p $!strace -kadds a stack to each call and can slow a busy program so much that the trace no longer shows its normal behavior. In one test, 15 seconds of tracingioctlwent from over 30,000 calls to about 300.- The first dword of every Delphi object is its class pointer, which is the address of the exported
VMT symbol
@Unit@TClass@(adjusted by the rebase delta if the package didn't load at its preferred base, which/proc/PID/mapsor the module list on Windows shows). Scanning readable memory for aligned dwords equal to that address lists the instances. Expect false hits inside the VMT itself, in RTTI and in freed objects, so check a few fields before trusting one. - To find which field holds a sub-object when you don't know the offset, scan the object for
pointers whose target starts with the VMT of the class you expect. Then read the container. Get the
layout from the getters (
TList.GetCount,TCollection.GetCount) in the build you are looking at, since field offsets change between compiler versions. - An AnsiString field points at the first character, with the length in the dword before it and the reference count before that.
- Comparing instances answers questions that the code alone doesn't. For example, when the same data exists in a runtime object and in an edit copy, counting the items each one holds shows which copy lost them.
- Growth per unit of work. To compare variants of a patched binary, sample the resident size and a counter that a hook increments once per unit, then divide the growth by the units over the same range for every variant. The cost of a unit depends on its content, so the cumulative average of runs of different lengths misleads. One variant looked like 0.77 MB per item that way and was 1.14 over the range the other runs shared. Disabling one callee at a time narrows a leak down quickly, but a variant that skips only the allocation's consumer may not change anything, because the leaked object is created before it.
- Where the time goes. Sampling
/proc/PID/task/TID/stat(the state letter) and/proc/PID/task/TID/syscallshows whether the main thread is running or blocked, and in which system call.perf record -e cpu-clock:u -g -p PIDcounts CPU only, so a program that spends most of its time waiting looks almost idle, and the wall clock is the number that matters to the user. Under Wine the packages have no names in/proc/PID/maps. Build the module table by reading the first bytes of each candidate image at its preferred base from/proc/PID/memand comparing theTimeDateStampwith the file's header, then name each sampled address with the nearest export fromrz-bin -E. Thewine-debuggingskill has the rest.
Debuggers under Wine are fragile. winedbg --gdb on a 32-bit program in Wine's new WoW64 mode
reports the target as i386, but its break-in thread runs at a 64-bit address. gdb truncates that
address, reports a SIGSEGV, and detaching then can leave the program dead or frozen. The gdb proxy
also accepts a single connection, so a failed session can't be resumed. Prefer reading memory as
above, or a GUI debugger such as x32dbg running inside the same Wine prefix, and warn whoever is
using the program that it may close.
Ghidra and ReVa
- Use Ghidra 12.1.3 or newer. Up to 12.1.2 the PE loader read the export ordinal table as signed 16-bit values, so every name whose index is 32768 or above came out unnamed. A package with 63k exports lost almost half its names. Re-import files loaded by an older version, since upgrading the project keeps the wrong symbols.
Import headless and let Ghidra pick the
borlanddelphicompiler spec on its own. The script isghidra-analyzeHeadlessin the Arch package andsupport/analyzeHeadlessin the release zip.ghidra-analyzeHeadless ~/ghidra-projects/app app -import app.bpl -loader PeLoader \ -analysisTimeoutPerFile 7200A 30 MB BPL with 63k exports took about 5 minutes to import and 15 to analyze on 20 cores, and the project used 700 MB. Name matching in the PE loader grows with the square of the export count, so import time climbs fast with very large packages. Reopening an analyzed project with
-process app.bpl -noanalysis -readOnlytakes seconds.ReVa in assistant mode (Ghidra GUI open, ReVa Application Plugin enabled, MCP server on
http://localhost:8080/mcp/message) works on the persistent, already analyzed project. That's the mode to use for large packages.claude mcp add --scope user --transport http ReVa -- http://localhost:8080/mcp/message- ReVa in headless/stdio mode (
mcp-reva) creates a temporary project for every session and has to import and analyze from scratch. With a large BPL the import passes its 120 s default timeout and ReVa falls back to another loader, which yields a 16-bit MZ program at0x1000:0000. If you see that address, the import is wrong. Fine for small DLLs, not for big packages. - ReVa's
run-scriptonly works when Ghidra was started through PyGhidra (pyghidrain the Arch package,support/pyghidraRunin the release zip), not through the plainghidralauncher.
Other tools
- pefile stops at 8192 exports and calls the rest corrupt. Pass the limit to the constructor,
pefile.PE(path, max_symbol_exports=1 << 20). Changingpefile.MAX_SYMBOL_EXPORT_COUNThas no effect, because the constructor reads it only as a default. Its import list is also incomplete for large BPLs. It stops after 8192 symbols and silently drops names with characters such as%, which Delphi uses inSystem@%SmallString$iuc$255%.bpl-xrefreads the import table itself. - IDR (Interactive Delphi Reconstructor) recovers class and form data from EXEs, but it's GUI-only on Windows and supports up to Delphi XE4. For BPLs the exports already give the names it would recover. Dhrake needs IDR's output.
strings -aandstrings -el(UTF-16) are quick to check that a literal exists before runningbpl-xref str.
Keep binaries, Ghidra projects and decompiled output out of git repositories.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

