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