A while ago I was asked to add some functionality to a Delphi app.
However the app is written in an old Delphi version; the company that wrote the app has long since disappeared and none of the contact people can be reached. Oh and there is no trace of source code anywhere.
Changing the application without writing code
Luckily the application uses SQL-server which is a nice multi-user database.
And there is the application itself. You can view and change the forms using a tool like Resource Hacker. This allows me to change things like SQL queries embedded in the forms.
The client requested me to add new functionality. This was not difficult, I can just write a separate application that accesses the database and gives them the bells and whistles they need.
Integrating the new forms into the old application
Having separate applications for new and existing functionality is not a great option so I tried to integrate the two applications into one.
The following is needed to achieve this goal:
- Application that starts the old app and injects a dll (Seattle);
- dll that alters the old application and loads the new functionality (D7);
- dll with the new functionality (Seattle);
- test application with the forms in dll (3) so I can test the correct operation of the dll.
- A copy of the exact Delphi version that was used to write the original application (D7).
Step 1: Inject a dll that will alter the old application
program InjectOldApp;
uses
uStartAndHookOldApp in 'uStartAndHookOldApp.pas';
begin
HookOldApp;
end.
procedure HookOldApp;
var
BytesWritten: SIZE_T;
Process, Thread, ThreadId, hKernel: cardinal;
pLoadLibrary, Parameters: pointer;
DLL: AnsiString;
HWndOldApp: HWnd;
StartupInfo: TStartupInfo;
ProcessInformation: TProcessInformation;
Path: string;
begin
Path:= ParamStr(0);
Path:= ExtractFilePath(Path);
Dll:= Path + 'HookOldApp.dll';
HWndOldApp:= FindWindowEx(0,0, nil, 'OldApp Window name');
if HWndOldApp = 0 then begin
FillChar(StartupInfo, SizeOf(TStartupInfo), #0);
StartupInfo.cb:= SizeOf(StartupInfo);
FillChar(ProcessInformation, SizeOf(TProcessInformation), #0);
Path:= Path + 'OldApp.exe';
CreateProcess(PWideChar(Path),nil,nil,nil,false,0,nil,nil,StartupInfo,ProcessInformation);
OldAppProcessID:= ProcessInformation.dwProcessId;
end else begin
Assert(HWndOldApp <> 0);
GetWindowThreadProcessId(HWndOldApp, @OldAppProcessID);
end;
Assert(OldAppProcessID <> 0);
Process:= OpenProcess(PROCESS_ALL_ACCESS, False, OldAppProcessID);
Assert(Process <> 0);
Parameters:= VirtualAllocEx(Process, nil, Length(DLL), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(Process, Parameters, PAnsiChar(DLL), Length(DLL)+1, BytesWritten);
hKernel:= GetModuleHandle('KERNEL32.DLL');
pLoadLibrary:= GetProcAddress(hKernel, 'LoadLibraryA');
Thread:= CreateRemoteThread(Process, nil, 0, pLoadLibrary, Parameters, 0, ThreadId);
WaitForSingleObject(Thread, INFINITE);
VirtualFreeEx(Process, Parameters, 0, MEM_RELEASE);
CloseHandle(Thread);
CloseHandle(Process);
end;
BTW: I omitted the error handling and try blocks everywhere for brevity.
Here’s how it works:
First we check to see if the old application is already running, if not we start it.
We get a ProcessID. Using this ID we gain access to the process.
Then we write a string (the name of the dll to load) in a bit of memory that we allocate in the address space of that application, we execute some code, wait for it to complete, and do clean up afterwards.
The code we execute is of course ‘LoadLibrary’ and the parameter we give is a pointer to the string we’ve just written.
This is text book code injection and this is bog standard.
Step 2: alter the old application using a dll written in exactly the same Delphi version as was used originally.
We need the old Delphi version (D7), because we need to make sure that the runtime library we’re using is exactly the same as the one the application is using.
We need to tread very carefully here and the smaller the impact we’re making on the old application the better it is.
We need to do the following things here:
- Start a procedure that does the following:
- Get a pointer to OldApp.MainForm, so we can inspect and activate new menus, buttons etc;
- Change the memory manager in our dll, so that it uses the memory manager of the application itself;
- Force the old application to load the dll with our shiny new functionality.
2.1 Start a procedure to do the work
We can’t just do work in dllmain. That may lock the application. In order to prevent deadlocks we will start a new thread and do our work there.
procedure EntryPoint(Reason: dword);
var
ThreadID: cardinal;
begin
if Reason = DLL_PROCESS_ATTACH then begin
Win32Check(CreateThread(nil,0, @Main, nil, 0, ThreadId));
end;
Assert(ThreadID <> 0);
end;
2.2 Get a pointer to OldApp.MainForm
We need a bit of voodoo to make this happen. The trick is to inspect the property list of the Window using EnumProps; a pointer to MainForm.Self is stored in a WinAPI property called ControlOf. Here’s how to get that pointer.
function Main(IgnoreMe: pointer): DWord; stdcall;
....
//Wait for the MainWindow to become visible and get its HWnd.
if HWndOldApp <> 0 then begin
EnumProps(HWndOldApp, @PropEnumProc);
end;
.....
function PropEnumProc(HWND: HWND; Prop: LPCTSTR; hData: integer): longbool; stdcall;
var
OrigProp: string;
begin
//ShowMessage('start enum');
Result:= true;
if (Integer(Prop) and $FFFF0000) <> 0 then begin //skip atoms
OrigProp:= string(Prop);
//ShowMessage(OrigProp);
if Pos('ControlOf', OrigProp) = 1 then begin
//ShowMessage('ControlOf found: '+ OrigProp);
MainFormSelf:= pointer(hData);
Result:= false; //stop enumerating
end;
//showmessage('exit enum');
end;
end;
The PropEnumProc puts a pointer to MainForm in the global variable MainFormSelf and exits. Now we can use Delphi to manipulate the form. However we need to be careful because we don’t know the framework that was used to create the controls. We can’t assume that just because a button is of type TButton that it’s a stock control. The original programmer may just have been obtuse in their naming of controls.
I got this code from the internet somewhere, but I can’t find the source any more. If someone knows the original source I’ll put up a link.
2.3 Change the memory manager in our dll so that it uses the application’s MemMan.
We can’t just hook into the old application and run its code whilst using our own memory manager. Using ShareMem does no good, we don’t want to share we want to cuddle and so we need to get very intimate.
function Main(IgnoreMe: pointer): DWord; stdcall;
.....
uModifyOldApp.HookMemMan;
procedure HookMemMan;
var
Data: PByte;
OffsetGetMem: integer;
begin
//GetMem
GetMemoryManager(MemMan);
Data:= @MemMan.GetMem;
SetLength(MemSnippet, SizeOf(TMemSnippet));
CopyMemory(@MemSnippet[0], Data, SizeOf(TMemSnippet));
//Go look for the address of the routine in memory
OffsetGetMem:= GetProcessBlock(MemSnippet, SizeOf(MemSnippet));
//ShowMessage(IntToHex(OffsetGetMem,8));
MemMan.GetMem:= pointer(OffsetGetMem);
//FreeMem
Data:= @MemMan.FreeMem;
SetLength(MemSnippet, SizeOf(TMemSnippet));
CopyMemory(@MemSnippet[0], Data, SizeOf(TMemSnippet));
//Go look for the address of the routine in memory
OffsetGetMem:= GetProcessBlock(MemSnippet, SizeOf(MemSnippet));
//ShowMessage(IntToHex(OffsetGetMem,8));
MemMan.FreeMem:= pointer(OffsetGetMem);
//ReallocMem
Data:= @MemMan.ReallocMem;
SetLength(MemSnippet, SizeOf(TMemSnippet));
CopyMemory(@MemSnippet[0], Data, SizeOf(TMemSnippet));
//Go look for the address of the routine in memory
OffsetGetMem:= GetProcessBlock(MemSnippet, SizeOf(MemSnippet));
//ShowMessage(IntToHex(OffsetGetMem,8));
MemMan.ReallocMem:= pointer(OffsetGetMem);
SetMemoryManager(MemMan);
end;
HookMemMan makes a few potentially dangerous assumptions:
- The original application uses the default memory manager;
- The memory routines are located somewhere near the start of the executable;
- The function signatures of the memory routines are unique (or at least unique enough).
We do a simple search and compare in the memory space of the old application to find the addresses of GetMem, FreeMem and ReAllocMem. This involves getting read access to the memory where the code of the application is stored using OpenProcess, VirtualQueryEx and ReadProcessMemory.
Finally we bolt our memory manager to the old application’s one using SetMemoryManager. Now we can safely call functions inside the application without memory corruptions.
If the application were to use FastMM then we’d have to get a pointer to GetMemoryManager in the old application and use that instead.
However there is another snag….
We are running in a different thread, so we need to somehow execute our code inside the main thread of the application.
In order to solve this we simply set the OnIdle event of the mainform so that it will in due course run the code we want in the correct thread using the correct memory manager.
constructor TEventHandler.Create(App: TApplication);
begin
inherited Create;
MyApp:= App;
OldApplicationActivate:= MyApp.OnActivate;
OldApplicationIdle:= MyApp.OnIdle;
MyApp.OnActivate:= Self.DoActivate;
MyApp.OnIdle:= Self.DoIdle;
end;
If the old application has fancy Setters and getters for the event handlers, this might fail due to the fact that the property is not stored where the RTL in the dll thinks it is.
So this code assumes the old application has direct access properties as is usual and the setting of the pointer is atomic so you should have no issues.
If the event handlers are rewired using getters and setters, you need to read the published properties of the form and retrieve the setter from there, but you’ll also run into thread contention issues.
2.4 Force the application to load our shiny new dll.
Prior to running this code we’ve changed the old exe file and added some menus and buttons as needed using Resource Hacker. Adding controls programmatically is a bad idea, because it breaks if the original application uses non-standard controls or has a patch in their VCL code.
In OldApp.OnIdle we change the click-handlers of these new controls so that they run the new forms:
procedure ScanInvoicesClick(Form: TForm; Sender: TMenuItem);
var
HLib: HInst;
ScanInvoive: TScanInvoice;
begin
HLib:= LoadLibrary('NewFuctionalityWrittenInDSeattle.dll');
ScanInvoice:= GetProcAddress(HLib, 'ShowFormScan');
if Assigned(ScanInvoice) then ScanInvoice(Form.Handle)
else ShowMessage('cannot find NewFuctionalityWrittenInDSeattle.dll');
end;
Showing the new forms
The new forms in NewFuctionalityWrittenInDSeattle.dll are completely stand-alone and share no state with the old application. The dll with the new functionality looks almost exactly like a stand-alone app. It is a library with a number of self-contained forms attached.
Every form has an exported function in the library code that looks like so:
procedure ShowFormScan(ParentForm: HWnd); export;
var
FormScan: TFormScan;
begin
FormScan:= TFormScan.Create(nil);
ShowForm(FormScan, ParentForm);
end;
...
exports
ShowFormScan;
That’s it, now I can add and replace as many forms in the old application as I want.
What I cannot do however is alter code inside existing forms in my old application, that is just too much of a minefield.