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