【发布时间】:2018-04-12 22:19:20
【问题描述】:
有没有一种简单的方法来指定要使用的替代函数(链接器)而不是标准函数?
我有一个围绕打开/关闭/读/写系统函数的包装器。我可以相对容易地测试这些功能的好路径的功能。
但测试潜在错误更难。为此,我需要打开/关闭/读取/写入来为每个测试生成特定的错误代码。有没有办法链接这些函数的替代版本,然后我可以编程以在返回之前设置适当的 errno 值?
【问题讨论】:
有没有一种简单的方法来指定要使用的替代函数(链接器)而不是标准函数?
我有一个围绕打开/关闭/读/写系统函数的包装器。我可以相对容易地测试这些功能的好路径的功能。
但测试潜在错误更难。为此,我需要打开/关闭/读取/写入来为每个测试生成特定的错误代码。有没有办法链接这些函数的替代版本,然后我可以编程以在返回之前设置适当的 errno 值?
【问题讨论】:
链接器选项--wrap 就是为此目的。
一些调用open的代码:-
main.c
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#define N 32
int main(int argc, char *argv[])
{
char buf[N] = {0};
int fd = open(argv[1],O_RDONLY);
read(fd,buf,N - 1);
puts(buf);
close(fd);
return 0;
}
为简单起见,它是一个程序,但不一定是。
使用真正的open:
$ gcc -Wall -c main.c
$ gcc -o prog main.o
$ echo "Hello world" > hw.txt
$ ./prog hw.txt
Hello world
您的替代open 必须称为__wrap_open,并且
一定要引用真实的open,如果需要,如__real_open:
dbg_open.c
#include <stdio.h>
extern int __real_open(const char *path, int oflag);
int __wrap_open(const char *path, int oflag)
{
printf("In tester %s\n",__FUNCTION__);
return __real_open(path,oflag);
}
无需重新编译main.c,将prog中的open替换为__wrap_open;只是
在prog 的不同链接中重用main.o
$ gcc -Wall -c dbg_open.c
$ gcc -o prog main.o dbg_open.o -Wl,--wrap=open
$ ./prog hw.txt
In tester __wrap_open
Hello world
如果您的 __wrap_foo 替代方案需要淘汰 C++ 函数
foo 那么你需要获得foo 的修改以在链接中指定
选项--wrap=mangled-foo。但是既然你想淘汰系统调用
您可以避免这种复杂情况。
【讨论】: