• iOS Hook 崩溃


    0x00 崩溃重现

    Hook 的类,是这样的:

    @interface ViewController : UIViewController
    @end
    
    @implementation ViewController
    - (void)loadView {
        [super loadView];
        
        NSLog(@"%s", __func__);
    }
    
    - (void)test {
        NSLog(@"%s", __func__);
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [self test];
    }
    
    @end
    

    写的 Hook 逻辑是这样的:

    @interface Hook : NSObject
    @end
    
    #import 
    @implementation Hook
    
    + (void)load {
        NSLog(@"%s", __func__);
        
        Class class = NSClassFromString(@"ViewController");
        Method originalMethod = class_getInstanceMethod(class, NSSelectorFromString(@"loadView"));
        Method swizzledMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"swizzled_loadView"));
        
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
    - (void)swizzled_loadView {
        NSLog(@"%s", __func__);
    
        [self swizzled_loadView];
    }
    
    @end
    

    真机运行后,是这样的,直接崩溃:

    +[Hook load]
    -[Hook swizzled_loadView]
    -[ViewController swizzled_loadView]: unrecognized selector sent to instance 0x102e08dd0
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController swizzled_loadView]: unrecognized selector sent to instance 0x102e08dd0'
    

    0x00 换个方式

    写的 Hook 逻辑是这样的:

    @interface UIViewController (Hook)
    @end
    
    #import 
    @implementation UIViewController (Hook)
    
    + (void)load {
        NSLog(@"%s", __func__);
        
        Class class = NSClassFromString(@"ViewController");
        Method originalMethod = class_getInstanceMethod(class, NSSelectorFromString(@"loadView"));
        Method swizzledMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"swizzled_loadView"));
    
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
    - (void)swizzled_loadView {
        NSLog(@"%s", __func__);
    
        [self swizzled_loadView];
        
        UIView *view = [[UIView alloc] init];
        view. frame = CGRectMake (100, 200, 200, 200);
        view.backgroundColor = [UIColor redColor];
        [self.view addSubview:view];
    }
    
    @end
    

    真机运行后,不崩溃了:

    +[UIViewController(Hook) load]
    -[UIViewController(Hook) swizzled_loadView]
    -[ViewController loadView]
    -[ViewController test]
    

    并且成功,添加了 view


  • 相关阅读:
    Linux 网络通信
    实现一个简单的长轮询
    Django —— 用户名和密码配置
    新的希望就在小雪季节,人大与加拿大女王大学金融硕士邀你来享金融知识盛宴
    动态修改日志级别,太有用了!
    Go语学习笔记 - gorm使用 - 事务操作 Web框架Gin(十一)
    Python编程 字典创建
    NDK 是什么 | FFmpeg 5.0 编译 so 库
    AD域控-漫游账户-同步中心
    操作系统学习笔记-精简复习版
  • 原文地址:https://blog.csdn.net/xjh093/article/details/139502032