* src/threads/threads-common.c (threads/critical.h): Added.
[cacao.git] / src / threads / threads-common.c
1 /* src/threads/threads-common.c - machine independent thread functions
2
3    Copyright (C) 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25    $Id: threads-common.c 7830 2007-04-26 11:14:39Z twisti $
26
27 */
28
29
30 #include "config.h"
31
32 #include <assert.h>
33
34 #include "vm/types.h"
35
36 #include "native/jni.h"
37
38 #include "native/include/java_lang_Object.h"
39 #include "native/include/java_lang_String.h"
40 #include "native/include/java_lang_Thread.h"
41
42 #if defined(WITH_CLASSPATH_GNU)
43 # include "native/include/java_lang_VMThread.h"
44 #endif
45
46 #include "threads/critical.h"
47 #include "threads/lock-common.h"
48 #include "threads/threads-common.h"
49
50 #include "vm/builtin.h"
51 #include "vm/stringlocal.h"
52 #include "vm/vm.h"
53
54 #include "vm/jit/stacktrace.h"
55
56 #include "vmcore/class.h"
57
58 #if defined(ENABLE_STATISTICS)
59 # include "vmcore/options.h"
60 # include "vmcore/statistics.h"
61 #endif
62
63 #include "vmcore/utf8.h"
64
65
66 /* global variables ***********************************************************/
67
68 /* global threads table */
69 static threads_table_t threads_table;
70
71
72 /* prototypes *****************************************************************/
73
74 static void threads_table_init(void);
75
76 #if !defined(NDEBUG) && 0
77 static void threads_table_dump(FILE *file);
78 #endif
79
80
81 /* threads_preinit *************************************************************
82
83    Do some early initialization of stuff required.
84
85    ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
86    is called AFTER this function!
87
88 *******************************************************************************/
89
90 void threads_preinit(void)
91 {
92         /* initialize the threads implementation */
93
94         threads_impl_preinit();
95
96         /* initialize the threads table */
97
98         threads_table_init();
99
100         /* initialize subsystems */
101
102         lock_init();
103
104         critical_init();
105 }
106
107
108 /* threads_table_init **********************************************************
109
110    Initialize the global threads table.
111
112 *******************************************************************************/
113
114 #define THREADS_INITIAL_TABLE_SIZE    8
115
116 static void threads_table_init(void)
117 {
118         s4 size;
119         s4 i;
120
121         size = THREADS_INITIAL_TABLE_SIZE;
122
123         threads_table.table = MNEW(threads_table_entry_t, size);
124         threads_table.size  = size;
125
126         /* link the entries in a freelist */
127
128         for (i = 0; i < size; i++) {
129                 threads_table.table[i].nextfree = i + 1;
130         }
131
132         /* terminate the freelist */
133
134         threads_table.table[size - 1].nextfree = 0;      /* index 0 is never free */
135 }
136
137
138 /* threads_table_add ***********************************************************
139
140    Add a thread to the global threads table. The index is entered in the
141    threadobject. The thinlock value for the thread is pre-computed.
142
143    IN:
144       thread............the thread to add
145
146    RETURN VALUE:
147       The table index for the newly added thread. This value has also been
148           entered in the threadobject.
149
150    PRE-CONDITION:
151       The caller must hold the threadlistlock!
152
153 *******************************************************************************/
154
155 s4 threads_table_add(threadobject *thread)
156 {
157         s4 index;
158         s4 oldsize;
159         s4 newsize;
160         s4 i;
161
162         /* table[0] serves as the head of the freelist */
163
164         index = threads_table.table[0].nextfree;
165
166         /* if we got a free index, use it */
167
168         if (index != 0) {
169 got_an_index:
170                 threads_table.table[0].nextfree   = threads_table.table[index].nextfree;
171                 threads_table.table[index].thread = thread;
172
173                 thread->index    = index;
174                 thread->thinlock = lock_pre_compute_thinlock(index);
175
176                 return index;
177         }
178
179         /* we must grow the table */
180
181         oldsize = threads_table.size;
182         newsize = oldsize * 2;
183
184         threads_table.table = MREALLOC(threads_table.table, threads_table_entry_t,
185                                                                    oldsize, newsize);
186         threads_table.size = newsize;
187
188         /* link the new entries to a free list */
189
190         for (i = oldsize; i < newsize; i++) {
191                 threads_table.table[i].nextfree = i + 1;
192         }
193
194         /* terminate the freelist */
195
196         threads_table.table[newsize - 1].nextfree = 0;   /* index 0 is never free */
197
198         /* use the first of the new entries */
199
200         index = oldsize;
201         goto got_an_index;
202 }
203
204
205 /* threads_table_remove *******************************************************
206
207    Remove a thread from the global threads table.
208
209    IN:
210       thread............the thread to remove
211
212    PRE-CONDITION:
213       The caller must hold the threadlistlock!
214
215 ******************************************************************************/
216
217 void threads_table_remove(threadobject *thread)
218 {
219         s4 index;
220
221         index = thread->index;
222
223         /* put the index into the freelist */
224
225         threads_table.table[index]      = threads_table.table[0];
226         threads_table.table[0].nextfree = index;
227
228         /* delete the index in the threadobject to discover bugs */
229 #if !defined(NDEBUG)
230         thread->index = 0;
231 #endif
232 }
233
234
235 /* threads_table_dump *********************************************************
236
237    Dump the threads table for debugging purposes.
238
239    IN:
240       file..............stream to write to
241
242 ******************************************************************************/
243
244 #if !defined(NDEBUG) && 0
245 static void threads_table_dump(FILE *file)
246 {
247         s4 i;
248         s4 size;
249         ptrint index;
250
251         pthread_mutex_lock(&threadlistlock);
252
253         size = threads_table.size;
254
255         fprintf(file, "======== THREADS TABLE (size %d) ========\n", size);
256
257         for (i=0; i<size; ++i) {
258                 index = threads_table.table[i].nextfree;
259
260                 fprintf(file, "%4d: ", i);
261
262                 if (index < size) {
263                         fprintf(file, "free, nextfree = %d\n", (int) index);
264                 }
265                 else {
266                         fprintf(file, "thread %p\n", (void*) threads_table.table[i].thread);
267                 }
268         }
269
270         fprintf(file, "======== END OF THREADS TABLE ========\n");
271
272         pthread_mutex_unlock(&threadlistlock);
273 }
274 #endif
275
276
277 /* threads_create_thread *******************************************************
278
279    Creates and initializes an internal thread data-structure.
280
281 *******************************************************************************/
282
283 threadobject *threads_create_thread(void)
284 {
285         threadobject *thread;
286
287         /* allocate internal thread data-structure */
288
289 #if defined(ENABLE_GC_BOEHM)
290         thread = GCNEW_UNCOLLECTABLE(threadobject, 1);
291 #else
292         thread = NEW(threadobject);
293 #endif
294
295 #if defined(ENABLE_STATISTICS)
296         if (opt_stat)
297                 size_threadobject += sizeof(threadobject);
298 #endif
299
300         /* initialize thread data structure */
301
302         threads_init_threadobject(thread);
303         lock_init_execution_env(thread);
304
305         return thread;
306 }
307
308
309 /* threads_thread_create_internal **********************************************
310
311    Creates an internal thread data-structure with the given name, plus
312    necessary Java objects for the VM (e.g. finalizer-thread,
313    signal-thread, ...).
314
315 *******************************************************************************/
316
317 threadobject *threads_thread_create_internal(utf *name)
318 {
319         threadobject       *thread;
320         java_lang_Thread   *t;
321 #if defined(WITH_CLASSPATH_GNU)
322         java_lang_VMThread *vmt;
323 #endif
324
325         /* create internal thread data-structure */
326
327         thread = threads_create_thread();
328
329         /* create the java thread object */
330
331         t = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
332
333         if (t == NULL)
334                 return NULL;
335
336 #if defined(WITH_CLASSPATH_GNU)
337         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
338
339         if (vmt == NULL)
340                 return NULL;
341
342         vmt->thread = t;
343         vmt->vmdata = (java_lang_Object *) thread;
344
345         t->vmThread = vmt;
346 #elif defined(WITH_CLASSPATH_CLDC1_1)
347         t->vm_thread = (java_lang_Object *) thread;
348 #endif
349
350         thread->object     = t;
351         thread->flags      = THREAD_FLAG_DAEMON;
352
353         /* set java.lang.Thread fields */
354
355         t->name     = (java_lang_String *) javastring_new(name);
356 #if defined(ENABLE_JAVASE)
357         t->daemon   = true;
358 #endif
359         t->priority = NORM_PRIORITY;
360
361         /* return the thread data-structure */
362
363         return thread;
364 }
365
366
367 /* threads_start_javathread ****************************************************
368
369    Start a thread in the JVM. Only the java thread object exists so far.
370
371    IN:
372       object.....the java thread object java.lang.Thread
373
374 *******************************************************************************/
375
376 void threads_start_javathread(java_lang_Thread *object)
377 {
378         threadobject *thread;
379
380         /* create internal thread data-structure */
381
382         thread = threads_create_thread();
383
384         /* link the two objects together */
385
386         thread->object = object;
387
388 #if defined(ENABLE_JAVASE)
389         /* is this a daemon thread? */
390
391         if (object->daemon == true)
392                 thread->flags |= THREAD_FLAG_DAEMON;
393 #endif
394
395 #if defined(WITH_CLASSPATH_GNU)
396         assert(object->vmThread);
397         assert(object->vmThread->vmdata == NULL);
398
399         object->vmThread->vmdata = (java_lang_Object *) thread;
400 #elif defined(WITH_CLASSPATH_CLDC1_1)
401         object->vm_thread = (java_lang_Object *) thread;
402 #endif
403
404         /* Actually start the thread.  Don't pass a function pointer
405            (NULL) since we want Thread.run()V here. */
406
407         threads_start_thread(thread, NULL);
408 }
409
410
411 /* threads_get_current_tid *****************************************************
412
413    Return the tid of the current thread.
414    
415    RETURN VALUE:
416        the current tid
417
418 *******************************************************************************/
419
420 ptrint threads_get_current_tid(void)
421 {
422         threadobject *thread;
423
424         thread = THREADOBJECT;
425
426         /* this may happen during bootstrap */
427
428         if (thread == NULL)
429                 return 0;
430
431         return (ptrint) thread->tid;
432 }
433
434
435 /* threads_thread_get_state ****************************************************
436
437    Returns the current state of the given thread.
438
439 *******************************************************************************/
440
441 utf *threads_thread_get_state(threadobject *thread)
442 {
443         utf *u;
444
445         switch (thread->state) {
446         case THREAD_STATE_NEW:
447                 u = utf_new_char("NEW");
448                 break;
449         case THREAD_STATE_RUNNABLE:
450                 u = utf_new_char("RUNNABLE");
451                 break;
452         case THREAD_STATE_BLOCKED:
453                 u = utf_new_char("BLOCKED");
454                 break;
455         case THREAD_STATE_WAITING:
456                 u = utf_new_char("WAITING");
457                 break;
458         case THREAD_STATE_TIMED_WAITING:
459                 u = utf_new_char("TIMED_WAITING");
460                 break;
461         case THREAD_STATE_TERMINATED:
462                 u = utf_new_char("TERMINATED");
463                 break;
464         default:
465                 vm_abort("threads_get_state: unknown thread state %d", thread->state);
466         }
467
468         return u;
469 }
470
471
472 /* threads_thread_is_alive *****************************************************
473
474    Returns if the give thread is alive.
475
476 *******************************************************************************/
477
478 bool threads_thread_is_alive(threadobject *thread)
479 {
480         bool result;
481
482         switch (thread->state) {
483         case THREAD_STATE_NEW:
484         case THREAD_STATE_TERMINATED:
485                 result = false;
486                 break;
487
488         case THREAD_STATE_RUNNABLE:
489         case THREAD_STATE_BLOCKED:
490         case THREAD_STATE_WAITING:
491         case THREAD_STATE_TIMED_WAITING:
492                 result = true;
493                 break;
494
495         default:
496                 vm_abort("threads_is_alive: unknown thread state %d", thread->state);
497         }
498
499         return result;
500 }
501
502
503 /* threads_dump ****************************************************************
504
505    Dumps info for all threads running in the JVM.  This function is
506    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
507
508 *******************************************************************************/
509
510 void threads_dump(void)
511 {
512         threadobject     *thread;
513         java_lang_Thread *t;
514         utf              *name;
515
516         /* XXX we should stop the world here */
517
518         printf("Full thread dump CACAO "VERSION":\n");
519
520         /* iterate over all started threads */
521
522         thread = mainthreadobj;
523
524         do {
525                 /* get thread object */
526
527                 t = thread->object;
528
529                 /* the thread may be currently in initalization, don't print it */
530
531                 if (t != NULL) {
532                         /* get thread name */
533
534 #if defined(ENABLE_JAVASE)
535                         name = javastring_toutf((java_objectheader *) t->name, false);
536 #elif defined(ENABLE_JAVAME_CLDC1_1)
537                         name = t->name;
538 #endif
539
540                         printf("\n\"");
541                         utf_display_printable_ascii(name);
542                         printf("\"");
543
544                         if (thread->flags & THREAD_FLAG_DAEMON)
545                                 printf(" daemon");
546
547                         printf(" prio=%d", t->priority);
548
549 #if SIZEOF_VOID_P == 8
550                         printf(" tid=0x%016lx (%ld)",
551                                    (ptrint) thread->tid, (ptrint) thread->tid);
552 #else
553                         printf(" tid=0x%08x (%d)",
554                                    (ptrint) thread->tid, (ptrint) thread->tid);
555 #endif
556
557                         /* print thread state */
558
559                         switch (thread->state) {
560                         case THREAD_STATE_NEW:
561                                 printf(" new");
562                                 break;
563                         case THREAD_STATE_RUNNABLE:
564                                 printf(" runnable");
565                                 break;
566                         case THREAD_STATE_BLOCKED:
567                                 printf(" blocked");
568                                 break;
569                         case THREAD_STATE_WAITING:
570                                 printf(" waiting");
571                                 break;
572                         case THREAD_STATE_TIMED_WAITING:
573                                 printf(" waiting on condition");
574                                 break;
575                         case THREAD_STATE_TERMINATED:
576                                 printf(" terminated");
577                                 break;
578                         default:
579                                 vm_abort("threads_dump: unknown thread state %d",
580                                                  thread->state);
581                         }
582
583                         printf("\n");
584
585                         /* print trace of thread */
586
587                         threads_thread_print_stacktrace(thread);
588                 }
589
590                 thread = thread->next;
591         } while ((thread != NULL) && (thread != mainthreadobj));
592 }
593
594
595 /* threads_thread_print_stacktrace *********************************************
596
597    Print the current stacktrace of the current thread.
598
599 *******************************************************************************/
600
601 void threads_thread_print_stacktrace(threadobject *thread)
602 {
603         stackframeinfo   *sfi;
604         stacktracebuffer *stb;
605         s4                dumpsize;
606
607         /* mark start of dump memory area */
608
609         dumpsize = dump_size();
610
611         /* create a stacktrace for the passed thread */
612
613         sfi = thread->_stackframeinfo;
614
615         stb = stacktrace_create(sfi);
616
617         /* print stacktrace */
618
619         if (stb != NULL)
620                 stacktrace_print_trace_from_buffer(stb);
621         else {
622                 puts("\t<<No stacktrace available>>");
623                 fflush(stdout);
624         }
625
626         dump_release(dumpsize);
627 }
628
629
630 /* threads_print_stacktrace ****************************************************
631
632    Print the current stacktrace of the current thread.
633
634 *******************************************************************************/
635
636 void threads_print_stacktrace(void)
637 {
638         threadobject *thread;
639
640         thread = THREADOBJECT;
641
642         threads_thread_print_stacktrace(thread);
643 }
644
645
646 /*
647  * These are local overrides for various environment variables in Emacs.
648  * Please do not remove this and leave it at the end of the file, where
649  * Emacs will automagically detect them.
650  * ---------------------------------------------------------------------
651  * Local variables:
652  * mode: c
653  * indent-tabs-mode: t
654  * c-basic-offset: 4
655  * tab-width: 4
656  * End:
657  * vim:noexpandtab:sw=4:ts=4:
658  */