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 <objc/runtime.h>
@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 <objc/runtime.h>
@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


相关推荐

  1. iOS Hook 崩溃

    2024-06-09 19:22:01       8 阅读
  2. 线程崩溃了,进程也会崩溃吗?

    2024-06-09 19:22:01       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-09 19:22:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-09 19:22:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-09 19:22:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-09 19:22:01       20 阅读

热门阅读

  1. 9.0 Android中的网络技术

    2024-06-09 19:22:01       8 阅读
  2. 一个python 程序执行顺序

    2024-06-09 19:22:01       10 阅读
  3. LeetCode 1193, 45, 48

    2024-06-09 19:22:01       9 阅读
  4. IO数据流

    2024-06-09 19:22:01       9 阅读
  5. antd DatePicker 日期 与 时间 分开选择

    2024-06-09 19:22:01       10 阅读
  6. dockerfile,shell脚本,yaml文件如何配合

    2024-06-09 19:22:01       6 阅读
  7. C++数据结构——队列queue

    2024-06-09 19:22:01       9 阅读