facebook / fishhook

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

Crash when hook fonction `object_setClass` #56

Closed 623637646 closed 3 years ago

623637646 commented 5 years ago

What crash

When I hook fonction object_setClass, then call object_setClass, it works. but when I call [NSString stringWithFormat:@"%@", @""];, It crash.

Demo code


#import <UIKit/UIKit.h>
#import "fishhook.h"
#import <objc/runtime.h>

Class _Nullable
(*orig_object_setClass)(id _Nullable obj, Class _Nonnull cls);

Class _Nullable
my_object_setClass(id _Nullable obj, Class _Nonnull cls)
{
    return orig_object_setClass(obj, cls);
}

int main(int argc, char * argv[]) {
    @autoreleasepool {
        rebind_symbols((struct rebinding[]){
            {"object_setClass", my_object_setClass, (void *)&orig_object_setClass}
        }, 1);

        object_setClass(@"", NSObject.class);

        [NSString stringWithFormat:@"%@", @""];

        return 0;
    }
}
XjShi commented 4 years ago

It may be a careless mistake. Try this:

Class _Nullable
my_object_setClass(id _Nullable obj, Class _Nonnull cls)
{
    return orig_object_setClass(obj, cls);
}
623637646 commented 4 years ago

Hi @XjShi , I fix it. But still crash:

Screenshot 2019-11-20 at 8 00 49 PM
XjShi commented 4 years ago

Call object_setClass(@"", NSObject.class) can also cause crash without hook object_setClass.

623637646 commented 4 years ago

@XjShi I tried. It doesn't crash without hooking.

#import "AppDelegate.h"
#import <UIKit/UIKit.h>
#import "fishhook.h"
#import <objc/runtime.h>

Class _Nullable
(*orig_object_setClass)(id _Nullable obj, Class _Nonnull cls);

Class _Nullable
my_object_setClass(id _Nullable obj, Class _Nonnull cls)
{
    return orig_object_setClass(obj, cls);
}

int main(int argc, char * argv[]) {
    @autoreleasepool {
//        rebind_symbols((struct rebinding[]){
//            {"object_setClass", my_object_setClass, (void *)&orig_object_setClass}
//        }, 1);

        object_setClass(@"", NSObject.class);

        [NSString stringWithFormat:@"%@", @""];

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}
XjShi commented 4 years ago

It may be an 'undefined' behavior. I tried this in several different situation. Crash did happens in some situation.

I don't know anything deeper about object_class. 😢

623637646 commented 4 years ago

Thanks @XjShi .

623637646 commented 3 years ago

Found the answer: https://stackoverflow.com/a/62068020/9315497 Tagged Pointer Strings are special objects.