Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding C library functions, calling original

Tags:

c

gcc

I am a bit puzzled on how and why this code works as it does. I have not actually encountered this in any project I've worked on, and I have not even thought of doing it myself.

override_getline.c:

#include <stdio.h>

#define OVERRIDE_GETLINE

#ifdef OVERRIDE_GETLINE
ssize_t getline(char **lineptr, size_t *n, FILE *stream)
{
    printf("getline &lineptr=%p &n=%p &stream=%p\n", lineptr, n, stream);
    return -1; // note: errno has undefined value
}
#endif

main.c:

#include <stdio.h>

int main()
{
    char *buf = NULL;
    size_t len = 0;
    printf("Hello World! %zd\n", getline(&buf, &len, stdin));
    return 0;
}

And finally, example compile and run command:

gcc main.c override_getline.c && ./a.out

With the OVERRIDE_GETLINE define, the custom function gets called, and if it is commented out, normal library function gets called, and both work as expected.

Questions

  1. What is the correct term for this? "Overriding", "shadowing", something else?

  2. Is this gcc-specific, or POSIX, or ANSI C, or even undefined in all?

  3. Does it make any difference if function is ANSI C function or (like here) a POSIX function?

  4. Where does the overriding function get called? By other .o files in the same linking, at least, and I presume .a files added to link command too. How about static or dynamic libs added with -l command line option of linker?

  5. If it is possible, how do I call the library version of getline from the overriden getline?

like image 700
hyde Avatar asked Sep 26 '13 08:09

hyde


1 Answers

The linker will search the files you provide on the command line first for symbols, before it searches in libraries. This means that as soon as it sees that getline has been defined, it will no longer look for another getline symbol. This is how linkers works on all platforms.

This of course has implications for your fifth point, in that there is no possibility to call the "original" getline, as your function is the original from the point of view of the linker.

For the fifth point, you may want to look at e.g. this old answer.

like image 133
Some programmer dude Avatar answered Oct 01 '22 02:10

Some programmer dude