title: Run-time mocking in C?
body: <p>This has been pending for a long time in my list now. In brief - I need to run <code>mocked_dummy()</code> in the place of <code>dummy()</code> <strong>ON RUN-TIME</strong>, without modifying <code>factorial()</code>. I do not care on the entry point of the software. I can add up any number of additional functions (but cannot modify code within <code>/*---- do not modify ----*/</code>). </p>
  
  <p>Why do I need this?<br>
  To do unit tests of some legacy C modules. I know there are a lot of tools available around, but if run-time mocking is possible I can change my UT approach (add reusable components) make my life easier :).</p>
  
  <p>Platform / Environment?<br>
  Linux, ARM, gcc.</p>
  
  <p>Approach that I'm trying with?  </p>
  
  <ul>
  <li>I know GDB uses trap/illegal instructions for adding up breakpoints (<a href="http://www.gnuarm.com/pdf/gdbint.pdf" rel="noreferrer">gdb internals</a>). </li>
  <li>Make the code self modifiable.</li>
  <li>Replace <code>dummy()</code> code segment with illegal instruction, and <strong>return</strong> as immediate next instruction.</li>
  <li>Control transfers to trap handler. </li>
  <li>Trap handler is a reusable function that reads from a unix domain socket.</li>
  <li>Address of <code>mocked_dummy()</code> function is passed (read from map file).</li>
  <li>Mock function executes.</li>
  </ul>
  
  <p>There are problems going ahead from here. I also found the approach is tedious and requires good amount of coding, some in assembly too.</p>
  
  <p>I also found, under gcc each function call can be <a href="http://balau82.wordpress.com/2010/10/06/trace-and-profile-function-calls-with-gcc" rel="noreferrer">hooked / instrumented</a>, but again not very useful since the the function is intended to be mocked will anyway get executed.</p>
  
  <p>Is there any other approach that I could use?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void mocked_dummy(void)
  {
      printf("__%s__()\n",__func__);
  }
  
  /*---- do not modify ----*/
  void dummy(void)
  {
      printf("__%s__()\n",__func__);
  }
  
  int factorial(int num) 
  {
      int                      fact = 1;
      printf("__%s__()\n",__func__);
      while (num &gt; 1)
      {
          fact *= num;
          num--;
      }
      dummy();
      return fact;
  }
  /*---- do not modify ----*/
  
  int main(int argc, char * argv[])
  {
      int (*fp)(int) = atoi(argv[1]);
      printf("fp = %x\n",fp);
      printf("factorial of 5 is = %d\n",fp(5));
      printf("factorial of 5 is = %d\n",factorial(5));
      return 1;
  }
  </code></pre>