1a7880f4eb239b2a62d6073f05eaa6339395bcd0
[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         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         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         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         /* Store the internal thread data-structure in the TSD. */
760
761         thread_set_current(t);
762
763         /* The thread is flagged and (non-)daemon thread, we can leave the
764            mutex. */
765
766         threads_mutex_join_unlock();
767
768         DEBUGTHREADS("attaching", t);
769
770         /* Get the thread name. */
771
772         if (vm_aargs != NULL) {
773                 u = utf_new_char(vm_aargs->name);
774         }
775         else {
776                 u = utf_null;
777         }
778
779         name = javastring_new(u);
780
781 #if defined(ENABLE_JAVASE)
782         /* Get the threadgroup. */
783
784         if (vm_aargs != NULL)
785                 group = (java_handle_t *) vm_aargs->group;
786         else
787                 group = NULL;
788
789         /* If no threadgroup was given, use the main threadgroup. */
790
791         if (group == NULL)
792                 group = threadgroup_main;
793 #endif
794
795 #if defined(ENABLE_INTRP)
796         /* create interpreter stack */
797
798         if (opt_intrp) {
799                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
800                 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
801         }
802 #endif
803
804         /* Create the Java thread object. */
805
806         if (!thread_create_object(t, name, group))
807                 return false;
808
809         /* The thread is completely initialized. */
810
811         thread_set_state_runnable(t);
812
813         return true;
814 }
815
816
817 /* thread_fprint_name **********************************************************
818
819    Print the name of the given thread to the given stream.
820
821    ARGUMENTS:
822        t ........ thread data-structure
823        stream ... stream to print to
824
825 *******************************************************************************/
826
827 void thread_fprint_name(threadobject *t, FILE *stream)
828 {
829         java_lang_Thread *to;
830
831 #if defined(WITH_CLASSPATH_GNU)
832         java_lang_String *name;
833 #elif defined(WITH_CLASSPATH_SUN) || defined(WITH_CLASSPATH_CLDC1_1)
834         java_chararray_t *name;
835 #endif
836
837         to = (java_lang_Thread *) thread_get_object(t);
838
839         if (to == NULL)
840                 vm_abort("");
841
842         LLNI_field_get_ref(to, name, name);
843
844 #if defined(WITH_CLASSPATH_GNU)
845
846         javastring_fprint((java_handle_t *) name, stream);
847
848 #elif defined(WITH_CLASSPATH_SUN) || defined(WITH_CLASSPATH_CLDC1_1)
849
850         /* FIXME: In OpenJDK and CLDC the name is a char[]. */
851         /* FIXME This prints to stdout. */
852         utf_display_printable_ascii(utf_null);
853
854 #else
855 # error unknown classpath configuration
856 #endif
857 }
858
859
860 /* thread_print_info ***********************************************************
861
862    Print information of the passed thread.
863
864    ARGUMENTS:
865        t ... thread data-structure.
866
867 *******************************************************************************/
868
869 void thread_print_info(threadobject *t)
870 {
871         java_lang_Thread *to;
872         int               state;
873
874         /* If the thread is currently in initalization, don't print it. */
875
876         to = (java_lang_Thread *) thread_get_object(t);
877
878         /* Print as much as we can when we are in state NEW. */
879
880         if (to != NULL) {
881                 /* Print thread name. */
882
883                 printf("\"");
884                 thread_fprint_name(t, stdout);
885                 printf("\"");
886         }
887         else {
888         }
889
890         if (thread_is_daemon(t))
891                 printf(" daemon");
892
893         if (to != NULL) {
894                 printf(" prio=%d", LLNI_field_direct(to, priority));
895         }
896
897 #if SIZEOF_VOID_P == 8
898         printf(" t=0x%016lx tid=0x%016lx (%ld)",
899                    (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
900 #else
901         printf(" t=0x%08x tid=0x%08x (%d)",
902                    (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
903 #endif
904
905         printf(" index=%d", t->index);
906
907         /* Print thread state. */
908
909         state = cacaothread_get_state(t);
910
911         switch (state) {
912         case THREAD_STATE_NEW:
913                 printf(" new");
914                 break;
915         case THREAD_STATE_RUNNABLE:
916                 printf(" runnable");
917                 break;
918         case THREAD_STATE_BLOCKED:
919                 printf(" blocked");
920                 break;
921         case THREAD_STATE_WAITING:
922                 printf(" waiting");
923                 break;
924         case THREAD_STATE_TIMED_WAITING:
925                 printf(" waiting on condition");
926                 break;
927         case THREAD_STATE_TERMINATED:
928                 printf(" terminated");
929                 break;
930         default:
931                 vm_abort("thread_print_info: unknown thread state %d", state);
932         }
933 }
934
935
936 /* threads_get_current_tid *****************************************************
937
938    Return the tid of the current thread.
939    
940    RETURN VALUE:
941        the current tid
942
943 *******************************************************************************/
944
945 intptr_t threads_get_current_tid(void)
946 {
947         threadobject *thread;
948
949         thread = THREADOBJECT;
950
951         /* this may happen during bootstrap */
952
953         if (thread == NULL)
954                 return 0;
955
956         return (intptr_t) thread->tid;
957 }
958
959
960 /* thread_set_state_runnable ***************************************************
961
962    Set the current state of the given thread to THREAD_STATE_RUNNABLE.
963
964    NOTE: If the thread has already terminated, don't set the state.
965          This is important for threads_detach_thread.
966
967 *******************************************************************************/
968
969 void thread_set_state_runnable(threadobject *t)
970 {
971         /* Set the state inside a lock. */
972
973         threadlist_lock();
974
975         if (t->state != THREAD_STATE_TERMINATED) {
976                 t->state = THREAD_STATE_RUNNABLE;
977
978                 DEBUGTHREADS("is RUNNABLE", t);
979         }
980
981         threadlist_unlock();
982 }
983
984
985 /* thread_set_state_waiting ****************************************************
986
987    Set the current state of the given thread to THREAD_STATE_WAITING.
988
989    NOTE: If the thread has already terminated, don't set the state.
990          This is important for threads_detach_thread.
991
992 *******************************************************************************/
993
994 void thread_set_state_waiting(threadobject *t)
995 {
996         /* Set the state inside a lock. */
997
998         threadlist_lock();
999
1000         if (t->state != THREAD_STATE_TERMINATED) {
1001                 t->state = THREAD_STATE_WAITING;
1002
1003                 DEBUGTHREADS("is WAITING", t);
1004         }
1005
1006         threadlist_unlock();
1007 }
1008
1009
1010 /* thread_set_state_timed_waiting **********************************************
1011
1012    Set the current state of the given thread to
1013    THREAD_STATE_TIMED_WAITING.
1014
1015    NOTE: If the thread has already terminated, don't set the state.
1016          This is important for threads_detach_thread.
1017
1018 *******************************************************************************/
1019
1020 void thread_set_state_timed_waiting(threadobject *t)
1021 {
1022         /* Set the state inside a lock. */
1023
1024         threadlist_lock();
1025
1026         if (t->state != THREAD_STATE_TERMINATED) {
1027                 t->state = THREAD_STATE_TIMED_WAITING;
1028
1029                 DEBUGTHREADS("is TIMED_WAITING", t);
1030         }
1031
1032         threadlist_unlock();
1033 }
1034
1035
1036 /* thread_set_state_terminated *************************************************
1037
1038    Set the current state of the given thread to
1039    THREAD_STATE_TERMINATED.
1040
1041 *******************************************************************************/
1042
1043 void thread_set_state_terminated(threadobject *t)
1044 {
1045         /* Set the state inside a lock. */
1046
1047         threadlist_lock();
1048
1049         t->state = THREAD_STATE_TERMINATED;
1050
1051         DEBUGTHREADS("is TERMINATED", t);
1052
1053         threadlist_unlock();
1054 }
1055
1056
1057 /* thread_get_thread **********************************************************
1058
1059    Return the thread data structure of the given Java thread object.
1060
1061    ARGUMENTS:
1062        h ... java.lang.{VM}Thread object
1063
1064    RETURN VALUE:
1065        the thread object
1066
1067 *******************************************************************************/
1068
1069 threadobject *thread_get_thread(java_handle_t *h)
1070 {
1071         threadobject       *t;
1072 #if defined(WITH_CLASSPATH_GNU)
1073         java_lang_VMThread *vmto;
1074         java_lang_Object   *to;
1075 #endif
1076 #if defined(WITH_CLASSPATH_SUN)
1077         bool                equal;
1078 #endif
1079
1080 #if defined(WITH_CLASSPATH_GNU)
1081
1082         vmto = (java_lang_VMThread *) h;
1083
1084         LLNI_field_get_val(vmto, vmdata, to);
1085
1086         t = (threadobject *) to;
1087
1088 #elif defined(WITH_CLASSPATH_SUN)
1089
1090         /* XXX This is just a quick hack. */
1091
1092         threadlist_lock();
1093
1094         for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
1095                 LLNI_equals(t->object, h, equal);
1096
1097                 if (equal == true)
1098                         break;
1099         }
1100
1101         threadlist_unlock();
1102
1103 #elif defined(WITH_CLASSPATH_CLDC1_1)
1104
1105         log_println("threads_get_thread: IMPLEMENT ME!");
1106
1107 #else
1108 # error unknown classpath configuration
1109 #endif
1110
1111         return t;
1112 }
1113
1114
1115 /* threads_thread_is_alive *****************************************************
1116
1117    Returns if the give thread is alive.
1118
1119 *******************************************************************************/
1120
1121 bool threads_thread_is_alive(threadobject *t)
1122 {
1123         int state;
1124
1125         state = cacaothread_get_state(t);
1126
1127         switch (state) {
1128         case THREAD_STATE_NEW:
1129         case THREAD_STATE_TERMINATED:
1130                 return false;
1131
1132         case THREAD_STATE_RUNNABLE:
1133         case THREAD_STATE_BLOCKED:
1134         case THREAD_STATE_WAITING:
1135         case THREAD_STATE_TIMED_WAITING:
1136                 return true;
1137
1138         default:
1139                 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
1140         }
1141
1142         /* keep compiler happy */
1143
1144         return false;
1145 }
1146
1147
1148 /* threads_dump ****************************************************************
1149
1150    Dumps info for all threads running in the JVM.  This function is
1151    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1152
1153 *******************************************************************************/
1154
1155 void threads_dump(void)
1156 {
1157         threadobject *t;
1158
1159         /* XXX we should stop the world here */
1160
1161         /* Lock the thread lists. */
1162
1163         threadlist_lock();
1164
1165         printf("Full thread dump CACAO "VERSION":\n");
1166
1167         /* iterate over all started threads */
1168
1169         for (t = threadlist_first(); t != NULL; t = threadlist_next(t)) {
1170                 /* ignore threads which are in state NEW */
1171                 if (t->state == THREAD_STATE_NEW)
1172                         continue;
1173
1174 #if defined(ENABLE_GC_CACAO)
1175                 /* Suspend the thread. */
1176                 /* XXX Is the suspend reason correct? */
1177
1178                 if (threads_suspend_thread(t, SUSPEND_REASON_JNI) == false)
1179                         vm_abort("threads_dump: threads_suspend_thread failed");
1180 #endif
1181
1182                 /* Print thread info. */
1183
1184                 printf("\n");
1185                 thread_print_info(t);
1186                 printf("\n");
1187
1188                 /* Print trace of thread. */
1189
1190                 stacktrace_print_of_thread(t);
1191
1192 #if defined(ENABLE_GC_CACAO)
1193                 /* Resume the thread. */
1194
1195                 if (threads_resume_thread(t) == false)
1196                         vm_abort("threads_dump: threads_resume_thread failed");
1197 #endif
1198         }
1199
1200         /* Unlock the thread lists. */
1201
1202         threadlist_unlock();
1203 }
1204
1205
1206 /*
1207  * These are local overrides for various environment variables in Emacs.
1208  * Please do not remove this and leave it at the end of the file, where
1209  * Emacs will automagically detect them.
1210  * ---------------------------------------------------------------------
1211  * Local variables:
1212  * mode: c
1213  * indent-tabs-mode: t
1214  * c-basic-offset: 4
1215  * tab-width: 4
1216  * End:
1217  * vim:noexpandtab:sw=4:ts=4:
1218  */