5

I want to rewrite object files so that most of the functions' addresses are altered to a no-op function. How can I do this?

More context: In C++ I want to auto-mock all functions by default. To go from having a() call a() {} and b() call b() {} to having a() really call replacement() {} and to have b() also call (the same) replacement() {}.

Things I've considered so far:

  • objcopy --redefine-syms=filename - this changes the name of a symbol, not the address of it.
  • Using the linker's --wrap argument - this requires compiling a distinct symbol __wrap_NameOfWrappedThing for each thing I want to wrap, and in general doesn't look like it'd scale nicely.
Mark
  • 3,806
  • 3
  • 21
  • 32
  • If using GCC or clang - have you tried [`__attribute__((weak))`](http://www.valvers.com/programming/c/gcc-weak-function-attributes/)? – Aconcagua Apr 19 '17 at 06:03
  • @AConcagua - That requires a code change. My goal is to require no code changes, as I'd like to do this for all symbols. – Mark Apr 19 '17 at 06:08
  • Your --wrap approach might not replace all calls [either](http://stackoverflow.com/questions/13961774/gnu-gcc-ld-wrapping-a-call-to-symbol-with-caller-and-callee-defined-in-the-sam) - they do not seem to have found a solution there yet. – Aconcagua Apr 19 '17 at 06:19
  • Found a solution that's in the right ballpark: `objcopy --localize-symbols` can turn calls to "auto-mocked" functions into linker errors. – Mark Apr 19 '17 at 07:40
  • One thing I did not account for when considering an approach that alters object files is that inline functions can't be mocked in this way. This approach is fundamentally flawed. – Mark Apr 19 '17 at 20:48
  • Hm - even if you decided to change code - as far as I know, weak attribute cannot be applied to inline functions either... Get more and more the impression that modifying the code itself is the easier solution, e. g. like this: `#if defined USE_MOCK && !defined UNMOCK_A`. You could then control the behaviour via compiler flags (-D)... – Aconcagua Apr 20 '17 at 08:12

0 Answers0