是否可以在运行时对系统调用设置钩子?在便携的方式,没有asm,也许是一些动态链接功能?我想拦截第三方图书馆的系统呼叫。不想使用LD_PRELOAD,它需要外部包装-启动程序脚本设置env。
发布于 2015-02-23 23:59:13
您可以通过重新定义函数来重写库调用:
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
void abort(void)
{
// If necessary, get a instance to the "real" function:
void (*real_abort)(void) = dlsym(RTLD_NEXT, "abort");
if (!real_abort) {
fpritnf(stderr, "Could not find real abort\n");
exit(1);
}
fprintf(stderr, "Calling abort\n");
real_abort();
}
带主
#include <stdlib.h>
int main(int argc, char** argv) {
abort();
}
其结果是:
$ ./a.out
Calling abort
Aborted
如果您想在运行时对一个独立的函数执行此操作(而不编译您自己的函数版本),您可以尝试使用ELF对象(可执行对象和共享对象)的重新定位信息,并在运行时更新重新定位。
让我们编译一个简单的地狱世界,看看它的重新定位:
$ LANG=C readelf -r ./a.out
Relocation section '.rela.dyn' at offset 0x348 contains 1 entries:
Offset Info Type Sym. Value Sym. Name + Addend
0000006008d8 000300000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0
Relocation section '.rela.plt' at offset 0x360 contains 3 entries:
Offset Info Type Sym. Value Sym. Name + Addend
0000006008f8 000100000007 R_X86_64_JUMP_SLO 0000000000000000 puts + 0
000000600900 000200000007 R_X86_64_JUMP_SLO 0000000000000000 __libc_start_main + 0
000000600908 000300000007 R_X86_64_JUMP_SLO 0000000000000000 __gmon_start__ + 0
这些是由动态链接器完成的重定位:.rela.plt
的第一行告诉动态链接器它需要在0x0000006008f8
为puts
符号设置一个puts
条目。为了覆盖put函数,我们可能会发现所有共享对象中的所有puts
符号,并将它们重新定位到合适的函数中。
https://stackoverflow.com/questions/28684681
复制相似问题