如何在Linux上重新实现(或包装)syscall函数? [英] How do I reimplement (or wrap) a syscall function on Linux?

查看:147
本文介绍了如何在Linux上重新实现(或包装)syscall函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想完全接管open()系统调用,也许要包装实际的syscall并执行一些日志记录. 一种方法这是使用LD_PRELOAD 加载一个(用户制作的)共享对象库,该库将接管open()入口点.

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.

然后,用户制作的open()例程通过dlsym()对其进行调用并获取指向glibc函数open()的指针.

The user-made open() routine then obtains the pointer to the glibc function open() by dlsym()ing it, and calling it.

但是,以上提出的解决方案是动态解决方案.假设我想静态链接我自己的open()包装器.我该怎么办?我猜想机制是一样的,但是我也猜想用户定义的open()和libc open()之间会出现符号冲突.

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提供的包装功能.来自man ld:

You can use the wrap feature provided by ld. From man ld:

--wrap symbol对符号使用包装函数.任何未定义的引用 symbol将解析为__wrap_symbol.

--wrap symbol Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to __wrap_symbol.

任何对__real_symbol的未定义引用都将解析为symbol.

Any undefined reference to __real_symbol will be resolved to symbol.

因此,您只需为包装函数使用前缀__wrap_,并在要调用实函数时使用__real_.一个简单的例子是:

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;
}

然后编译应用程序:

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上重新实现(或包装)syscall函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