2004-08-30 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / threads.c
1 /*
2  * threads.c: Thread support internal calls
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *      Paolo Molaro (lupus@ximian.com)
7  *      Patrik Torstensson (patrik.torstensson@labs2.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  */
11
12 #include <config.h>
13 #ifdef PLATFORM_WIN32
14 #define _WIN32_WINNT 0x0500
15 #endif
16
17 #include <glib.h>
18 #include <signal.h>
19 #include <string.h>
20
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
33
34 #include <mono/os/gc_wrapper.h>
35
36 #undef THREAD_DEBUG
37 #undef THREAD_WAIT_DEBUG
38
39 struct StartInfo 
40 {
41         guint32 (*func)(void *);
42         MonoThread *obj;
43         void *this;
44         MonoDomain *domain;
45 };
46
47 typedef union {
48         gint32 ival;
49         gfloat fval;
50 } IntFloatUnion;
51  
52 typedef struct {
53         int idx;
54         int offset;
55 } StaticDataInfo;
56
57 /*
58  * The "os_handle" field of the WaitHandle class.
59  */
60 static MonoClassField *wait_handle_os_handle_field = NULL;
61
62 /* Controls access to the 'threads' hash table */
63 static CRITICAL_SECTION threads_mutex;
64
65 /* Controls access to context static data */
66 static CRITICAL_SECTION contexts_mutex;
67
68 /* Holds current status of static data heap */
69 static StaticDataInfo thread_static_info;
70 static StaticDataInfo context_static_info;
71
72 /* The hash of existing threads (key is thread ID) that need joining
73  * before exit
74  */
75 static MonoGHashTable *threads=NULL;
76
77 /* The TLS key that holds the MonoObject assigned to each thread */
78 static guint32 current_object_key = -1;
79
80 #ifdef HAVE_KW_THREAD
81 /* we need to use both the Tls* functions and __thread because
82  * the gc needs to see all the threads 
83  */
84 static __thread MonoThread * tls_current_object;
85 #define SET_CURRENT_OBJECT(x) do { \
86         tls_current_object = x; \
87         TlsSetValue (current_object_key, thread); \
88 } while (FALSE)
89 #define GET_CURRENT_OBJECT() tls_current_object
90 #else
91 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, thread);
92 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
93 #endif
94
95 /* function called at thread start */
96 static MonoThreadStartCB mono_thread_start_cb = NULL;
97
98 /* function called at thread attach */
99 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
100
101 /* function called at thread cleanup */
102 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
103
104 /* function called when a new thread has been created */
105 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
106
107 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
108 static guint32 slothash_key = -1;
109
110 /* The default stack size for each thread */
111 static guint32 default_stacksize = 0;
112
113 static void thread_adjust_static_data (MonoThread *thread);
114 static void mono_init_static_data_info (StaticDataInfo *static_data);
115 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
116
117 /* Spin lock for InterlockedXXX 64 bit functions */
118 static CRITICAL_SECTION interlocked_mutex;
119
120 /* Controls access to interruption flag */
121 static CRITICAL_SECTION interruption_mutex;
122
123 /* global count of thread interruptions requested */
124 static gint32 thread_interruption_requested = 0;
125
126
127 /* handle_store() and handle_remove() manage the array of threads that
128  * still need to be waited for when the main thread exits.
129  */
130 static void handle_store(MonoThread *thread)
131 {
132         EnterCriticalSection(&threads_mutex);
133
134 #ifdef THREAD_DEBUG
135         g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
136                   thread->tid);
137 #endif
138
139         if(threads==NULL) {
140                 MONO_GC_REGISTER_ROOT (threads);
141                 threads=mono_g_hash_table_new(NULL, NULL);
142         }
143
144         /* We don't need to duplicate thread->handle, because it is
145          * only closed when the thread object is finalized by the GC.
146          */
147         mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
148         LeaveCriticalSection(&threads_mutex);
149 }
150
151 static void handle_remove(guint32 tid)
152 {
153 #ifdef THREAD_DEBUG
154         g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
155 #endif
156
157         EnterCriticalSection(&threads_mutex);
158
159         if (threads)
160                 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
161         
162         LeaveCriticalSection(&threads_mutex);
163
164         /* Don't close the handle here, wait for the object finalizer
165          * to do it. Otherwise, the following race condition applies:
166          *
167          * 1) Thread exits (and handle_remove() closes the handle)
168          *
169          * 2) Some other handle is reassigned the same slot
170          *
171          * 3) Another thread tries to join the first thread, and
172          * blocks waiting for the reassigned handle to be signalled
173          * (which might never happen).  This is possible, because the
174          * thread calling Join() still has a reference to the first
175          * thread's object.
176          */
177 }
178
179 static void thread_cleanup (MonoThread *thread)
180 {
181         if (!mono_monitor_enter (thread->synch_lock))
182                 return;
183
184         thread->state |= ThreadState_Stopped;
185         mono_monitor_exit (thread->synch_lock);
186
187         mono_profiler_thread_end (thread->tid);
188         handle_remove (thread->tid);
189
190         mono_thread_pop_appdomain_ref ();
191
192         if (mono_thread_cleanup)
193                 mono_thread_cleanup (thread);
194 }
195
196 static guint32 start_wrapper(void *data)
197 {
198         struct StartInfo *start_info=(struct StartInfo *)data;
199         guint32 (*start_func)(void *);
200         void *this;
201         guint32 tid;
202         MonoThread *thread=start_info->obj;
203         
204 #ifdef THREAD_DEBUG
205         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
206                   GetCurrentThreadId ());
207 #endif
208         
209         /* We can be sure start_info->obj->tid and
210          * start_info->obj->handle have been set, because the thread
211          * was created suspended, and these values were set before the
212          * thread resumed
213          */
214
215         tid=thread->tid;
216
217         SET_CURRENT_OBJECT (thread);
218         
219         if (!mono_domain_set (start_info->domain, FALSE)) {
220                 /* No point in raising an appdomain_unloaded exception here */
221                 /* FIXME: Cleanup here */
222                 return 0;
223         }
224
225         start_func = start_info->func;
226         this = start_info->this;
227
228         /* This MUST be called before any managed code can be
229          * executed, as it calls the callback function that (for the
230          * jit) sets the lmf marker.
231          */
232         mono_thread_new_init (tid, &tid, start_func);
233         thread->stack_ptr = &tid;
234
235 #ifdef LIBGC_DEBUG
236         g_message (G_GNUC_PRETTY_FUNCTION
237                    ": (%d,%d) Setting thread stack to %p",
238                    GetCurrentThreadId (), getpid (), thread->stack_ptr);
239 #endif
240
241 #ifdef THREAD_DEBUG
242         g_message (G_GNUC_PRETTY_FUNCTION
243                    ": (%d) Setting current_object_key to %p",
244                    GetCurrentThreadId (), thread);
245 #endif
246
247         mono_profiler_thread_start (tid);
248
249         if(thread->start_notify!=NULL) {
250                 /* Let the thread that called Start() know we're
251                  * ready
252                  */
253                 ReleaseSemaphore (thread->start_notify, 1, NULL);
254         }
255         
256         g_free (start_info);
257
258         /* Every thread references the appdomain which created it */
259         mono_thread_push_appdomain_ref (mono_domain_get ());
260
261         thread_adjust_static_data (thread);
262 #ifndef PLATFORM_WIN32
263 #ifdef DEBUG
264         g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
265 #endif
266         pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
267 #endif
268
269         start_func (this);
270 #ifdef PLATFORM_WIN32
271         /* If the thread calls ExitThread at all, this remaining code
272          * will not be executed, but the main thread will eventually
273          * call thread_cleanup() on this thread's behalf.
274          */
275
276 #ifdef THREAD_DEBUG
277         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
278                   GetCurrentThreadId ());
279 #endif
280
281         /* Remove the reference to the thread object in the TLS data,
282          * so the thread object can be finalized.  This won't be
283          * reached if the thread threw an uncaught exception, so those
284          * thread handles will stay referenced :-( (This is due to
285          * missing support for scanning thread-specific data in the
286          * Boehm GC - the io-layer keeps a GC-visible hash of pointers
287          * to TLS data.)
288          */
289         SET_CURRENT_OBJECT (NULL);
290         
291         thread_cleanup (thread);
292 #else
293         pthread_cleanup_pop (1);
294 #endif
295
296         return(0);
297 }
298
299 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
300 {
301         if (mono_thread_start_cb) {
302                 mono_thread_start_cb (tid, stack_start, func);
303         }
304
305         if (mono_thread_callbacks)
306                 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
307 }
308
309 void mono_threads_set_default_stacksize (guint32 stacksize)
310 {
311         default_stacksize = stacksize;
312 }
313
314 guint32 mono_threads_get_default_stacksize (void)
315 {
316         return default_stacksize;
317 }
318
319 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
320 {
321         MonoThread *thread;
322         HANDLE thread_handle;
323         struct StartInfo *start_info;
324         guint32 tid;
325         
326         thread=(MonoThread *)mono_object_new (domain,
327                                               mono_defaults.thread_class);
328
329         start_info=g_new0 (struct StartInfo, 1);
330         start_info->func = func;
331         start_info->obj = thread;
332         start_info->domain = domain;
333         start_info->this = arg;
334         
335         /* Create suspended, so we can do some housekeeping before the thread
336          * starts
337          */
338 #ifdef PLATFORM_WIN32
339         thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
340                                      CREATE_SUSPENDED, &tid);
341 #else
342         thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
343                                      CREATE_SUSPENDED, &tid);
344 #endif
345 #ifdef THREAD_DEBUG
346         g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
347                   tid, thread_handle);
348 #endif
349         g_assert (thread_handle);
350
351         thread->handle=thread_handle;
352         thread->tid=tid;
353
354         thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
355                                                   
356         handle_store(thread);
357
358         ResumeThread (thread_handle);
359 }
360
361 MonoThread *
362 mono_thread_attach (MonoDomain *domain)
363 {
364         MonoThread *thread;
365         HANDLE thread_handle;
366         guint32 tid;
367
368         if ((thread = mono_thread_current ())) {
369                 /* Already attached */
370                 return thread;
371         }
372
373         thread = (MonoThread *)mono_object_new (domain,
374                                                 mono_defaults.thread_class);
375
376         thread_handle = GetCurrentThread ();
377         g_assert (thread_handle);
378
379         tid=GetCurrentThreadId ();
380
381         thread->handle=thread_handle;
382         thread->tid=tid;
383
384 #ifdef THREAD_DEBUG
385         g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
386                   tid, thread_handle);
387 #endif
388
389         handle_store(thread);
390
391 #ifdef THREAD_DEBUG
392         g_message (G_GNUC_PRETTY_FUNCTION
393                    ": (%d) Setting current_object_key to %p",
394                    GetCurrentThreadId (), thread);
395 #endif
396
397         SET_CURRENT_OBJECT (thread);
398         mono_domain_set (domain, TRUE);
399
400         thread_adjust_static_data (thread);
401
402         if (mono_thread_attach_cb) {
403                 mono_thread_attach_cb (tid, &tid);
404         }
405
406         return(thread);
407 }
408
409 void
410 mono_thread_detach (MonoThread *thread)
411 {
412         g_return_if_fail (thread != NULL);
413
414 #ifdef DEBUG
415         g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
416 #endif
417         SET_CURRENT_OBJECT (NULL);
418         
419         thread_cleanup (thread);
420 }
421
422 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
423                                                          MonoObject *start)
424 {
425         MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
426         guint32 (*start_func)(void *);
427         struct StartInfo *start_info;
428         MonoMethod *im;
429         HANDLE thread;
430         guint32 tid;
431         
432         MONO_ARCH_SAVE_REGS;
433
434 #ifdef THREAD_DEBUG
435         g_message(G_GNUC_PRETTY_FUNCTION
436                   ": Trying to start a new thread: this (%p) start (%p)",
437                   this, start);
438 #endif
439         
440         im = mono_get_delegate_invoke (start->vtable->klass);
441         im = mono_marshal_get_delegate_invoke (im);
442         if (mono_thread_callbacks)
443                 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
444         else
445                 start_func = mono_compile_method (im);
446
447         if(start_func==NULL) {
448                 g_warning(G_GNUC_PRETTY_FUNCTION
449                           ": Can't locate start method!");
450                 return(NULL);
451         } else {
452                 /* This is freed in start_wrapper */
453                 start_info = g_new0 (struct StartInfo, 1);
454                 start_info->func = start_func;
455                 start_info->this = delegate;
456                 start_info->obj = this;
457                 start_info->domain = mono_domain_get ();
458
459                 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
460                 if(this->start_notify==NULL) {
461                         g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
462                         return(NULL);
463                 }
464
465                 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
466                                     CREATE_SUSPENDED, &tid);
467                 if(thread==NULL) {
468                         g_warning(G_GNUC_PRETTY_FUNCTION
469                                   ": CreateThread error 0x%x", GetLastError());
470                         return(NULL);
471                 }
472                 
473                 this->handle=thread;
474                 this->tid=tid;
475
476                 /* Don't call handle_store() here, delay it to Start.
477                  * We can't join a thread (trying to will just block
478                  * forever) until it actually starts running, so don't
479                  * store the handle till then.
480                  */
481
482 #ifdef THREAD_DEBUG
483                 g_message(G_GNUC_PRETTY_FUNCTION
484                           ": Started thread ID %d (handle %p)", tid, thread);
485 #endif
486
487                 return(thread);
488         }
489 }
490
491 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
492                                                              HANDLE thread)
493 {
494         MONO_ARCH_SAVE_REGS;
495
496 #ifdef THREAD_DEBUG
497         g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
498                    this, thread);
499 #endif
500
501         CloseHandle (thread);
502 }
503
504 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
505                                                       HANDLE thread)
506 {
507         MONO_ARCH_SAVE_REGS;
508
509 #ifdef THREAD_DEBUG
510         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
511                   GetCurrentThreadId (), this, this->tid);
512 #endif
513
514         /* Only store the handle when the thread is about to be
515          * launched, to avoid the main thread deadlocking while trying
516          * to clean up a thread that will never be signalled.
517          */
518         handle_store(this);
519
520         if (mono_thread_callbacks)
521                 (* mono_thread_callbacks->start_resume) (this->tid);
522
523         ResumeThread(thread);
524
525         if (mono_thread_callbacks)
526                 (* mono_thread_callbacks->end_resume) (this->tid);
527
528         if(this->start_notify!=NULL) {
529                 /* Wait for the thread to set up its TLS data etc, so
530                  * theres no potential race condition if someone tries
531                  * to look up the data believing the thread has
532                  * started
533                  */
534
535 #ifdef THREAD_DEBUG
536                 g_message(G_GNUC_PRETTY_FUNCTION
537                           ": (%d) waiting for thread %p (%d) to start",
538                           GetCurrentThreadId (), this, this->tid);
539 #endif
540
541                 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
542                 CloseHandle (this->start_notify);
543                 this->start_notify=NULL;
544         }
545
546 #ifdef THREAD_DEBUG
547         g_message(G_GNUC_PRETTY_FUNCTION
548                   ": (%d) Done launching thread %p (%d)",
549                   GetCurrentThreadId (), this, this->tid);
550 #endif
551 }
552
553 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
554 {
555         MonoThread *thread = mono_thread_current ();
556         
557         MONO_ARCH_SAVE_REGS;
558
559 #ifdef THREAD_DEBUG
560         g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
561 #endif
562
563         mono_monitor_enter (thread->synch_lock);
564         thread->state |= ThreadState_WaitSleepJoin;
565         mono_monitor_exit (thread->synch_lock);
566         
567         SleepEx(ms,TRUE);
568         
569         mono_monitor_enter (thread->synch_lock);
570         thread->state &= ~ThreadState_WaitSleepJoin;
571         mono_monitor_exit (thread->synch_lock);
572 }
573
574 gint32
575 ves_icall_System_Threading_Thread_GetDomainID (void) 
576 {
577         MONO_ARCH_SAVE_REGS;
578
579         return mono_domain_get()->domain_id;
580 }
581
582 MonoString* 
583 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
584 {
585         if (!this_obj->name)
586                 return NULL;
587         else
588                 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
589 }
590
591 void 
592 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
593 {
594         if (this_obj->name)
595                 g_free (this_obj->name);
596         if (name) {
597                 this_obj->name = g_new (gunichar2, mono_string_length (name));
598                 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
599                 this_obj->name_len = mono_string_length (name);
600         }
601         else
602                 this_obj->name = NULL;
603 }
604
605 /* the jit may read the compiled code of this function */
606 MonoThread *
607 mono_thread_current (void)
608 {
609 #ifdef THREAD_DEBUG
610         MonoThread *thread;
611         MONO_ARCH_SAVE_REGS;
612         thread = GET_CURRENT_OBJECT ();
613         g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
614         return thread;
615 #else
616         MONO_ARCH_SAVE_REGS;
617         return GET_CURRENT_OBJECT ();
618 #endif
619 }
620
621 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
622                                                          int ms, HANDLE thread)
623 {
624         gboolean ret;
625         
626         MONO_ARCH_SAVE_REGS;
627
628         mono_monitor_enter (this->synch_lock);
629         this->state |= ThreadState_WaitSleepJoin;
630         mono_monitor_exit (this->synch_lock);
631
632         if(ms== -1) {
633                 ms=INFINITE;
634         }
635 #ifdef THREAD_DEBUG
636         g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
637                    thread, ms);
638 #endif
639         
640         ret=WaitForSingleObjectEx (thread, ms, TRUE);
641
642         mono_monitor_enter (this->synch_lock);
643         this->state &= ~ThreadState_WaitSleepJoin;
644         mono_monitor_exit (this->synch_lock);
645         
646         if(ret==WAIT_OBJECT_0) {
647 #ifdef THREAD_DEBUG
648                 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
649 #endif
650
651                 return(TRUE);
652         }
653         
654 #ifdef THREAD_DEBUG
655                 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
656 #endif
657
658         return(FALSE);
659 }
660
661 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
662 {
663         MONO_ARCH_SAVE_REGS;
664
665 #ifdef THREAD_DEBUG
666         g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
667 #endif
668
669         /* Object location stored here */
670         TlsSetValue(slothash_key, data);
671 }
672
673 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
674 {
675         MonoObject *data;
676
677         MONO_ARCH_SAVE_REGS;
678
679         data=TlsGetValue(slothash_key);
680         
681 #ifdef THREAD_DEBUG
682         g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
683 #endif
684         
685         return(data);
686 }
687
688 /* FIXME: exitContext isnt documented */
689 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
690 {
691         HANDLE *handles;
692         guint32 numhandles;
693         guint32 ret;
694         guint32 i;
695         MonoObject *waitHandle;
696         MonoClass *klass;
697                 
698         MONO_ARCH_SAVE_REGS;
699
700         numhandles = mono_array_length(mono_handles);
701         handles = g_new0(HANDLE, numhandles);
702
703         if (wait_handle_os_handle_field == 0) {
704                 /* Get the field os_handle which will contain the actual handle */
705                 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");   
706                 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
707         }
708                 
709         for(i = 0; i < numhandles; i++) {       
710                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);              
711                 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
712         }
713         
714         if(ms== -1) {
715                 ms=INFINITE;
716         }
717         
718         ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
719
720         g_free(handles);
721
722         if(ret==WAIT_FAILED) {
723 #ifdef THREAD_WAIT_DEBUG
724                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
725                           GetCurrentThreadId ());
726 #endif
727                 return(FALSE);
728         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
729                 /* Do we want to try again if we get
730                  * WAIT_IO_COMPLETION? The documentation for
731                  * WaitHandle doesn't give any clues.  (We'd have to
732                  * fiddle with the timeout if we retry.)
733                  */
734 #ifdef THREAD_WAIT_DEBUG
735                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
736                           GetCurrentThreadId ());
737 #endif
738                 return(FALSE);
739         }
740         
741         return(TRUE);
742 }
743
744 /* FIXME: exitContext isnt documented */
745 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
746 {
747         HANDLE *handles;
748         guint32 numhandles;
749         guint32 ret;
750         guint32 i;
751         MonoObject *waitHandle;
752         MonoClass *klass;
753                 
754         MONO_ARCH_SAVE_REGS;
755
756         numhandles = mono_array_length(mono_handles);
757         handles = g_new0(HANDLE, numhandles);
758
759         if (wait_handle_os_handle_field == 0) {
760                 /* Get the field os_handle which will contain the actual handle */
761                 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");   
762                 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
763         }
764                 
765         for(i = 0; i < numhandles; i++) {       
766                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);              
767                 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
768         }
769         
770         if(ms== -1) {
771                 ms=INFINITE;
772         }
773
774         ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
775
776         g_free(handles);
777
778 #ifdef THREAD_WAIT_DEBUG
779         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
780                   GetCurrentThreadId (), ret);
781 #endif
782
783         /*
784          * These need to be here.  See MSDN dos on WaitForMultipleObjects.
785          */
786         if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
787                 return ret - WAIT_OBJECT_0;
788         }
789         else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
790                 return ret - WAIT_ABANDONED_0;
791         }
792         else {
793                 return ret;
794         }
795 }
796
797 /* FIXME: exitContext isnt documented */
798 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
799 {
800         guint32 ret;
801         
802         MONO_ARCH_SAVE_REGS;
803
804 #ifdef THREAD_WAIT_DEBUG
805         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
806                   GetCurrentThreadId (), handle, ms);
807 #endif
808         
809         if(ms== -1) {
810                 ms=INFINITE;
811         }
812         
813         ret=WaitForSingleObjectEx (handle, ms, TRUE);
814
815         if(ret==WAIT_FAILED) {
816 #ifdef THREAD_WAIT_DEBUG
817                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
818                           GetCurrentThreadId ());
819 #endif
820                 return(FALSE);
821         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
822                 /* Do we want to try again if we get
823                  * WAIT_IO_COMPLETION? The documentation for
824                  * WaitHandle doesn't give any clues.  (We'd have to
825                  * fiddle with the timeout if we retry.)
826                  */
827 #ifdef THREAD_WAIT_DEBUG
828                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
829                           GetCurrentThreadId ());
830 #endif
831                 return(FALSE);
832         }
833         
834         return(TRUE);
835 }
836
837 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
838
839         HANDLE mutex;
840         
841         MONO_ARCH_SAVE_REGS;
842    
843         *created = TRUE;
844         
845         if (name == NULL) {
846                 mutex = CreateMutex (NULL, owned, NULL);
847         } else {
848                 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
849                 
850                 if (GetLastError () == ERROR_ALREADY_EXISTS) {
851                         *created = FALSE;
852                 }
853         }
854
855         return(mutex);
856 }                                                                   
857
858 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) { 
859         MONO_ARCH_SAVE_REGS;
860
861         ReleaseMutex(handle);
862 }
863
864 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
865         MONO_ARCH_SAVE_REGS;
866
867         return(CreateEvent (NULL, manual, initial,
868                             name==NULL?NULL:mono_string_chars (name)));
869 }
870
871 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
872         MONO_ARCH_SAVE_REGS;
873
874         return (SetEvent(handle));
875 }
876
877 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
878         MONO_ARCH_SAVE_REGS;
879
880         return (ResetEvent(handle));
881 }
882
883 void
884 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
885         MONO_ARCH_SAVE_REGS;
886
887         CloseHandle (handle);
888 }
889
890 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
891 {
892         MONO_ARCH_SAVE_REGS;
893
894         return InterlockedIncrement (location);
895 }
896
897 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
898 {
899         gint32 lowret;
900         gint32 highret;
901
902         MONO_ARCH_SAVE_REGS;
903
904         EnterCriticalSection(&interlocked_mutex);
905
906         lowret = InterlockedIncrement((gint32 *) location);
907         if (0 == lowret)
908                 highret = InterlockedIncrement((gint32 *) location + 1);
909         else
910                 highret = *((gint32 *) location + 1);
911
912         LeaveCriticalSection(&interlocked_mutex);
913
914         return (gint64) highret << 32 | (gint64) lowret;
915 }
916
917 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
918 {
919         MONO_ARCH_SAVE_REGS;
920
921         return InterlockedDecrement(location);
922 }
923
924 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
925 {
926         gint32 lowret;
927         gint32 highret;
928
929         MONO_ARCH_SAVE_REGS;
930
931         EnterCriticalSection(&interlocked_mutex);
932
933         lowret = InterlockedDecrement((gint32 *) location);
934         if (-1 == lowret)
935                 highret = InterlockedDecrement((gint32 *) location + 1);
936         else
937                 highret = *((gint32 *) location + 1);
938
939         LeaveCriticalSection(&interlocked_mutex);
940
941         return (gint64) highret << 32 | (gint64) lowret;
942 }
943
944 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
945 {
946         MONO_ARCH_SAVE_REGS;
947
948         return InterlockedExchange(location1, value);
949 }
950
951 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
952 {
953         MONO_ARCH_SAVE_REGS;
954
955         return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
956 }
957
958 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
959 {
960         IntFloatUnion val, ret;
961
962         MONO_ARCH_SAVE_REGS;
963
964         val.fval = value;
965         ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
966
967         return ret.fval;
968 }
969
970 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
971 {
972         MONO_ARCH_SAVE_REGS;
973
974         return InterlockedCompareExchange(location1, value, comparand);
975 }
976
977 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
978 {
979         MONO_ARCH_SAVE_REGS;
980
981         return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
982 }
983
984 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
985 {
986         IntFloatUnion val, ret, cmp;
987
988         MONO_ARCH_SAVE_REGS;
989
990         val.fval = value;
991         cmp.fval = comparand;
992         ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
993
994         return ret.fval;
995 }
996
997 int  
998 mono_thread_get_abort_signal (void)
999 {
1000 #ifdef __MINGW32__
1001         return -1;
1002 #else
1003 #ifndef SIGRTMIN
1004         return SIGUSR1;
1005 #else
1006         return SIGRTMIN;
1007 #endif
1008 #endif /* __MINGW32__ */
1009 }
1010
1011 #ifdef __MINGW32__
1012 static guint32 interruption_request_apc (gpointer param)
1013 {
1014         MonoException* exc = mono_thread_request_interruption (FALSE);
1015         if (exc) mono_raise_exception (exc);
1016         return 0;
1017 }
1018 #endif /* __MINGW32__ */
1019
1020 /*
1021  * signal_thread_state_change
1022  *
1023  * Tells the thread that his state has changed and it has to enter the new
1024  * state as soon as possible.
1025  */
1026 static void signal_thread_state_change (MonoThread *thread)
1027 {
1028 #ifdef __MINGW32__
1029         QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1030 #else
1031         /* fixme: store the state somewhere */
1032 #ifdef PTHREAD_POINTER_ID
1033         pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1034 #else
1035         pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1036 #endif
1037 #endif /* __MINGW32__ */
1038 }
1039
1040 void
1041 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1042 {
1043         MONO_ARCH_SAVE_REGS;
1044
1045         mono_monitor_enter (thread->synch_lock);
1046
1047         if ((thread->state & ThreadState_AbortRequested) != 0 || 
1048                 (thread->state & ThreadState_StopRequested) != 0) 
1049         {
1050                 mono_monitor_exit (thread->synch_lock);
1051                 return;
1052         }
1053
1054         thread->state |= ThreadState_AbortRequested;
1055         thread->abort_state = state;
1056         thread->abort_exc = NULL;
1057
1058         mono_monitor_exit (thread->synch_lock);
1059
1060 #ifdef THREAD_DEBUG
1061         g_message (G_GNUC_PRETTY_FUNCTION
1062                    ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1063                    thread, thread->tid);
1064 #endif
1065         
1066         /* Make sure the thread is awake */
1067         ves_icall_System_Threading_Thread_Resume (thread);
1068         
1069         signal_thread_state_change (thread);
1070 }
1071
1072 void
1073 ves_icall_System_Threading_Thread_ResetAbort (void)
1074 {
1075         MonoThread *thread = mono_thread_current ();
1076
1077         MONO_ARCH_SAVE_REGS;
1078         
1079         mono_monitor_enter (thread->synch_lock);
1080         
1081         thread->state &= ~ThreadState_AbortRequested;
1082         
1083         if (!thread->abort_exc) {
1084                 const char *msg = "Unable to reset abort because no abort was requested";
1085                 mono_monitor_exit (thread->synch_lock);
1086                 mono_raise_exception (mono_get_exception_thread_state (msg));
1087         } else {
1088                 thread->abort_exc = NULL;
1089                 thread->abort_state = NULL;
1090         }
1091         
1092         mono_monitor_exit (thread->synch_lock);
1093 }
1094
1095 void
1096 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1097 {
1098         MONO_ARCH_SAVE_REGS;
1099
1100         mono_monitor_enter (thread->synch_lock);
1101
1102         if ((thread->state & ThreadState_Suspended) != 0 || 
1103                 (thread->state & ThreadState_SuspendRequested) != 0 ||
1104                 (thread->state & ThreadState_StopRequested) != 0) 
1105         {
1106                 mono_monitor_exit (thread->synch_lock);
1107                 return;
1108         }
1109         
1110         thread->state |= ThreadState_SuspendRequested;
1111         mono_monitor_exit (thread->synch_lock);
1112
1113         signal_thread_state_change (thread);
1114 }
1115
1116 void
1117 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1118 {
1119         MONO_ARCH_SAVE_REGS;
1120
1121         mono_monitor_enter (thread->synch_lock);
1122
1123         if ((thread->state & ThreadState_SuspendRequested) != 0) {
1124                 thread->state &= ~ThreadState_SuspendRequested;
1125                 mono_monitor_exit (thread->synch_lock);
1126                 return;
1127         }
1128                 
1129         if ((thread->state & ThreadState_Suspended) == 0) 
1130         {
1131                 mono_monitor_exit (thread->synch_lock);
1132                 return;
1133         }
1134         
1135         thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1136         
1137         /* Awake the thread */
1138         SetEvent (thread->suspend_event);
1139
1140         mono_monitor_exit (thread->synch_lock);
1141
1142         /* Wait for the thread to awake */
1143         WaitForSingleObject (thread->resume_event, INFINITE);
1144         CloseHandle (thread->resume_event);
1145         thread->resume_event = NULL;
1146 }
1147
1148 void mono_thread_stop (MonoThread *thread)
1149 {
1150         mono_monitor_enter (thread->synch_lock);
1151
1152         if ((thread->state & ThreadState_StopRequested) != 0 ||
1153                 (thread->state & ThreadState_Stopped) != 0)
1154         {
1155                 mono_monitor_exit (thread->synch_lock);
1156                 return;
1157         }
1158         
1159         /* Make sure the thread is awake */
1160         ves_icall_System_Threading_Thread_Resume (thread);
1161         
1162         thread->state |= ThreadState_StopRequested;
1163         thread->state &= ~ThreadState_AbortRequested;
1164         
1165         mono_monitor_exit (thread->synch_lock);
1166         
1167         signal_thread_state_change (thread);
1168 }
1169
1170 gint8
1171 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1172 {
1173         return *((volatile gint8 *) (ptr));
1174 }
1175
1176 gint16
1177 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1178 {
1179         return *((volatile gint16 *) (ptr));
1180 }
1181
1182 gint32
1183 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1184 {
1185         return *((volatile gint32 *) (ptr));
1186 }
1187
1188 gint64
1189 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1190 {
1191         return *((volatile gint64 *) (ptr));
1192 }
1193
1194 void *
1195 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1196 {
1197         return (void *)  *((volatile void **) ptr);
1198 }
1199
1200 void
1201 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1202 {
1203         *((volatile gint8 *) ptr) = value;
1204 }
1205
1206 void
1207 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1208 {
1209         *((volatile gint16 *) ptr) = value;
1210 }
1211
1212 void
1213 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1214 {
1215         *((volatile gint32 *) ptr) = value;
1216 }
1217
1218 void
1219 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1220 {
1221         *((volatile gint64 *) ptr) = value;
1222 }
1223
1224 void
1225 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1226 {
1227         *((volatile void **) ptr) = value;
1228 }
1229
1230 void mono_thread_init (MonoThreadStartCB start_cb,
1231                        MonoThreadAttachCB attach_cb)
1232 {
1233         InitializeCriticalSection(&threads_mutex);
1234         InitializeCriticalSection(&interlocked_mutex);
1235         InitializeCriticalSection(&contexts_mutex);
1236         InitializeCriticalSection(&interruption_mutex);
1237         
1238         mono_init_static_data_info (&thread_static_info);
1239         mono_init_static_data_info (&context_static_info);
1240
1241         current_object_key=TlsAlloc();
1242 #ifdef THREAD_DEBUG
1243         g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1244                    current_object_key);
1245 #endif
1246
1247         mono_thread_start_cb = start_cb;
1248         mono_thread_attach_cb = attach_cb;
1249
1250         slothash_key=TlsAlloc();
1251
1252         /* Get a pseudo handle to the current process.  This is just a
1253          * kludge so that wapi can build a process handle if needed.
1254          * As a pseudo handle is returned, we don't need to clean
1255          * anything up.
1256          */
1257         GetCurrentProcess ();
1258 }
1259
1260 void
1261 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1262 {
1263         mono_thread_cleanup = func;
1264 }
1265
1266 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1267 {
1268         mono_thread_callbacks = callbacks;
1269 }
1270
1271 #ifdef THREAD_DEBUG
1272 static void print_tids (gpointer key, gpointer value, gpointer user)
1273 {
1274         g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1275 }
1276 #endif
1277
1278 struct wait_data 
1279 {
1280         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1281         MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1282         guint32 num;
1283 };
1284
1285 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1286 {
1287         guint32 i, ret;
1288         
1289 #ifdef THREAD_DEBUG
1290         g_message(G_GNUC_PRETTY_FUNCTION
1291                   ": %d threads to wait for in this batch", wait->num);
1292 #endif
1293
1294         ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1295
1296         if(ret==WAIT_FAILED) {
1297                 /* See the comment in build_wait_tids() */
1298 #ifdef THREAD_DEBUG
1299                 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1300 #endif
1301                 return;
1302         }
1303         
1304
1305         for(i=0; i<wait->num; i++) {
1306                 guint32 tid=wait->threads[i]->tid;
1307                 CloseHandle (wait->handles[i]);
1308                 
1309                 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1310                         /* This thread must have been killed, because
1311                          * it hasn't cleaned itself up. (It's just
1312                          * possible that the thread exited before the
1313                          * parent thread had a chance to store the
1314                          * handle, and now there is another pointer to
1315                          * the already-exited thread stored.  In this
1316                          * case, we'll just get two
1317                          * mono_profiler_thread_end() calls for the
1318                          * same thread.)
1319                          */
1320         
1321 #ifdef THREAD_DEBUG
1322                         g_message (G_GNUC_PRETTY_FUNCTION
1323                                    ": cleaning up after thread %d", tid);
1324 #endif
1325                         thread_cleanup (wait->threads[i]);
1326                 }
1327         }
1328 }
1329
1330 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1331 {
1332         struct wait_data *wait=(struct wait_data *)user;
1333
1334         if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1335                 HANDLE handle;
1336                 MonoThread *thread=(MonoThread *)value;
1337
1338                 /* Ignore background threads, we abort them later */
1339                 if (thread->state & ThreadState_Background)
1340                         return; /* just leave, ignore */
1341                 
1342                 if (mono_gc_is_finalizer_thread (thread))
1343                         return;
1344
1345                 if (thread == mono_thread_current ())
1346                         return;
1347
1348                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1349                 if (handle == NULL)
1350                         return;
1351                 
1352                 wait->handles[wait->num]=handle;
1353                 wait->threads[wait->num]=thread;
1354                 wait->num++;
1355         } else {
1356                 /* Just ignore the rest, we can't do anything with
1357                  * them yet
1358                  */
1359         }
1360 }
1361
1362 static gboolean
1363 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1364 {
1365         struct wait_data *wait=(struct wait_data *)user;
1366         guint32 self = GetCurrentThreadId ();
1367         MonoThread *thread = (MonoThread *) value;
1368         HANDLE handle;
1369
1370         /* The finalizer thread is not a background thread */
1371         if (thread->tid != self && thread->state & ThreadState_Background) {
1372         
1373                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1374                 if (handle == NULL)
1375                         return FALSE;
1376                 
1377                 wait->handles[wait->num]=thread->handle;
1378                 wait->threads[wait->num]=thread;
1379                 wait->num++;
1380         
1381                 if(thread->state & ThreadState_AbortRequested ||
1382                    thread->state & ThreadState_Aborted) {
1383 #ifdef THREAD_DEBUG
1384                         g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1385 #endif
1386                         return(TRUE);
1387                 }
1388                 
1389 #ifdef THREAD_DEBUG
1390                 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1391 #endif
1392                 mono_thread_stop (thread);
1393                 return TRUE;
1394         }
1395
1396         return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
1397 }
1398
1399 void mono_thread_manage (void)
1400 {
1401         struct wait_data *wait=g_new0 (struct wait_data, 1);
1402         
1403         /* join each thread that's still running */
1404 #ifdef THREAD_DEBUG
1405         g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1406 #endif
1407         
1408         EnterCriticalSection (&threads_mutex);
1409         if(threads==NULL) {
1410 #ifdef THREAD_DEBUG
1411                 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1412 #endif
1413                 LeaveCriticalSection (&threads_mutex);
1414                 return;
1415         }
1416         LeaveCriticalSection (&threads_mutex);
1417         
1418         do {
1419                 EnterCriticalSection (&threads_mutex);
1420 #ifdef THREAD_DEBUG
1421                 g_message(G_GNUC_PRETTY_FUNCTION
1422                           ":There are %d threads to join",
1423                           mono_g_hash_table_size (threads));
1424                 mono_g_hash_table_foreach (threads, print_tids, NULL);
1425 #endif
1426         
1427                 wait->num=0;
1428                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1429                 LeaveCriticalSection (&threads_mutex);
1430                 if(wait->num>0) {
1431                         /* Something to wait for */
1432                         wait_for_tids (wait, INFINITE);
1433                 }
1434         } while(wait->num>0);
1435         
1436         mono_thread_pool_cleanup ();
1437
1438         EnterCriticalSection(&threads_mutex);
1439
1440         /* 
1441          * Remove everything but the finalizer thread and self.
1442          * Also abort all the background threads
1443          * */
1444         wait->num = 0;
1445         mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1446
1447         LeaveCriticalSection(&threads_mutex);
1448
1449         if(wait->num>0) {
1450                 /* Something to wait for */
1451                 wait_for_tids (wait, INFINITE);
1452         }
1453
1454         g_free (wait);
1455 }
1456
1457 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1458 {
1459         MonoThread *thread=(MonoThread *)value;
1460         guint32 self=GPOINTER_TO_UINT (user);
1461         
1462         if(thread->tid!=self) {
1463                 /*TerminateThread (thread->handle, -1);*/
1464         }
1465 }
1466
1467 void mono_thread_abort_all_other_threads (void)
1468 {
1469         guint32 self=GetCurrentThreadId ();
1470
1471         EnterCriticalSection (&threads_mutex);
1472 #ifdef THREAD_DEBUG
1473         g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1474                   mono_g_hash_table_size (threads));
1475         mono_g_hash_table_foreach (threads, print_tids, NULL);
1476 #endif
1477
1478         mono_g_hash_table_foreach (threads, terminate_thread,
1479                                    GUINT_TO_POINTER (self));
1480         
1481         LeaveCriticalSection (&threads_mutex);
1482 }
1483
1484 /*
1485  * mono_thread_push_appdomain_ref:
1486  *
1487  *   Register that the current thread may have references to objects in domain 
1488  * @domain on its stack. Each call to this function should be paired with a 
1489  * call to pop_appdomain_ref.
1490  */
1491 void 
1492 mono_thread_push_appdomain_ref (MonoDomain *domain)
1493 {
1494         MonoThread *thread = mono_thread_current ();
1495
1496         if (thread) {
1497                 /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
1498                 EnterCriticalSection (&threads_mutex);
1499                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1500                 LeaveCriticalSection (&threads_mutex);
1501         }
1502 }
1503
1504 void
1505 mono_thread_pop_appdomain_ref (void)
1506 {
1507         MonoThread *thread = mono_thread_current ();
1508
1509         if (thread) {
1510                 /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1511                 EnterCriticalSection (&threads_mutex);
1512                 /* FIXME: How can the list be empty ? */
1513                 if (thread->appdomain_refs)
1514                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1515                 LeaveCriticalSection (&threads_mutex);
1516         }
1517 }
1518
1519 static gboolean
1520 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1521 {
1522         gboolean res;
1523         EnterCriticalSection (&threads_mutex);
1524         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1525         LeaveCriticalSection (&threads_mutex);
1526         return res;
1527 }
1528
1529 typedef struct abort_appdomain_data {
1530         struct wait_data wait;
1531         MonoDomain *domain;
1532 } abort_appdomain_data;
1533
1534 static void
1535 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1536 {
1537         MonoThread *thread = (MonoThread*)value;
1538         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1539         MonoDomain *domain = data->domain;
1540
1541         if (mono_thread_has_appdomain_ref (thread, domain)) {
1542                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1543                 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1544                 if (handle == NULL)
1545                         return;
1546
1547                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1548
1549                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1550                         data->wait.handles [data->wait.num] = handle;
1551                         data->wait.threads [data->wait.num] = thread;
1552                         data->wait.num++;
1553                 } else {
1554                         /* Just ignore the rest, we can't do anything with
1555                          * them yet
1556                          */
1557                 }
1558         }
1559 }
1560
1561 /*
1562  * mono_threads_abort_appdomain_threads:
1563  *
1564  *   Abort threads which has references to the given appdomain.
1565  */
1566 gboolean
1567 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1568 {
1569         abort_appdomain_data user_data;
1570         guint32 start_time;
1571
1572         /* printf ("ABORT BEGIN.\n"); */
1573
1574         start_time = GetTickCount ();
1575         do {
1576                 EnterCriticalSection (&threads_mutex);
1577
1578                 user_data.domain = domain;
1579                 user_data.wait.num = 0;
1580                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1581                 LeaveCriticalSection (&threads_mutex);
1582
1583                 if (user_data.wait.num > 0)
1584                         wait_for_tids (&user_data.wait, timeout);
1585
1586                 /* Update remaining time */
1587                 timeout -= GetTickCount () - start_time;
1588                 start_time = GetTickCount ();
1589
1590                 if (timeout < 0)
1591                         return FALSE;
1592         }
1593         while (user_data.wait.num > 0);
1594
1595         /* printf ("ABORT DONE.\n"); */
1596
1597         return TRUE;
1598 }
1599
1600 /*
1601  * mono_thread_get_pending_exception:
1602  *
1603  *   Return an exception which needs to be raised when leaving a catch clause.
1604  * This is used for undeniable exception propagation.
1605  */
1606 MonoException*
1607 mono_thread_get_pending_exception (void)
1608 {
1609         MonoThread *thread = mono_thread_current ();
1610
1611         MONO_ARCH_SAVE_REGS;
1612
1613         if (thread && thread->abort_exc) {
1614                 /*
1615                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
1616                  * exception if the thread no longer references a dying appdomain.
1617                  */
1618                 thread->abort_exc->trace_ips = NULL;
1619                 thread->abort_exc->stack_trace = NULL;
1620                 return thread->abort_exc;
1621         }
1622
1623         return NULL;
1624 }
1625
1626 #define NUM_STATIC_DATA_IDX 8
1627 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1628         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1629 };
1630
1631
1632 /*
1633  *  mono_alloc_static_data
1634  *
1635  *   Allocate memory blocks for storing threads or context static data
1636  */
1637 static void 
1638 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1639 {
1640         guint idx = (offset >> 24) - 1;
1641         int i;
1642
1643         gpointer* static_data = *static_data_ptr;
1644         if (!static_data) {
1645 #if HAVE_BOEHM_GC
1646                 static_data = GC_MALLOC (static_data_size [0]);
1647 #else
1648                 static_data = g_malloc0 (static_data_size [0]);
1649 #endif
1650                 *static_data_ptr = static_data;
1651                 static_data [0] = static_data;
1652         }
1653         
1654         for (i = 1; i < idx; ++i) {
1655                 if (static_data [i])
1656                         continue;
1657 #if HAVE_BOEHM_GC
1658                 static_data [i] = GC_MALLOC (static_data_size [i]);
1659 #else
1660                 static_data [i] = g_malloc0 (static_data_size [i]);
1661 #endif
1662         }
1663 }
1664
1665 /*
1666  *  mono_init_static_data_info
1667  *
1668  *   Initializes static data counters
1669  */
1670 static void mono_init_static_data_info (StaticDataInfo *static_data)
1671 {
1672         static_data->idx = 0;
1673         static_data->offset = 0;
1674 }
1675
1676 /*
1677  *  mono_alloc_static_data_slot
1678  *
1679  *   Generates an offset for static data. static_data contains the counters
1680  *  used to generate it.
1681  */
1682 static guint32
1683 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1684 {
1685         guint32 offset;
1686
1687         if (!static_data->idx && !static_data->offset) {
1688                 /* 
1689                  * we use the first chunk of the first allocation also as
1690                  * an array for the rest of the data 
1691                  */
1692                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1693         }
1694         static_data->offset += align - 1;
1695         static_data->offset &= ~(align - 1);
1696         if (static_data->offset + size >= static_data_size [static_data->idx]) {
1697                 static_data->idx ++;
1698                 g_assert (size <= static_data_size [static_data->idx]);
1699                 /* 
1700                  * massive unloading and reloading of domains with thread-static
1701                  * data may eventually exceed the allocated storage...
1702                  * Need to check what the MS runtime does in that case.
1703                  * Note that for each appdomain, we need to allocate a separate
1704                  * thread data slot for security reasons. We could keep track
1705                  * of the slots per-domain and when the domain is unloaded
1706                  * out the slots on a sort of free list.
1707                  */
1708                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1709                 static_data->offset = 0;
1710         }
1711         offset = static_data->offset | ((static_data->idx + 1) << 24);
1712         static_data->offset += size;
1713         return offset;
1714 }
1715
1716 /* 
1717  * ensure thread static fields already allocated are valid for thread
1718  * This function is called when a thread is created or on thread attach.
1719  */
1720 static void
1721 thread_adjust_static_data (MonoThread *thread)
1722 {
1723         guint32 offset;
1724
1725         EnterCriticalSection (&threads_mutex);
1726         if (thread_static_info.offset || thread_static_info.idx > 0) {
1727                 /* get the current allocated size */
1728                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1729                 mono_alloc_static_data (&(thread->static_data), offset);
1730         }
1731         LeaveCriticalSection (&threads_mutex);
1732 }
1733
1734 static void 
1735 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1736 {
1737         MonoThread *thread = value;
1738         guint32 offset = GPOINTER_TO_UINT (user);
1739         
1740         mono_alloc_static_data (&(thread->static_data), offset);
1741 }
1742
1743 /*
1744  * The offset for a special static variable is composed of three parts:
1745  * a bit that indicates the type of static data (0:thread, 1:context),
1746  * an index in the array of chunks of memory for the thread (thread->static_data)
1747  * and an offset in that chunk of mem. This allows allocating less memory in the 
1748  * common case.
1749  */
1750
1751 guint32
1752 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1753 {
1754         guint32 offset;
1755         if (static_type == SPECIAL_STATIC_THREAD)
1756         {
1757                 EnterCriticalSection (&threads_mutex);
1758                 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1759                 /* This can be called during startup */
1760                 if (threads != NULL)
1761                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1762                 LeaveCriticalSection (&threads_mutex);
1763         }
1764         else
1765         {
1766                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1767                 EnterCriticalSection (&contexts_mutex);
1768                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1769                 LeaveCriticalSection (&contexts_mutex);
1770                 offset |= 0x80000000;   /* Set the high bit to indicate context static data */
1771         }
1772         return offset;
1773 }
1774
1775 gpointer
1776 mono_get_special_static_data (guint32 offset)
1777 {
1778         /* The high bit means either thread (0) or static (1) data. */
1779
1780         guint32 static_type = (offset & 0x80000000);
1781         int idx;
1782
1783         offset &= 0x7fffffff;
1784         idx = (offset >> 24) - 1;
1785
1786         if (static_type == 0)
1787         {
1788                 MonoThread *thread = mono_thread_current ();
1789                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1790         }
1791         else
1792         {
1793                 /* Allocate static data block under demand, since we don't have a list
1794                 // of contexts
1795                 */
1796                 MonoAppContext *context = mono_context_get ();
1797                 if (!context->static_data || !context->static_data [idx]) {
1798                         EnterCriticalSection (&contexts_mutex);
1799                         mono_alloc_static_data (&(context->static_data), offset);
1800                         LeaveCriticalSection (&contexts_mutex);
1801                 }
1802                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
1803         }
1804 }
1805
1806 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1807 {
1808         MonoThread *thread=(MonoThread *)value;
1809         guint32 self=GPOINTER_TO_UINT (user);
1810
1811 #ifdef LIBGC_DEBUG
1812         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1813 #endif
1814         
1815         if(thread->tid==self)
1816                 return;
1817
1818         SuspendThread (thread->handle);
1819 }
1820
1821 void mono_gc_stop_world (void)
1822 {
1823         guint32 self=GetCurrentThreadId ();
1824
1825 #ifdef LIBGC_DEBUG
1826         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1827 #endif
1828
1829         EnterCriticalSection (&threads_mutex);
1830
1831         if (threads != NULL)
1832                 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1833         
1834         LeaveCriticalSection (&threads_mutex);
1835 }
1836
1837 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1838 {
1839         MonoThread *thread=(MonoThread *)value;
1840         guint32 self=GPOINTER_TO_UINT (user);
1841         
1842 #ifdef LIBGC_DEBUG
1843         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1844 #endif
1845         
1846         if(thread->tid==self)
1847                 return;
1848
1849         ResumeThread (thread->handle);
1850 }
1851
1852 void mono_gc_start_world (void)
1853 {
1854         guint32 self=GetCurrentThreadId ();
1855
1856 #ifdef LIBGC_DEBUG
1857         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1858 #endif
1859
1860         EnterCriticalSection (&threads_mutex);
1861
1862         if (threads != NULL)
1863                 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1864         
1865         LeaveCriticalSection (&threads_mutex);
1866 }
1867
1868
1869 static guint32 dummy_apc (gpointer param)
1870 {
1871         return 0;
1872 }
1873
1874 /*
1875  * mono_thread_execute_interruption
1876  * 
1877  * Performs the operation that the requested thread state requires (abort,
1878  * suspend or stop)
1879  */
1880 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1881 {
1882         mono_monitor_enter (thread->synch_lock);
1883         
1884         if (thread->interruption_requested) {
1885                 /* this will consume pending APC calls */
1886                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1887                 EnterCriticalSection (&interruption_mutex);
1888                 thread_interruption_requested--;
1889                 LeaveCriticalSection (&interruption_mutex);
1890                 thread->interruption_requested = FALSE;
1891         }
1892
1893         if ((thread->state & ThreadState_AbortRequested) != 0) {
1894                 thread->abort_exc = mono_get_exception_thread_abort ();
1895                 mono_monitor_exit (thread->synch_lock);
1896                 return thread->abort_exc;
1897         }
1898         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1899                 thread->state &= ~ThreadState_SuspendRequested;
1900                 thread->state |= ThreadState_Suspended;
1901                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1902                 mono_monitor_exit (thread->synch_lock);
1903                 
1904                 WaitForSingleObject (thread->suspend_event, INFINITE);
1905                 
1906                 mono_monitor_enter (thread->synch_lock);
1907                 CloseHandle (thread->suspend_event);
1908                 thread->suspend_event = NULL;
1909                 thread->state &= ~ThreadState_Suspended;
1910         
1911                 /* The thread that requested the resume will have replaced this event
1912              * and will be waiting for it
1913                  */
1914                 SetEvent (thread->resume_event);
1915                 mono_monitor_exit (thread->synch_lock);
1916                 return NULL;
1917         }
1918         else if ((thread->state & ThreadState_StopRequested) != 0) {
1919                 /* FIXME: do this through the JIT? */
1920                 mono_monitor_exit (thread->synch_lock);
1921                 ExitThread (-1);
1922                 return NULL;
1923         }
1924         
1925         mono_monitor_exit (thread->synch_lock);
1926         return NULL;
1927 }
1928
1929 /*
1930  * mono_thread_request_interruption
1931  *
1932  * A signal handler can call this method to request the interruption of a
1933  * thread. The result of the interruption will depend on the current state of
1934  * the thread. If the result is an exception that needs to be throw, it is 
1935  * provided as return value.
1936  */
1937 MonoException* mono_thread_request_interruption (gboolean running_managed)
1938 {
1939         MonoThread *thread = mono_thread_current ();
1940
1941         /* The thread may already be stopping */
1942         if (thread == NULL) 
1943                 return NULL;
1944         
1945         mono_monitor_enter (thread->synch_lock);
1946         
1947         if (thread->interruption_requested) {
1948                 mono_monitor_exit (thread->synch_lock);
1949                 return NULL;
1950         }
1951
1952         if (!running_managed) {
1953                 /* Can't stop while in unmanaged code. Increase the global interruption
1954                    request count. When exiting the unmanaged method the count will be
1955                    checked and the thread will be interrupted. */
1956                 
1957                 EnterCriticalSection (&interruption_mutex);
1958                 thread_interruption_requested++;
1959                 LeaveCriticalSection (&interruption_mutex);
1960                 
1961                 thread->interruption_requested = TRUE;
1962                 mono_monitor_exit (thread->synch_lock);
1963                 
1964                 /* this will awake the thread if it is in WaitForSingleObject 
1965                or similar */
1966                 QueueUserAPC (dummy_apc, thread->handle, NULL);
1967                 
1968                 return NULL;
1969         }
1970         else {
1971                 mono_monitor_exit (thread->synch_lock);
1972                 return mono_thread_execute_interruption (thread);
1973         }
1974 }
1975
1976 gboolean mono_thread_interruption_requested ()
1977 {
1978         if (thread_interruption_requested) {
1979                 MonoThread *thread = mono_thread_current ();
1980                 /* The thread may already be stopping */
1981                 if (thread != NULL) 
1982                         return (thread->interruption_requested);
1983         }
1984         return FALSE;
1985 }
1986
1987 /*
1988  * Performs the interruption of the current thread, if one has been requested.
1989  */
1990 void mono_thread_interruption_checkpoint ()
1991 {
1992         MonoThread *thread = mono_thread_current ();
1993         
1994         /* The thread may already be stopping */
1995         if (thread == NULL) 
1996                 return;
1997         
1998         if (thread->interruption_requested) {
1999                 MonoException* exc = mono_thread_execute_interruption (thread);
2000                 if (exc) mono_raise_exception (exc);
2001         }
2002 }
2003
2004 /*
2005  * Returns the address of a flag that will be non-zero if an interruption has
2006  * been requested for a thread. The thread to interrupt may not be the current
2007  * thread, so an additional call to mono_thread_interruption_requested() or
2008  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2009  * zero.
2010  */
2011 gint32* mono_thread_interruption_request_flag ()
2012 {
2013         return &thread_interruption_requested;
2014 }
2015
2016 #ifdef WITH_INCLUDED_LIBGC
2017
2018 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2019 {
2020         MonoThread *thread=(MonoThread *)value;
2021         guint32 *selfp=(guint32 *)user, self = *selfp;
2022
2023 #ifdef LIBGC_DEBUG
2024         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2025 #endif
2026         
2027         if(thread->tid==self) {
2028 #ifdef LIBGC_DEBUG
2029                 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2030 #endif
2031                 GC_push_all_stack (selfp, thread->stack_ptr);
2032                 return;
2033         }
2034
2035 #ifdef PLATFORM_WIN32
2036         GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2037 #else
2038         mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2039 #endif
2040 }
2041
2042 void mono_gc_push_all_stacks (void)
2043 {
2044         guint32 self=GetCurrentThreadId ();
2045
2046 #ifdef LIBGC_DEBUG
2047         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2048 #endif
2049
2050         EnterCriticalSection (&threads_mutex);
2051
2052         if (threads != NULL)
2053                 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2054         
2055         LeaveCriticalSection (&threads_mutex);
2056 }
2057
2058 #endif /* WITH_INCLUDED_LIBGC */