{"id":13318107,"url":"https://github.com/faimin/ZDLibffiTutorial","last_synced_at":"2025-03-11T01:31:22.447Z","repository":{"id":140436313,"uuid":"227535222","full_name":"faimin/ZDLibffiTutorial","owner":"faimin","description":"libffi的基本用法","archived":false,"fork":false,"pushed_at":"2025-02-12T05:56:54.000Z","size":753,"stargazers_count":34,"open_issues_count":0,"forks_count":6,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-12T06:49:53.528Z","etag":null,"topics":["aspects","hook","ios","libffi","objective-c","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Objective-C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/faimin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-12T06:22:56.000Z","updated_at":"2025-02-12T05:56:58.000Z","dependencies_parsed_at":null,"dependency_job_id":"c1a53a79-dffc-4ea9-83f0-a7d8ecdb09e4","html_url":"https://github.com/faimin/ZDLibffiTutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faimin%2FZDLibffiTutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faimin%2FZDLibffiTutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faimin%2FZDLibffiTutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faimin%2FZDLibffiTutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/faimin","download_url":"https://codeload.github.com/faimin/ZDLibffiTutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242955355,"owners_count":20212310,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspects","hook","ios","libffi","objective-c","tutorial"],"created_at":"2024-07-29T18:29:37.984Z","updated_at":"2025-03-11T01:31:22.431Z","avatar_url":"https://github.com/faimin.png","language":"Objective-C","readme":"# libffi\n\n## 一、libffi简介\n\n\u003e  维基百科：\u003c/br\u003e\n\u003e [libffi](https://github.com/libffi/libffi) 是一个外部函数接口库。它提供了一个C编程语言接口，用于在运行时（而不是编译时）给定有关目标函数的信息来调用本地编译函数。它还实现了相反的功能：`libffi`可以生成一个指向可以接受和解码在运行时定义的参数组合的函数的指针。\n\n`FFI（Foreign Function Interface）`允许以一种语言编写的代码调用另一种语言的代码，而[libffi](https://github.com/libffi/libffi)库提供了最底层的、与架构相关的、完整的`FFI`。`libffi`的作用就相当于编译器，它为多种调用规则提供了一系列高级语言编程接口，然后通过相应接口完成函数调用，底层会根据对应的规则，完成数据准备，生成相应的汇编指令代码。\n\n    [libffi](https://github.com/libffi/libffi) 被称为`C语言的runtime`，它可根据 `参数类型`(`ffi_type`)、`参数个数`生成一个模板(`ffi_cif`)，然后通过`模板`、`函数指针` 、`参数地址` 来直接完成函数的调用(`ffi_call`)。\n\n    它也可以生成一个`闭包`(`ffi_closure`)，并同时得到一个函数指针`newIMP`，把这个新的函数指针`newIMP`与自定义的函数`void xx_func(ffi_cif *cif, void *ret, void **args, void *userdata)` 关联到一起，然后当我们执行`newIMP`时，会执行到我们自定义的`xx_func_`函数里（这个函数的参数格式是固定的），这里我们可以获得所有参数的地址和返回值以及自定义数据`userdata`。最后我们通过`ffi_call`函数来调用其他函数，简要流程是通过模板`cif`和`参数值`，把参数都按规则塞到栈/寄存器，然后调用的函数可以按规则获取到参数，调用完再获取返回值，最后记得释放内存。\n\n## 二、用法\n\n我们都知道`Objective-C`底层最终都会转成`objc_msgsend`这个`C`层的函数，而 `libffi` 能调用任意 `C` 函数，所以这也是`libffi`支持`Objective-C`的原因。`libffi`底层也是用汇编实现的。\n\n\n\u003e [**✅ 全部测试case**](./ZDLibffiDemoTests/ZDLibffiDemoTests.m)\n\n\n\u003cdetails close\u003e\n\u003csummary\u003e 先介绍一下 libffi 使用流程： \u003c/summary\u003e\n\n```c\n//1. 生成参数类型列表\n根据方法签名获取参数类型，然后转换成`ffi_type`类型\n\n//2. 创建函数模版\nffi_status ffi_prep_cif(ffi_cif *cif,\n            ffi_abi abi,\n            unsigned int nargs,\n            ffi_type *rtype,\n            ffi_type **atypes);\n\n//3. 如果需要用到切面，用下面函数生成一个`ffi_closure`闭包，否则直接执行第5步\nvoid *ffi_closure_alloc(size_t size, void **code);\n//4. 生成一个函数指针，并把闭包和函数指针绑定到函数模版上\nffi_status ffi_prep_closure_loc(ffi_closure*,\n              ffi_cif *,\n              void (*fun)(ffi_cif*,void*,void**,void*), //cif指针、返回值、参数列表、user_data\n              void *user_data,    \n              void*codeloc);    // 函数指针，执行函数实体\n\n//5. 调用函数\nvoid ffi_call(ffi_cif *cif,\n          void (*fn)(void),\n          void *rvalue,\n          void **avalue);\n\n//6. 在合适的时机释放`ffi_closure`\nffi_closure_free(void *)\n```\n\n\u003c/details\u003e\n\n\n##### 1. 调用C函数\n\n\u003cdetails\u003e\n\u003csummary\u003e Code \u003c/summary\u003e\n\n```c\nint cFunc(int a , int b) {\n    int x = a + b;\n    return x;\n}\n\n- (void)testCallCFunc {\n    ffi_cif cif;\n    ffi_type *argTypes[] = {\u0026ffi_type_sint, \u0026ffi_type_sint};\n    ffi_prep_cif(\u0026cif, FFI_DEFAULT_ABI, 2, \u0026ffi_type_sint, argTypes);\n\n    int a = 123;\n    int b = 456;\n    void *args[] = {\u0026a, \u0026b};\n    int retValue;\n    ffi_call(\u0026cif, (void *)cFunc, \u0026retValue, args);\n}\n```\n\n\u003c/details\u003e\n\n\n##### 2.调用OC方法\n\n\u003cdetails close\u003e\n\u003csummary\u003e Code \u003c/summary\u003e\n\n```objectivec\n// 直接调用OC方法\n- (void)testCallObjc {\n    SEL selector = @selector(a:b:c:);\n    NSMethodSignature *signature = [self methodSignatureForSelector:selector];\n\n    ffi_cif cif;\n    ffi_type *argTypes[] = {\u0026ffi_type_pointer, \u0026ffi_type_pointer, \u0026ffi_type_sint, \u0026ffi_type_pointer, \u0026ffi_type_pointer};\n    ffi_prep_cif(\u0026cif, FFI_DEFAULT_ABI, (uint32_t)signature.numberOfArguments, \u0026ffi_type_pointer, argTypes);\n\n    NSInteger arg1 = 100;\n    NSString *arg2 = @\"hello\";\n    id arg3 = NSObject.class;\n    void *args[] = {\u0026self, \u0026selector, \u0026arg1, \u0026arg2, \u0026arg3};\n    __unsafe_unretained id ret = nil;\n    IMP func = [self methodForSelector:selector];\n    ffi_call(\u0026cif, func, \u0026ret, args);\n    NSLog(@\"===== %@\", ret);\n}\n\n- (id)a:(NSInteger)a b:(NSString *)b c:(NSObject *)c {\n    NSString *ret = [NSString stringWithFormat:@\"%zd + %@ + %@\", a, b, c];\n    NSLog(@\"result = %@\", ret);\n    return ret;\n}\n```\n\n\u003c/details\u003e\n\n\n##### 3. 关联C函数\n\n\u003cdetails close\u003e\n\u003csummary\u003e Code \u003c/summary\u003e\n\n```c\nstatic void bindCFunc(ffi_cif *cif, int *ret, void **args, void *userdata) {\n    struct UserData ud = *(struct UserData *)userdata;\n    *ret = 999;\n    printf(\"==== %s, %d\\n\", ud.c, *(int *)ret);\n\n    //ffi_call(cif, ud.imp, ret, args); //再调用此方法会进入死循环\n}\n\n- (void)testBindCFunc {\n    ffi_cif cif;\n    ffi_type *argTypes[] = {\u0026ffi_type_sint, \u0026ffi_type_sint, \u0026ffi_type_sint};\n    ffi_prep_cif(\u0026cif, FFI_DEFAULT_ABI, 3, \u0026ffi_type_sint, argTypes);\n\n    // 新定义一个C函数指针\n    int(*newCFunc)(int, int, int);\n    ffi_closure *cloure = ffi_closure_alloc(sizeof(ffi_closure), (void *)\u0026newCFunc);\n    struct UserData userdata = {\"圣诞快乐\", 8888, newCFunc};\n    // 将newCFunc与bingCFunc关联\n    ffi_status status = ffi_prep_closure_loc(cloure, \u0026cif, (void *)bindCFunc, \u0026userdata, newCFunc);\n    if (status != FFI_OK) {\n        NSLog(@\"新函数指针生成失败\");\n        return;\n    }\n\n    int ret = newCFunc(11, 34, 24);\n    printf(\"********** %d\\n\", ret);\n\n    ffi_closure_free(cloure);\n}\n```\n\n\u003c/details\u003e\n\n\n##### 4. 生成`OC`切面函数\n\n\u003e  大家熟知的几种hook方式：\n\u003e \n\u003e 1. 方法交换\n\u003e \n\u003e 2. 消息转发（[Aspects](https://github.com/steipete/Aspects)）\n\u003e \n\u003e 3. 分类覆盖原方法\n\n\u003cdetails close\u003e\n\u003csummary\u003e Code \u003c/summary\u003e\n\n```objectivec\nstatic void zdfunc(ffi_cif *cif, void *ret, void **args, void *userdata) {\n    ZDFfiHookInfo *info = (__bridge ZDFfiHookInfo *)userdata;\n\n    // 打印参数\n    NSMethodSignature *methodSignature = info.signature;\n    NSInteger beginIndex = 2;\n    if (info.isBlock) {\n        beginIndex = 1;\n    }\n    for (NSInteger i = beginIndex; i \u003c methodSignature.numberOfArguments; ++i) {\n        id argValue = ZD_ArgumentAtIndex(methodSignature, ret, args, userdata, i);\n        NSLog(@\"arg ==\u003e index: %ld, value: %@\", i, argValue);\n    }\n\n    // 根据cif (函数原型，函数指针，返回值内存指针，函数参数) 调用这个函数\n    ffi_call(\u0026(info-\u003e_cif), info-\u003e_originalIMP, ret, args);\n}\n\n- (void)testHookOC {\n    SEL selector = @selector(x:y:z:);\n    NSMethodSignature *signature = [self methodSignatureForSelector:selector];\n    IMP originIMP = [self methodForSelector:selector];\n\n\n    ffi_type *argTypes[] = {\u0026ffi_type_pointer, \u0026ffi_type_pointer, \u0026ffi_type_sint, \u0026ffi_type_pointer, \u0026ffi_type_pointer};\n\n    ffi_cif cif;\n    ffi_prep_cif(\u0026cif, FFI_DEFAULT_ABI, (uint32_t)signature.numberOfArguments, \u0026ffi_type_pointer, argTypes);\n\n    IMP newIMP = NULL;\n    ffi_closure *cloure = ffi_closure_alloc(sizeof(ffi_closure), (void *)\u0026newIMP);\n    ZDFfiHookInfo *info = ({\n        ZDFfiHookInfo *model = ZDFfiHookInfo.new;\n        model-\u003e_cif = cif;\n        model-\u003e_argTypes = argTypes;\n        model-\u003e_closure = cloure;\n        model-\u003e_originalIMP = originIMP;\n        model-\u003e_newIMP = newIMP;\n        model.signature = signature;\n        model;\n    });\n    ffi_status status = ffi_prep_closure_loc(cloure, \u0026cif, zdfunc, (__bridge void *)info, newIMP);\n    if (status != FFI_OK) {\n        NSLog(@\"新函数指针生成失败\");\n        return;\n    }\n\n    //替换实现\n    Method method = class_getInstanceMethod(self.class, selector);\n    method_setImplementation(method, newIMP);\n\n    NSInteger arg1 = 100;\n    NSString *arg2 = @\"Zero.D.Saber\";\n    id arg3 = @(909090);\n    [self x:arg1 y:arg2 z:arg3];\n}\n\n- (id)x:(NSInteger)a y:(NSString *)b z:(id)c {\n    NSString *ret = [NSString stringWithFormat:@\"%zd + %@ + %@\", a, b, c];\n    NSLog(@\"result = %@\", ret);\n    return ret;\n}\n```\n\n\u003c/details\u003e\n\n\n## 三、如何 hook 单个实例对象？\n\n\u003e 只提供思路\n\n仿照`KVO`的实现机制，以当前实例对象所属类为父类，动态创建一个新的子类，把当前实例的`isa`设置为新建的子类，并重写`class`方法。接下来只要  `hook` 这个子类就可以了；\n\n### 四、总结：\n\n1. libffi的优势：\n   \n   \u003e + 支持多平台\n   \u003e \n   \u003e + 支持调用`C`、`Objective-C`\n   \u003e \n   \u003e + 执行速度快\n   \u003e \n   \u003e + 可以做到像[Aspects](https://github.com/steipete/Aspects)一样多次`hook`同一方法\n   \u003e \n   \u003e + 可以像`NSInvocation`动态调用`Objective-C`\n\n2. 缺点：\n   \n   \u003e + 构建模版函数时略繁琐\n\n3. 使用场景：\n   \n   \u003e + `hook` 原生方法\n   \u003e \n   \u003e + 替代`performSelector:`、`NSInvocation`调用`Objective-C`方法\n   \n\n    \u003e 通过`消息转发`和`libffi`两种方式实现对`block`的`hook`\n\n    + [ZDBlockHook](https://github.com/faimin/ZDBlockHook)\n\n## 编译：\n\n#### libffi编译\n\n\u003e 笔者其实更倾向于直接使用源码而不是编译成静态库，因为静态库需要适配多种架构，比较麻烦。\n\u003e\n\u003e 直接用源码不用考虑架构问题，而且还可以很好的支持`modulemap`，在`iOS`混编环境中更易使用。\n\n```shell\n1. `./autogen.sh`\n2. `python generate-darwin-source-and-headers.py --only-ios`\n3. open `libffi.xcodeproj`\n4. select scheme `libffi-iOS` and device `Generic iOS Device`\n5. click \"Product - Build\"\n\nIf success, you would see a \"Product/libffi.a\" in the side bar, you can right click it to get the lib in the finder.\n```\n\n#### ZDLibffi\n\n笔者基于当前最新的 [3.4.6](https://github.com/libffi/libffi/releases/tag/v3.4.6) 版本制作了一个源码版本的 [ZDLibffi](https://github.com/faimin/ZDLibffi_iOS)，支持`modulemap`，可以更好的兼容混编开发环境。\n\n```ruby\npod 'ZDLibffi'\n```\n\n## 参考：\n\n- [libffi](https://github.com/libffi/libffi)\n\n- [libffi文档](http://www.chiark.greenend.org.uk/doc/libffi-dev/html/Index.html#Index)\n\n- [使用libffi实现AOP](https://juejin.im/post/5a600d20518825732c539622)\n\n- [动态调用\u0026定义C函数](https://www.jianshu.com/p/92d4c06223e7)\n\n- [Stinger](https://github.com/eleme/Stinger)\n\n- [libffi编译方法](https://github.com/libffi/libffi/issues/510#issuecomment-654689416)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaimin%2FZDLibffiTutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffaimin%2FZDLibffiTutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaimin%2FZDLibffiTutorial/lists"}