Oh no, it worketh!
[cacao.git] / src / threads / threads-common.c
index 8d8dc04592a89ee76d3c6fe6eba2746c5fc29aea..b8bc7046b866670c33fcb05fe69bb4eb40b39cce 100644 (file)
@@ -1,9 +1,7 @@
 /* src/threads/threads-common.c - machine independent thread functions
 
-   Copyright (C) 2007 R. Grafl, A. Krall, C. Kruegel,
-   C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
-   E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
-   J. Wenninger, Institut f. Computersprachen - TU Wien
+   Copyright (C) 2007, 2008
+   CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
 
    This file is part of CACAO.
 
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
 
-   $Id: threads-common.c 7893 2007-05-10 13:27:29Z twisti $
-
 */
 
 
 #include "config.h"
 
 #include <assert.h>
+#include <stdint.h>
+#include <unistd.h>
 
 #include "vm/types.h"
 
+#include "mm/memory.h"
+
 #include "native/jni.h"
+#include "native/llni.h"
 
 #include "native/include/java_lang_Object.h"
 #include "native/include/java_lang_String.h"
 #include "native/include/java_lang_Thread.h"
 
 #if defined(WITH_CLASSPATH_GNU)
+# include "native/include/java_lang_Throwable.h"
 # include "native/include/java_lang_VMThread.h"
 #endif
 
 #include "threads/critical.h"
 #include "threads/lock-common.h"
+#include "threads/threadlist.h"
 #include "threads/threads-common.h"
 
+#include "toolbox/list.h"
+
 #include "vm/builtin.h"
 #include "vm/stringlocal.h"
 #include "vm/vm.h"
@@ -54,9 +59,9 @@
 #include "vm/jit/stacktrace.h"
 
 #include "vmcore/class.h"
+#include "vmcore/options.h"
 
 #if defined(ENABLE_STATISTICS)
-# include "vmcore/options.h"
 # include "vmcore/statistics.h"
 #endif
 
 
 /* global variables ***********************************************************/
 
-/* global threads table */
-static threads_table_t threads_table;
-
-
-/* prototypes *****************************************************************/
-
-static void threads_table_init(threadobject *mainthread);
+#if defined(__LINUX__)
+/* XXX Remove for exact-GC. */
+bool threads_pthreads_implementation_nptl;
+#endif
 
 
 /* threads_preinit *************************************************************
 
    Do some early initialization of stuff required.
 
-   ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
-   is called AFTER this function!
-
 *******************************************************************************/
 
 void threads_preinit(void)
 {
        threadobject *mainthread;
+#if defined(__LINUX__) && defined(_CS_GNU_LIBPTHREAD_VERSION)
+       char         *pathbuf;
+       size_t        len;
+#endif
+
+       TRACESUBSYSTEMINITIALIZATION("threads_preinit");
+
+#if defined(__LINUX__)
+       /* XXX Remove for exact-GC. */
+
+       /* On Linux we need to check the pthread implementation. */
+
+       /* _CS_GNU_LIBPTHREAD_VERSION (GNU C library only; since glibc 2.3.2) */
+       /* If the glibc is a pre-2.3.2 version, we fall back to
+          linuxthreads. */
+
+# if defined(_CS_GNU_LIBPTHREAD_VERSION)
+       len = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, (size_t) 0);
+
+       /* Some systems return as length 0 (maybe cross-compilation
+          related).  In this case we also fall back to linuxthreads. */
+
+       if (len > 0) {
+               pathbuf = MNEW(char, len);
+
+               (void) confstr(_CS_GNU_LIBPTHREAD_VERSION, pathbuf, len);
+
+               if (strstr(pathbuf, "NPTL") != NULL)
+                       threads_pthreads_implementation_nptl = true;
+               else
+                       threads_pthreads_implementation_nptl = false;
+       }
+       else
+               threads_pthreads_implementation_nptl = false;
+# else
+       threads_pthreads_implementation_nptl = false;
+# endif
+#endif
 
        /* Initialize the threads implementation (sets the thinlock on the
           main thread). */
@@ -94,598 +131,555 @@ void threads_preinit(void)
 
        /* create internal thread data-structure for the main thread */
 
-       mainthread = threads_create_thread();
-
-       mainthread->object   = NULL;
-       mainthread->index    = 1;
-       mainthread->thinlock = lock_pre_compute_thinlock(mainthread->index);
+       mainthread = threads_thread_new();
 
        /* thread is a Java thread and running */
 
-       mainthread->flags = THREAD_FLAG_JAVA;
+       mainthread->flags |= THREAD_FLAG_JAVA;
        mainthread->state = THREAD_STATE_RUNNABLE;
 
        /* store the internal thread data-structure in the TSD */
 
        threads_set_current_threadobject(mainthread);
