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