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