参考官方头文件:http://www.opensource.apple.com/source/dyld/dyld-353.2.1/include/mach-o/dyld-interposing.h


//  演示代码 
// #import <mach-o/dyld-interposing.h>
// from dyld-interposing.h
#define DYLD_INTERPOSE(_replacement,_replacee) __attribute__((used)) static struct{ const void* replacement; const void* replacee; } _interpose_##_replacee __attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacement, (const void*)(unsigned long)&_replacee };

ssize_t hacked_write(int fildes, const void *buf, size_t nbyte)
{
    printf("[++++]into hacked_write---by piaoyun");
    return write(fildes, buf, nbyte);
}

DYLD_INTERPOSE(hacked_write, write);



// 再来个演示代码:

// 编译
// cc -dynamiclib main.c -o libHook.dylib -Wall
// 强行注入ls测试
// DYLD_INSERT_LIBRARIES=libHook.dylib ls
#include <malloc/malloc.h>

#define DYLD_INTERPOSE(_replacement,_replacee) \
__attribute__((used)) static struct{ const void* replacement; const void* replacee; } _interpose_##_replacee \
__attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_replacement, (const void*)(unsigned long)&_replacee };


void *hacked_malloc(size_t size){
    void *ret = malloc(size);
    
    malloc_printf("+ %p %d\n", ret, size);
    return ret;
}

void hacked_free(void *freed){
    malloc_printf("- %p\n", freed);
    free(freed);
}

DYLD_INTERPOSE(hacked_malloc, malloc)
DYLD_INTERPOSE(hacked_free, free);


更加完整的代码可以参考lldb源代码:

https://github.com/llvm-mirror/lldb/blob/master/examples/interposing/darwin/fd_interposing/FDInterposing.cpp

你可能感兴趣的文章

评论区

发表评论

必填

选填

选填

必填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。