2008-05-13 Zoltan Varga <vargaz@gmail.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
14 #include <glib.h>
15 #include <signal.h>
16 #include <string.h>
17
18 #include <mono/metadata/object.h>
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/profiler-private.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/threadpool.h>
23 #include <mono/metadata/threads-types.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/environment.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/gc-internal.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/metadata/object-internals.h>
31 #include <mono/metadata/mono-debug-debugger.h>
32 #include <mono/utils/mono-compiler.h>
33 #include <mono/utils/mono-mmap.h>
34 #include <mono/utils/mono-membar.h>
35 #include <mono/utils/mono-time.h>
36
37 #include <mono/metadata/gc-internal.h>
38
39 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
40 #define THREAD_DEBUG(a)
41 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
42 #define THREAD_WAIT_DEBUG(a)
43 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
44 #define LIBGC_DEBUG(a)
45
46 /* Provide this for systems with glib < 2.6 */
47 #ifndef G_GSIZE_FORMAT
48 #   if GLIB_SIZEOF_LONG == 8
49 #       define G_GSIZE_FORMAT "lu"
50 #   else
51 #       define G_GSIZE_FORMAT "u"
52 #   endif
53 #endif
54
55 struct StartInfo 
56 {
57         guint32 (*func)(void *);
58         MonoThread *obj;
59         MonoObject *delegate;
60         void *start_arg;
61         MonoDomain *domain;
62 };
63
64 typedef union {
65         gint32 ival;
66         gfloat fval;
67 } IntFloatUnion;
68
69 typedef union {
70         gint64 ival;
71         gdouble fval;
72 } LongDoubleUnion;
73  
74 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
75 struct _MonoThreadDomainTls {
76         MonoThreadDomainTls *next;
77         guint32 offset;
78         guint32 size;
79 };
80
81 typedef struct {
82         int idx;
83         int offset;
84         MonoThreadDomainTls *freelist;
85 } StaticDataInfo;
86
87 typedef struct {
88         gpointer p;
89         MonoHazardousFreeFunc free_func;
90 } DelayedFreeItem;
91
92 /* Number of cached culture objects in the MonoThread->cached_culture_info array
93  * (per-type): we use the first NUM entries for CultureInfo and the last for
94  * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
95  */
96 #define NUM_CACHED_CULTURES 4
97 #define CULTURES_START_IDX 0
98 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
99
100 /* Controls access to the 'threads' hash table */
101 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
102 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
103 static CRITICAL_SECTION threads_mutex;
104
105 /* Controls access to context static data */
106 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
107 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
108 static CRITICAL_SECTION contexts_mutex;
109
110 /* Holds current status of static data heap */
111 static StaticDataInfo thread_static_info;
112 static StaticDataInfo context_static_info;
113
114 /* The hash of existing threads (key is thread ID) that need joining
115  * before exit
116  */
117 static MonoGHashTable *threads=NULL;
118
119 /*
120  * Threads which are starting up and they are not in the 'threads' hash yet.
121  * When handle_store is called for a thread, it will be removed from this hash table.
122  * Protected by mono_threads_lock ().
123  */
124 static MonoGHashTable *threads_starting_up = NULL;
125
126 /* The TLS key that holds the MonoObject assigned to each thread */
127 static guint32 current_object_key = -1;
128
129 #ifdef HAVE_KW_THREAD
130 /* we need to use both the Tls* functions and __thread because
131  * the gc needs to see all the threads 
132  */
133 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
134 #define SET_CURRENT_OBJECT(x) do { \
135         tls_current_object = x; \
136         TlsSetValue (current_object_key, x); \
137 } while (FALSE)
138 #define GET_CURRENT_OBJECT() tls_current_object
139 #else
140 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
141 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
142 #endif
143
144 /* function called at thread start */
145 static MonoThreadStartCB mono_thread_start_cb = NULL;
146
147 /* function called at thread attach */
148 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
149
150 /* function called at thread cleanup */
151 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
152
153 /* function called to notify the runtime about a pending exception on the current thread */
154 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
155
156 /* The default stack size for each thread */
157 static guint32 default_stacksize = 0;
158 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
159
160 static void thread_adjust_static_data (MonoThread *thread);
161 static void mono_init_static_data_info (StaticDataInfo *static_data);
162 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
163 static gboolean mono_thread_resume (MonoThread* thread);
164 static void mono_thread_start (MonoThread *thread);
165 static void signal_thread_state_change (MonoThread *thread);
166
167 /* Spin lock for InterlockedXXX 64 bit functions */
168 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
169 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
170 static CRITICAL_SECTION interlocked_mutex;
171
172 /* global count of thread interruptions requested */
173 static gint32 thread_interruption_requested = 0;
174
175 /* Event signaled when a thread changes its background mode */
176 static HANDLE background_change_event;
177
178 /* The table for small ID assignment */
179 static CRITICAL_SECTION small_id_mutex;
180 static int small_id_table_size = 0;
181 static int small_id_next = 0;
182 static int highest_small_id = -1;
183 static MonoThread **small_id_table = NULL;
184
185 /* The hazard table */
186 #define HAZARD_TABLE_MAX_SIZE   16384 /* There cannot be more threads than this number. */
187 static volatile int hazard_table_size = 0;
188 static MonoThreadHazardPointers * volatile hazard_table = NULL;
189
190 /* The table where we keep pointers to blocks to be freed but that
191    have to wait because they're guarded by a hazard pointer. */
192 static CRITICAL_SECTION delayed_free_table_mutex;
193 static GArray *delayed_free_table = NULL;
194
195 static gboolean shutting_down = FALSE;
196
197 guint32
198 mono_thread_get_tls_key (void)
199 {
200         return current_object_key;
201 }
202
203 gint32
204 mono_thread_get_tls_offset (void)
205 {
206         int offset;
207         MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
208         return offset;
209 }
210
211 /* handle_store() and handle_remove() manage the array of threads that
212  * still need to be waited for when the main thread exits.
213  *
214  * If handle_store() returns FALSE the thread must not be started
215  * because Mono is shutting down.
216  */
217 static gboolean handle_store(MonoThread *thread)
218 {
219         mono_threads_lock ();
220
221         THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
222
223         if (threads_starting_up)
224                 mono_g_hash_table_remove (threads_starting_up, thread);
225
226         if (shutting_down) {
227                 mono_threads_unlock ();
228                 return FALSE;
229         }
230
231         if(threads==NULL) {
232                 MONO_GC_REGISTER_ROOT (threads);
233                 threads=mono_g_hash_table_new(NULL, NULL);
234         }
235
236         /* We don't need to duplicate thread->handle, because it is
237          * only closed when the thread object is finalized by the GC.
238          */
239         mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
240                                  thread);
241
242         mono_threads_unlock ();
243
244         return TRUE;
245 }
246
247 static gboolean handle_remove(MonoThread *thread)
248 {
249         gboolean ret;
250         gsize tid = thread->tid;
251
252         THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
253
254         mono_threads_lock ();
255
256         if (threads) {
257                 /* We have to check whether the thread object for the
258                  * tid is still the same in the table because the
259                  * thread might have been destroyed and the tid reused
260                  * in the meantime, in which case the tid would be in
261                  * the table, but with another thread object.
262                  */
263                 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
264                         mono_g_hash_table_remove (threads, (gpointer)tid);
265                         ret = TRUE;
266                 } else {
267                         ret = FALSE;
268                 }
269         }
270         else
271                 ret = FALSE;
272         
273         mono_threads_unlock ();
274
275         /* Don't close the handle here, wait for the object finalizer
276          * to do it. Otherwise, the following race condition applies:
277          *
278          * 1) Thread exits (and handle_remove() closes the handle)
279          *
280          * 2) Some other handle is reassigned the same slot
281          *
282          * 3) Another thread tries to join the first thread, and
283          * blocks waiting for the reassigned handle to be signalled
284          * (which might never happen).  This is possible, because the
285          * thread calling Join() still has a reference to the first
286          * thread's object.
287          */
288         return ret;
289 }
290
291 /*
292  * Allocate a small thread id.
293  *
294  * FIXME: The biggest part of this function is very similar to
295  * domain_id_alloc() in domain.c and should be merged.
296  */
297 static int
298 small_id_alloc (MonoThread *thread)
299 {
300         int id = -1, i;
301
302         EnterCriticalSection (&small_id_mutex);
303
304         if (!small_id_table) {
305                 small_id_table_size = 2;
306                 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
307         }
308         for (i = small_id_next; i < small_id_table_size; ++i) {
309                 if (!small_id_table [i]) {
310                         id = i;
311                         break;
312                 }
313         }
314         if (id == -1) {
315                 for (i = 0; i < small_id_next; ++i) {
316                         if (!small_id_table [i]) {
317                                 id = i;
318                                 break;
319                         }
320                 }
321         }
322         if (id == -1) {
323                 MonoThread **new_table;
324                 int new_size = small_id_table_size * 2;
325                 if (new_size >= (1 << 16))
326                         g_assert_not_reached ();
327                 id = small_id_table_size;
328                 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
329                 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
330                 mono_gc_free_fixed (small_id_table);
331                 small_id_table = new_table;
332                 small_id_table_size = new_size;
333         }
334         thread->small_id = id;
335         g_assert (small_id_table [id] == NULL);
336         small_id_table [id] = thread;
337         small_id_next++;
338         if (small_id_next > small_id_table_size)
339                 small_id_next = 0;
340
341         if (id >= hazard_table_size) {
342                 gpointer page_addr;
343                 int pagesize = mono_pagesize ();
344                 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
345
346                 if (hazard_table == NULL) {
347                         hazard_table = mono_valloc (NULL,
348                                 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
349                                 MONO_MMAP_NONE);
350                 }
351
352                 g_assert (hazard_table != NULL);
353                 page_addr = (guint8*)hazard_table + num_pages * pagesize;
354
355                 g_assert (id < HAZARD_TABLE_MAX_SIZE);
356
357                 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
358
359                 ++num_pages;
360                 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
361
362                 g_assert (id < hazard_table_size);
363
364                 hazard_table [id].hazard_pointers [0] = NULL;
365                 hazard_table [id].hazard_pointers [1] = NULL;
366         }
367
368         if (id > highest_small_id) {
369                 highest_small_id = id;
370                 mono_memory_write_barrier ();
371         }
372
373         LeaveCriticalSection (&small_id_mutex);
374
375         return id;
376 }
377
378 static void
379 small_id_free (int id)
380 {
381         g_assert (id >= 0 && id < small_id_table_size);
382         g_assert (small_id_table [id] != NULL);
383
384         small_id_table [id] = NULL;
385 }
386
387 static gboolean
388 is_pointer_hazardous (gpointer p)
389 {
390         int i;
391         int highest = highest_small_id;
392
393         g_assert (highest < hazard_table_size);
394
395         for (i = 0; i <= highest; ++i) {
396                 if (hazard_table [i].hazard_pointers [0] == p
397                                 || hazard_table [i].hazard_pointers [1] == p)
398                         return TRUE;
399         }
400
401         return FALSE;
402 }
403
404 MonoThreadHazardPointers*
405 mono_hazard_pointer_get (void)
406 {
407         MonoThread *current_thread = mono_thread_current ();
408
409         if (!(current_thread && current_thread->small_id >= 0)) {
410                 static MonoThreadHazardPointers emerg_hazard_table;
411                 g_warning ("Thread %p may have been prematurely finalized", current_thread);
412                 return &emerg_hazard_table;
413         }
414
415         return &hazard_table [current_thread->small_id];
416 }
417
418 void
419 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
420 {
421         int i;
422
423         /* First try to free a few entries in the delayed free
424            table. */
425         for (i = 2; i >= 0; --i) {
426                 if (delayed_free_table->len > i) {
427                         DelayedFreeItem item;
428
429                         item.p = NULL;
430                         EnterCriticalSection (&delayed_free_table_mutex);
431                         /* We have to check the length again because another
432                            thread might have freed an item before we acquired
433                            the lock. */
434                         if (delayed_free_table->len > i) {
435                                 item = g_array_index (delayed_free_table, DelayedFreeItem, i);
436
437                                 if (!is_pointer_hazardous (item.p))
438                                         g_array_remove_index_fast (delayed_free_table, i);
439                                 else
440                                         item.p = NULL;
441                         }
442                         LeaveCriticalSection (&delayed_free_table_mutex);
443
444                         if (item.p != NULL)
445                                 item.free_func (item.p);
446                 }
447         }
448
449         /* Now see if the pointer we're freeing is hazardous.  If it
450            isn't, free it.  Otherwise put it in the delay list. */
451         if (is_pointer_hazardous (p)) {
452                 DelayedFreeItem item = { p, free_func };
453
454                 ++mono_stats.hazardous_pointer_count;
455
456                 EnterCriticalSection (&delayed_free_table_mutex);
457                 g_array_append_val (delayed_free_table, item);
458                 LeaveCriticalSection (&delayed_free_table_mutex);
459         } else
460                 free_func (p);
461 }
462
463 static void ensure_synch_cs_set (MonoThread *thread)
464 {
465         CRITICAL_SECTION *synch_cs;
466         
467         if (thread->synch_cs != NULL) {
468                 return;
469         }
470         
471         synch_cs = g_new0 (CRITICAL_SECTION, 1);
472         InitializeCriticalSection (synch_cs);
473         
474         if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
475                                                synch_cs, NULL) != NULL) {
476                 /* Another thread must have installed this CS */
477                 DeleteCriticalSection (synch_cs);
478                 g_free (synch_cs);
479         }
480 }
481
482 /*
483  * NOTE: this function can be called also for threads different from the current one:
484  * make sure no code called from it will ever assume it is run on the thread that is
485  * getting cleaned up.
486  */
487 static void thread_cleanup (MonoThread *thread)
488 {
489         g_assert (thread != NULL);
490
491         /* if the thread is not in the hash it has been removed already */
492         if (!handle_remove (thread))
493                 return;
494         mono_release_type_locks (thread);
495
496         EnterCriticalSection (thread->synch_cs);
497
498         thread->state |= ThreadState_Stopped;
499         thread->state &= ~ThreadState_Background;
500
501         LeaveCriticalSection (thread->synch_cs);
502         
503         mono_profiler_thread_end (thread->tid);
504
505         if (thread == mono_thread_current ())
506                 mono_thread_pop_appdomain_ref ();
507
508         if (thread->serialized_culture_info)
509                 g_free (thread->serialized_culture_info);
510
511         thread->cached_culture_info = NULL;
512
513         mono_gc_free_fixed (thread->static_data);
514         thread->static_data = NULL;
515
516         if (mono_thread_cleanup_fn)
517                 mono_thread_cleanup_fn (thread);
518
519         small_id_free (thread->small_id);
520         thread->small_id = -2;
521 }
522
523 static guint32 WINAPI start_wrapper(void *data)
524 {
525         struct StartInfo *start_info=(struct StartInfo *)data;
526         guint32 (*start_func)(void *);
527         void *start_arg;
528         gsize tid;
529         MonoThread *thread=start_info->obj;
530         MonoObject *start_delegate = start_info->delegate;
531
532         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
533
534         /* We can be sure start_info->obj->tid and
535          * start_info->obj->handle have been set, because the thread
536          * was created suspended, and these values were set before the
537          * thread resumed
538          */
539
540         tid=thread->tid;
541
542         SET_CURRENT_OBJECT (thread);
543
544         /* Every thread references the appdomain which created it */
545         mono_thread_push_appdomain_ref (start_info->domain);
546         
547         if (!mono_domain_set (start_info->domain, FALSE)) {
548                 /* No point in raising an appdomain_unloaded exception here */
549                 /* FIXME: Cleanup here */
550                 mono_thread_pop_appdomain_ref ();
551                 return 0;
552         }
553
554         start_func = start_info->func;
555         start_arg = start_info->start_arg;
556
557         /* This MUST be called before any managed code can be
558          * executed, as it calls the callback function that (for the
559          * jit) sets the lmf marker.
560          */
561         mono_thread_new_init (tid, &tid, start_func);
562         thread->stack_ptr = &tid;
563
564         LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
565
566         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
567
568         mono_profiler_thread_start (tid);
569
570         /* On 2.0 profile (and higher), set explicitly since state might have been
571            Unknown */
572         if (mono_get_runtime_info ()->framework_version [0] != '1') {
573                 if (thread->apartment_state == ThreadApartmentState_Unknown)
574                         thread->apartment_state = ThreadApartmentState_MTA;
575         }
576
577         mono_thread_init_apartment_state ();
578
579         if(thread->start_notify!=NULL) {
580                 /* Let the thread that called Start() know we're
581                  * ready
582                  */
583                 ReleaseSemaphore (thread->start_notify, 1, NULL);
584         }
585
586         MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
587         g_free (start_info);
588
589         thread_adjust_static_data (thread);
590 #ifdef DEBUG
591         g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
592                    thread->tid);
593 #endif
594
595         /* start_func is set only for unmanaged start functions */
596         if (start_func) {
597                 start_func (start_arg);
598         } else {
599                 void *args [1];
600                 g_assert (start_delegate != NULL);
601                 args [0] = start_arg;
602                 /* we may want to handle the exception here. See comment below on unhandled exceptions */
603                 mono_runtime_delegate_invoke (start_delegate, args, NULL);
604         }
605
606         /* If the thread calls ExitThread at all, this remaining code
607          * will not be executed, but the main thread will eventually
608          * call thread_cleanup() on this thread's behalf.
609          */
610
611         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
612
613         thread_cleanup (thread);
614
615         /* Do any cleanup needed for apartment state. This
616          * cannot be done in thread_cleanup since thread_cleanup could be 
617          * called for a thread other than the current thread.
618          * mono_thread_cleanup_apartment_state cleans up apartment
619          * for the current thead */
620         mono_thread_cleanup_apartment_state ();
621
622         /* Remove the reference to the thread object in the TLS data,
623          * so the thread object can be finalized.  This won't be
624          * reached if the thread threw an uncaught exception, so those
625          * thread handles will stay referenced :-( (This is due to
626          * missing support for scanning thread-specific data in the
627          * Boehm GC - the io-layer keeps a GC-visible hash of pointers
628          * to TLS data.)
629          */
630         SET_CURRENT_OBJECT (NULL);
631
632         return(0);
633 }
634
635 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
636 {
637         if (mono_thread_start_cb) {
638                 mono_thread_start_cb (tid, stack_start, func);
639         }
640 }
641
642 void mono_threads_set_default_stacksize (guint32 stacksize)
643 {
644         default_stacksize = stacksize;
645 }
646
647 guint32 mono_threads_get_default_stacksize (void)
648 {
649         return default_stacksize;
650 }
651
652 void mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
653 {
654         MonoThread *thread;
655         HANDLE thread_handle;
656         struct StartInfo *start_info;
657         gsize tid;
658
659         thread=(MonoThread *)mono_object_new (domain,
660                                               mono_defaults.thread_class);
661
662         start_info=g_new0 (struct StartInfo, 1);
663         start_info->func = func;
664         start_info->obj = thread;
665         start_info->domain = domain;
666         start_info->start_arg = arg;
667
668         /* 
669          * The argument may be an object reference, and there is no ref to keep it alive
670          * when the new thread is started but not yet registered with the collector.
671          */
672         MONO_GC_REGISTER_ROOT (start_info->start_arg);
673
674         mono_threads_lock ();
675         if (shutting_down) {
676                 mono_threads_unlock ();
677                 return;
678         }
679         if (threads_starting_up == NULL) {
680                 MONO_GC_REGISTER_ROOT (threads_starting_up);
681                 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
682         }
683         mono_g_hash_table_insert (threads_starting_up, thread, thread);
684         mono_threads_unlock (); 
685
686         /* Create suspended, so we can do some housekeeping before the thread
687          * starts
688          */
689         thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
690                                      CREATE_SUSPENDED, &tid);
691         THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
692         if (thread_handle == NULL) {
693                 /* The thread couldn't be created, so throw an exception */
694                 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
695                 mono_threads_lock ();
696                 mono_g_hash_table_remove (threads_starting_up, thread);
697                 mono_threads_unlock ();
698                 g_free (start_info);
699                 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
700                 return;
701         }
702
703         thread->handle=thread_handle;
704         thread->tid=tid;
705         thread->apartment_state=ThreadApartmentState_Unknown;
706         small_id_alloc (thread);
707
708         thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
709         InitializeCriticalSection (thread->synch_cs);
710
711         thread->threadpool_thread = threadpool_thread;
712
713         if (handle_store (thread))
714                 ResumeThread (thread_handle);
715 }
716
717 void
718 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
719 {
720         mono_thread_create_internal (domain, func, arg, FALSE);
721 }
722
723 /*
724  * mono_thread_get_stack_bounds:
725  *
726  *   Return the address and size of the current threads stack. Return NULL as the stack
727  * address if the stack address cannot be determined.
728  */
729 void
730 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
731 {
732 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
733         *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
734         *stsize = pthread_get_stacksize_np (pthread_self ());
735         return;
736         /* FIXME: simplify the mess below */
737 #elif !defined(PLATFORM_WIN32)
738         pthread_attr_t attr;
739         guint8 *current = (guint8*)&attr;
740
741         pthread_attr_init (&attr);
742 #ifdef HAVE_PTHREAD_GETATTR_NP
743                 pthread_getattr_np (pthread_self(), &attr);
744 #else
745 #ifdef HAVE_PTHREAD_ATTR_GET_NP
746                 pthread_attr_get_np (pthread_self(), &attr);
747 #elif defined(sun)
748                 *staddr = NULL;
749                 pthread_attr_getstacksize (&attr, &stsize);
750 #else
751                 *staddr = NULL;
752                 *stsize = 0;
753                 return;
754 #endif
755 #endif
756
757 #ifndef sun
758                 pthread_attr_getstack (&attr, (void**)staddr, stsize);
759                 if (*staddr)
760                         g_assert ((current > *staddr) && (current < *staddr + *stsize));
761 #endif
762
763                 pthread_attr_destroy (&attr); 
764 #endif
765 }       
766
767 MonoThread *
768 mono_thread_attach (MonoDomain *domain)
769 {
770         MonoThread *thread;
771         HANDLE thread_handle;
772         gsize tid;
773
774         if ((thread = mono_thread_current ())) {
775                 if (domain != mono_domain_get ())
776                         mono_domain_set (domain, TRUE);
777                 /* Already attached */
778                 return thread;
779         }
780
781         if (!mono_gc_register_thread (&domain)) {
782                 g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
783         }
784
785         thread = (MonoThread *)mono_object_new (domain,
786                                                 mono_defaults.thread_class);
787
788         thread_handle = GetCurrentThread ();
789         g_assert (thread_handle);
790
791         tid=GetCurrentThreadId ();
792
793         /* 
794          * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
795          * refer to the thread from other threads for things like aborting.
796          */
797         DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle, 
798                                          THREAD_ALL_ACCESS, TRUE, 0);
799
800         thread->handle=thread_handle;
801         thread->tid=tid;
802         thread->apartment_state=ThreadApartmentState_Unknown;
803         small_id_alloc (thread);
804         thread->stack_ptr = &tid;
805
806         thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
807         InitializeCriticalSection (thread->synch_cs);
808
809         THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
810
811         if (!handle_store (thread)) {
812                 /* Mono is shutting down, so just wait for the end */
813                 for (;;)
814                         Sleep (10000);
815         }
816
817         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
818
819         SET_CURRENT_OBJECT (thread);
820         mono_domain_set (domain, TRUE);
821
822         thread_adjust_static_data (thread);
823
824         if (mono_thread_attach_cb) {
825                 guint8 *staddr;
826                 size_t stsize;
827
828                 mono_thread_get_stack_bounds (&staddr, &stsize);
829
830                 if (staddr == NULL)
831                         mono_thread_attach_cb (tid, &tid);
832                 else
833                         mono_thread_attach_cb (tid, staddr + stsize);
834         }
835
836         return(thread);
837 }
838
839 void
840 mono_thread_detach (MonoThread *thread)
841 {
842         g_return_if_fail (thread != NULL);
843
844         THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
845         
846         thread_cleanup (thread);
847
848         SET_CURRENT_OBJECT (NULL);
849
850         /* Don't need to CloseHandle this thread, even though we took a
851          * reference in mono_thread_attach (), because the GC will do it
852          * when the Thread object is finalised.
853          */
854 }
855
856 void
857 mono_thread_exit ()
858 {
859         MonoThread *thread = mono_thread_current ();
860
861         THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
862
863         thread_cleanup (thread);
864         SET_CURRENT_OBJECT (NULL);
865
866         /* we could add a callback here for embedders to use. */
867         if (thread == mono_thread_get_main ())
868                 exit (mono_environment_exitcode_get ());
869         ExitThread (-1);
870 }
871
872 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
873                                                          MonoObject *start)
874 {
875         guint32 (*start_func)(void *);
876         struct StartInfo *start_info;
877         HANDLE thread;
878         gsize tid;
879         
880         MONO_ARCH_SAVE_REGS;
881
882         THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
883
884         ensure_synch_cs_set (this);
885
886         EnterCriticalSection (this->synch_cs);
887
888         if ((this->state & ThreadState_Unstarted) == 0) {
889                 LeaveCriticalSection (this->synch_cs);
890                 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
891                 return NULL;
892         }
893
894         this->small_id = -1;
895
896         if ((this->state & ThreadState_Aborted) != 0) {
897                 LeaveCriticalSection (this->synch_cs);
898                 return this;
899         }
900         start_func = NULL;
901         {
902                 /* This is freed in start_wrapper */
903                 start_info = g_new0 (struct StartInfo, 1);
904                 start_info->func = start_func;
905                 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
906                 start_info->delegate = start;
907                 start_info->obj = this;
908                 start_info->domain = mono_domain_get ();
909
910                 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
911                 if(this->start_notify==NULL) {
912                         LeaveCriticalSection (this->synch_cs);
913                         g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
914                         return(NULL);
915                 }
916
917                 mono_threads_lock ();
918                 if (threads_starting_up == NULL) {
919                         MONO_GC_REGISTER_ROOT (threads_starting_up);
920                         threads_starting_up = mono_g_hash_table_new (NULL, NULL);
921                 }
922                 mono_g_hash_table_insert (threads_starting_up, this, this);
923                 mono_threads_unlock (); 
924
925                 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
926                                     CREATE_SUSPENDED, &tid);
927                 if(thread==NULL) {
928                         LeaveCriticalSection (this->synch_cs);
929                         mono_threads_lock ();
930                         mono_g_hash_table_remove (threads_starting_up, this);
931                         mono_threads_unlock ();
932                         g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
933                         return(NULL);
934                 }
935                 
936                 this->handle=thread;
937                 this->tid=tid;
938                 small_id_alloc (this);
939
940                 /* Don't call handle_store() here, delay it to Start.
941                  * We can't join a thread (trying to will just block
942                  * forever) until it actually starts running, so don't
943                  * store the handle till then.
944                  */
945
946                 mono_thread_start (this);
947                 
948                 this->state &= ~ThreadState_Unstarted;
949
950                 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
951
952                 LeaveCriticalSection (this->synch_cs);
953                 return(thread);
954         }
955 }
956
957 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
958 {
959         MONO_ARCH_SAVE_REGS;
960
961         ensure_synch_cs_set (this);
962 }
963
964 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
965                                                              HANDLE thread)
966 {
967         MONO_ARCH_SAVE_REGS;
968
969         THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
970
971         CloseHandle (thread);
972
973         DeleteCriticalSection (this->synch_cs);
974         g_free (this->synch_cs);
975         this->synch_cs = NULL;
976 }
977
978 static void mono_thread_start (MonoThread *thread)
979 {
980         MONO_ARCH_SAVE_REGS;
981
982         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
983
984         /* Only store the handle when the thread is about to be
985          * launched, to avoid the main thread deadlocking while trying
986          * to clean up a thread that will never be signalled.
987          */
988         if (!handle_store (thread))
989                 return;
990
991         ResumeThread (thread->handle);
992
993         if(thread->start_notify!=NULL) {
994                 /* Wait for the thread to set up its TLS data etc, so
995                  * theres no potential race condition if someone tries
996                  * to look up the data believing the thread has
997                  * started
998                  */
999
1000                 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1001
1002                 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1003                 CloseHandle (thread->start_notify);
1004                 thread->start_notify = NULL;
1005         }
1006
1007         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1008 }
1009
1010 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1011 {
1012         MonoThread *thread = mono_thread_current ();
1013         
1014         MONO_ARCH_SAVE_REGS;
1015
1016         THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1017
1018         mono_thread_current_check_pending_interrupt ();
1019         
1020         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1021         
1022         SleepEx(ms,TRUE);
1023         
1024         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1025 }
1026
1027 void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
1028 {
1029         gint32 i;
1030         
1031         for(i = 0; i < iterations; i++) {
1032                 /* We're busy waiting, but at least we can tell the
1033                  * scheduler to let someone else have a go...
1034                  */
1035                 Sleep (0);
1036         }
1037 }
1038
1039 gint32
1040 ves_icall_System_Threading_Thread_GetDomainID (void) 
1041 {
1042         MONO_ARCH_SAVE_REGS;
1043
1044         return mono_domain_get()->domain_id;
1045 }
1046
1047 MonoString* 
1048 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1049 {
1050         MonoString* str;
1051
1052         ensure_synch_cs_set (this_obj);
1053         
1054         EnterCriticalSection (this_obj->synch_cs);
1055         
1056         if (!this_obj->name)
1057                 str = NULL;
1058         else
1059                 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1060         
1061         LeaveCriticalSection (this_obj->synch_cs);
1062         
1063         return str;
1064 }
1065
1066 void 
1067 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1068 {
1069         ensure_synch_cs_set (this_obj);
1070         
1071         EnterCriticalSection (this_obj->synch_cs);
1072         
1073         if (this_obj->name) {
1074                 LeaveCriticalSection (this_obj->synch_cs);
1075                 
1076                 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1077                 return;
1078         }
1079         if (name) {
1080                 this_obj->name = g_new (gunichar2, mono_string_length (name));
1081                 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1082                 this_obj->name_len = mono_string_length (name);
1083         }
1084         else
1085                 this_obj->name = NULL;
1086         
1087         LeaveCriticalSection (this_obj->synch_cs);
1088 }
1089
1090 static MonoObject*
1091 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1092 {
1093         MonoObject *res;
1094         int i;
1095
1096         if (this->cached_culture_info) {
1097                 domain = mono_domain_get ();
1098                 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1099                         res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1100                         if (res && res->vtable->domain == domain)
1101                                 return res;
1102                 }
1103         }
1104
1105         return NULL;
1106 }
1107
1108 MonoObject*
1109 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1110 {
1111         return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1112 }
1113
1114 MonoArray*
1115 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1116 {
1117         MonoArray *res;
1118
1119         ensure_synch_cs_set (this);
1120         
1121         EnterCriticalSection (this->synch_cs);
1122         
1123         if (this->serialized_culture_info) {
1124                 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1125                 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1126         } else {
1127                 res = NULL;
1128         }
1129
1130         LeaveCriticalSection (this->synch_cs);
1131
1132         return res;
1133 }
1134
1135 static void
1136 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1137 {
1138         int i;
1139         MonoDomain *domain = mono_domain_get ();
1140         MonoObject *obj;
1141         int free_slot = -1;
1142         int same_domain_slot = -1;
1143
1144         ensure_synch_cs_set (this);
1145         
1146         EnterCriticalSection (this->synch_cs);
1147         
1148         if (!this->cached_culture_info)
1149                 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1150
1151         for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1152                 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1153                 /* Free entry */
1154                 if (!obj) {
1155                         free_slot = i;
1156                         /* we continue, because there may be a slot used with the same domain */
1157                         continue;
1158                 }
1159                 /* Replace */
1160                 if (obj->vtable->domain == domain) {
1161                         same_domain_slot = i;
1162                         break;
1163                 }
1164         }
1165         if (same_domain_slot >= 0)
1166                 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1167         else if (free_slot >= 0)
1168                 mono_array_setref (this->cached_culture_info, free_slot, culture);
1169         /* we may want to replace an existing entry here, even when no suitable slot is found */
1170
1171         LeaveCriticalSection (this->synch_cs);
1172 }
1173
1174 void
1175 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1176 {
1177         cache_culture (this, culture, CULTURES_START_IDX);
1178 }
1179
1180 void
1181 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1182 {
1183         ensure_synch_cs_set (this);
1184         
1185         EnterCriticalSection (this->synch_cs);
1186         
1187         if (this->serialized_culture_info)
1188                 g_free (this->serialized_culture_info);
1189         this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1190         this->serialized_culture_info_len = mono_array_length (arr);
1191         memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1192
1193         LeaveCriticalSection (this->synch_cs);
1194 }
1195
1196
1197 MonoObject*
1198 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1199 {
1200         return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1201 }
1202
1203 MonoArray*
1204 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1205 {
1206         MonoArray *res;
1207
1208         ensure_synch_cs_set (this);
1209         
1210         EnterCriticalSection (this->synch_cs);
1211         
1212         if (this->serialized_ui_culture_info) {
1213                 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1214                 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1215         } else {
1216                 res = NULL;
1217         }
1218
1219         LeaveCriticalSection (this->synch_cs);
1220
1221         return res;
1222 }
1223
1224 void
1225 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1226 {
1227         cache_culture (this, culture, UICULTURES_START_IDX);
1228 }
1229
1230 void
1231 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1232 {
1233         ensure_synch_cs_set (this);
1234         
1235         EnterCriticalSection (this->synch_cs);
1236         
1237         if (this->serialized_ui_culture_info)
1238                 g_free (this->serialized_ui_culture_info);
1239         this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1240         this->serialized_ui_culture_info_len = mono_array_length (arr);
1241         memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1242
1243         LeaveCriticalSection (this->synch_cs);
1244 }
1245
1246 /* the jit may read the compiled code of this function */
1247 MonoThread *
1248 mono_thread_current (void)
1249 {
1250         THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
1251         return GET_CURRENT_OBJECT ();
1252 }
1253
1254 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1255                                                          int ms, HANDLE thread)
1256 {
1257         MonoThread *cur_thread = mono_thread_current ();
1258         gboolean ret;
1259         
1260         MONO_ARCH_SAVE_REGS;
1261         
1262         mono_thread_current_check_pending_interrupt ();
1263
1264         ensure_synch_cs_set (this);
1265         
1266         EnterCriticalSection (this->synch_cs);
1267         
1268         if ((this->state & ThreadState_Unstarted) != 0) {
1269                 LeaveCriticalSection (this->synch_cs);
1270                 
1271                 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1272                 return FALSE;
1273         }
1274
1275         LeaveCriticalSection (this->synch_cs);
1276
1277         if(ms== -1) {
1278                 ms=INFINITE;
1279         }
1280         THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1281         
1282         mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1283
1284         ret=WaitForSingleObjectEx (thread, ms, TRUE);
1285
1286         mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1287         
1288         if(ret==WAIT_OBJECT_0) {
1289                 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1290
1291                 return(TRUE);
1292         }
1293         
1294         THREAD_DEBUG (g_message ("%s: join failed", __func__));
1295
1296         return(FALSE);
1297 }
1298
1299 /* FIXME: exitContext isnt documented */
1300 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1301 {
1302         HANDLE *handles;
1303         guint32 numhandles;
1304         guint32 ret;
1305         guint32 i;
1306         MonoObject *waitHandle;
1307         MonoThread *thread = mono_thread_current ();
1308                 
1309         MONO_ARCH_SAVE_REGS;
1310
1311         /* Do this WaitSleepJoin check before creating objects */
1312         mono_thread_current_check_pending_interrupt ();
1313
1314         numhandles = mono_array_length(mono_handles);
1315         handles = g_new0(HANDLE, numhandles);
1316
1317         for(i = 0; i < numhandles; i++) {       
1318                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1319                 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1320         }
1321         
1322         if(ms== -1) {
1323                 ms=INFINITE;
1324         }
1325
1326         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1327         
1328         ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1329
1330         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1331
1332         g_free(handles);
1333
1334         if(ret==WAIT_FAILED) {
1335                 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1336                 return(FALSE);
1337         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1338                 /* Do we want to try again if we get
1339                  * WAIT_IO_COMPLETION? The documentation for
1340                  * WaitHandle doesn't give any clues.  (We'd have to
1341                  * fiddle with the timeout if we retry.)
1342                  */
1343                 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1344                 return(FALSE);
1345         }
1346         
1347         return(TRUE);
1348 }
1349
1350 /* FIXME: exitContext isnt documented */
1351 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1352 {
1353         HANDLE *handles;
1354         guint32 numhandles;
1355         guint32 ret;
1356         guint32 i;
1357         MonoObject *waitHandle;
1358         MonoThread *thread = mono_thread_current ();
1359                 
1360         MONO_ARCH_SAVE_REGS;
1361
1362         /* Do this WaitSleepJoin check before creating objects */
1363         mono_thread_current_check_pending_interrupt ();
1364
1365         numhandles = mono_array_length(mono_handles);
1366         handles = g_new0(HANDLE, numhandles);
1367
1368         for(i = 0; i < numhandles; i++) {       
1369                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1370                 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1371         }
1372         
1373         if(ms== -1) {
1374                 ms=INFINITE;
1375         }
1376
1377         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1378         
1379         ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1380
1381         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1382         
1383         g_free(handles);
1384
1385         THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1386
1387         /*
1388          * These need to be here.  See MSDN dos on WaitForMultipleObjects.
1389          */
1390         if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1391                 return ret - WAIT_OBJECT_0;
1392         }
1393         else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1394                 return ret - WAIT_ABANDONED_0;
1395         }
1396         else {
1397                 return ret;
1398         }
1399 }
1400
1401 /* FIXME: exitContext isnt documented */
1402 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1403 {
1404         guint32 ret;
1405         MonoThread *thread = mono_thread_current ();
1406         
1407         MONO_ARCH_SAVE_REGS;
1408
1409         THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1410         
1411         if(ms== -1) {
1412                 ms=INFINITE;
1413         }
1414         
1415         mono_thread_current_check_pending_interrupt ();
1416
1417         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1418         
1419         ret=WaitForSingleObjectEx (handle, ms, TRUE);
1420         
1421         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1422         
1423         if(ret==WAIT_FAILED) {
1424                 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1425                 return(FALSE);
1426         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1427                 /* Do we want to try again if we get
1428                  * WAIT_IO_COMPLETION? The documentation for
1429                  * WaitHandle doesn't give any clues.  (We'd have to
1430                  * fiddle with the timeout if we retry.)
1431                  */
1432                 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1433                 return(FALSE);
1434         }
1435         
1436         return(TRUE);
1437 }
1438
1439 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1440
1441         HANDLE mutex;
1442         
1443         MONO_ARCH_SAVE_REGS;
1444    
1445         *created = TRUE;
1446         
1447         if (name == NULL) {
1448                 mutex = CreateMutex (NULL, owned, NULL);
1449         } else {
1450                 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1451                 
1452                 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1453                         *created = FALSE;
1454                 }
1455         }
1456
1457         return(mutex);
1458 }                                                                   
1459
1460 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) { 
1461         MONO_ARCH_SAVE_REGS;
1462
1463         return(ReleaseMutex (handle));
1464 }
1465
1466 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1467                                                             gint32 rights,
1468                                                             gint32 *error)
1469 {
1470         HANDLE ret;
1471         
1472         MONO_ARCH_SAVE_REGS;
1473         
1474         *error = ERROR_SUCCESS;
1475         
1476         ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1477         if (ret == NULL) {
1478                 *error = GetLastError ();
1479         }
1480         
1481         return(ret);
1482 }
1483
1484
1485 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1486
1487         HANDLE sem;
1488         
1489         MONO_ARCH_SAVE_REGS;
1490    
1491         *created = TRUE;
1492         
1493         if (name == NULL) {
1494                 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1495         } else {
1496                 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1497                                        mono_string_chars (name));
1498                 
1499                 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1500                         *created = FALSE;
1501                 }
1502         }
1503
1504         return(sem);
1505 }                                                                   
1506
1507 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1508
1509         gint32 prevcount;
1510         
1511         MONO_ARCH_SAVE_REGS;
1512
1513         *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1514
1515         return (prevcount);
1516 }
1517
1518 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1519 {
1520         HANDLE ret;
1521         
1522         MONO_ARCH_SAVE_REGS;
1523         
1524         *error = ERROR_SUCCESS;
1525         
1526         ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1527         if (ret == NULL) {
1528                 *error = GetLastError ();
1529         }
1530         
1531         return(ret);
1532 }
1533
1534 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1535 {
1536         HANDLE event;
1537         
1538         MONO_ARCH_SAVE_REGS;
1539
1540         *created = TRUE;
1541
1542         if (name == NULL) {
1543                 event = CreateEvent (NULL, manual, initial, NULL);
1544         } else {
1545                 event = CreateEvent (NULL, manual, initial,
1546                                      mono_string_chars (name));
1547                 
1548                 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1549                         *created = FALSE;
1550                 }
1551         }
1552         
1553         return(event);
1554 }
1555
1556 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1557         MONO_ARCH_SAVE_REGS;
1558
1559         return (SetEvent(handle));
1560 }
1561
1562 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1563         MONO_ARCH_SAVE_REGS;
1564
1565         return (ResetEvent(handle));
1566 }
1567
1568 void
1569 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1570         MONO_ARCH_SAVE_REGS;
1571
1572         CloseHandle (handle);
1573 }
1574
1575 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1576                                                              gint32 rights,
1577                                                              gint32 *error)
1578 {
1579         HANDLE ret;
1580         
1581         MONO_ARCH_SAVE_REGS;
1582         
1583         *error = ERROR_SUCCESS;
1584         
1585         ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1586         if (ret == NULL) {
1587                 *error = GetLastError ();
1588         }
1589         
1590         return(ret);
1591 }
1592
1593 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1594 {
1595         MONO_ARCH_SAVE_REGS;
1596
1597         return InterlockedIncrement (location);
1598 }
1599
1600 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1601 {
1602         gint64 ret;
1603
1604         MONO_ARCH_SAVE_REGS;
1605
1606         mono_interlocked_lock ();
1607
1608         ret = ++ *location;
1609         
1610         mono_interlocked_unlock ();
1611
1612         
1613         return ret;
1614 }
1615
1616 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1617 {
1618         MONO_ARCH_SAVE_REGS;
1619
1620         return InterlockedDecrement(location);
1621 }
1622
1623 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1624 {
1625         gint64 ret;
1626
1627         MONO_ARCH_SAVE_REGS;
1628
1629         mono_interlocked_lock ();
1630
1631         ret = -- *location;
1632         
1633         mono_interlocked_unlock ();
1634
1635         return ret;
1636 }
1637
1638 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1639 {
1640         MONO_ARCH_SAVE_REGS;
1641
1642         return InterlockedExchange(location, value);
1643 }
1644
1645 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1646 {
1647         MONO_ARCH_SAVE_REGS;
1648
1649         return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1650 }
1651
1652 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1653 {
1654         IntFloatUnion val, ret;
1655
1656         MONO_ARCH_SAVE_REGS;
1657
1658         val.fval = value;
1659         ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1660
1661         return ret.fval;
1662 }
1663
1664 gint64 
1665 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1666 {
1667 #if SIZEOF_VOID_P == 8
1668         return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1669 #else
1670         gint64 res;
1671
1672         /* 
1673          * According to MSDN, this function is only atomic with regards to the 
1674          * other Interlocked functions on 32 bit platforms.
1675          */
1676         mono_interlocked_lock ();
1677         res = *location;
1678         *location = value;
1679         mono_interlocked_unlock ();
1680
1681         return res;
1682 #endif
1683 }
1684
1685 gdouble 
1686 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1687 {
1688 #if SIZEOF_VOID_P == 8
1689         LongDoubleUnion val, ret;
1690
1691         val.fval = value;
1692         ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1693
1694         return ret.fval;
1695 #else
1696         gdouble res;
1697
1698         /* 
1699          * According to MSDN, this function is only atomic with regards to the 
1700          * other Interlocked functions on 32 bit platforms.
1701          */
1702         mono_interlocked_lock ();
1703         res = *location;
1704         *location = value;
1705         mono_interlocked_unlock ();
1706
1707         return res;
1708 #endif
1709 }
1710
1711 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1712 {
1713         MONO_ARCH_SAVE_REGS;
1714
1715         return InterlockedCompareExchange(location, value, comparand);
1716 }
1717
1718 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1719 {
1720         MONO_ARCH_SAVE_REGS;
1721
1722         return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1723 }
1724
1725 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1726 {
1727         IntFloatUnion val, ret, cmp;
1728
1729         MONO_ARCH_SAVE_REGS;
1730
1731         val.fval = value;
1732         cmp.fval = comparand;
1733         ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1734
1735         return ret.fval;
1736 }
1737
1738 gdouble
1739 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1740 {
1741 #if SIZEOF_VOID_P == 8
1742         LongDoubleUnion val, comp, ret;
1743
1744         val.fval = value;
1745         comp.fval = comparand;
1746         ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1747
1748         return ret.fval;
1749 #else
1750         gdouble old;
1751
1752         mono_interlocked_lock ();
1753         old = *location;
1754         if (old == comparand)
1755                 *location = value;
1756         mono_interlocked_unlock ();
1757
1758         return old;
1759 #endif
1760 }
1761
1762 gint64 
1763 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1764 {
1765 #if SIZEOF_VOID_P == 8
1766         return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1767 #else
1768         gint64 old;
1769
1770         mono_interlocked_lock ();
1771         old = *location;
1772         if (old == comparand)
1773                 *location = value;
1774         mono_interlocked_unlock ();
1775         
1776         return old;
1777 #endif
1778 }
1779
1780 MonoObject*
1781 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1782 {
1783         MONO_ARCH_SAVE_REGS;
1784
1785         return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1786 }
1787
1788 MonoObject*
1789 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1790 {
1791         MONO_ARCH_SAVE_REGS;
1792
1793         return InterlockedExchangePointer ((gpointer *)location, value);
1794 }
1795
1796 gint32 
1797 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1798 {
1799 #if SIZEOF_VOID_P == 8
1800         /* Should be implemented as a JIT intrinsic */
1801         mono_raise_exception (mono_get_exception_not_implemented (NULL));
1802         return 0;
1803 #else
1804         gint32 orig;
1805
1806         mono_interlocked_lock ();
1807         orig = *location;
1808         *location = orig + value;
1809         mono_interlocked_unlock ();
1810
1811         return orig + value;
1812 #endif
1813 }
1814
1815 gint64 
1816 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1817 {
1818 #if SIZEOF_VOID_P == 8
1819         /* Should be implemented as a JIT intrinsic */
1820         mono_raise_exception (mono_get_exception_not_implemented (NULL));
1821         return 0;
1822 #else
1823         gint64 orig;
1824
1825         mono_interlocked_lock ();
1826         orig = *location;
1827         *location = orig + value;
1828         mono_interlocked_unlock ();
1829
1830         return orig + value;
1831 #endif
1832 }
1833
1834 gint64 
1835 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1836 {
1837 #if SIZEOF_VOID_P == 8
1838         /* 64 bit reads are already atomic */
1839         return *location;
1840 #else
1841         gint64 res;
1842
1843         mono_interlocked_lock ();
1844         res = *location;
1845         mono_interlocked_unlock ();
1846
1847         return res;
1848 #endif
1849 }
1850
1851 void
1852 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1853 {
1854         mono_threads_lock ();
1855         mono_threads_unlock ();
1856 }
1857
1858 void
1859 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1860 {
1861         mono_thread_clr_state (this, state);
1862
1863         if (state & ThreadState_Background) {
1864                 /* If the thread changes the background mode, the main thread has to
1865                  * be notified, since it has to rebuild the list of threads to
1866                  * wait for.
1867                  */
1868                 SetEvent (background_change_event);
1869         }
1870 }
1871
1872 void
1873 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1874 {
1875         mono_thread_set_state (this, state);
1876         
1877         if (state & ThreadState_Background) {
1878                 /* If the thread changes the background mode, the main thread has to
1879                  * be notified, since it has to rebuild the list of threads to
1880                  * wait for.
1881                  */
1882                 SetEvent (background_change_event);
1883         }
1884 }
1885
1886 guint32
1887 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1888 {
1889         guint32 state;
1890
1891         ensure_synch_cs_set (this);
1892         
1893         EnterCriticalSection (this->synch_cs);
1894         
1895         state = this->state;
1896
1897         LeaveCriticalSection (this->synch_cs);
1898         
1899         return state;
1900 }
1901
1902 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1903 {
1904         gboolean throw = FALSE;
1905         
1906         ensure_synch_cs_set (this);
1907         
1908         EnterCriticalSection (this->synch_cs);
1909         
1910         this->thread_interrupt_requested = TRUE;
1911         
1912         if (this->state & ThreadState_WaitSleepJoin) {
1913                 throw = TRUE;
1914         }
1915         
1916         LeaveCriticalSection (this->synch_cs);
1917         
1918         if (throw) {
1919                 signal_thread_state_change (this);
1920         }
1921 }
1922
1923 void mono_thread_current_check_pending_interrupt ()
1924 {
1925         MonoThread *thread = mono_thread_current ();
1926         gboolean throw = FALSE;
1927
1928         ensure_synch_cs_set (thread);
1929         
1930         EnterCriticalSection (thread->synch_cs);
1931         
1932         if (thread->thread_interrupt_requested) {
1933                 throw = TRUE;
1934                 thread->thread_interrupt_requested = FALSE;
1935         }
1936         
1937         LeaveCriticalSection (thread->synch_cs);
1938
1939         if (throw) {
1940                 mono_raise_exception (mono_get_exception_thread_interrupted ());
1941         }
1942 }
1943
1944 int  
1945 mono_thread_get_abort_signal (void)
1946 {
1947 #ifdef PLATFORM_WIN32
1948         return -1;
1949 #else
1950 #ifndef SIGRTMIN
1951         return SIGUSR1;
1952 #else
1953         static int abort_signum = -1;
1954         int i;
1955         if (abort_signum != -1)
1956                 return abort_signum;
1957         /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1958         for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1959                 struct sigaction sinfo;
1960                 sigaction (i, NULL, &sinfo);
1961                 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1962                         abort_signum = i;
1963                         return i;
1964                 }
1965         }
1966         /* fallback to the old way */
1967         return SIGRTMIN;
1968 #endif
1969 #endif /* PLATFORM_WIN32 */
1970 }
1971
1972 #ifdef PLATFORM_WIN32
1973 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1974 {
1975         MonoException* exc = mono_thread_request_interruption (FALSE);
1976         if (exc) mono_raise_exception (exc);
1977 }
1978 #endif /* PLATFORM_WIN32 */
1979
1980 /*
1981  * signal_thread_state_change
1982  *
1983  * Tells the thread that his state has changed and it has to enter the new
1984  * state as soon as possible.
1985  */
1986 static void signal_thread_state_change (MonoThread *thread)
1987 {
1988         if (thread == mono_thread_current ()) {
1989                 /* Do it synchronously */
1990                 MonoException *exc = mono_thread_request_interruption (FALSE); 
1991                 if (exc)
1992                         mono_raise_exception (exc);
1993         }
1994
1995 #ifdef PLATFORM_WIN32
1996         QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1997 #else
1998         /* fixme: store the state somewhere */
1999 #ifdef PTHREAD_POINTER_ID
2000         pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2001 #else
2002         pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2003 #endif
2004 #endif /* PLATFORM_WIN32 */
2005 }
2006
2007 void
2008 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2009 {
2010         MONO_ARCH_SAVE_REGS;
2011
2012         ensure_synch_cs_set (thread);
2013         
2014         EnterCriticalSection (thread->synch_cs);
2015         
2016         if ((thread->state & ThreadState_AbortRequested) != 0 || 
2017                 (thread->state & ThreadState_StopRequested) != 0 ||
2018                 (thread->state & ThreadState_Stopped) != 0)
2019         {
2020                 LeaveCriticalSection (thread->synch_cs);
2021                 return;
2022         }
2023
2024         if ((thread->state & ThreadState_Unstarted) != 0) {
2025                 thread->state |= ThreadState_Aborted;
2026                 LeaveCriticalSection (thread->synch_cs);
2027                 return;
2028         }
2029
2030         thread->state |= ThreadState_AbortRequested;
2031         MONO_OBJECT_SETREF (thread, abort_state, state);
2032         thread->abort_exc = NULL;
2033
2034         LeaveCriticalSection (thread->synch_cs);
2035
2036         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2037         
2038         /* Make sure the thread is awake */
2039         mono_thread_resume (thread);
2040         
2041         signal_thread_state_change (thread);
2042 }
2043
2044 void
2045 ves_icall_System_Threading_Thread_ResetAbort (void)
2046 {
2047         MonoThread *thread = mono_thread_current ();
2048
2049         MONO_ARCH_SAVE_REGS;
2050
2051         ensure_synch_cs_set (thread);
2052         
2053         EnterCriticalSection (thread->synch_cs);
2054
2055         thread->state &= ~ThreadState_AbortRequested;
2056         
2057         if (!thread->abort_exc) {
2058                 const char *msg = "Unable to reset abort because no abort was requested";
2059                 LeaveCriticalSection (thread->synch_cs);
2060                 mono_raise_exception (mono_get_exception_thread_state (msg));
2061         } else {
2062                 thread->abort_exc = NULL;
2063                 thread->abort_state = NULL;
2064         }
2065         
2066         LeaveCriticalSection (thread->synch_cs);
2067 }
2068
2069 static gboolean
2070 mono_thread_suspend (MonoThread *thread)
2071 {
2072         MONO_ARCH_SAVE_REGS;
2073
2074         ensure_synch_cs_set (thread);
2075         
2076         EnterCriticalSection (thread->synch_cs);
2077
2078         if ((thread->state & ThreadState_Unstarted) != 0 || 
2079                 (thread->state & ThreadState_Aborted) != 0 || 
2080                 (thread->state & ThreadState_Stopped) != 0)
2081         {
2082                 LeaveCriticalSection (thread->synch_cs);
2083                 return FALSE;
2084         }
2085
2086         if ((thread->state & ThreadState_Suspended) != 0 || 
2087                 (thread->state & ThreadState_SuspendRequested) != 0 ||
2088                 (thread->state & ThreadState_StopRequested) != 0) 
2089         {
2090                 LeaveCriticalSection (thread->synch_cs);
2091                 return TRUE;
2092         }
2093         
2094         thread->state |= ThreadState_SuspendRequested;
2095
2096         LeaveCriticalSection (thread->synch_cs);
2097
2098         signal_thread_state_change (thread);
2099         return TRUE;
2100 }
2101
2102 void
2103 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2104 {
2105         if (!mono_thread_suspend (thread))
2106                 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2107 }
2108
2109 static gboolean
2110 mono_thread_resume (MonoThread *thread)
2111 {
2112         MONO_ARCH_SAVE_REGS;
2113
2114         ensure_synch_cs_set (thread);
2115         
2116         EnterCriticalSection (thread->synch_cs);
2117
2118         if ((thread->state & ThreadState_SuspendRequested) != 0) {
2119                 thread->state &= ~ThreadState_SuspendRequested;
2120                 LeaveCriticalSection (thread->synch_cs);
2121                 return TRUE;
2122         }
2123
2124         if ((thread->state & ThreadState_Suspended) == 0 ||
2125                 (thread->state & ThreadState_Unstarted) != 0 || 
2126                 (thread->state & ThreadState_Aborted) != 0 || 
2127                 (thread->state & ThreadState_Stopped) != 0)
2128         {
2129                 LeaveCriticalSection (thread->synch_cs);
2130                 return FALSE;
2131         }
2132         
2133         thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2134         if (thread->resume_event == NULL) {
2135                 LeaveCriticalSection (thread->synch_cs);
2136                 return(FALSE);
2137         }
2138         
2139         /* Awake the thread */
2140         SetEvent (thread->suspend_event);
2141
2142         LeaveCriticalSection (thread->synch_cs);
2143
2144         /* Wait for the thread to awake */
2145         WaitForSingleObject (thread->resume_event, INFINITE);
2146         CloseHandle (thread->resume_event);
2147         thread->resume_event = NULL;
2148
2149         return TRUE;
2150 }
2151
2152 void
2153 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2154 {
2155         if (!mono_thread_resume (thread))
2156                 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2157 }
2158
2159 static gboolean
2160 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2161 {
2162         if (managed)
2163                 return TRUE;
2164
2165         if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2166                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2167                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH) 
2168         {
2169                 *((gboolean*)data) = TRUE;
2170                 return TRUE;
2171         }
2172         return FALSE;
2173 }
2174
2175 static gboolean 
2176 is_running_protected_wrapper (void)
2177 {
2178         gboolean found = FALSE;
2179         mono_stack_walk (find_wrapper, &found);
2180         return found;
2181 }
2182
2183 void mono_thread_stop (MonoThread *thread)
2184 {
2185         ensure_synch_cs_set (thread);
2186         
2187         EnterCriticalSection (thread->synch_cs);
2188
2189         if ((thread->state & ThreadState_StopRequested) != 0 ||
2190                 (thread->state & ThreadState_Stopped) != 0)
2191         {
2192                 LeaveCriticalSection (thread->synch_cs);
2193                 return;
2194         }
2195         
2196         /* Make sure the thread is awake */
2197         mono_thread_resume (thread);
2198
2199         thread->state |= ThreadState_StopRequested;
2200         thread->state &= ~ThreadState_AbortRequested;
2201         
2202         LeaveCriticalSection (thread->synch_cs);
2203         
2204         signal_thread_state_change (thread);
2205 }
2206
2207 gint8
2208 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2209 {
2210         return *((volatile gint8 *) (ptr));
2211 }
2212
2213 gint16
2214 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2215 {
2216         return *((volatile gint16 *) (ptr));
2217 }
2218
2219 gint32
2220 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2221 {
2222         return *((volatile gint32 *) (ptr));
2223 }
2224
2225 gint64
2226 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2227 {
2228         return *((volatile gint64 *) (ptr));
2229 }
2230
2231 void *
2232 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2233 {
2234         return (void *)  *((volatile void **) ptr);
2235 }
2236
2237 void
2238 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2239 {
2240         *((volatile gint8 *) ptr) = value;
2241 }
2242
2243 void
2244 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2245 {
2246         *((volatile gint16 *) ptr) = value;
2247 }
2248
2249 void
2250 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2251 {
2252         *((volatile gint32 *) ptr) = value;
2253 }
2254
2255 void
2256 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2257 {
2258         *((volatile gint64 *) ptr) = value;
2259 }
2260
2261 void
2262 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2263 {
2264         *((volatile void **) ptr) = value;
2265 }
2266
2267 void mono_thread_init (MonoThreadStartCB start_cb,
2268                        MonoThreadAttachCB attach_cb)
2269 {
2270         MONO_GC_REGISTER_ROOT (small_id_table);
2271         InitializeCriticalSection(&threads_mutex);
2272         InitializeCriticalSection(&interlocked_mutex);
2273         InitializeCriticalSection(&contexts_mutex);
2274         InitializeCriticalSection(&delayed_free_table_mutex);
2275         InitializeCriticalSection(&small_id_mutex);
2276         
2277         background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2278         g_assert(background_change_event != NULL);
2279         
2280         mono_init_static_data_info (&thread_static_info);
2281         mono_init_static_data_info (&context_static_info);
2282
2283         current_object_key=TlsAlloc();
2284         THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2285
2286         mono_thread_start_cb = start_cb;
2287         mono_thread_attach_cb = attach_cb;
2288
2289         delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2290
2291         /* Get a pseudo handle to the current process.  This is just a
2292          * kludge so that wapi can build a process handle if needed.
2293          * As a pseudo handle is returned, we don't need to clean
2294          * anything up.
2295          */
2296         GetCurrentProcess ();
2297 }
2298
2299 void mono_thread_cleanup (void)
2300 {
2301 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2302         /* The main thread must abandon any held mutexes (particularly
2303          * important for named mutexes as they are shared across
2304          * processes, see bug 74680.)  This will happen when the
2305          * thread exits, but if it's not running in a subthread it
2306          * won't exit in time.
2307          */
2308         /* Using non-w32 API is a nasty kludge, but I couldn't find
2309          * anything in the documentation that would let me do this
2310          * here yet still be safe to call on windows.
2311          */
2312         _wapi_thread_signal_self (mono_environment_exitcode_get ());
2313 #endif
2314
2315 #if 0
2316         /* This stuff needs more testing, it seems one of these
2317          * critical sections can be locked when mono_thread_cleanup is
2318          * called.
2319          */
2320         DeleteCriticalSection (&threads_mutex);
2321         DeleteCriticalSection (&interlocked_mutex);
2322         DeleteCriticalSection (&contexts_mutex);
2323         DeleteCriticalSection (&delayed_free_table_mutex);
2324         DeleteCriticalSection (&small_id_mutex);
2325         CloseHandle (background_change_event);
2326 #endif
2327
2328         g_array_free (delayed_free_table, TRUE);
2329
2330         TlsFree (current_object_key);
2331 }
2332
2333 void
2334 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2335 {
2336         mono_thread_cleanup_fn = func;
2337 }
2338
2339 void
2340 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2341 {
2342         thread->manage_callback = func;
2343 }
2344
2345 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2346 {
2347         mono_thread_notify_pending_exc_fn = func;
2348 }
2349
2350 G_GNUC_UNUSED
2351 static void print_tids (gpointer key, gpointer value, gpointer user)
2352 {
2353         /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2354          * sizeof(uint) and a cast to uint would overflow
2355          */
2356         /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2357          * print this as a pointer.
2358          */
2359         g_message ("Waiting for: %p", key);
2360 }
2361
2362 struct wait_data 
2363 {
2364         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2365         MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2366         guint32 num;
2367 };
2368
2369 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2370 {
2371         guint32 i, ret;
2372         
2373         THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2374
2375         ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2376
2377         if(ret==WAIT_FAILED) {
2378                 /* See the comment in build_wait_tids() */
2379                 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2380                 return;
2381         }
2382         
2383         for(i=0; i<wait->num; i++)
2384                 CloseHandle (wait->handles[i]);
2385
2386         if (ret == WAIT_TIMEOUT)
2387                 return;
2388
2389         for(i=0; i<wait->num; i++) {
2390                 gsize tid = wait->threads[i]->tid;
2391                 
2392                 mono_threads_lock ();
2393                 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2394                         /* This thread must have been killed, because
2395                          * it hasn't cleaned itself up. (It's just
2396                          * possible that the thread exited before the
2397                          * parent thread had a chance to store the
2398                          * handle, and now there is another pointer to
2399                          * the already-exited thread stored.  In this
2400                          * case, we'll just get two
2401                          * mono_profiler_thread_end() calls for the
2402                          * same thread.)
2403                          */
2404         
2405                         mono_threads_unlock ();
2406                         THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2407                         thread_cleanup (wait->threads[i]);
2408                 } else {
2409                         mono_threads_unlock ();
2410                 }
2411         }
2412 }
2413
2414 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2415 {
2416         guint32 i, ret, count;
2417         
2418         THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2419
2420         /* Add the thread state change event, so it wakes up if a thread changes
2421          * to background mode.
2422          */
2423         count = wait->num;
2424         if (count < MAXIMUM_WAIT_OBJECTS) {
2425                 wait->handles [count] = background_change_event;
2426                 count++;
2427         }
2428
2429         ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2430
2431         if(ret==WAIT_FAILED) {
2432                 /* See the comment in build_wait_tids() */
2433                 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2434                 return;
2435         }
2436         
2437         for(i=0; i<wait->num; i++)
2438                 CloseHandle (wait->handles[i]);
2439
2440         if (ret == WAIT_TIMEOUT)
2441                 return;
2442         
2443         if (ret < wait->num) {
2444                 gsize tid = wait->threads[ret]->tid;
2445                 mono_threads_lock ();
2446                 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2447                         /* See comment in wait_for_tids about thread cleanup */
2448                         mono_threads_unlock ();
2449                         THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2450                         thread_cleanup (wait->threads [ret]);
2451                 } else
2452                         mono_threads_unlock ();
2453         }
2454 }
2455
2456 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2457 {
2458         struct wait_data *wait=(struct wait_data *)user;
2459
2460         if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2461                 HANDLE handle;
2462                 MonoThread *thread=(MonoThread *)value;
2463
2464                 /* Ignore background threads, we abort them later */
2465                 /* Do not lock here since it is not needed and the caller holds threads_lock */
2466                 if (thread->state & ThreadState_Background) {
2467                         THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2468                         return; /* just leave, ignore */
2469                 }
2470                 
2471                 if (mono_gc_is_finalizer_thread (thread)) {
2472                         THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2473                         return;
2474                 }
2475
2476                 if (thread == mono_thread_current ()) {
2477                         THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2478                         return;
2479                 }
2480
2481                 if (thread == mono_thread_get_main ()) {
2482                         THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2483                         return;
2484                 }
2485
2486                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2487                 if (handle == NULL) {
2488                         THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2489                         return;
2490                 }
2491                 
2492                 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2493                 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2494                         wait->handles[wait->num]=handle;
2495                         wait->threads[wait->num]=thread;
2496                         wait->num++;
2497
2498                         THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2499                 } else {
2500                         THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2501                 }
2502                 
2503                 
2504         } else {
2505                 /* Just ignore the rest, we can't do anything with
2506                  * them yet
2507                  */
2508         }
2509 }
2510
2511 static gboolean
2512 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2513 {
2514         struct wait_data *wait=(struct wait_data *)user;
2515         gsize self = GetCurrentThreadId ();
2516         MonoThread *thread = (MonoThread *) value;
2517         HANDLE handle;
2518
2519         if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2520                 return FALSE;
2521
2522         /* The finalizer thread is not a background thread */
2523         if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2524         
2525                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2526                 if (handle == NULL)
2527                         return FALSE;
2528
2529                 /* printf ("A: %d\n", wait->num); */
2530                 wait->handles[wait->num]=thread->handle;
2531                 wait->threads[wait->num]=thread;
2532                 wait->num++;
2533
2534                 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2535                 mono_thread_stop (thread);
2536                 return TRUE;
2537         }
2538
2539         return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
2540 }
2541
2542 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
2543
2544 /** 
2545  * mono_threads_set_shutting_down:
2546  *
2547  * Is called by a thread that wants to shut down Mono. If the runtime is already
2548  * shutting down, the calling thread is suspended/stopped, and this function never
2549  * returns.
2550  */
2551 void
2552 mono_threads_set_shutting_down (void)
2553 {
2554         MonoThread *current_thread = mono_thread_current ();
2555
2556         mono_threads_lock ();
2557
2558         if (shutting_down) {
2559                 mono_threads_unlock ();
2560
2561                 /* Make sure we're properly suspended/stopped */
2562
2563                 EnterCriticalSection (current_thread->synch_cs);
2564
2565                 if ((current_thread->state & ThreadState_SuspendRequested) ||
2566                     (current_thread->state & ThreadState_AbortRequested) ||
2567                     (current_thread->state & ThreadState_StopRequested)) {
2568                         LeaveCriticalSection (current_thread->synch_cs);
2569                         mono_thread_execute_interruption (current_thread);
2570                 } else {
2571                         current_thread->state |= ThreadState_Stopped;
2572                         LeaveCriticalSection (current_thread->synch_cs);
2573                 }
2574
2575                 /* Wake up other threads potentially waiting for us */
2576                 ExitThread (0);
2577         } else {
2578                 shutting_down = TRUE;
2579
2580                 /* Not really a background state change, but this will
2581                  * interrupt the main thread if it is waiting for all
2582                  * the other threads.
2583                  */
2584                 SetEvent (background_change_event);
2585                 
2586                 mono_threads_unlock ();
2587         }
2588 }
2589
2590 /** 
2591  * mono_threads_is_shutting_down:
2592  *
2593  * Returns whether a thread has commenced shutdown of Mono.  Note that
2594  * if the function returns FALSE the caller must not assume that
2595  * shutdown is not in progress, because the situation might have
2596  * changed since the function returned.  For that reason this function
2597  * is of very limited utility.
2598  */
2599 gboolean
2600 mono_threads_is_shutting_down (void)
2601 {
2602         return shutting_down;
2603 }
2604
2605 void mono_thread_manage (void)
2606 {
2607         struct wait_data *wait=g_new0 (struct wait_data, 1);
2608
2609         /* join each thread that's still running */
2610         THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2611         
2612         mono_threads_lock ();
2613         if(threads==NULL) {
2614                 THREAD_DEBUG (g_message("%s: No threads", __func__));
2615                 mono_threads_unlock ();
2616                 return;
2617         }
2618         mono_threads_unlock ();
2619         
2620         do {
2621                 mono_threads_lock ();
2622                 if (shutting_down) {
2623                         /* somebody else is shutting down */
2624                         mono_threads_unlock ();
2625                         break;
2626                 }
2627                 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2628                         mono_g_hash_table_foreach (threads, print_tids, NULL));
2629         
2630                 ResetEvent (background_change_event);
2631                 wait->num=0;
2632                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2633                 mono_threads_unlock ();
2634                 if(wait->num>0) {
2635                         /* Something to wait for */
2636                         wait_for_tids_or_state_change (wait, INFINITE);
2637                 }
2638                 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2639         } while(wait->num>0);
2640
2641         mono_threads_set_shutting_down ();
2642
2643         /* No new threads will be created after this point */
2644
2645         mono_runtime_set_shutting_down ();
2646
2647         THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2648         mono_thread_pool_cleanup ();
2649
2650         /* 
2651          * Remove everything but the finalizer thread and self.
2652          * Also abort all the background threads
2653          * */
2654         do {
2655                 mono_threads_lock ();
2656
2657                 wait->num = 0;
2658                 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2659
2660                 mono_threads_unlock ();
2661
2662                 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2663                 if(wait->num>0) {
2664                         /* Something to wait for */
2665                         wait_for_tids (wait, INFINITE);
2666                 }
2667         } while (wait->num > 0);
2668         
2669         /* 
2670          * give the subthreads a chance to really quit (this is mainly needed
2671          * to get correct user and system times from getrusage/wait/time(1)).
2672          * This could be removed if we avoid pthread_detach() and use pthread_join().
2673          */
2674 #ifndef PLATFORM_WIN32
2675         sched_yield ();
2676 #endif
2677
2678         g_free (wait);
2679 }
2680
2681 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2682 {
2683         MonoThread *thread=(MonoThread *)value;
2684         
2685         if(thread->tid != (gsize)user) {
2686                 /*TerminateThread (thread->handle, -1);*/
2687         }
2688 }
2689
2690 void mono_thread_abort_all_other_threads (void)
2691 {
2692         gsize self = GetCurrentThreadId ();
2693
2694         mono_threads_lock ();
2695         THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2696                                  mono_g_hash_table_size (threads));
2697                       mono_g_hash_table_foreach (threads, print_tids, NULL));
2698
2699         mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2700         
2701         mono_threads_unlock ();
2702 }
2703
2704 static void
2705 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2706 {
2707         MonoThread *thread = (MonoThread*)value;
2708         struct wait_data *wait = (struct wait_data*)user_data;
2709         HANDLE handle;
2710
2711         /* 
2712          * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2713          * limitation.
2714          * This needs no locking.
2715          */
2716         if ((thread->state & ThreadState_Suspended) != 0 || 
2717                 (thread->state & ThreadState_Stopped) != 0)
2718                 return;
2719
2720         if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2721                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2722                 if (handle == NULL)
2723                         return;
2724
2725                 wait->handles [wait->num] = handle;
2726                 wait->threads [wait->num] = thread;
2727                 wait->num++;
2728         }
2729 }
2730
2731 /*
2732  * mono_thread_suspend_all_other_threads:
2733  *
2734  *  Suspend all managed threads except the finalizer thread and this thread. It is
2735  * not possible to resume them later.
2736  */
2737 void mono_thread_suspend_all_other_threads (void)
2738 {
2739         struct wait_data *wait = g_new0 (struct wait_data, 1);
2740         int i;
2741         gsize self = GetCurrentThreadId ();
2742         gpointer *events;
2743         guint32 eventidx = 0;
2744         gboolean starting, finished;
2745
2746         /*
2747          * The other threads could be in an arbitrary state at this point, i.e.
2748          * they could be starting up, shutting down etc. This means that there could be
2749          * threads which are not even in the threads hash table yet.
2750          */
2751
2752         /* 
2753          * First we set a barrier which will be checked by all threads before they
2754          * are added to the threads hash table, and they will exit if the flag is set.
2755          * This ensures that no threads could be added to the hash later.
2756          * We will use shutting_down as the barrier for now.
2757          */
2758         g_assert (shutting_down);
2759
2760         /*
2761          * We make multiple calls to WaitForMultipleObjects since:
2762          * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2763          * - some threads could exit without becoming suspended
2764          */
2765         finished = FALSE;
2766         while (!finished) {
2767                 /*
2768                  * Make a copy of the hashtable since we can't do anything with
2769                  * threads while threads_mutex is held.
2770                  */
2771                 wait->num = 0;
2772                 mono_threads_lock ();
2773                 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2774                 mono_threads_unlock ();
2775
2776                 events = g_new0 (gpointer, wait->num);
2777                 eventidx = 0;
2778                 /* Get the suspended events that we'll be waiting for */
2779                 for (i = 0; i < wait->num; ++i) {
2780                         MonoThread *thread = wait->threads [i];
2781
2782                         if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2783                                 //CloseHandle (wait->handles [i]);
2784                                 wait->threads [i] = NULL; /* ignore this thread in next loop */
2785                                 continue;
2786                         }
2787
2788                         ensure_synch_cs_set (thread);
2789                 
2790                         EnterCriticalSection (thread->synch_cs);
2791
2792                         if ((thread->state & ThreadState_Suspended) != 0 || 
2793                                 (thread->state & ThreadState_SuspendRequested) != 0 ||
2794                                 (thread->state & ThreadState_StopRequested) != 0 ||
2795                                 (thread->state & ThreadState_Stopped) != 0) {
2796                                 LeaveCriticalSection (thread->synch_cs);
2797                                 CloseHandle (wait->handles [i]);
2798                                 wait->threads [i] = NULL; /* ignore this thread in next loop */
2799                                 continue;
2800                         }
2801
2802                         /* Convert abort requests into suspend requests */
2803                         if ((thread->state & ThreadState_AbortRequested) != 0)
2804                                 thread->state &= ~ThreadState_AbortRequested;
2805                         
2806                         thread->state |= ThreadState_SuspendRequested;
2807
2808                         if (thread->suspended_event == NULL) {
2809                                 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2810                                 if (thread->suspended_event == NULL) {
2811                                         /* Forget this one and go on to the next */
2812                                         LeaveCriticalSection (thread->synch_cs);
2813                                         continue;
2814                                 }
2815                         }
2816
2817                         events [eventidx++] = thread->suspended_event;
2818                         LeaveCriticalSection (thread->synch_cs);
2819
2820                         /* Signal the thread to suspend */
2821                         signal_thread_state_change (thread);
2822                 }
2823
2824                 if (eventidx > 0) {
2825                         WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2826                         for (i = 0; i < wait->num; ++i) {
2827                                 MonoThread *thread = wait->threads [i];
2828
2829                                 if (thread == NULL)
2830                                         continue;
2831                         
2832                                 EnterCriticalSection (thread->synch_cs);
2833                                 if ((thread->state & ThreadState_Suspended) != 0) {
2834                                         CloseHandle (thread->suspended_event);
2835                                         thread->suspended_event = NULL;
2836                                 }
2837                                 LeaveCriticalSection (thread->synch_cs);
2838                         }
2839                 } else {
2840                         /* 
2841                          * If there are threads which are starting up, we wait until they
2842                          * are suspended when they try to register in the threads hash.
2843                          * This is guaranteed to finish, since the threads which can create new
2844                          * threads get suspended after a while.
2845                          * FIXME: The finalizer thread can still create new threads.
2846                          */
2847                         mono_threads_lock ();
2848                         starting = mono_g_hash_table_size (threads_starting_up) > 0;
2849                         mono_threads_unlock ();
2850                         if (starting)
2851                                 Sleep (100);
2852                         else
2853                                 finished = TRUE;
2854                 }
2855
2856                 g_free (events);
2857         }
2858
2859         g_free (wait);
2860 }
2861
2862 static void
2863 collect_threads (gpointer key, gpointer value, gpointer user_data)
2864 {
2865         MonoThread *thread = (MonoThread*)value;
2866         struct wait_data *wait = (struct wait_data*)user_data;
2867         HANDLE handle;
2868
2869         if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2870                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2871                 if (handle == NULL)
2872                         return;
2873
2874                 wait->handles [wait->num] = handle;
2875                 wait->threads [wait->num] = thread;
2876                 wait->num++;
2877         }
2878 }
2879
2880 /**
2881  * mono_threads_request_thread_dump:
2882  *
2883  *   Ask all threads except the current to print their stacktrace to stdout.
2884  */
2885 void
2886 mono_threads_request_thread_dump (void)
2887 {
2888         struct wait_data *wait = g_new0 (struct wait_data, 1);
2889         int i;
2890
2891         /* 
2892          * Make a copy of the hashtable since we can't do anything with
2893          * threads while threads_mutex is held.
2894          */
2895         mono_threads_lock ();
2896         mono_g_hash_table_foreach (threads, collect_threads, wait);
2897         mono_threads_unlock ();
2898
2899         for (i = 0; i < wait->num; ++i) {
2900                 MonoThread *thread = wait->threads [i];
2901
2902                 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2903                         thread->thread_dump_requested = TRUE;
2904
2905                         signal_thread_state_change (thread);
2906                 }
2907
2908                 CloseHandle (wait->handles [i]);
2909         }
2910 }
2911
2912 /*
2913  * mono_thread_push_appdomain_ref:
2914  *
2915  *   Register that the current thread may have references to objects in domain 
2916  * @domain on its stack. Each call to this function should be paired with a 
2917  * call to pop_appdomain_ref.
2918  */
2919 void 
2920 mono_thread_push_appdomain_ref (MonoDomain *domain)
2921 {
2922         MonoThread *thread = mono_thread_current ();
2923
2924         if (thread) {
2925                 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2926                 mono_threads_lock ();
2927                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2928                 mono_threads_unlock ();
2929         }
2930 }
2931
2932 void
2933 mono_thread_pop_appdomain_ref (void)
2934 {
2935         MonoThread *thread = mono_thread_current ();
2936
2937         if (thread) {
2938                 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2939                 mono_threads_lock ();
2940                 /* FIXME: How can the list be empty ? */
2941                 if (thread->appdomain_refs)
2942                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2943                 mono_threads_unlock ();
2944         }
2945 }
2946
2947 gboolean
2948 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2949 {
2950         gboolean res;
2951         mono_threads_lock ();
2952         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2953         mono_threads_unlock ();
2954         return res;
2955 }
2956
2957 typedef struct abort_appdomain_data {
2958         struct wait_data wait;
2959         MonoDomain *domain;
2960 } abort_appdomain_data;
2961
2962 static void
2963 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2964 {
2965         MonoThread *thread = (MonoThread*)value;
2966         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2967         MonoDomain *domain = data->domain;
2968
2969         if (mono_thread_has_appdomain_ref (thread, domain)) {
2970                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2971
2972                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2973
2974                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2975                         HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2976                         if (handle == NULL)
2977                                 return;
2978                         data->wait.handles [data->wait.num] = handle;
2979                         data->wait.threads [data->wait.num] = thread;
2980                         data->wait.num++;
2981                 } else {
2982                         /* Just ignore the rest, we can't do anything with
2983                          * them yet
2984                          */
2985                 }
2986         }
2987 }
2988
2989 /*
2990  * mono_threads_abort_appdomain_threads:
2991  *
2992  *   Abort threads which has references to the given appdomain.
2993  */
2994 gboolean
2995 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2996 {
2997         abort_appdomain_data user_data;
2998         guint32 start_time;
2999
3000         THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3001
3002         start_time = mono_msec_ticks ();
3003         do {
3004                 mono_threads_lock ();
3005
3006                 user_data.domain = domain;
3007                 user_data.wait.num = 0;
3008                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
3009                 mono_threads_unlock ();
3010
3011                 if (user_data.wait.num > 0)
3012                         /*
3013                          * We should wait for the threads either to abort, or to leave the
3014                          * domain. We can't do the latter, so we wait with a timeout.
3015                          */
3016                         wait_for_tids (&user_data.wait, 100);
3017
3018                 /* Update remaining time */
3019                 timeout -= mono_msec_ticks () - start_time;
3020                 start_time = mono_msec_ticks ();
3021
3022                 if (timeout < 0)
3023                         return FALSE;
3024         }
3025         while (user_data.wait.num > 0);
3026
3027         THREAD_DEBUG (g_message ("%s: abort done", __func__));
3028
3029         return TRUE;
3030 }
3031
3032 static void
3033 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3034 {
3035         MonoThread *thread = (MonoThread*)value;
3036         MonoDomain *domain = (MonoDomain*)user_data;
3037         int i;
3038
3039         /* No locking needed here */
3040         /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3041
3042         if (thread->cached_culture_info) {
3043                 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3044                         MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3045                         if (obj && obj->vtable->domain == domain)
3046                                 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3047                 }
3048         }
3049 }
3050         
3051 /*
3052  * mono_threads_clear_cached_culture:
3053  *
3054  *   Clear the cached_current_culture from all threads if it is in the
3055  * given appdomain.
3056  */
3057 void
3058 mono_threads_clear_cached_culture (MonoDomain *domain)
3059 {
3060         mono_threads_lock ();
3061         mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3062         mono_threads_unlock ();
3063 }
3064
3065 /*
3066  * mono_thread_get_undeniable_exception:
3067  *
3068  *   Return an exception which needs to be raised when leaving a catch clause.
3069  * This is used for undeniable exception propagation.
3070  */
3071 MonoException*
3072 mono_thread_get_undeniable_exception (void)
3073 {
3074         MonoThread *thread = mono_thread_current ();
3075
3076         MONO_ARCH_SAVE_REGS;
3077
3078         if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3079                 /*
3080                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
3081                  * exception if the thread no longer references a dying appdomain.
3082                  */
3083                 thread->abort_exc->trace_ips = NULL;
3084                 thread->abort_exc->stack_trace = NULL;
3085                 return thread->abort_exc;
3086         }
3087
3088         return NULL;
3089 }
3090
3091 #define NUM_STATIC_DATA_IDX 8
3092 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3093         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3094 };
3095
3096
3097 /*
3098  *  mono_alloc_static_data
3099  *
3100  *   Allocate memory blocks for storing threads or context static data
3101  */
3102 static void 
3103 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3104 {
3105         guint idx = (offset >> 24) - 1;
3106         int i;
3107
3108         gpointer* static_data = *static_data_ptr;
3109         if (!static_data) {
3110                 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3111                 *static_data_ptr = static_data;
3112                 static_data [0] = static_data;
3113         }
3114
3115         for (i = 1; i <= idx; ++i) {
3116                 if (static_data [i])
3117                         continue;
3118                 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3119         }
3120 }
3121
3122 /*
3123  *  mono_init_static_data_info
3124  *
3125  *   Initializes static data counters
3126  */
3127 static void mono_init_static_data_info (StaticDataInfo *static_data)
3128 {
3129         static_data->idx = 0;
3130         static_data->offset = 0;
3131         static_data->freelist = NULL;
3132 }
3133
3134 /*
3135  *  mono_alloc_static_data_slot
3136  *
3137  *   Generates an offset for static data. static_data contains the counters
3138  *  used to generate it.
3139  */
3140 static guint32
3141 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3142 {
3143         guint32 offset;
3144
3145         if (!static_data->idx && !static_data->offset) {
3146                 /* 
3147                  * we use the first chunk of the first allocation also as
3148                  * an array for the rest of the data 
3149                  */
3150                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3151         }
3152         static_data->offset += align - 1;
3153         static_data->offset &= ~(align - 1);
3154         if (static_data->offset + size >= static_data_size [static_data->idx]) {
3155                 static_data->idx ++;
3156                 g_assert (size <= static_data_size [static_data->idx]);
3157                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3158                 static_data->offset = 0;
3159         }
3160         offset = static_data->offset | ((static_data->idx + 1) << 24);
3161         static_data->offset += size;
3162         return offset;
3163 }
3164
3165 /* 
3166  * ensure thread static fields already allocated are valid for thread
3167  * This function is called when a thread is created or on thread attach.
3168  */
3169 static void
3170 thread_adjust_static_data (MonoThread *thread)
3171 {
3172         guint32 offset;
3173
3174         mono_threads_lock ();
3175         if (thread_static_info.offset || thread_static_info.idx > 0) {
3176                 /* get the current allocated size */
3177                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3178                 mono_alloc_static_data (&(thread->static_data), offset);
3179         }
3180         mono_threads_unlock ();
3181 }
3182
3183 static void 
3184 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3185 {
3186         MonoThread *thread = value;
3187         guint32 offset = GPOINTER_TO_UINT (user);
3188         
3189         mono_alloc_static_data (&(thread->static_data), offset);
3190 }
3191
3192 static MonoThreadDomainTls*
3193 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3194 {
3195         MonoThreadDomainTls* prev = NULL;
3196         MonoThreadDomainTls* tmp = static_data->freelist;
3197         while (tmp) {
3198                 if (tmp->size == size) {
3199                         if (prev)
3200                                 prev->next = tmp->next;
3201                         else
3202                                 static_data->freelist = tmp->next;
3203                         return tmp;
3204                 }
3205                 tmp = tmp->next;
3206         }
3207         return NULL;
3208 }
3209
3210 /*
3211  * The offset for a special static variable is composed of three parts:
3212  * a bit that indicates the type of static data (0:thread, 1:context),
3213  * an index in the array of chunks of memory for the thread (thread->static_data)
3214  * and an offset in that chunk of mem. This allows allocating less memory in the 
3215  * common case.
3216  */
3217
3218 guint32
3219 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3220 {
3221         guint32 offset;
3222         if (static_type == SPECIAL_STATIC_THREAD)
3223         {
3224                 MonoThreadDomainTls *item;
3225                 mono_threads_lock ();
3226                 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3227                 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3228                 if (item) {
3229                         offset = item->offset;
3230                         g_free (item);
3231                 } else {
3232                         offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3233                 }
3234                 /* This can be called during startup */
3235                 if (threads != NULL)
3236                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3237                 mono_threads_unlock ();
3238         }
3239         else
3240         {
3241                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3242                 mono_contexts_lock ();
3243                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3244                 mono_contexts_unlock ();
3245                 offset |= 0x80000000;   /* Set the high bit to indicate context static data */
3246         }
3247         return offset;
3248 }
3249
3250 gpointer
3251 mono_get_special_static_data (guint32 offset)
3252 {
3253         /* The high bit means either thread (0) or static (1) data. */
3254
3255         guint32 static_type = (offset & 0x80000000);
3256         int idx;
3257
3258         offset &= 0x7fffffff;
3259         idx = (offset >> 24) - 1;
3260
3261         if (static_type == 0)
3262         {
3263                 MonoThread *thread = mono_thread_current ();
3264                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3265         }
3266         else
3267         {
3268                 /* Allocate static data block under demand, since we don't have a list
3269                 // of contexts
3270                 */
3271                 MonoAppContext *context = mono_context_get ();
3272                 if (!context->static_data || !context->static_data [idx]) {
3273                         mono_contexts_lock ();
3274                         mono_alloc_static_data (&(context->static_data), offset);
3275                         mono_contexts_unlock ();
3276                 }
3277                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
3278         }
3279 }
3280
3281 typedef struct {
3282         guint32 offset;
3283         guint32 size;
3284 } TlsOffsetSize;
3285
3286 static void 
3287 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3288 {
3289         MonoThread *thread = value;
3290         TlsOffsetSize *data = user;
3291         int idx = (data->offset >> 24) - 1;
3292         char *ptr;
3293
3294         if (!thread->static_data || !thread->static_data [idx])
3295                 return;
3296         ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3297         memset (ptr, 0, data->size);
3298 }
3299
3300 static void
3301 do_free_special (gpointer key, gpointer value, gpointer data)
3302 {
3303         MonoClassField *field = key;
3304         guint32 offset = GPOINTER_TO_UINT (value);
3305         guint32 static_type = (offset & 0x80000000);
3306         gint32 align;
3307         guint32 size;
3308         size = mono_type_size (field->type, &align);
3309         /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3310         if (static_type == 0) {
3311                 TlsOffsetSize data;
3312                 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3313                 data.offset = offset & 0x7fffffff;
3314                 data.size = size;
3315                 if (threads != NULL)
3316                         mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3317                 item->offset = offset;
3318                 item->size = size;
3319                 item->next = thread_static_info.freelist;
3320                 thread_static_info.freelist = item;
3321         } else {
3322                 /* FIXME: free context static data as well */
3323         }
3324 }
3325
3326 void
3327 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3328 {
3329         mono_threads_lock ();
3330         g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3331         mono_threads_unlock ();
3332 }
3333
3334 static MonoClassField *local_slots = NULL;
3335
3336 typedef struct {
3337         /* local tls data to get locals_slot from a thread */
3338         guint32 offset;
3339         int idx;
3340         /* index in the locals_slot array */
3341         int slot;
3342 } LocalSlotID;
3343
3344 static void
3345 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3346 {
3347         LocalSlotID *sid = user_data;
3348         MonoThread *thread = (MonoThread*)value;
3349         MonoArray *slots_array;
3350         /*
3351          * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3352          * it is for the right domain, so we need to check if it is allocated an initialized
3353          * for the current thread.
3354          */
3355         /*g_print ("handling thread %p\n", thread);*/
3356         if (!thread->static_data || !thread->static_data [sid->idx])
3357                 return;
3358         slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3359         if (!slots_array || sid->slot >= mono_array_length (slots_array))
3360                 return;
3361         mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3362 }
3363
3364 void
3365 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3366 {
3367         MonoDomain *domain;
3368         LocalSlotID sid;
3369         sid.slot = slot;
3370         if (thread_local) {
3371                 void *addr = NULL;
3372                 if (!local_slots) {
3373                         local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3374                         if (!local_slots) {
3375                                 g_warning ("local_slots field not found in Thread class");
3376                                 return;
3377                         }
3378                 }
3379                 domain = mono_domain_get ();
3380                 mono_domain_lock (domain);
3381                 if (domain->special_static_fields)
3382                         addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3383                 mono_domain_unlock (domain);
3384                 if (!addr)
3385                         return;
3386                 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3387                 sid.offset = GPOINTER_TO_UINT (addr);
3388                 sid.offset &= 0x7fffffff;
3389                 sid.idx = (sid.offset >> 24) - 1;
3390                 mono_threads_lock ();
3391                 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3392                 mono_threads_unlock ();
3393         } else {
3394                 /* FIXME: clear the slot for MonoAppContexts, too */
3395         }
3396 }
3397
3398 #ifdef PLATFORM_WIN32
3399 static void CALLBACK dummy_apc (ULONG_PTR param)
3400 {
3401 }
3402 #else
3403 static guint32 dummy_apc (gpointer param)
3404 {
3405         return 0;
3406 }
3407 #endif
3408
3409 /*
3410  * mono_thread_execute_interruption
3411  * 
3412  * Performs the operation that the requested thread state requires (abort,
3413  * suspend or stop)
3414  */
3415 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3416 {
3417         ensure_synch_cs_set (thread);
3418         
3419         EnterCriticalSection (thread->synch_cs);
3420
3421         if (thread->interruption_requested) {
3422                 /* this will consume pending APC calls */
3423                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3424                 InterlockedDecrement (&thread_interruption_requested);
3425                 thread->interruption_requested = FALSE;
3426         }
3427
3428         if ((thread->state & ThreadState_AbortRequested) != 0) {
3429                 if (thread->abort_exc == NULL)
3430                         MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3431                 LeaveCriticalSection (thread->synch_cs);
3432                 return thread->abort_exc;
3433         }
3434         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3435                 thread->state &= ~ThreadState_SuspendRequested;
3436                 thread->state |= ThreadState_Suspended;
3437                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3438                 if (thread->suspend_event == NULL) {
3439                         LeaveCriticalSection (thread->synch_cs);
3440                         return(NULL);
3441                 }
3442                 if (thread->suspended_event)
3443                         SetEvent (thread->suspended_event);
3444
3445                 LeaveCriticalSection (thread->synch_cs);
3446
3447                 if (shutting_down) {
3448                         /* After we left the lock, the runtime might shut down so everything becomes invalid */
3449                         for (;;)
3450                                 Sleep (1000);
3451                 }
3452                 
3453                 WaitForSingleObject (thread->suspend_event, INFINITE);
3454                 
3455                 EnterCriticalSection (thread->synch_cs);
3456
3457                 CloseHandle (thread->suspend_event);
3458                 thread->suspend_event = NULL;
3459                 thread->state &= ~ThreadState_Suspended;
3460         
3461                 /* The thread that requested the resume will have replaced this event
3462                  * and will be waiting for it
3463                  */
3464                 SetEvent (thread->resume_event);
3465
3466                 LeaveCriticalSection (thread->synch_cs);
3467                 
3468                 return NULL;
3469         }
3470         else if ((thread->state & ThreadState_StopRequested) != 0) {
3471                 /* FIXME: do this through the JIT? */
3472
3473                 LeaveCriticalSection (thread->synch_cs);
3474                 
3475                 mono_thread_exit ();
3476                 return NULL;
3477         } else if (thread->thread_interrupt_requested) {
3478
3479                 LeaveCriticalSection (thread->synch_cs);
3480                 
3481                 return(mono_get_exception_thread_interrupted ());
3482         }
3483         
3484         LeaveCriticalSection (thread->synch_cs);
3485         
3486         return NULL;
3487 }
3488
3489 /*
3490  * mono_thread_request_interruption
3491  *
3492  * A signal handler can call this method to request the interruption of a
3493  * thread. The result of the interruption will depend on the current state of
3494  * the thread. If the result is an exception that needs to be throw, it is 
3495  * provided as return value.
3496  */
3497 MonoException* mono_thread_request_interruption (gboolean running_managed)
3498 {
3499         MonoThread *thread = mono_thread_current ();
3500
3501         /* The thread may already be stopping */
3502         if (thread == NULL) 
3503                 return NULL;
3504         
3505         ensure_synch_cs_set (thread);
3506
3507         /* FIXME: This is NOT signal safe */
3508         EnterCriticalSection (thread->synch_cs);
3509         
3510         if (thread->interruption_requested) {
3511                 LeaveCriticalSection (thread->synch_cs);
3512                 
3513                 return NULL;
3514         }
3515
3516         if (!running_managed || is_running_protected_wrapper ()) {
3517                 /* Can't stop while in unmanaged code. Increase the global interruption
3518                    request count. When exiting the unmanaged method the count will be
3519                    checked and the thread will be interrupted. */
3520                 
3521                 InterlockedIncrement (&thread_interruption_requested);
3522                 thread->interruption_requested = TRUE;
3523
3524                 LeaveCriticalSection (thread->synch_cs);
3525
3526                 if (mono_thread_notify_pending_exc_fn && !running_managed)
3527                         /* The JIT will notify the thread about the interruption */
3528                         /* This shouldn't take any locks */
3529                         mono_thread_notify_pending_exc_fn ();
3530
3531                 /* this will awake the thread if it is in WaitForSingleObject 
3532                    or similar */
3533                 /* FIXME: This is NOT signal-safe, since it allocates memory and uses locking */
3534                 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3535                 return NULL;
3536         }
3537         else {
3538                 LeaveCriticalSection (thread->synch_cs);
3539                 
3540                 return mono_thread_execute_interruption (thread);
3541         }
3542 }
3543
3544 gboolean mono_thread_interruption_requested ()
3545 {
3546         if (thread_interruption_requested) {
3547                 MonoThread *thread = mono_thread_current ();
3548                 /* The thread may already be stopping */
3549                 if (thread != NULL) 
3550                         return (thread->interruption_requested);
3551         }
3552         return FALSE;
3553 }
3554
3555 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3556 {
3557         MonoThread *thread = mono_thread_current ();
3558
3559         /* The thread may already be stopping */
3560         if (thread == NULL)
3561                 return;
3562
3563         if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3564                 MonoException* exc = mono_thread_execute_interruption (thread);
3565                 if (exc) mono_raise_exception (exc);
3566         }
3567 }
3568
3569 /*
3570  * Performs the interruption of the current thread, if one has been requested,
3571  * and the thread is not running a protected wrapper.
3572  */
3573 void mono_thread_interruption_checkpoint ()
3574 {
3575         mono_thread_interruption_checkpoint_request (FALSE);
3576 }
3577
3578 /*
3579  * Performs the interruption of the current thread, if one has been requested.
3580  */
3581 void mono_thread_force_interruption_checkpoint ()
3582 {
3583         mono_thread_interruption_checkpoint_request (TRUE);
3584 }
3585
3586 /*
3587  * mono_thread_get_and_clear_pending_exception:
3588  *
3589  *   Return any pending exceptions for the current thread and clear it as a side effect.
3590  */
3591 MonoException*
3592 mono_thread_get_and_clear_pending_exception (void)
3593 {
3594         MonoThread *thread = mono_thread_current ();
3595
3596         /* The thread may already be stopping */
3597         if (thread == NULL)
3598                 return NULL;
3599
3600         if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3601                 return mono_thread_execute_interruption (thread);
3602         }
3603         else
3604                 return NULL;
3605 }
3606
3607 /**
3608  * mono_thread_interruption_request_flag:
3609  *
3610  * Returns the address of a flag that will be non-zero if an interruption has
3611  * been requested for a thread. The thread to interrupt may not be the current
3612  * thread, so an additional call to mono_thread_interruption_requested() or
3613  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3614  * zero.
3615  */
3616 gint32* mono_thread_interruption_request_flag ()
3617 {
3618         return &thread_interruption_requested;
3619 }
3620
3621 void 
3622 mono_thread_init_apartment_state (void)
3623 {
3624         MonoThread* thread;
3625         thread = mono_thread_current ();
3626
3627 #ifdef PLATFORM_WIN32
3628         /* Positive return value indicates success, either
3629          * S_OK if this is first CoInitialize call, or
3630          * S_FALSE if CoInitialize already called, but with same
3631          * threading model. A negative value indicates failure,
3632          * probably due to trying to change the threading model.
3633          */
3634         if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA) 
3635                         ? COINIT_APARTMENTTHREADED 
3636                         : COINIT_MULTITHREADED) < 0) {
3637                 thread->apartment_state = ThreadApartmentState_Unknown;
3638         }
3639 #endif
3640 }
3641
3642 void 
3643 mono_thread_cleanup_apartment_state (void)
3644 {
3645 #ifdef PLATFORM_WIN32
3646         MonoThread* thread;
3647         thread = mono_thread_current ();
3648
3649         if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3650                 CoUninitialize ();
3651         }
3652 #endif
3653 }
3654
3655 void
3656 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3657 {
3658         ensure_synch_cs_set (thread);
3659         
3660         EnterCriticalSection (thread->synch_cs);
3661         thread->state |= state;
3662         LeaveCriticalSection (thread->synch_cs);
3663 }
3664
3665 void
3666 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3667 {
3668         ensure_synch_cs_set (thread);
3669         
3670         EnterCriticalSection (thread->synch_cs);
3671         thread->state &= ~state;
3672         LeaveCriticalSection (thread->synch_cs);
3673 }
3674
3675 gboolean
3676 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3677 {
3678         gboolean ret = FALSE;
3679
3680         ensure_synch_cs_set (thread);
3681         
3682         EnterCriticalSection (thread->synch_cs);
3683
3684         if ((thread->state & test) != 0) {
3685                 ret = TRUE;
3686         }
3687         
3688         LeaveCriticalSection (thread->synch_cs);
3689         
3690         return ret;
3691 }