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