Detours Overview

Microsoft Research Detours Package Overview

Detours is a library for intercepting arbitrary Win32 binary functions on x86 machines. Interception code is applied dynamically at runtime. Detours replaces the first few instructions of the target function with an unconditional jump to the user-provided detour function. Instructions from the target function are placed in a trampoline. The address of the trampoline is placed in a target pointer. The detour function can either replace the target function or extend its semantics by invoking the target function as a subroutine through the target pointer to the trampoline.

Detours are inserted at execution time. The code of the target function is modified in memory, not on disk, thus enabling interception of binary functions at a very fine granularity. For example, the procedures in a DLL can be detoured in one execution of an application, while the original procedures are not detoured in another execution running at the same time. Unlike DLL re-linking or static redirection, the interception techniques used in the Detours library are guaranteed to work regardless of the method used by application or system code to locate the target function.

In addition to basic detour functionality, Detours also includes functions to edit the DLL import table of any binary, to attach arbitrary data segments to existing binaries, and to load a DLL into a new process. Once loaded into a process, the instrumentation DLL can detour any function in the process, whether in the application or the system libraries, such as the Windows APIs.

The technical overview of Detours is divided into three sections:

  • Interception of Binary Functions
  • Using Detours
  • Payloads and DLL Import Editing

Developers new to Detours will find the it very useful to read all three technical overview sections and the Simple sample.

This documentation also contains the following information:

  • Detours API reference
  • Sample programs using the Detours APIs.
  • Frequently Asked Questions (FAQ)


Interception of Binary Functions

The Detours library enables interception of function calls. Interception code is applied dynamically at runtime. Detours replaces the first few instructions of the target function with an unconditional jump to the user-provided detour function. Instructions from the target function are preserved in a trampoline function. The trampoline consists of the instructions removed from the target function and an unconditional branch to the remainder of the target function.

When execution reaches the target function, control jumps directly to the user-supplied detour function. The detour function performs whatever interception preprocessing is appropriate. The detour function can return control to the source function or it can call the trampoline function, which invokes the target function without interception. When the target function completes, it returns control to the detour function. The detour function performs appropriate postprocessing and returns control to the source function. Figure 1 shows the logical flow of control for function invocation with and without interception.

Figure 1. Control flow of invocation without Detours and with Detours.

The Detours library intercepts target functions by rewriting their in-process binary image. For each target function, Detours actual rewrites two functions, the target function and the matching trampoline function, and one functon pointer, the target ppinter. The trampoline function is allocated dynamically by Detours. Prior to insertion of a detour, the trampoline contains only a single jump instruction to the target function. After insertion, the trampoline contains the initial instructions from the target function and a jump to the remainder of the target function.

The target pointer is initialized by the user to point to the target function. After a detour is attached to the target function, the target pointer is modified to point to the trampoline function. After the detour is detached from the target function, the target pointer is returned to point to the original target function.

Figure 2. Trampoline and target functions, before (on the left) and after (on the right) insertion of the detour.

Figure 2 shows the insertion of a detour. To detour a target function, Detours first allocates memory for the dynamic trampoline function (if no static trampoline is provided) and then enables write access to both the target and the trampoline. Starting with the first instruction, Detours copies instructions from the target to the trampoline until at least 5 bytes have been copied (enough for an unconditional jump instruction). If the target function is fewer than 5 bytes, Detours aborts and returns an error code.

To copy instructions, Detours uses a simple table-driven disassembler. Detours adds a jump instruction from the end of the trampoline to the first non-copied instruction of the target function. Detours writes an unconditional jump instruction to the detour function as the first instruction of the target function. To finish, Detours restores the original page permissions on both the target and trampoline functions and flushes the CPU instruction cache with a call to the FlushInstructionCache API.


Using Detours

Two things are necessary in order to detour a target function: a target pointer containing the address of the target function and a detour function. For proper interception the target function, detour function, and the target pointer must have exactly the same call signature including number of arguments and calling convention. Using the same calling convention insures that registers will be properly preserved and that the stack will be properly aligned between detour and target functions

The code fragment in Figure 5 illustrates the usage of the Detours library. User code must include the detours.h header file, link with the detours.lib library, and have access to the detoured.dll dynamic link library at runtime.

#include <windows.h>
#include <detours.h>

static LONG dwSlept = 0;

// Target pointer for the uninstrumented Sleep API.
static VOID (WINAPI * TrueSleep)(DWORD dwMilliseconds) = Sleep;

// Detour function that replaces the Sleep API.
VOID WINAPI TimedSleep(DWORD dwMilliseconds)
{
    // Save the before and after times around calling the Sleep API.
    DWORD dwBeg = GetTickCount();
    TrueSleep(dwMilliseconds);
    DWORD dwEnd = GetTickCount();

    InterlockedExchangeAdd(&dwSlept, dwEnd - dwBeg);
}

// DllMain function attaches and detaches the TimedSleep detour to the
// Sleep target function.  The Sleep target function is referred to
// through the TrueSleep target pointer.
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
    if (dwReason == DLL_PROCESS_ATTACH) {
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourAttach(&(PVOID&)TrueSleep, TimedSleep);
        DetourTransactionCommit();
    }
    else if (dwReason == DLL_PROCESS_DETACH) {
        DetourTransactionBegin();
        DetourUpdateThread(GetCurrentThread());
        DetourDetach(&(PVOID&)TrueSleep, TimedSleep);
        DetourTransactionCommit();
    }
    return TRUE;
}
Figure 5. Simple detour to modify the Windows Sleep API.

Interception of the target function is enabled by invoking the DetourAttach API within a detour transaction. A detour transaction is marked by calls to the DetourTransactionBegin API and the DetourTransactionCommit API. The DetourAttach API takes two arguments: the address of the target pointer and the pointer to the detour function. The target function is not given as an argument because it must already be stored in the target pointer.

The DetourUpdateThread API enlists threads in the transaction so that their instruction pointers are appropriately updated when the transaction commits.

The DetourAttach API allocates and prepares a trampoline for calling the target function. When the detour transaction commits, the target function and trampoline are rewritten and the target pointer is updated to point to the trampoline function.

Once a target function has been detoured, any call to the target function will be re-routed through the detour function. It is the responsibility of the detour function to copy arguments when invoking the target function through the trampoline. This is intuitive as the target function becomes simply a subroutine callable by the detour function.

Interception of a target function is removed by calling the DetourDetach API within a detour transaction. Like the DetourAttach API, the DetourDetach API takes two arguments: the address of the target pointer and the pointer to the detour function. When the detour transaction commits, the target function is rewritten and restored to its original code, the trampoline function is deleted, and the target pointer is restored to point to the original target function.

