2004-09-24 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, x); \
88 } while (FALSE)
89 #define GET_CURRENT_OBJECT() tls_current_object
90 #else
91 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
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 #ifdef DEBUG
263         g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
264 #endif
265
266         start_func (this);
267 #ifdef PLATFORM_WIN32
268         /* If the thread calls ExitThread at all, this remaining code
269          * will not be executed, but the main thread will eventually
270          * call thread_cleanup() on this thread's behalf.
271          */
272
273 #ifdef THREAD_DEBUG
274         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
275                   GetCurrentThreadId ());
276 #endif
277
278         /* Remove the reference to the thread object in the TLS data,
279          * so the thread object can be finalized.  This won't be
280          * reached if the thread threw an uncaught exception, so those
281          * thread handles will stay referenced :-( (This is due to
282          * missing support for scanning thread-specific data in the
283          * Boehm GC - the io-layer keeps a GC-visible hash of pointers
284          * to TLS data.)
285          */
286         SET_CURRENT_OBJECT (NULL);
287 #endif
288         
289         thread_cleanup (thread);
290
291         return(0);
292 }
293
294 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
295 {
296         if (mono_thread_start_cb) {
297                 mono_thread_start_cb (tid, stack_start, func);
298         }
299
300         if (mono_thread_callbacks)
301                 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
302 }
303
304 void mono_threads_set_default_stacksize (guint32 stacksize)
305 {
306         default_stacksize = stacksize;
307 }
308
309 guint32 mono_threads_get_default_stacksize (void)
310 {
311         return default_stacksize;
312 }
313
314 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
315 {
316         MonoThread *thread;
317         HANDLE thread_handle;
318         struct StartInfo *start_info;
319         guint32 tid;
320         
321         thread=(MonoThread *)mono_object_new (domain,
322                                               mono_defaults.thread_class);
323
324         start_info=g_new0 (struct StartInfo, 1);
325         start_info->func = func;
326         start_info->obj = thread;
327         start_info->domain = domain;
328         start_info->this = arg;
329         
330         /* Create suspended, so we can do some housekeeping before the thread
331          * starts
332          */
333 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
334         thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
335                                      CREATE_SUSPENDED, &tid);
336 #else
337         thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
338                                      CREATE_SUSPENDED, &tid);
339 #endif
340 #ifdef THREAD_DEBUG
341         g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
342                   tid, thread_handle);
343 #endif
344         g_assert (thread_handle);
345
346         thread->handle=thread_handle;
347         thread->tid=tid;
348
349         thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
350                                                   
351         handle_store(thread);
352
353         ResumeThread (thread_handle);
354 }
355
356 MonoThread *
357 mono_thread_attach (MonoDomain *domain)
358 {
359         MonoThread *thread;
360         HANDLE thread_handle;
361         guint32 tid;
362
363         if ((thread = mono_thread_current ())) {
364                 /* Already attached */
365                 return thread;
366         }
367
368         thread = (MonoThread *)mono_object_new (domain,
369                                                 mono_defaults.thread_class);
370
371         thread_handle = GetCurrentThread ();
372         g_assert (thread_handle);
373
374         tid=GetCurrentThreadId ();
375
376         thread->handle=thread_handle;
377         thread->tid=tid;
378
379 #ifdef THREAD_DEBUG
380         g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
381                   tid, thread_handle);
382 #endif
383
384         handle_store(thread);
385
386 #ifdef THREAD_DEBUG
387         g_message (G_GNUC_PRETTY_FUNCTION
388                    ": (%d) Setting current_object_key to %p",
389                    GetCurrentThreadId (), thread);
390 #endif
391
392         SET_CURRENT_OBJECT (thread);
393         mono_domain_set (domain, TRUE);
394
395         thread_adjust_static_data (thread);
396
397         if (mono_thread_attach_cb) {
398                 mono_thread_attach_cb (tid, &tid);
399         }
400
401         return(thread);
402 }
403
404 void
405 mono_thread_detach (MonoThread *thread)
406 {
407         g_return_if_fail (thread != NULL);
408
409 #ifdef DEBUG
410         g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
411 #endif
412         SET_CURRENT_OBJECT (NULL);
413         
414         thread_cleanup (thread);
415 }
416
417 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
418                                                          MonoObject *start)
419 {
420         MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
421         guint32 (*start_func)(void *);
422         struct StartInfo *start_info;
423         MonoMethod *im;
424         HANDLE thread;
425         guint32 tid;
426         
427         MONO_ARCH_SAVE_REGS;
428
429 #ifdef THREAD_DEBUG
430         g_message(G_GNUC_PRETTY_FUNCTION
431                   ": Trying to start a new thread: this (%p) start (%p)",
432                   this, start);
433 #endif
434         
435         im = mono_get_delegate_invoke (start->vtable->klass);
436         im = mono_marshal_get_delegate_invoke (im);
437         if (mono_thread_callbacks)
438                 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
439         else
440                 start_func = mono_compile_method (im);
441
442         if(start_func==NULL) {
443                 g_warning(G_GNUC_PRETTY_FUNCTION
444                           ": Can't locate start method!");
445                 return(NULL);
446         } else {
447                 /* This is freed in start_wrapper */
448                 start_info = g_new0 (struct StartInfo, 1);
449                 start_info->func = start_func;
450                 start_info->this = delegate;
451                 start_info->obj = this;
452                 start_info->domain = mono_domain_get ();
453
454                 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
455                 if(this->start_notify==NULL) {
456                         g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
457                         return(NULL);
458                 }
459
460 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
461                 thread=GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
462                                     CREATE_SUSPENDED, &tid);
463 #else
464                 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
465                                     CREATE_SUSPENDED, &tid);
466 #endif
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          * give the subthreads a chance to really quit (this is mainly needed
1455          * to get correct user and system times from getrusage/wait/time(1)).
1456          * This could be removed if we avoid pthread_detach() and use pthread_join().
1457          */
1458 #ifndef PLATFORM_WIN32
1459         sched_yield ();
1460 #endif
1461
1462         g_free (wait);
1463 }
1464
1465 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1466 {
1467         MonoThread *thread=(MonoThread *)value;
1468         guint32 self=GPOINTER_TO_UINT (user);
1469         
1470         if(thread->tid!=self) {
1471                 /*TerminateThread (thread->handle, -1);*/
1472         }
1473 }
1474
1475 void mono_thread_abort_all_other_threads (void)
1476 {
1477         guint32 self=GetCurrentThreadId ();
1478
1479         EnterCriticalSection (&threads_mutex);
1480 #ifdef THREAD_DEBUG
1481         g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1482                   mono_g_hash_table_size (threads));
1483         mono_g_hash_table_foreach (threads, print_tids, NULL);
1484 #endif
1485
1486         mono_g_hash_table_foreach (threads, terminate_thread,
1487                                    GUINT_TO_POINTER (self));
1488         
1489         LeaveCriticalSection (&threads_mutex);
1490 }
1491
1492 /*
1493  * mono_thread_push_appdomain_ref:
1494  *
1495  *   Register that the current thread may have references to objects in domain 
1496  * @domain on its stack. Each call to this function should be paired with a 
1497  * call to pop_appdomain_ref.
1498  */
1499 void 
1500 mono_thread_push_appdomain_ref (MonoDomain *domain)
1501 {
1502         MonoThread *thread = mono_thread_current ();
1503
1504         if (thread) {
1505                 /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
1506                 EnterCriticalSection (&threads_mutex);
1507                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1508                 LeaveCriticalSection (&threads_mutex);
1509         }
1510 }
1511
1512 void
1513 mono_thread_pop_appdomain_ref (void)
1514 {
1515         MonoThread *thread = mono_thread_current ();
1516
1517         if (thread) {
1518                 /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1519                 EnterCriticalSection (&threads_mutex);
1520                 /* FIXME: How can the list be empty ? */
1521                 if (thread->appdomain_refs)
1522                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1523                 LeaveCriticalSection (&threads_mutex);
1524         }
1525 }
1526
1527 static gboolean
1528 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1529 {
1530         gboolean res;
1531         EnterCriticalSection (&threads_mutex);
1532         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1533         LeaveCriticalSection (&threads_mutex);
1534         return res;
1535 }
1536
1537 typedef struct abort_appdomain_data {
1538         struct wait_data wait;
1539         MonoDomain *domain;
1540 } abort_appdomain_data;
1541
1542 static void
1543 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1544 {
1545         MonoThread *thread = (MonoThread*)value;
1546         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1547         MonoDomain *domain = data->domain;
1548
1549         if (mono_thread_has_appdomain_ref (thread, domain)) {
1550                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1551                 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1552                 if (handle == NULL)
1553                         return;
1554
1555                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1556
1557                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1558                         data->wait.handles [data->wait.num] = handle;
1559                         data->wait.threads [data->wait.num] = thread;
1560                         data->wait.num++;
1561                 } else {
1562                         /* Just ignore the rest, we can't do anything with
1563                          * them yet
1564                          */
1565                 }
1566         }
1567 }
1568
1569 /*
1570  * mono_threads_abort_appdomain_threads:
1571  *
1572  *   Abort threads which has references to the given appdomain.
1573  */
1574 gboolean
1575 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1576 {
1577         abort_appdomain_data user_data;
1578         guint32 start_time;
1579
1580         /* printf ("ABORT BEGIN.\n"); */
1581
1582         start_time = GetTickCount ();
1583         do {
1584                 EnterCriticalSection (&threads_mutex);
1585
1586                 user_data.domain = domain;
1587                 user_data.wait.num = 0;
1588                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1589                 LeaveCriticalSection (&threads_mutex);
1590
1591                 if (user_data.wait.num > 0)
1592                         wait_for_tids (&user_data.wait, timeout);
1593
1594                 /* Update remaining time */
1595                 timeout -= GetTickCount () - start_time;
1596                 start_time = GetTickCount ();
1597
1598                 if (timeout < 0)
1599                         return FALSE;
1600         }
1601         while (user_data.wait.num > 0);
1602
1603         /* printf ("ABORT DONE.\n"); */
1604
1605         return TRUE;
1606 }
1607
1608 /*
1609  * mono_thread_get_pending_exception:
1610  *
1611  *   Return an exception which needs to be raised when leaving a catch clause.
1612  * This is used for undeniable exception propagation.
1613  */
1614 MonoException*
1615 mono_thread_get_pending_exception (void)
1616 {
1617         MonoThread *thread = mono_thread_current ();
1618
1619         MONO_ARCH_SAVE_REGS;
1620
1621         if (thread && thread->abort_exc) {
1622                 /*
1623                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
1624                  * exception if the thread no longer references a dying appdomain.
1625                  */
1626                 thread->abort_exc->trace_ips = NULL;
1627                 thread->abort_exc->stack_trace = NULL;
1628                 return thread->abort_exc;
1629         }
1630
1631         return NULL;
1632 }
1633
1634 #define NUM_STATIC_DATA_IDX 8
1635 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1636         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1637 };
1638
1639
1640 /*
1641  *  mono_alloc_static_data
1642  *
1643  *   Allocate memory blocks for storing threads or context static data
1644  */
1645 static void 
1646 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1647 {
1648         guint idx = (offset >> 24) - 1;
1649         int i;
1650
1651         gpointer* static_data = *static_data_ptr;
1652         if (!static_data) {
1653 #if HAVE_BOEHM_GC
1654                 static_data = GC_MALLOC (static_data_size [0]);
1655 #else
1656                 static_data = g_malloc0 (static_data_size [0]);
1657 #endif
1658                 *static_data_ptr = static_data;
1659                 static_data [0] = static_data;
1660         }
1661         
1662         for (i = 1; i < idx; ++i) {
1663                 if (static_data [i])
1664                         continue;
1665 #if HAVE_BOEHM_GC
1666                 static_data [i] = GC_MALLOC (static_data_size [i]);
1667 #else
1668                 static_data [i] = g_malloc0 (static_data_size [i]);
1669 #endif
1670         }
1671 }
1672
1673 /*
1674  *  mono_init_static_data_info
1675  *
1676  *   Initializes static data counters
1677  */
1678 static void mono_init_static_data_info (StaticDataInfo *static_data)
1679 {
1680         static_data->idx = 0;
1681         static_data->offset = 0;
1682 }
1683
1684 /*
1685  *  mono_alloc_static_data_slot
1686  *
1687  *   Generates an offset for static data. static_data contains the counters
1688  *  used to generate it.
1689  */
1690 static guint32
1691 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1692 {
1693         guint32 offset;
1694
1695         if (!static_data->idx && !static_data->offset) {
1696                 /* 
1697                  * we use the first chunk of the first allocation also as
1698                  * an array for the rest of the data 
1699                  */
1700                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1701         }
1702         static_data->offset += align - 1;
1703         static_data->offset &= ~(align - 1);
1704         if (static_data->offset + size >= static_data_size [static_data->idx]) {
1705                 static_data->idx ++;
1706                 g_assert (size <= static_data_size [static_data->idx]);
1707                 /* 
1708                  * massive unloading and reloading of domains with thread-static
1709                  * data may eventually exceed the allocated storage...
1710                  * Need to check what the MS runtime does in that case.
1711                  * Note that for each appdomain, we need to allocate a separate
1712                  * thread data slot for security reasons. We could keep track
1713                  * of the slots per-domain and when the domain is unloaded
1714                  * out the slots on a sort of free list.
1715                  */
1716                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1717                 static_data->offset = 0;
1718         }
1719         offset = static_data->offset | ((static_data->idx + 1) << 24);
1720         static_data->offset += size;
1721         return offset;
1722 }
1723
1724 /* 
1725  * ensure thread static fields already allocated are valid for thread
1726  * This function is called when a thread is created or on thread attach.
1727  */
1728 static void
1729 thread_adjust_static_data (MonoThread *thread)
1730 {
1731         guint32 offset;
1732
1733         EnterCriticalSection (&threads_mutex);
1734         if (thread_static_info.offset || thread_static_info.idx > 0) {
1735                 /* get the current allocated size */
1736                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1737                 mono_alloc_static_data (&(thread->static_data), offset);
1738         }
1739         LeaveCriticalSection (&threads_mutex);
1740 }
1741
1742 static void 
1743 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1744 {
1745         MonoThread *thread = value;
1746         guint32 offset = GPOINTER_TO_UINT (user);
1747         
1748         mono_alloc_static_data (&(thread->static_data), offset);
1749 }
1750
1751 /*
1752  * The offset for a special static variable is composed of three parts:
1753  * a bit that indicates the type of static data (0:thread, 1:context),
1754  * an index in the array of chunks of memory for the thread (thread->static_data)
1755  * and an offset in that chunk of mem. This allows allocating less memory in the 
1756  * common case.
1757  */
1758
1759 guint32
1760 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1761 {
1762         guint32 offset;
1763         if (static_type == SPECIAL_STATIC_THREAD)
1764         {
1765                 EnterCriticalSection (&threads_mutex);
1766                 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1767                 /* This can be called during startup */
1768                 if (threads != NULL)
1769                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1770                 LeaveCriticalSection (&threads_mutex);
1771         }
1772         else
1773         {
1774                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1775                 EnterCriticalSection (&contexts_mutex);
1776                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1777                 LeaveCriticalSection (&contexts_mutex);
1778                 offset |= 0x80000000;   /* Set the high bit to indicate context static data */
1779         }
1780         return offset;
1781 }
1782
1783 gpointer
1784 mono_get_special_static_data (guint32 offset)
1785 {
1786         /* The high bit means either thread (0) or static (1) data. */
1787
1788         guint32 static_type = (offset & 0x80000000);
1789         int idx;
1790
1791         offset &= 0x7fffffff;
1792         idx = (offset >> 24) - 1;
1793
1794         if (static_type == 0)
1795         {
1796                 MonoThread *thread = mono_thread_current ();
1797                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1798         }
1799         else
1800         {
1801                 /* Allocate static data block under demand, since we don't have a list
1802                 // of contexts
1803                 */
1804                 MonoAppContext *context = mono_context_get ();
1805                 if (!context->static_data || !context->static_data [idx]) {
1806                         EnterCriticalSection (&contexts_mutex);
1807                         mono_alloc_static_data (&(context->static_data), offset);
1808                         LeaveCriticalSection (&contexts_mutex);
1809                 }
1810                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
1811         }
1812 }
1813
1814 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1815 {
1816         MonoThread *thread=(MonoThread *)value;
1817         guint32 self=GPOINTER_TO_UINT (user);
1818
1819 #ifdef LIBGC_DEBUG
1820         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1821 #endif
1822         
1823         if(thread->tid==self)
1824                 return;
1825
1826         SuspendThread (thread->handle);
1827 }
1828
1829 void mono_gc_stop_world (void)
1830 {
1831         guint32 self=GetCurrentThreadId ();
1832
1833 #ifdef LIBGC_DEBUG
1834         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1835 #endif
1836
1837         EnterCriticalSection (&threads_mutex);
1838
1839         if (threads != NULL)
1840                 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1841         
1842         LeaveCriticalSection (&threads_mutex);
1843 }
1844
1845 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1846 {
1847         MonoThread *thread=(MonoThread *)value;
1848         guint32 self=GPOINTER_TO_UINT (user);
1849         
1850 #ifdef LIBGC_DEBUG
1851         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1852 #endif
1853         
1854         if(thread->tid==self)
1855                 return;
1856
1857         ResumeThread (thread->handle);
1858 }
1859
1860 void mono_gc_start_world (void)
1861 {
1862         guint32 self=GetCurrentThreadId ();
1863
1864 #ifdef LIBGC_DEBUG
1865         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1866 #endif
1867
1868         EnterCriticalSection (&threads_mutex);
1869
1870         if (threads != NULL)
1871                 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1872         
1873         LeaveCriticalSection (&threads_mutex);
1874 }
1875
1876
1877 static guint32 dummy_apc (gpointer param)
1878 {
1879         return 0;
1880 }
1881
1882 /*
1883  * mono_thread_execute_interruption
1884  * 
1885  * Performs the operation that the requested thread state requires (abort,
1886  * suspend or stop)
1887  */
1888 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1889 {
1890         mono_monitor_enter (thread->synch_lock);
1891         
1892         if (thread->interruption_requested) {
1893                 /* this will consume pending APC calls */
1894                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1895                 EnterCriticalSection (&interruption_mutex);
1896                 thread_interruption_requested--;
1897                 LeaveCriticalSection (&interruption_mutex);
1898                 thread->interruption_requested = FALSE;
1899         }
1900
1901         if ((thread->state & ThreadState_AbortRequested) != 0) {
1902                 thread->abort_exc = mono_get_exception_thread_abort ();
1903                 mono_monitor_exit (thread->synch_lock);
1904                 return thread->abort_exc;
1905         }
1906         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1907                 thread->state &= ~ThreadState_SuspendRequested;
1908                 thread->state |= ThreadState_Suspended;
1909                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1910                 mono_monitor_exit (thread->synch_lock);
1911                 
1912                 WaitForSingleObject (thread->suspend_event, INFINITE);
1913                 
1914                 mono_monitor_enter (thread->synch_lock);
1915                 CloseHandle (thread->suspend_event);
1916                 thread->suspend_event = NULL;
1917                 thread->state &= ~ThreadState_Suspended;
1918         
1919                 /* The thread that requested the resume will have replaced this event
1920              * and will be waiting for it
1921                  */
1922                 SetEvent (thread->resume_event);
1923                 mono_monitor_exit (thread->synch_lock);
1924                 return NULL;
1925         }
1926         else if ((thread->state & ThreadState_StopRequested) != 0) {
1927                 /* FIXME: do this through the JIT? */
1928                 mono_monitor_exit (thread->synch_lock);
1929                 ExitThread (-1);
1930                 return NULL;
1931         }
1932         
1933         mono_monitor_exit (thread->synch_lock);
1934         return NULL;
1935 }
1936
1937 /*
1938  * mono_thread_request_interruption
1939  *
1940  * A signal handler can call this method to request the interruption of a
1941  * thread. The result of the interruption will depend on the current state of
1942  * the thread. If the result is an exception that needs to be throw, it is 
1943  * provided as return value.
1944  */
1945 MonoException* mono_thread_request_interruption (gboolean running_managed)
1946 {
1947         MonoThread *thread = mono_thread_current ();
1948
1949         /* The thread may already be stopping */
1950         if (thread == NULL) 
1951                 return NULL;
1952         
1953         mono_monitor_enter (thread->synch_lock);
1954         
1955         if (thread->interruption_requested) {
1956                 mono_monitor_exit (thread->synch_lock);
1957                 return NULL;
1958         }
1959
1960         if (!running_managed) {
1961                 /* Can't stop while in unmanaged code. Increase the global interruption
1962                    request count. When exiting the unmanaged method the count will be
1963                    checked and the thread will be interrupted. */
1964                 
1965                 EnterCriticalSection (&interruption_mutex);
1966                 thread_interruption_requested++;
1967                 LeaveCriticalSection (&interruption_mutex);
1968                 
1969                 thread->interruption_requested = TRUE;
1970                 mono_monitor_exit (thread->synch_lock);
1971                 
1972                 /* this will awake the thread if it is in WaitForSingleObject 
1973                or similar */
1974                 QueueUserAPC (dummy_apc, thread->handle, NULL);
1975                 
1976                 return NULL;
1977         }
1978         else {
1979                 mono_monitor_exit (thread->synch_lock);
1980                 return mono_thread_execute_interruption (thread);
1981         }
1982 }
1983
1984 gboolean mono_thread_interruption_requested ()
1985 {
1986         if (thread_interruption_requested) {
1987                 MonoThread *thread = mono_thread_current ();
1988                 /* The thread may already be stopping */
1989                 if (thread != NULL) 
1990                         return (thread->interruption_requested);
1991         }
1992         return FALSE;
1993 }
1994
1995 /*
1996  * Performs the interruption of the current thread, if one has been requested.
1997  */
1998 void mono_thread_interruption_checkpoint ()
1999 {
2000         MonoThread *thread = mono_thread_current ();
2001         
2002         /* The thread may already be stopping */
2003         if (thread == NULL) 
2004                 return;
2005         
2006         if (thread->interruption_requested) {
2007                 MonoException* exc = mono_thread_execute_interruption (thread);
2008                 if (exc) mono_raise_exception (exc);
2009         }
2010 }
2011
2012 /*
2013  * Returns the address of a flag that will be non-zero if an interruption has
2014  * been requested for a thread. The thread to interrupt may not be the current
2015  * thread, so an additional call to mono_thread_interruption_requested() or
2016  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2017  * zero.
2018  */
2019 gint32* mono_thread_interruption_request_flag ()
2020 {
2021         return &thread_interruption_requested;
2022 }
2023
2024 #ifdef WITH_INCLUDED_LIBGC
2025
2026 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2027 {
2028         MonoThread *thread=(MonoThread *)value;
2029         guint32 *selfp=(guint32 *)user, self = *selfp;
2030
2031 #ifdef LIBGC_DEBUG
2032         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2033 #endif
2034         
2035         if(thread->tid==self) {
2036 #ifdef LIBGC_DEBUG
2037                 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2038 #endif
2039                 GC_push_all_stack (selfp, thread->stack_ptr);
2040                 return;
2041         }
2042
2043 #ifdef PLATFORM_WIN32
2044         GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2045 #else
2046         mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2047 #endif
2048 }
2049
2050 void mono_gc_push_all_stacks (void)
2051 {
2052         guint32 self=GetCurrentThreadId ();
2053
2054 #ifdef LIBGC_DEBUG
2055         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2056 #endif
2057
2058         EnterCriticalSection (&threads_mutex);
2059
2060         if (threads != NULL)
2061                 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2062         
2063         LeaveCriticalSection (&threads_mutex);
2064 }
2065
2066 #endif /* WITH_INCLUDED_LIBGC */