-       
-       /* initialize the threads table with the main-thread */
-
-       threads_table_init(mainthread);
-
-       /* initialize locking subsystems */
-
-       lock_init();
-
-       /* initialize the critical section */
-
-       critical_init();
 }
 
 
-/* threads_table_init **********************************************************
-
-   Initialize the global threads table.  We initialize the table with
-   the main-thread, which has always the index 1.
+/* threads_thread_new **********************************************************
 
-   IN:
-      mainthread....the main-thread
+   Allocates and initializes an internal thread data-structure and
+   adds it to the threads list.
 
 *******************************************************************************/
 
-#define THREADS_INITIAL_TABLE_SIZE    8
-
-static void threads_table_init(threadobject *mainthread)
+threadobject *threads_thread_new(void)
 {
-       threads_table_entry_t *ttemain;
-       s4                     size;
-       s4                     i;
-
-       /* initialize the threads table lock */
-
-       threads_impl_table_init();
-
-       /* initialize the table */
-
-       size = THREADS_INITIAL_TABLE_SIZE;
-
-       threads_table.table   = MNEW(threads_table_entry_t, size);
-       threads_table.size    = size;
-       threads_table.used    = 0;
-       threads_table.daemons = 0;
-
-       /* Link the entries in a freelist.  Skip 2 entries: 0 is the
-          free-list header and 1 is the main thread. */
-
-       for (i = 2; i < size; i++) {
-               threads_table.table[i].thread = NULL;
-               threads_table.table[i].next   = i + 1;
-       }
-
-       threads_table.table[0].next = 2;
-
-       /* terminate the freelist */
-
-       threads_table.table[size - 1].next = 0;          /* index 0 is never free */
-
-       /* insert the main-thread */
-
-       ttemain = &(threads_table.table[1]);
-
-       ttemain->thread = mainthread;
-       ttemain->next   = 0;
+       int32_t         index;
+       threadobject   *t;
+       
+       /* lock the threads-lists */
 
-       /* now 1 entry is used */
+       threads_list_lock();
 
-       threads_table.used = 1;
-}
+       index = threadlist_get_free_index();
 
+       /* Allocate a thread data structure. */
 
-/* threads_table_add ***********************************************************
+       /* First, try to get one from the free-list. */
 
-   Add a thread to the global threads table. The index is entered in the
-   threadobject. The thinlock value for the thread is pre-computed.
+       t = threadlist_free_first();
 
-   IN:
-      thread............the thread to add
+       if (t != NULL) {
+               /* Remove from free list. */
 
-   RETURN VALUE:
-      The table index for the newly added thread. This value has also been
-         entered in the threadobject.
+               threadlist_free_remove(t);
 
-*******************************************************************************/
+               /* Equivalent of MZERO on the else path */
 
-s4 threads_table_add(threadobject *thread)
-{
-       threads_table_entry_t *ttefree;
-       threads_table_entry_t *ttemain;
-       threads_table_entry_t *tte;
-       s4 index;
-       s4 oldsize;
-       s4 newsize;
-       s4 i;
-
-       /* lock the threads table */
-
-       threads_table_lock();
+               threads_impl_thread_clear(t);
+       }
+       else {
+#if defined(ENABLE_GC_BOEHM)
+               t = GCNEW_UNCOLLECTABLE(threadobject, 1);
+#else
+               t = NEW(threadobject);
+#endif
 
-       /* get free and main entry */
+#if defined(ENABLE_STATISTICS)
+               if (opt_stat)
+                       size_threadobject += sizeof(threadobject);
+#endif
 
-       ttefree = &(threads_table.table[0]);
-       ttemain = &(threads_table.table[1]);
+               /* Clear memory. */
 
-       /* get the next free index */
+               MZERO(t, threadobject, 1);
 
-       index = ttefree->next;
+#if defined(ENABLE_GC_CACAO)
+               /* Register reference to java.lang.Thread with the GC. */
+               /* FIXME is it ok to do this only once? */
 
-       /* no entry free anymore? resize the table */
+               gc_reference_register(&(t->object), GC_REFTYPE_THREADOBJECT);
+               gc_reference_register(&(t->_exceptionptr), GC_REFTYPE_THREADOBJECT);
+#endif
 
-       if (index == 0) {
-               /* we must grow the table */
+               /* Initialize the implementation-specific bits. */
 
-               oldsize = threads_table.size;
-               newsize = oldsize * 2;
+               threads_impl_thread_init(t);
+       }
 
-               threads_table.table = MREALLOC(threads_table.table,
-                                                                          threads_table_entry_t, oldsize, newsize);
-               threads_table.size = newsize;
+       /* Pre-compute the thinlock-word. */
 
-               /* the addresses have changed, get them again */
+       assert(index != 0);
 
-               ttefree = &(threads_table.table[0]);
-               ttemain = &(threads_table.table[1]);
+       t->index     = index;
+       t->thinlock  = lock_pre_compute_thinlock(t->index);
+       t->flags     = 0;
+       t->state     = THREAD_STATE_NEW;
 
-               /* link the new entries to a free list */
+#if defined(ENABLE_GC_CACAO)
+       t->flags    |= THREAD_FLAG_IN_NATIVE; 
+#endif
 
-               for (i = oldsize; i < newsize; i++) {
-                       threads_table.table[i].thread = NULL;
-                       threads_table.table[i].next   = i + 1;
-               }
+       /* Initialize the implementation-specific bits. */
 
-               ttefree->next = oldsize;
+       threads_impl_thread_reuse(t);
 
-               /* terminate the freelist */
+       /* Add the thread to the thread list. */
 
-               threads_table.table[newsize - 1].next = 0;   /* index 0 is never free */
+       threadlist_add(t);
 
-               /* use the first of the new entries */
+       /* Unlock the threads-lists. */
 
-               index = ttefree->next;
-       }
+       threads_list_unlock();
 
-       /* get the entry with the assigned index */
+       return t;
+}
 
-       tte = &(threads_table.table[index]);
 
-       /* store the next free index into the free-list header */
+/* threads_thread_free *********************************************************
 
-       ttefree->next = tte->next;
+   Remove the thread from the threads-list and free the internal
+   thread data structure.  The thread index is added to the
+   thread-index free-list.
 
-       /* store the thread in the table */
+   IN:
+       t....thread data structure
 
-       tte->thread = thread;
+*******************************************************************************/
 
-       /* link the new entry into the used-list */
+void threads_thread_free(threadobject *t)
+{
+       /* Lock the threads lists. */
 
-       tte->next     = ttemain->next;
-       ttemain->next = index;
+       threads_list_lock();
 
-       /* update the counters */
+       /* Remove the thread from the thread-list. */
 
-       threads_table.used++;
+       threadlist_remove(t);
 
-       if (thread->flags & THREAD_FLAG_DAEMON)
-               threads_table.daemons++;
+       /* Add the thread index to the free list. */
 
-       assert(threads_table.used < threads_table.size);
+       threadlist_index_add(t->index);
 
-       /* set the thread variables */
+       /* Add the thread data structure to the free list. */
 
-       thread->index    = index;
-       thread->thinlock = lock_pre_compute_thinlock(index);
+       threads_thread_set_object(t, NULL);
 
-       /* unlock the threads table */
+       threadlist_free_add(t);
 
-       threads_table_unlock();
+       /* Unlock the threads lists. */
 
-       return index;
+       threads_list_unlock();
 }
 
 
-/* threads_table_remove *******************************************************
+/* threads_thread_start_internal ***********************************************
 
-   Remove a thread from the global threads table.
+   Start an internal thread in the JVM.  No Java thread objects exists
+   so far.
 
    IN:
-      thread............the thread to remove
+      name.......UTF-8 name of the thread
+      f..........function pointer to C function to start
 
-******************************************************************************/
+*******************************************************************************/
 
-void threads_table_remove(threadobject *thread)
+bool threads_thread_start_internal(utf *name, functionptr f)
 {
-       threads_table_entry_t *ttefree;
-       threads_table_entry_t *tte;
-       s4                     index;
-       s4                     i;
-
-       /* lock the threads table */
-
-       threads_table_lock();
-
-       /* get the free entry */
-
-       ttefree = &(threads_table.table[0]);
+       threadobject       *t;
+       java_lang_Thread   *object;
+#if defined(WITH_CLASSPATH_GNU)
+       java_lang_VMThread *vmt;
+#endif
 
-       /* get the current entry */
+       /* Enter the join-mutex, so if the main-thread is currently
+          waiting to join all threads, the number of non-daemon threads
+          is correct. */
 
-       index = thread->index;
-       tte   = &(threads_table.table[index]);
+       threads_mutex_join_lock();
 
-       assert(tte->thread == thread);
+       /* create internal thread data-structure */
 
-       /* Find the entry which has the one to be removed as next entry (I
-          think it's better to do it at the removal in linear time than
-          to have a list or to do it every time we iterate over all
-          threads). */
+       t = threads_thread_new();
 
-       for (i = 0; i < threads_table.size; i++) {
-               if (threads_table.table[i].next == index) {
-                       threads_table.table[i].next = tte->next;
-                       break;
-               }
-       }
+       t->flags |= THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON;
 
-       /* clear the thread pointer in the entry */
+       /* The thread is flagged as (non-)daemon thread, we can leave the
+          mutex. */
 
-       tte->thread = NULL;
+       threads_mutex_join_unlock();
 
-       /* this entry is free now, add it to the free-list */
+       /* create the java thread object */
 
-       tte->next     = ttefree->next;
-       ttefree->next = index;
+       object = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
 
-       /* update the counters */
+       /* XXX memory leak!!! */
+       if (object == NULL)
+               return false;
 
-       threads_table.used--;
+#if defined(WITH_CLASSPATH_GNU)
+       vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
 
-       if (thread->flags & THREAD_FLAG_DAEMON)
-               threads_table.daemons--;
+       /* XXX memory leak!!! */
+       if (vmt == NULL)
+               return false;
 
-       assert(threads_table.used >= 0);
+       LLNI_field_set_ref(vmt, thread, object);
+       LLNI_field_set_val(vmt, vmdata, (java_lang_Object *) t);
 
-       /* delete the index in the threadobject to discover bugs */
-#if !defined(NDEBUG)
-       thread->index = 0;
+       LLNI_field_set_ref(object, vmThread, vmt);
+#elif defined(WITH_CLASSPATH_CLDC1_1)
+       LLNI_field_set_val(object, vm_thread, (java_lang_Object *) t);
 #endif
 
-       /* unlock the threads table */
-
-       threads_table_unlock();
-}
-
-
-/* threads_table_get ***********************************************************
-
-   Return the thread of the given table-entry index.
+       threads_thread_set_object(t, (java_handle_t *) object);
 
-   NOTE: It is valid to pass and index of 0, as this entry is the
-         free-list header where the thread pointer is always NULL and
-         this is thre expected behavior.
+       /* set java.lang.Thread fields */
 
