Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


[C++][ASM] Detouring with thiscall hook

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming
View previous topic :: View next topic  
Author Message
atomen
How do I cheat?
Reputation: 0

Joined: 29 Jun 2009
Posts: 3

PostPosted: Fri May 04, 2012 2:34 am    Post subject: [C++][ASM] Detouring with thiscall hook Reply with quote

Hi!

NOTE: Before reading, everything is on linux with GCC calling conventions, that
means no push to the ecx registry for thiscalls and etc.

I've been programming detours the two past days and everything has gone smooth, but I
want to turn it up a notch! My detour implementation is complete (i.e it has a trampoline,
patcher/unpatcher, the usual goodies) except one thing, object orientation.

I'm a C++ person, I never use global functions/variables and I enclose everything in classes.
This becomes a problem with my current 'hooker' because it doesn't support _thiscall as
callbacks. So to be clear; I can hook _thiscalls but I can't use them as callbacks, basically,
because I don't know how.

My implementation is just like any other, you replace the first 5 bytes. Offset zero is replaced
with JMP (0xE9) and the rest with an address (4 bytes). Now if you take that into consideration,
how would I require to modify my implementation to enable class methods as 'callback' hooks?

I haven't succeeded with anything yet (though I haven't been testing either). I guess it wouldn't be
so easy as to just use the 'push' operator before my jump, to insert my 'this' pointer on the stack?

Just to illustrate; my current implementation:
Code:
int test(int x, int y) { return x + y; }
int hookTest(int x, int y) { return x - y; }

int main(int argc, char * argv[])
{
   Patch((void*) &test, (void*) &hookTest);
}
What I'm trying to achieve:
Code:

int test(int x, int y) { return x+ y; }
class Hook
{
public:
   MyHook(int x, int y) { return x - y; }
   Patch(void * addr);
}

int main(int argc, char * argv[])
{
   Hook hook;
   hook.Patch((void*) &test); // <-- This makes the hook routed to my member function 'MyHook'
}

Before I attempt to solve my problem, I'd like to know how everything should work in thoery,
so please share any ideas that might help me find a solution/method to make this work!
Back to top
View user's profile Send private message
661089799107
Expert Cheater
Reputation: 3

Joined: 25 Jan 2009
Posts: 186

PostPosted: Fri May 04, 2012 4:22 am    Post subject: Reply with quote

I'm pretty sure you have to make your callback static.

Also instead of using ECX you just push the object pointer as the first argument.
Back to top
View user's profile Send private message
atomen
How do I cheat?
Reputation: 0

Joined: 29 Jun 2009
Posts: 3

PostPosted: Fri May 04, 2012 6:08 am    Post subject: Reply with quote

Blacknight wrote:
I'm pretty sure you have to make your callback static.

Also instead of using ECX you just push the object pointer as the first argument.

I thought so (or well, it's not impossible, but I don't know any way to implement it 'stably'
and efficiently without taking up way too much memory).

If I have to implement a static callback, do you have any idea how I could 'handle'
these callbacks dynamically? For example; right now I'm programming plugins to a game
which only offers a C API. Because of this I have _tons_ of different static callback events,
and if I'm forced to have an additional ~20 for all the 'hooks' it would surely become a
nightmare...

I was thinking if it would be possible to somehow detect the calling function (and having
the hook as a completely 'dynamic' function, such as: void * HookCallbackPre/Post(...))
which could then (by assembly) send these to the corresponding member methods?

To illustrate; I have a generic callback function (static) which somehow finds out where
the call came from (to identify the caller):
Code:

MyMainClass mainClass; // <-- Global object which the static function have access to

class MyMainClass
{
   // Static callback hook
   static void * HookCallback(...);

   // Non static functions
   void Func1(int arg1, float arg2);
   int Func2(const char * str);

   std::map<uint, void*> m_callbacks;
};

void * MyMainClass::HookCallback(...)
{
   // Somehow I identify the caller
   // which then has a corresponding
   // callback in a global/static vector
   // or std::map for all callback functions
   void * sendAddr = "find out calling func";

   void * targetCb = m_callbacks[reinterpret_cast<uint>(sendAddr)];

   // Here all the arguments are looped, one by
   // one, pushed to the stack (perhaps va_args or something similiar?)
   for(int i = 0; i < 'arguments'; i++)
      asm volatile("push %0;" : : "r"(arguments[i]));

   // Return value
   void * retVal;

   // Calls the callback function
   asm( "push %2;"            // <-- The this pointer
      "call *%1;"            // <-- Callback method address
      "movl %%ebx, %0;"         // <-- Return value
      : "=r"(retVal)
      : "a"(targetCb), "b"(&mainClass)
      : "eax", "ebx");

   // Return, and clean up stack
   asm(...);
   return retVal;
}

