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