[uClibc]uClibc fix for bug in __compare_and_swap, and other stuff

Nathan Field ndf at ghs.com
Thu Jan 23 00:57:35 UTC 2003


	I've been trying to get thread debugging working with uClibc for a
while now, and I've come across a ton of uClibc bugs. I've also found that
pthread_mutex_lock/pthread_mutex_unlock don't work. I've attached a C
program (lock_break.c) that shows this bug when run on a Broadcom 7320
board running uClibc 0.9.15. After about 10 seconds it should have printed
out error messages showing that the critical section has not been guarded.  
To put it mildly, this is a serious bug. :)

	The attached pt-machine.h contains a patched version of the
__compare_and_swap inline function. This fix makes
__pthread_lock/__pthread_unlock work, which is the foundation of numerous
internal libpthread operations (used extensivly during debugging), as well
as the externally accessable pthread_mutex_lock/pthread_mutex_unlock. 
Actually, it might be used all over uClibc, but I was only working on 
getting pthread debugging to work.

	At the end of the file in comments you will find a description of 
what each line of assembly code does, as well as a comment on the line I 
changed. Basically whoever wrote this function forgot that mips has a 
branch delay slot.

	There are several other modifications that I made to the
distribution specific to pthread debugging. I'm not really sure what
format you want, so I've attached all of the relavent files along with a
standard "diff -U 2 origfile myfile" format with a summary of what the
change is for. If there is another format that is preferred just let me
know. You can also search the attached files for "[NDF]" to see where my 
changes are.

	Here are the changes:

libpthread/linuxthreads/sysdeps/mips/pt-machine.h:
	* fix __compare_and_swap
--- 
/export/ndf/src/uClibc-0.9.15_orig/libpthread/linuxthreads/sysdeps/mips/pt-machine.h        
2002-02-20 01:18:48.000000000 -0800
+++ pt-machine.h        2002-12-17 15:55:06.000000000 -0800
@@ -78,4 +78,5 @@
        ".set\tnoreorder\n\t"
        "bne\t%0,%2,2f\n\t"
+       "move\t%0,$0\n\t" /*[NDF] Failure case. */
        "move\t%0,%3\n\t"
        ".set\treorder\n\t"
@@ -88,3 +89,29 @@

   return ret;
+
+  /*
+    1:  load locked: into ret(%0), from *p(0(%4))
+        branch to 2 if ret(%0) != oldval(%2)
+         Delay slot: move 0 into ret(%0) // [NDF] Added
+       Don't branch case:
+       move newval(%3) into ret(%0)
+       setcompare ret(%0) into *p(0(%1))
+       branch to 1 if ret(%0) == 0 (sc failed)
+         Delay slot: unknown/none
+       return
+
+    2: Delay slot
+       return
+
+ll a b
+Sets a to the value pointed to by address b, and "locks" b so that if
+any of a number of things are attempted that might access b then the
+next sc will fail.
+
+sc a b
+Sets the memory address pointed to by b to the value in a atomically.
+If it succeeds then a will be set to 1, if it fails a will be set to 0.
+
+  */
+
 }


libpthread/linuxthreads/manager.c:
	* fix pthread_handle_create so it doesn't call clone twice under a 
debugger (I reported this fix earlier)
	* added a couple of variables which the uClibc provided 
libthread_db library believes are present in the libpthread library
--- /export/ndf/src/uClibc-0.9.15_orig/libpthread/linuxthreads/manager.c        
2002-02-20 01:18:44.000000000
-0800
+++ manager.c   2003-01-22 16:37:09.000000000 -0800
@@ -47,4 +47,9 @@
 const int __linuxthreads_pthread_threads_max = PTHREAD_THREADS_MAX;

+/* [NDF] For debugging purposes put the size of the pthread_descr in a
+ * variable. */
+const int __linuxthreads_pthread_sizeof_descr
+  = sizeof(struct _pthread_descr_struct);
+
 /* Indicate whether at least one thread has a user-defined stack (if 1),
    or if all threads have stacks supplied by LinuxThreads (if 0). */
@@ -529,9 +534,13 @@
        }
     }
-  if (pid == 0)
+
+  /* [NDF] Someone forgot a { } pair. */
+
+  if (pid == 0) { /* [NDF] Added opening brace. */
 PDEBUG("cloning new_thread = %p\n", new_thread);
     pid = clone(pthread_start_thread, (void **) new_thread,
                  CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
                  __pthread_sig_cancel, new_thread);
+  } /* [NDF] Added closing brace. */
   /* Check if cloning succeeded */
   if (pid == -1) {


libpthread/linuxthreads/pthread.c:
	* fix __pthread_initialize_manager so it locks before calling 
clone when under a debugger (I submitted this earlier)
	* fix __pthread_initialize_manager so it unlocks on success or
failure of clone when under a debugger (I submitted this earlier)
--- /export/ndf/src/uClibc-0.9.15_orig/libpthread/linuxthreads/pthread.c        
2002-08-19 03:05:03.000000000
-0700
+++ pthread.c   2003-01-22 16:39:28.000000000 -0800
@@ -385,4 +385,8 @@
          != 0)
        {
+
+         /* [NDF] Added lock here. */
+         __pthread_lock(__pthread_manager_thread.p_lock, NULL);
+
          pid = clone(__pthread_manager_event,
                        (void **) __pthread_manager_thread_tos,
@@ -406,7 +410,12 @@
              __linuxthreads_create_event ();

-             /* Now restart the thread.  */
-             __pthread_unlock(__pthread_manager_thread.p_lock);
+             /* [NDF] Moved lock from here... */
+
            }
+
+         /* [NDF] to here. */
+         /* Now restart the thread.  */
+         __pthread_unlock(__pthread_manager_thread.p_lock);
+
        }
     }



libpthread/linuxthreads/specific.c:
	* added a variable which the uClibc provided libthread_db library 
believes are present in the libpthread library
--- /export/ndf/src/uClibc-0.9.15_orig/libpthread/linuxthreads/specific.c       
2002-08-06 07:49:12.000000000
-0700
+++ specific.c  2002-12-16 16:39:46.000000000 -0800
@@ -28,4 +28,8 @@
   { { 0, NULL } };

+/* [NDF] For debugging purposes put the maximum number of keys in a
+ * variable. */
+const int __linuxthreads_pthread_keys_max = PTHREAD_KEYS_MAX;
+
 /* Mutex to protect access to pthread_keys */


libpthread/linuxthreads_db/td_symbol_list.c:
	* the libthread_db library was searching for the wrong symbol 
name. This is a bit of a hack to support debugging different builds of the 
libpthread library. Since uClibc is not binary compatible at the moment it 
is probably best to simply fix the name in the correct place rather than 
do this. However, here's what I did:
--- 
/export/ndf/src/uClibc-0.9.15_orig/libpthread/linuxthreads_db/td_symbol_list.c      
2002-08-08 01:47:17.000000000 -0700
+++ td_symbol_list.c    2002-12-16 16:40:10.000000000 -0800
@@ -51,4 +51,10 @@
 {
   assert (idx >= 0 && idx < NUM_MESSAGES);
-  return ps_pglobal_lookup (ps, LIBPTHREAD_SO, symbol_list_arr[idx], 
sym_addr);
+  int ret = ps_pglobal_lookup (ps, LIBPTHREAD_SO, symbol_list_arr[idx], 
sym_addr);
+  if( (ret == TD_ERR) && (idx == LINUXTHREADS_PTHREAD_THREADS_MAX) ) {
+      /* [NDF] I believe in uClibc this variable is actually known by
+       * __pthread_threads_max, try searching for that instead. */
+      ret = ps_pglobal_lookup (ps, LIBPTHREAD_SO, 
"__pthread_threads_max", sym_addr);
+  }
+  return ret;
 }

	nathan

--
Nathan Field (ndf at ghs.com)

        A number of years ago, the Dali Lama visited the United States. As
part of his travels, he visited the headquarters in Chicago of one of the
great American news magazines. He was given the Cook's tour, and then
there was a grand formal lunch at which the various exectives of the
enterprise pontificated ad nauseum. The Dali Lama - an elfin man - sat
swathed in his saffron robe, an inscrutable smile on his face, saying
nothing. After about an hour, the CEO of the publishing company turned to
the Dali Lama and said, "Do you have any questions about our magazine, the
nation's premiere news magazine? Go ahead, ask us anything at all." The
Dali Lama bowed his head for a moment, apparently deep in thought. Then he
looked up and said, "Why do you publish it?"
        -- Steven G. Krantz, from a review of Stephen Wolframs new book
-------------- next part --------------
/* Machine-dependent pthreads configuration and inline functions.

   Copyright (C) 1996, 1997, 1998 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Contributed by Ralf Baechle <ralf at gnu.ai.mit.edu>.
   Based on the Alpha version by Richard Henderson <rth at tamu.edu>.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with the GNU C Library; see the file COPYING.LIB.  If
   not, write to the Free Software Foundation, Inc.,
   59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

   TODO: This version makes use of MIPS ISA 2 features.  It won't
   work on ISA 1.  These machines will have to take the overhead of
   a sysmips(MIPS_ATOMIC_SET, ...) syscall which isn't implemented
   yet correctly.  There is however a better solution for R3000
   uniprocessor machines possible.  */

#ifndef PT_EI
# define PT_EI extern inline
#endif