// Implementation of my non-static methods below
// ................
// .........

Now this code above is all just in theory, but would it work? I mean, since everything is based around
the cdecl convention (even _thiscalls since it's GCC) which can take a variadic amount of arguments,
wouldn't this implementation be possible?

The reason I ask is because I don't want to implement this huge amount of code, without being
ensured that it will actually work. I would love an implementation like this for it's simplicity and
"some-what" object-oriented implementation.

Please comment any thoughts!
Back to top
View user's profile Send private message
Dark Byte
Site Admin
Reputation: 470

Joined: 09 May 2003
Posts: 25805
Location: The netherlands

PostPosted: Fri May 04, 2012 8:17 am    Post subject: Reply with quote

On gcc _thiscall is basically a cdecl with the first parameter the "this" pointer


so let's say you want to hook a class that looks like this:
Code:

class CSomeClass
{
   void Func1(int arg1, float arg2);
   int Func2(const char * str);
};


In actuality, the generated functions will be:
void Func1(CSomeClass *this, int arg1, float arg2);
int Func2(CSomeClass *this, const char * str);

So, if you find the address of Func1, let it redirect to a function that looks like this:
Code:

void Func1(CSomeClass *this, int arg1, float arg2)
{
  this->Func2("bla"); //just because you can (assuming your header is 100% correct, else use UnhookedFunction2(this,"bla")
  UnhookedFunction1(this, arg1, arg2);   
}

_________________
Do not ask me about online cheats. I don't know any and wont help finding them.

Like my help? Join me on Patreon so i can keep helping
Back to top
View user's profile Send private message MSN Messenger
atomen
How do I cheat?
Reputation: 0

Joined: 29 Jun 2009
Posts: 3

PostPosted: Fri May 04, 2012 8:47 am    Post subject: Reply with quote

Dark Byte wrote:
On gcc _thiscall is basically a cdecl with the first parameter the "this" pointer


so let's say you want to hook a class that looks like this:
Code:

class CSomeClass
{
   void Func1(int arg1, float arg2);
   int Func2(const char * str);
};


In actuality, the generated functions will be:
void Func1(CSomeClass *this, int arg1, float arg2);
int Func2(CSomeClass *this, const char * str);

So, if you find the address of Func1, let it redirect to a function that looks like this:
Code:

void Func1(CSomeClass *this, int arg1, float arg2)
{
  this->Func2("bla"); //just because you can (assuming your header is 100% correct, else use UnhookedFunction2(this,"bla")
  UnhookedFunction1(this, arg1, arg2);   
}
You didn't quite seem to understand what I wanted. I'm fully aware of how the thiscall
convention works under GCC and I have had no problems implementing it. What I wanted was the hook,
my hook, to be a method in my own class. So that "Func1" that you defined, a.k.a the hook, is what I want
wrapped as an method in my class. So the problem is not how to hook other classes _thiscalls, but to direct
the callbacks to a hook which is a method of my own class.
Code:

void ___MYCLASS___::Func1(CSomeClass *this, int arg1, float arg2)
{
  this->Func2("bla"); //just because you can (assuming your header is 100% correct, else use UnhookedFunction2(this,"bla")
  UnhookedFunction1(this, arg1, arg2);   
}
So the problem is; I want a single static hook function in my class, which redirects
all the calls to the corresponding member method, dynamically. But I'm open to other solutions,
as long as I can communicate easily with my class object, without having to abuse tons of static functions
and global variables.

Double Posts combined: ----------------------------------------------------------------------------------------

Wow! I might just have had a major breakthrough! I understand now that one single static function
won't be enough. Since the functions need to be 'customized' for each hook (i.e they need to
jump back to the original function), it would be more or less impossible since the function
would be required to change for each different call.

What I discovered was how easy (or well, achievable) this is with assembly. With assembly I
can create something awesome! Since I know all the functions I want to hook at runtime (their
arguments and return values) I should be able to create a 'Function' class. This function class
takes a variadic amount of arguments in its constructor, wherein you would specify each arguments
size (for example bool is 1 byte) and if it's a plain value or a pointer/reference. I could then
allocate the required memory for this function (malloc/new) and then by using C++ memory techniques,
create my function directly in memory (by setting assembly operators through pointers/memset,
for example; 0xE9 is jump).

In the end, I would have a fully dynamic implementation which would easily offer support for
class methods as callbacks (just push an additional pointer, that's all). What do you think? Smile
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites