vittoriom / VMInstrumenter

A simple Objective-C singleton to instrument, protect, trace, and suppress selectors at runtime
GNU General Public License v2.0
111 stars 4 forks source link

Find a workaround for protecting selectors from being called from sources other than specific instances #39

Open vittoriom opened 10 years ago

vittoriom commented 10 years ago

Check if there is any way to get the address of the caller of a method. The debugger already does that, jumping on the previous frame of the stacktrace.

vittoriom commented 10 years ago

https://www.mikeash.com/pyblog/friday-qa-2014-01-10-lets-break-cocoa.html explains how to achieve this

vittoriom commented 10 years ago

Code snippet is:

Caller Inspection The compiler builtin __builtin_return_address will give you the address of the code that called you:

    void *addr = __builtin_return_address(0);

From that, we can get information about the caller, including its name:

    Dl_info info;
    dladdr(addr, &info);
    NSString *callerName = [NSString stringWithUTF8String: info.dli_sname];

With this, we can do some seriously nefarious stuff, like behaving completely differently depending on what called a certain method:

    @interface CallerInspection : NSObject @end
    @implementation CallerInspection

    - (void)method
    {
        void *addr = __builtin_return_address(0);
        Dl_info info;
        dladdr(addr, &info);
        NSString *callerName = [NSString stringWithUTF8String: info.dli_sname];
        if([callerName isEqualToString: @"__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__"])
            NSLog(@"Do some notification stuff");
        else
            NSLog(@"Do some regular stuff");
    }

    @end
vittoriom commented 10 years ago

Useful information at http://linux.die.net/man/3/dlopen

Public Attributes of the struct:

const char *    dli_fname
void *  dli_fbase
const char *    dli_sname
void *  dli_saddr
int     dli_version 
int     dli_reserved1
long    dli_reserved [4]
stanislaw commented 10 years ago

@vittoriom, it is nice to follow these your explorations! :+1:

vittoriom commented 10 years ago

@stanislaw I'm glad you're interested in this kind of things! If you know something more about inspecting the caller, help is welcome! :)