using wrap to mock internal shared library functions
Thanos Makatos
thanos.makatos@nutanix.com
Thu Nov 7 14:57:00 GMT 2019
I'm trying to use the wrap option to unit test a library. This is a shared library which I fully control however to simplify the problem I'm using static linking. The problem I have is that if library function bar calls library function foo, there's no way to call bar (from a test file) that calls a mocked version of foo. Consider the following example:
/* foo.h */
void foo(void);
void bar(void);
/* foo.c */
#include <stdio.h>
void __attribute__((weak)) foo(void) {
printf("called real foo\n");
}
void __attribute__((weak)) bar(void) {
printf("called real bar calling\n");
foo();
}
/* test.c */
#include <stdio.h>
#include <stdbool.h>
bool orig_foo, orig_bar;
void __wrap_foo(void) {
printf("in foo wrapper\n");
if (orig_foo)
__real_foo();
else
printf("called wrapped foo\n");
}
void __wrap_bar() {
printf("in bar wrapper\n");
if (orig_bar)
__real_bar();
else
printf("called wrapped bar\n");
}
int main(void) {
orig_bar = true;
orig_foo = false;
printf("calling foo from main\n");
foo();
printf("\n");
printf("calling bar from main\n");
bar();
return 0;
}
I compile as follows:
gcc -Wl,--wrap=foo -Wl,--wrap=bar test.c foo.c
And when I run it I get the following result:
# ./a.out
calling foo from main
in foo wrapper
called wrapped foo
calling bar from main
in bar wrapper
called real bar calling
called real foo
The last line printed "called real foo" is the problematic one: real bar calls real foo while I want the mocked one to be called. If I put foo and bar into separate files it works as desired. Why does this happen? I cannot move each library function into a separate file, is there a way to fix this?
PS: please CC me to your answer as I am not subscribed to this list
More information about the Gcc-help
mailing list