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