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