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