Easyhook tipps and tricks

I wanted to hook the WinApi funktion CreateFile, CloseHandle, ReadFile and WriteFile to decode a device protocol. So I searched for a hooking library in the internet. Unfortunately the only good one for c++ was detour from Mircrosoft which was free only for x86 non comercial use. As my laptop runs with a x64 Windows Vista this was no option for me. So I found easyhook, a c# hooking library. It was quite easy to achive the first success with it, but then I had a few small problems for which I want to describe the solutions here.

Lets asume you want to hook a function which easy hook which executes some hooking code before and after the original call:

You will notice that the code after the original call never gets executed. This is because the DllImport gives you the already hooked function. So you are calling the hooked function from the hooked function. This is prevented by the easyhook lib, by returning the flow to the calling program. (which is a very good thing, because it would lead to a infinite loop)
To avoid this behaviour you have to get the unhooked function from the easyhook library.

And in the run method of your injected dll right after installing the hooks.

Now your code after the original api call gets executed!

The second problem I encounterd was on hooking WriteFile:

On every WriteFile call I got a exception in the loop for i=1, because if the call comes from a unmanaged app the byte array has no size and therefore the size 1 is assumed.
To fix the problem one has to use the marshal class and change all the byte arrays to pointers.

Now the hook works. The same works for hooking ReadFile but after calling the original function (also use tipp 1!)

For hooking I simply changed the FileMonInject example the source can be downloaded here:
C# Source