很多时候我们需要帮助客户改变应用程序跟操作系统或其它SDK的交互方式。这种任务通常需要涉及到源代码。很多情况下虽然是自己的程序,但或许也有一部分的模块没有源代码。  幸运的是,微软研究院的一个团队研发出了Detours SDK用于解决这些问题。 简单的说,Detours 允许你创建一个dll用于hook到系统的其它函数中,在被hook了的函数被调用时就会转到去调用你实现的那个函数。

 

整个流程很简单:

 

·        下载 detours SDK http://research.microsoft.com/sn/detours/  然后建立工程。

·         你可以用 Visual Studio 命令行的方式编译里面的一个"simple"示例代码工程。

·        创建一个你需要hook的目标API函数原型指针。这个函数指针必须跟需要hook的API函数的参数和返回类型一致,否则会就会出问题。把这个函数指针指向需要hook的API函数地址。在接下来的示例中,将以hook系统API函数 CreateFile为例来说明使用方法。

·         你需要实现你自己的API函数相关功能来代替被你hook了的API函数功能。在这个示例中,我们将实现一个我们自己的ModifyCreateFile函数,这个函数里面将直接调用reateFile,仅仅修改一下调用参数而已。

 

static HANDLE (WINAPI * TrueCreateFile)(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) = CreateFile;

 

HANDLE WINAPI ModifyCreateFile(LPCTSTR lpFileName,  DWORD dwDesiredAccess, DWORD dwShareMode,

    LPSECURITY_ATTRIBUTES   lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)

{

    dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH;

    return TrueCreateFile(lpFileName, dwDesiredAccess,  dwShareMode, lpSecurityAttributes, 

           dwCreationDisposition,      dwFlagsAndAttributes,  hTemplateFile);     

}

 

·         你需要在你的dll的dllmain函数里调用相关的Detours库函数。  这些函数将在Dll 载人事件 DLL_PROCESS_ATTACH中被执行。在调用DetourAttach函数中,我们传入实际的API地址和我们自己实现的代替API那个函数的地址。剩下的事就由Detours SDK处理了。

        DetourRestoreAfterWith();

        DetourTransactionBegin();

        DetourUpdateThread(GetCurrentThread());

        DetourAttach(&(PVOID&)TrueCreateFile, ModifyCreateFile);

        DetourTransactionCommit();

 

·         When the DLL_PROCESS_DETACH happens you will need to clean up the detour and unhook the real API.

 

        DetourTransactionBegin();

        DetourUpdateThread(GetCurrentThread());

        DetourDetach(&(PVOID&)TrueCreateFile, ModifyCreateFile);

        DetourTransactionCommit();

 

      总之,detours就是这么简单。