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