-   NOTE: This function does not lock the table.
+#if defined(WITH_CLASSPATH_GNU)
+       LLNI_field_set_ref(object, name    , (java_lang_String *) javastring_new(name));
+#elif defined(WITH_CLASSPATH_CLDC1_1)
+       /* FIXME: In cldc the name is a char[] */
+/*     LLNI_field_set_ref(object, name    , (java_chararray *) javastring_new(name)); */
+       LLNI_field_set_ref(object, name    , NULL);
+#endif
 
-*******************************************************************************/
+#if defined(ENABLE_JAVASE)
+       LLNI_field_set_val(object, daemon  , true);
+#endif
 
-static threadobject *threads_table_get(s4 index)
-{
-       threadobject *thread;
+       LLNI_field_set_val(object, priority, NORM_PRIORITY);
 
-       /* get the requested entry */
+       /* start the thread */
 
-       assert((index >= 0) && (index < threads_table.size));
+       threads_impl_thread_start(t, f);
 
-       thread = threads_table.table[index].thread;
+       /* everything's ok */
 
-       return thread;
+       return true;
 }
 
 
-/* threads_table_get_threads ***************************************************
+/* threads_thread_start ********************************************************
 
-   Return the number of running threads.
+   Start a Java thread in the JVM.  Only the java thread object exists
+   so far.
 
-   NOTE: This function does not lock the table.
+   IN:
+      object.....the java thread object java.lang.Thread
 
 *******************************************************************************/
 
-s4 threads_table_get_threads(void)
+void threads_thread_start(java_handle_t *object)
 {
-       return threads_table.used;
-}
-
-
-/* threads_table_get_non_daemons ***********************************************
-
-   Return the number of non-daemon threads.
+       java_lang_Thread   *o;
+       threadobject       *thread;
+#if defined(WITH_CLASSPATH_GNU)
+       java_lang_VMThread *vmt;
+#endif
 
-*******************************************************************************/
+       o = (java_lang_Thread *) object;
 
-s4 threads_table_get_non_daemons(void)
-{
-       s4 nondaemons;
+       /* Enter the join-mutex, so if the main-thread is currently
+          waiting to join all threads, the number of non-daemon threads
+          is correct. */
 
-       /* lock the threads table */
+       threads_mutex_join_lock();
 
-       threads_table_lock();
+       /* create internal thread data-structure */
 
-       nondaemons = threads_table.used - threads_table.daemons;
+       thread = threads_thread_new();
 
-       /* unlock the threads table */
+       /* this is a normal Java thread */
 
-       threads_table_unlock();
+       thread->flags |= THREAD_FLAG_JAVA;
 
-       return nondaemons;
-}
+#if defined(ENABLE_JAVASE)
+       /* is this a daemon thread? */
 
+       if (LLNI_field_direct(o, daemon) == true)
+               thread->flags |= THREAD_FLAG_DAEMON;
+#endif
 
-/* threads_table_first *********************************************************
+       /* The thread is flagged and (non-)daemon thread, we can leave the
+          mutex. */
 
-   Return the first thread of the threads table.
+       threads_mutex_join_unlock();
 
-   NOTE: This is always the entry with index 1 and must be the main
-         thread.
+       /* link the two objects together */
 
-   NOTE: This function does not lock the table.
+       threads_thread_set_object(thread, object);
 
-*******************************************************************************/
+#if defined(WITH_CLASSPATH_GNU)
+       LLNI_field_get_ref(o, vmThread, vmt);
 