/* Spinlock implementation; required.  */
PT_EI long int
testandset (int *spinlock)
{
  long int ret, temp;

  __asm__ __volatile__(
	"# Inline spinlock test & set\n\t"
	".set\tmips2\n"
	"1:\tll\t%0,%3\n\t"
	"bnez\t%0,2f\n\t"
	".set\tnoreorder\n\t"
	"li\t%1,1\n\t"
	".set\treorder\n\t"
	"sc\t%1,%2\n\t"
	"beqz\t%1,1b\n"
	"2:\t.set\tmips0\n\t"
	"/* End spinlock test & set */"
	: "=&r"(ret), "=&r" (temp), "=m"(*spinlock)
	: "m"(*spinlock)
	: "memory");

  return ret;
}


/* Get some notion of the current stack.  Need not be exactly the top
   of the stack, just something somewhere in the current frame.  */
#define CURRENT_STACK_FRAME  stack_pointer
register char * stack_pointer __asm__ ("$29");


/* Compare-and-swap for semaphores. */

#define HAS_COMPARE_AND_SWAP
PT_EI int
__compare_and_swap (long int *p, long int oldval, long int newval)
{
  long ret;

  __asm__ __volatile__ (
	"/* Inline compare & swap */\n\t"
	".set\tmips2\n"
	"1:\tll\t%0,%4\n\t"
	".set\tnoreorder\n\t"
	"bne\t%0,%2,2f\n\t"
	"move\t%0,$0\n\t" /*[NDF] Failure case. */
	"move\t%0,%3\n\t"
	".set\treorder\n\t"
	"sc\t%0,%1\n\t"
	"beqz\t%0,1b\n"
	"2:\t.set\tmips0\n\t"
	"/* End compare & swap */"
	: "=&r"(ret), "=m"(*p)
	: "r"(oldval), "r"(newval), "m"(*p));

  return ret;

  /*
    1:  load locked: into ret(%0), from *p(0(%4))
        branch to 2 if ret(%0) != oldval(%2)
	  Delay slot: move 0 into ret(%0) // [NDF] Added
	Don't branch case:
	move newval(%3) into ret(%0)
	setcompare ret(%0) into *p(0(%1))
	branch to 1 if ret(%0) == 0 (sc failed)
	  Delay slot: unknown/none
	return

    2: Delay slot
       return

ll a b
Sets a to the value pointed to by address b, and "locks" b so that if
any of a number of things are attempted that might access b then the
next sc will fail.

sc a b
Sets the memory address pointed to by b to the value in a atomically.
If it succeeds then a will be set to 1, if it fails a will be set to 0.

  */	
	
}
-------------- next part --------------
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 100
pthread_mutex_t *mutex;
volatile int test = 0;

int other_func(int arg)
{
    return arg;
}

void *func(void *arg)
{
    while(1) {
	pthread_mutex_lock(mutex);
	if(test != 0) {
	    fprintf(stderr, "ERROR: test value is non-zero, lock broken.\n");
	}
	test = getpid();
	test = other_func(test);
	if(test != getpid()) {
	    fprintf(stderr, "ERROR: test value is not pid, lock broken.\n");
	}
	test = 0;
	pthread_mutex_unlock(mutex);
    }
    return NULL;
}

int main()
{
    int i;
    pthread_t thr;
    fprintf(stderr, "Starting pthread_test.\n");

    mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(mutex, NULL);

    for(i=0; i<NUM_THREADS; ++i) {
	pthread_create(&thr, NULL, func, (void*)i);
    }
    func((void*)i);
    return 0;
}
-------------- next part --------------
/* Linuxthreads - a simple clone()-based implementation of Posix        */
/* threads for Linux.                                                   */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy at inria.fr)              */
/*                                                                      */
/* This program is free software; you can redistribute it and/or        */
/* modify it under the terms of the GNU Library General Public License  */
/* as published by the Free Software Foundation; either version 2       */
/* of the License, or (at your option) any later version.               */
/*                                                                      */
/* This program is distributed in the hope that it will be useful,      */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
/* GNU Library General Public License for more details.                 */

/* The "thread manager" thread: manages creation and termination of threads */

/* mods for uClibc: getpwd and getpagesize are the syscalls */
#define __getpid getpid
#define __getpagesize getpagesize

#include <errno.h>
#include <sched.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/poll.h>		/* for poll */
#include <sys/mman.h>           /* for mmap */
#include <sys/param.h>
#include <sys/time.h>
#include <sys/wait.h>           /* for waitpid macros */

#include "pthread.h"
#include "internals.h"
#include "spinlock.h"
#include "restart.h"
#include "semaphore.h"
#include "debug.h" /* PDEBUG, added by StS */

/* Array of active threads. Entry 0 is reserved for the initial thread. */
struct pthread_handle_struct __pthread_handles[PTHREAD_THREADS_MAX] =
{ { LOCK_INITIALIZER, &__pthread_initial_thread, 0},
  { LOCK_INITIALIZER, &__pthread_manager_thread, 0}, /* All NULLs */ };

/* For debugging purposes put the maximum number of threads in a variable.  */
const int __linuxthreads_pthread_threads_max = PTHREAD_THREADS_MAX;

/* [NDF] For debugging purposes put the size of the pthread_descr in a
 * variable. */
const int __linuxthreads_pthread_sizeof_descr
  = sizeof(struct _pthread_descr_struct);

/* Indicate whether at least one thread has a user-defined stack (if 1),
   or if all threads have stacks supplied by LinuxThreads (if 0). */
int __pthread_nonstandard_stacks;

/* Number of active entries in __pthread_handles (used by gdb) */
volatile int __pthread_handles_num = 2;

/* Whether to use debugger additional actions for thread creation
   (set to 1 by gdb) */
volatile int __pthread_threads_debug;

/* Globally enabled events.  */
volatile td_thr_events_t __pthread_threads_events;

/* Pointer to thread descriptor with last event.  */
volatile pthread_descr __pthread_last_event;

/* Mapping from stack segment to thread descriptor. */
/* Stack segment numbers are also indices into the __pthread_handles array. */
/* Stack segment number 0 is reserved for the initial thread. */

static inline pthread_descr thread_segment(int seg)
{
  return (pthread_descr)(THREAD_STACK_START_ADDRESS - (seg - 1) * STACK_SIZE)
         - 1;
}

/* Flag set in signal handler to record child termination */

static volatile int terminated_children = 0;

/* Flag set when the initial thread is blocked on pthread_exit waiting
   for all other threads to terminate */

static int main_thread_exiting = 0;

/* Counter used to generate unique thread identifier.
   Thread identifier is pthread_threads_counter + segment. */

static pthread_t pthread_threads_counter = 0;

/* Forward declarations */

static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
                                 void * (*start_routine)(void *), void *arg,
                                 sigset_t *mask, int father_pid,
				 int report_events,
				 td_thr_events_t *event_maskp);
static void pthread_handle_free(pthread_t th_id);
static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode);
static void pthread_reap_children(void);
static void pthread_kill_all_threads(int sig, int main_thread_also);

/* The server thread managing requests for thread creation and termination */

int __pthread_manager(void *arg)
{
  int reqfd = (int) (long int) arg;
  struct pollfd ufd;
  sigset_t mask;
  int n;
  struct pthread_request request;

  /* If we have special thread_self processing, initialize it.  */
#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(&__pthread_manager_thread, 1);
#endif
  /* Set the error variable.  */
  __pthread_manager_thread.p_errnop = &__pthread_manager_thread.p_errno;
  __pthread_manager_thread.p_h_errnop = &__pthread_manager_thread.p_h_errno;
  /* Block all signals except __pthread_sig_cancel and SIGTRAP */
  sigfillset(&mask);
  sigdelset(&mask, __pthread_sig_cancel); /* for thread termination */
  sigdelset(&mask, SIGTRAP);            /* for debugging purposes */
  sigprocmask(SIG_SETMASK, &mask, NULL);
  /* Raise our priority to match that of main thread */
  __pthread_manager_adjust_prio(__pthread_main_thread->p_priority);
  /* Synchronize debugging of the thread manager */
  n = __libc_read(reqfd, (char *)&request, sizeof(request));
  ASSERT(n == sizeof(request) && request.req_kind == REQ_DEBUG);
  ufd.fd = reqfd;
  ufd.events = POLLIN;
  /* Enter server loop */
  while(1) {
PDEBUG("before poll\n");
    n = poll(&ufd, 1, 2000);
PDEBUG("after poll\n");

    /* Check for termination of the main thread */
    if (getppid() == 1) {
      pthread_kill_all_threads(SIGKILL, 0);
      _exit(0);
    }
    /* Check for dead children */
    if (terminated_children) {
      terminated_children = 0;
      pthread_reap_children();
    }
    /* Read and execute request */
    if (n == 1 && (ufd.revents & POLLIN)) {
PDEBUG("before __libc_read\n");
      n = __libc_read(reqfd, (char *)&request, sizeof(request));
PDEBUG("after __libc_read, n=%d\n", n);
      ASSERT(n == sizeof(request));
      switch(request.req_kind) {
      case REQ_CREATE:
PDEBUG("got REQ_CREATE\n");
        request.req_thread->p_retcode =
          pthread_handle_create((pthread_t *) &request.req_thread->p_retval,
                                request.req_args.create.attr,
                                request.req_args.create.fn,
                                request.req_args.create.arg,
                                &request.req_args.create.mask,
                                request.req_thread->p_pid,
				request.req_thread->p_report_events,
				&request.req_thread->p_eventbuf.eventmask);
PDEBUG("restarting %d\n", request.req_thread);
        restart(request.req_thread);
        break;
      case REQ_FREE:
PDEBUG("got REQ_FREE\n");
	pthread_handle_free(request.req_args.free.thread_id);
        break;
      case REQ_PROCESS_EXIT:
PDEBUG("got REQ_PROCESS_EXIT from %d, exit code = %d\n", 
       request.req_thread, request.req_args.exit.code);
        pthread_handle_exit(request.req_thread,
                            request.req_args.exit.code);
        break;
      case REQ_MAIN_THREAD_EXIT:
PDEBUG("got REQ_MAIN_THREAD_EXIT\n");
        main_thread_exiting = 1;
        if (__pthread_main_thread->p_nextlive == __pthread_main_thread) {
          restart(__pthread_main_thread);
          return 0;
        }
        break;
      case REQ_POST:
PDEBUG("got REQ_POST\n");
        __new_sem_post(request.req_args.post);
        break;
      case REQ_DEBUG:
PDEBUG("got REQ_DEBUG\n");
	/* Make gdb aware of new thread and gdb will restart the
	   new thread when it is ready to handle the new thread. */
	if (__pthread_threads_debug && __pthread_sig_debug > 0)
PDEBUG("about to call raise(__pthread_sig_debug)\n");
	  raise(__pthread_sig_debug);
        break;
      }
    }
  }
}

