* src/threads/threads-common.c (threads_thread_state_runnable): Don't
[cacao.git] / src / threads / threads-common.c
1 /* src/threads/threads-common.c - machine independent thread functions
2
3    Copyright (C) 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25 */
26
27
28 #include "config.h"
29
30 #include <assert.h>
31 #include <stdint.h>
32 #include <unistd.h>
33
34 #include "vm/types.h"
35
36 #include "mm/memory.h"
37
38 #include "native/jni.h"
39 #include "native/llni.h"
40
41 #include "native/include/java_lang_Object.h"
42 #include "native/include/java_lang_String.h"
43 #include "native/include/java_lang_Thread.h"
44
45 #if defined(WITH_CLASSPATH_GNU)
46 # include "native/include/java_lang_VMThread.h"
47 #endif
48
49 #include "threads/critical.h"
50 #include "threads/lock-common.h"
51 #include "threads/threads-common.h"
52
53 #include "toolbox/list.h"
54
55 #include "vm/builtin.h"
56 #include "vm/stringlocal.h"
57 #include "vm/vm.h"
58
59 #include "vm/jit/stacktrace.h"
60
61 #include "vmcore/class.h"
62
63 #if defined(ENABLE_STATISTICS)
64 # include "vmcore/options.h"
65 # include "vmcore/statistics.h"
66 #endif
67
68 #include "vmcore/utf8.h"
69
70
71 /* global variables ***********************************************************/
72
73 /* global threads list */
74 static list_t *list_threads;
75
76 /* global threads free-list */
77 static list_t *list_threads_free;
78
79 #if defined(__LINUX__)
80 /* XXX Remove for exact-GC. */
81 bool threads_pthreads_implementation_nptl;
82 #endif
83
84
85 /* threads_preinit *************************************************************
86
87    Do some early initialization of stuff required.
88
89    ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
90    is called AFTER this function!
91
92 *******************************************************************************/
93
94 void threads_preinit(void)
95 {
96         threadobject *mainthread;
97 #if defined(__LINUX__) && defined(_CS_GNU_LIBPTHREAD_VERSION)
98         char         *pathbuf;
99         size_t        len;
100 #endif
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 lists */
135
136         list_threads      = list_create(OFFSET(threadobject, linkage));
137         list_threads_free = list_create(OFFSET(threadobject, linkage));
138
139         /* Initialize the threads implementation (sets the thinlock on the
140            main thread). */
141
142         threads_impl_preinit();
143
144         /* create internal thread data-structure for the main thread */
145
146         mainthread = threads_thread_new();
147
148         /* thread is a Java thread and running */
149
150         mainthread->flags = THREAD_FLAG_JAVA;
151         mainthread->state = THREAD_STATE_RUNNABLE;
152
153         /* store the internal thread data-structure in the TSD */
154
155         threads_set_current_threadobject(mainthread);
156
157         /* initialize locking subsystems */
158
159         lock_init();
160
161         /* initialize the critical section */
162
163         critical_init();
164 }
165
166
167 /* threads_list_first **********************************************************
168
169    Return the first entry in the threads list.
170
171    NOTE: This function does not lock the lists.
172
173 *******************************************************************************/
174
175 threadobject *threads_list_first(void)
176 {
177         threadobject *t;
178
179         t = list_first_unsynced(list_threads);
180
181         return t;
182 }
183
184
185 /* threads_list_next ***********************************************************
186
187    Return the next entry in the threads list.
188
189    NOTE: This function does not lock the lists.
190
191 *******************************************************************************/
192
193 threadobject *threads_list_next(threadobject *t)
194 {
195         threadobject *next;
196
197         next = list_next_unsynced(list_threads, t);
198
199         return next;
200 }
201
202
203 /* threads_list_get_non_daemons ************************************************
204
205    Return the number of non-daemon threads.
206
207    NOTE: This function does a linear-search over the threads list,
208          because it's only used for joining the threads.
209
210 *******************************************************************************/
211
212 s4 threads_list_get_non_daemons(void)
213 {
214         threadobject *t;
215         s4            nondaemons;
216
217         /* lock the threads lists */
218
219         threads_list_lock();
220
221         nondaemons = 0;
222
223         for (t = threads_list_first(); t != NULL; t = threads_list_next(t)) {
224                 if (!(t->flags & THREAD_FLAG_DAEMON))
225                         nondaemons++;
226         }
227
228         /* unlock the threads lists */
229
230         threads_list_unlock();
231
232         return nondaemons;
233 }
234
235
236 /* threads_thread_new **********************************************************
237
238    Allocates and initializes an internal thread data-structure and
239    adds it to the threads list.
240
241 *******************************************************************************/
242
243 threadobject *threads_thread_new(void)
244 {
245         threadobject *t;
246
247         /* lock the threads-lists */
248
249         threads_list_lock();
250
251         /* try to get a thread from the free-list */
252
253         t = list_first_unsynced(list_threads_free);
254
255         /* is a free thread available? */
256
257         if (t != NULL) {
258                 /* yes, remove it from the free list */
259
260                 list_remove_unsynced(list_threads_free, t);
261         }
262         else {
263                 /* no, allocate a new one */
264
265 #if defined(ENABLE_GC_BOEHM)
266                 t = GCNEW_UNCOLLECTABLE(threadobject, 1);
267 #else
268                 t = NEW(threadobject);
269 #endif
270
271 #if defined(ENABLE_STATISTICS)
272                 if (opt_stat)
273                         size_threadobject += sizeof(threadobject);
274 #endif
275
276                 /* clear memory */
277
278                 MZERO(t, threadobject, 1);
279
280                 /* set the threads-index */
281
282                 t->index = list_threads->size + 1;
283
284 #if defined(ENABLE_GC_CACAO)
285                 /* register reference to java.lang.Thread with the GC */
286
287                 gc_reference_register((java_object_t **) &(t->object), GC_REFTYPE_THREADOBJECT);
288 #endif
289         }
290
291         /* pre-compute the thinlock-word */
292
293         assert(t->index != 0);
294
295         t->thinlock = lock_pre_compute_thinlock(t->index);
296         t->flags    = 0;
297         t->state    = THREAD_STATE_NEW;
298
299 #if defined(ENABLE_GC_CACAO)
300         t->flags |= THREAD_FLAG_IN_NATIVE; 
301 #endif
302
303         /* initialize the implementation-specific bits */
304
305         threads_impl_thread_new(t);
306
307         /* add the thread to the threads-list */
308
309         list_add_last_unsynced(list_threads, t);
310
311         /* unlock the threads-lists */
312
313         threads_list_unlock();
314
315         return t;
316 }
317
318
319 /* threads_thread_free *********************************************************
320
321    Frees an internal thread data-structure by removing it from the
322    threads-list and adding it to the free-list.
323
324    NOTE: The data-structure is NOT freed, the pointer keeps valid!
325
326 *******************************************************************************/
327
328 void threads_thread_free(threadobject *t)
329 {
330         int32_t  index;
331         uint32_t state;
332
333         /* lock the threads-lists */
334
335         threads_list_lock();
336
337         /* cleanup the implementation-specific bits */
338
339         threads_impl_thread_free(t);
340
341         /* remove the thread from the threads-list */
342
343         list_remove_unsynced(list_threads, t);
344
345         /* Clear memory, but keep the thread-index and the
346            thread-state. */
347
348         /* ATTENTION: Do this after list_remove, otherwise the linkage
349            pointers are invalid. */
350
351         index = t->index;
352         state = t->state;
353
354         MZERO(t, threadobject, 1);
355
356         t->index = index;
357         t->state = state;
358
359         /* add the thread to the free list */
360
361         list_add_first_unsynced(list_threads_free, t);
362
363         /* unlock the threads-lists */
364
365         threads_list_unlock();
366 }
367
368
369 /* threads_thread_start_internal ***********************************************
370
371    Start an internal thread in the JVM.  No Java thread objects exists
372    so far.
373
374    IN:
375       name.......UTF-8 name of the thread
376       f..........function pointer to C function to start
377
378 *******************************************************************************/
379
380 bool threads_thread_start_internal(utf *name, functionptr f)
381 {
382         threadobject       *t;
383         java_lang_Thread   *object;
384 #if defined(WITH_CLASSPATH_GNU)
385         java_lang_VMThread *vmt;
386 #endif
387
388         /* Enter the join-mutex, so if the main-thread is currently
389            waiting to join all threads, the number of non-daemon threads
390            is correct. */
391
392         threads_mutex_join_lock();
393
394         /* create internal thread data-structure */
395
396         t = threads_thread_new();
397
398         t->flags |= THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON;
399
400         /* The thread is flagged as (non-)daemon thread, we can leave the
401            mutex. */
402
403         threads_mutex_join_unlock();
404
405         /* create the java thread object */
406
407         object = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
408
409         /* XXX memory leak!!! */
410         if (object == NULL)
411                 return false;
412
413 #if defined(WITH_CLASSPATH_GNU)
414         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
415
416         /* XXX memory leak!!! */
417         if (vmt == NULL)
418                 return false;
419
420         LLNI_field_set_ref(vmt, thread, object);
421         LLNI_field_set_val(vmt, vmdata, (java_lang_Object *) t);
422
423         LLNI_field_set_ref(object, vmThread, vmt);
424 #elif defined(WITH_CLASSPATH_CLDC1_1)
425         LLNI_field_set_val(object, vm_thread, (java_lang_Object *) t);
426 #endif
427
428         t->object = object;
429
430         /* set java.lang.Thread fields */
431
432 #if defined(WITH_CLASSPATH_GNU)
433         LLNI_field_set_ref(object, name    , (java_lang_String *) javastring_new(name));
434 #elif defined(WITH_CLASSPATH_CLDC1_1)
435         /* FIXME: In cldc the name is a char[] */
436 /*      LLNI_field_set_ref(object, name    , (java_chararray *) javastring_new(name)); */
437         LLNI_field_set_ref(object, name    , NULL);
438 #endif
439
440 #if defined(ENABLE_JAVASE)
441         LLNI_field_set_val(object, daemon  , true);
442 #endif
443
444         LLNI_field_set_val(object, priority, NORM_PRIORITY);
445
446         /* start the thread */
447
448         threads_impl_thread_start(t, f);
449
450         /* everything's ok */
451
452         return true;
453 }
454
455
456 /* threads_thread_start ********************************************************
457
458    Start a Java thread in the JVM.  Only the java thread object exists
459    so far.
460
461    IN:
462       object.....the java thread object java.lang.Thread
463
464 *******************************************************************************/
465
466 void threads_thread_start(java_lang_Thread *object)
467 {
468         threadobject *thread;
469 #if defined(WITH_CLASSPATH_GNU)
470         java_lang_VMThread *vmt;
471 #endif
472
473         /* Enter the join-mutex, so if the main-thread is currently
474            waiting to join all threads, the number of non-daemon threads
475            is correct. */
476
477         threads_mutex_join_lock();
478
479         /* create internal thread data-structure */
480
481         thread = threads_thread_new();
482
483         /* this is a normal Java thread */
484
485         thread->flags |= THREAD_FLAG_JAVA;
486
487 #if defined(ENABLE_JAVASE)
488         /* is this a daemon thread? */
489
490         if (LLNI_field_direct(object, daemon) == true)
491                 thread->flags |= THREAD_FLAG_DAEMON;
492 #endif
493
494         /* The thread is flagged and (non-)daemon thread, we can leave the
495            mutex. */
496
497         threads_mutex_join_unlock();
498
499         /* link the two objects together */
500
501         thread->object = object;
502
503 #if defined(WITH_CLASSPATH_GNU)
504         LLNI_field_get_ref(object, vmThread, vmt);
505
506         assert(vmt);
507         assert(LLNI_field_direct(vmt, vmdata) == NULL);
508
509         LLNI_field_set_val(vmt, vmdata, (java_lang_Object *) thread);
510 #elif defined(WITH_CLASSPATH_CLDC1_1)
511         LLNI_field_set_val(object, vm_thread, (java_lang_Object *) thread);
512 #endif
513
514         /* Start the thread.  Don't pass a function pointer (NULL) since
515            we want Thread.run()V here. */
516
517         threads_impl_thread_start(thread, NULL);
518 }
519
520
521 /* threads_thread_print_info ***************************************************
522
523    Print information of the passed thread.
524    
525 *******************************************************************************/
526
527 void threads_thread_print_info(threadobject *t)
528 {
529         java_lang_Thread *object;
530 #if defined(WITH_CLASSPATH_GNU)
531         java_lang_String *namestring;
532 #endif
533         utf              *name;
534
535         assert(t->state != THREAD_STATE_NEW);
536
537         /* the thread may be currently in initalization, don't print it */
538
539         object = t->object;
540
541         if (object != NULL) {
542                 /* get thread name */
543
544 #if defined(WITH_CLASSPATH_GNU)
545                 LLNI_field_get_ref(object, name, namestring);
546                 name = javastring_toutf((java_handle_t *) namestring, false);
547 #elif defined(WITH_CLASSPATH_SUN) || defined(WITH_CLASSPATH_CLDC1_1)
548                 /* FIXME: In cldc the name is a char[] */
549 /*              name = object->name; */
550                 name = utf_null;
551 #else
552 # error unknown classpath configuration
553 #endif
554
555                 printf("\"");
556                 utf_display_printable_ascii(name);
557                 printf("\"");
558
559                 if (t->flags & THREAD_FLAG_DAEMON)
560                         printf(" daemon");
561
562                 printf(" prio=%d", LLNI_field_direct(object, priority));
563
564 #if SIZEOF_VOID_P == 8
565                 printf(" t=0x%016lx tid=0x%016lx (%ld)",
566                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
567 #else
568                 printf(" t=0x%08x tid=0x%08x (%d)",
569                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
570 #endif
571
572                 printf(" index=%d", t->index);
573
574                 /* print thread state */
575
576                 switch (t->state) {
577                 case THREAD_STATE_NEW:
578                         printf(" new");
579                         break;
580                 case THREAD_STATE_RUNNABLE:
581                         printf(" runnable");
582                         break;
583                 case THREAD_STATE_BLOCKED:
584                         printf(" blocked");
585                         break;
586                 case THREAD_STATE_WAITING:
587                         printf(" waiting");
588                         break;
589                 case THREAD_STATE_TIMED_WAITING:
590                         printf(" waiting on condition");
591                         break;
592                 case THREAD_STATE_TERMINATED:
593                         printf(" terminated");
594                         break;
595                 default:
596                         vm_abort("threads_thread_print_info: unknown thread state %d",
597                                          t->state);
598                 }
599         }
600 }
601
602
603 /* threads_get_current_tid *****************************************************
604
605    Return the tid of the current thread.
606    
607    RETURN VALUE:
608        the current tid
609
610 *******************************************************************************/
611
612 ptrint threads_get_current_tid(void)
613 {
614         threadobject *thread;
615
616         thread = THREADOBJECT;
617
618         /* this may happen during bootstrap */
619
620         if (thread == NULL)
621                 return 0;
622
623         return (ptrint) thread->tid;
624 }
625
626
627 /* threads_thread_state_runnable ***********************************************
628
629    Set the current state of the given thread to THREAD_STATE_RUNNABLE.
630
631    NOTE: If the thread has already terminated, don't set the state.
632          This is important for threads_detach_thread.
633
634 *******************************************************************************/
635
636 void threads_thread_state_runnable(threadobject *t)
637 {
638         /* Set the state inside a lock. */
639
640         threads_list_lock();
641
642         if (t->state != THREAD_STATE_TERMINATED)
643                 t->state = THREAD_STATE_RUNNABLE;
644
645         threads_list_unlock();
646 }
647
648
649 /* threads_thread_state_waiting ************************************************
650
651    Set the current state of the given thread to THREAD_STATE_WAITING.
652
653    NOTE: If the thread has already terminated, don't set the state.
654          This is important for threads_detach_thread.
655
656 *******************************************************************************/
657
658 void threads_thread_state_waiting(threadobject *t)
659 {
660         /* Set the state inside a lock. */
661
662         threads_list_lock();
663
664         if (t->state != THREAD_STATE_TERMINATED)
665                 t->state = THREAD_STATE_WAITING;
666
667         threads_list_unlock();
668 }
669
670
671 /* threads_thread_state_timed_waiting ******************************************
672
673    Set the current state of the given thread to
674    THREAD_STATE_TIMED_WAITING.
675
676    NOTE: If the thread has already terminated, don't set the state.
677          This is important for threads_detach_thread.
678
679 *******************************************************************************/
680
681 void threads_thread_state_timed_waiting(threadobject *t)
682 {
683         /* Set the state inside a lock. */
684
685         threads_list_lock();
686
687         if (t->state != THREAD_STATE_TERMINATED)
688                 t->state = THREAD_STATE_TIMED_WAITING;
689
690         threads_list_unlock();
691 }
692
693
694 /* threads_thread_state_terminated *********************************************
695
696    Set the current state of the given thread to
697    THREAD_STATE_TERMINATED.
698
699 *******************************************************************************/
700
701 void threads_thread_state_terminated(threadobject *t)
702 {
703         /* set the state in the lock */
704
705         threads_list_lock();
706
707         t->state = THREAD_STATE_TERMINATED;
708
709         threads_list_unlock();
710 }
711
712
713 /* threads_thread_get_state ****************************************************
714
715    Returns the current state of the given thread.
716
717 *******************************************************************************/
718
719 utf *threads_thread_get_state(threadobject *t)
720 {
721         utf *u;
722
723         switch (t->state) {
724         case THREAD_STATE_NEW:
725                 u = utf_new_char("NEW");
726                 break;
727         case THREAD_STATE_RUNNABLE:
728                 u = utf_new_char("RUNNABLE");
729                 break;
730         case THREAD_STATE_BLOCKED:
731                 u = utf_new_char("BLOCKED");
732                 break;
733         case THREAD_STATE_WAITING:
734                 u = utf_new_char("WAITING");
735                 break;
736         case THREAD_STATE_TIMED_WAITING:
737                 u = utf_new_char("TIMED_WAITING");
738                 break;
739         case THREAD_STATE_TERMINATED:
740                 u = utf_new_char("TERMINATED");
741                 break;
742         default:
743                 vm_abort("threads_get_state: unknown thread state %d", t->state);
744
745                 /* keep compiler happy */
746
747                 u = NULL;
748         }
749
750         return u;
751 }
752
753
754 /* threads_thread_is_alive *****************************************************
755
756    Returns if the give thread is alive.
757
758 *******************************************************************************/
759
760 bool threads_thread_is_alive(threadobject *t)
761 {
762         switch (t->state) {
763         case THREAD_STATE_NEW:
764         case THREAD_STATE_TERMINATED:
765                 return false;
766
767         case THREAD_STATE_RUNNABLE:
768         case THREAD_STATE_BLOCKED:
769         case THREAD_STATE_WAITING:
770         case THREAD_STATE_TIMED_WAITING:
771                 return true;
772
773         default:
774                 vm_abort("threads_thread_is_alive: unknown thread state %d", t->state);
775         }
776
777         /* keep compiler happy */
778
779         return false;
780 }
781
782
783 /* threads_dump ****************************************************************
784
785    Dumps info for all threads running in the JVM.  This function is
786    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
787
788 *******************************************************************************/
789
790 void threads_dump(void)
791 {
792         threadobject *t;
793
794         /* XXX we should stop the world here */
795
796         /* lock the threads lists */
797
798         threads_list_lock();
799
800         printf("Full thread dump CACAO "VERSION":\n");
801
802         /* iterate over all started threads */
803
804         for (t = threads_list_first(); t != NULL; t = threads_list_next(t)) {
805                 /* print thread info */
806
807                 printf("\n");
808                 threads_thread_print_info(t);
809                 printf("\n");
810
811                 /* print trace of thread */
812
813                 threads_thread_print_stacktrace(t);
814         }
815
816         /* unlock the threads lists */
817
818         threads_list_unlock();
819 }
820
821
822 /* threads_thread_print_stacktrace *********************************************
823
824    Print the current stacktrace of the current thread.
825
826 *******************************************************************************/
827
828 void threads_thread_print_stacktrace(threadobject *thread)
829 {
830         stackframeinfo   *sfi;
831         stacktracebuffer *stb;
832         s4                dumpsize;
833
834         /* mark start of dump memory area */
835
836         dumpsize = dump_size();
837
838         /* create a stacktrace for the passed thread */
839
840         sfi = thread->_stackframeinfo;
841
842         stb = stacktrace_create(sfi);
843
844         /* print stacktrace */
845
846         if (stb != NULL)
847                 stacktrace_print_trace_from_buffer(stb);
848         else {
849                 puts("\t<<No stacktrace available>>");
850                 fflush(stdout);
851         }
852
853         dump_release(dumpsize);
854 }
855
856
857 /* threads_print_stacktrace ****************************************************
858
859    Print the current stacktrace of the current thread.
860
861 *******************************************************************************/
862
863 void threads_print_stacktrace(void)
864 {
865         threadobject *thread;
866
867         thread = THREADOBJECT;
868
869         threads_thread_print_stacktrace(thread);
870 }
871
872
873 /*
874  * These are local overrides for various environment variables in Emacs.
875  * Please do not remove this and leave it at the end of the file, where
876  * Emacs will automagically detect them.
877  * ---------------------------------------------------------------------
878  * Local variables:
879  * mode: c
880  * indent-tabs-mode: t
881  * c-basic-offset: 4
882  * tab-width: 4
883  * End:
884  * vim:noexpandtab:sw=4:ts=4:
885  */