Skip to content

Instantly share code, notes, and snippets.

@ytlvy
Created October 7, 2015 13:06
Show Gist options
  • Save ytlvy/db42fdd7b2a6b5f24862 to your computer and use it in GitHub Desktop.
Save ytlvy/db42fdd7b2a6b5f24862 to your computer and use it in GitHub Desktop.
利用 DYLD_INTERPOSE 宏 完成OS X系统函数hook
// 演示代码
// #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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment