public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* using wrap to mock internal shared library functions
@ 2019-11-07 14:57 Thanos Makatos
  0 siblings, 0 replies; only message in thread
From: Thanos Makatos @ 2019-11-07 14:57 UTC (permalink / raw)
  To: gcc-help

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

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2019-11-07 14:57 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2019-11-07 14:57 using wrap to mock internal shared library functions Thanos Makatos

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).