1

I am studying how to hook a self-defined function through dynamical linking using LD_PRELOAD.

However, most of the tutorials try to hook a libc function, e.g. puts(). Is it possible to hook a self-defined function, too?

I am trying the following code

//test.c

#include <stdio.h>      

int ptest(){ 
    printf("test!\n"); 

    return 0;
}  

int main(void){ 
    printf("%d\n", ptest()); 

    return 0;
}   
//hook.c
//compile: "gcc hook.c -shared -fPIC -Wall -o hook.so"

#include <stdio.h>      

int ptest(){
    printf("fake!\n");

    return 1; 
}

run

LD_PRELOAD=./hook.so ./test

Result (It means nothing changed by hook.so)

test!
0

What I expect

fake!
1
desionxxx
  • 21
  • 3
  • 1
    I don't think you can hook a function that's built into the actual program - it would have to be a linked library for it to work as you expect. – fredrik Apr 14 '21 at 08:58
  • A function defined as part of the actual program (not dynamically linked from a different library) is not even guaranteed to exist at all, it may have been inlined by the compiler. And even if not the calls are usually translated as fixed memory addresses (or address offsets) or labels, so you'd need to hack the binary to change which address is being used – UnholySheep Apr 14 '21 at 09:04
  • 1
    You're mixing dynamical linking and static linking. The function `ptest` in `test.c` is linked statically because it is in the same file and compiled together with main into the same object file, whereas you try to link the `ptest` from `hook.c` dynamically. That can't work. You should remove the `ptest` function from main and put it into it's own file. Then you can specify the function you want to link with the command `LD_PRELOAD=./hook{1|2}.so ./test`. – Wör Du Schnaffzig Apr 14 '21 at 09:08
  • I don't know what `hook.so` is really doing, but I would assume that you have to export your function, if it is to be hooked. Otherwise I don't see how it should know what it should hook to. https://stackoverflow.com/questions/52719364/how-to-use-the-attribute-visibilitydefault – Devolus Apr 14 '21 at 09:11
  • `function through dynamical linking` but `./test` is not dynamically linked. – KamilCuk Apr 15 '21 at 01:01

0 Answers0