-threadobject *threads_table_first(void)
-{
-       threadobject *thread;
+       assert(vmt);
+       assert(LLNI_field_direct(vmt, vmdata) == NULL);
 
-       /* get the requested entry */
+       LLNI_field_set_val(vmt, vmdata, (java_lang_Object *) thread);
+#elif defined(WITH_CLASSPATH_CLDC1_1)
+       LLNI_field_set_val(o, vm_thread, (java_lang_Object *) thread);
+#endif
 
-       thread = threads_table_get(1);
+       /* Start the thread.  Don't pass a function pointer (NULL) since
+          we want Thread.run()V here. */
 
-       return thread;
+       threads_impl_thread_start(thread, NULL);
 }
 
 
-/* threads_table_next **********************************************************
-
-   Return the next thread of the threads table relative to the passed
-   one.
-
-   NOTE: This function does not lock the table.
+/* threads_thread_print_info ***************************************************
 
+   Print information of the passed thread.
+   
 *******************************************************************************/
 
-threadobject *threads_table_next(threadobject *thread)
+void threads_thread_print_info(threadobject *t)
 {
-       threads_table_entry_t *tte;
-       threadobject          *next;
-       s4                     index;
-
-       index = thread->index;
-
-       /* get the passed entry */
-
-       assert((index > 0) && (index < threads_table.size));
-
-       tte = &(threads_table.table[index]);
-
-       /* get the requested entry */
+       java_lang_Thread *object;
+#if defined(WITH_CLASSPATH_GNU)
+       java_lang_String *namestring;
+#endif
+       utf              *name;
 
-       next = threads_table_get(tte->next);
+       assert(t->state != THREAD_STATE_NEW);
 
-       return next;
-}
+       /* the thread may be currently in initalization, don't print it */
 
+       object = (java_lang_Thread *) threads_thread_get_object(t);
 
-/* threads_table_dump *********************************************************
+       if (object != NULL) {
+               /* get thread name */
 
-   Dump the threads table for debugging purposes.
+#if defined(WITH_CLASSPATH_GNU)
+               LLNI_field_get_ref(object, name, namestring);
+               name = javastring_toutf((java_handle_t *) namestring, false);
+#elif defined(WITH_CLASSPATH_SUN) || defined(WITH_CLASSPATH_CLDC1_1)
+               /* FIXME: In cldc the name is a char[] */
+/*             name = object->name; */
+               name = utf_null;
+#else
+# error unknown classpath configuration
+#endif
 
-******************************************************************************/
+               printf("\"");
+               utf_display_printable_ascii(name);
+               printf("\"");
 
-#if !defined(NDEBUG)
-void threads_table_dump(void)
-{
-       s4 i;
-       s4 size;
-       ptrint index;
+               if (t->flags & THREAD_FLAG_DAEMON)
+                       printf(" daemon");
 
-       size = threads_table.size;
+               printf(" prio=%d", LLNI_field_direct(object, priority));
 
-       log_println("threads table ==========");
+#if SIZEOF_VOID_P == 8
+               printf(" t=0x%016lx tid=0x%016lx (%ld)",
+                          (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
+#else
+               printf(" t=0x%08x tid=0x%08x (%d)",
+                          (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
+#endif
 
-       log_println("size:    %d", size);
-       log_println("used:    %d", threads_table.used);
-       log_println("daemons: %d", threads_table.daemons);
+               printf(" index=%d", t->index);
 
-       for (i = 0; i < size; i++) {
-               index = threads_table.table[i].next;
+               /* print thread state */
 
-               if (threads_table.table[i].thread != NULL)
-                       log_println("%4d: thread=0x%08x, next=%d", i,
-                                               threads_table.table[i].thread->tid, (int) index);
-               else
-                       log_println("%4d: free, next=%d", i, (int) index);
+               switch (t->state) {
+               case THREAD_STATE_NEW:
+                       printf(" new");
+                       break;
+               case THREAD_STATE_RUNNABLE:
+                       printf(" runnable");
+                       break;
+               case THREAD_STATE_BLOCKED:
+                       printf(" blocked");
+                       break;
+               case THREAD_STATE_WAITING:
+                       printf(" waiting");
+                       break;
+               case THREAD_STATE_TIMED_WAITING:
+                       printf(" waiting on condition");
+                       break;
+               case THREAD_STATE_TERMINATED:
+                       printf(" terminated");
+                       break;
+               default:
+                       vm_abort("threads_thread_print_info: unknown thread state %d",
+                                        t->state);
+               }
        }
-
-       log_println("end of threads table ==========");
 }
-#endif
 
 
-/* threads_create_thread *******************************************************
+/* threads_get_current_tid *****************************************************
 
-   Creates and initializes an internal thread data-structure.
+   Return the tid of the current thread.
+   
+   RETURN VALUE:
+       the current tid
 
 *******************************************************************************/
 
-threadobject *threads_create_thread(void)
+ptrint threads_get_current_tid(void)
 {
        threadobject *thread;
 
-       /* allocate internal thread data-structure */
-
-#if defined(ENABLE_GC_BOEHM)
-       thread = GCNEW_UNCOLLECTABLE(threadobject, 1);
-#else
-       thread = NEW(threadobject);
-#endif
-
-#if defined(ENABLE_STATISTICS)
-       if (opt_stat)
-               size_threadobject += sizeof(threadobject);
-#endif
+       thread = THREADOBJECT;
 
-       /* initialize thread data structure */
+       /* this may happen during bootstrap */
 
-       threads_init_threadobject(thread);
-       lock_init_execution_env(thread);
+       if (thread == NULL)
+               return 0;
 
-       return thread;
+       return (ptrint) thread->tid;
 }
 
 
-/* threads_thread_start_internal ***********************************************
+/* threads_get_current_object **************************************************
 
-   Start an internal thread in the JVM.  No Java thread objects exists
-   so far.
-
-   IN:
-      name.......UTF-8 name of the thread
-      f..........function pointer to C function to start
+   Return the Java object of the current thread.
+   
+   RETURN VALUE:
+       the Java object
 
 *******************************************************************************/
 
-bool threads_thread_start_internal(utf *name, functionptr f)
+#include "native/include/java_lang_ThreadGroup.h"
+
+java_object_t *threads_get_current_object(void)
 {
-       threadobject       *thread;
-       java_lang_Thread   *t;
-#if defined(WITH_CLASSPATH_GNU)
-       java_lang_VMThread *vmt;
+#if defined(ENABLE_THREADS)
+       threadobject  *t;
+# if defined(ENABLE_JAVASE)
+       java_lang_ThreadGroup *group;
+# endif
 #endif
+       java_lang_Thread *o;
 
-       /* create internal thread data-structure */
-
-       thread = threads_create_thread();
+#if defined(ENABLE_THREADS)
+       t = THREADOBJECT;
+       o = threads_thread_get_object(t);
 
-       /* create the java thread object */
+# if defined(ENABLE_JAVASE)
+       /* TODO Do we really need this code?  Or should we check, when we
+          create the threads, that all of them have a group? */
+       /* TWISTI No, we don't need this code!  We need to allocate a
+          ThreadGroup before we initialize the main thread. */
 
-       t = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
+       LLNI_field_get_ref(o, group, group);
 
-       if (t == NULL)
-               return false;
+       if (group == NULL) {
+               /* ThreadGroup of currentThread is not initialized */
 
-#if defined(WITH_CLASSPATH_GNU)
-       vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
+               group = (java_lang_ThreadGroup *)
+                       native_new_and_init(class_java_lang_ThreadGroup);
 
-       if (vmt == NULL)
-               return false;
+               if (group == NULL)
+                       vm_abort("unable to create ThreadGroup");
 
-       vmt->thread = t;
-       vmt->vmdata = (java_lang_Object *) thread;
+               LLNI_field_set_ref(o, group, group);
+       }
+# endif
+#else
+       /* We just return a fake java.lang.Thread object, otherwise we get
+          NullPointerException's in GNU Classpath. */
 
-       t->vmThread = vmt;
-#elif defined(WITH_CLASSPATH_CLDC1_1)
-       t->vm_thread = (java_lang_Object *) thread;
+       o = builtin_new(class_java_lang_Thread);
 #endif
 
-       thread->object = t;
+       return o;
+}
 
-       thread->flags = THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON;
 
-       /* set java.lang.Thread fields */
+/* threads_thread_state_runnable ***********************************************
 
-       t->name     = (java_lang_String *) javastring_new(name);
-#if defined(ENABLE_JAVASE)
-       t->daemon   = true;
-#endif
-       t->priority = NORM_PRIORITY;
+   Set the current state of the given thread to THREAD_STATE_RUNNABLE.
 
-       /* start the thread */
+   NOTE: If the thread has already terminated, don't set the state.
+         This is important for threads_detach_thread.
 
-       threads_impl_thread_start(thread, f);
+*******************************************************************************/
 
-       /* everything's ok */
+void threads_thread_state_runnable(threadobject *t)
+{
+       /* Set the state inside a lock. */
 
-       return true;
+       threads_list_lock();
+
+       if (t->state != THREAD_STATE_TERMINATED)
+               t->state = THREAD_STATE_RUNNABLE;
+
+       DEBUGTHREADS("is RUNNABLE", t);
+
+       threads_list_unlock();
 }
 
 
-/* threads_thread_start ********************************************************
+/* threads_thread_state_waiting ************************************************
 
-   Start a Java thread in the JVM.  Only the java thread object exists
-   so far.
+   Set the current state of the given thread to THREAD_STATE_WAITING.
 
-   IN:
-      object.....the java thread object java.lang.Thread
+   NOTE: If the thread has already terminated, don't set the state.
+         This is important for threads_detach_thread.
 
 *******************************************************************************/
 
-void threads_thread_start(java_lang_Thread *object)
+void threads_thread_state_waiting(threadobject *t)
 {
-       threadobject *thread;
+       /* Set the state inside a lock. */
 
-       /* create internal thread data-structure */
+       threads_list_lock();
 
-       thread = threads_create_thread();
+       if (t->state != THREAD_STATE_TERMINATED)
+               t->state = THREAD_STATE_WAITING;
 
-       /* link the two objects together */
+       DEBUGTHREADS("is WAITING", t);
 
-       thread->object = object;
+       threads_list_unlock();
+}
 
-       /* this is a normal Java thread */
 
-       thread->flags = THREAD_FLAG_JAVA;
+/* threads_thread_state_timed_waiting ******************************************
 
-#if defined(ENABLE_JAVASE)
-       /* is this a daemon thread? */
+   Set the current state of the given thread to
+   THREAD_STATE_TIMED_WAITING.
 
-       if (object->daemon == true)
-               thread->flags |= THREAD_FLAG_DAEMON;
-#endif
+   NOTE: If the thread has already terminated, don't set the state.
+         This is important for threads_detach_thread.
 
-#if defined(WITH_CLASSPATH_GNU)
-       assert(object->vmThread);
-       assert(object->vmThread->vmdata == NULL);
+*******************************************************************************/
 
-       object->vmThread->vmdata = (java_lang_Object *) thread;
-#elif defined(WITH_CLASSPATH_CLDC1_1)
-       object->vm_thread = (java_lang_Object *) thread;
-#endif
+void threads_thread_state_timed_waiting(threadobject *t)
+{
+       /* Set the state inside a lock. */
 
-       /* Start the thread.  Don't pass a function pointer (NULL) since
-          we want Thread.run()V here. */
+       threads_list_lock();
 
-       threads_impl_thread_start(thread, NULL);
+       if (t->state != THREAD_STATE_TERMINATED)
+               t->state = THREAD_STATE_TIMED_WAITING;
+
+       DEBUGTHREADS("is TIMED_WAITING", t);
+
+       threads_list_unlock();
 }
 
 
-/* threads_get_current_tid *****************************************************
+/* threads_thread_state_terminated *********************************************
 
-   Return the tid of the current thread.
-   
-   RETURN VALUE:
-       the current tid
+   Set the current state of the given thread to
+   THREAD_STATE_TERMINATED.
 
 *******************************************************************************/
 
-ptrint threads_get_current_tid(void)
+void threads_thread_state_terminated(threadobject *t)
 {
-       threadobject *thread;
+       /* set the state in the lock */
 
-       thread = THREADOBJECT;
+       threads_list_lock();
 
-       /* this may happen during bootstrap */
+       t->state = THREAD_STATE_TERMINATED;
 
-       if (thread == NULL)
-               return 0;
+       DEBUGTHREADS("is TERMINATED", t);
 
-       return (ptrint) thread->tid;
+       threads_list_unlock();
 }
 
 
@@ -695,11 +689,11 @@ ptrint threads_get_current_tid(void)
 
 *******************************************************************************/
 
-utf *threads_thread_get_state(threadobject *thread)
+utf *threads_thread_get_state(threadobject *t)
 {
        utf *u;
 
-       switch (thread->state) {
+       switch (t->state) {
        case THREAD_STATE_NEW:
                u = utf_new_char("NEW");
                break;
@@ -719,7 +713,11 @@ utf *threads_thread_get_state(threadobject *thread)
                u = utf_new_char("TERMINATED");
                break;
        default:
-               vm_abort("threads_get_state: unknown thread state %d", thread->state);
+               vm_abort("threads_get_state: unknown thread state %d", t->state);
+
+               /* keep compiler happy */
+
+               u = NULL;
        }
 
        return u;
@@ -732,28 +730,26 @@ utf *threads_thread_get_state(threadobject *thread)
 
 *******************************************************************************/
 
-bool threads_thread_is_alive(threadobject *thread)
+bool threads_thread_is_alive(threadobject *t)
 {
-       bool result;
-
-       switch (thread->state) {
+       switch (t->state) {
        case THREAD_STATE_NEW:
        case THREAD_STATE_TERMINATED:
-               result = false;
-               break;
+               return false;
 
        case THREAD_STATE_RUNNABLE:
        case THREAD_STATE_BLOCKED:
        case THREAD_STATE_WAITING:
        case THREAD_STATE_TIMED_WAITING:
-               result = true;
-               break;
+               return true;
 
        default:
-               vm_abort("threads_is_alive: unknown thread state %d", thread->state);
+               vm_abort("threads_thread_is_alive: unknown thread state %d", t->state);
        }
 
-       return result;
+       /* keep compiler happy */
+
+       return false;
 }
 
 
@@ -766,122 +762,90 @@ bool threads_thread_is_alive(threadobject *thread)
 
 void threads_dump(void)
 {
-       threadobject     *t;
-       java_lang_Thread *object;
-       utf              *name;
+       threadobject *t;
 
        /* XXX we should stop the world here */
 
-       /* lock the threads table */
+       /* lock the threads lists */
 
-       threads_table_lock();
+       threads_list_lock();
 
        printf("Full thread dump CACAO "VERSION":\n");
 
        /* iterate over all started threads */
 
-       for (t = threads_table_first(); t != NULL; t = threads_table_next(t)) {
-               /* get thread object */
+       for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
+               /* ignore threads which are in state NEW */
+               if (t->state == THREAD_STATE_NEW)
+                       continue;
 
-               object = t->object;
+#if defined(ENABLE_GC_CACAO)
+               /* Suspend the thread. */
+               /* XXX Is the suspend reason correct? */
 
-               /* the thread may be currently in initalization, don't print it */
+               if (threads_suspend_thread(t, SUSPEND_REASON_JNI) == false)
+                       vm_abort("threads_dump: threads_suspend_thread failed");
+#endif
 
-               if (object != NULL) {
-                       /* get thread name */
+               /* Print thread info. */
 
-#if defined(ENABLE_JAVASE)
-                       name = javastring_toutf((java_objectheader *) object->name, false);
-#elif defined(ENABLE_JAVAME_CLDC1_1)
-                       name = object->name;
-#endif
+               printf("\n");
+               threads_thread_print_info(t);
+               printf("\n");
 
-                       printf("\n\"");
-                       utf_display_printable_ascii(name);
-                       printf("\"");
+               /* Print trace of thread. */
 
-                       if (t->flags & THREAD_FLAG_DAEMON)
-                               printf(" daemon");
+               threads_thread_print_stacktrace(t);
 
-                       printf(" prio=%d", object->priority);
+#if defined(ENABLE_GC_CACAO)
+               /* Resume the thread. */
 
-#if SIZEOF_VOID_P == 8
-                       printf(" tid=0x%016lx (%ld)", (ptrint) t->tid, (ptrint) t->tid);
-#else
-                       printf(" tid=0x%08x (%d)", (ptrint) t->tid, (ptrint) t->tid);
+               if (threads_resume_thread(t) == false)
+                       vm_abort("threads_dump: threads_resume_thread failed");
 #endif
-
-                       /* print thread state */
-
-                       switch (t->state) {
-                       case THREAD_STATE_NEW:
-                               printf(" new");
-                               break;
-                       case THREAD_STATE_RUNNABLE:
-                               printf(" runnable");
-                               break;
-                       case THREAD_STATE_BLOCKED:
-                               printf(" blocked");
-                               break;
-                       case THREAD_STATE_WAITING:
-                               printf(" waiting");
-                               break;
-                       case THREAD_STATE_TIMED_WAITING:
-                               printf(" waiting on condition");
-                               break;
-                       case THREAD_STATE_TERMINATED:
-                               printf(" terminated");
-                               break;
-                       default:
-                               vm_abort("threads_dump: unknown thread state %d", t->state);
-                       }
-
-                       printf("\n");
-
-                       /* print trace of thread */
-
-                       threads_thread_print_stacktrace(t);
-               }
        }
 
-       /* unlock the threads table */
+       /* unlock the threads lists */
 
-       threads_table_unlock();
+       threads_list_unlock();
 }
 
 
 /* threads_thread_print_stacktrace *********************************************
 
-   Print the current stacktrace of the current thread.
+   Print the current stacktrace of the given thread.
 
 *******************************************************************************/
 
 void threads_thread_print_stacktrace(threadobject *thread)
 {
-       stackframeinfo   *sfi;
-       stacktracebuffer *stb;
-       s4                dumpsize;
-
-       /* mark start of dump memory area */
+       stackframeinfo_t        *sfi;
+       java_handle_bytearray_t *ba;
+       stacktrace_t            *st;
 
-       dumpsize = dump_size();
-
-       /* create a stacktrace for the passed thread */
+       /* Build a stacktrace for the passed thread. */
 
        sfi = thread->_stackframeinfo;
+       ba  = stacktrace_get(sfi);
+       
+       if (ba != NULL) {
+               /* We need a critical section here as we use the byte-array
+                  data pointer directly. */
 
-       stb = stacktrace_create(sfi);
+               LLNI_CRITICAL_START;
+       
+               st = (stacktrace_t *) LLNI_array_data(ba);
+
+               /* Print stacktrace. */
 
-       /* print stacktrace */
+               stacktrace_print(st);
 
-       if (stb != NULL)
-               stacktrace_print_trace_from_buffer(stb);
+               LLNI_CRITICAL_END;
+       }
        else {
                puts("\t<<No stacktrace available>>");
                fflush(stdout);
        }
-
-       dump_release(dumpsize);
 }