Delphi Detours

The Detour library is an amazing way to mock the Delphi routines or apply run-time redirection of a function calls inside of the executable module. The library can be found at the following location: https://github.com/MahdiSafsafi/delphi-detours-library.

Using this library you can hook not only the Delphi routines but also the WinAPI calls! This is one of the possibilities to test the code which uses the system calls.

For example if we have the following code we want to “test”:

function Victim: String;
begin
  Result := GetCurrentDir;
end;

we can write following small test project to do that:

program DetourTest;

{$APPTYPE CONSOLE}

uses
 DDetours,
 System.SysUtils;

function Victim: String;
begin
 Result := GetCurrentDir;
end;

function VictimMock: String;
begin
 Result := 'C:\Your\Test\Path';
end;

function TestVictim: String;
var
 P: Pointer;
begin
 P := InterceptCreate(@Victim, @VictimMock);
 try
   Result := Victim;
 finally
   InterceptRemove(P);
 end;
end;

begin
 Writeln(Victim);
 Writeln(TestVictim);
end.

The output of the program above will be:

C:\Users\Admin\Documents\Embarcadero\Studio\Projects\Win32\Debug
C:\Your\Test\Path

The main idea there is not about the thing that we test GetCurrentDir routine, but the thing that we can mock the call to it and give the return value we need for our purposes.

This library works like a charm with Delphi Berlin 10.2 Update 2 – haven’t tested with any version before.

More detailed documentation about the hooking you can find at the author’s documentation page: https://github.com/MahdiSafsafi/delphi-detours-library/blob/wiki/DDetours.md.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s