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