Re: [gnome-love] Help - libc hooks



On Sat, 2008-05-24 at 22:28 +0300, Andrei Soare wrote:
On Sat, May 24, 2008 at 10:22 PM, Yu Feng <rainwoodman gmail com>
wrote:
        Thread safety?


This is the first time i have heard about this concept. I looked it up
on Wikipedia, but I don't know how to ensure thread safety :-s 
Your hooks has to be in a critical section when access global resources
in a multithread context. GLib has GMutex which can build a critical
section. I've never used them though.

An illustration for malloc-hook unsafety:

static void *
my_malloc_hook (size_t size, const void *caller)
{
  void *result;
 
  /* Restore all old hooks */
  __malloc_hook = old_malloc_hook;
  __free_hook = old_free_hook;
  __realloc_hook= old_realloc_hook;
 
  /* log_file */
  ensure_log_file ();
  fprintf(log_file, "malloc\n");
  fflush(log_file);
 
  /* Call recursively */

*********Suppose At this point another thread went to $$$$$$$$$$ code
  result = malloc (size);
 
  /* Save underlying hooks */
  old_malloc_hook = __malloc_hook;
  old_free_hook = __free_hook;
  old_realloc_hook= __realloc_hook;
 
  /* log_file */
  fprintf (log_file,"%p %lu\n", result, size);
  fflush(log_file);
 
  /* Restore our own hooks */
$$$$$$$$$$$ when a thread is in ******** code.
  __malloc_hook = my_malloc_hook;
  __free_hook = my_free_hook;
  __realloc_hook= my_realloc_hook;
 
  return result;
}

The hooked malloc will get recursively invoked. There might also be
other cases that damages the __malloc_hook you saved.

I was reading GCC's document to see if there is any built-in functions
for a critical section. Unfortunately there isn't.

There is TLS in gcc. They won't be helpful because the problem is a
competition over the shared variable __malloc_hook and its friends.


Yu
-- 
Andrei Soare




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]