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