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