int __pthread_manager_event(void *arg)
{
  /* If we have special thread_self processing, initialize it.  */
#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(&__pthread_manager_thread, 1);
#endif

  /* Get the lock the manager will free once all is correctly set up.  */
  __pthread_lock (THREAD_GETMEM((&__pthread_manager_thread), p_lock), NULL);
  /* Free it immediately.  */
  __pthread_unlock (THREAD_GETMEM((&__pthread_manager_thread), p_lock));

  return __pthread_manager(arg);
}

/* Process creation */

static int pthread_start_thread(void *arg)
{
  pthread_descr self = (pthread_descr) arg;
  struct pthread_request request;
  void * outcome;
  /* Initialize special thread_self processing, if any.  */
#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(self, self->p_nr);
#endif
PDEBUG("\n");
  /* Make sure our pid field is initialized, just in case we get there
     before our father has initialized it. */
  THREAD_SETMEM(self, p_pid, __getpid());
  /* Initial signal mask is that of the creating thread. (Otherwise,
     we'd just inherit the mask of the thread manager.) */
  sigprocmask(SIG_SETMASK, &self->p_start_args.mask, NULL);
  /* Set the scheduling policy and priority for the new thread, if needed */
  if (THREAD_GETMEM(self, p_start_args.schedpolicy) >= 0)
    /* Explicit scheduling attributes were provided: apply them */
    sched_setscheduler(THREAD_GETMEM(self, p_pid),
			 THREAD_GETMEM(self, p_start_args.schedpolicy),
                         &self->p_start_args.schedparam);
  else if (__pthread_manager_thread.p_priority > 0)
    /* Default scheduling required, but thread manager runs in realtime
       scheduling: switch new thread to SCHED_OTHER policy */
    {
      struct sched_param default_params;
      default_params.sched_priority = 0;
      sched_setscheduler(THREAD_GETMEM(self, p_pid),
                           SCHED_OTHER, &default_params);
    }
  /* Make gdb aware of new thread */
  if (__pthread_threads_debug && __pthread_sig_debug > 0) {
    request.req_thread = self;
    request.req_kind = REQ_DEBUG;
    __libc_write(__pthread_manager_request,
                 (char *) &request, sizeof(request));
    suspend(self);
  }
  /* Run the thread code */
  outcome = self->p_start_args.start_routine(THREAD_GETMEM(self,
							   p_start_args.arg));
  /* Exit with the given return value */
  pthread_exit(outcome);
  return 0;
}

static int pthread_start_thread_event(void *arg)
{
  pthread_descr self = (pthread_descr) arg;

#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(self, self->p_nr);
#endif
  /* Make sure our pid field is initialized, just in case we get there
     before our father has initialized it. */
  THREAD_SETMEM(self, p_pid, __getpid());
  /* Get the lock the manager will free once all is correctly set up.  */
  __pthread_lock (THREAD_GETMEM(self, p_lock), NULL);
  /* Free it immediately.  */
  __pthread_unlock (THREAD_GETMEM(self, p_lock));

  /* Continue with the real function.  */
  return pthread_start_thread (arg);
}

static int pthread_allocate_stack(const pthread_attr_t *attr,
                                  pthread_descr default_new_thread,
                                  int pagesize,
                                  pthread_descr * out_new_thread,
                                  char ** out_new_thread_bottom,
                                  char ** out_guardaddr,
                                  size_t * out_guardsize)
{
  pthread_descr new_thread;
  char * new_thread_bottom;
  char * guardaddr;
  size_t stacksize, guardsize;

  if (attr != NULL && attr->__stackaddr_set)
    {
      /* The user provided a stack. */
      new_thread =
        (pthread_descr) ((long)(attr->__stackaddr) & -sizeof(void *)) - 1;
      new_thread_bottom = (char *) attr->__stackaddr - attr->__stacksize;
      guardaddr = NULL;
      guardsize = 0;
      __pthread_nonstandard_stacks = 1;
    }
  else
    {
#ifdef __UCLIBC_HAS_MMU__
      stacksize = STACK_SIZE - pagesize;
      if (attr != NULL)
        stacksize = MIN (stacksize, roundup(attr->__stacksize, pagesize));
      /* Allocate space for stack and thread descriptor at default address */
      new_thread = default_new_thread;
      new_thread_bottom = (char *) (new_thread + 1) - stacksize;
      if (mmap((caddr_t)((char *)(new_thread + 1) - INITIAL_STACK_SIZE),
               INITIAL_STACK_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC,
               MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_GROWSDOWN,
               -1, 0) == MAP_FAILED)
        /* Bad luck, this segment is already mapped. */
        return -1;
      /* We manage to get a stack.  Now see whether we need a guard
         and allocate it if necessary.  Notice that the default
         attributes (stack_size = STACK_SIZE - pagesize) do not need
	 a guard page, since the RLIMIT_STACK soft limit prevents stacks
	 from running into one another. */
      if (stacksize == STACK_SIZE - pagesize)
        {
          /* We don't need a guard page. */
          guardaddr = NULL;
          guardsize = 0;
        }
      else
        {
          /* Put a bad page at the bottom of the stack */
          guardsize = attr->__guardsize;
          guardaddr = (void *)new_thread_bottom - guardsize;
          if (mmap ((caddr_t) guardaddr, guardsize, 0, MAP_FIXED, -1, 0)
              == MAP_FAILED)
            {
              /* We don't make this an error.  */
              guardaddr = NULL;
              guardsize = 0;
            }
        }
#else
      /* We cannot mmap to this huge chunk of stack space when we don't have
       * an MMU. Pretend we are using a user provided stack even if there was
       * none provided by the user. Thus, we get around the mmap and reservation
       * of a huge stack segment. -StS */

      char *new_stack;

      if ((new_stack = malloc(INITIAL_STACK_SIZE)) == NULL) {
	/* bad luck, we cannot malloc any more */
	return -1;
      }

      PDEBUG("malloced chunk: base=%p, size=0x%04x\n", new_stack, INITIAL_STACK_SIZE);

      /* Set up the pointers. new_thread marks the TOP of the stack frame and
       * the address of the pthread_descr struct at the same time. Therefore we
       * must account for its size and fit it in the malloc()'ed block. The
       * value of `new_thread' is then passed to clone() as the stack argument.
       *
       *               ^ +------------------------+
       *               | |  pthread_descr struct  |
       *               | +------------------------+  <- new_thread 
       * malloc block  | |                        |
       *               | |  thread stack          |
       *               | |                        |
       *               v +------------------------+  <- new_thread_bottom
       *
       * Note: The calculated value of new_thread must be word aligned otherwise
       * the kernel chokes on a non-aligned stack frame. Choose the lower
       * available word boundary.
       */
      new_thread_bottom = (pthread_descr) new_stack;
      new_thread = (long)((char *) new_stack + INITIAL_STACK_SIZE - sizeof(*new_thread) - 1) 
	  & -sizeof(void*); /* align new_thread */
      guardaddr = NULL;
      guardsize = 0;

      PDEBUG("thread stack: bos=%p, tos=%p\n", new_thread_bottom, new_thread);

      /* check the initial thread stack boundaries so they don't overlap */
      NOMMU_INITIAL_THREAD_BOUNDS(new_thread, new_thread_bottom);

      PDEBUG("initial stack: bos=%p, tos=%p\n", __pthread_initial_thread_bos, 
	     __pthread_initial_thread_tos);

      /* on non-MMU systems we always have non-standard stack frames */
      __pthread_nonstandard_stacks = 1;
      
#endif /* __UCLIBC_HAS_MMU__ */
    }

  /* Clear the thread data structure.  */
  memset (new_thread, '\0', sizeof (*new_thread));
  *out_new_thread = new_thread;
  *out_new_thread_bottom = new_thread_bottom;
  *out_guardaddr = guardaddr;
  *out_guardsize = guardsize;
  return 0;
}

static int pthread_handle_create(pthread_t *thread, const pthread_attr_t *attr,
				 void * (*start_routine)(void *), void *arg,
				 sigset_t * mask, int father_pid,
				 int report_events,
				 td_thr_events_t *event_maskp)
{
  size_t sseg;
  int pid;
  pthread_descr new_thread;
  char * new_thread_bottom;
  pthread_t new_thread_id;
  char *guardaddr = NULL;
  size_t guardsize = 0;
  int pagesize = __getpagesize();

  /* First check whether we have to change the policy and if yes, whether
     we can  do this.  Normally this should be done by examining the
     return value of the sched_setscheduler call in pthread_start_thread
     but this is hard to implement.  FIXME  */
  if (attr != NULL && attr->__schedpolicy != SCHED_OTHER && geteuid () != 0)
    return EPERM;
  /* Find a free segment for the thread, and allocate a stack if needed */
  for (sseg = 2; ; sseg++)
    {
      if (sseg >= PTHREAD_THREADS_MAX)
	return EAGAIN;
      if (__pthread_handles[sseg].h_descr != NULL)
	continue;
      if (pthread_allocate_stack(attr, thread_segment(sseg), pagesize,
                                 &new_thread, &new_thread_bottom,
                                 &guardaddr, &guardsize) == 0)
        break;
    }
  __pthread_handles_num++;
  /* Allocate new thread identifier */
  pthread_threads_counter += PTHREAD_THREADS_MAX;
  new_thread_id = sseg + pthread_threads_counter;
  /* Initialize the thread descriptor.  Elements which have to be
     initialized to zero already have this value.  */
  new_thread->p_tid = new_thread_id;
  new_thread->p_lock = &(__pthread_handles[sseg].h_lock);
  new_thread->p_cancelstate = PTHREAD_CANCEL_ENABLE;
  new_thread->p_canceltype = PTHREAD_CANCEL_DEFERRED;
  new_thread->p_errnop = &new_thread->p_errno;
  new_thread->p_h_errnop = &new_thread->p_h_errno;
  new_thread->p_guardaddr = guardaddr;
  new_thread->p_guardsize = guardsize;
  new_thread->p_self = new_thread;
  new_thread->p_nr = sseg;
  /* Initialize the thread handle */
  __pthread_init_lock(&__pthread_handles[sseg].h_lock);
  __pthread_handles[sseg].h_descr = new_thread;
  __pthread_handles[sseg].h_bottom = new_thread_bottom;
  /* Determine scheduling parameters for the thread */
  new_thread->p_start_args.schedpolicy = -1;
  if (attr != NULL) {
    new_thread->p_detached = attr->__detachstate;
    new_thread->p_userstack = attr->__stackaddr_set;

    switch(attr->__inheritsched) {
    case PTHREAD_EXPLICIT_SCHED:
      new_thread->p_start_args.schedpolicy = attr->__schedpolicy;
      memcpy (&new_thread->p_start_args.schedparam, &attr->__schedparam,
	      sizeof (struct sched_param));
      break;
    case PTHREAD_INHERIT_SCHED:
      new_thread->p_start_args.schedpolicy = sched_getscheduler(father_pid);
      sched_getparam(father_pid, &new_thread->p_start_args.schedparam);
      break;
    }
    new_thread->p_priority =
      new_thread->p_start_args.schedparam.sched_priority;
  }
  /* Finish setting up arguments to pthread_start_thread */
  new_thread->p_start_args.start_routine = start_routine;
  new_thread->p_start_args.arg = arg;
  new_thread->p_start_args.mask = *mask;
  /* Raise priority of thread manager if needed */
  __pthread_manager_adjust_prio(new_thread->p_priority);
  /* Do the cloning.  We have to use two different functions depending
     on whether we are debugging or not.  */
  pid = 0;     /* Note that the thread never can have PID zero.  */
  if (report_events)
    {
      /* See whether the TD_CREATE event bit is set in any of the
         masks.  */
      int idx = __td_eventword (TD_CREATE);
      uint32_t mask = __td_eventmask (TD_CREATE);

      if ((mask & (__pthread_threads_events.event_bits[idx]
		   | event_maskp->event_bits[idx])) != 0)
	{
	  /* Lock the mutex the child will use now so that it will stop.  */
	  __pthread_lock(new_thread->p_lock, NULL);

	  /* We have to report this event.  */
	  pid = clone(pthread_start_thread_event, (void **) new_thread,
		        CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
		        __pthread_sig_cancel, new_thread);
	  if (pid != -1)
	    {
	      /* Now fill in the information about the new thread in
	         the newly created thread's data structure.  We cannot let
	         the new thread do this since we don't know whether it was
	         already scheduled when we send the event.  */
	      new_thread->p_eventbuf.eventdata = new_thread;
	      new_thread->p_eventbuf.eventnum = TD_CREATE;
	      __pthread_last_event = new_thread;

	      /* We have to set the PID here since the callback function
		 in the debug library will need it and we cannot guarantee
		 the child got scheduled before the debugger.  */
	      new_thread->p_pid = pid;

	      /* Now call the function which signals the event.  */
	      __linuxthreads_create_event ();

	      /* Now restart the thread.  */
	      __pthread_unlock(new_thread->p_lock);
	    }
	}
    }

  /* [NDF] Someone forgot a { } pair. */

  if (pid == 0) { /* [NDF] Added opening brace. */
PDEBUG("cloning new_thread = %p\n", new_thread);
    pid = clone(pthread_start_thread, (void **) new_thread,
		  CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
		  __pthread_sig_cancel, new_thread);
  } /* [NDF] Added closing brace. */
  /* Check if cloning succeeded */
  if (pid == -1) {
    /* Free the stack if we allocated it */
    if (attr == NULL || !attr->__stackaddr_set)
      {
#ifdef __UCLIBC_HAS_MMU__
	if (new_thread->p_guardsize != 0)
	  munmap(new_thread->p_guardaddr, new_thread->p_guardsize);
	munmap((caddr_t)((char *)(new_thread+1) - INITIAL_STACK_SIZE),
	       INITIAL_STACK_SIZE);
#else
	free(new_thread_bottom);
#endif /* __UCLIBC_HAS_MMU__ */
      }
    __pthread_handles[sseg].h_descr = NULL;
    __pthread_handles[sseg].h_bottom = NULL;
    __pthread_handles_num--;
    return errno;
  }
PDEBUG("new thread pid = %d\n", pid);
  /* Insert new thread in doubly linked list of active threads */
  new_thread->p_prevlive = __pthread_main_thread;
  new_thread->p_nextlive = __pthread_main_thread->p_nextlive;
  __pthread_main_thread->p_nextlive->p_prevlive = new_thread;
  __pthread_main_thread->p_nextlive = new_thread;
  /* Set pid field of the new thread, in case we get there before the
     child starts. */
  new_thread->p_pid = pid;
  /* We're all set */
  *thread = new_thread_id;
  return 0;
}


/* Try to free the resources of a thread when requested by pthread_join
   or pthread_detach on a terminated thread. */

static void pthread_free(pthread_descr th)
{
  pthread_handle handle;
  pthread_readlock_info *iter, *next;
  char *h_bottom_save;

  ASSERT(th->p_exited);
  /* Make the handle invalid */
  handle =  thread_handle(th->p_tid);
  __pthread_lock(&handle->h_lock, NULL);
  h_bottom_save = handle->h_bottom;
  handle->h_descr = NULL;
  handle->h_bottom = (char *)(-1L);
  __pthread_unlock(&handle->h_lock);
#ifdef FREE_THREAD_SELF
  FREE_THREAD_SELF(th, th->p_nr);
#endif
  /* One fewer threads in __pthread_handles */
  __pthread_handles_num--;

  /* Destroy read lock list, and list of free read lock structures.
     If the former is not empty, it means the thread exited while
     holding read locks! */

  for (iter = th->p_readlock_list; iter != NULL; iter = next)
    {
      next = iter->pr_next;
      free(iter);
    }

  for (iter = th->p_readlock_free; iter != NULL; iter = next)
    {
      next = iter->pr_next;
      free(iter);
    }

  /* If initial thread, nothing to free */
  if (th == &__pthread_initial_thread) return;
#ifdef __UCLIBC_HAS_MMU__
  if (!th->p_userstack)
    {
      /* Free the stack and thread descriptor area */
      if (th->p_guardsize != 0)
	munmap(th->p_guardaddr, th->p_guardsize);
      munmap((caddr_t) ((char *)(th+1) - STACK_SIZE), STACK_SIZE);
    }
#else
  /* For non-MMU systems we always malloc the stack, so free it here. -StS */
  if (!th->p_userstack) {
      free(h_bottom_save);
  }
#endif /* __UCLIBC_HAS_MMU__ */
}

/* Handle threads that have exited */

static void pthread_exited(pid_t pid)
{
  pthread_descr th;
  int detached;
  /* Find thread with that pid */
  for (th = __pthread_main_thread->p_nextlive;
       th != __pthread_main_thread;
       th = th->p_nextlive) {
    if (th->p_pid == pid) {
      /* Remove thread from list of active threads */
      th->p_nextlive->p_prevlive = th->p_prevlive;
      th->p_prevlive->p_nextlive = th->p_nextlive;
      /* Mark thread as exited, and if detached, free its resources */
      __pthread_lock(th->p_lock, NULL);
      th->p_exited = 1;
      /* If we have to signal this event do it now.  */
      if (th->p_report_events)
	{
	  /* See whether TD_DEATH is in any of the mask.  */
	  int idx = __td_eventword (TD_REAP);
	  uint32_t mask = __td_eventmask (TD_REAP);

	  if ((mask & (__pthread_threads_events.event_bits[idx]
		       | th->p_eventbuf.eventmask.event_bits[idx])) != 0)
	    {
	      /* Yep, we have to signal the death.  */
	      th->p_eventbuf.eventnum = TD_DEATH;
	      th->p_eventbuf.eventdata = th;
	      __pthread_last_event = th;

	      /* Now call the function to signal the event.  */
	      __linuxthreads_reap_event();
	    }
	}
      detached = th->p_detached;
      __pthread_unlock(th->p_lock);
      if (detached)
	pthread_free(th);
      break;
    }
  }
  /* If all threads have exited and the main thread is pending on a
     pthread_exit, wake up the main thread and terminate ourselves. */
  if (main_thread_exiting &&
      __pthread_main_thread->p_nextlive == __pthread_main_thread) {
    restart(__pthread_main_thread);
    _exit(0);
  }
}

