美文网首页
fishhook 的简单使用体验

fishhook 的简单使用体验

作者: AndyGF | 来源:发表于2020-05-09 11:57 被阅读0次

    fishhook 是 FaceBook 提供的一个动态修改链接 mach-O 文件的工具.利用 mach-O 文件加载原理, 通过修改懒加载和非懒加载两个表的指针达到 C 函数 Hook 的目的.

    • fishhook 只能 Hook 系统的 C 函数, 无法 Hook 自定义函数 和 OC 方法.

    fishhook 只提供两个, 我们本次先说 rebind_symbols 的使用, 以 Hook 系统 NSLog 函数为例,

    int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel);
    

    rebind_symbols 函数有两个参数:

    • rebinding 结构体的数组, 可以把所有需要 Hook 的函数都构建相应的 rebinding 结构体放入数组中, 调用一次即可.
    • 数组长度

    rebinding 结构体声明:

    struct rebinding {
      const char *name;     //需要HOOK的函数名称,C字符串
      void *replacement;    //新函数的地址
      void **replaced;      //原始函数地址的指针!
    };
    

    开始体验 fishhook 的功能.

    • 上代码前准备拖入 fishhook 文件, 导入 fishhook 头文件.
    #import "fishhook.h"
    
    fishhook文件
    1. 声明保存系统 NSLog 的函数.
    static void (*sys_nslog)(NSString *format, ...);
    
    1. 定义替换 NSLog 的函数.
    void myNSLog(NSString *format, ...) {
        format = [format stringByAppendingFormat: @" hook 住了"];
        sys_nslog(format);
    }
    
    1. 调用 rebind_symbols 函数进行 Hook.
    + (void)load {
        
        struct rebinding nslog;
        
        nslog.name = "NSLog"; 
        nslog.replacement = myNSLog;
        nslog.replaced = (void *)&sys_nslog;
        
        struct rebinding rebs[1] = { nslog };
        
        rebind_symbols(rebs, 1);
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        NSLog(@"我是系统原生的 log");
    }
    

    Hook 代码为什么要写在 + (void)load 方法中 ?
    + (void)load 会在 main 函数之前调用, 因此使用 fishhook 做一些安全防护的时候 hook 时机比较早, 效果会更好.

    相关文章

      网友评论

          本文标题:fishhook 的简单使用体验

          本文链接:https://www.haomeiwen.com/subject/euwhnhtx.html