* src/vm/jit/s390/patcher.c (patcher_wrapper): Formatting changes.
[cacao.git] / src / threads / native / threads.c
1 /* src/threads/native/threads.c - native threads support
2
3    Copyright (C) 1996-2005, 2006, 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.c 7338 2007-02-13 00:17:22Z twisti $
26
27 */
28
29
30 #include "config.h"
31
32 /* XXX cleanup these includes */
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <assert.h>
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <signal.h>
40 #include <sys/time.h>
41 #include <time.h>
42 #include <errno.h>
43
44 #include <pthread.h>
45
46 #include "vm/types.h"
47
48 #include "arch.h"
49
50 #if !defined(USE_FAKE_ATOMIC_INSTRUCTIONS)
51 # include "machine-instr.h"
52 #else
53 # include "threads/native/generic-primitives.h"
54 #endif
55
56 #include "mm/gc-common.h"
57 #include "mm/memory.h"
58
59 #include "native/jni.h"
60 #include "native/native.h"
61 #include "native/include/java_lang_Object.h"
62 #include "native/include/java_lang_String.h"
63 #include "native/include/java_lang_Throwable.h"
64 #include "native/include/java_lang_Thread.h"
65
66 #if defined(ENABLE_JAVASE)
67 # include "native/include/java_lang_ThreadGroup.h"
68 #endif
69
70 #if defined(WITH_CLASSPATH_GNU)
71 # include "native/include/java_lang_VMThread.h"
72 #endif
73
74 #include "threads/threads-common.h"
75
76 #include "threads/native/threads.h"
77
78 #include "toolbox/avl.h"
79 #include "toolbox/logging.h"
80
81 #include "vm/builtin.h"
82 #include "vm/exceptions.h"
83 #include "vm/global.h"
84 #include "vm/stringlocal.h"
85 #include "vm/vm.h"
86
87 #include "vm/jit/asmpart.h"
88
89 #include "vmcore/options.h"
90
91 #if !defined(__DARWIN__)
92 # if defined(__LINUX__)
93 #  define GC_LINUX_THREADS
94 # elif defined(__MIPS__)
95 #  define GC_IRIX_THREADS
96 # endif
97 # include <semaphore.h>
98 # if defined(ENABLE_GC_BOEHM)
99 #  include "mm/boehm-gc/include/gc.h"
100 # endif
101 #endif
102
103 #if defined(ENABLE_JVMTI)
104 #include "native/jvmti/cacaodbg.h"
105 #endif
106
107 #if defined(__DARWIN__)
108 /* Darwin has no working semaphore implementation.  This one is taken
109    from Boehm-GC. */
110
111 /*
112    This is a very simple semaphore implementation for darwin. It
113    is implemented in terms of pthreads calls so it isn't async signal
114    safe. This isn't a problem because signals aren't used to
115    suspend threads on darwin.
116 */
117    
118 static int sem_init(sem_t *sem, int pshared, int value)
119 {
120         if (pshared)
121                 assert(0);
122
123         sem->value = value;
124     
125         if (pthread_mutex_init(&sem->mutex, NULL) < 0)
126                 return -1;
127
128         if (pthread_cond_init(&sem->cond, NULL) < 0)
129                 return -1;
130
131         return 0;
132 }
133
134 static int sem_post(sem_t *sem)
135 {
136         if (pthread_mutex_lock(&sem->mutex) < 0)
137                 return -1;
138
139         sem->value++;
140
141         if (pthread_cond_signal(&sem->cond) < 0) {
142                 pthread_mutex_unlock(&sem->mutex);
143                 return -1;
144         }
145
146         if (pthread_mutex_unlock(&sem->mutex) < 0)
147                 return -1;
148
149         return 0;
150 }
151
152 static int sem_wait(sem_t *sem)
153 {
154         if (pthread_mutex_lock(&sem->mutex) < 0)
155                 return -1;
156
157         while (sem->value == 0) {
158                 pthread_cond_wait(&sem->cond, &sem->mutex);
159         }
160
161         sem->value--;
162
163         if (pthread_mutex_unlock(&sem->mutex) < 0)
164                 return -1;    
165
166         return 0;
167 }
168
169 static int sem_destroy(sem_t *sem)
170 {
171         if (pthread_cond_destroy(&sem->cond) < 0)
172                 return -1;
173
174         if (pthread_mutex_destroy(&sem->mutex) < 0)
175                 return -1;
176
177         return 0;
178 }
179 #endif /* defined(__DARWIN__) */
180
181
182 /* internally used constants **************************************************/
183
184 /* CAUTION: Do not change these values. Boehm GC code depends on them.        */
185 #define STOPWORLD_FROM_GC               1
186 #define STOPWORLD_FROM_CLASS_NUMBERING  2
187
188 #define THREADS_INITIAL_TABLE_SIZE      8
189
190
191 /* startupinfo *****************************************************************
192
193    Struct used to pass info from threads_start_thread to 
194    threads_startup_thread.
195
196 ******************************************************************************/
197
198 typedef struct {
199         threadobject *thread;      /* threadobject for this thread             */
200         functionptr   function;    /* function to run in the new thread        */
201         sem_t        *psem;        /* signals when thread has been entered     */
202                                    /* in the thread list                       */
203         sem_t        *psem_first;  /* signals when pthread_create has returned */
204 } startupinfo;
205
206
207 /* prototypes *****************************************************************/
208
209 static void threads_table_init(void);
210 static s4 threads_table_add(threadobject *thread);
211 static void threads_table_remove(threadobject *thread);
212 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
213
214 #if !defined(NDEBUG) && 0
215 static void threads_table_dump(FILE *file);
216 #endif
217
218 /******************************************************************************/
219 /* GLOBAL VARIABLES                                                           */
220 /******************************************************************************/
221
222 /* the main thread                                                            */
223 threadobject *mainthreadobj;
224
225 static methodinfo *method_thread_init;
226
227 /* the thread object of the current thread                                    */
228 /* This is either a thread-local variable defined with __thread, or           */
229 /* a thread-specific value stored with key threads_current_threadobject_key.  */
230 #if defined(HAVE___THREAD)
231 __thread threadobject *threads_current_threadobject;
232 #else
233 pthread_key_t threads_current_threadobject_key;
234 #endif
235
236 /* global threads table                                                       */
237 static threads_table_t threads_table;
238
239 /* global compiler mutex                                                      */
240 static pthread_mutex_t compiler_mutex;
241
242 /* global mutex for changing the thread list                                  */
243 static pthread_mutex_t threadlistlock;
244
245 /* global mutex for stop-the-world                                            */
246 static pthread_mutex_t stopworldlock;
247
248 /* this is one of the STOPWORLD_FROM_ constants, telling why the world is     */
249 /* being stopped                                                              */
250 static volatile int stopworldwhere;
251
252 /* semaphore used for acknowleding thread suspension                          */
253 static sem_t suspend_ack;
254 #if defined(__MIPS__)
255 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
256 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
257 #endif
258
259 static pthread_attr_t threadattr;
260
261 /* mutexes used by the fake atomic instructions                               */
262 #if defined(USE_FAKE_ATOMIC_INSTRUCTIONS)
263 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
264 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
265 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
266 #endif
267
268
269 /* threads_sem_init ************************************************************
270  
271    Initialize a semaphore. Checks against errors and interruptions.
272
273    IN:
274        sem..............the semaphore to initialize
275            shared...........true if this semaphore will be shared between processes
276            value............the initial value for the semaphore
277    
278 *******************************************************************************/
279
280 void threads_sem_init(sem_t *sem, bool shared, int value)
281 {
282         int r;
283
284         assert(sem);
285
286         do {
287                 r = sem_init(sem, shared, value);
288                 if (r == 0)
289                         return;
290         } while (errno == EINTR);
291
292         vm_abort("sem_init failed: %s", strerror(errno));
293 }
294
295
296 /* threads_sem_wait ************************************************************
297  
298    Wait for a semaphore, non-interruptible.
299
300    IMPORTANT: Always use this function instead of `sem_wait` directly, as
301               `sem_wait` may be interrupted by signals!
302   
303    IN:
304        sem..............the semaphore to wait on
305    
306 *******************************************************************************/
307
308 void threads_sem_wait(sem_t *sem)
309 {
310         int r;
311
312         assert(sem);
313
314         do {
315                 r = sem_wait(sem);
316                 if (r == 0)
317                         return;
318         } while (errno == EINTR);
319
320         vm_abort("sem_wait failed: %s", strerror(errno));
321 }
322
323
324 /* threads_sem_post ************************************************************
325  
326    Increase the count of a semaphore. Checks for errors.
327
328    IN:
329        sem..............the semaphore to increase the count of
330    
331 *******************************************************************************/
332
333 void threads_sem_post(sem_t *sem)
334 {
335         int r;
336
337         assert(sem);
338
339         /* unlike sem_wait, sem_post is not interruptible */
340
341         r = sem_post(sem);
342         if (r == 0)
343                 return;
344
345         vm_abort("sem_post failed: %s", strerror(errno));
346 }
347
348
349 /* compiler_lock ***************************************************************
350
351    Enter the compiler lock.
352
353 ******************************************************************************/
354
355 void compiler_lock(void)
356 {
357         pthread_mutex_lock(&compiler_mutex);
358 }
359
360
361 /* compiler_unlock *************************************************************
362
363    Release the compiler lock.
364
365 ******************************************************************************/
366
367 void compiler_unlock(void)
368 {
369         pthread_mutex_unlock(&compiler_mutex);
370 }
371
372
373 /* lock_stopworld **************************************************************
374
375    Enter the stopworld lock, specifying why the world shall be stopped.
376
377    IN:
378       where........ STOPWORLD_FROM_GC              (1) from within GC
379                     STOPWORLD_FROM_CLASS_NUMBERING (2) class numbering
380
381 ******************************************************************************/
382
383 void lock_stopworld(int where)
384 {
385         pthread_mutex_lock(&stopworldlock);
386         stopworldwhere = where;
387 }
388
389
390 /* unlock_stopworld ************************************************************
391
392    Release the stopworld lock.
393
394 ******************************************************************************/
395
396 void unlock_stopworld(void)
397 {
398         stopworldwhere = 0;
399         pthread_mutex_unlock(&stopworldlock);
400 }
401
402 #if !defined(__DARWIN__)
403 /* Caller must hold threadlistlock */
404 static int threads_cast_sendsignals(int sig, int count)
405 {
406         /* Count threads */
407         threadobject *tobj = mainthreadobj;
408         threadobject *self = THREADOBJECT;
409
410         if (count == 0) {
411                 do {
412                         count++;
413                         tobj = tobj->next;
414                 } while (tobj != mainthreadobj);
415         }
416
417         assert(tobj == mainthreadobj);
418
419         do {
420                 if (tobj != self)
421                         pthread_kill(tobj->tid, sig);
422                 tobj = tobj->next;
423         } while (tobj != mainthreadobj);
424
425         return count - 1;
426 }
427
428 #else
429
430 static void threads_cast_darwinstop(void)
431 {
432         threadobject *tobj = mainthreadobj;
433         threadobject *self = THREADOBJECT;
434
435         do {
436                 if (tobj != self)
437                 {
438                         thread_state_flavor_t flavor = MACHINE_THREAD_STATE;
439                         mach_msg_type_number_t thread_state_count = MACHINE_THREAD_STATE_COUNT;
440 #if defined(__I386__)
441                         i386_thread_state_t thread_state;
442 #else
443                         ppc_thread_state_t thread_state;
444 #endif
445                         mach_port_t thread = tobj->mach_thread;
446                         kern_return_t r;
447
448                         r = thread_suspend(thread);
449
450                         if (r != KERN_SUCCESS)
451                                 vm_abort("thread_suspend failed");
452
453                         r = thread_get_state(thread, flavor, (natural_t *) &thread_state,
454                                                                  &thread_state_count);
455
456                         if (r != KERN_SUCCESS)
457                                 vm_abort("thread_get_state failed");
458
459                         thread_restartcriticalsection((ucontext_t *) &thread_state);
460
461                         r = thread_set_state(thread, flavor, (natural_t *) &thread_state,
462                                                                  thread_state_count);
463
464                         if (r != KERN_SUCCESS)
465                                 vm_abort("thread_set_state failed");
466                 }
467
468                 tobj = tobj->next;
469         } while (tobj != mainthreadobj);
470 }
471
472 static void threads_cast_darwinresume(void)
473 {
474         threadobject *tobj = mainthreadobj;
475         threadobject *self = THREADOBJECT;
476
477         do {
478                 if (tobj != self)
479                 {
480                         mach_port_t thread = tobj->mach_thread;
481                         kern_return_t r;
482
483                         r = thread_resume(thread);
484
485                         if (r != KERN_SUCCESS)
486                                 vm_abort("thread_resume failed");
487                 }
488
489                 tobj = tobj->next;
490         } while (tobj != mainthreadobj);
491 }
492
493 #endif
494
495 #if defined(__MIPS__)
496 static void threads_cast_irixresume(void)
497 {
498         pthread_mutex_lock(&suspend_ack_lock);
499         pthread_cond_broadcast(&suspend_cond);
500         pthread_mutex_unlock(&suspend_ack_lock);
501 }
502 #endif
503
504 #if !defined(DISABLE_GC)
505
506 void threads_cast_stopworld(void)
507 {
508 #if !defined(__DARWIN__) && !defined(__CYGWIN__)
509         int count, i;
510 #endif
511
512         lock_stopworld(STOPWORLD_FROM_CLASS_NUMBERING);
513         pthread_mutex_lock(&threadlistlock);
514
515 #if defined(__DARWIN__)
516         threads_cast_darwinstop();
517 #elif defined(__CYGWIN__)
518         /* TODO */
519         assert(0);
520 #else
521         count = threads_cast_sendsignals(GC_signum1(), 0);
522         for (i = 0; i < count; i++)
523                 threads_sem_wait(&suspend_ack);
524 #endif
525
526         pthread_mutex_unlock(&threadlistlock);
527 }
528
529 void threads_cast_startworld(void)
530 {
531         pthread_mutex_lock(&threadlistlock);
532 #if defined(__DARWIN__)
533         threads_cast_darwinresume();
534 #elif defined(__MIPS__)
535         threads_cast_irixresume();
536 #elif defined(__CYGWIN__)
537         /* TODO */
538         assert(0);
539 #else
540         threads_cast_sendsignals(GC_signum2(), -1);
541 #endif
542         pthread_mutex_unlock(&threadlistlock);
543         unlock_stopworld();
544 }
545
546
547 #if !defined(__DARWIN__)
548 static void threads_sigsuspend_handler(ucontext_t *ctx)
549 {
550         int sig;
551         sigset_t sigs;
552
553         /* XXX TWISTI: this is just a quick hack */
554 #if defined(ENABLE_JIT)
555         thread_restartcriticalsection(ctx);
556 #endif
557
558         /* Do as Boehm does. On IRIX a condition variable is used for wake-up
559            (not POSIX async-safe). */
560 #if defined(__IRIX__)
561         pthread_mutex_lock(&suspend_ack_lock);
562         threads_sem_post(&suspend_ack);
563         pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
564         pthread_mutex_unlock(&suspend_ack_lock);
565 #elif defined(__CYGWIN__)
566         /* TODO */
567         assert(0);
568 #else
569         threads_sem_post(&suspend_ack);
570
571         sig = GC_signum2();
572         sigfillset(&sigs);
573         sigdelset(&sigs, sig);
574         sigsuspend(&sigs);
575 #endif
576 }
577
578 /* This function is called from Boehm GC code. */
579
580 int cacao_suspendhandler(ucontext_t *ctx)
581 {
582         if (stopworldwhere != STOPWORLD_FROM_CLASS_NUMBERING)
583                 return 0;
584
585         threads_sigsuspend_handler(ctx);
586         return 1;
587 }
588 #endif
589
590 #endif /* DISABLE_GC */
591
592 /* threads_set_current_threadobject ********************************************
593
594    Set the current thread object.
595    
596    IN:
597       thread.......the thread object to set
598
599 *******************************************************************************/
600
601 static void threads_set_current_threadobject(threadobject *thread)
602 {
603 #if !defined(HAVE___THREAD)
604         pthread_setspecific(threads_current_threadobject_key, thread);
605 #else
606         threads_current_threadobject = thread;
607 #endif
608 }
609
610
611 /* threads_init_threadobject **************************************************
612
613    Initialize implementation fields of a threadobject.
614
615    IN:
616       thread............the threadobject
617
618 ******************************************************************************/
619
620 static void threads_init_threadobject(threadobject *thread)
621 {
622         thread->tid = pthread_self();
623
624         thread->index = 0;
625
626         /* TODO destroy all those things */
627         pthread_mutex_init(&(thread->joinmutex), NULL);
628         pthread_cond_init(&(thread->joincond), NULL);
629
630         pthread_mutex_init(&(thread->waitmutex), NULL);
631         pthread_cond_init(&(thread->waitcond), NULL);
632
633         thread->interrupted = false;
634         thread->signaled = false;
635         thread->sleeping = false;
636 }
637
638
639 /* threads_get_current_threadobject ********************************************
640
641    Return the threadobject of the current thread.
642    
643    RETURN VALUE:
644        the current threadobject * (an instance of java.lang.Thread)
645
646 *******************************************************************************/
647
648 threadobject *threads_get_current_threadobject(void)
649 {
650         return THREADOBJECT;
651 }
652
653
654 /* threads_preinit *************************************************************
655
656    Do some early initialization of stuff required.
657
658    ATTENTION: Do NOT use any Java heap allocation here, as gc_init()
659    is called AFTER this function!
660
661 *******************************************************************************/
662
663 void threads_preinit(void)
664 {
665         pthread_mutexattr_t mutexattr;
666         pthread_mutexattr_init(&mutexattr);
667         pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
668         pthread_mutex_init(&compiler_mutex, &mutexattr);
669         pthread_mutexattr_destroy(&mutexattr);
670
671         pthread_mutex_init(&threadlistlock, NULL);
672         pthread_mutex_init(&stopworldlock, NULL);
673
674         mainthreadobj = NEW(threadobject);
675         mainthreadobj->tid      = pthread_self();
676         mainthreadobj->index    = 1;
677         mainthreadobj->thinlock = lock_pre_compute_thinlock(mainthreadobj->index);
678         
679 #if !defined(HAVE___THREAD)
680         pthread_key_create(&threads_current_threadobject_key, NULL);
681 #endif
682         threads_set_current_threadobject(mainthreadobj);
683
684         threads_sem_init(&suspend_ack, 0, 0);
685
686         /* initialize the threads table */
687
688         threads_table_init();
689
690         /* initialize subsystems */
691
692         lock_init();
693
694         critical_init();
695 }
696
697
698 /* threads_init ****************************************************************
699
700    Initializes the threads required by the JVM: main, finalizer.
701
702 *******************************************************************************/
703
704 bool threads_init(void)
705 {
706         java_lang_String      *threadname;
707         threadobject          *tempthread;
708         java_objectheader     *o;
709
710 #if defined(ENABLE_JAVASE)
711         java_lang_ThreadGroup *threadgroup;
712         methodinfo            *m;
713         java_lang_Thread      *t;
714 #endif
715
716 #if defined(WITH_CLASSPATH_GNU)
717         java_lang_VMThread    *vmt;
718 #endif
719
720         tempthread = mainthreadobj;
721
722         /* XXX We have to find a new way to free lock records */
723         /*     with the new locking algorithm.                */
724         /* lock_record_free_pools(mainthreadobj->ee.lockrecordpools); */
725
726         /* This is kinda tricky, we grow the java.lang.Thread object so we
727            can keep the execution environment there. No Thread object must
728            have been created at an earlier time. */
729
730         class_java_lang_Thread->instancesize = sizeof(threadobject);
731
732         /* get methods we need in this file */
733
734 #if defined(WITH_CLASSPATH_GNU)
735         method_thread_init =
736                 class_resolveclassmethod(class_java_lang_Thread,
737                                                                  utf_init,
738                                                                  utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
739                                                                  class_java_lang_Thread,
740                                                                  true);
741 #else
742         method_thread_init =
743                 class_resolveclassmethod(class_java_lang_Thread,
744                                                                  utf_init,
745                                                                  utf_new_char("(Ljava/lang/String;)V"),
746                                                                  class_java_lang_Thread,
747                                                                  true);
748 #endif
749
750         if (method_thread_init == NULL)
751                 return false;
752
753         /* create a java.lang.Thread for the main thread */
754
755         mainthreadobj = (threadobject *) builtin_new(class_java_lang_Thread);
756
757         if (mainthreadobj == NULL)
758                 return false;
759
760         FREE(tempthread, threadobject);
761
762         threads_init_threadobject(mainthreadobj);
763
764         threads_set_current_threadobject(mainthreadobj);
765
766         lock_init_execution_env(mainthreadobj);
767
768         mainthreadobj->next = mainthreadobj;
769         mainthreadobj->prev = mainthreadobj;
770
771         threads_table_add(mainthreadobj);
772
773         /* mark main thread as Java thread */
774
775         mainthreadobj->flags = THREAD_FLAG_JAVA;
776
777 #if defined(ENABLE_INTRP)
778         /* create interpreter stack */
779
780         if (opt_intrp) {
781                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
782                 mainthreadobj->_global_sp = (Cell*) (intrp_main_stack + opt_stacksize);
783         }
784 #endif
785
786         threadname = javastring_new(utf_new_char("main"));
787
788 #if defined(ENABLE_JAVASE)
789         /* allocate and init ThreadGroup */
790
791         threadgroup = (java_lang_ThreadGroup *)
792                 native_new_and_init(class_java_lang_ThreadGroup);
793
794         if (threadgroup == NULL)
795                 throw_exception_exit();
796 #endif
797
798 #if defined(WITH_CLASSPATH_GNU)
799         /* create a java.lang.VMThread for the main thread */
800
801         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
802
803         if (vmt == NULL)
804                 throw_exception_exit();
805
806         /* set the thread */
807
808         t           = (java_lang_Thread *) mainthreadobj;
809         vmt->thread = t;
810
811         /* call java.lang.Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
812         o = (java_objectheader *) mainthreadobj;
813
814         (void) vm_call_method(method_thread_init, o, vmt, threadname, NORM_PRIORITY,
815                                                   false);
816 #elif defined(WITH_CLASSPATH_CLDC1_1)
817         /* call public Thread(String name) */
818
819         o = (java_objectheader *) mainthreadobj;
820
821         (void) vm_call_method(method_thread_init, o, threadname);
822 #endif
823
824         if (*exceptionptr)
825                 return false;
826
827 #if defined(ENABLE_JAVASE)
828         mainthreadobj->o.group = threadgroup;
829
830         /* add main thread to java.lang.ThreadGroup */
831
832         m = class_resolveclassmethod(class_java_lang_ThreadGroup,
833                                                                  utf_addThread,
834                                                                  utf_java_lang_Thread__V,
835                                                                  class_java_lang_ThreadGroup,
836                                                                  true);
837
838         o = (java_objectheader *) threadgroup;
839         t = (java_lang_Thread *) mainthreadobj;
840
841         (void) vm_call_method(m, o, t);
842
843         if (*exceptionptr)
844                 return false;
845
846 #endif
847
848         threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
849
850         /* initialize the thread attribute object */
851
852         if (pthread_attr_init(&threadattr)) {
853                 log_println("pthread_attr_init failed: %s", strerror(errno));
854                 return false;
855         }
856
857         pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
858
859         /* everything's ok */
860
861         return true;
862 }
863
864
865 /* threads_table_init *********************************************************
866
867    Initialize the global threads table.
868
869 ******************************************************************************/
870
871 static void threads_table_init(void)
872 {
873         s4 size;
874         s4 i;
875
876         size = THREADS_INITIAL_TABLE_SIZE;
877
878         threads_table.size = size;
879         threads_table.table = MNEW(threads_table_entry_t, size);
880
881         /* link the entries in a freelist */
882
883         for (i=0; i<size; ++i) {
884                 threads_table.table[i].nextfree = i+1;
885         }
886
887         /* terminate the freelist */
888
889         threads_table.table[size-1].nextfree = 0; /* index 0 is never free */
890 }
891
892
893 /* threads_table_add **********************************************************
894
895    Add a thread to the global threads table. The index is entered in the
896    threadobject. The thinlock value for the thread is pre-computed.
897
898    IN:
899       thread............the thread to add
900
901    RETURN VALUE:
902       The table index for the newly added thread. This value has also been
903           entered in the threadobject.
904
905    PRE-CONDITION:
906       The caller must hold the threadlistlock!
907
908 ******************************************************************************/
909
910 static s4 threads_table_add(threadobject *thread)
911 {
912         s4 index;
913         s4 oldsize;
914         s4 newsize;
915         s4 i;
916
917         /* table[0] serves as the head of the freelist */
918
919         index = threads_table.table[0].nextfree;
920
921         /* if we got a free index, use it */
922
923         if (index) {
924 got_an_index:
925                 threads_table.table[0].nextfree = threads_table.table[index].nextfree;
926                 threads_table.table[index].thread = thread;
927                 thread->index = index;
928                 thread->thinlock = lock_pre_compute_thinlock(index);
929                 return index;
930         }
931
932         /* we must grow the table */
933
934         oldsize = threads_table.size;
935         newsize = oldsize * 2;
936
937         threads_table.table = MREALLOC(threads_table.table, threads_table_entry_t,
938                                                                    oldsize, newsize);
939         threads_table.size = newsize;
940
941         /* link the new entries to a free list */
942
943         for (i=oldsize; i<newsize; ++i) {
944                 threads_table.table[i].nextfree = i+1;
945         }
946
947         /* terminate the freelist */
948
949         threads_table.table[newsize-1].nextfree = 0; /* index 0 is never free */
950
951         /* use the first of the new entries */
952
953         index = oldsize;
954         goto got_an_index;
955 }
956
957
958 /* threads_table_remove *******************************************************
959
960    Remove a thread from the global threads table.
961
962    IN:
963       thread............the thread to remove
964
965    PRE-CONDITION:
966       The caller must hold the threadlistlock!
967
968 ******************************************************************************/
969
970 static void threads_table_remove(threadobject *thread)
971 {
972         s4 index;
973
974         index = thread->index;
975
976         /* put the index into the freelist */
977
978         threads_table.table[index] = threads_table.table[0];
979         threads_table.table[0].nextfree = index;
980
981         /* delete the index in the threadobject to discover bugs */
982 #if !defined(NDEBUG)
983         thread->index = 0;
984 #endif
985 }
986
987
988 /* threads_startup_thread ******************************************************
989
990    Thread startup function called by pthread_create.
991
992    Thread which have a startup.function != NULL are marked as internal
993    threads. All other threads are threated as normal Java threads.
994
995    NOTE: This function is not called directly by pthread_create. The Boehm GC
996          inserts its own GC_start_routine in between, which then calls
997                  threads_startup.
998
999    IN:
1000       t............the argument passed to pthread_create, ie. a pointer to
1001                        a startupinfo struct. CAUTION: When the `psem` semaphore
1002                                    is posted, the startupinfo struct becomes invalid! (It
1003                                    is allocated on the stack of threads_start_thread.)
1004
1005 ******************************************************************************/
1006
1007 static void *threads_startup_thread(void *t)
1008 {
1009         startupinfo        *startup;
1010         threadobject       *thread;
1011 #if defined(WITH_CLASSPATH_GNU)
1012         java_lang_VMThread *vmt;
1013 #endif
1014         sem_t              *psem;
1015         threadobject       *tnext;
1016         classinfo          *c;
1017         methodinfo         *m;
1018         java_objectheader  *o;
1019         functionptr         function;
1020
1021 #if defined(ENABLE_INTRP)
1022         u1 *intrp_thread_stack;
1023
1024         /* create interpreter stack */
1025
1026         if (opt_intrp) {
1027                 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
1028                 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
1029         }
1030         else
1031                 intrp_thread_stack = NULL;
1032 #endif
1033
1034         /* get passed startupinfo structure and the values in there */
1035
1036         startup = t;
1037         t = NULL; /* make sure it's not used wrongly */
1038
1039         thread   = startup->thread;
1040         function = startup->function;
1041         psem     = startup->psem;
1042
1043         /* Seems like we've encountered a situation where thread->tid was not set by
1044          * pthread_create. We alleviate this problem by waiting for pthread_create
1045          * to return. */
1046         threads_sem_wait(startup->psem_first);
1047
1048         /* set the thread object */
1049
1050 #if defined(__DARWIN__)
1051         thread->mach_thread = mach_thread_self();
1052 #endif
1053         threads_set_current_threadobject(thread);
1054
1055         /* insert the thread into the threadlist and the threads table */
1056
1057         pthread_mutex_lock(&threadlistlock);
1058
1059         thread->prev = mainthreadobj;
1060         thread->next = tnext = mainthreadobj->next;
1061         mainthreadobj->next = thread;
1062         tnext->prev = thread;
1063
1064         threads_table_add(thread);
1065
1066         pthread_mutex_unlock(&threadlistlock);
1067
1068         /* init data structures of this thread */
1069
1070         lock_init_execution_env(thread);
1071
1072         /* tell threads_startup_thread that we registered ourselves */
1073         /* CAUTION: *startup becomes invalid with this!             */
1074
1075         startup = NULL;
1076         threads_sem_post(psem);
1077
1078         /* set our priority */
1079
1080         threads_set_thread_priority(thread->tid, thread->o.priority);
1081
1082 #if defined(ENABLE_INTRP)
1083         /* set interpreter stack */
1084
1085         if (opt_intrp)
1086                 thread->_global_sp = (Cell *) (intrp_thread_stack + opt_stacksize);
1087 #endif
1088
1089 #if defined(ENABLE_JVMTI)
1090         /* fire thread start event */
1091
1092         if (jvmti) 
1093                 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_START);
1094 #endif
1095
1096         /* find and run the Thread.run()V method if no other function was passed */
1097
1098         if (function == NULL) {
1099                 /* this is a normal Java thread */
1100
1101                 thread->flags |= THREAD_FLAG_JAVA;
1102
1103 #if defined(WITH_CLASSPATH_GNU)
1104                 /* We need to start the run method of
1105                    java.lang.VMThread. Since this is a final class, we can use
1106                    the class object directly. */
1107
1108                 c   = class_java_lang_VMThread;
1109 #elif defined(WITH_CLASSPATH_CLDC1_1)
1110                 c   = thread->o.header.vftbl->class;
1111 #endif
1112
1113                 m = class_resolveclassmethod(c, utf_run, utf_void__void, c, true);
1114
1115                 if (m == NULL)
1116                         throw_exception();
1117
1118                 /* set ThreadMXBean variables */
1119
1120                 _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1121                 _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1122
1123                 if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1124                         _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1125                         _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1126                                 _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1127
1128 #if defined(WITH_CLASSPATH_GNU)
1129                 /* we need to start the run method of java.lang.VMThread */
1130
1131                 vmt = (java_lang_VMThread *) thread->o.vmThread;
1132                 o   = (java_objectheader *) vmt;
1133
1134 #elif defined(WITH_CLASSPATH_CLDC1_1)
1135                 o   = (java_objectheader *) thread;
1136 #endif
1137
1138                 (void) vm_call_method(m, o);
1139         }
1140         else {
1141                 /* this is an internal thread */
1142
1143                 thread->flags |= THREAD_FLAG_INTERNAL;
1144
1145                 /* set ThreadMXBean variables */
1146
1147                 _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount++;
1148                 _Jv_jvm->java_lang_management_ThreadMXBean_TotalStartedThreadCount++;
1149
1150                 if (_Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount >
1151                         _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount)
1152                         _Jv_jvm->java_lang_management_ThreadMXBean_PeakThreadCount =
1153                                 _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount;
1154
1155                 /* call passed function, e.g. finalizer_thread */
1156
1157                 (function)();
1158         }
1159
1160 #if defined(ENABLE_JVMTI)
1161         /* fire thread end event */
1162
1163         if (jvmti)
1164                 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_END);
1165 #endif
1166
1167         threads_detach_thread(thread);
1168
1169         /* set ThreadMXBean variables */
1170
1171         _Jv_jvm->java_lang_management_ThreadMXBean_ThreadCount--;
1172
1173         return NULL;
1174 }
1175
1176
1177 /* threads_start_thread ********************************************************
1178
1179    Start a thread in the JVM.
1180
1181    IN:
1182       thread.......the thread object
1183           function.....function to run in the new thread. NULL means that the
1184                        "run" method of the object `t` should be called
1185
1186 ******************************************************************************/
1187
1188 void threads_start_thread(threadobject *thread, functionptr function)
1189 {
1190         sem_t          sem;
1191         sem_t          sem_first;
1192         pthread_attr_t attr;
1193         startupinfo    startup;
1194
1195         /* fill startupinfo structure passed by pthread_create to
1196          * threads_startup_thread */
1197
1198         startup.thread     = thread;
1199         startup.function   = function;       /* maybe we don't call Thread.run()V */
1200         startup.psem       = &sem;
1201         startup.psem_first = &sem_first;
1202
1203         threads_sem_init(&sem, 0, 0);
1204         threads_sem_init(&sem_first, 0, 0);
1205
1206         /* initialize thread attribute object */
1207
1208         if (pthread_attr_init(&attr))
1209                 vm_abort("pthread_attr_init failed: %s", strerror(errno));
1210
1211         /* initialize thread stacksize */
1212
1213         if (pthread_attr_setstacksize(&attr, opt_stacksize))
1214                 vm_abort("pthread_attr_setstacksize failed: %s", strerror(errno));
1215
1216         /* create the thread */
1217
1218         if (pthread_create(&(thread->tid), &attr, threads_startup_thread, &startup))
1219                 vm_abort("pthread_create failed: %s", strerror(errno));
1220
1221         /* signal that pthread_create has returned, so thread->tid is valid */
1222
1223         threads_sem_post(&sem_first);
1224
1225         /* wait here until the thread has entered itself into the thread list */
1226
1227         threads_sem_wait(&sem);
1228
1229         /* cleanup */
1230
1231         sem_destroy(&sem);
1232         sem_destroy(&sem_first);
1233 }
1234
1235
1236 /* threads_set_thread_priority *************************************************
1237
1238    Set the priority of the given thread.
1239
1240    IN:
1241       tid..........thread id
1242           priority.....priority to set
1243
1244 ******************************************************************************/
1245
1246 void threads_set_thread_priority(pthread_t tid, int priority)
1247 {
1248         struct sched_param schedp;
1249         int policy;
1250
1251 #if defined(ENABLE_JAVAME_CLDC1_1)
1252         /* The thread id is zero when a thread is created in Java.  The
1253            priority is set later during startup. */
1254
1255         if (tid == NULL)
1256                 return;
1257 #endif
1258
1259         pthread_getschedparam(tid, &policy, &schedp);
1260         schedp.sched_priority = priority;
1261         pthread_setschedparam(tid, policy, &schedp);
1262 }
1263
1264
1265 /* threads_attach_current_thread ***********************************************
1266
1267    Attaches the current thread to the VM.  Used in JNI.
1268
1269 *******************************************************************************/
1270
1271 bool threads_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
1272 {
1273         threadobject          *thread;
1274         utf                   *u;
1275         java_lang_String      *s;
1276         java_objectheader     *o;
1277         java_lang_Thread      *t;
1278
1279 #if defined(ENABLE_JAVASE)
1280         java_lang_ThreadGroup *group;
1281         methodinfo            *m;
1282 #endif
1283
1284 #if defined(WITH_CLASSPATH_GNU)
1285         java_lang_VMThread    *vmt;
1286 #endif
1287
1288         /* create a java.lang.Thread object */
1289
1290         thread = (threadobject *) builtin_new(class_java_lang_Thread);
1291
1292         if (thread == NULL)
1293                 return false;
1294
1295         /* cast for convenience */
1296
1297         t = (java_lang_Thread *) thread;
1298
1299         threads_init_threadobject(thread);
1300         threads_set_current_threadobject(thread);
1301         lock_init_execution_env(thread);
1302
1303         /* insert the thread into the threadlist and the threads table */
1304
1305         pthread_mutex_lock(&threadlistlock);
1306
1307         thread->prev        = mainthreadobj;
1308         thread->next        = mainthreadobj->next;
1309         mainthreadobj->next = thread;
1310         thread->next->prev  = thread;
1311
1312         threads_table_add(thread);
1313
1314         pthread_mutex_unlock(&threadlistlock);
1315
1316         /* mark thread as Java thread */
1317
1318         thread->flags = THREAD_FLAG_JAVA;
1319
1320         if (isdaemon)
1321                 thread->flags |= THREAD_FLAG_DAEMON;
1322
1323 #if defined(ENABLE_INTRP)
1324         /* create interpreter stack */
1325
1326         if (opt_intrp) {
1327                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1328                 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
1329         }
1330 #endif
1331
1332 #if defined(WITH_CLASSPATH_GNU)
1333         /* create a java.lang.VMThread object */
1334
1335         vmt = (java_lang_VMThread *) builtin_new(class_java_lang_VMThread);
1336
1337         if (vmt == NULL)
1338                 return false;
1339
1340         /* set the thread */
1341
1342         vmt->thread = t;
1343 #endif
1344
1345         if (vm_aargs != NULL) {
1346                 u     = utf_new_char(vm_aargs->name);
1347 #if defined(ENABLE_JAVASE)
1348                 group = (java_lang_ThreadGroup *) vm_aargs->group;
1349 #endif
1350         }
1351         else {
1352                 u     = utf_null;
1353 #if defined(ENABLE_JAVASE)
1354                 group = mainthreadobj->o.group;
1355 #endif
1356         }
1357
1358         s = javastring_new(u);
1359
1360         o = (java_objectheader *) thread;
1361
1362 #if defined(WITH_CLASSPATH_GNU)
1363         (void) vm_call_method(method_thread_init, o, vmt, s, NORM_PRIORITY,
1364                                                   isdaemon);
1365 #elif defined(WITH_CLASSPATH_CLDC1_1)
1366         (void) vm_call_method(method_thread_init, o, s);
1367 #endif
1368
1369         if (*exceptionptr)
1370                 return false;
1371
1372 #if defined(ENABLE_JAVASE)
1373         /* store the thread group in the object */
1374
1375         thread->o.group = group;
1376
1377         /* add thread to given thread-group */
1378
1379         m = class_resolveclassmethod(group->header.vftbl->class,
1380                                                                  utf_addThread,
1381                                                                  utf_java_lang_Thread__V,
1382                                                                  class_java_lang_ThreadGroup,
1383                                                                  true);
1384
1385         o = (java_objectheader *) group;
1386
1387         (void) vm_call_method(m, o, t);
1388
1389         if (*exceptionptr)
1390                 return false;
1391 #endif
1392
1393         return true;
1394 }
1395
1396
1397 /* threads_detach_thread *******************************************************
1398
1399    Detaches the passed thread from the VM.  Used in JNI.
1400
1401 *******************************************************************************/
1402
1403 bool threads_detach_thread(threadobject *thread)
1404 {
1405 #if defined(ENABLE_JAVASE)
1406         java_lang_ThreadGroup *group;
1407         methodinfo            *m;
1408         java_objectheader     *o;
1409         java_lang_Thread      *t;
1410 #endif
1411
1412         /* Allow lock record pools to be used by other threads. They
1413            cannot be deleted so we'd better not waste them. */
1414
1415         /* XXX We have to find a new way to free lock records */
1416         /*     with the new locking algorithm.                */
1417         /* lock_record_free_pools(thread->ee.lockrecordpools); */
1418
1419         /* XXX implement uncaught exception stuff (like JamVM does) */
1420
1421 #if defined(ENABLE_JAVASE)
1422         /* remove thread from the thread group */
1423
1424         group = thread->o.group;
1425
1426         /* XXX TWISTI: should all threads be in a ThreadGroup? */
1427
1428         if (group != NULL) {
1429                 m = class_resolveclassmethod(group->header.vftbl->class,
1430                                                                          utf_removeThread,
1431                                                                          utf_java_lang_Thread__V,
1432                                                                          class_java_lang_ThreadGroup,
1433                                                                          true);
1434
1435                 if (m == NULL)
1436                         return false;
1437
1438                 o = (java_objectheader *) group;
1439                 t = (java_lang_Thread *) thread;
1440
1441                 (void) vm_call_method(m, o, t);
1442
1443                 if (*exceptionptr)
1444                         return false;
1445         }
1446 #endif
1447
1448         /* remove thread from thread list and threads table, do this
1449            inside a lock */
1450
1451         pthread_mutex_lock(&threadlistlock);
1452
1453         thread->next->prev = thread->prev;
1454         thread->prev->next = thread->next;
1455
1456         threads_table_remove(thread);
1457
1458         pthread_mutex_unlock(&threadlistlock);
1459
1460         /* reset thread id (lock on joinmutex? TWISTI) */
1461
1462         pthread_mutex_lock(&(thread->joinmutex));
1463         thread->tid = 0;
1464         pthread_mutex_unlock(&(thread->joinmutex));
1465
1466         /* tell everyone that a thread has finished */
1467
1468         pthread_cond_broadcast(&(thread->joincond));
1469
1470         return true;
1471 }
1472
1473
1474 /* threads_find_non_daemon_thread **********************************************
1475
1476    Helper function used by threads_join_all_threads for finding
1477    non-daemon threads that are still running.
1478
1479 *******************************************************************************/
1480
1481 /* At the end of the program, we wait for all running non-daemon
1482    threads to die. */
1483
1484 static threadobject *threads_find_non_daemon_thread(threadobject *thread)
1485 {
1486         while (thread != mainthreadobj) {
1487                 if (!(thread->flags & THREAD_FLAG_DAEMON))
1488                         return thread;
1489
1490                 thread = thread->prev;
1491         }
1492
1493         return NULL;
1494 }
1495
1496
1497 /* threads_join_all_threads ****************************************************
1498
1499    Join all non-daemon threads.
1500
1501 *******************************************************************************/
1502
1503 void threads_join_all_threads(void)
1504 {
1505         threadobject *thread;
1506
1507         pthread_mutex_lock(&threadlistlock);
1508
1509         while ((thread = threads_find_non_daemon_thread(mainthreadobj->prev)) != NULL) {
1510                 pthread_mutex_lock(&(thread->joinmutex));
1511
1512                 pthread_mutex_unlock(&threadlistlock);
1513
1514                 while (thread->tid)
1515                         pthread_cond_wait(&(thread->joincond), &(thread->joinmutex));
1516
1517                 pthread_mutex_unlock(&(thread->joinmutex));
1518
1519                 pthread_mutex_lock(&threadlistlock);
1520         }
1521
1522         pthread_mutex_unlock(&threadlistlock);
1523 }
1524
1525
1526 /* threads_timespec_earlier ****************************************************
1527
1528    Return true if timespec tv1 is earlier than timespec tv2.
1529
1530    IN:
1531       tv1..........first timespec
1532           tv2..........second timespec
1533
1534    RETURN VALUE:
1535       true, if the first timespec is earlier
1536
1537 *******************************************************************************/
1538
1539 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1540                                                                                         const struct timespec *tv2)
1541 {
1542         return (tv1->tv_sec < tv2->tv_sec)
1543                                 ||
1544                 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1545 }
1546
1547
1548 /* threads_current_time_is_earlier_than ****************************************
1549
1550    Check if the current time is earlier than the given timespec.
1551
1552    IN:
1553       tv...........the timespec to compare against
1554
1555    RETURN VALUE:
1556       true, if the current time is earlier
1557
1558 *******************************************************************************/
1559
1560 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1561 {
1562         struct timeval tvnow;
1563         struct timespec tsnow;
1564
1565         /* get current time */
1566
1567         if (gettimeofday(&tvnow, NULL) != 0)
1568                 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1569
1570         /* convert it to a timespec */
1571
1572         tsnow.tv_sec = tvnow.tv_sec;
1573         tsnow.tv_nsec = tvnow.tv_usec * 1000;
1574
1575         /* compare current time with the given timespec */
1576
1577         return threads_timespec_earlier(&tsnow, tv);
1578 }
1579
1580
1581 /* threads_wait_with_timeout ***************************************************
1582
1583    Wait until the given point in time on a monitor until either
1584    we are notified, we are interrupted, or the time is up.
1585
1586    IN:
1587       t............the current thread
1588           wakeupTime...absolute (latest) wakeup time
1589                            If both tv_sec and tv_nsec are zero, this function
1590                                            waits for an unlimited amount of time.
1591
1592    RETURN VALUE:
1593       true.........if the wait has been interrupted,
1594           false........if the wait was ended by notification or timeout
1595
1596 *******************************************************************************/
1597
1598 static bool threads_wait_with_timeout(threadobject *thread,
1599                                                                           struct timespec *wakeupTime)
1600 {
1601         bool wasinterrupted;
1602
1603         /* acquire the waitmutex */
1604
1605         pthread_mutex_lock(&thread->waitmutex);
1606
1607         /* mark us as sleeping */
1608
1609         thread->sleeping = true;
1610
1611         /* wait on waitcond */
1612
1613         if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1614                 /* with timeout */
1615                 while (!thread->interrupted && !thread->signaled
1616                            && threads_current_time_is_earlier_than(wakeupTime))
1617                 {
1618                         pthread_cond_timedwait(&thread->waitcond, &thread->waitmutex,
1619                                                                    wakeupTime);
1620                 }
1621         }
1622         else {
1623                 /* no timeout */
1624                 while (!thread->interrupted && !thread->signaled)
1625                         pthread_cond_wait(&thread->waitcond, &thread->waitmutex);
1626         }
1627
1628         /* check if we were interrupted */
1629
1630         wasinterrupted = thread->interrupted;
1631
1632         /* reset all flags */
1633
1634         thread->interrupted = false;
1635         thread->signaled    = false;
1636         thread->sleeping    = false;
1637
1638         /* release the waitmutex */
1639
1640         pthread_mutex_unlock(&thread->waitmutex);
1641
1642         return wasinterrupted;
1643 }
1644
1645
1646 /* threads_wait_with_timeout_relative ******************************************
1647
1648    Wait for the given maximum amount of time on a monitor until either
1649    we are notified, we are interrupted, or the time is up.
1650
1651    IN:
1652       t............the current thread
1653           millis.......milliseconds to wait
1654           nanos........nanoseconds to wait
1655
1656    RETURN VALUE:
1657       true.........if the wait has been interrupted,
1658           false........if the wait was ended by notification or timeout
1659
1660 *******************************************************************************/
1661
1662 bool threads_wait_with_timeout_relative(threadobject *thread, s8 millis,
1663                                                                                 s4 nanos)
1664 {
1665         struct timespec wakeupTime;
1666
1667         /* calculate the the (latest) wakeup time */
1668
1669         threads_calc_absolute_time(&wakeupTime, millis, nanos);
1670
1671         /* wait */
1672
1673         return threads_wait_with_timeout(thread, &wakeupTime);
1674 }
1675
1676
1677 /* threads_calc_absolute_time **************************************************
1678
1679    Calculate the absolute point in time a given number of ms and ns from now.
1680
1681    IN:
1682       millis............milliseconds from now
1683           nanos.............nanoseconds from now
1684
1685    OUT:
1686       *tm...............receives the timespec of the absolute point in time
1687
1688 *******************************************************************************/
1689
1690 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1691 {
1692         if ((millis != 0x7fffffffffffffffLLU) && (millis || nanos)) {
1693                 struct timeval tv;
1694                 long nsec;
1695                 gettimeofday(&tv, NULL);
1696                 tv.tv_sec += millis / 1000;
1697                 millis %= 1000;
1698                 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1699                 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1700                 tm->tv_nsec = nsec % 1000000000;
1701         }
1702         else {
1703                 tm->tv_sec = 0;
1704                 tm->tv_nsec = 0;
1705         }
1706 }
1707
1708
1709 /* threads_thread_interrupt ****************************************************
1710
1711    Interrupt the given thread.
1712
1713    The thread gets the "waitcond" signal and 
1714    its interrupted flag is set to true.
1715
1716    IN:
1717       thread............the thread to interrupt
1718
1719 *******************************************************************************/
1720
1721 void threads_thread_interrupt(threadobject *thread)
1722 {
1723         /* Signal the thread a "waitcond" and tell it that it has been
1724            interrupted. */
1725
1726         pthread_mutex_lock(&thread->waitmutex);
1727
1728         /* Interrupt blocking system call using a signal. */
1729
1730         pthread_kill(thread->tid, SIGHUP);
1731
1732         if (thread->sleeping)
1733                 pthread_cond_signal(&thread->waitcond);
1734
1735         thread->interrupted = true;
1736
1737         pthread_mutex_unlock(&thread->waitmutex);
1738 }
1739
1740
1741 /* threads_check_if_interrupted_and_reset **************************************
1742
1743    Check if the current thread has been interrupted and reset the
1744    interruption flag.
1745
1746    RETURN VALUE:
1747       true, if the current thread had been interrupted
1748
1749 *******************************************************************************/
1750
1751 bool threads_check_if_interrupted_and_reset(void)
1752 {
1753         threadobject *thread;
1754         bool intr;
1755
1756         thread = THREADOBJECT;
1757
1758         /* get interrupted flag */
1759
1760         intr = thread->interrupted;
1761
1762         /* reset interrupted flag */
1763
1764         thread->interrupted = false;
1765
1766         return intr;
1767 }
1768
1769
1770 /* threads_thread_has_been_interrupted *****************************************
1771
1772    Check if the given thread has been interrupted
1773
1774    IN:
1775       t............the thread to check
1776
1777    RETURN VALUE:
1778       true, if the given thread had been interrupted
1779
1780 *******************************************************************************/
1781
1782 bool threads_thread_has_been_interrupted(threadobject *thread)
1783 {
1784         return thread->interrupted;
1785 }
1786
1787
1788 /* threads_sleep ***************************************************************
1789
1790    Sleep the current thread for the specified amount of time.
1791
1792 *******************************************************************************/
1793
1794 void threads_sleep(s8 millis, s4 nanos)
1795 {
1796         threadobject    *thread;
1797         struct timespec  wakeupTime;
1798         bool             wasinterrupted;
1799
1800         thread = THREADOBJECT;
1801
1802         threads_calc_absolute_time(&wakeupTime, millis, nanos);
1803
1804         wasinterrupted = threads_wait_with_timeout(thread, &wakeupTime);
1805
1806         if (wasinterrupted)
1807                 exceptions_throw_interruptedexception();
1808 }
1809
1810
1811 /* threads_yield ***************************************************************
1812
1813    Yield to the scheduler.
1814
1815 *******************************************************************************/
1816
1817 void threads_yield(void)
1818 {
1819         sched_yield();
1820 }
1821
1822
1823 /* threads_dump ****************************************************************
1824
1825    Dumps info for all threads running in the JVM. This function is
1826    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1827
1828 *******************************************************************************/
1829
1830 void threads_dump(void)
1831 {
1832         threadobject     *thread;
1833         java_lang_Thread *t;
1834         utf              *name;
1835
1836         thread = mainthreadobj;
1837
1838         /* XXX we should stop the world here */
1839
1840         printf("Full thread dump CACAO "VERSION":\n");
1841
1842         /* iterate over all started threads */
1843
1844         do {
1845                 /* get thread object */
1846
1847                 t = (java_lang_Thread *) thread;
1848
1849                 /* the thread may be currently in initalization, don't print it */
1850
1851                 if (t != NULL) {
1852                         /* get thread name */
1853
1854 #if defined(ENABLE_JAVASE)
1855                         name = javastring_toutf(t->name, false);
1856 #elif defined(ENABLE_JAVAME_CLDC1_1)
1857                         name = t->name;
1858 #endif
1859
1860                         printf("\n\"");
1861                         utf_display_printable_ascii(name);
1862                         printf("\" ");
1863
1864                         if (thread->flags & THREAD_FLAG_DAEMON)
1865                                 printf("daemon ");
1866
1867 #if SIZEOF_VOID_P == 8
1868                         printf("prio=%d tid=0x%016lx\n", t->priority, (ptrint) thread->tid);
1869 #else
1870                         printf("prio=%d tid=0x%08lx\n", t->priority, (ptrint) thread->tid);
1871 #endif
1872
1873                         /* dump trace of thread */
1874
1875                         stacktrace_dump_trace(thread);
1876                 }
1877
1878                 thread = thread->next;
1879         } while ((thread != NULL) && (thread != mainthreadobj));
1880 }
1881
1882
1883 /* threads_table_dump *********************************************************
1884
1885    Dump the threads table for debugging purposes.
1886
1887    IN:
1888       file..............stream to write to
1889
1890 ******************************************************************************/
1891
1892 #if !defined(NDEBUG) && 0
1893 static void threads_table_dump(FILE *file)
1894 {
1895         s4 i;
1896         s4 size;
1897         ptrint index;
1898
1899         pthread_mutex_lock(&threadlistlock);
1900
1901         size = threads_table.size;
1902
1903         fprintf(file, "======== THREADS TABLE (size %d) ========\n", size);
1904
1905         for (i=0; i<size; ++i) {
1906                 index = threads_table.table[i].nextfree;
1907
1908                 fprintf(file, "%4d: ", i);
1909
1910                 if (index < size) {
1911                         fprintf(file, "free, nextfree = %d\n", (int) index);
1912                 }
1913                 else {
1914                         fprintf(file, "thread %p\n", (void*) threads_table.table[i].thread);
1915                 }
1916         }
1917
1918         fprintf(file, "======== END OF THREADS TABLE ========\n");
1919
1920         pthread_mutex_unlock(&threadlistlock);
1921 }
1922 #endif
1923
1924 /*
1925  * These are local overrides for various environment variables in Emacs.
1926  * Please do not remove this and leave it at the end of the file, where
1927  * Emacs will automagically detect them.
1928  * ---------------------------------------------------------------------
1929  * Local variables:
1930  * mode: c
1931  * indent-tabs-mode: t
1932  * c-basic-offset: 4
1933  * tab-width: 4
1934  * End:
1935  * vim:noexpandtab:sw=4:ts=4:
1936  */