Merged revisions 8056-8122 via svnmerge from
[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 8123 2007-06-20 23:50:55Z 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         /* 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_objectheader **) &(t->object));
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         s4 index;
331
332         /* lock the threads-lists */
333
334         threads_list_lock();
335
336         /* cleanup the implementation-specific bits */
337
338         threads_impl_thread_free(t);
339
340         /* remove the thread from the threads-list */
341
342         list_remove_unsynced(list_threads, t);
343
344         /* Clear memory, but keep the thread-index. */
345         /* ATTENTION: Do this after list_remove, otherwise the linkage
346            pointers are invalid. */
347
348         index = t->index;
349
350         MZERO(t, threadobject, 1);
351
352         t->index = index;
353
354         /* add the thread to the free list */
355
356         list_add_first_unsynced(list_threads_free, t);
357
358         /* unlock the threads-lists */
359
360         threads_list_unlock();
361 }
362
363
364 /* threads_thread_start_internal ***********************************************
365
366    Start an internal thread in the JVM.  No Java thread objects exists
367    so far.
368
369    IN:
370       name.......UTF-8 name of the thread
371       f..........function pointer to C function to start
372
373 *******************************************************************************/
374
375 bool threads_thread_start_internal(utf *name, functionptr f)
376 {
377         threadobject       *t;
378         java_lang_Thread   *object;
379 #if defined(WITH_CLASSPATH_GNU)
380         java_lang_VMThread *vmt;
381 #endif
382
383         /* Enter the join-mutex, so if the main-thread is currently
384            waiting to join all threads, the number of non-daemon threads
385            is correct. */
386
387         threads_mutex_join_lock();
388
389         /* create internal thread data-structure */
390
391         t = threads_thread_new();
392
393         t->flags |= THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON;
394
395         /* The thread is flagged as (non-)daemon thread, we can leave the
396            mutex. */
397
398         threads_mutex_join_unlock();
399
400         /* create the java thread object */
401
402         object = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
403
404         /* XXX memory leak!!! */
405         if (object == NULL)
406                 return false;
407
408 #if defined(WITH_CLASSPATH_GNU)
409         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
410
411         /* XXX memory leak!!! */
412         if (vmt == NULL)
413                 return false;
414
415         vmt->thread = object;
416         vmt->vmdata = (java_lang_Object *) t;
417
418         object->vmThread = vmt;
419 #elif defined(WITH_CLASSPATH_CLDC1_1)
420         object->vm_thread = (java_lang_Object *) t;
421 #endif
422
423         t->object = object;
424
425         /* set java.lang.Thread fields */
426
427 #if defined(WITH_CLASSPATH_GNU)
428         object->name     = (java_lang_String *) javastring_new(name);
429 #elif defined(WITH_CLASSPATH_CLDC1_1)
430         /* FIXME: In cldc the name is a char[] */
431 /*      object->name     = (java_chararray *) javastring_new(name); */
432         object->name     = NULL;
433 #endif
434
435 #if defined(ENABLE_JAVASE)
436         object->daemon   = true;
437 #endif
438
439         object->priority = NORM_PRIORITY;
440
441         /* start the thread */
442
443         threads_impl_thread_start(t, f);
444
445         /* everything's ok */
446
447         return true;
448 }
449
450
451 /* threads_thread_start ********************************************************
452
453    Start a Java thread in the JVM.  Only the java thread object exists
454    so far.
455
456    IN:
457       object.....the java thread object java.lang.Thread
458
459 *******************************************************************************/
460
461 void threads_thread_start(java_lang_Thread *object)
462 {
463         threadobject *thread;
464
465         /* Enter the join-mutex, so if the main-thread is currently
466            waiting to join all threads, the number of non-daemon threads
467            is correct. */
468
469         threads_mutex_join_lock();
470
471         /* create internal thread data-structure */
472
473         thread = threads_thread_new();
474
475         /* this is a normal Java thread */
476
477         thread->flags |= THREAD_FLAG_JAVA;
478
479 #if defined(ENABLE_JAVASE)
480         /* is this a daemon thread? */
481
482         if (object->daemon == true)
483                 thread->flags |= THREAD_FLAG_DAEMON;
484 #endif
485
486         /* The thread is flagged and (non-)daemon thread, we can leave the
487            mutex. */
488
489         threads_mutex_join_unlock();
490
491         /* link the two objects together */
492
493         thread->object = object;
494
495 #if defined(WITH_CLASSPATH_GNU)
496         assert(object->vmThread);
497         assert(object->vmThread->vmdata == NULL);
498
499         object->vmThread->vmdata = (java_lang_Object *) thread;
500 #elif defined(WITH_CLASSPATH_CLDC1_1)
501         object->vm_thread = (java_lang_Object *) thread;
502 #endif
503
504         /* Start the thread.  Don't pass a function pointer (NULL) since
505            we want Thread.run()V here. */
506
507         threads_impl_thread_start(thread, NULL);
508 }
509
510
511 /* threads_thread_print_info ***************************************************
512
513    Print information of the passed thread.
514    
515 *******************************************************************************/
516
517 void threads_thread_print_info(threadobject *t)
518 {
519         java_lang_Thread *object;
520         utf              *name;
521
522         assert(t->state != THREAD_STATE_NEW);
523
524         /* the thread may be currently in initalization, don't print it */
525
526         object = t->object;
527
528         if (object != NULL) {
529                 /* get thread name */
530
531 #if defined(ENABLE_JAVASE)
532                 name = javastring_toutf((java_objectheader *) object->name, false);
533 #elif defined(ENABLE_JAVAME_CLDC1_1)
534                 /* FIXME: In cldc the name is a char[] */
535 /*              name = object->name; */
536                 name = utf_null;
537 #endif
538
539                 printf("\"");
540                 utf_display_printable_ascii(name);
541                 printf("\"");
542
543                 if (t->flags & THREAD_FLAG_DAEMON)
544                         printf(" daemon");
545
546                 printf(" prio=%d", object->priority);
547
548 #if SIZEOF_VOID_P == 8
549                 printf(" t=0x%016lx tid=0x%016lx (%ld)",
550                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
551 #else
552                 printf(" t=0x%08x tid=0x%08x (%d)",
553                            (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
554 #endif
555
556                 printf(" index=%d", t->index);
557
558                 /* print thread state */
559
560                 switch (t->state) {
561                 case THREAD_STATE_NEW:
562                         printf(" new");
563                         break;
564                 case THREAD_STATE_RUNNABLE:
565                         printf(" runnable");
566                         break;
567                 case THREAD_STATE_BLOCKED:
568                         printf(" blocked");
569                         break;
570                 case THREAD_STATE_WAITING:
571                         printf(" waiting");
572                         break;
573                 case THREAD_STATE_TIMED_WAITING:
574                         printf(" waiting on condition");
575                         break;
576                 case THREAD_STATE_TERMINATED:
577                         printf(" terminated");
578                         break;
579                 default:
580                         vm_abort("threads_thread_print_info: unknown thread state %d",
581                                          t->state);
582                 }
583         }
584 }
585
586
587 /* threads_get_current_tid *****************************************************
588
589    Return the tid of the current thread.
590    
591    RETURN VALUE:
592        the current tid
593
594 *******************************************************************************/
595
596 ptrint threads_get_current_tid(void)
597 {
598         threadobject *thread;
599
600         thread = THREADOBJECT;
601
602         /* this may happen during bootstrap */
603
604         if (thread == NULL)
605                 return 0;
606
607         return (ptrint) thread->tid;
608 }
609
610
611 /* threads_thread_state_runnable ***********************************************
612
613    Set the current state of the given thread to THREAD_STATE_RUNNABLE.
614
615 *******************************************************************************/
616
617 void threads_thread_state_runnable(threadobject *t)
618 {
619         /* set the state inside the lock */
620
621         threads_list_lock();
622
623         t->state = THREAD_STATE_RUNNABLE;
624
625         threads_list_unlock();
626 }
627
628
629 /* threads_thread_state_waiting ************************************************
630
631    Set the current state of the given thread to THREAD_STATE_WAITING.
632
633 *******************************************************************************/
634
635 void threads_thread_state_waiting(threadobject *t)
636 {
637         /* set the state in the lock */
638
639         threads_list_lock();
640
641         t->state = THREAD_STATE_WAITING;
642
643         threads_list_unlock();
644 }
645
646
647 /* threads_thread_state_timed_waiting ******************************************
648
649    Set the current state of the given thread to
650    THREAD_STATE_TIMED_WAITING.
651
652 *******************************************************************************/
653
654 void threads_thread_state_timed_waiting(threadobject *t)
655 {
656         /* set the state in the lock */
657
658         threads_list_lock();
659
660         t->state = THREAD_STATE_TIMED_WAITING;
661
662         threads_list_unlock();
663 }
664
665
666 /* threads_thread_state_terminated *********************************************
667
668    Set the current state of the given thread to
669    THREAD_STATE_TERMINATED.
670
671 *******************************************************************************/
672
673 void threads_thread_state_terminated(threadobject *t)
674 {
675         /* set the state in the lock */
676
677         threads_list_lock();
678
679         t->state = THREAD_STATE_TERMINATED;
680
681         threads_list_unlock();
682 }
683
684
685 /* threads_thread_get_state ****************************************************
686
687    Returns the current state of the given thread.
688
689 *******************************************************************************/
690
691 utf *threads_thread_get_state(threadobject *t)
692 {
693         utf *u;
694
695         switch (t->state) {
696         case THREAD_STATE_NEW:
697                 u = utf_new_char("NEW");
698                 break;
699         case THREAD_STATE_RUNNABLE:
700                 u = utf_new_char("RUNNABLE");
701                 break;
702         case THREAD_STATE_BLOCKED:
703                 u = utf_new_char("BLOCKED");
704                 break;
705         case THREAD_STATE_WAITING:
706                 u = utf_new_char("WAITING");
707                 break;
708         case THREAD_STATE_TIMED_WAITING:
709                 u = utf_new_char("TIMED_WAITING");
710                 break;
711         case THREAD_STATE_TERMINATED:
712                 u = utf_new_char("TERMINATED");
713                 break;
714         default:
715                 vm_abort("threads_get_state: unknown thread state %d", t->state);
716
717                 /* keep compiler happy */
718
719                 u = NULL;
720         }
721
722         return u;
723 }
724
725
726 /* threads_thread_is_alive *****************************************************
727
728    Returns if the give thread is alive.
729
730 *******************************************************************************/
731
732 bool threads_thread_is_alive(threadobject *thread)
733 {
734         bool result;
735
736         switch (thread->state) {
737         case THREAD_STATE_NEW:
738         case THREAD_STATE_TERMINATED:
739                 result = false;
740                 break;
741
742         case THREAD_STATE_RUNNABLE:
743         case THREAD_STATE_BLOCKED:
744         case THREAD_STATE_WAITING:
745         case THREAD_STATE_TIMED_WAITING:
746                 result = true;
747                 break;
748
749         default:
750                 vm_abort("threads_is_alive: unknown thread state %d", thread->state);
751
752                 /* keep compiler happy */
753
754                 result = false;
755         }
756
757         return result;
758 }
759
760
761 /* threads_dump ****************************************************************
762
763    Dumps info for all threads running in the JVM.  This function is
764    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
765
766 *******************************************************************************/
767
768 void threads_dump(void)
769 {
770         threadobject *t;
771
772         /* XXX we should stop the world here */
773
774         /* lock the threads lists */
775
776         threads_list_lock();
777
778         printf("Full thread dump CACAO "VERSION":\n");
779
780         /* iterate over all started threads */
781
782         for (t = threads_list_first(); t != NULL; t = threads_list_next(t)) {
783                 /* print thread info */
784
785                 printf("\n");
786                 threads_thread_print_info(t);
787                 printf("\n");
788
789                 /* print trace of thread */
790
791                 threads_thread_print_stacktrace(t);
792         }
793
794         /* unlock the threads lists */
795
796         threads_list_unlock();
797 }
798
799
800 /* threads_thread_print_stacktrace *********************************************
801
802    Print the current stacktrace of the current thread.
803
804 *******************************************************************************/
805
806 void threads_thread_print_stacktrace(threadobject *thread)
807 {
808         stackframeinfo   *sfi;
809         stacktracebuffer *stb;
810         s4                dumpsize;
811
812         /* mark start of dump memory area */
813
814         dumpsize = dump_size();
815
816         /* create a stacktrace for the passed thread */
817
818         sfi = thread->_stackframeinfo;
819
820         stb = stacktrace_create(sfi);
821
822         /* print stacktrace */
823
824         if (stb != NULL)
825                 stacktrace_print_trace_from_buffer(stb);
826         else {
827                 puts("\t<<No stacktrace available>>");
828                 fflush(stdout);
829         }
830
831         dump_release(dumpsize);
832 }
833
834
835 /* threads_print_stacktrace ****************************************************
836
837    Print the current stacktrace of the current thread.
838
839 *******************************************************************************/
840
841 void threads_print_stacktrace(void)
842 {
843         threadobject *thread;
844
845         thread = THREADOBJECT;
846
847         threads_thread_print_stacktrace(thread);
848 }
849
850
851 /*
852  * These are local overrides for various environment variables in Emacs.
853  * Please do not remove this and leave it at the end of the file, where
854  * Emacs will automagically detect them.
855  * ---------------------------------------------------------------------
856  * Local variables:
857  * mode: c
858  * indent-tabs-mode: t
859  * c-basic-offset: 4
860  * tab-width: 4
861  * End:
862  * vim:noexpandtab:sw=4:ts=4:
863  */