In cases where detour functions need to inserted into an existing application without source code access, the detour functions should be packaged in a DLL. The DLL can be loaded into a new process at creation time using the DetourCreateProcessWithDll API.

NOTE: Microsoft in no way warrants or supports any Microsoft or third-party code that has been altered either with a detour or with any other mechanism.

The withdll.exe program include in the Detours package uses the DetourCreateProcessWithDll API to start a new process with a named DLL.


Payloads and DLL Import Editing

In addition to APIs for attaching and detaching detours functions, the Detours package also include APIs for attaching arbitrary data segments, called payloads, to Windows binary files and for editing DLL import tables. The binary editing APIs in Detours are fully reversible; Detours stores recovery information within the binary to enable removal of the edits at any time in the future.

Figure 3. Format of a Windows PE binary file.

Figure 3 shows the basic structure of a Windows Portable Executable (PE) binary file. The PE format for Windows binaries is an extension of COFF (the Common Object File Format). A Windows binary consists of a DOS compatible header, a PE header, a text section containing program code, a data section containing initialized data, an import table listing any imported DLLS and functions, an export table listing functions exported by the code, and debug symbols. With the exception of the two headers, each of the other sections of the file is optional and may not exist in a given binary.

Figure 4. Format of a Detours-modified binary file.

To modify a Windows binary, Detours creates a new .detours section between the export table and the debug symbols, as shown in Figure 4. Note that debug symbols must always reside last in a Windows binary. The new section contains a detours header record and a copy of the original PE header. If modifying the import table, Detours creates the new import table, appends it to the copied PE header, then modifies the original PE header to point to the new import table. Finally, Detours writes any user payloads at the end of the .detours section and appends the debug symbols to finish the file. Detours can reverse modifications to the Windows binary by restoring the original PE header from the .detours section and removing the .detours section. Figure 4 shows the format of a Detours-modified Windows binary.

Creating a new import table serves two purposes. First, it preserves the original import table in case the programmer needs to reverse all modifications to the Windows file. Second, the new import table can contain renamed import DLLs and functions or entirely new DLLs and functions. For example, the setdll.exe program included in the Detours package, inserts an initial entry for a user’s DLL into a target application binary. As the first entry in the application’s import table, the user’s DLL is always the first DLL to run in the application’s address space.

Detours provides APIs for editing import tables (DetourBinaryEditImports), adding payloads (DetourBinarySetPayload), enumerating payloads (DetourBinaryEnumeratePayloads), and removing payloads (DetourBinaryPurgePayloads). Detours also provides APIs for enumerating the binary files mapped into an address space (DetourEnumerateModules) and locating payloads within those mapped binaries (DetourFindPayload). Each payload is identified by a 128-bit globally unique identifier (GUID). Payloads can be used to attach per-application configuration data to application binaries.

Payloads can be copied directly into a target process using the DetourCopyPayloadToProcess API.


Detours Reference

Detours API Reference

The Table of Contents provides an alphabetical listing of the available API functions, which can be grouped as follows:

APIs For Detouring Target Functions

  • DetourTransactionBegin
  • DetourUpdateThread
  • DetourAttach
  • DetourAttachEx
  • DetourDetach
  • DetourSetIgnoreTooSmall
  • DetourTransactionAbort
  • DetourTransactionCommit
  • DetourTransactionCommitEx

APIs For Finding Targets Functions

  • DetourFindFunction
  • DetourCodeFromPointer

APIs For Accessing Loaded Binaries and Payloads

  • DetourEnumerateModules
  • DetourGetEntryPoint
  • DetourGetModuleSize
  • DetourEnumerateExports
  • DetourFindPayload
  • DetourGetSizeOfPayloads

APIs For Modifying Binaries

  • DetourBinaryOpen
  • DetourBinaryEnumeratePayloads
  • DetourBinaryFindPayload
  • DetourBinarySetPayload
  • DetourBinaryDeletePayload
  • DetourBinaryPurgePayloads
  • DetourBinaryEditImports
  • DetourBinaryResetImports
  • DetourBinaryWrite
  • DetourBinaryClose

APIs For Inserting DLLs and Payloads Into New Processes

  • DetourCreateProcessWithDll
  • DetourCopyPayloadToProcess
  • DetourGetDetouredMarker
  • DetourRestoreAfterWith


DetourAttach

Attach a detour to a target function.

Definition

LONG DetourAttach(
    PVOID * ppPointer,
    PVOID pDetour
    );

Parameters

ppPointer
Pointer to the target pointer to which the detour will be attached.
pDetour
Pointer to the detour function.

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_INVALID_BLOCK
The function referenced is too small to be detoured.
ERROR_INVALID_HANDLE
The ppPointer parameter is null or points to a null pointer.
ERROR_INVALID_OPERATION
No pending transaction exists.
ERROR_NOT_ENOUGH_MEMORY
Not enough memory exists to complete the operation.

Remarks

DetourAttach attaches a detour to a target function as part of the current transaction opened by the DetourTransactionBegin API.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Commem, Cping, Dtest, Excep, FindFunc, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


DetourAttachEx

Attach a detour to a target function and retrieve additional detail about the ultimate target.

Definition

LONG DetourAttachEx(
    PVOID * ppPointer,
    PVOID pDetour,
    PDETOUR_TRAMPOLINE * ppRealTrampoline
    PVOID * ppRealTarget
    PVOID * ppRealDetour
    );

Parameters

ppPointer
Pointer to the target pointer to which the detour will be attached.
pDetour
Pointer to the detour function.
ppRealTrampoline
Variable to receive the address of the trampoline.
ppRealTarget
Variable to receive the final address of the target function.
ppRealDetour
Variable to receive the final address of the detour function.

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_INVALID_BLOCK
The function referenced is too small to be detoured.
ERROR_INVALID_HANDLE
The ppPointer parameter is null or points to a null pointer.
ERROR_INVALID_OPERATION
No pending transaction exists.
ERROR_NOT_ENOUGH_MEMORY
Not enough memory exists to complete the operation.

Remarks

DetourAttachEx attaches a detour to a target function and retrieves additional detail about the ultimate target as part of the current transaction opened by the DetourTransactionBegin API.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.


DetourBinaryClose

Close a binary opened for editing.

Definition