static void pthread_reap_children(void)
{
  pid_t pid;
  int status;
PDEBUG("\n");

  while ((pid = __libc_waitpid(-1, &status, WNOHANG | __WCLONE)) > 0) {
    pthread_exited(pid);
    if (WIFSIGNALED(status)) {
      /* If a thread died due to a signal, send the same signal to
         all other threads, including the main thread. */
      pthread_kill_all_threads(WTERMSIG(status), 1);
      _exit(0);
    }
  }
}

/* Try to free the resources of a thread when requested by pthread_join
   or pthread_detach on a terminated thread. */

static void pthread_handle_free(pthread_t th_id)
{
  pthread_handle handle = thread_handle(th_id);
  pthread_descr th;

  __pthread_lock(&handle->h_lock, NULL);
  if (invalid_handle(handle, th_id)) {
    /* pthread_reap_children has deallocated the thread already,
       nothing needs to be done */
    __pthread_unlock(&handle->h_lock);
    return;
  }
  th = handle->h_descr;
  if (th->p_exited) {
    __pthread_unlock(&handle->h_lock);
    pthread_free(th);
  } else {
    /* The Unix process of the thread is still running.
       Mark the thread as detached so that the thread manager will
       deallocate its resources when the Unix process exits. */
    th->p_detached = 1;
    __pthread_unlock(&handle->h_lock);
  }
}

/* Send a signal to all running threads */

static void pthread_kill_all_threads(int sig, int main_thread_also)
{
  pthread_descr th;
  for (th = __pthread_main_thread->p_nextlive;
       th != __pthread_main_thread;
       th = th->p_nextlive) {
    kill(th->p_pid, sig);
  }
  if (main_thread_also) {
    kill(__pthread_main_thread->p_pid, sig);
  }
}

/* Process-wide exit() */

static void pthread_handle_exit(pthread_descr issuing_thread, int exitcode)
{
  pthread_descr th;
  __pthread_exit_requested = 1;
  __pthread_exit_code = exitcode;
  /* Send the CANCEL signal to all running threads, including the main
     thread, but excluding the thread from which the exit request originated
     (that thread must complete the exit, e.g. calling atexit functions
     and flushing stdio buffers). */
  for (th = issuing_thread->p_nextlive;
       th != issuing_thread;
       th = th->p_nextlive) {
    kill(th->p_pid, __pthread_sig_cancel);
  }
  /* Now, wait for all these threads, so that they don't become zombies
     and their times are properly added to the thread manager's times. */
  for (th = issuing_thread->p_nextlive;
       th != issuing_thread;
       th = th->p_nextlive) {
    waitpid(th->p_pid, NULL, __WCLONE);
  }
  restart(issuing_thread);
  _exit(0);
}

/* Handler for __pthread_sig_cancel in thread manager thread */

void __pthread_manager_sighandler(int sig)
{
  terminated_children = 1;
}

/* Adjust priority of thread manager so that it always run at a priority
   higher than all threads */

void __pthread_manager_adjust_prio(int thread_prio)
{
  struct sched_param param;

  if (thread_prio <= __pthread_manager_thread.p_priority) return;
  param.sched_priority =
    thread_prio < sched_get_priority_max(SCHED_FIFO)
    ? thread_prio + 1 : thread_prio;
  sched_setscheduler(__pthread_manager_thread.p_pid, SCHED_FIFO, &param);
  __pthread_manager_thread.p_priority = thread_prio;
}
-------------- next part --------------
/* Linuxthreads - a simple clone()-based implementation of Posix        */
/* threads for Linux.                                                   */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy at inria.fr)              */
/*                                                                      */
/* This program is free software; you can redistribute it and/or        */
/* modify it under the terms of the GNU Library General Public License  */
/* as published by the Free Software Foundation; either version 2       */
/* of the License, or (at your option) any later version.               */
/*                                                                      */
/* This program is distributed in the hope that it will be useful,      */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
/* GNU Library General Public License for more details.                 */

/* Thread creation, initialization, and basic low-level routines */

#define __FORCE_GLIBC
#include <features.h>
#include <errno.h>
#include <netdb.h>	/* for h_errno */
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "pthread.h"
#include "internals.h"
#include "spinlock.h"
#include "restart.h"
#include "debug.h"      /* added to linuxthreads -StS */


/* Mods for uClibc: Some includes */
#include <signal.h>
#include <sys/types.h>
#include <sys/syscall.h>

/* mods for uClibc: getpwd and getpagesize are the syscalls */
#define __getpid getpid
#define __getpagesize getpagesize
/* mods for uClibc: __libc_sigaction is not in any standard headers */
extern int __libc_sigaction (int sig, const struct sigaction *act, struct sigaction *oact);


/* These variables are used by the setup code.  */
extern int _errno;
extern int _h_errno;


/* Descriptor of the initial thread */

struct _pthread_descr_struct __pthread_initial_thread = {
  &__pthread_initial_thread,  /* pthread_descr p_nextlive */
  &__pthread_initial_thread,  /* pthread_descr p_prevlive */
  NULL,                       /* pthread_descr p_nextwaiting */
  NULL,			      /* pthread_descr p_nextlock */
  PTHREAD_THREADS_MAX,        /* pthread_t p_tid */
  0,                          /* int p_pid */
  0,                          /* int p_priority */
  &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
  0,                          /* int p_signal */
  NULL,                       /* sigjmp_buf * p_signal_buf */
  NULL,                       /* sigjmp_buf * p_cancel_buf */
  0,                          /* char p_terminated */
  0,                          /* char p_detached */
  0,                          /* char p_exited */
  NULL,                       /* void * p_retval */
  0,                          /* int p_retval */
  NULL,                       /* pthread_descr p_joining */
  NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
  0,                          /* char p_cancelstate */
  0,                          /* char p_canceltype */
  0,                          /* char p_canceled */
  &_errno,                       /* int *p_errnop */
  0,                          /* int p_errno */
  &_h_errno,                       /* int *p_h_errnop */
  0,                          /* int p_h_errno */
  NULL,                       /* char * p_in_sighandler */
  0,                          /* char p_sigwaiting */
  PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  0,                          /* int p_userstack */
  NULL,                       /* void * p_guardaddr */
  0,                          /* size_t p_guardsize */
  &__pthread_initial_thread,  /* pthread_descr p_self */
  0,                          /* Always index 0 */
  0,                          /* int p_report_events */
  {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
  ATOMIC_INITIALIZER,         /* struct pthread_atomic p_resume_count */
  0,                          /* char p_woken_by_cancel */
  NULL,                       /* struct pthread_extricate_if *p_extricate */
  NULL,	                      /* pthread_readlock_info *p_readlock_list; */
  NULL,                       /* pthread_readlock_info *p_readlock_free; */
  0                           /* int p_untracked_readlock_count; */
};

/* Descriptor of the manager thread; none of this is used but the error
   variables, the p_pid and p_priority fields,
   and the address for identification.  */

struct _pthread_descr_struct __pthread_manager_thread = {
  NULL,                       /* pthread_descr p_nextlive */
  NULL,                       /* pthread_descr p_prevlive */
  NULL,                       /* pthread_descr p_nextwaiting */
  NULL,			      /* pthread_descr p_nextlock */
  0,                          /* int p_tid */
  0,                          /* int p_pid */
  0,                          /* int p_priority */
  &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
  0,                          /* int p_signal */
  NULL,                       /* sigjmp_buf * p_signal_buf */
  NULL,                       /* sigjmp_buf * p_cancel_buf */
  0,                          /* char p_terminated */
  0,                          /* char p_detached */
  0,                          /* char p_exited */
  NULL,                       /* void * p_retval */
  0,                          /* int p_retval */
  NULL,                       /* pthread_descr p_joining */
  NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
  0,                          /* char p_cancelstate */
  0,                          /* char p_canceltype */
  0,                          /* char p_canceled */
  &__pthread_manager_thread.p_errno, /* int *p_errnop */
  0,                          /* int p_errno */
  NULL,                       /* int *p_h_errnop */
  0,                          /* int p_h_errno */
  NULL,                       /* char * p_in_sighandler */
  0,                          /* char p_sigwaiting */
  PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
  {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
  {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
  0,                          /* int p_userstack */
  NULL,                       /* void * p_guardaddr */
  0,                          /* size_t p_guardsize */
  &__pthread_manager_thread,  /* pthread_descr p_self */
  1,                          /* Always index 1 */
  0,                          /* int p_report_events */
  {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
  ATOMIC_INITIALIZER,         /* struct pthread_atomic p_resume_count */
  0,                          /* char p_woken_by_cancel */
  NULL,                       /* struct pthread_extricate_if *p_extricate */
  NULL,	                      /* pthread_readlock_info *p_readlock_list; */
  NULL,                       /* pthread_readlock_info *p_readlock_free; */
  0                           /* int p_untracked_readlock_count; */
};

/* Pointer to the main thread (the father of the thread manager thread) */
/* Originally, this is the initial thread, but this changes after fork() */

pthread_descr __pthread_main_thread = &__pthread_initial_thread;

/* Limit between the stack of the initial thread (above) and the
   stacks of other threads (below). Aligned on a STACK_SIZE boundary. */

char *__pthread_initial_thread_bos = NULL;

/* For non-MMU systems also remember to stack top of the initial thread.
 * This is adapted when other stacks are malloc'ed since we don't know
 * the bounds a-priori. -StS */

#ifndef __UCLIBC_HAS_MMU__
char *__pthread_initial_thread_tos = NULL;
#endif /* __UCLIBC_HAS_MMU__ */

/* File descriptor for sending requests to the thread manager. */
/* Initially -1, meaning that the thread manager is not running. */

int __pthread_manager_request = -1;

/* Other end of the pipe for sending requests to the thread manager. */

int __pthread_manager_reader;

/* Limits of the thread manager stack */

char *__pthread_manager_thread_bos = NULL;
char *__pthread_manager_thread_tos = NULL;

/* For process-wide exit() */

int __pthread_exit_requested = 0;
int __pthread_exit_code = 0;

/* Communicate relevant LinuxThreads constants to gdb */

const int __pthread_threads_max = PTHREAD_THREADS_MAX;
const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
                                              h_descr);
const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
                                            p_pid);

/* Forward declarations */

static void pthread_exit_process(int retcode, void *arg);
#ifndef __i386__
static void pthread_handle_sigcancel(int sig);
static void pthread_handle_sigrestart(int sig);
#else
static void pthread_handle_sigcancel(int sig, struct sigcontext ctx);
static void pthread_handle_sigrestart(int sig, struct sigcontext ctx);
#endif
static void pthread_handle_sigdebug(int sig);

/* Signal numbers used for the communication.
   In these variables we keep track of the used variables.  If the
   platform does not support any real-time signals we will define the
   values to some unreasonable value which will signal failing of all
   the functions below.  */
#ifdef __NR_rt_sigaction
int __pthread_sig_restart = __SIGRTMIN;
int __pthread_sig_cancel = __SIGRTMIN + 1;
int __pthread_sig_debug = __SIGRTMIN + 2;
void (*__pthread_restart)(pthread_descr) = __pthread_restart_new;
void (*__pthread_suspend)(pthread_descr) = __pthread_wait_for_restart_signal;
#else
int __pthread_sig_restart = SIGUSR1;
int __pthread_sig_cancel = SIGUSR2;
int __pthread_sig_debug = 0;
/* Pointers that select new or old suspend/resume functions
   based on availability of rt signals. */
void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
#endif

/* Initialize the pthread library.
   Initialization is split in two functions:
   - a constructor function that blocks the __pthread_sig_restart signal
     (must do this very early, since the program could capture the signal
      mask with e.g. sigsetjmp before creating the first thread);
   - a regular function called from pthread_create when needed. */

static void pthread_initialize(void) __attribute__((constructor));

