Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to replace a function in a library?

Tags:

c++

linux

g++

I work with a library which defines its internal division operator for a scripting language. Unfortunately it does not zero-check the divisor. Which leads to lot of headaches. I know the signature of the operator.

double ScriptClass::Divide(double&, double&);

Sadly it isn't even a C function. Is there any way I could make my application use my own Divide function instead of ScriptClass::Divide function?

EDIT: I was aware of dlopen(NULL,..) and replacing "C" functions with user defined ones. Can this be done for class member functions (Without resorting to using mangled names)?

like image 595
nakiya Avatar asked Nov 23 '10 14:11

nakiya


1 Answers

Generally speaking it's up to the programmer, not the underlying divide operator to prevent division by zero. If you're dividing by zero a lot that seems to indicate a possible flaw in the algorithm being used. Consider reworking the algorithm, or if that's not an option, guard calls to divide with a zero check. You could even do that inside a protected_divide type function.

All that being said, assuming that since it looks like a C++ function you have a C++ library compiled with all the same options you're using to build your application so name mangling matches you might be able to redefine the function into a .so and use LD_PRELOAD to force it to load. If you link statically, I think you can create the function into your own .o file and linking that prior to the library itself will cause the linker to pick up your version.

like image 190
Mark B Avatar answered Oct 03 '22 05:10

Mark B