title: using glibc malloc hooks in a thread safe manner
body: <p>I would like to monitor the use of mallocs and frees in an application by using the malloc and free hooks.</p>
  
  <p>Here's the documentation <a href="http://www.gnu.org/s/libc/manual/html_node/Hooks-for-Malloc.html" rel="nofollow noreferrer">http://www.gnu.org/s/libc/manual/html_node/Hooks-for-Malloc.html</a></p>
  
  <p>From the example page you can see that <code>my_malloc_hook</code> transiently switches the malloc hook off (or to the previous hook in the chain) before re-invoking malloc.</p>
  
  <p>This is a problem when monitoring multi-threaded applications (see end of question for explanation).</p>
  
  <p>Other examples of the use of malloc hook that I have found on the internet have the same problem.</p>
  
  <p>Is there a way to re-write this function to work correctly in a multi-threaded application?</p>
  
  <p>For instance, is there an internal libc function that the malloc hook can invoke that completes the allocation, without the need to deactivate my hook.</p>
  
  <p>I can't look at the libc source code due to corporate legal policy, so the answer may be obvious.</p>
  
  <p>My design spec says I cannot replace malloc with a different malloc design.</p>
  
  <p>I can assume that no other hooks are in play.</p>
  
  <hr>
  
  <p>UPDATE</p>
  
  <p>Since the malloc hook is temporarily removed while servicing the malloc, another thread may call malloc and NOT get the hook.</p>
  
  <p>It has been suggested that malloc has a big lock around it that prevents this from happening, but it's not documented, and the fact that I effectively recursively call malloc suggests any lock must either exist after the hook, or be jolly clever:</p>
  
  <pre><code>caller -&gt; 
    malloc -&gt; 
      malloc-hook (disables hook) -&gt; 
        malloc -&gt; # possible hazard starts here
          malloc_internals
        malloc &lt;-
      malloc-hook (enables hook) &lt;-
    malloc
  caller
  </code></pre>