facebook / fishhook

A library that enables dynamically rebinding symbols in Mach-O binaries running on iOS.
BSD 3-Clause "New" or "Revised" License
5.2k stars 966 forks source link

can fishhook hook c function written by ourself? #25

Closed intheway closed 8 years ago

intheway commented 8 years ago

myFunction is a c function written by me in my project, I want to hook it, but I tried this code failed.

int myFunction(int a){
    return a+1;
}

static int (*orig_myFunction)(int);

int hook_myFunction(int a){
    return a+2;
}

int main(int argc, char * argv[])
{
    @autoreleasepool {
        rebind_symbols((struct rebinding[1]){{"myFunction", hook_myFunction, (void *)&orig_myFunction}}, 1);
        printf("%d\n" , myFunction(1));
       return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

This means fishhook can only hook system api or how to hook c function written by ourself ? Thanks.

fpotter commented 8 years ago

fishhook can only hook functions that exist in other libraries. It cannot hook functions that exist in the same image (library or executable) as your currently running code.

The reason for this is that there's no indirection that happens when you call a function in your own executable. It's just a plain jump to another code address in your executable.

That's very different from calling a function in an external library, where your executable uses dyld to figure out the address of the function being called before jumping to it.

On Sun, Mar 6, 2016 at 10:59 PM, Zhengwei Yin notifications@github.com wrote:

myFunction is a c function written by me in my project, I want to hook it, but I tried this code failed.

int myFunction(int a){ return a+1; }

static int (*orig_myFunction)(int);

int hook_myFunction(int a){ return a+2; }

int main(int argc, char * argv[]) { @autoreleasepool { rebind_symbols((struct rebinding[1]){{"myFunction", hook_myFunction, (void *)&orig_myFunction}}, 1); printf("%d\n" , myFunction(1)); return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }

This means fishhook can only hook system api or how to hook c function written by ourself ? Thanks.

— Reply to this email directly or view it on GitHub https://github.com/facebook/fishhook/issues/25.

intheway commented 8 years ago

Thanks!