Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking C++ Methods on OSX?

I am injecting a dylib in some application for some desired behavior.

I am able to hook flat C APIs properly. Once I inject the dylib, I look out in symbol table and update its entry with my function address and in turn call the original one.

Thus, symbol names becomes important to me.

My problem is with C++ name mangling. How can we hook a C++ function whose name have been mangled. I read some places on stack overflow, that its possible to hook c++ code with mach_override, but no example or references.

Can some give me example on how to achieve hooking of C++?

Edit: I used $ c++filt -n _ZN10WindowData12GetCGContextEv as a example and got the out put as WindowData::GetCGContext()

  1. Is WindowData a class or namespace?
  2. How can I hook it? I ma need some forward declarations and externs to use WindowData::GetCGContext() properly for hooking.

Something like this...

typedef void* (*WindowData_GetCGContextProcPtr)(void* inObj);
static WindowData_GetCGContextProcPtr gWindowDataGetCGContextProcPtr = NULL;
void*  try_WindowDataGetCGContextProcPtr(void* inObj)
{
    printf("try_WindowDataGetCGContextProcPtr \n");

    return gWindowDataGetCGContextProcPtr(inObj);
}

Now, I want to patch this method.

gWindowDataGetCGContextProcPtr  = (WindowData_GetCGContextProcPtr)Patch((const void*)&WindowData::GetCGContext, (const void*)&try_WindowDataGetCGContextProcPtr);

This patch gives compilation error.

error: 'WindowData' has not been declared
error: 'GetCGContext' was not declared in this scope

How I fix it?

like image 932
RLT Avatar asked Dec 05 '11 14:12

RLT


1 Answers

You can use c++filt to decode the mangling and do the injection.

But methods that are inlined by the optimizer won't work with this approach

like image 146
parapura rajkumar Avatar answered Nov 07 '22 22:11

parapura rajkumar