 /* Do some minimal initialization which has to be done during the
    startup of the C library.  */
void __pthread_initialize_minimal(void)
{
    /* If we have special thread_self processing, initialize 
     * that for the main thread now.  */
#ifdef INIT_THREAD_SELF
    INIT_THREAD_SELF(&__pthread_initial_thread, 0);
#endif
}


static void pthread_initialize(void)
{
  struct sigaction sa;
  sigset_t mask;
  struct rlimit limit;
  int max_stack;

  /* If already done (e.g. by a constructor called earlier!), bail out */
  if (__pthread_initial_thread_bos != NULL) return;
#ifdef TEST_FOR_COMPARE_AND_SWAP
  /* Test if compare-and-swap is available */
  __pthread_has_cas = compare_and_swap_is_available();
#endif
  /* For the initial stack, reserve at least STACK_SIZE bytes of stack
     below the current stack address, and align that on a
     STACK_SIZE boundary. */
  __pthread_initial_thread_bos =
    (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
  /* Update the descriptor for the initial thread. */
  __pthread_initial_thread.p_pid = __getpid();
  /* If we have special thread_self processing, initialize that for the
     main thread now.  */
#ifdef INIT_THREAD_SELF
  INIT_THREAD_SELF(&__pthread_initial_thread, 0);
#endif
  /* The errno/h_errno variable of the main thread are the global ones.  */
  __pthread_initial_thread.p_errnop = &_errno;
  __pthread_initial_thread.p_h_errnop = &_h_errno;
  /* Play with the stack size limit to make sure that no stack ever grows
     beyond STACK_SIZE minus two pages (one page for the thread descriptor
     immediately beyond, and one page to act as a guard page). */

#ifdef __UCLIBC_HAS_MMU__
  /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
   * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
  getrlimit(RLIMIT_STACK, &limit);
  max_stack = STACK_SIZE - 2 * __getpagesize();
  if (limit.rlim_cur > max_stack) {
    limit.rlim_cur = max_stack;
    setrlimit(RLIMIT_STACK, &limit);
  }
#else
  /* For non-MMU assume __pthread_initial_thread_tos at upper page boundary, and
   * __pthread_initial_thread_bos at address 0. These bounds are refined as we 
   * malloc other stack frames such that they don't overlap. -StS
   */
  __pthread_initial_thread_tos =
    (char *)(((long)CURRENT_STACK_FRAME + __getpagesize()) & ~(__getpagesize() - 1));
  __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
  PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
	 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
#endif /* __UCLIBC_HAS_MMU__ */

  /* Setup signal handlers for the initial thread.
     Since signal handlers are shared between threads, these settings
     will be inherited by all other threads. */
#ifndef __i386__
  sa.sa_handler = pthread_handle_sigrestart;
#else
  sa.sa_handler = (__sighandler_t) pthread_handle_sigrestart;
#endif
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  __libc_sigaction(__pthread_sig_restart, &sa, NULL);
#ifndef __i386__
  sa.sa_handler = pthread_handle_sigcancel;
#else
  sa.sa_handler = (__sighandler_t) pthread_handle_sigcancel;
#endif
  sa.sa_flags = 0;
  __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  if (__pthread_sig_debug > 0) {
    sa.sa_handler = pthread_handle_sigdebug;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    __libc_sigaction(__pthread_sig_debug, &sa, NULL);
  }
  /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
  sigemptyset(&mask);
  sigaddset(&mask, __pthread_sig_restart);
PDEBUG("block mask = %x\n", mask);
  sigprocmask(SIG_BLOCK, &mask, NULL);
  /* Register an exit function to kill all other threads. */
  /* Do it early so that user-registered atexit functions are called
     before pthread_exit_process. */
  on_exit(pthread_exit_process, NULL);
}

void __pthread_initialize(void)
{
  pthread_initialize();
}

int __pthread_initialize_manager(void)
{
  int manager_pipe[2];
  int pid;
  struct pthread_request request;

  /* If basic initialization not done yet (e.g. we're called from a
     constructor run before our constructor), do it now */
  if (__pthread_initial_thread_bos == NULL) pthread_initialize();
  /* Setup stack for thread manager */
  __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
  if (__pthread_manager_thread_bos == NULL) return -1;
  __pthread_manager_thread_tos =
    __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;

  /* On non-MMU systems we make sure that the initial thread bounds don't overlap
   * with the manager stack frame */
  NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
  PDEBUG("manager stack: size=%d, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
	 __pthread_manager_thread_bos, __pthread_manager_thread_tos);
#if 0
  PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
  	 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
#endif

  /* Setup pipe to communicate with thread manager */
  if (pipe(manager_pipe) == -1) {
    free(__pthread_manager_thread_bos);
    return -1;
  }
  /* Start the thread manager */
  pid = 0;
  if (__pthread_initial_thread.p_report_events)
    {
      /* It's a bit more complicated.  We have to report the creation of
	 the manager thread.  */
      int idx = __td_eventword (TD_CREATE);
      uint32_t mask = __td_eventmask (TD_CREATE);

      if ((mask & (__pthread_threads_events.event_bits[idx]
		   | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
	  != 0)
	{

	  /* [NDF] Added lock here. */
	  __pthread_lock(__pthread_manager_thread.p_lock, NULL);

	  pid = clone(__pthread_manager_event,
			(void **) __pthread_manager_thread_tos,
			CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
			(void *)(long)manager_pipe[0]);

	  if (pid != -1)
	    {
	      /* Now fill in the information about the new thread in
	         the newly created thread's data structure.  We cannot let
	         the new thread do this since we don't know whether it was
	         already scheduled when we send the event.  */
	      __pthread_manager_thread.p_eventbuf.eventdata =
		&__pthread_manager_thread;
	      __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
	      __pthread_last_event = &__pthread_manager_thread;
	      __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
	      __pthread_manager_thread.p_pid = pid;

	      /* Now call the function which signals the event.  */
	      __linuxthreads_create_event ();

	      /* [NDF] Moved lock from here... */

	    }

	  /* [NDF] to here. */
	  /* Now restart the thread.  */
	  __pthread_unlock(__pthread_manager_thread.p_lock);

	}
    }

  if (pid == 0) {
    pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
		  CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
		  (void *)(long)manager_pipe[0]);
  }
  if (pid == -1) {
    free(__pthread_manager_thread_bos);
    __libc_close(manager_pipe[0]);
    __libc_close(manager_pipe[1]);
    return -1;
  }
  __pthread_manager_request = manager_pipe[1]; /* writing end */
  __pthread_manager_reader = manager_pipe[0]; /* reading end */
  __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
  __pthread_manager_thread.p_pid = pid;
  /* Make gdb aware of new thread manager */
  if (__pthread_threads_debug && __pthread_sig_debug > 0)
    {
      raise(__pthread_sig_debug);
      /* We suspend ourself and gdb will wake us up when it is
	 ready to handle us. */
      __pthread_wait_for_restart_signal(thread_self());
    }
  /* Synchronize debugging of the thread manager */
PDEBUG("send REQ_DEBUG to manager thread\n");
  request.req_kind = REQ_DEBUG;
  __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
  return 0;
}

/* Thread creation */

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
			 void * (*start_routine)(void *), void *arg)
{
  pthread_descr self = thread_self();
  struct pthread_request request;
  if (__pthread_manager_request < 0) {
    if (__pthread_initialize_manager() < 0) return EAGAIN;
  }
  request.req_thread = self;
  request.req_kind = REQ_CREATE;
  request.req_args.create.attr = attr;
  request.req_args.create.fn = start_routine;
  request.req_args.create.arg = arg;
  sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
              &request.req_args.create.mask);
  PDEBUG("write REQ_CREATE to manager thread\n");
  __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
PDEBUG("before suspend(self)\n");
  suspend(self);
PDEBUG("after suspend(self)\n");
  if (THREAD_GETMEM(self, p_retcode) == 0)
    *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
  return THREAD_GETMEM(self, p_retcode);
}

/* Simple operations on thread identifiers */

pthread_t pthread_self(void)
{
  pthread_descr self = thread_self();
  return THREAD_GETMEM(self, p_tid);
}

int pthread_equal(pthread_t thread1, pthread_t thread2)
{
  return thread1 == thread2;
}

/* Helper function for thread_self in the case of user-provided stacks */

#ifndef THREAD_SELF

pthread_descr __pthread_find_self()
{
  char * sp = CURRENT_STACK_FRAME;
  pthread_handle h;

  /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
     the manager threads handled specially in thread_self(), so start at 2 */
  h = __pthread_handles + 2;
  while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;

#ifdef DEBUG_PT
  if (h->h_descr == NULL) {
      printf("*** "__FUNCTION__" ERROR descriptor is NULL!!!!! ***\n\n");
      _exit(1);
  }
#endif

  return h->h_descr;
}

#endif

/* Thread scheduling */

int pthread_setschedparam(pthread_t thread, int policy,
                          const struct sched_param *param)
{
  pthread_handle handle = thread_handle(thread);
  pthread_descr th;

  __pthread_lock(&handle->h_lock, NULL);
  if (invalid_handle(handle, thread)) {
    __pthread_unlock(&handle->h_lock);
    return ESRCH;
  }
  th = handle->h_descr;
  if (sched_setscheduler(th->p_pid, policy, param) == -1) {
    __pthread_unlock(&handle->h_lock);
    return errno;
  }
  th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
  __pthread_unlock(&handle->h_lock);
  if (__pthread_manager_request >= 0)
    __pthread_manager_adjust_prio(th->p_priority);
  return 0;
}

int pthread_getschedparam(pthread_t thread, int *policy,
                          struct sched_param *param)
{
  pthread_handle handle = thread_handle(thread);
  int pid, pol;

