title: Why does the linker modify a --defsym "absolute address"
body: <p>Goal: a shared library to use a function from an executable (which does not export symbols).</p>
  
  <p>Means: <code>gcc -Wl,--defsym,function=0x432238</code></p>
  
  <p>The man page states that:</p>
  
  <pre><code>"--defsym symbol=expression" Create a global symbol in the output
  file, containing the absolute address given by expression.
  </code></pre>
  
  <p>To my dismay, <code>dlopen()</code> is adding <code>0x7ffff676f000</code>, the shared library's base address (this is 64-bit code) to the exported "absolute symbol address":</p>
  
  <pre><code>        executable        shared library
          ---------- linker --------------
  symbol: 0x432238   =====&gt; 0x7ffff6ba1238
  </code></pre>
  
  <p>objdump shows the correct symbol address (<code>0x432238</code>) in the library, but once loaded with <code>dlopen()</code>, the symbol has address <code>0x7ffff6ba1238</code>.</p>
  
  <p>If, once loaded, I manually patch the library symbol to the correct address then all works fine (else, the library SEGFAULTs).</p>
  
  <ul>
  <li>Why the "absolute address" is modified?</li>
  <li>How to avoid it?</li>
  </ul>
  
  <p><strong>Update:</strong></p>
  
  <p><em>I contest the technical relevance of the reply below, and, even more its 'update':</em></p>
  
  <p>Having --defsym to define a relocated symbol in a PIC library/executable is pointless (it does not serve ANY purpose other than polluting the binary without any usable feature).</p>
  
  <p>Therefore, the only relevant use of --defsym in a PIC shared library or PIC executable should be to define a (<em>non-relocated</em>) "absolute address".</p>
  
  <p>Incidentally, that's the official purpose of --defsym if you bother to read the man page:</p>
  
  <p><em>"Create a global symbol in the output file, containing the <code>absolute address</code> given by expression."</em></p>
  
  <p>At best, this is a Linux linker deffect which would be trivial to fix. And for those who can't wait for the people-in-denial to realize (and fix) their mistake, the solution is to patch the relocation table after the binary image has been loaded by the defective linker.</p>
  
  <p>Then, --defsym becomes useful in PIC libraries/executables, which seems to me is a welcome progress.</p>