iOS中的HOOK技术

简介

OC语言是动态的

C语言是纯静态的,C函数的调用是通过函数地址,函数地址在编译时期就必须确认。如果要hook,要直接修改二进制,要直接去写汇编代码。

fishhook

介绍

fishhook是facebook出品的一个开源库。利用mach-o文件加载原理,通过rebind_symbols函数修改__DATA Segment的符号指针指向,来动态的Hook C函数。

主要信息

结构体

struct rebinding {
  const char *name;   //函数名称
  void *replacement;  //新的函数地址
  void **replaced;   //保存原始函数地址变量的指针(通常要存储下来,在替换后的方法里调用)
};

主要接口

  /*
  交换方法
  arg1: 存放rebinding结构体的数组
  arg2: 数组的长度
  */
int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel);

实现

在这里插入图片描述
hook OC函数

//
//  ViewController.m
//  fishhookTest
//
//  Created by  on 2020/3/3.
//  Copyright © 2020 Shae. All rights reserved.
//

#import "ViewController.h"
#import "fishhook.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //这里必须要先加载一次要交换的函数,否则符号表里面不会出现要交换的函数的地址
    NSLog(@"我是纯正的NSLog函数");
    
    //定义rebinding结构体
    struct rebinding manager;
    //要交换的函数的名称
    manager.name="NSLog";
    //新的函数的地址
    manager.replacement=new_NSLog;
    //保存原始函数地址变量的指针(存储下来,在替换的方法里调用)
    manager.replaced=(void*)&old_NSLog;
    //定义数组
    struct rebinding rebs[]={manager};
    /*
     交换方法
     arg1: 存放rebinding结构体的数组
     arg2: 数组的长度
     */
    rebind_symbols(rebs, 1);
    
}
//函数指针,用来保存原始的函数地址
static void (* old_NSLog)(NSString *format, ...);
//新的NSLog函数
void new_NSLog(NSString *format, ...){
    format=[format stringByAppendingString:@"被勾上了"];
    //再调原来的
    old_NSLog(format);

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"点击屏幕");
}

@end

hook C函数

#import "ViewController.h"
#import "fishhook.h"

@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];

  //这里必须要先加载一次要交换的函数,否则符号表里面不会出现要交换的函数的地址
  printf("我是纯正的printf函数\n");

  //定义rebinding结构体
  struct rebinding manager;
  //要交换函数的名称
  manager.name = "printf";
  //新的函数地址
  manager.replacement = new_printf;
  //保存原始函数地址变量的指针(存储下来,在替换后的方法里调用)
  manager.replaced = (void *)&old_printf;

  //定义数组
  struct rebinding rebs[] = {manager};

 /*
  交换方法
  arg1: 存放rebinding结构体的数组
  arg2: 数组的长度
  */
  rebind_symbols(rebs, 1);
}

//函数指针,用来保存原始的函数地址
static int (* old_printf)(const char *, ...);

//新的printf函数
void new_printf(const char * name, ...) {
  //再调用原来的
  old_printf("勾上了!\n");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  printf("点击屏幕");
}
@end

在这里插入图片描述

Method Swizzle

在这里插入图片描述
Method Swizzle是利用OC的Runtime特性,动态改变SEL(方法编号)和IMP(方法实现)的对应关系,达到OC方法调用流程改变的目的。主要用于OC方法调换或往系统方法注入代码。

Runtime 术语的数据结构

SEL

它是selector在 Objc 中的表示(Swift 中是 Selector 类)。selector 是方法选择器,其实作用就和名字一样,日常生活中,我们通过人名辨别谁是谁,注意 Objc 在相同的类中不会有命名相同的两个方法。selector 对方法名进行包装,以便找到对应的方法实现。它的数据结构是:

typedef struct objc_selector *SEL;

我们可以看出它是个映射到方法的 C 字符串,你可以通过 Objc 编译器器命令@selector() 或者 Runtime 系统的 sel_registerName 函数来获取一个 SEL 类型的方法选择器。

注意:
不同类中相同名字的方法所对应的selector是相同的,由于变量的类型不同,所以不会导致它们调用方法实现混乱。

id

id 是一个参数类型,它是指向某个类的实例的指针。定义如下:

typedef struct objc_object *id;
struct objc_object { Class isa; };

以上定义,看到 objc_object 结构体包含一个 isa 指针,根据 isa 指针就可以找到对象所属的类。

注意:
isa 指针在代码运行时并不总指向实例对象所属的类型,所以不能依靠它来确定类型,要想确定类型还是需要用对象的 -class 方法。(如:KVO 的实现机理就是将被观察对象的 isa 指针指向一个中间类而不是真实类型)

Class

typedef struct objc_class *Class;

Class 其实是指向 objc_class 结构体的指针。objc_class 的数据结构如下:

struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;   //类的isa指针,指向其所属的元类(meta)

