microsoft / Detours

Detours is a software package for monitoring and instrumenting API calls on Windows. It is distributed in source code form.
MIT License
5.02k stars 981 forks source link

Can Detours hook functions defined by myself??? #154

Closed hiber987 closed 3 years ago

hiber987 commented 3 years ago

Hi: I've been learning to use Detours recently, but I have a question: Can Detours hook functions defined by myself? For example, there is a function in the header file written by myself: void runcmd(const char *) If I get this header file, is it possible for me to hook this function using Detours? Thank U!

hiber987 commented 3 years ago

And my files are here! runcmd.zip

sylveon commented 3 years ago

Yes

hiber987 commented 3 years ago

Yes

Then the question is, why cannot my detour function modify the target function's execution? In my code "runcmd.zip“,although the runcmd function is successfully hooked, runcmd still executes its original process rather than following the modified process. I expect it to output: simple64.dll: Starting. simple64.dll: Detoured runCmd(). 6 + 6 = 12 Hello world Hello Detours! cmd: Hei, my brother from another mother! simple64.dll: Removed runCmd() (result=0).

However, it still outputs: simple64.dll: Starting. simple64.dll: Detoured runCmd(). Hello Detours! cmd: Hei, my brother from another mother! simple64.dll: Removed runCmd() (result=0).

Did I forget something? Could you look at the code for me? Thank U!

sylveon commented 3 years ago

The function is implemented in a header, so there are two versions of runCmd:

The .DLL is only altering its own copy of the function. Furthermore, compiler inlining might also prevent all call sites from being affected.

hiber987 commented 3 years ago

The function is implemented in a header, so there are two versions of runCmd:

  • One in the .DLL
  • One in the .exe

The .DLL is only altering its own copy of the function. Furthermore, compiler inlining might also prevent all call sites from being affected.

I changed the program. Put the implementation of runCmd in the CPP file, but this would cause the following error when generating runCmd64.dll: error LNK2001: unresolvable external symbol "void __cdecl runCmd(char const *)" (?runCmd@@..........)

My code was modified from simple.cpp in the Detours\ Sample \simple directory. But it doesn't work as well as simple.cpp. I really don't know how to fix it... Could you please change the runcmd.zip at your convenience? It's really too hard for a person who is new to Detours to understand. Thank U!

bgianfo commented 3 years ago

@hiber987 do you still need help here? Or can this be closed?

bgianfo commented 3 years ago

closing this after no response