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