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