如何重新实现(或包裹)在Linux系统调用函数? [英] How to reimplement (or wrap) a syscall function in linux?
问题描述
假设我要完全接管的open()系统调用,也许包裹的实际系统调用和执行一些记录。 <一href=\"http://scaryreasoner.word$p$pss.com/2007/11/17/using-ld_$p$pload-libraries-and-glibc-backtrace-function-for-debugging/\">One办法做到这一点是使用LD_ preLOAD 加载(用户制作)共享对象库接管的open()入口点。
然后,用户自制的open()函数获取的指针glibc的功能的open()
按则dlsym()
ING它,并调用它。
Suppose I want to completely take over the open() system call, maybe to wrap the actual syscall and perform some logging. One way to do this is to use LD_PRELOAD to load a (user-made) shared object library that takes over the open() entry point.
The user-made open() routine then obtain the pointer to the glibc function open()
by dlsym()
ing it, and calling it.
上面提出的解决方案是一个动态的解决方案,但是。假设我想静态链接我自己的的open()
包装。我会怎么做呢?我猜的机制是相同的,但我也想会有之间的符号冲突的用户定义的的open()
和libc的打开( )
。
The solution proposed above is a dynamic solution, however. Suppose I want to link my own open()
wrapper statically. How would I do it ? I guess the mechanism is the same, but I also guess there will be a symbol clash between the user-defined open()
and the libc open()
.
请分享任何其它技术来达到同样的目的。
Please share any other techniques to achieve the same goal.
推荐答案
您可以使用 LD
提供的换行功能。从男人LD
:
You can use the wrap feature provided by ld
. From man ld
:
- 包装符号
使用符号的包装功能。任何未定义的引用
符号
将被解析为 __ wrap_symbol
。
--wrap symbol
Use a wrapper function for symbol. Any undefined reference tosymbol
will be resolved to__wrap_symbol
.
任何未定义的引用 __ real_symbol
将被解析为符号
。
Any undefined reference to __real_symbol
will be resolved to symbol
.
所以,你只需要使用preFIX __包_
为您的包装功能和 __真正_当你想
调用的真正功能。一个简单的例子是:
So you just have to use the prefix __wrap_
for your wrapper function and __real_
when you want to call the real function. A simple example is:
malloc_wrapper.c
:
#include <stdio.h>
void *__real_malloc (size_t);
/* This function wraps the real malloc */
void * __wrap_malloc (size_t size)
{
void *lptr = __real_malloc(size);
printf("Malloc: %lu bytes @%p\n", size, lptr);
return lptr;
}
测试应用程序 testapp.c
:
#include <stdio.h>
#include <stdlib.h>
int main()
{
free(malloc(1024)); // malloc will resolve to __wrap_malloc
return 0;
}
然后编译应用程序:
Then compile the application:
gcc -c malloc_wrapper.c
gcc -c testapp.c
gcc -Wl,-wrap,malloc testapp.o malloc_wrapper.o -o testapp
生成的应用程序的输出将是:
The output of the resulting application will be:
$ ./testapp
Malloc: 1024 bytes @0x20d8010
这篇关于如何重新实现(或包裹)在Linux系统调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!