title: Position independent code, shared libraries and code veneers - getting them to work together
body: <p>I'm developing for an embedded platform and I'm having a hard time working out how to link shared libraries dynamically. I'm using the bFLT file format and I don't have control over where the executable and shared library is loaded. </p>
  
  <p>My loader correctly loads the shared library and executable into memory and modifies the executable's GOT at run time to link to the shared library. </p>
  
  <p>I can successfully take the address of the function and I know it's correct from disassembling the code at that location. However, if I try to call the function, the whole thing crashes.</p>
  
  <p>Turns out GCC adds a 'code veneer' when calling shared library functions and takes a detour when the function is called and doesn't actually branch to the address of the function. The address that the code veneer branches to isn't relocated properly because it doesn't show up in the list of relocations in the executable binary.</p>
  
  <p>The disassembly of the veneer looks like this:</p>
  
  <pre><code>000008d0 &lt;__library_call_veneer&gt;:
   8d0:   e51ff004    ldr pc, [pc, #-4]   ; 8d4 &lt;__library_call_veneer+0x4&gt;
   8d4:   03000320    .word   0x03000320  ; This address isn't correctly relocated!
  </code></pre>
  
  <p>If I take the address of the function and put it into a function pointer (therefore, bypassing the 'code veneer') and call it, the shared library works perfectly.</p>
  
  <p>So for example:</p>
  
  <pre><code>#define DIRECT_LIB_CALL(x, args...) do { \
          typeof(x) * volatile tmp = x; \
          tmp(#args); \
      } while (0)
  
  DIRECT_LIB_CALL(library_call); /* works */
  library_call(); /* crashes */
  </code></pre>
  
  <p>Is there a way to either, tell GCC to not produce a code veneer and branch directly to the address located in the GOT or somehow make the address that the code veneer branches show up in the list of relocations to perform?</p>