0

This is probably going to be embarrassing:

I am using library prelaoding in other projects, but I cannot get this minimal example to work:

weakref.h:

void f_weak() __attribute__((weak));

weakref.c:

#include <stdio.h>
#include "weakref.h"

void f_weak(){
    printf("f_weak()\n");
    fflush(stdout);
}

test_weakref.c:

#include <stdio.h>
#include "weakref.h"

int main(void)
{
    if (f_weak) {
        printf("main: f_weak()\n");
    }
    else {
        printf("main: ---\n");
    }

    fflush(stdout);
    return 0;
}

Here is what I do:

$ gcc weakref.c -shared -fPIC -o libweakref.so
$ nm libweakref.so | grep f_weak
0000000000000708 W f_weak
$ gcc test_weakref.c -o test_weakref
$ ./test_weakref
main: ---
$ LD_PRELOAD=./libweakref.so ./test_weakref
main: ---

The expected output of the last command is

main: f_weak()

What am I missing?

steffen
  • 7,380
  • 8
  • 40
  • 78

2 Answers2

0

As far as I know, external functions are resolved only when you call them. So, your test if (f_weak) will always fail. If you do it the following way, you can see that it works:

weakref.c:

#include <stdio.h>
#include "weakref.h"

void f_weak(){
   printf("original\n");
   fflush(stdout);
}

weak2.c:

#include <stdio.h>
#include "weakref.h"

void f_weak(){
   printf("overridden\n");
   fflush(stdout);
}

test_weakref.c:

#include <stdio.h>
#include "weakref.h"

int main(void)
{
  f_weak();
  fflush(stdout);
  return 0;
}

and then:

tmp> gcc weakref.c -shared -fPIC -o libweakref.so
tmp> gcc weak2.c -shared -fPIC -o libweak2.so
tmp> gcc -o test_weakref test_weakref.c ./libweakref.so 
tmp> ./test_weakref 
original
tmp> LD_PRELOAD=./libweak2.so !.
LD_PRELOAD=./libweak2.so ./test_weakref 
overridden
dodo
  • 152
  • 5
0

I found the solution in an old Makefile: the program has also to be compiled with the -fPIC flag.

$ gcc weakref.c -shared -fPIC -o libweakref.so
$ nm libweakref.so | grep f_weak
0000000000000708 W f_weak
$ gcc test_weakref.c -o test_weakref -fPIC
$ ./test_weakref
main: ---
$ LD_PRELOAD=./libweakref.so ./test_weakref
main: f_weak()
steffen
  • 7,380
  • 8
  • 40
  • 78