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