#if !__OBJC2__
    Class super_class  //父类指针                       OBJC2_UNAVAILABLE;
    const char *name   //类名                           OBJC2_UNAVAILABLE;
    long version  //是类的版本信息                       OBJC2_UNAVAILABLE;
    long info  //是类的详情                             OBJC2_UNAVAILABLE;
    long instance_size  //该类的实例对象的大小            OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars  //成员变量列表         OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists  //方法列表    OBJC2_UNAVAILABLE;
    struct objc_cache *cache  //缓存                    OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols  //协议列表     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;

·Class 也有一个 isa 指针,指向其所属的元类(meta)。
·super_class:指向其超类。
·name:是类名。
·version:是类的版本信息。
·info:是类的详情。
·instance_size:是该类的实例对象的大小。
·ivars:指向该类的成员变量列表。
·methodLists:指向该类的实例方法列表,它将方法选择器和方法实现地址联系起来。methodLists 是指向 ·objc_method_list 指针的指针,也就是说可以动态修改 *methodLists 的值来添加成员方法,这也是 Category 实现的原理,同样解释了 Category 不能添加属性的原因。
·cache:Runtime 系统会把被调用的方法存到 cache 中(理论上讲一个方法如果被调用,那么它有可能今后还会被调用),下次查找的时候效率更高。
·protocols:指向该类的协议列表。

其中 objc_ivar_list 和 objc_method_list 分别是成员变量列表和方法列表:

//成员变量列表
struct objc_ivar_list {
    int ivar_count                                     OBJC2_UNAVAILABLE;
#ifdef __LP64__
    int space                                          OBJC2_UNAVAILABLE;
#endif
    /* variable length structure */
    struct objc_ivar ivar_list[1]                      OBJC2_UNAVAILABLE;
}                                                      OBJC2_UNAVAILABLE;
//方法列表
struct objc_method_list {
    struct objc_method_list *obsolete                  OBJC2_UNAVAILABLE;

    int method_count                                   OBJC2_UNAVAILABLE;
#ifdef __LP64__
    int space                                          OBJC2_UNAVAILABLE;
#endif
    /* variable length structure */
    struct objc_method method_list[1]                  OBJC2_UNAVAILABLE;
}

由此可见,我们可以动态修改 *methodList 的值来添加成员方法,这也是 Category 实现的原理,同样解释了 Category 不能添加属性的原因。

objc_ivar_list 结构体用来存储成员变量的列表,而 objc_ivar 则是存储了单个成员变量的信息;同理,objc_method_list 结构体存储着方法数组的列表,而单个方法的信息则由 objc_method 结构体存储。

值得注意的时,objc_class 中也有一个 isa 指针,这说明 Objc 类本身也是一个对象。为了处理类和对象的关系,Runtime 库创建了一种叫做 Meta Class(元类) 的东西,类对象所属的类就叫做元类。Meta Class 表述了类对象本身所具备的元数据。

在这里插入图片描述

Method

Method 代表类中某个方法的类型

typedef struct objc_method *Method;

struct objc_method {
    SEL method_name                                    OBJC2_UNAVAILABLE;
    char *method_types                                 OBJC2_UNAVAILABLE;
    IMP method_imp                                     OBJC2_UNAVAILABLE;
}

objc_method 存储了方法名,方法类型和方法实现:

方法名,类型为 SEL
方法类型 method_types 是个 char 指针,存储方法的参数类型和返回值类型
method_imp 指向了方法的实现,本质是一个函数指针

Ivar

Ivar 是表示成员变量的类型。

typedef struct objc_ivar *Ivar;

struct objc_ivar {
    char *ivar_name                                    OBJC2_UNAVAILABLE;
    char *ivar_type                                    OBJC2_UNAVAILABLE;
    int ivar_offset                                    OBJC2_UNAVAILABLE;
#ifdef __LP64__
    int space                                           OBJC2_UNAVAILABLE;
#endif
}

其中 ivar_offset 是基地址偏移字节

IMP

IMP在objc.h中的定义是:

typedef id (*IMP)(id, SEL, ...);

它就是一个函数指针,这是由编译器生成的。当你发起一个 ObjC 消息之后,最终它会执行的那段代码,就是由这个函数指针指定的。而 IMP 这个函数指针就指向了这个方法的实现。

你会发现 IMP 指向的方法与 objc_msgSend 函数类型相同,参数都包含 id 和 SEL 类型。每个方法名都对应一个 SEL 类型的方法选择器,而每个实例对象中的 SEL 对应的方法实现肯定是唯一的,通过一组 id和 SEL参数就能确定唯一的方法实现地址。

Cache

Cache 定义如下:

typedef struct objc_cache *Cache

struct objc_cache {
    unsigned int mask /* total = mask + 1 */           OBJC2_UNAVAILABLE;
    unsigned int occupied                              OBJC2_UNAVAILABLE;
    Method buckets[1]                                  OBJC2_UNAVAILABLE;
};

