Menooker / PFishHook

An x64 inline hook library
Apache License 2.0
30 stars 10 forks source link

refine mem allocator #6

Closed ghost closed 5 years ago

ghost commented 5 years ago

1.use a simpler allocator which uses mmap to search a proper place to allocate MemChunk(instead of read /proc/self/maps to guess the free address space) 2.use jmp addr64 to replace (push addr;ret;) ,which improves performance

Menooker commented 5 years ago

I have an unrelated question: I am considering the compatibility of this library with Windows. If I port this library to Windows, will it be more useful for you? :)

ghost commented 5 years ago

I have an unrelated question: I am considering the compatibility of this library with Windows. If I port this library to Windows, will it be more useful for you? :)

That's kind of you :D,but I'm not going to develop programs on Windows. Thanks,anyway.

ghost commented 5 years ago
inline int isHooked(void* oldfunc){
    return memcmp(oldfunc,"\xff\x25\x00\x00\x00\x00",6)==0;
}
HookStatus DupHook(void* oldfunc, void** poutold, void* newfunc){
    char* fc=AllocFunc(14,nullptr);
    memcpy(fc,oldfunc,14);
    *poutold=fc;
    if(rangeProtect(oldfunc,14,1)!=FHSuccess) return FHMprotectFail;
    memcpy((char*)oldfunc+6,&newfunc,8);
    if(rangeProtect(oldfunc,14,0)!=FHSuccess) return FHMprotectFail;
    return FHSuccess;
}
HookStatus HookIt(void* oldfunc, void** poutold, void* newfunc)
{
    if(isHooked(oldfunc)){
        return DupHook(oldfunc,poutold,newfunc);
    }

seems that HookIt cannot process "jmp qword ptr [rip];.QWORD".Hook a function twice will cause unexpected behavior

Menooker commented 5 years ago

Please view my comments, and maybe polish the code. Thanks a lot!

ghost commented 5 years ago

I think patch instructions which use rip-relative jump,and make sure the instructions which use rip-relative memory read/write have the correct memory address is enough. For example,jmp rip+0x18 should be patched to jmp rip+xxx,but jmp qword ptr [rip+0] should not be patched.copy the next qword to shadow function is a good choice. This means if we meet a instruction needs the memory at [oldfunc,oldfunc+14],we shouldn't patch the rip-offset.Instead,copy it directly,and also copy the memory it accesses

Menooker commented 5 years ago

I think you are right. we should patch rip+0 as a special case