* src/threads/threads-common.c (threads_thread_create_internal):
[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 7831 2007-04-26 12:48:16Z 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_start_internal ***********************************************
310
311    Start an internal thread in the JVM.  No Java thread objects exists
312    so far.
313
314    IN:
315       name.......UTF-8 name of the thread
316       f..........function pointer to C function to start
317
318 *******************************************************************************/
319
320 bool threads_thread_start_internal(utf *name, functionptr f)
321 {
322         threadobject       *thread;
323         java_lang_Thread   *t;
324 #if defined(WITH_CLASSPATH_GNU)
325         java_lang_VMThread *vmt;
326 #endif
327
328         /* create internal thread data-structure */
329
330         thread = threads_create_thread();
331
332         /* create the java thread object */
333
334         t = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
335
336         if (t == NULL)
337                 return false;
338
339 #if defined(WITH_CLASSPATH_GNU)
340         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
341
342         if (vmt == NULL)
343                 return false;
344
345         vmt->thread = t;
346         vmt->vmdata = (java_lang_Object *) thread;
347
348         t->vmThread = vmt;
349 #elif defined(WITH_CLASSPATH_CLDC1_1)
350         t->vm_thread = (java_lang_Object *) thread;
351 #endif
352
353         thread->object     = t;
354         thread->flags      = THREAD_FLAG_DAEMON;
355
356         /* set java.lang.Thread fields */
357
358         t->name     = (java_lang_String *) javastring_new(name);
359 #if defined(ENABLE_JAVASE)
360         t->daemon   = true;
361 #endif
362         t->priority = NORM_PRIORITY;
363
364         /* start the thread */
365
366         threads_impl_thread_start(thread, f);
367
368         /* everything's ok */
369
370         return true;
371 }
372
373
374 /* threads_thread_start ********************************************************
375
376    Start a Java thread in the JVM.  Only the java thread object exists
377    so far.
378
379    IN:
380       object.....the java thread object java.lang.Thread
381
382 *******************************************************************************/
383
384 void threads_thread_start(java_lang_Thread *object)
385 {
386         threadobject *thread;
387
388         /* create internal thread data-structure */
389
390         thread = threads_create_thread();
391
392         /* link the two objects together */
393
394         thread->object = object;
395
396 #if defined(ENABLE_JAVASE)
397         /* is this a daemon thread? */
398
399         if (object->daemon == true)
400                 thread->flags |= THREAD_FLAG_DAEMON;
401 #endif
402
403 #if defined(WITH_CLASSPATH_GNU)
404         assert(object->vmThread);
405         assert(object->vmThread->vmdata == NULL);
406
407         object->vmThread->vmdata = (java_lang_Object *) thread;
408 #elif defined(WITH_CLASSPATH_CLDC1_1)
409         object->vm_thread = (java_lang_Object *) thread;
410 #endif
411
412         /* Start the thread.  Don't pass a function pointer (NULL) since
413            we want Thread.run()V here. */
414
415         threads_impl_thread_start(thread, NULL);
416 }
417
418
419 /* threads_get_current_tid *****************************************************
420
421    Return the tid of the current thread.
422    
423    RETURN VALUE:
424        the current tid
425
426 *******************************************************************************/
427
428 ptrint threads_get_current_tid(void)
429 {
430         threadobject *thread;
431
432         thread = THREADOBJECT;
433
434         /* this may happen during bootstrap */
435
436         if (thread == NULL)
437                 return 0;
438
439         return (ptrint) thread->tid;
440 }
441
442
443 /* threads_thread_get_state ****************************************************
444
445    Returns the current state of the given thread.
446
447 *******************************************************************************/
448
449 utf *threads_thread_get_state(threadobject *thread)
450 {
451         utf *u;
452
453         switch (thread->state) {
454         case THREAD_STATE_NEW:
455                 u = utf_new_char("NEW");
456                 break;
457         case THREAD_STATE_RUNNABLE:
458                 u = utf_new_char("RUNNABLE");
459                 break;
460         case THREAD_STATE_BLOCKED:
461                 u = utf_new_char("BLOCKED");
462                 break;
463         case THREAD_STATE_WAITING:
464                 u = utf_new_char("WAITING");
465                 break;
466         case THREAD_STATE_TIMED_WAITING:
467                 u = utf_new_char("TIMED_WAITING");
468                 break;
469         case THREAD_STATE_TERMINATED:
470                 u = utf_new_char("TERMINATED");
471                 break;
472         default:
473                 vm_abort("threads_get_state: unknown thread state %d", thread->state);
474         }
475
476         return u;
477 }
478
479
480 /* threads_thread_is_alive *****************************************************
481
482    Returns if the give thread is alive.
483
484 *******************************************************************************/
485
486 bool threads_thread_is_alive(threadobject *thread)
487 {
488         bool result;
489
490         switch (thread->state) {
491         case THREAD_STATE_NEW:
492         case THREAD_STATE_TERMINATED:
493                 result = false;
494                 break;
495
496         case THREAD_STATE_RUNNABLE:
497         case THREAD_STATE_BLOCKED:
498         case THREAD_STATE_WAITING:
499         case THREAD_STATE_TIMED_WAITING:
500                 result = true;
501                 break;
502
503         default:
504                 vm_abort("threads_is_alive: unknown thread state %d", thread->state);
505         }
506
507         return result;
508 }
509
510
511 /* threads_dump ****************************************************************
512
513    Dumps info for all threads running in the JVM.  This function is
514    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
515
516 *******************************************************************************/
517
518 void threads_dump(void)
519 {
520         threadobject     *thread;
521         java_lang_Thread *t;
522         utf              *name;
523
524         /* XXX we should stop the world here */
525
526         printf("Full thread dump CACAO "VERSION":\n");
527
528         /* iterate over all started threads */
529
530         thread = mainthreadobj;
531
532         do {
533                 /* get thread object */
534
535                 t = thread->object;
536
537                 /* the thread may be currently in initalization, don't print it */
538
539                 if (t != NULL) {
540                         /* get thread name */
541
542 #if defined(ENABLE_JAVASE)
543                         name = javastring_toutf((java_objectheader *) t->name, false);
544 #elif defined(ENABLE_JAVAME_CLDC1_1)
545                         name = t->name;
546 #endif
547
548                         printf("\n\"");
549                         utf_display_printable_ascii(name);
550                         printf("\"");
551
552                         if (thread->flags & THREAD_FLAG_DAEMON)
553                                 printf(" daemon");
554
555                         printf(" prio=%d", t->priority);
556
557 #if SIZEOF_VOID_P == 8
558                         printf(" tid=0x%016lx (%ld)",
559                                    (ptrint) thread->tid, (ptrint) thread->tid);
560 #else
561                         printf(" tid=0x%08x (%d)",
562                                    (ptrint) thread->tid, (ptrint) thread->tid);
563 #endif
564
565                         /* print thread state */
566
567                         switch (thread->state) {
568                         case THREAD_STATE_NEW:
569                                 printf(" new");
570                                 break;
571                         case THREAD_STATE_RUNNABLE:
572                                 printf(" runnable");
573                                 break;
574                         case THREAD_STATE_BLOCKED:
575                                 printf(" blocked");
576                                 break;
577                         case THREAD_STATE_WAITING:
578                                 printf(" waiting");
579                                 break;
580                         case THREAD_STATE_TIMED_WAITING:
581                                 printf(" waiting on condition");
582                                 break;
583                         case THREAD_STATE_TERMINATED:
584                                 printf(" terminated");
585                                 break;
586                         default:
587                                 vm_abort("threads_dump: unknown thread state %d",
588                                                  thread->state);
589                         }
590
591                         printf("\n");
592
593                         /* print trace of thread */
594
595                         threads_thread_print_stacktrace(thread);
596                 }
597
598                 thread = thread->next;
599         } while ((thread != NULL) && (thread != mainthreadobj));
600 }
601
602
603 /* threads_thread_print_stacktrace *********************************************
604
605    Print the current stacktrace of the current thread.
606
607 *******************************************************************************/
608
609 void threads_thread_print_stacktrace(threadobject *thread)
610 {
611         stackframeinfo   *sfi;
612         stacktracebuffer *stb;
613         s4                dumpsize;
614
615         /* mark start of dump memory area */
616
617         dumpsize = dump_size();
618
619         /* create a stacktrace for the passed thread */
620
621         sfi = thread->_stackframeinfo;
622
623         stb = stacktrace_create(sfi);
624
625         /* print stacktrace */
626
627         if (stb != NULL)
628                 stacktrace_print_trace_from_buffer(stb);
629         else {
630                 puts("\t<<No stacktrace available>>");
631                 fflush(stdout);
632         }
633
634         dump_release(dumpsize);
635 }
636
637
638 /* threads_print_stacktrace ****************************************************
639
640    Print the current stacktrace of the current thread.
641
642 *******************************************************************************/
643
644 void threads_print_stacktrace(void)
645 {
646         threadobject *thread;
647
648         thread = THREADOBJECT;
649
650         threads_thread_print_stacktrace(thread);
651 }
652
653
654 /*
655  * These are local overrides for various environment variables in Emacs.
656  * Please do not remove this and leave it at the end of the file, where
657  * Emacs will automagically detect them.
658  * ---------------------------------------------------------------------
659  * Local variables:
660  * mode: c
661  * indent-tabs-mode: t
662  * c-basic-offset: 4
663  * tab-width: 4
664  * End:
665  * vim:noexpandtab:sw=4:ts=4:
666  */