c++ - Hijacking a function's implementation by linking another object file -


i've heard possible override / hijack / hack function's implementation linking against object file function resides in 1 authored. i've been playing around, , seems can work in 1 situation. however, wondering if it's possible achieve result (shown below) in other situations besides 1 described.

compiler used: tdm-gcc 4.9.2

os: windows 8 64-bit

the following describes situation hijacking "successful":

here's sample source called sample.cpp

#include <iostream>  int returnone();  int main() {     std::cout << "returnone() returns " << returnone();      return 0; } 

compilation:

g++ -c sample.cpp -o sample.o 

after checking object file nm.exe, function's mangled name is: __z9returnonev

so, off source hack.cpp:

extern "c" int _z9returnonev() {     return 5;  //rather return 1 } 

compilation:

g++ -c hack.cpp -o hack.o 

now "recreate" executable hack.o file:

g++ -wl,--allow-multiple-definition hack.o sample.o -o sample.exe 

when ran, sample.exe produces:

returnone() returns 5 

so hijack successful.

now, if @ point provide implementation of returnone() in original source, technique no longer works. in:

#include <iostream>  int returnone();  int main() {     std::cout << "returnone() returns " << returnone();      return 0; }  int returnone() {     return 1; } 

it compiles fine, when invoked, function uses original implementation every time.

so, i'm wondering if it's possible "hijack" function's implementation in fashion if it's implementation defined in original source, or possible if it's prototype defined?


edit (7/15/15):
compiled w/o optimizations, in:

g++ -wl,--allow-multiple-definition,-o0 hack.o sample.o -o sample.exe 

however, problem persists.


edit2 (7/15/15):
ok, cleaned, compiled , linked w/ -o0 switch:

g++ -o0 -c sample.cpp -o sample.o  g++ -o0 -c hack.cpp -o hack.o  g++ -wl,--allow-multiple-definition,-o0 hack.o sample.o -o sample.exe 

it's still returning 1.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -