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