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