  __pthread_lock(&handle->h_lock, NULL);
  if (invalid_handle(handle, thread)) {
    __pthread_unlock(&handle->h_lock);
    return ESRCH;
  }
  pid = handle->h_descr->p_pid;
  __pthread_unlock(&handle->h_lock);
  pol = sched_getscheduler(pid);
  if (pol == -1) return errno;
  if (sched_getparam(pid, param) == -1) return errno;
  *policy = pol;
  return 0;
}

/* Process-wide exit() request */

static void pthread_exit_process(int retcode, void *arg)
{
  struct pthread_request request;
  pthread_descr self = thread_self();

  if (__pthread_manager_request >= 0) {
    request.req_thread = self;
    request.req_kind = REQ_PROCESS_EXIT;
    request.req_args.exit.code = retcode;
    __libc_write(__pthread_manager_request,
		 (char *) &request, sizeof(request));
    suspend(self);
    /* Main thread should accumulate times for thread manager and its
       children, so that timings for main thread account for all threads. */
    if (self == __pthread_main_thread)
      waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
  }
}

/* The handler for the RESTART signal just records the signal received
   in the thread descriptor, and optionally performs a siglongjmp
   (for pthread_cond_timedwait). */

#ifndef __i386__
static void pthread_handle_sigrestart(int sig)
{
  pthread_descr self = thread_self();
  PDEBUG("got called in non-i386 mode for %u\n", self);
#else
static void pthread_handle_sigrestart(int sig, struct sigcontext ctx)
{
  pthread_descr self;
  asm volatile ("movw %w0,%%gs" : : "r" (ctx.gs));
  self = thread_self();
  PDEBUG("got called in i386-mode for %u\n", self);
#endif
  THREAD_SETMEM(self, p_signal, sig);
  if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
    siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
}

/* The handler for the CANCEL signal checks for cancellation
   (in asynchronous mode), for process-wide exit and exec requests.
   For the thread manager thread, redirect the signal to
   __pthread_manager_sighandler. */

#ifndef __i386__
static void pthread_handle_sigcancel(int sig)
{
  pthread_descr self = thread_self();
  sigjmp_buf * jmpbuf;
#else
static void pthread_handle_sigcancel(int sig, struct sigcontext ctx)
{
  pthread_descr self;
  sigjmp_buf * jmpbuf;
  asm volatile ("movw %w0,%%gs" : : "r" (ctx.gs));
  self = thread_self();
#endif

  if (self == &__pthread_manager_thread)
    {
      __pthread_manager_sighandler(sig);
      return;
    }
  if (__pthread_exit_requested) {
    /* Main thread should accumulate times for thread manager and its
       children, so that timings for main thread account for all threads. */
    if (self == __pthread_main_thread)
      waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
    _exit(__pthread_exit_code);
  }
  if (THREAD_GETMEM(self, p_canceled)
      && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
    if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
      pthread_exit(PTHREAD_CANCELED);
    jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
    if (jmpbuf != NULL) {
      THREAD_SETMEM(self, p_cancel_jmp, NULL);
      siglongjmp(*jmpbuf, 1);
    }
  }
}

/* Handler for the DEBUG signal.
   The debugging strategy is as follows:
   On reception of a REQ_DEBUG request (sent by new threads created to
   the thread manager under debugging mode), the thread manager throws
   __pthread_sig_debug to itself. The debugger (if active) intercepts
   this signal, takes into account new threads and continue execution
   of the thread manager by propagating the signal because it doesn't
   know what it is specifically done for. In the current implementation,
   the thread manager simply discards it. */

static void pthread_handle_sigdebug(int sig)
{
  /* Nothing */
}

/* Reset the state of the thread machinery after a fork().
   Close the pipe used for requests and set the main thread to the forked
   thread.
   Notice that we can't free the stack segments, as the forked thread
   may hold pointers into them. */

void __pthread_reset_main_thread()
{
  pthread_descr self = thread_self();

  if (__pthread_manager_request != -1) {
    /* Free the thread manager stack */
    free(__pthread_manager_thread_bos);
    __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
    /* Close the two ends of the pipe */
    __libc_close(__pthread_manager_request);
    __libc_close(__pthread_manager_reader);
    __pthread_manager_request = __pthread_manager_reader = -1;
  }

  /* Update the pid of the main thread */
  THREAD_SETMEM(self, p_pid, __getpid());
  /* Make the forked thread the main thread */
  __pthread_main_thread = self;
  THREAD_SETMEM(self, p_nextlive, self);
  THREAD_SETMEM(self, p_prevlive, self);
  /* Now this thread modifies the global variables.  */
  THREAD_SETMEM(self, p_errnop, &_errno);
  THREAD_SETMEM(self, p_h_errnop, &_h_errno);
}

/* Process-wide exec() request */

void __pthread_kill_other_threads_np(void)
{
  struct sigaction sa;
  /* Terminate all other threads and thread manager */
  pthread_exit_process(0, NULL);
  /* Make current thread the main thread in case the calling thread
     changes its mind, does not exec(), and creates new threads instead. */
  __pthread_reset_main_thread();
  /* Reset the signal handlers behaviour for the signals the
     implementation uses since this would be passed to the new
     process.  */
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = SIG_DFL;
  __libc_sigaction(__pthread_sig_restart, &sa, NULL);
  __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
  if (__pthread_sig_debug > 0)
    __libc_sigaction(__pthread_sig_debug, &sa, NULL);
}
weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)

/* Concurrency symbol level.  */
static int current_level;

int __pthread_setconcurrency(int level)
{
  /* We don't do anything unless we have found a useful interpretation.  */
  current_level = level;
  return 0;
}
weak_alias (__pthread_setconcurrency, pthread_setconcurrency)

int __pthread_getconcurrency(void)
{
  return current_level;
}
weak_alias (__pthread_getconcurrency, pthread_getconcurrency)

void __pthread_set_own_extricate_if(pthread_descr self, pthread_extricate_if *peif)
{
  __pthread_lock(self->p_lock, self);
  THREAD_SETMEM(self, p_extricate, peif);
  __pthread_unlock(self->p_lock);
}

/* Primitives for controlling thread execution */

void __pthread_wait_for_restart_signal(pthread_descr self)
{
  sigset_t mask;

  sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
  sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
  do {
    self->p_signal = 0;
    PDEBUG("temporary block mask = %x\n", mask);
    sigsuspend(&mask);                   /* Wait for signal */
    PDEBUG(" *** after sigsuspend *** \n");
  } while (self->p_signal !=__pthread_sig_restart );
}

#ifdef __NR_rt_sigaction
void __pthread_restart_new(pthread_descr th)
{
    kill(th->p_pid, __pthread_sig_restart);
}

/* There is no __pthread_suspend_new because it would just
   be a wasteful wrapper for __pthread_wait_for_restart_signal */
#if 0
void __pthread_suspend_new(pthread_descr th)
{
    __pthread_wait_for_restart_signal(th);
}
#endif

#else
/* The _old variants are for 2.0 and early 2.1 kernels which don't have RT signals.
   On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
   Since the restart signal does not queue, we use an atomic counter to create
   queuing semantics. This is needed to resolve a rare race condition in
   pthread_cond_timedwait_relative. */
void __pthread_restart_old(pthread_descr th)
{
  if (atomic_increment(&th->p_resume_count) == -1)
    kill(th->p_pid, __pthread_sig_restart);
}

void __pthread_suspend_old(pthread_descr self)
{
  if (atomic_decrement(&self->p_resume_count) <= 0)
    __pthread_wait_for_restart_signal(self);
}
#endif

/* There is no __pthread_suspend_new because it would just
   be a wasteful wrapper for __pthread_wait_for_restart_signal */

/* Debugging aid */

#ifdef DEBUG_PT
#include <stdarg.h>

void __pthread_message(char * fmt, ...)
{
  char buffer[1024];
  va_list args;
  sprintf(buffer, "%05d : ", __getpid());
  va_start(args, fmt);
  vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
  va_end(args);
  __libc_write(2, buffer, strlen(buffer));
}

#endif


#ifndef PIC
/* We need a hook to force the cancelation wrappers to be linked in when
   static libpthread is used.  */
extern const int __pthread_provide_wrappers;
static const int *const __pthread_require_wrappers =
  &__pthread_provide_wrappers;
#endif
-------------- next part --------------
/* Linuxthreads - a simple clone()-based implementation of Posix        */
/* threads for Linux.                                                   */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy at inria.fr)              */
/*                                                                      */
/* This program is free software; you can redistribute it and/or        */
/* modify it under the terms of the GNU Library General Public License  */
/* as published by the Free Software Foundation; either version 2       */
/* of the License, or (at your option) any later version.               */
/*                                                                      */
/* This program is distributed in the hope that it will be useful,      */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
/* GNU Library General Public License for more details.                 */

/* mods for uClibc: removed strong_alias'es */

/* Thread-specific data */

#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include "pthread.h"
#include "internals.h"

/* Table of keys. */

static struct pthread_key_struct pthread_keys[PTHREAD_KEYS_MAX] =
  { { 0, NULL } };

/* [NDF] For debugging purposes put the maximum number of keys in a
 * variable. */
const int __linuxthreads_pthread_keys_max = PTHREAD_KEYS_MAX;

/* Mutex to protect access to pthread_keys */

static pthread_mutex_t pthread_keys_mutex = PTHREAD_MUTEX_INITIALIZER;

/* Create a new key */

int pthread_key_create(pthread_key_t * key, destr_function destr)
{
  int i;

  pthread_mutex_lock(&pthread_keys_mutex);
  for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
    if (! pthread_keys[i].in_use) {
      /* Mark key in use */
      pthread_keys[i].in_use = 1;
      pthread_keys[i].destr = destr;
      pthread_mutex_unlock(&pthread_keys_mutex);
      *key = i;
      return 0;
    }
  }
  pthread_mutex_unlock(&pthread_keys_mutex);
  return EAGAIN;
}
//strong_alias (__pthread_key_create, pthread_key_create)

/* Delete a key */

int pthread_key_delete(pthread_key_t key)
{
  pthread_descr self = thread_self();
  pthread_descr th;
  unsigned int idx1st, idx2nd;

  pthread_mutex_lock(&pthread_keys_mutex);
  if (key >= PTHREAD_KEYS_MAX || !pthread_keys[key].in_use) {
    pthread_mutex_unlock(&pthread_keys_mutex);
    return EINVAL;
  }
  pthread_keys[key].in_use = 0;
  pthread_keys[key].destr = NULL;
  /* Set the value of the key to NULL in all running threads, so
     that if the key is reallocated later by pthread_key_create, its
     associated values will be NULL in all threads. */
  idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE;
  idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE;
  th = self;
  do {
    /* If the thread already is terminated don't modify the memory.  */
    if (!th->p_terminated && th->p_specific[idx1st] != NULL)
      th->p_specific[idx1st][idx2nd] = NULL;
    th = th->p_nextlive;
  } while (th != self);
  pthread_mutex_unlock(&pthread_keys_mutex);
  return 0;
}

/* Set the value of a key */

int pthread_setspecific(pthread_key_t key, const void * pointer)
{
  pthread_descr self = thread_self();
  unsigned int idx1st, idx2nd;

  if (key >= PTHREAD_KEYS_MAX || !pthread_keys[key].in_use)
    return EINVAL;
  idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE;
  idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE;
  if (THREAD_GETMEM_NC(self, p_specific[idx1st]) == NULL) {
    void *newp = calloc(PTHREAD_KEY_2NDLEVEL_SIZE, sizeof (void *));
    if (newp == NULL)
      return ENOMEM;
    THREAD_SETMEM_NC(self, p_specific[idx1st], newp);
  }
  THREAD_GETMEM_NC(self, p_specific[idx1st])[idx2nd] = (void *) pointer;
  return 0;
}
//strong_alias (__pthread_setspecific, pthread_setspecific)

/* Get the value of a key */

void * pthread_getspecific(pthread_key_t key)
{
  pthread_descr self = thread_self();
  unsigned int idx1st, idx2nd;

  if (key >= PTHREAD_KEYS_MAX)
    return NULL;
  idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE;
  idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE;
  if (THREAD_GETMEM_NC(self, p_specific[idx1st]) == NULL
      || !pthread_keys[key].in_use)
    return NULL;
  return THREAD_GETMEM_NC(self, p_specific[idx1st])[idx2nd];
}
//strong_alias (__pthread_getspecific, pthread_getspecific)

/* Call the destruction routines on all keys */

void __pthread_destroy_specifics()
{
  pthread_descr self = thread_self();
  int i, j, round, found_nonzero;
  destr_function destr;
  void * data;

  for (round = 0, found_nonzero = 1;
       found_nonzero && round < PTHREAD_DESTRUCTOR_ITERATIONS;
       round++) {
    found_nonzero = 0;
    for (i = 0; i < PTHREAD_KEY_1STLEVEL_SIZE; i++)
      if (THREAD_GETMEM_NC(self, p_specific[i]) != NULL)
        for (j = 0; j < PTHREAD_KEY_2NDLEVEL_SIZE; j++) {
          destr = pthread_keys[i * PTHREAD_KEY_2NDLEVEL_SIZE + j].destr;
          data = THREAD_GETMEM_NC(self, p_specific[i])[j];
          if (destr != NULL && data != NULL) {
            THREAD_GETMEM_NC(self, p_specific[i])[j] = NULL;
            destr(data);
            found_nonzero = 1;
          }
        }
  }
  for (i = 0; i < PTHREAD_KEY_1STLEVEL_SIZE; i++) {
    if (THREAD_GETMEM_NC(self, p_specific[i]) != NULL)
      free(THREAD_GETMEM_NC(self, p_specific[i]));
  }
}

/* Thread-specific data for libc. */

static int
libc_internal_tsd_set(enum __libc_tsd_key_t key, const void * pointer)
{
  pthread_descr self = thread_self();

  THREAD_SETMEM_NC(self, p_libc_specific[key], (void *) pointer);
  return 0;
}
int (*__libc_internal_tsd_set)(enum __libc_tsd_key_t key, const void * pointer)
    = libc_internal_tsd_set;

static void *
libc_internal_tsd_get(enum __libc_tsd_key_t key)
{
  pthread_descr self = thread_self();

  return THREAD_GETMEM_NC(self, p_libc_specific[key]);
}
void * (*__libc_internal_tsd_get)(enum __libc_tsd_key_t key)
    = libc_internal_tsd_get;

-------------- next part --------------
/* Return list of symbols the library can request.
   Copyright (C) 2001 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Contributed by Ulrich Drepper <drepper at cygnus.com>, 2001.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */

#include <assert.h>
#include "thread_dbP.h"


static const char *symbol_list_arr[] =
{
  [PTHREAD_THREADS_EVENTS] = "__pthread_threads_events",
  [PTHREAD_LAST_EVENT] = "__pthread_last_event",
  [PTHREAD_HANDLES_NUM] = "__pthread_handles_num",
  [PTHREAD_HANDLES] = "__pthread_handles",
  [PTHREAD_KEYS] = "pthread_keys",
  [LINUXTHREADS_PTHREAD_THREADS_MAX] = "__linuxthreads_pthread_threads_max",
  [LINUXTHREADS_PTHREAD_KEYS_MAX] = "__linuxthreads_pthread_keys_max",
  [LINUXTHREADS_PTHREAD_SIZEOF_DESCR] = "__linuxthreads_pthread_sizeof_descr",
  [LINUXTHREADS_CREATE_EVENT] = "__linuxthreads_create_event",
  [LINUXTHREADS_DEATH_EVENT] = "__linuxthreads_death_event",
  [LINUXTHREADS_REAP_EVENT] = "__linuxthreads_reap_event",
  [NUM_MESSAGES] = NULL
};


const char **
td_symbol_list (void)
{
  return symbol_list_arr;
}


int
td_lookup (struct ps_prochandle *ps, int idx, psaddr_t *sym_addr)
{
  assert (idx >= 0 && idx < NUM_MESSAGES);
  int ret = ps_pglobal_lookup (ps, LIBPTHREAD_SO, symbol_list_arr[idx], sym_addr);
  if( (ret == TD_ERR) && (idx == LINUXTHREADS_PTHREAD_THREADS_MAX) ) {
      /* [NDF] I believe in uClibc this variable is actually known by
       * __pthread_threads_max, try searching for that instead. */
      ret = ps_pglobal_lookup (ps, LIBPTHREAD_SO, "__pthread_threads_max", sym_addr);
  }
  return ret;
}


More information about the uClibc mailing list