BOOL DetourBinaryClose(
    PDETOUR_BINARY pBinary
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen, .

Return value

If successful, returns TRUE; otherwise, returns FALSE.

Remarks

DetourBinaryClose closes the binary opened for editing by DetourBinaryOpen.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Related Samples

Dumpi, Impmunge, Setdll.


DetourBinaryDeletePayload

Remove a payload from a binary.

Definition

BOOL DetourBinaryDeletePayload(
    PDETOUR_BINARY pBinary,
    REFGUID rguid
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen, .
rguid
GUID of payload to remove.

Remarks

DetourBinaryDeletePayload removes a payload from a binary opened by DetourBinaryOpen .

For more information on binary editing with Detours and paylods, see Payloads and DLL Import Editing in the Detours Overview.

Return value

If successful, returns TRUE; otherwise, returns FALSE.


DetourBinaryEditImports

Edit the import tables of a binary.

Definition

BOOL DetourBinaryEditImports(
    PDETOUR_BINARY pBinary,
    PVOID pContext,
    PF_DETOUR_BINARY_BYWAY_CALLBACK pfByway,
    PF_DETOUR_BINARY_FILE_CALLBACK pfFile,
    PF_DETOUR_BINARY_SYMBOL_CALLBACK pfSymbol,
    PF_DETOUR_BINARY_COMMIT_CALLBACK pfFinal
    );

Parameters

pBinary
Pointer to binary opened by DetourBinaryOpen .
pContext
Program specific context pointer to be passed unmodified to each callback function.
pfByway
Callback function called before each module in the import table.
pfFile
Callback function called once for each module in the import table.
pfSymbol
Callback function called once for each symbol in the import table.
pfCommit
Callback function called at the end of the import table if there have been no errors.

Return value

If successful, returns TRUE; otherwise, returns FALSE.

Remarks

DetourBinaryEditImports edits the import tables of a binary opened by DetourBinaryOpen. Detours stores edits in a reversible format using a Detours payload. The DetourBinaryResetImports function can be used to remove the edits.

DetourBinaryEditImports walks sequentially through the import table of a binary making callbacks on all points of interest. Four points of interest are currently support, each with its own callback function:

  • Files: The pfFile function is called for each file listed in the import table. The callback function can alter the file name at its discretion.
  • Symbols: The pfSynbol function is called for each symbol listed in each file in the import table. The callback function can alter the symbol name at its discretion.
  • Byways: The pfByway function is called once at the start of the import table, between each pair of import functions, and again at the end of the import table. The pfByway function can at its dicretion introduce a new import file into the import table. When a byway is inserted, the import table is modified to import the function exported with ordinal #1 from the named import file.
  • Commit: The pfCommit function is called at the end of walking the import table if no errors have been returned by previous callback functions.

Consider a binary that imports the functions CreateFileW and CloseHandle from Kernel32.dll, the function CommandLineToArgvW from Shell32.dll, the functions RegOpenKeyExW, RegQueryValueW, and RegCloseKey from AdvApi32.dll, and has a byway for MyDetour.Dll inserted from a previous call to DetoursBinaryEditImports. A program calling DetoursBinaryEditImports would receive the following callbacks:

  • BywayCallback (..., NULL, ...)
  • BywayCallback (..., "MyDetour.dll", ... )
  • BywayCallback (..., NULL, ...)
  • FileCallback (..., "Kernel32.dll", ...)
  • SymbolCallback (..., "CloseHandle", ...)
  • SymbolCallback (..., "CreateFileW", ...)
  • BywayCallback (..., NULL, ...)
  • FileCallback (..., "Shell32.dll", ...)
  • SymbolCallback (..., "CommandLineToArgvW", ...)
  • BywayCallback (..., NULL, ...)
  • FileCallback (..., "AdvApi32.dll", ...)
  • SymbolCallback (..., "RegCloseKey", ...)
  • SymbolCallback (..., "RegQueryValueW", ...)
  • SymbolCallback (..., "RegOpenKeyExW", ...)
  • BywayCallback (..., NULL, ...)
  • CommitCallback (...)

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Note: Each DLL inserted as a byway must export a function with ordinal #1. If the export table for the DLL does not export a function with ordinal #1, the target binary will fail to load correct.

Related Samples

Dumpi, Impmunge, Setdll.


PF_DETOUR_BINARY_BYWAY_CALLBACK

Pointer to function called once for each existing byway or opportunity to insert a new byway while editing an import table using the DetourBinaryEditImports API.

Definition

BOOL BinaryBywayCallback(
    PVOID pContext,
    PCHAR pszFile,
    PCHAR * ppszOutFile
    );

Parameters

pContext
Umodified program specific context pointer passed as pContext argument to DetourBinaryEditImports.
pszFile
Name of byway listed in current import table or NULL.
ppszOutFile
Pointer to output name of desired byway.

Return value

TRUE to continue editing import table or FALSE to abort.

Remarks

PF_DETOUR_BINARY_BYWAY_CALLBACK is called once for each existing byway in the target binary and once before or after each file or byway listed in the existing import table. When called for an existing byway, pszFile will have a non-NULL value.

When PF_DETOUR_BINARY_BYWAY_CALLBACK is called before or after an existing file or byway, pszFile will be NULL. The callback function can use this opportuninty to insert a new byway if desired.

Note: Each DLL inserted as a byway must export a function with ordinal #1. If the export table for the DLL does not export a function with ordinal #1, the target binary will fail to load correct.


PF_DETOUR_BINARY_COMMIT_CALLBACK

Pointer to function called at the end of editing an import table using the DetourBinaryEditImports API.

Definition

BOOL BinaryCommitCallback(
    PVOID pContext
    );

Parameters

pContext
Umodified program specific context pointer passed as pContext argument to DetourBinaryEditImports.

Return value

TRUE to continue editing import table or FALSE to abort.


PF_DETOUR_BINARY_FILE_CALLBACK

Pointer to function called once for file while editing an import table using the DetourBinaryEditImports API.

Definition

BOOL BinaryFileCallback(
    PVOID pContext,
    PCHAR pszOrigFile,
    PCHAR pszFile,
    PCHAR * ppszOutFile
    );

Parameters

pContext
Umodified program specific context pointer passed as pContext argument to DetourBinaryEditImports.
pszOrigFile
Name of file listed in original import table.
pszFile
Name of file listed in current import table
ppszOutFile
Pointer to output desired import table name.

Return value

TRUE to continue editing import table or FALSE to abort.


PF_DETOUR_BINARY_SYMBOL_CALLBACK

Pointer to function called once for each symbol while editing an import table using the DetourBinaryEditImports API.

Definition

BOOL BinarySymbolCallback(
    PVOID pContext,
    ULONG nOrigOrdinal,
    ULONG nOrdinal,
    ULONG * pnOutOrdinal,
    PCHAR pszOrigSymbol,
    PCHAR pszSymbol,
    PCHAR *ppszOutSymbol
    );

Parameters

pContext
Umodified program specific context pointer passed as pContext argument to DetourBinaryEditImports.
nOrigOrdinal
Import ordinal listed in original import table.
nOrdinal
Import ordinal listed in current import table.
pnOutOrdinal
Pointer to output desired import ordinal.
pszOrigSymbol
Import symbol listed in original import table.
pszSymbol
Import symbol listed in current import table.
ppszOutSymbol
Pointer to output desire import symbol.

Return value

TRUE to continue editing import table or FALSE to abort.


DetourBinaryEnumeratePayloads

Enumerate the payloads in a binary.

Definition

PVOID DetourBinaryEnumeratePayloads(
    PDETOUR_BINARY pBinary,
    GUID * pGuid,
    DWORD * pcbData,
    DWORD * pnIterator
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen .
pGuid
Pointer to the variable to receive the GUID of the next payload.
pcbData
Poiunter to the Variable to receive the size in bytes of the next payload.
pnIterator
Enumeration variable. Should be set to zero to start enumeration. The enumeration variable should not be modified between successive calls to this function.

Remarks

DetourBinaryEnumeratePayloads enumerates all of the payloads in a binary opened by DetourBinaryOpen .

For more information on binary editing with Detours and paylods, see Payloads and DLL Import Editing in the Detours Overview.

Return value

If successful, returns a pointer to the next payload; otherwise, returns NULL.


DetourBinaryFindPayload

Find a payload within a binary.

Definition

PVOID DetourBinaryFindPayload(
    PDETOUR_BINARY pBinary,
    REFGUID rguid,
    DWORD * pcbData
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen .
rguid
GUID of the specified payload.
pcbData
Pointer to the variable that receives the size of the specified payload in bytes.

Remarks

DetourBinaryFindPayloadFinds a specific payload within a binary opened by DetourBinaryOpen.

For more information on binary editing with Detours and paylods, see Payloads and DLL Import Editing in the Detours Overview.

Return value

If successful, returns TRUE; otherwise, returns FALSE.


DetourBinaryOpen

Read the contents of a binary into memory for editing.

Definition

PDETOUR_BINARY DetourBinaryOpen(
    HANDLE hFile
    );

Parameters

hFile
The handle of the binary to be opened for editing.

Return value

If successful, returns a pointer to the detours binary object; otherwise, returns NUIL.

Error codes

The function sets the following error code, if appropriate. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_OUT_OF_MEMORY
Not enough memory to complete the operation.

Remarks

DetourBinaryOpen reads the contents of a Windows PE COFF binary into memory for editing.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Related Samples

Dumpi, Impmunge, Setdll.


DetourBinaryPurgePayloads

Remove all payloads from a binary.

Definition

BOOL DetourBinaryPurgePayloads(
    PDETOUR_BINARY pBinary
    );

Parameters

pBinary
Pointer to binary, opened by DetourBinaryOpen, to be purged.

Remarks

DetourBinaryPurgePayloadsRemoves all payloads from a binary opened by DetourBinaryOpen.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Return value

If successful, returns TRUE; otherwise, returns FALSE.


DetourBinaryResetImports

Remove all edits by Detours of the binary's import table.

Definition

BOOL DetourBinaryResetImports(
    PDETOUR_BINARY pBinary
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen.

Return value

If successful, returns TRUE; otherwise, returns FALSE.

Remarks

DetourBinaryResetImportsRemoves all Detours edits made to the import table of a binary opened by DetourBinaryOpen.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Related Samples

Setdll.


DetourBinarySetPayload

Attach a payload to a binary.

Definition

PVOID DetourBinarySetPayload(
    PDETOUR_BINARY pBinary,
    REFGUID rguid,
    PVOID pData,
    DWORD cbData
    );

Parameters

pBinary
Pointer to the binary opened by DetourBinaryOpen
rguid
GUID of the payload to be added to binary.
pData
Pointer to payload data.
cbData
Size of the payload data in bytes.

Remarks

DetourBinarySetPayload attaches a payload to a binary opened by DetourBinaryOpen. The payload can be located at runtime using the DetourFindPayload API.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Return value

If successful, returns TRUE; otherwise, returns FALSE.


DetourBinaryWrite

Write an updated binary to a file.

Definition

BOOL DetourBinaryWrite(
    PDETOUR_BINARY pBinary,
    HANDLE hFile
    );

Parameters

pBinary
Pointer to the binary to be written to a file.
hFile
Handle of the file to receive the contents of the binary.

Return value

If successful, returns TRUE; otherwise, returns FALSE.

Remarks

DetourBinaryWrite writes the updated binary, opened by DetourBinaryOpen, to a file.

For more information on binary editing with Detours, see Payloads and DLL Import Editing in the Detours Overview.

Related Samples

Impmunge, Setdll.


DetourCodeFromPointer

Return a pointer to the code that implements a function pointer.

Definition

PVOID DetourCodeFromPointer(
    PVOID pPointer,
    PVOID *ppGlobals
    );

Parameters

pPointer
Pointer to the function.
ppGlobals
Variable to receive the address of the function's globals data.

Return value

Returns a pointer to the code implementing the function.

Remarks

DetourCodeFromPointer returns a pointer to the code that implements a function pointed to by a function pointer. When a binary is statically linked against a DLL, pointers to functions from the DLL often point not to the code from the DLL, but to a jump statement in the binary's import table. DetourCodeFromPointer returns the address of the actual target function, not the jump statement.

On some platforms, function pointer point to indirection labels, not code. On these platforms, the indirection labels also contains a pointer to the global (or static) data associated with the function.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Slept.


DetourCopyPayloadToProcess

Copy a payload into a target process.

Definition

BOOL DetourCopyPayloadToProcess(
    HANDLE hProcess,
    REFGUID rguid,
    PVOID pvData,
    DWORD cbData
    );

Parameters

hProcess
Process into which payload should be copied.
rguid
GUID of the specified payload.
pvData
Pointer to payload data.
pcbData
Size in bytes of payload data.

Return value

Returns TRUE if the payload was successfully copied to the target process.

Error codes

On failure, DetourCopyPayloadToProcess will return FALSE. Extended error code information may be retrieved by calling GetLastError.

Remarks

DetourCopyPayloadToProcess allocated a region of memory in the target process using the VirtualAllocEx API. It then uses the WriteProcessMemory API to create an artificial PE binary module in the target memory. In the artificial module, DetourCopyPayloadToProcess creates a .detours section with the specified payload data.

Code in the target process can find the payload by enumerating through all modules using the DetourEnumerateModules API and querying each module for the payload using the DetourFindPayload API.

Related Samples

WithDll.


DetourCreateProcessWithDll

Create a new process and load a DLL into it..

Definition

BOOL DetourCreateProcessWithDll(
    LPCTSTR lpApplicationName,
    LPTSTR lpCommandLine,
    LPSECURITY_ATTRIBUTES lpProcessAttributes,
    LPSECURITY_ATTRIBUTES lpThreadAttributes,
    BOOL bInheritHandles,
    DWORD dwCreationFlags,
    LPVOID lpEnvironment,
    LPCTSTR lpCurrentDirectory,
    LPSTARTUPINFOW lpStartupInfo,
    LPPROCESS_INFORMATION lpProcessInformation,
    LPCSTR lpDetouredDllPath,
    LPCSTR lpDllName,
    PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW
    );

Parameters

lpApplicationName
Application name as defined for CreateProcess API.
lpCommandLine
Command line as defined for CreateProcess API.
lpProcessAttributes
Process attributes as defined for CreateProcess API.
lpThreadAttributes
Thread attributes as defined for CreateProcess API.
bInheritHandles
Inherit handle flags as defined for CreateProcess API.
dwCreationFlags
Creation flags as defined for CreateProcess API.
lpEnvironment
Process environment variables as defined for CreateProcess API.
lpCurrentDirectory
Process current directory as defined for CreateProcess API.
lpStartupInfo
Process startup information as defined for CreateProcess API.
lpProcessInformation
Process handle information as defined for CreateProcess API.
lpDetouredDllPath
Pathname of the detoured.dll marker library.
lpDllName
Pathname of the DLL to be insert into the new process.
pfCreateProcessW
Pointer to program specific replacement for the CreateProcess API, or NULL if the standard CreateProcess API should be used to create the new process.

Return value

Returns TRUE if the new process was created; otherwise returns FALSE.

Error codes

See error code returned from CreateProcess.

Remarks

DetourCreateProcessWithDll creates a new process with the specified DLL inserted into it.

The process is created in a suspended state with the CREATE_SUSPENDED flag to CreateProcess. Detours then modifies the image of the application binary in the new process to include the specified DLL as its first import. Execution in the process is then resumed. When execution resumes, the Windows process loader will first load the target DLL and then any other DLLs in the application's import table, before calling the application entry point.

DetourCreateProcessWithDll modifies the in-memory import table of the target PE binary program in the new process it creates. The updated import table will contain a reference to function ordinal #1 exported from the target DLL.

Note: The new process will fail to start if the target DLL does not contain a exported function with ordinal #1.

After the target DLL has been loaded, it can reverse changes to the in-memory import table by calling DetourRestoreAfterWith. To facilitate reversing these changes, DetourCreateProcessWithDll copies relevant reversal data into a payload in the target process using the DetourCopyPayloadToProcess API. The loaded DLL can then use the DetourRestoreAfterWith API to restores the contents of the import table.

To tag the target process as modified using Detours, the detoured.dll marker library must be loaded into the process as well. Its pathame must be specified using the lpDetouredDllPath argument. If lpDetouredDllPath is NULL, DetourCreateProcessWithDll will let the process loader locate detoured.dll.

The DetourGetDetouredMarker API can be used to locate path of the same detoured.dll library that was loaded into the current process.

Related Samples

Tracemem, Tracereg, Traceser, Withdll.


DetourDetach

Detach a detour from a target function.

Definition

LONG DetourDetach(
    PVOID * ppPointer,
    PVOID pDetour
    );

Parameters

ppPointer
Pointer to the target pointer from which the detour will be detached.
pDetour
Pointer to the detour function.

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_INVALID_BLOCK
The function to be detached was too small to be detoured.
ERROR_INVALID_HANDLE
The ppPointer parameter is null or references a null address.
ERROR_INVALID_OPERATION
No pending transaction exists.
ERROR_NOT_ENOUGH_MEMORY
Not enough memory to complete the operation.

Remarks

DetourDetach detaches a detour from a target function as part of the current transaction opened by the DetourTransactionBegin API.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Commem, Cping, FindFunc, Member, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


DetourEnumerateExports

Enumerate exports from a module.

Definition

BOOL DetourEnumerateExports(
    HMODULE hModule,
    PVOID pContext,
    PF_DETOUR_ENUMERATE_EXPORT_CALLBACK pfExport
    );

Parameters

hModule
The handle to the module whose exports are to be enumerated.
pContext
Program specific context that will be passed to pfExport.
pfExport
Callback function to be called once per symbol exported from module.

Return value

TRUE if module exports are enumerated; otherwise FALSE.

Error codes

The function sets one of the following error codes, as appropriate. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_BAD_EXE_FORMAT
The MZ header of specified module is invalid.
ERROR_EXE_MARKED_INVALID
The NT COFF header of the specified module is invalid.
ERROR_INVALID_EXE_SIGNATURE
The NT COFF header of the specified module has an invalid signature.

Related Samples

Disas, Dumpe, Disas, Einst, Tracelnk, Tracereg.


PF_DETOUR_ENUMERATE_EXPORT_CALLBACK

Pointer to function called once for each export enumerated by DetourEnumerateExports.

Definition

BOOL EnumerateExportCallback(
    PVOID pContext,
    ULONG nOrdinal,
    PCHAR pszName,
    PVOID pCode
    );

Parameters

pContext
Umodified program specific context pointer passed as pContext argument to DetourEnumerateExports.
nOrdinal
Ordinal of export function.
pszName
Name of export function.
pCode

Return value

TRUE to continue enumeration of export symbols or FALSE to abort enumeration.


DetourEnumerateModules

Enumerate the PE binaries in a process.

Definition

HMODULE DetourEnumerateModules(
    HMODULE hModuleLast
    );

Parameters

hModuleLast
The handle of the last module enumerated. Pass NULL to start enumeration for the beginning of the process.

Return value

Handle to the next module loaded in a process.

Remarks

DetourEnumerateModules enumerates all of the PE binaries loaded into a process. Once a module has been enumerated, its entry point can be located with the DetourGetEntryPoint API, its exports can be enumerated with the DetourEnumerateExports API, and its payloads can be found using the DetourFindPayload API.

Related Samples

Disas, Einst, Tracelnk, Tracereg.


DetourFindFunction

Find the address of a target function by name.

Definition

PVOID DetourFindFunction(
    PCHAR pszModule,
    PCHAR pszFunction
    );

Parameters

pszModule
The path of the DLL or binary in which the function should be found.
pszFunction
The name of the function to be found.

Return value

If successful, returns the address of the function pszFunction; otherwise, returns NULL.

Remarks

DetourFindFunction tries to retrieve a function pointer for a named function through the dynamic linking export tables of the named module and then, if that fails, through debugging symbols using the DbgHelp APIs if available.

DetourFindFunction uses the DbgHelp APIs to access debug symbols. It dynamically links to the DbgHelp APIs by dynamically loading DBGHELP.DLL.

If your program can't find debug symbols that you know are available, the most likely cause is that system either can't find DBGHELP.DLL or the version of DBGHELP.DLL loaded by the system is broken. This can happen on 64-bit machines (X64 and IA64) where the system will often load a 32-bit version of DBGHELP.DLL even though you have written 64-bit code. Some 32-bit versions of Windows also included a non-functional DBGHELP.DLL stub.

You can test your version of DBGHELP.DLL by using the SymTest program from the FindFunc. directory..

Related Samples

Cping, Excep. FindFunc.


DetourFindPayload

Return the address of the specified payload within a module.

Definition

PVOID DetourFindPayload(
    HMODULE hModule,
    REFGUID rguid,
    DWORD * pcbData
    );

Parameters

hModule
Module holding the payload specified payload.
rguid
GUID of the specified payload.
pcbData
Variable to receive the size in bytes of the specified payload.

Return value

Pointer to the specified payload or NULL if the payload doesn't exist.

Error codes

The function sets one of the following error codes if it was unable to search the module for the target payload. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_BAD_EXE_FORMAT
The MZ header of specified module is invalid.
ERROR_EXE_MARKED_INVALID
The NT COFF header of the specified module is invalid.
ERROR_INVALID_EXE_SIGNATURE
The NT COFF header of the specified module has an invalid signature.

Remarks

DetourFindPayload returns the address of the specified payload within a module. Payloads can either be created at compile link time, see the Einst, or can be inserted it an existing binary using the DetourBinarySetPayload API.

For more information on binary editing with Detours and paylods, see Payloads and DLL Import Editing in the Detours Overview.

Related Samples

Einst.


DetourGetDetouredMarker

Returns the handle of detoured.dll, the DLL loaded to mark this process as detoured.

Definition

HMODULE DetourGetDetouredMarker();

Return value

Returns the HMODULE of detoured.dll in the current process.

Remarks

Detours loads the detoured.dll shared library stub into any process which has been modified by the insertion of a detour. This allows the Microsoft Customer Support Services (CSS) and the Microsoft Online Crash Analysis (OCA) teams to quickly and accurately determine that the behavior of a process has been altered by a detour. CSS does not provide customer assistance on detoured products from Microsoft or any other vendor.

Programs using the DetourCreateProcessWithDll API must provide the path location of the detoured.dll library. It can be located using the DetouredGetDetouredMarker API.

Related Samples

Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp. Withdll,


DetourGetEntryPoint

Return the entry point for a module..

Definition

PVOID DetourGetEntryPoint(
    HMODULE hModule
    );

Parameters

hModule
The handle of the module to which the entry point is desired.

Return value

Returns the entry point for the module, if found; otherwise, returns NULL.

Error codes

The function sets one of the following error codes, as appropriate. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_BAD_EXE_FORMAT
The MZ header of specified module is invalid.
ERROR_EXE_MARKED_INVALID
The NT COFF header of the specified module is invalid.
ERROR_INVALID_EXE_SIGNATURE
The NT COFF header of the specified module has an invalid signature.

Remarks

DetourGetEntryPoint returns the entry point for a module. For a .EXE file, the entry point is the start of the code for the main or runtime startup runtimes. For a .DLL file, the entry point is the start of the code for the DllMain function.

The Slept sample shows how to capture program execution after DLL initialization by detouring the entry point of a program.

Related Samples

Disas, Dumpe, Dumpe, Slept.


DetourGetModuleSize

Return the load size of a module.

Definition

ULONG DetourGetModuleSize(
    HMODULE hModule
    );

Parameters

hModule
The handle to the module whose load size is desired.

Return value

Returns the size of the module in bytes, if it can be determined; otherwise, returns 0.

Error codes

The function sets one of the following error codes, as appropriate. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_BAD_EXE_FORMAT
The MZ header of specified module is invalid.
ERROR_EXE_MARKED_INVALID
The NT COFF header of the specified module is invalid.
ERROR_INVALID_EXE_SIGNATURE
The NT COFF header of the specified module has an invalid signature.

Related Samples

Disas.


DetourGetSizeOfPayloads

Return the size of all payloads within a module.

Definition

DWORD DetourGetSizeOfPayloads(
    HMODULE hModule
    );

Parameters

hModule
The module for which the size of the payloads is to be returned.

Return value

If successful, returns the size in bytes of the payloads within a module; otherwise, returns zero.

Error codes

The function sets one of the following error codes, as appropriate. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_INVALID_HANDLE
The module handle was invalid.

Related Samples

Einst.


DetourRestoreAfterWith

Restore the contents in memory import table after a process was started with DetourCreateProcessWithDll .

Definition

BOOL DetourRestoreAfterWith();

Return value

Returns true if the necessary payload was found and the restore succeeded.

Error codes

The function sets one of the following error codes if it was unable to find the necessary payload or restore the import table. The error code may be retrived after the function has returned by calling GetLastError.

ERROR_MOD_NOT_FOUND
Could not find the necessary payload.

Remarks

The DetourCreateProcessWithDll API modifies the in-memory import table of the target PE binary program in the new process it creates. Under some circumstances, it is desirable to reverse these changes after the process has been created, but before the target program runs. To facilitate reversing these changes, DetourCreateProcessWithDll copies relevant reversal data into a payload in the target process using the DetourCopyPayloadToProcess API. When called in the target process, DetourRestoreAfterWith searches for the necessary payloaded and restores the contents of the import table.

For optimal results, DetourRestoreAfterWith should be called in the PROCESS_ATTACH portion of the DllMain function of the DLL loaded into the target process.

Related Samples

Simple, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


DetourSetIgnoreTooSmall

Enable or disable transaction abort on a failure to attach or detach an individual detour function.

Definition

VOID DetourSetIgnoreTooSmall(
    BOOL fIgnore
    );

Parameters

fIgnore
Specifies whether to ignore functions that are too small to detour. If this parameter is set to TRUE, these functions will be ignored if encountered. If this parameter is set to FALSE, then encountering a function too small to be detoured will cause DetourTransactionCommit to fail.

Remarks

DetourSetIgnoreTooSmall sets the flag to determine if failure to detour a target function that is too small for detouring is sufficient error to cause abort of the current detour transaction.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Traceapi.


DetourTransactionAbort

Abort the current transaction.

Definition

LONG DetourTransactionAbort();

Return value

Returns NO_ERROR if the pending transaction was completely aborted; otherwise, returns an error code.

Error codes

ERROR_INVALID_OPERATION
No pending transaction exists.

Remarks

DetourTransactionAbort aborts the current transaction created with DetourTransactionBegin. Aborting a transaction reverse the effects of any calls to the DetourAttach, DetourAttachEx, DetourDetach, or DetourUpdateThread APIs made within the transaction.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.


DetourTransactionBegin

Begin a new transaction for attaching or detaching detours.

Definition

LONG DetourTransactionBegin();

Return value

Returns NO_ERROR if successful; otherwise returns ERROR_INVALID_OPERATION.

Error codes

ERROR_INVALID_OPERATION
A pending transaction alrady exists.

Remarks

DetourTransactionBegin begins a new transaction for attaching or detaching detours.

After beginning a transaction, a program calls the DetourAttach or DetourAttachEx API to attach a detour to a target function, calls the DetourDetach API to detach a detour from a target function, or calls the DetourUpdateThread API to include include a thread in the transaction update.

The attach, detach, and thread operations do not take effect until the program commits the transaction using the DetourTransactionCommit or DetourTransactionCommitEx API. Alternatively, the program can abort the transaction using the DetourTransactionAbort API.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Commem, Cping, Dtest, Excep, FindFunc, Member, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


DetourTransactionCommit

Commit the current transaction.

Definition

LONG DetourTransactionCommit();

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_INVALID_DATA
Target function was changed by third party between steps of the transaction.
ERROR_INVALID_OPERATION
No pending transaction exists.
Other
Error code returned by API within DetourAttach, DetourAttachEx, or DetourDetach that caused transaction to fail.

Remarks

DetourTransactionCommit commits the current transaction created with DetourTransactionBegin. Commiting a transaction make all updates specified in any calls to the DetourAttach, DetourAttachEx, DetourDetach, or DetourUpdateThread APIs within the transaction.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Commem, Cping, Dtest, Excep, FindFunc, Member, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


DetourTransactionCommitEx

Commit the current transaction.

Definition

LONG DetourTransactionCommitEx(
    PVOID ** pppFailedPointer
    );

Parameters

pppFailedPointer
Variable to receive the target pointer passed to the DetourAttach, DetourAttachEx, or DetourDetach call that caused the latest transaction to fail.

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_INVALID_DATA
Target function was changed by third party before the transaction could complete.
ERROR_INVALID_OPERATION
No pending transaction exists.
Other Codes
Error code returned by API within DetourAttach, DetourAttachEx, or DetourDetach that caused transaction to fail.

Remarks

DetourTransactionCommitEx commits the current transaction created with DetourTransactionBegin. Commiting a transaction make all updates specified in any calls to the DetourAttach, DetourAttachEx, DetourDetach, or DetourUpdateThread APIs within the transaction.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Traceapi,


DetourUpdateThread

Enlist a thread for update in the current transaction.

Definition

LONG DetourUpdateThread(
    HANDLE hThread
    );

Parameters

hThread
The handle of the thread to be updated with the pending transaction.

Return value

Returns NO_ERROR if successful; otherwise, returns an error code.

Error codes

ERROR_NOT_ENOUGH_MEMORY
Not enough memory to record identity of thread.

Remarks

DetourUpdateThread enlists the specified thread for update when the current transaction, opened by the DetourTransactionBegin API, commits.

When a detour transaction commmits, Detours insures that all threads enlisted in the transcation via the DetourUpdateThread API are updated if their instruction pointer lies within the rewritten code in either the target function or the trampoline function.

Threads not enlisted in the transaction are not updated when the transaction commits. As a result, they may attempt to execute an illegal combination of old and new code.

For more information on using Detours to interception function calls, see Interception of Binary Functions or Using Detours in the Detours Overview.

Related Samples

Commem, Cping, Dtest, Excep, FindFunc, Member, Simple, Slept, Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, Tracetcp.


Samples

Building The Samples

To build the sample applications, type nmake in the samples directory. Note that you must build the setdll and syslog samples in order to use many of the other sample programs.

Each of the sample directories has a test, which can be invoked by typing nmake test, to demonstrate the usage of the sample. With very few exceptions, all of the .exe programs also accept a /? command to display a usage message.

The trace samples log their output through the syelogd.exe daemon and hook CreateProcessW to load themselves into any child processes. For example, typing withdll -d:traceapi.dll cmd.exe will create a command shell under which all processes log their API calls through traceapi.dll.

Detours includes the following samples:

  • Commem
  • Cping
  • Disas
  • Dtest
  • Dumpe
  • Dumpi
  • Einst
  • Excep
  • FindFunc
  • Impmunge
  • Member
  • Setdll
  • Simple
  • Slept
  • Syelog
  • Traceapi
  • Tracelnk
  • Tracemem
  • Tracereg
  • Traceser
  • Tracetcp
  • Withdll


Samples: Commem

Commem

Demostrates how to detour a member function of a COM interface.

Uses

DetourAttach, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Cping

Cping

Detours multiple functions in the DCOM/RPC stack to measure the overhead of sending DCOM messages.

Uses

DetourAttach, DetourFindFunction, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Disas

Disas

Tests the Detours disassembler tables.

Uses

DetourEnumerateExports, DetourEnumerateModules, DetourGetEntryPoint, DetourGetModuleSize.


Samples: Dtest

Dtest

Detours the Win32 Sleep function and a private function. The private function is first detoured, then detoured recursively 3 times using the DetourAttach API.

Uses

DetourAttach, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Dumpe

Dumpe

Dumps the list of all functions exported from a binary.

Uses

DetourEnumerateExports, DetourGetEntryPoint.


Samples: Dumpi

Dumpi

Dumps the list of all functions imported by a binary.

Uses

DetourBinaryClose, DetourBinaryEditImports, DetourBinaryOpen.


Samples: Einst

Einst

Find payloads compiled into binary files.

Uses

DetourEnumerateModules, DetourFindPayload.


Samples: Excep

Excep

Uses a first-chance exception filter to toggle VM permissions on a page; enabling writes after catching the first write to a page.

Uses

DetourAttach, DetourFindFunction, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: FindFunc

FindFunc

Demostrates how to detour a function using DetourFindFunction to find the function using debug symbols.

Uses

DetourAttach, DetourDetach, DetourFindFunction, DetourRestoreAfterWith, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Impmunge

Impmunge

Modifies all of the entries in a binary's imports table.

Uses

DetourBinaryClose, DetourBinaryEditImports, DetourBinaryOpen, DetourBinaryWrite.


Samples: Member

Member

Demostrates how to detour a class member function.

Uses

DetourAttach, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Setdll

Setdll

Add a DLL to the import table of any binary (a .DLL or .EXE for example). Use setdll.exe to attach one of the sample DLLs to an application .EXE file.

Note: The target binary will fail to load if the target DLL does not contain a exported function with ordinal #1. For more information, see the DetourBinaryEditImports API.

Related Samples

Withdll.

Uses

DetourBinaryClose, DetourBinaryEditImports, DetourBinaryOpen, DetourBinaryResetImports, DetourBinaryWrite.


Samples: Simple

Simple

Simplest example of a Detours-based DLL which modifies and adds functionality to a Windows API. Modifies the Sleep API to record the number of ticks spent sleeping.

The Simple example is described in more detail in Using Detours.

Uses

DetourAttach, DetourDetach, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Slept

Slept

More ellaborate version of the simple sample. Demonstrates detouring both static and dynamic functions. Also demonstrates how to capture program execution after DLL initialization by detouring the programs entry point.

Uses

DetourAttach, DetourCodeFromPointer, DetourDetach, DetourGetEntryPoint, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Syelog

Syelog

System event logging library and service. All of the tracing samples connect to syelogd.exe through a named pipe. Syelogd outputs tracing information to the console. You must run syelogd.exe in a seperate window in order to see the output from any of the following tracing DLLs: Traceapi, Tracelnk, Tracemem, Tracereg, Traceser, or Tracetcp.

Uses

Uses none of the Detours APIs.


Samples: Traceapi

Traceapi

Win32 API tracing sample. Detours and prints tracing statements for 1401 Win32 API functions. Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourDetach, DetourSetIgnoreTooSmall, DetourTransactionBegin, DetourTransactionCommit, DetourTransactionCommitEx, DetourUpdateThread.


Samples: Tracelnk

Tracelnk

Traces all calls to the Windows dynamic linking APIs. Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourDetach, DetourEnumerateModules, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Tracemem

Tracemem

Traces all calls to the Windows HeapAlloc API. Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourCreateProcessWithDll, DetourDetach, DetourGetDetouredMarked DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Tracereg

Tracereg

Traces activity through the registry APIs. Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourCreateProcessWithDll, DetourDetach, DetourEnumerateModules, DetourGetDetouredMarked DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Traceser

Traceser

Traces activity through the serial ports (com1 or com2). Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourCreateProcessWithDll, DetourDetach, DetourGetDetouredMarked DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Tracetcp

Tracetcp

Traces activity through WinSock TCP APIs. Output from the trace is logged to the syelogd.exe deamon.

Uses

DetourAttach, DetourDetach, DetourTransactionBegin, DetourTransactionCommit, DetourUpdateThread.


Samples: Withdll

Withdll

Demonstrates how to use the DetourCreateProcessWithDll API to load a detour DLL into a new process without modifying the target application. Calls CreateProcess and loads a named DLL into the target process. Also insures that the detoured.dll marker library is loaded into the process as well.

Note: The new process will fail to start if the target DLL does not contain a exported function with ordinal #1. For more information, see the DetourCreateProcessWithDll API.

Related Samples

Setdll.

Uses

DetourCreateProcessWithDll DetourGetDetouredMarked .


Frequently Asked Questions (FAQ)

Detours Frequently Asked Questions (FAQ)

This page contains a list of questions frequently asked about Detours. The questions are grouped by general topic and area of interest.

Compatibility

Can I use Detours with Windows 95, Windows 98, or Windows ME?

No. Detours is compatible only with the Windows NT family of operating systems: Windows NT, Windows XP, and Windows Server 2003, etc. Detours does not work on the Windows 9x family of operating systems because they have a primitive virtual memory system.

Compiling with Detours Code

How do I do thing X with Detours?

Look in the Detours Samples. The Detours Samples are quit extensive. It is likely that anything you want to accomplish with Detours is covered in one of the included samples.

Where can I find detours.lib and detours.h?

You need to build a version of detours.lib for your C/C++ compiler in the detours/src directory by typing nmake either in the detours directory or in the detours/src directory.

Running with Detours

Why don't I see any calls to my detour of malloc?

Probably because the target program is not using the malloc function you detoured.

Standard library functions like malloc can be linked with a program either statically, from one of the libc*.lib libraries, or dynamically, from one of the msvcrt*.dll libraries. When statically linked, a program receives its own private version of the standard library functions. When dynamically linked, a program shares version of the standard library functions in a DLL. If you detour your private version of the function, or if the target program uses its own private version of the function, your detour won't be called by the target program.

Why is Detours packaged as a static library (detours.lib) and not as a dynamic link library (say detours.dll)?

Packaging Detours as a statical library minimizes the risk that you will accidentally detour a function required by the Detours package itself and reduces versioning problems. Note that Detours adds only about 16KB when statically linked with your code.

Why do I need to include detoured.dll?

The detoured.dll file is a marker that guides Microsoft technical support personnel and tools, like Windows OCA, by helping them quickly determine that a process has been altered by the Detours package. Microsoft can not guarantee nor support in any way, the modification of Microsoft binaries by third parties. Nor can Microsoft support, in any way, an application that that contains Microsoft binaries that have been modified by third parties. This includes in-memory modification using the Detours package.

How can I debug the startup of my detour DLL?

The Windbg can single step or break on exceptions in process startup. Windbg is available in the "Debugging Tools for Windows" download from on www.microsoft.com. For example, you can use the command line:

windbg -o withdll.exe -d:mydll.dll myexe.exe

Licensing

Can Detours be used in commercial applications?

Yes. A commerical license for Detours is available upon request. To inquiry about acquiring a commercial license to the Detours Package, send email to Microsoft's Intellectual Property and Licensing Group at iplg@microsoft.com. Please include the text "DETOURS LICENSE REQUEST" in the subject line.

Bug Reports

How do I report a bug?

Please send detailed bug reports to detours@microsoft.com. Bug reports may be used to fix bugs in future versions of the Detours package. Please include the text "DETOURS BUG REPORT" in the subject line. Within the body of your message, please include the first line from the README.TXT file which contains the full description of the version Detours you are using.

Before submitted a bug report, please make every effort to insure that the problem is not an error in your own code or your usage of Detours. The most common sources of user error are covered in this FAQ.

The detours@microsoft.com email address is for bug reports only, it is not a product support line.