Cache 为方法调用的性能进行优化,每当实例对象接收到一个消息时,它不会直接在 isa 指针指向的类的方法列表中遍历查找能够响应的方法,因为每次都要查找效率太低了,而是优先在 Cache 中查找。

Runtime 系统会把被调用的方法存到 Cache 中,如果一个方法被调用,那么它有可能今后还会被调用,下次查找的时候就会效率更高。就像计算机组成原理中 CPU 绕过主存先访问 Cache 一样。

方法交换(Method Swizzling)

下面代码对UIViewController中的viewDidLoad方法进行交换
UIViewController+swizzling.m文件

#import "UIViewController+swizzling.h"
#import <objc/runtime.h>

@implementation UIViewController (swizzling)

//load类方法(当某个类的代码被读到内存后调用)
+ (void)load
{
    /*
     SEL: 它就是个映射到方法的C字符串,可以用Objective-C编译器命令@selector()或者Runtime系统的sel_registerName函数来获得一个SEL类型的方法选择器。
     
     数据结构是:
     typedef struct objc_selector *SEL;
     */
    SEL origSel = @selector(viewDidLoad);
    SEL swizSel = @selector(swiz_viewDidLoad);
  
    [UIViewController swizzleMethods:[self class] originalSelector:origSel swizzledSelector:swizSel];
}

//交换两个方法的实现
+ (void)swizzleMethods:(Class)class originalSelector:(SEL)origSel swizzledSelector:(SEL)swizSel
{
    /*
     Method 代表类中某个方法的类型
     
     typedef struct objc_method *Method;
     
     struct objc_method {
     SEL method_name                                    OBJC2_UNAVAILABLE;
     char *method_types                                 OBJC2_UNAVAILABLE;
     IMP method_imp                                     OBJC2_UNAVAILABLE;
     }
     objc_method 存储了方法名,方法类型和方法实现:
     
     方法名类型为 SEL
     方法类型 method_types 是个 char 指针,存储方法的参数类型和返回值类型
     method_imp 指向了方法的实现,本质是一个函数指针
     
     
     class_getInstanceMethod(class, origSel);
     返回class类的origSel方法。
    */
    Method origMethod = class_getInstanceMethod(class, origSel);
    Method swizMethod = class_getInstanceMethod(class, swizSel);
    
    /*
     周全起见,有两种情况要考虑一下
     第一种情况:要交换的方法并没有在目标类中实现,而是在其父类中实现了, 这时使用class_getInstanceMethod函数获取到的originalSelector指向的就是父类的方法
     第二种情况:要交换的方法已经存在于目标类中

     
      class_addMethod(class, origSel, method_getImplementation(swizMethod), method_getTypeEncoding(swizMethod));
      往class这个类,添加方法origSel,新增方法的实现地址为method_getImplementation(swizMethod),参数及返回值类型为method_getTypeEncoding(swizMethod)
      添加成功返回YES,失败返回NO(例如,该类已经包含一个同名的方法实现)
     
      method_getImplementation(swizMethod)  返回swizMethod方法实现
      method_getTypeEncoding(swizMethod)  返回描述swizMethod方法参数和返回值类型的字符串
     */
    //判断是情况一还是情况二
    BOOL didAddMethod = class_addMethod(class, origSel, method_getImplementation(swizMethod), method_getTypeEncoding(swizMethod));
  
    if (didAddMethod)
    {
        /*
          第一种情况:要交换的方法已经在父类中实现了,则替换父类方法
          使用replaceMethod来替换给定类的方法实现(将origMethod方法替换成swizSel方法)
         */
        class_replaceMethod(class, swizSel, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    }
    else
    {
        /*
          第二种情况:要交换的方法已经存在于目标类中
          通过method_exchangeImplementations来交换方法
         */
        method_exchangeImplementations(origMethod, swizMethod);
    }
}

//自己实现的用于交换的方法
- (void)swiz_viewDidLoad
{
    NSLog(@"调用了swiz_viewDidLoad方法");
    
    /*
       需要注入的代码写在此处
     */
    
    //执行这句的时候跳转到viewDidLoad方法中
    [self swiz_viewDidLoad];
}
@end

ViewController.m文件

#import "ViewController.h"
#import "UIViewController+swizzling.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    //执行这句的时候跳到swiz_viewDidLoad方法中
    [super viewDidLoad];
  
    NSLog(@"调用了viewDidLoad方法");
}
@end

当执行[super viewDidLoad]时,跳转到swiz_viewDidLoad方法中。当执行到[self swiz_viewDidLoad]时,再跳转到viewDidLoad方法中。因此,先打印“调用了swiz_viewDidLoad方法”,再打印“调用了viewDidLoad方法”

在这里插入图片描述

macoView

用来研究应用的可执行文件的。

fishhook替换oc方法demo

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值