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