Loki Astari
Loki Astari

Reputation: 264621

g++/clang override linker for specific functions

Is there a simple way to specify alternative functions (to the linker) to be used rather than the standard ones?

I have a wrapper around open/close/read/write system functions. I can test the functionality of the good path for these functions relatively easily.

But testing the potential errors is harder. To do this I need to get open/close/read/write to generate specific error codes for each test. Is there a way to link in alternative versions of these functions that I can then program to set the appropriate errno value before returning?

Upvotes: 4

Views: 1025

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61550

The linker option --wrap is for this purpose.

Some code that calls 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;
}

For simplicity it's a program, but it needn't be.

Using the true open:

$ gcc -Wall -c main.c
$ gcc -o prog main.o
$ echo "Hello world" > hw.txt
$ ./prog hw.txt 
Hello world

Your alternative open must be called __wrap_open, and must refer to the real open, if it needs to, as __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);
}

There's no need to recompile main.c to replace open with __wrap_open in prog; just reuse main.o in a different linkage of prog

$ 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

If your __wrap_foo alternatives needed to knock out C++ functions foo then you would need to obtain the mangling of foo to specify in the linkage option --wrap=mangled-foo. But since you want to knock out system calls you're spared that complication.

Upvotes: 6

Related Questions