krisy
krisy

Reputation: 43

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?

Upvotes: 3

Views: 1485

Answers (2)

Didier Trosset
Didier Trosset

Reputation: 37427

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

Upvotes: 3

Artyom
Artyom

Reputation: 31233

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.

Upvotes: 6

Related Questions