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