如何用--wrap选项正确包装函数? [英] How to wrap functions with the `--wrap` option correctly?
问题描述
gcc 6.3的手册页说:
The man page of gcc 6.3 says:
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to
symbol will be resolved to "__wrap_symbol". Any undefined
reference to "__real_symbol" will be resolved to symbol.
...
If you link other code with this file using --wrap malloc, then all
calls to "malloc" will call the function "__wrap_malloc" instead.
The call to "__real_malloc" in "__wrap_malloc" will call the real
"malloc" function.
因此,我创建了一个简单的示例:
So I created a simple example:
#include <stdio.h>
int foo() {
printf("foo\n");
return 0;
}
int __wrap_foo() {
printf("wrap foo\n");
return 0;
}
int main () {
printf("foo:");foo();
printf("wrapfoo:");__wrap_foo();
printf("realfoo:");__real_foo();
return 0;
}
并使用以下代码进行编译:
And compiled it with:
gcc main.c -Wl,--wrap=foo -o main
这给了我一个警告:
main.c:18:21: warning: implicit declaration of function ‘__real_foo’ [-Wimplicit-function-declaration]
printf("realfoo:");__real_foo();
^~~~~~~~~~
好吧.现在,我建议这样的输出:
Well going on. Now I would suggest an output like this:
foo:wrap foo
wrapfoo:wrap foo
realfoo:foo
相反,我得到了:
foo:foo
wrapfoo:wrap foo
realfoo:foo
我希望事情已经清楚了.我对警告感到困惑.通常,链接器应将__real
函数链接到foo()
.此外,对foo()
的调用应链接到__wrap_foo
.但是输出显示,正在执行foo()
代替.
I hope the thing is clear. I am confused about the warning. Normally the __real
function should be linked by the linker to foo()
. Furthermore a call to foo()
should be linked to __wrap_foo
. But the output showes, that foo()
is being executed instead.
如何正确使用--wrap
?
推荐答案
正如StoryTeller告诉我的那样,我忽略了上面已经发布的未定义引用"要求:
As StoryTeller told me, I ignored the "undefined reference" requirement which I already posted above:
...对符号的任何未定义引用都将解析为"__wrap_symbol".任何对"__real_symbol"的未定义引用都将解析为符号.
... Any undefined reference to symbol will be resolved to "__wrap_symbol". Any undefined reference to "__real_symbol" will be resolved to symbol.
要使用--wrap
选项,我重新排列了代码示例,如下所示:
To use the --wrap
option I rearranged my code example like this:
main.c:
#include <stdio.h>
extern int foo();
extern int __real_foo();
int __wrap_foo() {
printf("wrap foo\n");
return 0;
}
int main () {
printf("foo:");foo();
printf("wrapfoo:");__wrap_foo();
printf("realfoo:");__real_foo();
return 0;
}
foo.c:
#include <stdio.h>
int foo() {
printf("foo\n");
return 0;
}
然后编译:
gcc main.c foo.c -Wl,--wrap=foo -o main
运行./main
之后的惊人输出:
foo:wrap foo
wrapfoo:wrap foo
realfoo:foo
技巧是(如果我错了,请纠正我)是在编译时未定义foo()
和__real_foo()
的引用. I. E.他们有** undefined reference,这是链接器将foo()
链接到__wrap_foo()
和__real_foo()
链接到foo()
的要求.
The trick is (correct me if I am wrong) that the reference of foo()
and __real_foo()
is not defined at compile time. I. E. they have **undefined references" which is the requierement for the linker to link foo()
to __wrap_foo()
and __real_foo()
to foo()
.
这篇关于如何用--wrap选项正确包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!