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