简体   繁体   中英

LD_PRELOAD help

I'm trying to use LD_PRELOAD.

original.cpp

void myPuts() {  
    puts ("Hello myPuts");  
}  
int main() {  
    myPuts();  
    return 0;  
}

hacked.cpp

void myPuts() {  
    std::cout >> "Hello hacked myPuts";  
}

I compile original.cpp:

g++ original.cpp

And hacked.cpp:

g++ -shared -fPIC hacked.cpp

I try:

LD_PRELOAD=./hacked.so ./original.out

The string "Hello hacked myPuts" should be seen, by "Hello myPuts" appears. (If I try to "overwrite" the puts function, it works correctly)

What am I missing?

From man ld.so

LD_PRELOAD

A whitespace-separated list of additional, user-specified, ELF shared libraries to be loaded before all others. This can be used to selectively override functions in other shared libraries .

If myPuts was in shared library linked to main application it would work, but not when myPuts exists in the application and does not resolved in an external library.

You should have:

main.cpp

int main() {  
    myPuts();  
    return 0;  
}

original.cpp

void myPuts() {  
    puts ("Hello myPuts");  
}  

hacked.cpp

void myPuts() {  
    std::cout << "Hello hacked myPuts";  
}

Compiling all:

g++ -shared -fPIC original.cpp -o liboriginal.so
g++ -shared -fPIC hacked.cpp -o libhacked.so
g++ main.cpp -loriginal -o main.out

And using:

LD_PRELOAD=./libhacked.so ./main.out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM