afa21e8d62536859a74e54f48e4da5c0978a8c21
[cacao.git] / src / threads / thread.c
1 /* src/threads/thread.c - machine independent thread functions
2
3    Copyright (C) 2007, 2008
4    CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
5
6    This file is part of CACAO.
7
8    This program is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License as
10    published by the Free Software Foundation; either version 2, or (at
11    your option) any later version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23 */
24
25
26 #include "config.h"
27
28 #include <assert.h>
29 #include <stdint.h>
30 #include <unistd.h>
31
32 #include "vm/types.h"
33
34 #include "mm/memory.h"
35
36 #include "native/jni.h"
37 #include "native/llni.h"
38 #include "native/native.h"
39
40 #include "native/include/java_lang_Object.h"
41 #include "native/include/java_lang_String.h"
42 #include "native/include/java_lang_Thread.h"
43
44 #if defined(ENABLE_JAVASE)
45 # include "native/include/java_lang_ThreadGroup.h"
46 #endif
47
48 #if defined(WITH_CLASSPATH_GNU)
49 # include "native/include/java_lang_VMThread.h"
50 #endif
51
52 #include "threads/critical.h"
53 #include "threads/lock-common.h"
54 #include "threads/threadlist.h"
55 #include "threads/thread.h"
56
57 #include "vm/builtin.h"
58 #include "vm/exceptions.h"
59 #include "vm/stringlocal.h"
60 #include "vm/vm.h"
61
62 #include "vm/jit/stacktrace.h"
63
64 #include "vmcore/class.h"
65 #include "vmcore/method.h"
66 #include "vmcore/options.h"
67
68 #if defined(ENABLE_STATISTICS)
69 # include "vmcore/statistics.h"
70 #endif
71
72 #include "vmcore/utf8.h"
73
74
75 /* global variables ***********************************************************/
76
77 static methodinfo    *thread_method_init;
78 static java_handle_t *threadgroup_system;
79 static java_handle_t *threadgroup_main;
80
81 #if defined(__LINUX__)
82 /* XXX Remove for exact-GC. */
83 bool threads_pthreads_implementation_nptl;
84 #endif
85
86
87 /* static functions ***********************************************************/
88
89 static void          thread_create_initial_threadgroups(void);
90 static void          thread_create_initial_thread(void);
91 static threadobject *thread_new(void);
92
93
94 /* threads_preinit *************************************************************
95
96    Do some early initialization of stuff required.
97
98 *******************************************************************************/
99
100 void threads_preinit(void)
101 {
102         threadobject *mainthread;
103 #if defined(__LINUX__) && defined(_CS_GNU_LIBPTHREAD_VERSION)
104         char         *pathbuf;
105         size_t        len;
106 #endif
107
108         TRACESUBSYSTEMINITIALIZATION("threads_preinit");
109
110 #if defined(__LINUX__)
111         /* XXX Remove for exact-GC. */
112
113         /* On Linux we need to check the pthread implementation. */
114
115         /* _CS_GNU_LIBPTHREAD_VERSION (GNU C library only; since glibc 2.3.2) */
116         /* If the glibc is a pre-2.3.2 version, we fall back to
117            linuxthreads. */
118
119 # if defined(_CS_GNU_LIBPTHREAD_VERSION)
120         len = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, (size_t) 0);
121
122         /* Some systems return as length 0 (maybe cross-compilation
123            related).  In this case we also fall back to linuxthreads. */
124
125         if (len > 0) {
126                 pathbuf = MNEW(char, len);
127
128                 (void) confstr(_CS_GNU_LIBPTHREAD_VERSION, pathbuf, len);
129
130                 if (strstr(pathbuf, "NPTL") != NULL)
131                         threads_pthreads_implementation_nptl = true;
132                 else
133                         threads_pthreads_implementation_nptl = false;
134         }
135         else
136                 threads_pthreads_implementation_nptl = false;
137 # else
138         threads_pthreads_implementation_nptl = false;
139 # endif
140 #endif
141
142         /* Initialize the threads implementation (sets the thinlock on the
143            main thread). */
144
145         threads_impl_preinit();
146
147         /* Create internal thread data-structure for the main thread. */
148
149         mainthread = thread_new();
150
151         /* thread is a Java thread and running */
152
153         mainthread->flags |= THREAD_FLAG_JAVA;
154         mainthread->state = THREAD_STATE_RUNNABLE;
155
156         /* Store the internal thread data-structure in the TSD. */
157
158         thread_set_current(mainthread);
159 }
160
161
162 /* threads_init ****************************************************************
163
164    Initialize the main thread.
165
166 *******************************************************************************/
167
168 void threads_init(void)
169 {
170         TRACESUBSYSTEMINITIALIZATION("threads_init");
171
172         /* Create the system and main thread groups. */
173
174         thread_create_initial_threadgroups();
175
176         /* Cache the java.lang.Thread initialization method. */
177
178 #if defined(WITH_CLASSPATH_GNU)
179
180         thread_method_init =
181                 class_resolveclassmethod(class_java_lang_Thread,
182                                                                  utf_init,
183                                                                  utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
184                                                                  class_java_lang_Thread,
185                                                                  true);
186
187 #elif defined(WITH_CLASSPATH_SUN)
188
189         thread_method_init =
190                 class_resolveclassmethod(class_java_lang_Thread,
191                                                                  utf_init,
192                                                                  utf_new_char("(Ljava/lang/ThreadGroup;Ljava/lang/String;)V"),
193                                                                  class_java_lang_Thread,
194                                                                  true);
195
196 #elif defined(WITH_CLASSPATH_CLDC1_1)
197
198         thread_method_init =
199                 class_resolveclassmethod(class_java_lang_Thread,
200                                                                  utf_init,
201                                                                  utf_java_lang_String__void,
202                                                                  class_java_lang_Thread,
203                                                                  true);
204
205 #else
206 # error unknown classpath configuration
207 #endif
208
209         if (thread_method_init == NULL)
210                 vm_abort("threads_init: failed to resolve thread init method");
211
212         thread_create_initial_thread();
213 }
214
215
216 /* thread_create_object ********************************************************
217
218    Create a Java thread object for the given thread data-structure,
219    initializes it and adds the thread to the threadgroup.
220
221    ARGUMENTS:
222
223        t ....... thread
224        name .... thread name
225        group ... threadgroup
226
227    RETURN:
228
229 *******************************************************************************/
230
231 static bool thread_create_object(threadobject *t, java_handle_t *name, java_handle_t *group)
232 {
233         java_handle_t    *o;
234         java_lang_Thread *to;
235
236 #if defined(WITH_CLASSPATH_GNU)
237         java_lang_VMThread    *vmto;
238         classinfo             *c;
239         methodinfo            *m;
240         bool                   isdaemon;
241 #endif
242
243         /* Create a java.lang.Thread Java object. */
244
245         o = builtin_new(class_java_lang_Thread);
246
247         if (o == NULL)
248                 return false;
249
250         to = (java_lang_Thread *) o;
251
252         /* Set the Java object in the thread data-structure.  This
253            indicates that the thread is attached to the VM. */
254
255         threads_thread_set_object(t, (java_handle_t *) to);
256
257 #if defined(WITH_CLASSPATH_GNU)
258
259         /* Create a java.lang.VMThread Java object. */
260
261         vmto = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
262
263         if (vmto == NULL)
264                 return false;
265
266         /* Set the Java thread object in the Java VM-thread object. */
267
268         LLNI_field_set_ref(vmto, thread, to);
269
270         /* Set the thread data-structure in the Java VM-thread object. */
271
272         LLNI_field_set_val(vmto, vmdata, (java_lang_Object *) t);
273
274         /* Call:
275            java.lang.Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
276
277         isdaemon = thread_is_daemon(t);
278
279         (void) vm_call_method(thread_method_init, o, vmto, name, NORM_PRIORITY,
280                                                   isdaemon);
281
282         if (exceptions_get_exception())
283                 return false;
284
285         /* Set the threadgroup in the Java thread object. */
286
287         LLNI_field_set_ref(to, group, (java_lang_ThreadGroup *) group);
288
289         /* Add thread to the threadgroup. */
290
291         LLNI_class_get(group, c);
292
293         m = class_resolveclassmethod(c,
294                                                                  utf_addThread,
295                                                                  utf_java_lang_Thread__V,
296                                                                  class_java_lang_ThreadGroup,
297                                                                  true);
298
299         if (m == NULL)
300                 return false;
301
302         (void) vm_call_method(m, group, to);
303
304         if (exceptions_get_exception())
305                 return false;
306
307 #elif defined(WITH_CLASSPATH_SUN)
308
309         /* OpenJDK's java.lang.Thread does not have a VMThread field in
310            the class.  Nothing to do here. */
311
312         /* Set the priority.  java.lang.Thread.<init> requires it because
313            it sets the priority of the current thread to the parent's one
314            (which is the current thread in this case). */
315
316         LLNI_field_set_val(to, priority, NORM_PRIORITY);
317
318         /* Call:
319            java.lang.Thread.<init>(Ljava/lang/ThreadGroup;Ljava/lang/String;)V */
320
321         (void) vm_call_method(thread_method_init, o, group, name);
322
323         if (exceptions_get_exception())
324                 return false;
325
326 #elif defined(WITH_CLASSPATH_CLDC1_1)
327
328         /* Set the thread data-structure in the Java thread object. */
329
330         LLNI_field_set_val(to, vm_thread, (java_lang_Object *) t);
331
332         /* Call: public Thread(Ljava/lang/String;)V */
333
334         (void) vm_call_method(thread_method_init, o, name);
335
336         if (exceptions_get_exception())
337                 return false;
338
339 #else
340 # error unknown classpath configuration
341 #endif
342
343         return true;
344 }
345
346
347 /* thread_create_initial_threadgroups ******************************************
348
349    Create the initial threadgroups.
350
351    GNU Classpath:
352        Create the main threadgroup only and set the system
353        threadgroup to the main threadgroup.
354
355    SUN:
356        Create the system and main threadgroup.
357
358    CLDC:
359        This function is a no-op.
360
361 *******************************************************************************/
362
363 static void thread_create_initial_threadgroups(void)
364 {
365 #if defined(ENABLE_JAVASE)
366 # if defined(WITH_CLASSPATH_GNU)
367
368         /* Allocate and initialize the main thread group. */
369
370         threadgroup_main = native_new_and_init(class_java_lang_ThreadGroup);
371
372         if (threadgroup_main == NULL)
373                 vm_abort("thread_create_initial_threadgroups: failed to allocate main threadgroup");
374
375         /* Use the same threadgroup for system as for main. */
376
377         threadgroup_system = threadgroup_main;
378
379 # elif defined(WITH_CLASSPATH_SUN)
380
381         java_handle_t *name;
382         methodinfo    *m;
383
384         /* Allocate and initialize the system thread group. */
385
386         threadgroup_system = native_new_and_init(class_java_lang_ThreadGroup);
387
388         if (threadgroup_system == NULL)
389                 vm_abort("thread_create_initial_threadgroups: failed to allocate system threadgroup");
390
391         /* Allocate and initialize the main thread group. */
392
393         threadgroup_main = builtin_new(class_java_lang_ThreadGroup);
394
395         if (threadgroup_main == NULL)
396                 vm_abort("thread_create_initial_threadgroups: failed to allocate main threadgroup");
397
398         name = javastring_new(utf_main);
399
400         m = class_resolveclassmethod(class_java_lang_ThreadGroup,
401                                                                  utf_init,
402                                                                  utf_Ljava_lang_ThreadGroup_Ljava_lang_String__V,
403                                                                  class_java_lang_ThreadGroup,
404                                                                  true);
405
406         if (m == NULL)
407                 vm_abort("thread_create_initial_threadgroups: failed to resolve threadgroup init method");
408
409         (void) vm_call_method(m, threadgroup_main, threadgroup_system, name);
410
411         if (exceptions_get_exception())
412                 vm_abort("thread_create_initial_threadgroups: exception while initializing main threadgroup");
413
414 # else
415 #  error unknown classpath configuration
416 # endif
417 #endif
418 }
419
420
421 /* thread_create_initial_thread ***********************************************
422
423    Create the initial thread: main
424
425 *******************************************************************************/
426
427 static void thread_create_initial_thread(void)
428 {
429         threadobject  *t;
430         java_handle_t *name;
431
432         /* Get the main-thread (NOTE: The main thread is always the first
433            thread in the list). */
434
435         t = threadlist_first();
436
437         /* The thread name. */
438
439         name = javastring_new(utf_main);
440
441 #if defined(ENABLE_INTRP)
442         /* create interpreter stack */
443
444         if (opt_intrp) {
445                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
446                 mainthread->_global_sp = (Cell*) (intrp_main_stack + opt_stacksize);
447         }
448 #endif
449
450         /* Create the Java thread object. */
451
452         if (!thread_create_object(t, name, threadgroup_main))
453                 vm_abort("thread_create_initial_thread: failed to create Java object");
454
455         /* Initialize the implementation specific bits. */
456
457         threads_impl_init();
458
459         DEBUGTHREADS("starting (main)", t);
460 }
461
462
463 /* thread_new ******************************************************************
464
465    Allocates and initializes an internal thread data-structure and
466    adds it to the threads list.
467
468 *******************************************************************************/
469
470 static threadobject *thread_new(void)
471 {
472         int32_t       index;
473         threadobject *t;
474         
475         /* Lock the thread lists */
476
477         threadlist_lock();
478
479         index = threadlist_get_free_index();
480
481         /* Allocate a thread data structure. */
482
483         /* First, try to get one from the free-list. */
484
485         t = threadlist_free_first();
486
487         if (t != NULL) {
488                 /* Remove from free list. */
489
490                 threadlist_free_remove(t);
491
492                 /* Equivalent of MZERO on the else path */
493
494                 threads_impl_thread_clear(t);
495         }
496         else {
497 #if defined(ENABLE_GC_BOEHM)
498                 t = GCNEW_UNCOLLECTABLE(threadobject, 1);
499 #else
500                 t = NEW(threadobject);
501 #endif
502
503 #if defined(ENABLE_STATISTICS)
504                 if (opt_stat)
505                         size_threadobject += sizeof(threadobject);
506 #endif
507
508                 /* Clear memory. */
509
510                 MZERO(t, threadobject, 1);
511
512 #if defined(ENABLE_GC_CACAO)
513                 /* Register reference to java.lang.Thread with the GC. */
514                 /* FIXME is it ok to do this only once? */
515
516                 gc_reference_register(&(t->object), GC_REFTYPE_THREADOBJECT);
517                 gc_reference_register(&(t->_exceptionptr), GC_REFTYPE_THREADOBJECT);
518 #endif
519
520                 /* Initialize the implementation-specific bits. */
521
522                 threads_impl_thread_init(t);
523         }
524
525         /* Pre-compute the thinlock-word. */
526
527         assert(index != 0);
528
529         t->index     = index;
530         t->thinlock  = lock_pre_compute_thinlock(t->index);
531         t->flags     = 0;
532         t->state     = THREAD_STATE_NEW;
533
534 #if defined(ENABLE_GC_CACAO)
535         t->flags    |= THREAD_FLAG_IN_NATIVE; 
536 #endif
537
538         /* Initialize the implementation-specific bits. */
539
540         threads_impl_thread_reuse(t);
541
542         /* Add the thread to the thread list. */
543
544         threadlist_add(t);
545
546         /* Unlock the thread lists. */
547
548         threadlist_unlock();
549
550         return t;
551 }
552
553
554 /* thread_free *****************************************************************
555
556    Remove the thread from the threads-list and free the internal
557    thread data structure.  The thread index is added to the
558    thread-index free-list.
559
560    IN:
561        t ... thread data structure
562
563 *******************************************************************************/
564
565 void thread_free(threadobject *t)
566 {
567         /* Lock the thread lists. */
568
569         threadlist_lock();
570
571         /* Remove the thread from the thread-list. */
572
573         threadlist_remove(t);
574
575         /* Add the thread index to the free list. */
576
577         threadlist_index_add(t->index);
578
579         /* Set the reference to the Java object to NULL. */
580
581         threads_thread_set_object(t, NULL);
582
583         /* Add the thread data structure to the free list. */
584
585         threadlist_free_add(t);
586
587         /* Unlock the thread lists. */
588
589         threadlist_unlock();
590 }
591
592
593 /* threads_thread_start_internal ***********************************************
594
595    Start an internal thread in the JVM.  No Java thread objects exists
596    so far.
597
598    IN:
599       name.......UTF-8 name of the thread
600       f..........function pointer to C function to start
601
602 *******************************************************************************/
603
604 bool threads_thread_start_internal(utf *name, functionptr f)
605 {
606         threadobject *t;
607
608         /* Enter the join-mutex, so if the main-thread is currently
609            waiting to join all threads, the number of non-daemon threads
610            is correct. */
611
612         threads_mutex_join_lock();
613
614         /* Create internal thread data-structure. */
615
616         t = thread_new();
617
618         t->flags |= THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON;
619
620         /* The thread is flagged as (non-)daemon thread, we can leave the
621            mutex. */
622
623         threads_mutex_join_unlock();
624
625         /* Create the Java thread object. */
626
627         if (!thread_create_object(t, javastring_new(name), threadgroup_system))
628                 return false;
629
630         /* Start the thread. */
631
632         threads_impl_thread_start(t, f);
633
634         /* everything's ok */
635
636         return true;
637 }
638
639
640 /* threads_thread_start ********************************************************
641
642    Start a Java thread in the JVM.  Only the java thread object exists
643    so far.
644
645    IN:
646       object.....the java thread object java.lang.Thread
647
648 *******************************************************************************/
649
650 void threads_thread_start(java_handle_t *object)
651 {
652         java_lang_Thread   *to;
653         threadobject       *t;
654 #if defined(WITH_CLASSPATH_GNU)
655         java_lang_VMThread *vmto;
656 #endif
657
658         to = (java_lang_Thread *) object;
659
660         /* Enter the join-mutex, so if the main-thread is currently
661            waiting to join all threads, the number of non-daemon threads
662            is correct. */
663
664         threads_mutex_join_lock();
665
666         /* Create internal thread data-structure. */
667
668         t = thread_new();
669
670         /* this is a normal Java thread */
671
672         t->flags |= THREAD_FLAG_JAVA;
673
674 #if defined(ENABLE_JAVASE)
675         /* Is this a daemon thread? */
676
677         if (LLNI_field_direct(to, daemon) == true)
678                 t->flags |= THREAD_FLAG_DAEMON;
679 #endif
680
681         /* The thread is flagged and (non-)daemon thread, we can leave the
682            mutex. */
683
684         threads_mutex_join_unlock();
685
686         /* Link the two objects together. */
687
688         threads_thread_set_object(t, object);
689
690 #if defined(WITH_CLASSPATH_GNU)
691
692         /* Get the java.lang.VMThread object and do some sanity checks. */
693
694         LLNI_field_get_ref(to, vmThread, vmto);
695
696         assert(vmto);
697         assert(LLNI_field_direct(vmto, vmdata) == NULL);
698
699         LLNI_field_set_val(vmto, vmdata, (java_lang_Object *) t);
700
701 #elif defined(WITH_CLASSPATH_SUN)
702
703         /* Nothing to do. */
704
705 #elif defined(WITH_CLASSPATH_CLDC1_1)
706
707         LLNI_field_set_val(to, vm_thread, (java_lang_Object *) t);
708
709 #else
710 # error unknown classpath configuration
711 #endif
712
713         /* Start the thread.  Don't pass a function pointer (NULL) since
714            we want Thread.run()V here. */
715
716         threads_impl_thread_start(t, NULL);
717 }
718
719
720 /* threads_attach_current_thread ***********************************************
721
722    Attaches the current thread to the VM.  Used in JNI.
723
724 *******************************************************************************/
725
726 bool threads_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
727 {
728         bool           result;
729         threadobject  *t;
730         utf           *u;
731         java_handle_t *name;
732         java_handle_t *group;
733
734     /* If the current thread has already been attached, this operation
735            is a no-op. */
736
737         result = thread_current_is_attached();
738
739         if (result == true)
740                 return true;
741
742         /* Enter the join-mutex, so if the main-thread is currently
743            waiting to join all threads, the number of non-daemon threads
744            is correct. */
745
746         threads_mutex_join_lock();
747
748         /* Create internal thread data structure. */
749
750         t = thread_new();
751
752         /* Thread is a Java thread and running. */
753
754         t->flags = THREAD_FLAG_JAVA;
755
756         if (isdaemon)
757                 t->flags |= THREAD_FLAG_DAEMON;
758
759         /* The thread is flagged and (non-)daemon thread, we can leave the
760            mutex. */
761
762         threads_mutex_join_unlock();
763
764         DEBUGTHREADS("attaching", t);
765
766         /* Get the thread name. */
767
768         if (vm_aargs != NULL) {
769                 u = utf_new_char(vm_aargs->name);
770         }
771         else {
772                 u = utf_null;
773         }
774
775         name = javastring_new(u);
776
777 #if defined(ENABLE_JAVASE)
778         /* Get the threadgroup. */
779
780         if (vm_aargs != NULL)
781                 group = (java_handle_t *) vm_aargs->group;
782                 
783         /* If no threadgroup was given, use the main threadgroup. */
784
785         if (group == NULL)
786                 group = threadgroup_main;
787 #endif
788
789 #if defined(ENABLE_INTRP)
790         /* create interpreter stack */
791
792         if (opt_intrp) {
793                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
794                 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
795         }
796 #endif
797
798         /* Create the Java thread object. */
799
800         if (!thread_create_object(t, name, group))
801                 return false;
802
803         /* The thread is completely initialized. */
804
805         threads_thread_state_runnable(t);
806
807         return true;
808 }
809
810
811 /* threads_thread_print_info ***************************************************
812
813    Print information of the passed thread.
814    
815 *******************************************************************************/
816
817 void threads_thread_print_info(threadobject *t)
818 {
819         java_lang_Thread *object;
820 #if defined(WITH_CLASSPATH_GNU)
821         java_lang_String *namestring;
822 #endif
823         utf              *name;
824
825         assert(t->state != THREAD_STATE_NEW);
826
827         /* the thread may be currently in initalization, don't print it */
828
829         object = (java_lang_Thread *) threads_thread_get_object(t);
830
831         if (object != NULL) {
832                 /* get thread name */
833
834 #if defined(WITH_CLASSPATH_GNU)
835                 LLNI_field_get_ref(object, name, namestring);
836                 name = javastring_toutf((java_handle_t *) namestring, false);
837 #elif defined(WITH_CLASSPATH_SUN) || defined(WITH_CLASSPATH_CLDC1_1)
838                 /* FIXME: In cldc the name is a char[] */
839 /*              name = object->name; */
840                 name = utf_null;
841 #else
842 # error unknown classpath configuration
843 #endif
844
845                 printf("\"");
846                 utf_display_printable_ascii(name);
847                 printf("\"");
848
849                 if (thread_is_daemon(t))
850                         printf(" daemon");
851
852                 printf(" prio=%d", LLNI_field_direct(object, priority));
853
854 #if SIZEOF_VOID_P == 8
855                 printf(" t=0x%016lx tid=0x%016lx (%ld)",
856                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
857 #else
858                 printf(" t=0x%08x tid=0x%08x (%d)",
859                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
860 #endif
861
862                 printf(" index=%d", t->index);
863
864                 /* print thread state */
865
866                 switch (t->state) {
867                 case THREAD_STATE_NEW:
868                         printf(" new");
869                         break;
870                 case THREAD_STATE_RUNNABLE:
871                         printf(" runnable");
872                         break;
873                 case THREAD_STATE_BLOCKED:
874                         printf(" blocked");
875                         break;
876                 case THREAD_STATE_WAITING:
877                         printf(" waiting");
878                         break;
879                 case THREAD_STATE_TIMED_WAITING:
880                         printf(" waiting on condition");
881                         break;
882                 case THREAD_STATE_TERMINATED:
883                         printf(" terminated");
884                         break;
885                 default:
886                         vm_abort("threads_thread_print_info: unknown thread state %d",
887                                          t->state);
888                 }
889         }
890 }
891
892
893 /* threads_get_current_tid *****************************************************
894
895    Return the tid of the current thread.
896    
897    RETURN VALUE:
898        the current tid
899
900 *******************************************************************************/
901
902 intptr_t threads_get_current_tid(void)
903 {
904         threadobject *thread;
905
906         thread = THREADOBJECT;
907
908         /* this may happen during bootstrap */
909
910         if (thread == NULL)
911                 return 0;
912
913         return (intptr_t) thread->tid;
914 }
915
916
917 /* threads_thread_state_runnable ***********************************************
918
919    Set the current state of the given thread to THREAD_STATE_RUNNABLE.
920
921    NOTE: If the thread has already terminated, don't set the state.
922          This is important for threads_detach_thread.
923
924 *******************************************************************************/
925
926 void threads_thread_state_runnable(threadobject *t)
927 {
928         /* Set the state inside a lock. */
929
930         threadlist_lock();
931
932         if (t->state != THREAD_STATE_TERMINATED)
933                 t->state = THREAD_STATE_RUNNABLE;
934
935         DEBUGTHREADS("is RUNNABLE", t);
936
937         threadlist_unlock();
938 }
939
940
941 /* threads_thread_state_waiting ************************************************
942
943    Set the current state of the given thread to THREAD_STATE_WAITING.
944
945    NOTE: If the thread has already terminated, don't set the state.
946          This is important for threads_detach_thread.
947
948 *******************************************************************************/
949
950 void threads_thread_state_waiting(threadobject *t)
951 {
952         /* Set the state inside a lock. */
953
954         threadlist_lock();
955
956         if (t->state != THREAD_STATE_TERMINATED)
957                 t->state = THREAD_STATE_WAITING;
958
959         DEBUGTHREADS("is WAITING", t);
960
961         threadlist_unlock();
962 }
963
964
965 /* threads_thread_state_timed_waiting ******************************************
966
967    Set the current state of the given thread to
968    THREAD_STATE_TIMED_WAITING.
969
970    NOTE: If the thread has already terminated, don't set the state.
971          This is important for threads_detach_thread.
972
973 *******************************************************************************/
974
975 void threads_thread_state_timed_waiting(threadobject *t)
976 {
977         /* Set the state inside a lock. */
978
979         threadlist_lock();
980
981         if (t->state != THREAD_STATE_TERMINATED)
982                 t->state = THREAD_STATE_TIMED_WAITING;
983
984         DEBUGTHREADS("is TIMED_WAITING", t);
985
986         threadlist_unlock();
987 }
988
989
990 /* threads_thread_state_terminated *********************************************
991
992    Set the current state of the given thread to
993    THREAD_STATE_TERMINATED.
994
995 *******************************************************************************/
996
997 void threads_thread_state_terminated(threadobject *t)
998 {
999         /* set the state in the lock */
1000
1001         threadlist_lock();
1002
1003         t->state = THREAD_STATE_TERMINATED;
1004
1005         DEBUGTHREADS("is TERMINATED", t);
1006
1007         threadlist_unlock();
1008 }
1009
1010
1011 /* threads_thread_get_state ****************************************************
1012
1013    Returns the current state of the given thread.
1014
1015 *******************************************************************************/
1016
1017 utf *threads_thread_get_state(threadobject *t)
1018 {
1019         utf *u;
1020
1021         switch (t->state) {
1022         case THREAD_STATE_NEW:
1023                 u = utf_new_char("NEW");
1024                 break;
1025         case THREAD_STATE_RUNNABLE:
1026                 u = utf_new_char("RUNNABLE");
1027                 break;
1028         case THREAD_STATE_BLOCKED:
1029                 u = utf_new_char("BLOCKED");
1030                 break;
1031         case THREAD_STATE_WAITING:
1032                 u = utf_new_char("WAITING");
1033                 break;
1034         case THREAD_STATE_TIMED_WAITING:
1035                 u = utf_new_char("TIMED_WAITING");
1036                 break;
1037         case THREAD_STATE_TERMINATED:
1038                 u = utf_new_char("TERMINATED");
1039                 break;
1040         default:
1041                 vm_abort("threads_get_state: unknown thread state %d", t->state);
1042
1043                 /* keep compiler happy */
1044
1045                 u = NULL;
1046         }
1047
1048         return u;
1049 }
1050
1051
1052 /* thread_get_thread **********************************************************
1053
1054    Return the thread data structure of the given Java thread object.
1055
1056    ARGUMENTS:
1057        h ... java.lang.{VM}Thread object
1058
1059    RETURN VALUE:
1060        the thread object
1061
1062 *******************************************************************************/
1063
1064 threadobject *thread_get_thread(java_handle_t *h)
1065 {
1066         threadobject       *t;
1067 #if defined(WITH_CLASSPATH_GNU)
1068         java_lang_VMThread *vmto;
1069         java_lang_Object   *to;
1070 #endif
1071 #if defined(WITH_CLASSPATH_SUN)
1072         bool                equal;
1073 #endif
1074
1075 #if defined(WITH_CLASSPATH_GNU)
1076
1077         vmto = (java_lang_VMThread *) h;
1078
1079         LLNI_field_get_val(vmto, vmdata, to);
1080
1081         t = (threadobject *) to;
1082
1083 #elif defined(WITH_CLASSPATH_SUN)
1084
1085         /* XXX This is just a quick hack. */
1086
1087         threadlist_lock();
1088
1089         for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
1090                 LLNI_equals(t->object, h, equal);
1091
1092                 if (equal == true)
1093                         break;
1094         }
1095
1096         threadlist_unlock();
1097
1098 #elif defined(WITH_CLASSPATH_CLDC1_1)
1099
1100         log_println("threads_get_thread: IMPLEMENT ME!");
1101
1102 #else
1103 # error unknown classpath configuration
1104 #endif
1105
1106         return t;
1107 }
1108
1109
1110 /* threads_thread_is_alive *****************************************************
1111
1112    Returns if the give thread is alive.
1113
1114 *******************************************************************************/
1115
1116 bool threads_thread_is_alive(threadobject *t)
1117 {
1118         switch (t->state) {
1119         case THREAD_STATE_NEW:
1120         case THREAD_STATE_TERMINATED:
1121                 return false;
1122
1123         case THREAD_STATE_RUNNABLE:
1124         case THREAD_STATE_BLOCKED:
1125         case THREAD_STATE_WAITING:
1126         case THREAD_STATE_TIMED_WAITING:
1127                 return true;
1128
1129         default:
1130                 vm_abort("threads_thread_is_alive: unknown thread state %d", t->state);
1131         }
1132
1133         /* keep compiler happy */
1134
1135         return false;
1136 }
1137
1138
1139 /* threads_dump ****************************************************************
1140
1141    Dumps info for all threads running in the JVM.  This function is
1142    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1143
1144 *******************************************************************************/
1145
1146 void threads_dump(void)
1147 {
1148         threadobject *t;
1149
1150         /* XXX we should stop the world here */
1151
1152         /* Lock the thread lists. */
1153
1154         threadlist_lock();
1155
1156         printf("Full thread dump CACAO "VERSION":\n");
1157
1158         /* iterate over all started threads */
1159
1160         for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
1161                 /* ignore threads which are in state NEW */
1162                 if (t->state == THREAD_STATE_NEW)
1163                         continue;
1164
1165 #if defined(ENABLE_GC_CACAO)
1166                 /* Suspend the thread. */
1167                 /* XXX Is the suspend reason correct? */
1168
1169                 if (threads_suspend_thread(t, SUSPEND_REASON_JNI) == false)
1170                         vm_abort("threads_dump: threads_suspend_thread failed");
1171 #endif
1172
1173                 /* Print thread info. */
1174
1175                 printf("\n");
1176                 threads_thread_print_info(t);
1177                 printf("\n");
1178
1179                 /* Print trace of thread. */
1180
1181                 threads_thread_print_stacktrace(t);
1182
1183 #if defined(ENABLE_GC_CACAO)
1184                 /* Resume the thread. */
1185
1186                 if (threads_resume_thread(t) == false)
1187                         vm_abort("threads_dump: threads_resume_thread failed");
1188 #endif
1189         }
1190
1191         /* Unlock the thread lists. */
1192
1193         threadlist_unlock();
1194 }
1195
1196
1197 /* threads_thread_print_stacktrace *********************************************
1198
1199    Print the current stacktrace of the given thread.
1200
1201 *******************************************************************************/
1202
1203 void threads_thread_print_stacktrace(threadobject *thread)
1204 {
1205         stackframeinfo_t        *sfi;
1206         java_handle_bytearray_t *ba;
1207         stacktrace_t            *st;
1208
1209         /* Build a stacktrace for the passed thread. */
1210
1211         sfi = thread->_stackframeinfo;
1212         ba  = stacktrace_get(sfi);
1213         
1214         if (ba != NULL) {
1215                 /* We need a critical section here as we use the byte-array
1216                    data pointer directly. */
1217
1218                 LLNI_CRITICAL_START;
1219         
1220                 st = (stacktrace_t *) LLNI_array_data(ba);
1221
1222                 /* Print stacktrace. */
1223
1224                 stacktrace_print(st);
1225
1226                 LLNI_CRITICAL_END;
1227         }
1228         else {
1229                 puts("\t<<No stacktrace available>>");
1230                 fflush(stdout);
1231         }
1232 }
1233
1234
1235 /* threads_print_stacktrace ****************************************************
1236
1237    Print the current stacktrace of the current thread.
1238
1239 *******************************************************************************/
1240
1241 void threads_print_stacktrace(void)
1242 {
1243         threadobject *thread;
1244
1245         thread = THREADOBJECT;
1246
1247         threads_thread_print_stacktrace(thread);
1248 }
1249
1250
1251 /*
1252  * These are local overrides for various environment variables in Emacs.
1253  * Please do not remove this and leave it at the end of the file, where
1254  * Emacs will automagically detect them.
1255  * ---------------------------------------------------------------------
1256  * Local variables:
1257  * mode: c
1258  * indent-tabs-mode: t
1259  * c-basic-offset: 4
1260  * tab-width: 4
1261  * End:
1262  * vim:noexpandtab:sw=4:ts=4:
1263  */