#import <Foundation/Foundation.h> #import <objc/runtime.h> IMP PYSwizzleClassSelector(Class aClass, SEL selector, IMP newImplementation) { // Get the original implementation we are replacing Class metaClass = objc_getMetaClass(class_getName(aClass)); Method method = class_getClassMethod(metaClass, selector); IMP origImp = method_getImplementation(method); if (! origImp) { return NULL; } class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method)); return origImp; } IMP PYSwizzleSelector(Class aClass, SEL selector, IMP newImplementation) { // Get the original implementation we are replacing Method method = class_getInstanceMethod(aClass, selector); IMP origImp = method_getImplementation(method); if (! origImp) { return NULL; } class_replaceMethod(aClass, selector, newImplementation, method_getTypeEncoding(method)); return origImp; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // 自定义一个类,进行hook测试 @interface myClass : NSObject - (void)dllhook_com; @end @implementation myClass - (void)dllhook_com{ NSLog(@"[++++]myClass:dllhook_com"); } @end ///////////////////////////////////////////////////////////////////////////////////////////////////////// // 函数原型 static NSString *(*pfn_NSString_uppercaseString_imp)(id self, SEL _cmd) = NULL; static NSString *swizzled_NSString_uppercaseString_imp(NSString *self, SEL _cmd){ NSLog(@"[++++]into swizzled_NSString_uppercaseString_imp"); // 调用原函数 NSString *str = (*pfn_NSString_uppercaseString_imp)(self, _cmd); return str; } // 函数原型 static void (*pfn_myClass_dllhook_com_imp)(id self, SEL _cmd) = NULL; static void swizzled_myClass_dllhook_com_imp(NSString *self, SEL _cmd){ NSLog(@"[++++]into swizzled_myClass_fun1_imp"); // 调用原函数 (*pfn_myClass_dllhook_com_imp)(self, _cmd); } void fun1(id self, SEL _cmd){ NSLog(@"[++++]fun1调用!!"); } int main(int argc, const char * argv[]) { @autoreleasepool { pfn_NSString_uppercaseString_imp = (NSString *(*)(id, SEL))PYSwizzleSelector(objc_getClass("NSString")/*[NSString class]*/, @selector(uppercaseString), (IMP)swizzled_NSString_uppercaseString_imp); NSString *s = @"www.dllhook.com"; NSLog(@"%@", [s uppercaseString]); // hook自己的类 pfn_myClass_dllhook_com_imp = (void (*)(id, SEL))PYSwizzleSelector([myClass class], @selector(dllhook_com), (IMP)swizzled_myClass_dllhook_com_imp); myClass *my1 = [myClass new]; // 或者 //myClass *my1 = [[myClass alloc] init]; [my1 dllhook_com]; // 给myClass添加一个方法 class_addMethod([myClass class], sel_registerName("fun1"), (IMP)fun1, "v@:"); // 调用新增的方法 [my1 performSelector:@selector(fun1)]; u_int count = 0; Method *methods = class_copyMethodList([myClass class], &count); for (int i = 0; i < count; i++) { SEL name = method_getName(methods[i]); NSString *strName = [NSString stringWithCString:sel_getName(name) encoding:NSUTF8StringEncoding]; NSLog(@"%@", strName); } } return 0; }
发表评论