2004-12-29 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 /* 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                 
890         MONO_ARCH_SAVE_REGS;
891
892         numhandles = mono_array_length(mono_handles);
893         handles = g_new0(HANDLE, numhandles);
894
895         if (wait_handle_os_handle_field == 0) {
896                 /* Get the field os_handle which will contain the actual handle */
897                 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");   
898                 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
899         }
900                 
901         for(i = 0; i < numhandles; i++) {       
902                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);              
903                 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
904         }
905         
906         if(ms== -1) {
907                 ms=INFINITE;
908         }
909         
910         ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
911
912         g_free(handles);
913
914         if(ret==WAIT_FAILED) {
915 #ifdef THREAD_WAIT_DEBUG
916                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
917                           GetCurrentThreadId ());
918 #endif
919                 return(FALSE);
920         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
921                 /* Do we want to try again if we get
922                  * WAIT_IO_COMPLETION? The documentation for
923                  * WaitHandle doesn't give any clues.  (We'd have to
924                  * fiddle with the timeout if we retry.)
925                  */
926 #ifdef THREAD_WAIT_DEBUG
927                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
928                           GetCurrentThreadId ());
929 #endif
930                 return(FALSE);
931         }
932         
933         return(TRUE);
934 }
935
936 /* FIXME: exitContext isnt documented */
937 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
938 {
939         HANDLE *handles;
940         guint32 numhandles;
941         guint32 ret;
942         guint32 i;
943         MonoObject *waitHandle;
944         MonoClass *klass;
945                 
946         MONO_ARCH_SAVE_REGS;
947
948         numhandles = mono_array_length(mono_handles);
949         handles = g_new0(HANDLE, numhandles);
950
951         if (wait_handle_os_handle_field == 0) {
952                 /* Get the field os_handle which will contain the actual handle */
953                 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");   
954                 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
955         }
956                 
957         for(i = 0; i < numhandles; i++) {       
958                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);              
959                 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
960         }
961         
962         if(ms== -1) {
963                 ms=INFINITE;
964         }
965
966         ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
967
968         g_free(handles);
969
970 #ifdef THREAD_WAIT_DEBUG
971         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
972                   GetCurrentThreadId (), ret);
973 #endif
974
975         /*
976          * These need to be here.  See MSDN dos on WaitForMultipleObjects.
977          */
978         if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
979                 return ret - WAIT_OBJECT_0;
980         }
981         else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
982                 return ret - WAIT_ABANDONED_0;
983         }
984         else {
985                 return ret;
986         }
987 }
988
989 /* FIXME: exitContext isnt documented */
990 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
991 {
992         guint32 ret;
993         
994         MONO_ARCH_SAVE_REGS;
995
996 #ifdef THREAD_WAIT_DEBUG
997         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
998                   GetCurrentThreadId (), handle, ms);
999 #endif
1000         
1001         if(ms== -1) {
1002                 ms=INFINITE;
1003         }
1004         
1005         ret=WaitForSingleObjectEx (handle, ms, TRUE);
1006
1007         if(ret==WAIT_FAILED) {
1008 #ifdef THREAD_WAIT_DEBUG
1009                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1010                           GetCurrentThreadId ());
1011 #endif
1012                 return(FALSE);
1013         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1014                 /* Do we want to try again if we get
1015                  * WAIT_IO_COMPLETION? The documentation for
1016                  * WaitHandle doesn't give any clues.  (We'd have to
1017                  * fiddle with the timeout if we retry.)
1018                  */
1019 #ifdef THREAD_WAIT_DEBUG
1020                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1021                           GetCurrentThreadId ());
1022 #endif
1023                 return(FALSE);
1024         }
1025         
1026         return(TRUE);
1027 }
1028
1029 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1030
1031         HANDLE mutex;
1032         
1033         MONO_ARCH_SAVE_REGS;
1034    
1035         *created = TRUE;
1036         
1037         if (name == NULL) {
1038                 mutex = CreateMutex (NULL, owned, NULL);
1039         } else {
1040                 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1041                 
1042                 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1043                         *created = FALSE;
1044                 }
1045         }
1046
1047         return(mutex);
1048 }                                                                   
1049
1050 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) { 
1051         MONO_ARCH_SAVE_REGS;
1052
1053         ReleaseMutex(handle);
1054 }
1055
1056 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1057         MONO_ARCH_SAVE_REGS;
1058
1059         return(CreateEvent (NULL, manual, initial,
1060                             name==NULL?NULL:mono_string_chars (name)));
1061 }
1062
1063 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1064         MONO_ARCH_SAVE_REGS;
1065
1066         return (SetEvent(handle));
1067 }
1068
1069 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1070         MONO_ARCH_SAVE_REGS;
1071
1072         return (ResetEvent(handle));
1073 }
1074
1075 void
1076 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1077         MONO_ARCH_SAVE_REGS;
1078
1079         CloseHandle (handle);
1080 }
1081
1082 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1083 {
1084         MONO_ARCH_SAVE_REGS;
1085
1086         return InterlockedIncrement (location);
1087 }
1088
1089 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1090 {
1091         gint64 ret;
1092
1093         MONO_ARCH_SAVE_REGS;
1094
1095         EnterCriticalSection(&interlocked_mutex);
1096
1097         ret = ++ *location;
1098         
1099         LeaveCriticalSection(&interlocked_mutex);
1100
1101         
1102         return ret;
1103 }
1104
1105 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1106 {
1107         MONO_ARCH_SAVE_REGS;
1108
1109         return InterlockedDecrement(location);
1110 }
1111
1112 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1113 {
1114         gint64 ret;
1115
1116         MONO_ARCH_SAVE_REGS;
1117
1118         EnterCriticalSection(&interlocked_mutex);
1119
1120         ret = -- *location;
1121         
1122         LeaveCriticalSection(&interlocked_mutex);
1123
1124         return ret;
1125 }
1126
1127 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1128 {
1129         MONO_ARCH_SAVE_REGS;
1130
1131         return InterlockedExchange(location1, value);
1132 }
1133
1134 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1135 {
1136         MONO_ARCH_SAVE_REGS;
1137
1138         return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1139 }
1140
1141 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1142 {
1143         IntFloatUnion val, ret;
1144
1145         MONO_ARCH_SAVE_REGS;
1146
1147         val.fval = value;
1148         ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1149
1150         return ret.fval;
1151 }
1152
1153 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1154 {
1155         MONO_ARCH_SAVE_REGS;
1156
1157         return InterlockedCompareExchange(location1, value, comparand);
1158 }
1159
1160 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1161 {
1162         MONO_ARCH_SAVE_REGS;
1163
1164         return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1165 }
1166
1167 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1168 {
1169         IntFloatUnion val, ret, cmp;
1170
1171         MONO_ARCH_SAVE_REGS;
1172
1173         val.fval = value;
1174         cmp.fval = comparand;
1175         ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1176
1177         return ret.fval;
1178 }
1179
1180 int  
1181 mono_thread_get_abort_signal (void)
1182 {
1183 #ifdef __MINGW32__
1184         return -1;
1185 #else
1186 #ifndef SIGRTMIN
1187         return SIGUSR1;
1188 #else
1189         return SIGRTMIN;
1190 #endif
1191 #endif /* __MINGW32__ */
1192 }
1193
1194 #ifdef __MINGW32__
1195 static guint32 interruption_request_apc (gpointer param)
1196 {
1197         MonoException* exc = mono_thread_request_interruption (FALSE);
1198         if (exc) mono_raise_exception (exc);
1199         return 0;
1200 }
1201 #endif /* __MINGW32__ */
1202
1203 /*
1204  * signal_thread_state_change
1205  *
1206  * Tells the thread that his state has changed and it has to enter the new
1207  * state as soon as possible.
1208  */
1209 static void signal_thread_state_change (MonoThread *thread)
1210 {
1211 #ifdef __MINGW32__
1212         QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1213 #else
1214         /* fixme: store the state somewhere */
1215 #ifdef PTHREAD_POINTER_ID
1216         pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1217 #else
1218         pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1219 #endif
1220 #endif /* __MINGW32__ */
1221 }
1222
1223 void
1224 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1225 {
1226         MONO_ARCH_SAVE_REGS;
1227
1228         mono_monitor_enter (thread->synch_lock);
1229
1230         if ((thread->state & ThreadState_AbortRequested) != 0 || 
1231                 (thread->state & ThreadState_StopRequested) != 0) 
1232         {
1233                 mono_monitor_exit (thread->synch_lock);
1234                 return;
1235         }
1236
1237         thread->state |= ThreadState_AbortRequested;
1238         thread->abort_state = state;
1239         thread->abort_exc = NULL;
1240
1241         mono_monitor_exit (thread->synch_lock);
1242
1243 #ifdef THREAD_DEBUG
1244         g_message (G_GNUC_PRETTY_FUNCTION
1245                    ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1246                    thread, thread->tid);
1247 #endif
1248         
1249         /* Make sure the thread is awake */
1250         ves_icall_System_Threading_Thread_Resume (thread);
1251         
1252         signal_thread_state_change (thread);
1253 }
1254
1255 void
1256 ves_icall_System_Threading_Thread_ResetAbort (void)
1257 {
1258         MonoThread *thread = mono_thread_current ();
1259
1260         MONO_ARCH_SAVE_REGS;
1261         
1262         mono_monitor_enter (thread->synch_lock);
1263         
1264         thread->state &= ~ThreadState_AbortRequested;
1265         
1266         if (!thread->abort_exc) {
1267                 const char *msg = "Unable to reset abort because no abort was requested";
1268                 mono_monitor_exit (thread->synch_lock);
1269                 mono_raise_exception (mono_get_exception_thread_state (msg));
1270         } else {
1271                 thread->abort_exc = NULL;
1272                 thread->abort_state = NULL;
1273         }
1274         
1275         mono_monitor_exit (thread->synch_lock);
1276 }
1277
1278 void
1279 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1280 {
1281         MONO_ARCH_SAVE_REGS;
1282
1283         mono_monitor_enter (thread->synch_lock);
1284
1285         if ((thread->state & ThreadState_Suspended) != 0 || 
1286                 (thread->state & ThreadState_SuspendRequested) != 0 ||
1287                 (thread->state & ThreadState_StopRequested) != 0) 
1288         {
1289                 mono_monitor_exit (thread->synch_lock);
1290                 return;
1291         }
1292         
1293         thread->state |= ThreadState_SuspendRequested;
1294         mono_monitor_exit (thread->synch_lock);
1295
1296         signal_thread_state_change (thread);
1297 }
1298
1299 void
1300 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1301 {
1302         MONO_ARCH_SAVE_REGS;
1303
1304         mono_monitor_enter (thread->synch_lock);
1305
1306         if ((thread->state & ThreadState_SuspendRequested) != 0) {
1307                 thread->state &= ~ThreadState_SuspendRequested;
1308                 mono_monitor_exit (thread->synch_lock);
1309                 return;
1310         }
1311                 
1312         if ((thread->state & ThreadState_Suspended) == 0) 
1313         {
1314                 mono_monitor_exit (thread->synch_lock);
1315                 return;
1316         }
1317         
1318         thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1319         
1320         /* Awake the thread */
1321         SetEvent (thread->suspend_event);
1322
1323         mono_monitor_exit (thread->synch_lock);
1324
1325         /* Wait for the thread to awake */
1326         WaitForSingleObject (thread->resume_event, INFINITE);
1327         CloseHandle (thread->resume_event);
1328         thread->resume_event = NULL;
1329 }
1330
1331 static gboolean
1332 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1333 {
1334         if (managed)
1335                 return TRUE;
1336
1337         if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1338                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1339                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH) 
1340         {
1341                 *((gboolean*)data) = TRUE;
1342                 return TRUE;
1343         }
1344         return FALSE;
1345 }
1346
1347 static gboolean 
1348 is_running_protected_wrapper (void)
1349 {
1350         gboolean found = FALSE;
1351         mono_stack_walk (find_wrapper, &found);
1352         return found;
1353 }
1354
1355 void mono_thread_stop (MonoThread *thread)
1356 {
1357         mono_monitor_enter (thread->synch_lock);
1358
1359         if ((thread->state & ThreadState_StopRequested) != 0 ||
1360                 (thread->state & ThreadState_Stopped) != 0)
1361         {
1362                 mono_monitor_exit (thread->synch_lock);
1363                 return;
1364         }
1365         
1366         /* Make sure the thread is awake */
1367         ves_icall_System_Threading_Thread_Resume (thread);
1368         
1369         thread->state |= ThreadState_StopRequested;
1370         thread->state &= ~ThreadState_AbortRequested;
1371         
1372         mono_monitor_exit (thread->synch_lock);
1373         
1374         signal_thread_state_change (thread);
1375 }
1376
1377 gint8
1378 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1379 {
1380         return *((volatile gint8 *) (ptr));
1381 }
1382
1383 gint16
1384 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1385 {
1386         return *((volatile gint16 *) (ptr));
1387 }
1388
1389 gint32
1390 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1391 {
1392         return *((volatile gint32 *) (ptr));
1393 }
1394
1395 gint64
1396 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1397 {
1398         return *((volatile gint64 *) (ptr));
1399 }
1400
1401 void *
1402 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1403 {
1404         return (void *)  *((volatile void **) ptr);
1405 }
1406
1407 void
1408 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1409 {
1410         *((volatile gint8 *) ptr) = value;
1411 }
1412
1413 void
1414 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1415 {
1416         *((volatile gint16 *) ptr) = value;
1417 }
1418
1419 void
1420 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1421 {
1422         *((volatile gint32 *) ptr) = value;
1423 }
1424
1425 void
1426 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1427 {
1428         *((volatile gint64 *) ptr) = value;
1429 }
1430
1431 void
1432 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1433 {
1434         *((volatile void **) ptr) = value;
1435 }
1436
1437 void mono_thread_init (MonoThreadStartCB start_cb,
1438                        MonoThreadAttachCB attach_cb)
1439 {
1440         InitializeCriticalSection(&threads_mutex);
1441         InitializeCriticalSection(&interlocked_mutex);
1442         InitializeCriticalSection(&contexts_mutex);
1443         InitializeCriticalSection(&interruption_mutex);
1444         
1445         mono_init_static_data_info (&thread_static_info);
1446         mono_init_static_data_info (&context_static_info);
1447
1448         current_object_key=TlsAlloc();
1449 #ifdef THREAD_DEBUG
1450         g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1451                    current_object_key);
1452 #endif
1453
1454         mono_thread_start_cb = start_cb;
1455         mono_thread_attach_cb = attach_cb;
1456
1457         slothash_key=TlsAlloc();
1458
1459         /* Get a pseudo handle to the current process.  This is just a
1460          * kludge so that wapi can build a process handle if needed.
1461          * As a pseudo handle is returned, we don't need to clean
1462          * anything up.
1463          */
1464         GetCurrentProcess ();
1465 }
1466
1467 void
1468 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1469 {
1470         mono_thread_cleanup = func;
1471 }
1472
1473 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1474 {
1475         mono_thread_callbacks = callbacks;
1476 }
1477
1478 #ifdef THREAD_DEBUG
1479 static void print_tids (gpointer key, gpointer value, gpointer user)
1480 {
1481         g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1482 }
1483 #endif
1484
1485 struct wait_data 
1486 {
1487         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1488         MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1489         guint32 num;
1490 };
1491
1492 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1493 {
1494         guint32 i, ret;
1495         
1496 #ifdef THREAD_DEBUG
1497         g_message(G_GNUC_PRETTY_FUNCTION
1498                   ": %d threads to wait for in this batch", wait->num);
1499 #endif
1500
1501         ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1502
1503         if(ret==WAIT_FAILED) {
1504                 /* See the comment in build_wait_tids() */
1505 #ifdef THREAD_DEBUG
1506                 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1507 #endif
1508                 return;
1509         }
1510         
1511         for(i=0; i<wait->num; i++)
1512                 CloseHandle (wait->handles[i]);
1513
1514         if (ret == WAIT_TIMEOUT)
1515                 return;
1516
1517         for(i=0; i<wait->num; i++) {
1518                 guint32 tid=wait->threads[i]->tid;
1519                 
1520                 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1521                         /* This thread must have been killed, because
1522                          * it hasn't cleaned itself up. (It's just
1523                          * possible that the thread exited before the
1524                          * parent thread had a chance to store the
1525                          * handle, and now there is another pointer to
1526                          * the already-exited thread stored.  In this
1527                          * case, we'll just get two
1528                          * mono_profiler_thread_end() calls for the
1529                          * same thread.)
1530                          */
1531         
1532 #ifdef THREAD_DEBUG
1533                         g_message (G_GNUC_PRETTY_FUNCTION
1534                                    ": cleaning up after thread %d", tid);
1535 #endif
1536                         thread_cleanup (wait->threads[i]);
1537                 }
1538         }
1539 }
1540
1541 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1542 {
1543         struct wait_data *wait=(struct wait_data *)user;
1544
1545         if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1546                 HANDLE handle;
1547                 MonoThread *thread=(MonoThread *)value;
1548
1549                 /* Ignore background threads, we abort them later */
1550                 if (thread->state & ThreadState_Background)
1551                         return; /* just leave, ignore */
1552                 
1553                 if (mono_gc_is_finalizer_thread (thread))
1554                         return;
1555
1556                 if (thread == mono_thread_current ())
1557                         return;
1558
1559                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1560                 if (handle == NULL)
1561                         return;
1562                 
1563                 wait->handles[wait->num]=handle;
1564                 wait->threads[wait->num]=thread;
1565                 wait->num++;
1566         } else {
1567                 /* Just ignore the rest, we can't do anything with
1568                  * them yet
1569                  */
1570         }
1571 }
1572
1573 static gboolean
1574 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1575 {
1576         struct wait_data *wait=(struct wait_data *)user;
1577         guint32 self = GetCurrentThreadId ();
1578         MonoThread *thread = (MonoThread *) value;
1579         HANDLE handle;
1580
1581         /* The finalizer thread is not a background thread */
1582         if (thread->tid != self && thread->state & ThreadState_Background) {
1583         
1584                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1585                 if (handle == NULL)
1586                         return FALSE;
1587                 
1588                 wait->handles[wait->num]=thread->handle;
1589                 wait->threads[wait->num]=thread;
1590                 wait->num++;
1591         
1592                 if(thread->state & ThreadState_AbortRequested ||
1593                    thread->state & ThreadState_Aborted) {
1594 #ifdef THREAD_DEBUG
1595                         g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1596 #endif
1597                         return(TRUE);
1598                 }
1599                 
1600 #ifdef THREAD_DEBUG
1601                 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1602 #endif
1603                 mono_thread_stop (thread);
1604                 return TRUE;
1605         }
1606
1607         return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
1608 }
1609
1610 void mono_thread_manage (void)
1611 {
1612         struct wait_data *wait=g_new0 (struct wait_data, 1);
1613         
1614         /* join each thread that's still running */
1615 #ifdef THREAD_DEBUG
1616         g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1617 #endif
1618         
1619         EnterCriticalSection (&threads_mutex);
1620         if(threads==NULL) {
1621 #ifdef THREAD_DEBUG
1622                 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1623 #endif
1624                 LeaveCriticalSection (&threads_mutex);
1625                 return;
1626         }
1627         LeaveCriticalSection (&threads_mutex);
1628         
1629         do {
1630                 EnterCriticalSection (&threads_mutex);
1631 #ifdef THREAD_DEBUG
1632                 g_message(G_GNUC_PRETTY_FUNCTION
1633                           ":There are %d threads to join",
1634                           mono_g_hash_table_size (threads));
1635                 mono_g_hash_table_foreach (threads, print_tids, NULL);
1636 #endif
1637         
1638                 wait->num=0;
1639                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1640                 LeaveCriticalSection (&threads_mutex);
1641                 if(wait->num>0) {
1642                         /* Something to wait for */
1643                         wait_for_tids (wait, INFINITE);
1644                 }
1645         } while(wait->num>0);
1646         
1647         mono_thread_pool_cleanup ();
1648
1649         EnterCriticalSection(&threads_mutex);
1650
1651         /* 
1652          * Remove everything but the finalizer thread and self.
1653          * Also abort all the background threads
1654          * */
1655         wait->num = 0;
1656         mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1657
1658         LeaveCriticalSection(&threads_mutex);
1659
1660         if(wait->num>0) {
1661                 /* Something to wait for */
1662                 wait_for_tids (wait, INFINITE);
1663         }
1664         /* 
1665          * give the subthreads a chance to really quit (this is mainly needed
1666          * to get correct user and system times from getrusage/wait/time(1)).
1667          * This could be removed if we avoid pthread_detach() and use pthread_join().
1668          */
1669 #ifndef PLATFORM_WIN32
1670         sched_yield ();
1671 #endif
1672
1673         g_free (wait);
1674 }
1675
1676 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1677 {
1678         MonoThread *thread=(MonoThread *)value;
1679         guint32 self=GPOINTER_TO_UINT (user);
1680         
1681         if(thread->tid!=self) {
1682                 /*TerminateThread (thread->handle, -1);*/
1683         }
1684 }
1685
1686 void mono_thread_abort_all_other_threads (void)
1687 {
1688         guint32 self=GetCurrentThreadId ();
1689
1690         EnterCriticalSection (&threads_mutex);
1691 #ifdef THREAD_DEBUG
1692         g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1693                   mono_g_hash_table_size (threads));
1694         mono_g_hash_table_foreach (threads, print_tids, NULL);
1695 #endif
1696
1697         mono_g_hash_table_foreach (threads, terminate_thread,
1698                                    GUINT_TO_POINTER (self));
1699         
1700         LeaveCriticalSection (&threads_mutex);
1701 }
1702
1703 /*
1704  * mono_thread_push_appdomain_ref:
1705  *
1706  *   Register that the current thread may have references to objects in domain 
1707  * @domain on its stack. Each call to this function should be paired with a 
1708  * call to pop_appdomain_ref.
1709  */
1710 void 
1711 mono_thread_push_appdomain_ref (MonoDomain *domain)
1712 {
1713         MonoThread *thread = mono_thread_current ();
1714
1715         if (thread) {
1716                 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1717                 EnterCriticalSection (&threads_mutex);
1718                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1719                 LeaveCriticalSection (&threads_mutex);
1720         }
1721 }
1722
1723 void
1724 mono_thread_pop_appdomain_ref (void)
1725 {
1726         MonoThread *thread = mono_thread_current ();
1727
1728         if (thread) {
1729                 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1730                 EnterCriticalSection (&threads_mutex);
1731                 /* FIXME: How can the list be empty ? */
1732                 if (thread->appdomain_refs)
1733                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1734                 LeaveCriticalSection (&threads_mutex);
1735         }
1736 }
1737
1738 gboolean
1739 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1740 {
1741         gboolean res;
1742         EnterCriticalSection (&threads_mutex);
1743         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1744         LeaveCriticalSection (&threads_mutex);
1745         return res;
1746 }
1747
1748 typedef struct abort_appdomain_data {
1749         struct wait_data wait;
1750         MonoDomain *domain;
1751 } abort_appdomain_data;
1752
1753 static void
1754 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1755 {
1756         MonoThread *thread = (MonoThread*)value;
1757         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1758         MonoDomain *domain = data->domain;
1759
1760         if (mono_thread_has_appdomain_ref (thread, domain)) {
1761                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1762                 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1763                 if (handle == NULL)
1764                         return;
1765
1766                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1767
1768                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1769                         data->wait.handles [data->wait.num] = handle;
1770                         data->wait.threads [data->wait.num] = thread;
1771                         data->wait.num++;
1772                 } else {
1773                         /* Just ignore the rest, we can't do anything with
1774                          * them yet
1775                          */
1776                 }
1777         }
1778 }
1779
1780 /*
1781  * mono_threads_abort_appdomain_threads:
1782  *
1783  *   Abort threads which has references to the given appdomain.
1784  */
1785 gboolean
1786 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1787 {
1788         abort_appdomain_data user_data;
1789         guint32 start_time;
1790
1791         /* printf ("ABORT BEGIN.\n"); */
1792
1793         start_time = GetTickCount ();
1794         do {
1795                 EnterCriticalSection (&threads_mutex);
1796
1797                 user_data.domain = domain;
1798                 user_data.wait.num = 0;
1799                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1800                 LeaveCriticalSection (&threads_mutex);
1801
1802                 if (user_data.wait.num > 0)
1803                         wait_for_tids (&user_data.wait, timeout);
1804
1805                 /* Update remaining time */
1806                 timeout -= GetTickCount () - start_time;
1807                 start_time = GetTickCount ();
1808
1809                 if (timeout < 0)
1810                         return FALSE;
1811         }
1812         while (user_data.wait.num > 0);
1813
1814         /* printf ("ABORT DONE.\n"); */
1815
1816         return TRUE;
1817 }
1818
1819 static void
1820 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1821 {
1822         MonoThread *thread = (MonoThread*)value;
1823         MonoDomain *domain = (MonoDomain*)user_data;
1824         int i;
1825
1826         /* No locking needed here */
1827
1828         if (thread->culture_info) {
1829                 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1830                         if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1831                                 thread->culture_info [i] = NULL;
1832                 }
1833         }
1834         if (thread->ui_culture_info) {
1835                 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1836                         if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1837                                 thread->ui_culture_info [i] = NULL;
1838                 }
1839         }
1840 }
1841         
1842 /*
1843  * mono_threads_clear_cached_culture:
1844  *
1845  *   Clear the cached_current_culture from all threads if it is in the
1846  * given appdomain.
1847  */
1848 void
1849 mono_threads_clear_cached_culture (MonoDomain *domain)
1850 {
1851         EnterCriticalSection (&threads_mutex);
1852         mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1853         LeaveCriticalSection (&threads_mutex);
1854 }
1855
1856 /*
1857  * mono_thread_get_pending_exception:
1858  *
1859  *   Return an exception which needs to be raised when leaving a catch clause.
1860  * This is used for undeniable exception propagation.
1861  */
1862 MonoException*
1863 mono_thread_get_pending_exception (void)
1864 {
1865         MonoThread *thread = mono_thread_current ();
1866
1867         MONO_ARCH_SAVE_REGS;
1868
1869         if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1870                 /*
1871                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
1872                  * exception if the thread no longer references a dying appdomain.
1873                  */
1874                 thread->abort_exc->trace_ips = NULL;
1875                 thread->abort_exc->stack_trace = NULL;
1876                 return thread->abort_exc;
1877         }
1878
1879         return NULL;
1880 }
1881
1882 #define NUM_STATIC_DATA_IDX 8
1883 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1884         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1885 };
1886
1887
1888 /*
1889  *  mono_alloc_static_data
1890  *
1891  *   Allocate memory blocks for storing threads or context static data
1892  */
1893 static void 
1894 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1895 {
1896         guint idx = (offset >> 24) - 1;
1897         int i;
1898
1899         gpointer* static_data = *static_data_ptr;
1900         if (!static_data) {
1901 #if HAVE_BOEHM_GC
1902                 static_data = GC_MALLOC (static_data_size [0]);
1903 #else
1904                 static_data = g_malloc0 (static_data_size [0]);
1905 #endif
1906                 *static_data_ptr = static_data;
1907                 static_data [0] = static_data;
1908         }
1909         
1910         for (i = 1; i < idx; ++i) {
1911                 if (static_data [i])
1912                         continue;
1913 #if HAVE_BOEHM_GC
1914                 static_data [i] = GC_MALLOC (static_data_size [i]);
1915 #else
1916                 static_data [i] = g_malloc0 (static_data_size [i]);
1917 #endif
1918         }
1919 }
1920
1921 /*
1922  *  mono_init_static_data_info
1923  *
1924  *   Initializes static data counters
1925  */
1926 static void mono_init_static_data_info (StaticDataInfo *static_data)
1927 {
1928         static_data->idx = 0;
1929         static_data->offset = 0;
1930 }
1931
1932 /*
1933  *  mono_alloc_static_data_slot
1934  *
1935  *   Generates an offset for static data. static_data contains the counters
1936  *  used to generate it.
1937  */
1938 static guint32
1939 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1940 {
1941         guint32 offset;
1942
1943         if (!static_data->idx && !static_data->offset) {
1944                 /* 
1945                  * we use the first chunk of the first allocation also as
1946                  * an array for the rest of the data 
1947                  */
1948                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1949         }
1950         static_data->offset += align - 1;
1951         static_data->offset &= ~(align - 1);
1952         if (static_data->offset + size >= static_data_size [static_data->idx]) {
1953                 static_data->idx ++;
1954                 g_assert (size <= static_data_size [static_data->idx]);
1955                 /* 
1956                  * massive unloading and reloading of domains with thread-static
1957                  * data may eventually exceed the allocated storage...
1958                  * Need to check what the MS runtime does in that case.
1959                  * Note that for each appdomain, we need to allocate a separate
1960                  * thread data slot for security reasons. We could keep track
1961                  * of the slots per-domain and when the domain is unloaded
1962                  * out the slots on a sort of free list.
1963                  */
1964                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1965                 static_data->offset = 0;
1966         }
1967         offset = static_data->offset | ((static_data->idx + 1) << 24);
1968         static_data->offset += size;
1969         return offset;
1970 }
1971
1972 /* 
1973  * ensure thread static fields already allocated are valid for thread
1974  * This function is called when a thread is created or on thread attach.
1975  */
1976 static void
1977 thread_adjust_static_data (MonoThread *thread)
1978 {
1979         guint32 offset;
1980
1981         EnterCriticalSection (&threads_mutex);
1982         if (thread_static_info.offset || thread_static_info.idx > 0) {
1983                 /* get the current allocated size */
1984                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1985                 mono_alloc_static_data (&(thread->static_data), offset);
1986         }
1987         LeaveCriticalSection (&threads_mutex);
1988 }
1989
1990 static void 
1991 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1992 {
1993         MonoThread *thread = value;
1994         guint32 offset = GPOINTER_TO_UINT (user);
1995         
1996         mono_alloc_static_data (&(thread->static_data), offset);
1997 }
1998
1999 /*
2000  * The offset for a special static variable is composed of three parts:
2001  * a bit that indicates the type of static data (0:thread, 1:context),
2002  * an index in the array of chunks of memory for the thread (thread->static_data)
2003  * and an offset in that chunk of mem. This allows allocating less memory in the 
2004  * common case.
2005  */
2006
2007 guint32
2008 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2009 {
2010         guint32 offset;
2011         if (static_type == SPECIAL_STATIC_THREAD)
2012         {
2013                 EnterCriticalSection (&threads_mutex);
2014                 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2015                 /* This can be called during startup */
2016                 if (threads != NULL)
2017                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2018                 LeaveCriticalSection (&threads_mutex);
2019         }
2020         else
2021         {
2022                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2023                 EnterCriticalSection (&contexts_mutex);
2024                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2025                 LeaveCriticalSection (&contexts_mutex);
2026                 offset |= 0x80000000;   /* Set the high bit to indicate context static data */
2027         }
2028         return offset;
2029 }
2030
2031 gpointer
2032 mono_get_special_static_data (guint32 offset)
2033 {
2034         /* The high bit means either thread (0) or static (1) data. */
2035
2036         guint32 static_type = (offset & 0x80000000);
2037         int idx;
2038
2039         offset &= 0x7fffffff;
2040         idx = (offset >> 24) - 1;
2041
2042         if (static_type == 0)
2043         {
2044                 MonoThread *thread = mono_thread_current ();
2045                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2046         }
2047         else
2048         {
2049                 /* Allocate static data block under demand, since we don't have a list
2050                 // of contexts
2051                 */
2052                 MonoAppContext *context = mono_context_get ();
2053                 if (!context->static_data || !context->static_data [idx]) {
2054                         EnterCriticalSection (&contexts_mutex);
2055                         mono_alloc_static_data (&(context->static_data), offset);
2056                         LeaveCriticalSection (&contexts_mutex);
2057                 }
2058                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
2059         }
2060 }
2061
2062 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2063 {
2064         MonoThread *thread=(MonoThread *)value;
2065         guint32 self=GPOINTER_TO_UINT (user);
2066
2067 #ifdef LIBGC_DEBUG
2068         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2069 #endif
2070         
2071         if(thread->tid==self)
2072                 return;
2073
2074         SuspendThread (thread->handle);
2075 }
2076
2077 void mono_gc_stop_world (void)
2078 {
2079         guint32 self=GetCurrentThreadId ();
2080
2081 #ifdef LIBGC_DEBUG
2082         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2083 #endif
2084
2085         EnterCriticalSection (&threads_mutex);
2086
2087         if (threads != NULL)
2088                 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2089         
2090         LeaveCriticalSection (&threads_mutex);
2091 }
2092
2093 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2094 {
2095         MonoThread *thread=(MonoThread *)value;
2096         guint32 self=GPOINTER_TO_UINT (user);
2097         
2098 #ifdef LIBGC_DEBUG
2099         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2100 #endif
2101         
2102         if(thread->tid==self)
2103                 return;
2104
2105         ResumeThread (thread->handle);
2106 }
2107
2108 void mono_gc_start_world (void)
2109 {
2110         guint32 self=GetCurrentThreadId ();
2111
2112 #ifdef LIBGC_DEBUG
2113         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2114 #endif
2115
2116         EnterCriticalSection (&threads_mutex);
2117
2118         if (threads != NULL)
2119                 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2120         
2121         LeaveCriticalSection (&threads_mutex);
2122 }
2123
2124
2125 static guint32 dummy_apc (gpointer param)
2126 {
2127         return 0;
2128 }
2129
2130 /*
2131  * mono_thread_execute_interruption
2132  * 
2133  * Performs the operation that the requested thread state requires (abort,
2134  * suspend or stop)
2135  */
2136 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2137 {
2138         mono_monitor_enter (thread->synch_lock);
2139
2140         if (thread->interruption_requested) {
2141                 /* this will consume pending APC calls */
2142                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2143                 EnterCriticalSection (&interruption_mutex);
2144                 thread_interruption_requested--;
2145                 LeaveCriticalSection (&interruption_mutex);
2146                 thread->interruption_requested = FALSE;
2147         }
2148
2149         if ((thread->state & ThreadState_AbortRequested) != 0) {
2150                 if (thread->abort_exc == NULL)
2151                         thread->abort_exc = mono_get_exception_thread_abort ();
2152                 mono_monitor_exit (thread->synch_lock);
2153                 return thread->abort_exc;
2154         }
2155         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2156                 thread->state &= ~ThreadState_SuspendRequested;
2157                 thread->state |= ThreadState_Suspended;
2158                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2159                 mono_monitor_exit (thread->synch_lock);
2160                 
2161                 WaitForSingleObject (thread->suspend_event, INFINITE);
2162                 
2163                 mono_monitor_enter (thread->synch_lock);
2164                 CloseHandle (thread->suspend_event);
2165                 thread->suspend_event = NULL;
2166                 thread->state &= ~ThreadState_Suspended;
2167         
2168                 /* The thread that requested the resume will have replaced this event
2169              * and will be waiting for it
2170                  */
2171                 SetEvent (thread->resume_event);
2172                 mono_monitor_exit (thread->synch_lock);
2173                 return NULL;
2174         }
2175         else if ((thread->state & ThreadState_StopRequested) != 0) {
2176                 /* FIXME: do this through the JIT? */
2177                 mono_monitor_exit (thread->synch_lock);
2178                 mono_thread_exit ();
2179                 return NULL;
2180         }
2181         
2182         mono_monitor_exit (thread->synch_lock);
2183         return NULL;
2184 }
2185
2186 /*
2187  * mono_thread_request_interruption
2188  *
2189  * A signal handler can call this method to request the interruption of a
2190  * thread. The result of the interruption will depend on the current state of
2191  * the thread. If the result is an exception that needs to be throw, it is 
2192  * provided as return value.
2193  */
2194 MonoException* mono_thread_request_interruption (gboolean running_managed)
2195 {
2196         MonoThread *thread = mono_thread_current ();
2197
2198         /* The thread may already be stopping */
2199         if (thread == NULL) 
2200                 return NULL;
2201         
2202         mono_monitor_enter (thread->synch_lock);
2203         
2204         if (thread->interruption_requested) {
2205                 mono_monitor_exit (thread->synch_lock);
2206                 return NULL;
2207         }
2208
2209         if (!running_managed || is_running_protected_wrapper ()) {
2210                 /* Can't stop while in unmanaged code. Increase the global interruption
2211                    request count. When exiting the unmanaged method the count will be
2212                    checked and the thread will be interrupted. */
2213                 
2214                 EnterCriticalSection (&interruption_mutex);
2215                 thread_interruption_requested++;
2216                 LeaveCriticalSection (&interruption_mutex);
2217                 
2218                 thread->interruption_requested = TRUE;
2219                 mono_monitor_exit (thread->synch_lock);
2220                 
2221                 /* this will awake the thread if it is in WaitForSingleObject 
2222                or similar */
2223                 QueueUserAPC (dummy_apc, thread->handle, NULL);
2224                 
2225                 return NULL;
2226         }
2227         else {
2228                 mono_monitor_exit (thread->synch_lock);
2229                 return mono_thread_execute_interruption (thread);
2230         }
2231 }
2232
2233 gboolean mono_thread_interruption_requested ()
2234 {
2235         if (thread_interruption_requested) {
2236                 MonoThread *thread = mono_thread_current ();
2237                 /* The thread may already be stopping */
2238                 if (thread != NULL) 
2239                         return (thread->interruption_requested);
2240         }
2241         return FALSE;
2242 }
2243
2244 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2245 {
2246         MonoThread *thread = mono_thread_current ();
2247
2248         /* The thread may already be stopping */
2249         if (thread == NULL) 
2250                 return;
2251         
2252         if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2253                 MonoException* exc = mono_thread_execute_interruption (thread);
2254                 if (exc) mono_raise_exception (exc);
2255         }
2256 }
2257
2258 /*
2259  * Performs the interruption of the current thread, if one has been requested,
2260  * and the thread is not running a protected wrapper.
2261  */
2262 void mono_thread_interruption_checkpoint ()
2263 {
2264         mono_thread_interruption_checkpoint_request (FALSE);
2265 }
2266
2267 /*
2268  * Performs the interruption of the current thread, if one has been requested.
2269  */
2270 void mono_thread_force_interruption_checkpoint ()
2271 {
2272         mono_thread_interruption_checkpoint_request (TRUE);
2273 }
2274
2275 /**
2276  * mono_thread_interruption_request_flag:
2277  *
2278  * Returns the address of a flag that will be non-zero if an interruption has
2279  * been requested for a thread. The thread to interrupt may not be the current
2280  * thread, so an additional call to mono_thread_interruption_requested() or
2281  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2282  * zero.
2283  */
2284 gint32* mono_thread_interruption_request_flag ()
2285 {
2286         return &thread_interruption_requested;
2287 }
2288
2289 #ifdef WITH_INCLUDED_LIBGC
2290
2291 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2292 {
2293         MonoThread *thread=(MonoThread *)value;
2294         guint32 *selfp=(guint32 *)user, self = *selfp;
2295
2296 #ifdef LIBGC_DEBUG
2297         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2298 #endif
2299         
2300         if(thread->tid==self) {
2301 #ifdef LIBGC_DEBUG
2302                 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2303 #endif
2304                 GC_push_all_stack (selfp, thread->stack_ptr);
2305                 return;
2306         }
2307
2308 #ifdef PLATFORM_WIN32
2309         GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2310 #else
2311         mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2312 #endif
2313 }
2314
2315 void mono_gc_push_all_stacks (void)
2316 {
2317         guint32 self=GetCurrentThreadId ();
2318
2319 #ifdef LIBGC_DEBUG
2320         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2321 #endif
2322
2323         EnterCriticalSection (&threads_mutex);
2324
2325         if (threads != NULL)
2326                 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2327         
2328         LeaveCriticalSection (&threads_mutex);
2329 }
2330
2331 #endif /* WITH_INCLUDED_LIBGC */