e0a7aee8edc4b6711420fb1961fd2373138bab09
[mono.git] / mono / metadata / threads.c
1 /**
2  * \file
3  * Thread support internal calls
4  *
5  * Author:
6  *      Dick Porter (dick@ximian.com)
7  *      Paolo Molaro (lupus@ximian.com)
8  *      Patrik Torstensson (patrik.torstensson@labs2.com)
9  *
10  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 #include <config.h>
17
18 #include <glib.h>
19 #include <string.h>
20
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/environment.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/gc-internals.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/runtime.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/debug-internals.h>
34 #include <mono/utils/monobitset.h>
35 #include <mono/utils/mono-compiler.h>
36 #include <mono/utils/mono-mmap.h>
37 #include <mono/utils/mono-membar.h>
38 #include <mono/utils/mono-time.h>
39 #include <mono/utils/mono-threads.h>
40 #include <mono/utils/mono-threads-coop.h>
41 #include <mono/utils/hazard-pointer.h>
42 #include <mono/utils/mono-tls.h>
43 #include <mono/utils/atomic.h>
44 #include <mono/utils/mono-memory-model.h>
45 #include <mono/utils/mono-error-internals.h>
46 #include <mono/utils/os-event.h>
47 #include <mono/utils/mono-threads-debug.h>
48 #include <mono/metadata/w32handle.h>
49 #include <mono/metadata/w32event.h>
50 #include <mono/metadata/w32mutex.h>
51
52 #include <mono/metadata/reflection-internals.h>
53 #include <mono/metadata/abi-details.h>
54 #include <mono/metadata/w32error.h>
55 #include <mono/utils/w32api.h>
56
57 #ifdef HAVE_SIGNAL_H
58 #include <signal.h>
59 #endif
60
61 #if defined(HOST_WIN32)
62 #include <objbase.h>
63 #endif
64
65 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
66 #define USE_TKILL_ON_ANDROID 1
67 #endif
68
69 #ifdef PLATFORM_ANDROID
70 #include <errno.h>
71
72 #ifdef USE_TKILL_ON_ANDROID
73 extern int tkill (pid_t tid, int signal);
74 #endif
75 #endif
76
77 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
78 #define THREAD_DEBUG(a)
79 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
80 #define THREAD_WAIT_DEBUG(a)
81 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
82 #define LIBGC_DEBUG(a)
83
84 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
85 #define SPIN_LOCK(i) do { \
86                                 if (SPIN_TRYLOCK (i)) \
87                                         break; \
88                         } while (1)
89
90 #define SPIN_UNLOCK(i) i = 0
91
92 #define LOCK_THREAD(thread) lock_thread((thread))
93 #define UNLOCK_THREAD(thread) unlock_thread((thread))
94
95 typedef union {
96         gint32 ival;
97         gfloat fval;
98 } IntFloatUnion;
99
100 typedef union {
101         gint64 ival;
102         gdouble fval;
103 } LongDoubleUnion;
104  
105 typedef struct _StaticDataFreeList StaticDataFreeList;
106 struct _StaticDataFreeList {
107         StaticDataFreeList *next;
108         guint32 offset;
109         guint32 size;
110 };
111
112 typedef struct {
113         int idx;
114         int offset;
115         StaticDataFreeList *freelist;
116 } StaticDataInfo;
117
118 /* Controls access to the 'threads' hash table */
119 static void mono_threads_lock (void);
120 static void mono_threads_unlock (void);
121 static MonoCoopMutex threads_mutex;
122
123 /* Controls access to the 'joinable_threads' hash table */
124 #define joinable_threads_lock() mono_os_mutex_lock (&joinable_threads_mutex)
125 #define joinable_threads_unlock() mono_os_mutex_unlock (&joinable_threads_mutex)
126 static mono_mutex_t joinable_threads_mutex;
127
128 /* Holds current status of static data heap */
129 static StaticDataInfo thread_static_info;
130 static StaticDataInfo context_static_info;
131
132 /* The hash of existing threads (key is thread ID, value is
133  * MonoInternalThread*) that need joining before exit
134  */
135 static MonoGHashTable *threads=NULL;
136
137 /* List of app context GC handles.
138  * Added to from mono_threads_register_app_context ().
139  */
140 static GHashTable *contexts = NULL;
141
142 /* Cleanup queue for contexts. */
143 static MonoReferenceQueue *context_queue;
144
145 /*
146  * Threads which are starting up and they are not in the 'threads' hash yet.
147  * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
148  * Protected by mono_threads_lock ().
149  */
150 static MonoGHashTable *threads_starting_up = NULL;
151
152 /* Contains tids */
153 /* Protected by the threads lock */
154 static GHashTable *joinable_threads;
155 static int joinable_thread_count;
156
157 #define SET_CURRENT_OBJECT(x) mono_tls_set_thread (x)
158 #define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_tls_get_thread ()
159
160 /* function called at thread start */
161 static MonoThreadStartCB mono_thread_start_cb = NULL;
162
163 /* function called at thread attach */
164 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
165
166 /* function called at thread cleanup */
167 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
168
169 /* The default stack size for each thread */
170 static guint32 default_stacksize = 0;
171 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
172
173 static void context_adjust_static_data (MonoAppContext *ctx);
174 static void mono_free_static_data (gpointer* static_data);
175 static void mono_init_static_data_info (StaticDataInfo *static_data);
176 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
177 static gboolean mono_thread_resume (MonoInternalThread* thread);
178 static void async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort);
179 static void self_abort_internal (MonoError *error);
180 static void async_suspend_internal (MonoInternalThread *thread, gboolean interrupt);
181 static void self_suspend_internal (void);
182
183 static MonoException* mono_thread_execute_interruption (void);
184 static void ref_stack_destroy (gpointer rs);
185
186 /* Spin lock for InterlockedXXX 64 bit functions */
187 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
188 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
189 static mono_mutex_t interlocked_mutex;
190
191 /* global count of thread interruptions requested */
192 static gint32 thread_interruption_requested = 0;
193
194 /* Event signaled when a thread changes its background mode */
195 static MonoOSEvent background_change_event;
196
197 static gboolean shutting_down = FALSE;
198
199 static gint32 managed_thread_id_counter = 0;
200
201 /* Class lazy loading functions */
202 static GENERATE_GET_CLASS_WITH_CACHE (appdomain_unloaded_exception, "System", "AppDomainUnloadedException")
203
204 static void
205 mono_threads_lock (void)
206 {
207         mono_locks_coop_acquire (&threads_mutex, ThreadsLock);
208 }
209
210 static void
211 mono_threads_unlock (void)
212 {
213         mono_locks_coop_release (&threads_mutex, ThreadsLock);
214 }
215
216
217 static guint32
218 get_next_managed_thread_id (void)
219 {
220         return InterlockedIncrement (&managed_thread_id_counter);
221 }
222
223 /*
224  * We separate interruptions/exceptions into either sync (they can be processed anytime,
225  * normally as soon as they are set, and are set by the same thread) and async (they can't
226  * be processed inside abort protected blocks and are normally set by other threads). We
227  * can have both a pending sync and async interruption. In this case, the sync exception is
228  * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
229  * also handle all sync type exceptions before the async type exceptions.
230  */
231 enum {
232         INTERRUPT_SYNC_REQUESTED_BIT = 0x1,
233         INTERRUPT_ASYNC_REQUESTED_BIT = 0x2,
234         INTERRUPT_REQUESTED_MASK = 0x3,
235         ABORT_PROT_BLOCK_SHIFT = 2,
236         ABORT_PROT_BLOCK_BITS = 8,
237         ABORT_PROT_BLOCK_MASK = (((1 << ABORT_PROT_BLOCK_BITS) - 1) << ABORT_PROT_BLOCK_SHIFT)
238 };
239
240 static int
241 mono_thread_get_abort_prot_block_count (MonoInternalThread *thread)
242 {
243         gsize state = thread->thread_state;
244         return (state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT;
245 }
246
247 void
248 mono_threads_begin_abort_protected_block (void)
249 {
250         MonoInternalThread *thread = mono_thread_internal_current ();
251         gsize old_state, new_state;
252         int new_val;
253         do {
254                 old_state = thread->thread_state;
255
256                 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) + 1;
257                 //bounds check abort_prot_count
258                 g_assert (new_val > 0);
259                 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
260
261                 new_state = old_state + (1 << ABORT_PROT_BLOCK_SHIFT);
262         } while (InterlockedCompareExchangePointer ((volatile gpointer)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
263
264         /* Defer async request since we won't be able to process until exiting the block */
265         if (new_val == 1 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
266                 InterlockedDecrement (&thread_interruption_requested);
267                 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
268                 if (thread_interruption_requested < 0)
269                         g_warning ("bad thread_interruption_requested state");
270         } else {
271                 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
272         }
273 }
274
275 static gboolean
276 mono_thread_state_has_interruption (gsize state)
277 {
278         /* pending exception, self abort */
279         if (state & INTERRUPT_SYNC_REQUESTED_BIT)
280                 return TRUE;
281
282         /* abort, interruption, suspend */
283         if ((state & INTERRUPT_ASYNC_REQUESTED_BIT) && !(state & ABORT_PROT_BLOCK_MASK))
284                 return TRUE;
285
286         return FALSE;
287 }
288
289 gboolean
290 mono_threads_end_abort_protected_block (void)
291 {
292         MonoInternalThread *thread = mono_thread_internal_current ();
293         gsize old_state, new_state;
294         int new_val;
295         do {
296                 old_state = thread->thread_state;
297
298                 //bounds check abort_prot_count
299                 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) - 1;
300                 g_assert (new_val >= 0);
301                 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
302
303                 new_state = old_state - (1 << ABORT_PROT_BLOCK_SHIFT);
304         } while (InterlockedCompareExchangePointer ((volatile gpointer)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
305
306         if (new_val == 0 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
307                 InterlockedIncrement (&thread_interruption_requested);
308                 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
309         } else {
310                 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
311         }
312
313         return mono_thread_state_has_interruption (new_state);
314 }
315
316 static gboolean
317 mono_thread_get_interruption_requested (MonoInternalThread *thread)
318 {
319         gsize state = thread->thread_state;
320
321         return mono_thread_state_has_interruption (state);
322 }
323
324 /*
325  * Returns TRUE is there was a state change
326  * We clear a single interruption request, sync has priority.
327  */
328 static gboolean
329 mono_thread_clear_interruption_requested (MonoInternalThread *thread)
330 {
331         gsize old_state, new_state;
332         do {
333                 old_state = thread->thread_state;
334
335                 // no interruption to process
336                 if (!(old_state & INTERRUPT_SYNC_REQUESTED_BIT) &&
337                                 (!(old_state & INTERRUPT_ASYNC_REQUESTED_BIT) || (old_state & ABORT_PROT_BLOCK_MASK)))
338                         return FALSE;
339
340                 if (old_state & INTERRUPT_SYNC_REQUESTED_BIT)
341                         new_state = old_state & ~INTERRUPT_SYNC_REQUESTED_BIT;
342                 else
343                         new_state = old_state & ~INTERRUPT_ASYNC_REQUESTED_BIT;
344         } while (InterlockedCompareExchangePointer ((volatile gpointer)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
345
346         InterlockedDecrement (&thread_interruption_requested);
347         THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
348         if (thread_interruption_requested < 0)
349                 g_warning ("bad thread_interruption_requested state");
350         return TRUE;
351 }
352
353 /* Returns TRUE is there was a state change and the interruption can be processed */
354 static gboolean
355 mono_thread_set_interruption_requested (MonoInternalThread *thread)
356 {
357         //always force when the current thread is doing it to itself.
358         gboolean sync = thread == mono_thread_internal_current ();
359         gsize old_state, new_state;
360         do {
361                 old_state = thread->thread_state;
362
363                 //Already set
364                 if ((sync && (old_state & INTERRUPT_SYNC_REQUESTED_BIT)) ||
365                                 (!sync && (old_state & INTERRUPT_ASYNC_REQUESTED_BIT)))
366                         return FALSE;
367
368                 if (sync)
369                         new_state = old_state | INTERRUPT_SYNC_REQUESTED_BIT;
370                 else
371                         new_state = old_state | INTERRUPT_ASYNC_REQUESTED_BIT;
372         } while (InterlockedCompareExchangePointer ((volatile gpointer)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
373
374         if (sync || !(new_state & ABORT_PROT_BLOCK_MASK)) {
375                 InterlockedIncrement (&thread_interruption_requested);
376                 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
377         } else {
378                 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
379         }
380
381         return sync || !(new_state & ABORT_PROT_BLOCK_MASK);
382 }
383
384 static inline MonoNativeThreadId
385 thread_get_tid (MonoInternalThread *thread)
386 {
387         /* We store the tid as a guint64 to keep the object layout constant between platforms */
388         return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
389 }
390
391 static void ensure_synch_cs_set (MonoInternalThread *thread)
392 {
393         MonoCoopMutex *synch_cs;
394
395         if (thread->synch_cs != NULL) {
396                 return;
397         }
398
399         synch_cs = g_new0 (MonoCoopMutex, 1);
400         mono_coop_mutex_init_recursive (synch_cs);
401
402         if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
403                                                synch_cs, NULL) != NULL) {
404                 /* Another thread must have installed this CS */
405                 mono_coop_mutex_destroy (synch_cs);
406                 g_free (synch_cs);
407         }
408 }
409
410 static inline void
411 lock_thread (MonoInternalThread *thread)
412 {
413         if (!thread->synch_cs)
414                 ensure_synch_cs_set (thread);
415
416         g_assert (thread->synch_cs);
417
418         mono_coop_mutex_lock (thread->synch_cs);
419 }
420
421 static inline void
422 unlock_thread (MonoInternalThread *thread)
423 {
424         mono_coop_mutex_unlock (thread->synch_cs);
425 }
426
427 static inline gboolean
428 is_appdomainunloaded_exception (MonoClass *klass)
429 {
430         return klass == mono_class_get_appdomain_unloaded_exception_class ();
431 }
432
433 static inline gboolean
434 is_threadabort_exception (MonoClass *klass)
435 {
436         return klass == mono_defaults.threadabortexception_class;
437 }
438
439 /*
440  * A special static data offset (guint32) consists of 3 parts:
441  *
442  * [0]   6-bit index into the array of chunks.
443  * [6]   25-bit offset into the array.
444  * [31]  Bit indicating thread or context static.
445  */
446
447 typedef union {
448         struct {
449 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
450                 guint32 type : 1;
451                 guint32 offset : 25;
452                 guint32 index : 6;
453 #else
454                 guint32 index : 6;
455                 guint32 offset : 25;
456                 guint32 type : 1;
457 #endif
458         } fields;
459         guint32 raw;
460 } SpecialStaticOffset;
461
462 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
463 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
464
465 #define MAKE_SPECIAL_STATIC_OFFSET(index, offset, type) \
466         ((SpecialStaticOffset) { .fields = { (index), (offset), (type) } }.raw)
467 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
468         (((SpecialStaticOffset *) &(x))->fields.f)
469
470 static gpointer
471 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
472 {
473         g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_THREAD);
474
475         int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
476         int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
477
478         return ((char *) thread->static_data [idx]) + off;
479 }
480
481 static gpointer
482 get_context_static_data (MonoAppContext *ctx, guint32 offset)
483 {
484         g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT);
485
486         int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
487         int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
488
489         return ((char *) ctx->static_data [idx]) + off;
490 }
491
492 static MonoThread**
493 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
494 {
495         static MonoClassField *current_thread_field = NULL;
496
497         guint32 offset;
498
499         if (!current_thread_field) {
500                 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
501                 g_assert (current_thread_field);
502         }
503
504         mono_class_vtable (domain, mono_defaults.thread_class);
505         mono_domain_lock (domain);
506         offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
507         mono_domain_unlock (domain);
508         g_assert (offset);
509
510         return (MonoThread **)get_thread_static_data (thread, offset);
511 }
512
513 static void
514 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
515 {
516         MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
517
518         g_assert (current->obj.vtable->domain == domain);
519
520         g_assert (!*current_thread_ptr);
521         *current_thread_ptr = current;
522 }
523
524 static MonoThread*
525 create_thread_object (MonoDomain *domain, MonoInternalThread *internal)
526 {
527         MonoThread *thread;
528         MonoVTable *vtable;
529         MonoError error;
530
531         vtable = mono_class_vtable (domain, mono_defaults.thread_class);
532         g_assert (vtable);
533
534         thread = (MonoThread*)mono_object_new_mature (vtable, &error);
535         /* only possible failure mode is OOM, from which we don't expect to recover. */
536         mono_error_assert_ok (&error);
537
538         MONO_OBJECT_SETREF (thread, internal_thread, internal);
539
540         return thread;
541 }
542
543 static MonoInternalThread*
544 create_internal_thread_object (void)
545 {
546         MonoError error;
547         MonoInternalThread *thread;
548         MonoVTable *vt;
549
550         vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
551         thread = (MonoInternalThread*) mono_object_new_mature (vt, &error);
552         /* only possible failure mode is OOM, from which we don't exect to recover */
553         mono_error_assert_ok (&error);
554
555         thread->synch_cs = g_new0 (MonoCoopMutex, 1);
556         mono_coop_mutex_init_recursive (thread->synch_cs);
557
558         thread->apartment_state = ThreadApartmentState_Unknown;
559         thread->managed_id = get_next_managed_thread_id ();
560         if (mono_gc_is_moving ()) {
561                 thread->thread_pinning_ref = thread;
562                 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref, MONO_ROOT_SOURCE_THREADING, "thread pinning reference");
563         }
564
565         thread->priority = MONO_THREAD_PRIORITY_NORMAL;
566
567         thread->suspended = g_new0 (MonoOSEvent, 1);
568         mono_os_event_init (thread->suspended, TRUE);
569
570         return thread;
571 }
572
573 static void
574 mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPriority priority)
575 {
576         g_assert (internal);
577
578         g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
579         g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
580         g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
581
582 #ifdef HOST_WIN32
583         BOOL res;
584
585         g_assert (internal->native_handle);
586
587         res = SetThreadPriority (internal->native_handle, priority - 2);
588         if (!res)
589                 g_error ("%s: SetThreadPriority failed, error %d", __func__, GetLastError ());
590 #else /* HOST_WIN32 */
591         pthread_t tid;
592         int policy;
593         struct sched_param param;
594         gint res;
595
596         tid = thread_get_tid (internal);
597
598         res = pthread_getschedparam (tid, &policy, &param);
599         if (res != 0)
600                 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
601
602 #ifdef _POSIX_PRIORITY_SCHEDULING
603         int max, min;
604
605         /* Necessary to get valid priority range */
606
607         min = sched_get_priority_min (policy);
608         max = sched_get_priority_max (policy);
609
610         if (max > 0 && min >= 0 && max > min) {
611                 double srange, drange, sposition, dposition;
612                 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
613                 drange = max - min;
614                 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
615                 dposition = (sposition / srange) * drange;
616                 param.sched_priority = (int)(dposition + min);
617         } else
618 #endif
619         {
620                 switch (policy) {
621                 case SCHED_FIFO:
622                 case SCHED_RR:
623                         param.sched_priority = 50;
624                         break;
625 #ifdef SCHED_BATCH
626                 case SCHED_BATCH:
627 #endif
628                 case SCHED_OTHER:
629                         param.sched_priority = 0;
630                         break;
631                 default:
632                         g_warning ("%s: unknown policy %d", __func__, policy);
633                         return;
634                 }
635         }
636
637         res = pthread_setschedparam (tid, policy, &param);
638         if (res != 0) {
639                 if (res == EPERM) {
640                         g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
641                         return;
642                 }
643                 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
644         }
645 #endif /* HOST_WIN32 */
646 }
647
648 static void 
649 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal);
650
651 static gboolean
652 mono_thread_attach_internal (MonoThread *thread, gboolean force_attach, gboolean force_domain)
653 {
654         MonoThreadInfo *info;
655         MonoInternalThread *internal;
656         MonoDomain *domain, *root_domain;
657
658         g_assert (thread);
659
660         info = mono_thread_info_current ();
661         g_assert (info);
662
663         internal = thread->internal_thread;
664         g_assert (internal);
665
666         /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
667          *  - the MonoInternalThread TLS key is destroyed: set it to NULL
668          *  - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
669          *    - it calls MonoThreadInfoCallbacks.thread_detach
670          *      - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
671         mono_thread_info_set_internal_thread_gchandle (info, mono_gchandle_new ((MonoObject*) internal, FALSE));
672
673         internal->handle = mono_threads_open_thread_handle (info->handle);
674 #ifdef HOST_WIN32
675         internal->native_handle = OpenThread (THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId ());
676 #endif
677         internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
678         internal->thread_info = info;
679         internal->small_id = info->small_id;
680
681         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, mono_native_thread_id_get (), internal));
682
683         SET_CURRENT_OBJECT (internal);
684
685         domain = mono_object_domain (thread);
686
687         mono_thread_push_appdomain_ref (domain);
688         if (!mono_domain_set (domain, force_domain)) {
689                 mono_thread_pop_appdomain_ref ();
690                 return FALSE;
691         }
692
693         mono_threads_lock ();
694
695         if (threads_starting_up)
696                 mono_g_hash_table_remove (threads_starting_up, thread);
697
698         if (shutting_down && !force_attach) {
699                 mono_threads_unlock ();
700                 mono_thread_pop_appdomain_ref ();
701                 return FALSE;
702         }
703
704         if (!threads) {
705                 threads = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_THREADING, "threads table");
706         }
707
708         /* We don't need to duplicate thread->handle, because it is
709          * only closed when the thread object is finalized by the GC. */
710         mono_g_hash_table_insert (threads, (gpointer)(gsize)(internal->tid), internal);
711
712         /* We have to do this here because mono_thread_start_cb
713          * requires that root_domain_thread is set up. */
714         if (thread_static_info.offset || thread_static_info.idx > 0) {
715                 /* get the current allocated size */
716                 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (thread_static_info.idx, thread_static_info.offset, 0);
717                 mono_alloc_static_data (&internal->static_data, offset, TRUE);
718         }
719
720         mono_threads_unlock ();
721
722         root_domain = mono_get_root_domain ();
723
724         g_assert (!internal->root_domain_thread);
725         if (domain != root_domain)
726                 MONO_OBJECT_SETREF (internal, root_domain_thread, create_thread_object (root_domain, internal));
727         else
728                 MONO_OBJECT_SETREF (internal, root_domain_thread, thread);
729
730         if (domain != root_domain)
731                 set_current_thread_for_domain (root_domain, internal, internal->root_domain_thread);
732
733         set_current_thread_for_domain (domain, internal, thread);
734
735         THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, internal->tid, internal->handle));
736
737         return TRUE;
738 }
739
740 typedef struct {
741         gint32 ref;
742         MonoThread *thread;
743         MonoObject *start_delegate;
744         MonoObject *start_delegate_arg;
745         MonoThreadStart start_func;
746         gpointer start_func_arg;
747         gboolean force_attach;
748         gboolean failed;
749         MonoCoopSem registered;
750 } StartInfo;
751
752 static guint32 WINAPI start_wrapper_internal(StartInfo *start_info, gsize *stack_ptr)
753 {
754         MonoError error;
755         MonoThreadStart start_func;
756         void *start_func_arg;
757         gsize tid;
758         /* 
759          * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
760          * GC stack walk.
761          */
762         MonoThread *thread;
763         MonoInternalThread *internal;
764         MonoObject *start_delegate;
765         MonoObject *start_delegate_arg;
766         MonoDomain *domain;
767
768         thread = start_info->thread;
769         internal = thread->internal_thread;
770         domain = mono_object_domain (start_info->thread);
771
772         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, mono_native_thread_id_get ()));
773
774         if (!mono_thread_attach_internal (thread, start_info->force_attach, FALSE)) {
775                 start_info->failed = TRUE;
776
777                 mono_coop_sem_post (&start_info->registered);
778
779                 if (InterlockedDecrement (&start_info->ref) == 0) {
780                         mono_coop_sem_destroy (&start_info->registered);
781                         g_free (start_info);
782                 }
783
784                 return 0;
785         }
786
787         mono_thread_internal_set_priority (internal, internal->priority);
788
789         tid = internal->tid;
790
791         start_delegate = start_info->start_delegate;
792         start_delegate_arg = start_info->start_delegate_arg;
793         start_func = start_info->start_func;
794         start_func_arg = start_info->start_func_arg;
795
796         /* This MUST be called before any managed code can be
797          * executed, as it calls the callback function that (for the
798          * jit) sets the lmf marker.
799          */
800
801         if (mono_thread_start_cb)
802                 mono_thread_start_cb (tid, stack_ptr, start_func);
803
804         /* On 2.0 profile (and higher), set explicitly since state might have been
805            Unknown */
806         if (internal->apartment_state == ThreadApartmentState_Unknown)
807                 internal->apartment_state = ThreadApartmentState_MTA;
808
809         mono_thread_init_apartment_state ();
810
811         /* Let the thread that called Start() know we're ready */
812         mono_coop_sem_post (&start_info->registered);
813
814         if (InterlockedDecrement (&start_info->ref) == 0) {
815                 mono_coop_sem_destroy (&start_info->registered);
816                 g_free (start_info);
817         }
818
819         /* start_info is not valid anymore */
820         start_info = NULL;
821
822         /* 
823          * Call this after calling start_notify, since the profiler callback might want
824          * to lock the thread, and the lock is held by thread_start () which waits for
825          * start_notify.
826          */
827         MONO_PROFILER_RAISE (thread_started, (tid));
828
829         /* if the name was set before starting, we didn't invoke the profiler callback */
830         if (internal->name) {
831                 char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
832                 MONO_PROFILER_RAISE (thread_name, (internal->tid, tname));
833                 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), tname);
834                 g_free (tname);
835         }
836
837         /* start_func is set only for unmanaged start functions */
838         if (start_func) {
839                 start_func (start_func_arg);
840         } else {
841                 void *args [1];
842
843                 g_assert (start_delegate != NULL);
844
845                 /* we may want to handle the exception here. See comment below on unhandled exceptions */
846                 args [0] = (gpointer) start_delegate_arg;
847                 mono_runtime_delegate_invoke_checked (start_delegate, args, &error);
848
849                 if (!mono_error_ok (&error)) {
850                         MonoException *ex = mono_error_convert_to_exception (&error);
851
852                         g_assert (ex != NULL);
853                         MonoClass *klass = mono_object_get_class (&ex->object);
854                         if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
855                             !is_threadabort_exception (klass)) {
856                                 mono_unhandled_exception (&ex->object);
857                                 mono_invoke_unhandled_exception_hook (&ex->object);
858                                 g_assert_not_reached ();
859                         }
860                 } else {
861                         mono_error_cleanup (&error);
862                 }
863         }
864
865         /* If the thread calls ExitThread at all, this remaining code
866          * will not be executed, but the main thread will eventually
867          * call mono_thread_detach_internal() on this thread's behalf.
868          */
869
870         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
871
872         /* Do any cleanup needed for apartment state. This
873          * cannot be done in mono_thread_detach_internal since
874          * mono_thread_detach_internal could be  called for a
875          * thread other than the current thread.
876          * mono_thread_cleanup_apartment_state cleans up apartment
877          * for the current thead */
878         mono_thread_cleanup_apartment_state ();
879
880         mono_thread_detach_internal (internal);
881
882         internal->tid = 0;
883
884         return(0);
885 }
886
887 static gsize WINAPI
888 start_wrapper (gpointer data)
889 {
890         StartInfo *start_info;
891         MonoThreadInfo *info;
892         gsize res;
893
894         start_info = (StartInfo*) data;
895         g_assert (start_info);
896
897         info = mono_thread_info_attach ();
898         info->runtime_thread = TRUE;
899
900         /* Run the actual main function of the thread */
901         res = start_wrapper_internal (start_info, info->stack_end);
902
903         mono_thread_info_exit (res);
904
905         g_assert_not_reached ();
906 }
907
908 /*
909  * create_thread:
910  *
911  *   Common thread creation code.
912  * LOCKING: Acquires the threads lock.
913  */
914 static gboolean
915 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
916         MonoThreadCreateFlags flags, MonoError *error)
917 {
918         StartInfo *start_info = NULL;
919         MonoNativeThreadId tid;
920         gboolean ret;
921         gsize stack_set_size;
922
923         if (start_delegate)
924                 g_assert (!start_func && !start_func_arg);
925         if (start_func)
926                 g_assert (!start_delegate);
927
928         if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
929                 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
930                 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
931         }
932         if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
933                 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
934                 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
935         }
936
937         /*
938          * Join joinable threads to prevent running out of threads since the finalizer
939          * thread might be blocked/backlogged.
940          */
941         mono_threads_join_threads ();
942
943         error_init (error);
944
945         mono_threads_lock ();
946         if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
947                 mono_threads_unlock ();
948                 return FALSE;
949         }
950         if (threads_starting_up == NULL) {
951                 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_THREADING, "starting threads table");
952         }
953         mono_g_hash_table_insert (threads_starting_up, thread, thread);
954         mono_threads_unlock ();
955
956         internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
957         if (internal->threadpool_thread)
958                 mono_thread_set_state (internal, ThreadState_Background);
959
960         internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
961
962         start_info = g_new0 (StartInfo, 1);
963         start_info->ref = 2;
964         start_info->thread = thread;
965         start_info->start_delegate = start_delegate;
966         start_info->start_delegate_arg = thread->start_obj;
967         start_info->start_func = start_func;
968         start_info->start_func_arg = start_func_arg;
969         start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
970         start_info->failed = FALSE;
971         mono_coop_sem_init (&start_info->registered, 0);
972
973         if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
974                 stack_set_size = default_stacksize_for_thread (internal);
975         else
976                 stack_set_size = 0;
977
978         if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
979                 /* The thread couldn't be created, so set an exception */
980                 mono_threads_lock ();
981                 mono_g_hash_table_remove (threads_starting_up, thread);
982                 mono_threads_unlock ();
983                 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
984                 /* ref is not going to be decremented in start_wrapper_internal */
985                 InterlockedDecrement (&start_info->ref);
986                 ret = FALSE;
987                 goto done;
988         }
989
990         internal->stack_size = (int) stack_set_size;
991
992         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
993
994         /*
995          * Wait for the thread to set up its TLS data etc, so
996          * theres no potential race condition if someone tries
997          * to look up the data believing the thread has
998          * started
999          */
1000
1001         mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1002
1003         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1004
1005         ret = !start_info->failed;
1006
1007 done:
1008         if (InterlockedDecrement (&start_info->ref) == 0) {
1009                 mono_coop_sem_destroy (&start_info->registered);
1010                 g_free (start_info);
1011         }
1012
1013         return ret;
1014 }
1015
1016 /**
1017  * mono_thread_new_init:
1018  */
1019 void
1020 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1021 {
1022         if (mono_thread_start_cb) {
1023                 mono_thread_start_cb (tid, stack_start, func);
1024         }
1025 }
1026
1027 /**
1028  * mono_threads_set_default_stacksize:
1029  */
1030 void
1031 mono_threads_set_default_stacksize (guint32 stacksize)
1032 {
1033         default_stacksize = stacksize;
1034 }
1035
1036 /**
1037  * mono_threads_get_default_stacksize:
1038  */
1039 guint32
1040 mono_threads_get_default_stacksize (void)
1041 {
1042         return default_stacksize;
1043 }
1044
1045 /*
1046  * mono_thread_create_internal:
1047  *
1048  *   ARG should not be a GC reference.
1049  */
1050 MonoInternalThread*
1051 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1052 {
1053         MonoThread *thread;
1054         MonoInternalThread *internal;
1055         gboolean res;
1056
1057         error_init (error);
1058
1059         internal = create_internal_thread_object ();
1060
1061         thread = create_thread_object (domain, internal);
1062
1063         LOCK_THREAD (internal);
1064
1065         res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1066
1067         UNLOCK_THREAD (internal);
1068
1069         return_val_if_nok (error, NULL);
1070         return internal;
1071 }
1072
1073 /**
1074  * mono_thread_create:
1075  */
1076 void
1077 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1078 {
1079         MonoError error;
1080         if (!mono_thread_create_checked (domain, func, arg, &error))
1081                 mono_error_cleanup (&error);
1082 }
1083
1084 gboolean
1085 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1086 {
1087         return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1088 }
1089
1090 static MonoThread *
1091 mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
1092 {
1093         MonoInternalThread *internal;
1094         MonoThread *thread;
1095         MonoThreadInfo *info;
1096         MonoNativeThreadId tid;
1097
1098         if (mono_thread_internal_current_is_attached ()) {
1099                 if (domain != mono_domain_get ())
1100                         mono_domain_set (domain, TRUE);
1101                 /* Already attached */
1102                 return mono_thread_current ();
1103         }
1104
1105         info = mono_thread_info_attach ();
1106         g_assert (info);
1107
1108         tid=mono_native_thread_id_get ();
1109
1110         internal = create_internal_thread_object ();
1111
1112         thread = create_thread_object (domain, internal);
1113
1114         if (!mono_thread_attach_internal (thread, force_attach, TRUE)) {
1115                 /* Mono is shutting down, so just wait for the end */
1116                 for (;;)
1117                         mono_thread_info_sleep (10000, NULL);
1118         }
1119
1120         THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, internal->handle));
1121
1122         if (mono_thread_attach_cb)
1123                 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1124
1125         /* Can happen when we attach the profiler helper thread in order to heapshot. */
1126         if (!mono_thread_info_current ()->tools_thread)
1127                 MONO_PROFILER_RAISE (thread_started, (MONO_NATIVE_THREAD_ID_TO_UINT (tid)));
1128
1129         return thread;
1130 }
1131
1132 /**
1133  * mono_thread_attach:
1134  */
1135 MonoThread *
1136 mono_thread_attach (MonoDomain *domain)
1137 {
1138         return mono_thread_attach_full (domain, FALSE);
1139 }
1140
1141 void
1142 mono_thread_detach_internal (MonoInternalThread *thread)
1143 {
1144         gboolean removed;
1145
1146         g_assert (thread != NULL);
1147         SET_CURRENT_OBJECT (thread);
1148
1149         THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1150
1151 #ifndef HOST_WIN32
1152         mono_w32mutex_abandon ();
1153 #endif
1154
1155         if (thread->abort_state_handle) {
1156                 mono_gchandle_free (thread->abort_state_handle);
1157                 thread->abort_state_handle = 0;
1158         }
1159
1160         thread->abort_exc = NULL;
1161         thread->current_appcontext = NULL;
1162
1163         /*
1164          * thread->synch_cs can be NULL if this was called after
1165          * ves_icall_System_Threading_InternalThread_Thread_free_internal.
1166          * This can happen only during shutdown.
1167          * The shutting_down flag is not always set, so we can't assert on it.
1168          */
1169         if (thread->synch_cs)
1170                 LOCK_THREAD (thread);
1171
1172         thread->state |= ThreadState_Stopped;
1173         thread->state &= ~ThreadState_Background;
1174
1175         if (thread->synch_cs)
1176                 UNLOCK_THREAD (thread);
1177
1178         /*
1179         An interruption request has leaked to cleanup. Adjust the global counter.
1180
1181         This can happen is the abort source thread finds the abortee (this) thread
1182         in unmanaged code. If this thread never trips back to managed code or check
1183         the local flag it will be left set and positively unbalance the global counter.
1184         
1185         Leaving the counter unbalanced will cause a performance degradation since all threads
1186         will now keep checking their local flags all the time.
1187         */
1188         mono_thread_clear_interruption_requested (thread);
1189
1190         mono_threads_lock ();
1191
1192         if (!threads) {
1193                 removed = FALSE;
1194         } else if (mono_g_hash_table_lookup (threads, (gpointer)thread->tid) != thread) {
1195                 /* We have to check whether the thread object for the
1196                  * tid is still the same in the table because the
1197                  * thread might have been destroyed and the tid reused
1198                  * in the meantime, in which case the tid would be in
1199                  * the table, but with another thread object.
1200                  */
1201                 removed = FALSE;
1202         } else {
1203                 mono_g_hash_table_remove (threads, (gpointer)thread->tid);
1204                 removed = TRUE;
1205         }
1206
1207         mono_threads_unlock ();
1208
1209         /* Don't close the handle here, wait for the object finalizer
1210          * to do it. Otherwise, the following race condition applies:
1211          *
1212          * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
1213          *
1214          * 2) Some other handle is reassigned the same slot
1215          *
1216          * 3) Another thread tries to join the first thread, and
1217          * blocks waiting for the reassigned handle to be signalled
1218          * (which might never happen).  This is possible, because the
1219          * thread calling Join() still has a reference to the first
1220          * thread's object.
1221          */
1222
1223         /* if the thread is not in the hash it has been removed already */
1224         if (!removed) {
1225                 mono_domain_unset ();
1226                 mono_memory_barrier ();
1227
1228                 if (mono_thread_cleanup_fn)
1229                         mono_thread_cleanup_fn (thread_get_tid (thread));
1230
1231                 goto done;
1232         }
1233
1234         mono_release_type_locks (thread);
1235
1236         /* Can happen when we attach the profiler helper thread in order to heapshot. */
1237         if (!mono_thread_info_lookup (MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid))->tools_thread)
1238                 MONO_PROFILER_RAISE (thread_stopped, (thread->tid));
1239
1240         mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
1241
1242         /*
1243          * This will signal async signal handlers that the thread has exited.
1244          * The profiler callback needs this to be set, so it cannot be done earlier.
1245          */
1246         mono_domain_unset ();
1247         mono_memory_barrier ();
1248
1249         if (thread == mono_thread_internal_current ())
1250                 mono_thread_pop_appdomain_ref ();
1251
1252         mono_free_static_data (thread->static_data);
1253         thread->static_data = NULL;
1254         ref_stack_destroy (thread->appdomain_refs);
1255         thread->appdomain_refs = NULL;
1256
1257         g_assert (thread->suspended);
1258         mono_os_event_destroy (thread->suspended);
1259         g_free (thread->suspended);
1260         thread->suspended = NULL;
1261
1262         if (mono_thread_cleanup_fn)
1263                 mono_thread_cleanup_fn (thread_get_tid (thread));
1264
1265         mono_memory_barrier ();
1266
1267         if (mono_gc_is_moving ()) {
1268                 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
1269                 thread->thread_pinning_ref = NULL;
1270         }
1271
1272 done:
1273         SET_CURRENT_OBJECT (NULL);
1274         mono_domain_unset ();
1275
1276         mono_thread_info_unset_internal_thread_gchandle ((MonoThreadInfo*) thread->thread_info);
1277
1278         /* Don't need to close the handle to this thread, even though we took a
1279          * reference in mono_thread_attach (), because the GC will do it
1280          * when the Thread object is finalised.
1281          */
1282 }
1283
1284 /**
1285  * mono_thread_detach:
1286  */
1287 void
1288 mono_thread_detach (MonoThread *thread)
1289 {
1290         if (thread)
1291                 mono_thread_detach_internal (thread->internal_thread);
1292 }
1293
1294 /**
1295  * mono_thread_detach_if_exiting:
1296  *
1297  * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1298  * This should be used at the end of embedding code which calls into managed code, and which
1299  * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1300  */
1301 mono_bool
1302 mono_thread_detach_if_exiting (void)
1303 {
1304         if (mono_thread_info_is_exiting ()) {
1305                 MonoInternalThread *thread;
1306
1307                 thread = mono_thread_internal_current ();
1308                 if (thread) {
1309                         mono_thread_detach_internal (thread);
1310                         mono_thread_info_detach ();
1311                         return TRUE;
1312                 }
1313         }
1314         return FALSE;
1315 }
1316
1317 gboolean
1318 mono_thread_internal_current_is_attached (void)
1319 {
1320         MonoInternalThread *internal;
1321
1322         internal = GET_CURRENT_OBJECT ();
1323         if (!internal)
1324                 return FALSE;
1325
1326         return TRUE;
1327 }
1328
1329 /**
1330  * mono_thread_exit:
1331  */
1332 void
1333 mono_thread_exit (void)
1334 {
1335         MonoInternalThread *thread = mono_thread_internal_current ();
1336
1337         THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1338
1339         mono_thread_detach_internal (thread);
1340
1341         /* we could add a callback here for embedders to use. */
1342         if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1343                 exit (mono_environment_exitcode_get ());
1344
1345         mono_thread_info_exit (0);
1346 }
1347
1348 void
1349 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this_obj)
1350 {
1351         MonoInternalThread *internal;
1352
1353         internal = create_internal_thread_object ();
1354
1355         internal->state = ThreadState_Unstarted;
1356
1357         InterlockedCompareExchangePointer ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1358 }
1359
1360 MonoThread *
1361 ves_icall_System_Threading_Thread_GetCurrentThread (void)
1362 {
1363         return mono_thread_current ();
1364 }
1365
1366 HANDLE
1367 ves_icall_System_Threading_Thread_Thread_internal (MonoThread *this_obj,
1368                                                                                                    MonoObject *start)
1369 {
1370         MonoError error;
1371         MonoInternalThread *internal;
1372         gboolean res;
1373
1374         THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1375
1376         if (!this_obj->internal_thread)
1377                 ves_icall_System_Threading_Thread_ConstructInternalThread (this_obj);
1378         internal = this_obj->internal_thread;
1379
1380         LOCK_THREAD (internal);
1381
1382         if ((internal->state & ThreadState_Unstarted) == 0) {
1383                 UNLOCK_THREAD (internal);
1384                 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has already been started."));
1385                 return NULL;
1386         }
1387
1388         if ((internal->state & ThreadState_Aborted) != 0) {
1389                 UNLOCK_THREAD (internal);
1390                 return this_obj;
1391         }
1392
1393         res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, &error);
1394         if (!res) {
1395                 mono_error_cleanup (&error);
1396                 UNLOCK_THREAD (internal);
1397                 return NULL;
1398         }
1399
1400         internal->state &= ~ThreadState_Unstarted;
1401
1402         THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1403
1404         UNLOCK_THREAD (internal);
1405         return internal->handle;
1406 }
1407
1408 /*
1409  * This is called from the finalizer of the internal thread object.
1410  */
1411 void
1412 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this_obj)
1413 {
1414         THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, this_obj->handle));
1415
1416         /*
1417          * Since threads keep a reference to their thread object while running, by
1418          * the time this function is called, the thread has already exited/detached,
1419          * i.e. mono_thread_detach_internal () has ran. The exception is during
1420          * shutdown, when mono_thread_detach_internal () can be called after this.
1421          */
1422         if (this_obj->handle) {
1423                 mono_threads_close_thread_handle (this_obj->handle);
1424                 this_obj->handle = NULL;
1425         }
1426
1427 #if HOST_WIN32
1428         CloseHandle (this_obj->native_handle);
1429 #endif
1430
1431         if (this_obj->synch_cs) {
1432                 MonoCoopMutex *synch_cs = this_obj->synch_cs;
1433                 this_obj->synch_cs = NULL;
1434                 mono_coop_mutex_destroy (synch_cs);
1435                 g_free (synch_cs);
1436         }
1437
1438         if (this_obj->name) {
1439                 void *name = this_obj->name;
1440                 this_obj->name = NULL;
1441                 g_free (name);
1442         }
1443 }
1444
1445 void
1446 ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1447 {
1448         guint32 res;
1449         MonoInternalThread *thread = mono_thread_internal_current ();
1450
1451         THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1452
1453         if (mono_thread_current_check_pending_interrupt ())
1454                 return;
1455
1456         while (TRUE) {
1457                 gboolean alerted = FALSE;
1458
1459                 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1460
1461                 res = mono_thread_info_sleep (ms, &alerted);
1462
1463                 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1464
1465                 if (alerted) {
1466                         MonoException* exc = mono_thread_execute_interruption ();
1467                         if (exc) {
1468                                 mono_raise_exception (exc);
1469                         } else {
1470                                 // FIXME: !MONO_INFINITE_WAIT
1471                                 if (ms != MONO_INFINITE_WAIT)
1472                                         break;
1473                         }
1474                 } else {
1475                         break;
1476                 }
1477         }
1478 }
1479
1480 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1481 {
1482 }
1483
1484 gint32
1485 ves_icall_System_Threading_Thread_GetDomainID (void) 
1486 {
1487         return mono_domain_get()->domain_id;
1488 }
1489
1490 gboolean 
1491 ves_icall_System_Threading_Thread_Yield (void)
1492 {
1493         return mono_thread_info_yield ();
1494 }
1495
1496 /*
1497  * mono_thread_get_name:
1498  *
1499  *   Return the name of the thread. NAME_LEN is set to the length of the name.
1500  * Return NULL if the thread has no name. The returned memory is owned by the
1501  * caller.
1502  */
1503 gunichar2*
1504 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1505 {
1506         gunichar2 *res;
1507
1508         LOCK_THREAD (this_obj);
1509         
1510         if (!this_obj->name) {
1511                 *name_len = 0;
1512                 res = NULL;
1513         } else {
1514                 *name_len = this_obj->name_len;
1515                 res = g_new (gunichar2, this_obj->name_len);
1516                 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1517         }
1518         
1519         UNLOCK_THREAD (this_obj);
1520
1521         return res;
1522 }
1523
1524 /**
1525  * mono_thread_get_name_utf8:
1526  * \returns the name of the thread in UTF-8.
1527  * Return NULL if the thread has no name.
1528  * The returned memory is owned by the caller.
1529  */
1530 char *
1531 mono_thread_get_name_utf8 (MonoThread *thread)
1532 {
1533         if (thread == NULL)
1534                 return NULL;
1535
1536         MonoInternalThread *internal = thread->internal_thread;
1537         if (internal == NULL)
1538                 return NULL;
1539
1540         LOCK_THREAD (internal);
1541
1542         char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
1543
1544         UNLOCK_THREAD (internal);
1545
1546         return tname;
1547 }
1548
1549 /**
1550  * mono_thread_get_managed_id:
1551  * \returns the \c Thread.ManagedThreadId value of \p thread.
1552  * Returns \c -1 if \p thread is NULL.
1553  */
1554 int32_t
1555 mono_thread_get_managed_id (MonoThread *thread)
1556 {
1557         if (thread == NULL)
1558                 return -1;
1559
1560         MonoInternalThread *internal = thread->internal_thread;
1561         if (internal == NULL)
1562                 return -1;
1563
1564         int32_t id = internal->managed_id;
1565
1566         return id;
1567 }
1568
1569 MonoString* 
1570 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1571 {
1572         MonoError error;
1573         MonoString* str;
1574
1575         error_init (&error);
1576
1577         LOCK_THREAD (this_obj);
1578         
1579         if (!this_obj->name)
1580                 str = NULL;
1581         else
1582                 str = mono_string_new_utf16_checked (mono_domain_get (), this_obj->name, this_obj->name_len, &error);
1583         
1584         UNLOCK_THREAD (this_obj);
1585
1586         if (mono_error_set_pending_exception (&error))
1587                 return NULL;
1588         
1589         return str;
1590 }
1591
1592 void 
1593 mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean permanent, gboolean reset, MonoError *error)
1594 {
1595         LOCK_THREAD (this_obj);
1596
1597         error_init (error);
1598
1599         if (reset) {
1600                 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1601         } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1602                 UNLOCK_THREAD (this_obj);
1603                 
1604                 mono_error_set_invalid_operation (error, "Thread.Name can only be set once.");
1605                 return;
1606         }
1607         if (this_obj->name) {
1608                 g_free (this_obj->name);
1609                 this_obj->name_len = 0;
1610         }
1611         if (name) {
1612                 this_obj->name = g_memdup (mono_string_chars (name), mono_string_length (name) * sizeof (gunichar2));
1613                 this_obj->name_len = mono_string_length (name);
1614
1615                 if (permanent)
1616                         this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1617         }
1618         else
1619                 this_obj->name = NULL;
1620
1621         
1622         UNLOCK_THREAD (this_obj);
1623
1624         if (this_obj->name && this_obj->tid) {
1625                 char *tname = mono_string_to_utf8_checked (name, error);
1626                 return_if_nok (error);
1627                 MONO_PROFILER_RAISE (thread_name, (this_obj->tid, tname));
1628                 mono_native_thread_set_name (thread_get_tid (this_obj), tname);
1629                 mono_free (tname);
1630         }
1631 }
1632
1633 void 
1634 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1635 {
1636         MonoError error;
1637         mono_thread_set_name_internal (this_obj, name, TRUE, FALSE, &error);
1638         mono_error_set_pending_exception (&error);
1639 }
1640
1641 /*
1642  * ves_icall_System_Threading_Thread_GetPriority_internal:
1643  * @param this_obj: The MonoInternalThread on which to operate.
1644  *
1645  * Gets the priority of the given thread.
1646  * @return: The priority of the given thread.
1647  */
1648 int
1649 ves_icall_System_Threading_Thread_GetPriority (MonoThread *this_obj)
1650 {
1651         gint32 priority;
1652         MonoInternalThread *internal = this_obj->internal_thread;
1653
1654         LOCK_THREAD (internal);
1655         priority = internal->priority;
1656         UNLOCK_THREAD (internal);
1657
1658         return priority;
1659 }
1660
1661 /* 
1662  * ves_icall_System_Threading_Thread_SetPriority_internal:
1663  * @param this_obj: The MonoInternalThread on which to operate.
1664  * @param priority: The priority to set.
1665  *
1666  * Sets the priority of the given thread.
1667  */
1668 void
1669 ves_icall_System_Threading_Thread_SetPriority (MonoThread *this_obj, int priority)
1670 {
1671         MonoInternalThread *internal = this_obj->internal_thread;
1672
1673         LOCK_THREAD (internal);
1674         internal->priority = priority;
1675         if (internal->thread_info != NULL)
1676                 mono_thread_internal_set_priority (internal, priority);
1677         UNLOCK_THREAD (internal);
1678 }
1679
1680 /* If the array is already in the requested domain, we just return it,
1681    otherwise we return a copy in that domain. */
1682 static MonoArray*
1683 byte_array_to_domain (MonoArray *arr, MonoDomain *domain, MonoError *error)
1684 {
1685         MonoArray *copy;
1686
1687         error_init (error);
1688         if (!arr)
1689                 return NULL;
1690
1691         if (mono_object_domain (arr) == domain)
1692                 return arr;
1693
1694         copy = mono_array_new_checked (domain, mono_defaults.byte_class, arr->max_length, error);
1695         memmove (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1696         return copy;
1697 }
1698
1699 MonoArray*
1700 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1701 {
1702         MonoError error;
1703         MonoArray *result = byte_array_to_domain (arr, mono_get_root_domain (), &error);
1704         mono_error_set_pending_exception (&error);
1705         return result;
1706 }
1707
1708 MonoArray*
1709 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1710 {
1711         MonoError error;
1712         MonoArray *result = byte_array_to_domain (arr, mono_domain_get (), &error);
1713         mono_error_set_pending_exception (&error);
1714         return result;
1715 }
1716
1717 /**
1718  * mono_thread_current:
1719  */
1720 MonoThread *
1721 mono_thread_current (void)
1722 {
1723         MonoDomain *domain = mono_domain_get ();
1724         MonoInternalThread *internal = mono_thread_internal_current ();
1725         MonoThread **current_thread_ptr;
1726
1727         g_assert (internal);
1728         current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1729
1730         if (!*current_thread_ptr) {
1731                 g_assert (domain != mono_get_root_domain ());
1732                 *current_thread_ptr = create_thread_object (domain, internal);
1733         }
1734         return *current_thread_ptr;
1735 }
1736
1737 /* Return the thread object belonging to INTERNAL in the current domain */
1738 static MonoThread *
1739 mono_thread_current_for_thread (MonoInternalThread *internal)
1740 {
1741         MonoDomain *domain = mono_domain_get ();
1742         MonoThread **current_thread_ptr;
1743
1744         g_assert (internal);
1745         current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1746
1747         if (!*current_thread_ptr) {
1748                 g_assert (domain != mono_get_root_domain ());
1749                 *current_thread_ptr = create_thread_object (domain, internal);
1750         }
1751         return *current_thread_ptr;
1752 }
1753
1754 MonoInternalThread*
1755 mono_thread_internal_current (void)
1756 {
1757         MonoInternalThread *res = GET_CURRENT_OBJECT ();
1758         THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1759         return res;
1760 }
1761
1762 static MonoThreadInfoWaitRet
1763 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
1764 {
1765         MonoException *exc;
1766         MonoThreadInfoWaitRet ret;
1767         gint64 start;
1768         gint32 diff_ms;
1769         gint32 wait = ms;
1770
1771         error_init (error);
1772
1773         start = (ms == -1) ? 0 : mono_msec_ticks ();
1774         for (;;) {
1775                 MONO_ENTER_GC_SAFE;
1776                 ret = mono_thread_info_wait_one_handle (thread_to_join, ms, TRUE);
1777                 MONO_EXIT_GC_SAFE;
1778
1779                 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
1780                         return ret;
1781
1782                 exc = mono_thread_execute_interruption ();
1783                 if (exc) {
1784                         mono_error_set_exception_instance (error, exc);
1785                         return ret;
1786                 }
1787
1788                 if (ms == -1)
1789                         continue;
1790
1791                 /* Re-calculate ms according to the time passed */
1792                 diff_ms = (gint32)(mono_msec_ticks () - start);
1793                 if (diff_ms >= ms) {
1794                         ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
1795                         return ret;
1796                 }
1797                 wait = ms - diff_ms;
1798         }
1799
1800         return ret;
1801 }
1802
1803 gboolean
1804 ves_icall_System_Threading_Thread_Join_internal(MonoThread *this_obj, int ms)
1805 {
1806         MonoInternalThread *thread = this_obj->internal_thread;
1807         MonoThreadHandle *handle = thread->handle;
1808         MonoInternalThread *cur_thread = mono_thread_internal_current ();
1809         gboolean ret;
1810         MonoError error;
1811
1812         if (mono_thread_current_check_pending_interrupt ())
1813                 return FALSE;
1814
1815         LOCK_THREAD (thread);
1816         
1817         if ((thread->state & ThreadState_Unstarted) != 0) {
1818                 UNLOCK_THREAD (thread);
1819                 
1820                 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started."));
1821                 return FALSE;
1822         }
1823
1824         UNLOCK_THREAD (thread);
1825
1826         if(ms== -1) {
1827                 ms=MONO_INFINITE_WAIT;
1828         }
1829         THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
1830         
1831         mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1832
1833         ret=mono_join_uninterrupted (handle, ms, &error);
1834
1835         mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1836
1837         mono_error_set_pending_exception (&error);
1838
1839         if(ret==MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
1840                 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1841
1842                 return(TRUE);
1843         }
1844         
1845         THREAD_DEBUG (g_message ("%s: join failed", __func__));
1846
1847         return(FALSE);
1848 }
1849
1850 #define MANAGED_WAIT_FAILED 0x7fffffff
1851
1852 static gint32
1853 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
1854 {
1855         if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
1856                 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
1857         } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
1858                 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
1859         } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
1860                 return WAIT_IO_COMPLETION;
1861         } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
1862                 return WAIT_TIMEOUT;
1863         } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
1864                 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
1865                 return MANAGED_WAIT_FAILED;
1866         } else {
1867                 g_error ("%s: unknown val value %d", __func__, val);
1868         }
1869 }
1870
1871 gint32
1872 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
1873 {
1874         MonoW32HandleWaitRet ret;
1875         MonoInternalThread *thread;
1876         MonoException *exc;
1877         gint64 start;
1878         guint32 timeoutLeft;
1879
1880         /* Do this WaitSleepJoin check before creating objects */
1881         if (mono_thread_current_check_pending_interrupt ())
1882                 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
1883
1884         thread = mono_thread_internal_current ();
1885
1886         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1887
1888         if (timeout == -1)
1889                 timeout = MONO_INFINITE_WAIT;
1890         if (timeout != MONO_INFINITE_WAIT)
1891                 start = mono_msec_ticks ();
1892
1893         timeoutLeft = timeout;
1894
1895         for (;;) {
1896                 MONO_ENTER_GC_SAFE;
1897 #ifdef HOST_WIN32
1898                 if (numhandles != 1)
1899                         ret = mono_w32handle_convert_wait_ret (WaitForMultipleObjectsEx (numhandles, handles, waitall, timeoutLeft, TRUE), numhandles);
1900                 else
1901                         ret = mono_w32handle_convert_wait_ret (WaitForSingleObjectEx (handles [0], timeoutLeft, TRUE), 1);
1902 #else
1903                 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
1904                 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE);
1905 #endif /* HOST_WIN32 */
1906                 MONO_EXIT_GC_SAFE;
1907
1908                 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
1909                         break;
1910
1911                 exc = mono_thread_execute_interruption ();
1912                 if (exc) {
1913                         mono_error_set_exception_instance (error, exc);
1914                         break;
1915                 }
1916
1917                 if (timeout != MONO_INFINITE_WAIT) {
1918                         gint64 elapsed;
1919
1920                         elapsed = mono_msec_ticks () - start;
1921                         if (elapsed >= timeout) {
1922                                 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
1923                                 break;
1924                         }
1925
1926                         timeoutLeft = timeout - elapsed;
1927                 }
1928         }
1929
1930         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1931
1932         return map_native_wait_result_to_managed (ret, numhandles);
1933 }
1934
1935 gint32
1936 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
1937 {
1938         MonoW32HandleWaitRet ret;
1939         MonoInternalThread *thread = mono_thread_internal_current ();
1940
1941         if (ms == -1)
1942                 ms = MONO_INFINITE_WAIT;
1943
1944         if (mono_thread_current_check_pending_interrupt ())
1945                 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
1946
1947         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1948         
1949         MONO_ENTER_GC_SAFE;
1950 #ifdef HOST_WIN32
1951         ret = mono_w32handle_convert_wait_ret (SignalObjectAndWait (toSignal, toWait, ms, TRUE), 1);
1952 #else
1953         ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
1954 #endif
1955         MONO_EXIT_GC_SAFE;
1956         
1957         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1958
1959         return map_native_wait_result_to_managed (ret, 1);
1960 }
1961
1962 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1963 {
1964         return InterlockedIncrement (location);
1965 }
1966
1967 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1968 {
1969 #if SIZEOF_VOID_P == 4
1970         if (G_UNLIKELY ((size_t)location & 0x7)) {
1971                 gint64 ret;
1972                 mono_interlocked_lock ();
1973                 (*location)++;
1974                 ret = *location;
1975                 mono_interlocked_unlock ();
1976                 return ret;
1977         }
1978 #endif
1979         return InterlockedIncrement64 (location);
1980 }
1981
1982 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1983 {
1984         return InterlockedDecrement(location);
1985 }
1986
1987 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1988 {
1989 #if SIZEOF_VOID_P == 4
1990         if (G_UNLIKELY ((size_t)location & 0x7)) {
1991                 gint64 ret;
1992                 mono_interlocked_lock ();
1993                 (*location)--;
1994                 ret = *location;
1995                 mono_interlocked_unlock ();
1996                 return ret;
1997         }
1998 #endif
1999         return InterlockedDecrement64 (location);
2000 }
2001
2002 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2003 {
2004         return InterlockedExchange(location, value);
2005 }
2006
2007 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
2008 {
2009         MonoObject *res;
2010         res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
2011         mono_gc_wbarrier_generic_nostore (location);
2012         return res;
2013 }
2014
2015 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2016 {
2017         return InterlockedExchangePointer(location, value);
2018 }
2019
2020 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2021 {
2022         IntFloatUnion val, ret;
2023
2024         val.fval = value;
2025         ret.ival = InterlockedExchange((gint32 *) location, val.ival);
2026
2027         return ret.fval;
2028 }
2029
2030 gint64 
2031 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2032 {
2033 #if SIZEOF_VOID_P == 4
2034         if (G_UNLIKELY ((size_t)location & 0x7)) {
2035                 gint64 ret;
2036                 mono_interlocked_lock ();
2037                 ret = *location;
2038                 *location = value;
2039                 mono_interlocked_unlock ();
2040                 return ret;
2041         }
2042 #endif
2043         return InterlockedExchange64 (location, value);
2044 }
2045
2046 gdouble 
2047 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2048 {
2049         LongDoubleUnion val, ret;
2050
2051         val.fval = value;
2052         ret.ival = (gint64)InterlockedExchange64((gint64 *) location, val.ival);
2053
2054         return ret.fval;
2055 }
2056
2057 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2058 {
2059         return InterlockedCompareExchange(location, value, comparand);
2060 }
2061
2062 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2063 {
2064         gint32 r = InterlockedCompareExchange(location, value, comparand);
2065         *success = r == comparand;
2066         return r;
2067 }
2068
2069 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
2070 {
2071         MonoObject *res;
2072         res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
2073         mono_gc_wbarrier_generic_nostore (location);
2074         return res;
2075 }
2076
2077 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2078 {
2079         return InterlockedCompareExchangePointer(location, value, comparand);
2080 }
2081
2082 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2083 {
2084         IntFloatUnion val, ret, cmp;
2085
2086         val.fval = value;
2087         cmp.fval = comparand;
2088         ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
2089
2090         return ret.fval;
2091 }
2092
2093 gdouble
2094 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2095 {
2096 #if SIZEOF_VOID_P == 8
2097         LongDoubleUnion val, comp, ret;
2098
2099         val.fval = value;
2100         comp.fval = comparand;
2101         ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2102
2103         return ret.fval;
2104 #else
2105         gdouble old;
2106
2107         mono_interlocked_lock ();
2108         old = *location;
2109         if (old == comparand)
2110                 *location = value;
2111         mono_interlocked_unlock ();
2112
2113         return old;
2114 #endif
2115 }
2116
2117 gint64 
2118 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2119 {
2120 #if SIZEOF_VOID_P == 4
2121         if (G_UNLIKELY ((size_t)location & 0x7)) {
2122                 gint64 old;
2123                 mono_interlocked_lock ();
2124                 old = *location;
2125                 if (old == comparand)
2126                         *location = value;
2127                 mono_interlocked_unlock ();
2128                 return old;
2129         }
2130 #endif
2131         return InterlockedCompareExchange64 (location, value, comparand);
2132 }
2133
2134 MonoObject*
2135 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2136 {
2137         MonoObject *res;
2138         res = (MonoObject *)InterlockedCompareExchangePointer ((volatile gpointer *)location, value, comparand);
2139         mono_gc_wbarrier_generic_nostore (location);
2140         return res;
2141 }
2142
2143 MonoObject*
2144 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2145 {
2146         MonoObject *res;
2147         MONO_CHECK_NULL (location, NULL);
2148         res = (MonoObject *)InterlockedExchangePointer ((volatile gpointer *)location, value);
2149         mono_gc_wbarrier_generic_nostore (location);
2150         return res;
2151 }
2152
2153 gint32 
2154 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2155 {
2156         return InterlockedAdd (location, value);
2157 }
2158
2159 gint64 
2160 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2161 {
2162 #if SIZEOF_VOID_P == 4
2163         if (G_UNLIKELY ((size_t)location & 0x7)) {
2164                 gint64 ret;
2165                 mono_interlocked_lock ();
2166                 *location += value;
2167                 ret = *location;
2168                 mono_interlocked_unlock ();
2169                 return ret;
2170         }
2171 #endif
2172         return InterlockedAdd64 (location, value);
2173 }
2174
2175 gint64 
2176 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2177 {
2178 #if SIZEOF_VOID_P == 4
2179         if (G_UNLIKELY ((size_t)location & 0x7)) {
2180                 gint64 ret;
2181                 mono_interlocked_lock ();
2182                 ret = *location;
2183                 mono_interlocked_unlock ();
2184                 return ret;
2185         }
2186 #endif
2187         return InterlockedRead64 (location);
2188 }
2189
2190 void
2191 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2192 {
2193         mono_memory_barrier ();
2194 }
2195
2196 void
2197 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this_obj, guint32 state)
2198 {
2199         mono_thread_clr_state (this_obj, (MonoThreadState)state);
2200
2201         if (state & ThreadState_Background) {
2202                 /* If the thread changes the background mode, the main thread has to
2203                  * be notified, since it has to rebuild the list of threads to
2204                  * wait for.
2205                  */
2206                 mono_os_event_set (&background_change_event);
2207         }
2208 }
2209
2210 void
2211 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this_obj, guint32 state)
2212 {
2213         mono_thread_set_state (this_obj, (MonoThreadState)state);
2214         
2215         if (state & ThreadState_Background) {
2216                 /* If the thread changes the background mode, the main thread has to
2217                  * be notified, since it has to rebuild the list of threads to
2218                  * wait for.
2219                  */
2220                 mono_os_event_set (&background_change_event);
2221         }
2222 }
2223
2224 guint32
2225 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this_obj)
2226 {
2227         guint32 state;
2228
2229         LOCK_THREAD (this_obj);
2230         
2231         state = this_obj->state;
2232
2233         UNLOCK_THREAD (this_obj);
2234         
2235         return state;
2236 }
2237
2238 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this_obj)
2239 {
2240         MonoInternalThread *current;
2241         gboolean throw_;
2242         MonoInternalThread *thread = this_obj->internal_thread;
2243
2244         LOCK_THREAD (thread);
2245
2246         current = mono_thread_internal_current ();
2247
2248         thread->thread_interrupt_requested = TRUE;
2249         throw_ = current != thread && (thread->state & ThreadState_WaitSleepJoin);
2250
2251         UNLOCK_THREAD (thread);
2252
2253         if (throw_) {
2254                 async_abort_internal (thread, FALSE);
2255         }
2256 }
2257
2258 /**
2259  * mono_thread_current_check_pending_interrupt:
2260  * Checks if there's a interruption request and set the pending exception if so.
2261  * \returns true if a pending exception was set
2262  */
2263 gboolean
2264 mono_thread_current_check_pending_interrupt (void)
2265 {
2266         MonoInternalThread *thread = mono_thread_internal_current ();
2267         gboolean throw_ = FALSE;
2268
2269         LOCK_THREAD (thread);
2270         
2271         if (thread->thread_interrupt_requested) {
2272                 throw_ = TRUE;
2273                 thread->thread_interrupt_requested = FALSE;
2274         }
2275         
2276         UNLOCK_THREAD (thread);
2277
2278         if (throw_)
2279                 mono_set_pending_exception (mono_get_exception_thread_interrupted ());
2280         return throw_;
2281 }
2282
2283 static gboolean
2284 request_thread_abort (MonoInternalThread *thread, MonoObject *state)
2285 {
2286         LOCK_THREAD (thread);
2287         
2288         if (thread->state & (ThreadState_AbortRequested | ThreadState_Stopped))
2289         {
2290                 UNLOCK_THREAD (thread);
2291                 return FALSE;
2292         }
2293
2294         if ((thread->state & ThreadState_Unstarted) != 0) {
2295                 thread->state |= ThreadState_Aborted;
2296                 UNLOCK_THREAD (thread);
2297                 return FALSE;
2298         }
2299
2300         thread->state |= ThreadState_AbortRequested;
2301         if (thread->abort_state_handle)
2302                 mono_gchandle_free (thread->abort_state_handle);
2303         if (state) {
2304                 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2305                 g_assert (thread->abort_state_handle);
2306         } else {
2307                 thread->abort_state_handle = 0;
2308         }
2309         thread->abort_exc = NULL;
2310
2311         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, mono_native_thread_id_get (), thread, (gsize)thread->tid));
2312
2313         /* During shutdown, we can't wait for other threads */
2314         if (!shutting_down)
2315                 /* Make sure the thread is awake */
2316                 mono_thread_resume (thread);
2317
2318         UNLOCK_THREAD (thread);
2319         return TRUE;
2320 }
2321
2322 void
2323 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2324 {
2325         if (!request_thread_abort (thread, state))
2326                 return;
2327
2328         if (thread == mono_thread_internal_current ()) {
2329                 MonoError error;
2330                 self_abort_internal (&error);
2331                 mono_error_set_pending_exception (&error);
2332         } else {
2333                 async_abort_internal (thread, TRUE);
2334         }
2335 }
2336
2337 /**
2338  * mono_thread_internal_abort:
2339  * Request thread \p thread to be aborted.
2340  * \p thread MUST NOT be the current thread.
2341  */
2342 void
2343 mono_thread_internal_abort (MonoInternalThread *thread)
2344 {
2345         g_assert (thread != mono_thread_internal_current ());
2346
2347         if (!request_thread_abort (thread, NULL))
2348                 return;
2349         async_abort_internal (thread, TRUE);
2350 }
2351
2352 void
2353 ves_icall_System_Threading_Thread_ResetAbort (MonoThread *this_obj)
2354 {
2355         MonoInternalThread *thread = mono_thread_internal_current ();
2356         gboolean was_aborting;
2357
2358         LOCK_THREAD (thread);
2359         was_aborting = thread->state & ThreadState_AbortRequested;
2360         thread->state &= ~ThreadState_AbortRequested;
2361         UNLOCK_THREAD (thread);
2362
2363         if (!was_aborting) {
2364                 const char *msg = "Unable to reset abort because no abort was requested";
2365                 mono_set_pending_exception (mono_get_exception_thread_state (msg));
2366                 return;
2367         }
2368
2369         mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2370         thread->abort_exc = NULL;
2371         if (thread->abort_state_handle) {
2372                 mono_gchandle_free (thread->abort_state_handle);
2373                 /* This is actually not necessary - the handle
2374                    only counts if the exception is set */
2375                 thread->abort_state_handle = 0;
2376         }
2377 }
2378
2379 void
2380 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2381 {
2382         LOCK_THREAD (thread);
2383
2384         thread->state &= ~ThreadState_AbortRequested;
2385
2386         if (thread->abort_exc) {
2387                 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2388                 thread->abort_exc = NULL;
2389                 if (thread->abort_state_handle) {
2390                         mono_gchandle_free (thread->abort_state_handle);
2391                         /* This is actually not necessary - the handle
2392                            only counts if the exception is set */
2393                         thread->abort_state_handle = 0;
2394                 }
2395         }
2396
2397         UNLOCK_THREAD (thread);
2398 }
2399
2400 MonoObject*
2401 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this_obj)
2402 {
2403         MonoError error;
2404         MonoInternalThread *thread = this_obj->internal_thread;
2405         MonoObject *state, *deserialized = NULL;
2406         MonoDomain *domain;
2407
2408         if (!thread->abort_state_handle)
2409                 return NULL;
2410
2411         state = mono_gchandle_get_target (thread->abort_state_handle);
2412         g_assert (state);
2413
2414         domain = mono_domain_get ();
2415         if (mono_object_domain (state) == domain)
2416                 return state;
2417
2418         deserialized = mono_object_xdomain_representation (state, domain, &error);
2419
2420         if (!deserialized) {
2421                 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2422                 if (!is_ok (&error)) {
2423                         MonoObject *exc = (MonoObject*)mono_error_convert_to_exception (&error);
2424                         MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2425                 }
2426                 mono_set_pending_exception (invalid_op_exc);
2427                 return NULL;
2428         }
2429
2430         return deserialized;
2431 }
2432
2433 static gboolean
2434 mono_thread_suspend (MonoInternalThread *thread)
2435 {
2436         LOCK_THREAD (thread);
2437
2438         if (thread->state & (ThreadState_Unstarted | ThreadState_Aborted | ThreadState_Stopped))
2439         {
2440                 UNLOCK_THREAD (thread);
2441                 return FALSE;
2442         }
2443
2444         if (thread->state & (ThreadState_Suspended | ThreadState_SuspendRequested | ThreadState_AbortRequested))
2445         {
2446                 UNLOCK_THREAD (thread);
2447                 return TRUE;
2448         }
2449         
2450         thread->state |= ThreadState_SuspendRequested;
2451         mono_os_event_reset (thread->suspended);
2452
2453         if (thread == mono_thread_internal_current ()) {
2454                 /* calls UNLOCK_THREAD (thread) */
2455                 self_suspend_internal ();
2456         } else {
2457                 /* calls UNLOCK_THREAD (thread) */
2458                 async_suspend_internal (thread, FALSE);
2459         }
2460
2461         return TRUE;
2462 }
2463
2464 void
2465 ves_icall_System_Threading_Thread_Suspend (MonoThread *this_obj)
2466 {
2467         if (!mono_thread_suspend (this_obj->internal_thread)) {
2468                 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2469                 return;
2470         }
2471 }
2472
2473 /* LOCKING: LOCK_THREAD(thread) must be held */
2474 static gboolean
2475 mono_thread_resume (MonoInternalThread *thread)
2476 {
2477         if ((thread->state & ThreadState_SuspendRequested) != 0) {
2478                 // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (1) thread %p\n", thread_get_tid (thread));
2479                 thread->state &= ~ThreadState_SuspendRequested;
2480                 mono_os_event_set (thread->suspended);
2481                 return TRUE;
2482         }
2483
2484         if ((thread->state & ThreadState_Suspended) == 0 ||
2485                 (thread->state & ThreadState_Unstarted) != 0 || 
2486                 (thread->state & ThreadState_Aborted) != 0 || 
2487                 (thread->state & ThreadState_Stopped) != 0)
2488         {
2489                 // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (2) thread %p\n", thread_get_tid (thread));
2490                 return FALSE;
2491         }
2492
2493         // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (3) thread %p\n", thread_get_tid (thread));
2494
2495         mono_os_event_set (thread->suspended);
2496
2497         if (!thread->self_suspended) {
2498                 UNLOCK_THREAD (thread);
2499
2500                 /* Awake the thread */
2501                 if (!mono_thread_info_resume (thread_get_tid (thread)))
2502                         return FALSE;
2503
2504                 LOCK_THREAD (thread);
2505         }
2506
2507         thread->state &= ~ThreadState_Suspended;
2508
2509         return TRUE;
2510 }
2511
2512 void
2513 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2514 {
2515         if (!thread->internal_thread) {
2516                 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2517         } else {
2518                 LOCK_THREAD (thread->internal_thread);
2519                 if (!mono_thread_resume (thread->internal_thread))
2520                         mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2521                 UNLOCK_THREAD (thread->internal_thread);
2522         }
2523 }
2524
2525 static gboolean
2526 mono_threads_is_critical_method (MonoMethod *method)
2527 {
2528         switch (method->wrapper_type) {
2529         case MONO_WRAPPER_RUNTIME_INVOKE:
2530         case MONO_WRAPPER_XDOMAIN_INVOKE:
2531         case MONO_WRAPPER_XDOMAIN_DISPATCH:     
2532                 return TRUE;
2533         }
2534         return FALSE;
2535 }
2536
2537 static gboolean
2538 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2539 {
2540         if (managed)
2541                 return TRUE;
2542
2543         if (mono_threads_is_critical_method (m)) {
2544                 *((gboolean*)data) = TRUE;
2545                 return TRUE;
2546         }
2547         return FALSE;
2548 }
2549
2550 static gboolean 
2551 is_running_protected_wrapper (void)
2552 {
2553         gboolean found = FALSE;
2554         mono_stack_walk (find_wrapper, &found);
2555         return found;
2556 }
2557
2558 /**
2559  * mono_thread_stop:
2560  */
2561 void
2562 mono_thread_stop (MonoThread *thread)
2563 {
2564         MonoInternalThread *internal = thread->internal_thread;
2565
2566         if (!request_thread_abort (internal, NULL))
2567                 return;
2568
2569         if (internal == mono_thread_internal_current ()) {
2570                 MonoError error;
2571                 self_abort_internal (&error);
2572                 /*
2573                 This function is part of the embeding API and has no way to return the exception
2574                 to be thrown. So what we do is keep the old behavior and raise the exception.
2575                 */
2576                 mono_error_raise_exception (&error); /* OK to throw, see note */
2577         } else {
2578                 async_abort_internal (internal, TRUE);
2579         }
2580 }
2581
2582 gint8
2583 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2584 {
2585         gint8 tmp = *(volatile gint8 *)ptr;
2586         mono_memory_barrier ();
2587         return tmp;
2588 }
2589
2590 gint16
2591 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2592 {
2593         gint16 tmp = *(volatile gint16 *)ptr;
2594         mono_memory_barrier ();
2595         return tmp;
2596 }
2597
2598 gint32
2599 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2600 {
2601         gint32 tmp = *(volatile gint32 *)ptr;
2602         mono_memory_barrier ();
2603         return tmp;
2604 }
2605
2606 gint64
2607 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2608 {
2609         gint64 tmp = *(volatile gint64 *)ptr;
2610         mono_memory_barrier ();
2611         return tmp;
2612 }
2613
2614 void *
2615 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2616 {
2617         volatile void *tmp = *(volatile void **)ptr;
2618         mono_memory_barrier ();
2619         return (void *) tmp;
2620 }
2621
2622 void *
2623 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
2624 {
2625         volatile MonoObject *tmp = *(volatile MonoObject **)ptr;
2626         mono_memory_barrier ();
2627         return (MonoObject *) tmp;
2628 }
2629
2630 double
2631 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
2632 {
2633         double tmp = *(volatile double *)ptr;
2634         mono_memory_barrier ();
2635         return tmp;
2636 }
2637
2638 float
2639 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
2640 {
2641         float tmp = *(volatile float *)ptr;
2642         mono_memory_barrier ();
2643         return tmp;
2644 }
2645
2646 gint8
2647 ves_icall_System_Threading_Volatile_Read1 (void *ptr)
2648 {
2649         return InterlockedRead8 ((volatile gint8 *)ptr);
2650 }
2651
2652 gint16
2653 ves_icall_System_Threading_Volatile_Read2 (void *ptr)
2654 {
2655         return InterlockedRead16 ((volatile gint16 *)ptr);
2656 }
2657
2658 gint32
2659 ves_icall_System_Threading_Volatile_Read4 (void *ptr)
2660 {
2661         return InterlockedRead ((volatile gint32 *)ptr);
2662 }
2663
2664 gint64
2665 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
2666 {
2667 #if SIZEOF_VOID_P == 4
2668         if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2669                 gint64 val;
2670                 mono_interlocked_lock ();
2671                 val = *(gint64*)ptr;
2672                 mono_interlocked_unlock ();
2673                 return val;
2674         }
2675 #endif
2676         return InterlockedRead64 ((volatile gint64 *)ptr);
2677 }
2678
2679 void *
2680 ves_icall_System_Threading_Volatile_ReadIntPtr (void *ptr)
2681 {
2682         return InterlockedReadPointer ((volatile gpointer *)ptr);
2683 }
2684
2685 double
2686 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
2687 {
2688         LongDoubleUnion u;
2689
2690 #if SIZEOF_VOID_P == 4
2691         if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2692                 double val;
2693                 mono_interlocked_lock ();
2694                 val = *(double*)ptr;
2695                 mono_interlocked_unlock ();
2696                 return val;
2697         }
2698 #endif
2699
2700         u.ival = InterlockedRead64 ((volatile gint64 *)ptr);
2701
2702         return u.fval;
2703 }
2704
2705 float
2706 ves_icall_System_Threading_Volatile_ReadFloat (void *ptr)
2707 {
2708         IntFloatUnion u;
2709
2710         u.ival = InterlockedRead ((volatile gint32 *)ptr);
2711
2712         return u.fval;
2713 }
2714
2715 MonoObject*
2716 ves_icall_System_Threading_Volatile_Read_T (void *ptr)
2717 {
2718         return (MonoObject *)InterlockedReadPointer ((volatile gpointer *)ptr);
2719 }
2720
2721 void
2722 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2723 {
2724         mono_memory_barrier ();
2725         *(volatile gint8 *)ptr = value;
2726 }
2727
2728 void
2729 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2730 {
2731         mono_memory_barrier ();
2732         *(volatile gint16 *)ptr = value;
2733 }
2734
2735 void
2736 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2737 {
2738         mono_memory_barrier ();
2739         *(volatile gint32 *)ptr = value;
2740 }
2741
2742 void
2743 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2744 {
2745         mono_memory_barrier ();
2746         *(volatile gint64 *)ptr = value;
2747 }
2748
2749 void
2750 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2751 {
2752         mono_memory_barrier ();
2753         *(volatile void **)ptr = value;
2754 }
2755
2756 void
2757 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
2758 {
2759         mono_memory_barrier ();
2760         mono_gc_wbarrier_generic_store (ptr, value);
2761 }
2762
2763 void
2764 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
2765 {
2766         mono_memory_barrier ();
2767         *(volatile double *)ptr = value;
2768 }
2769
2770 void
2771 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
2772 {
2773         mono_memory_barrier ();
2774         *(volatile float *)ptr = value;
2775 }
2776
2777 void
2778 ves_icall_System_Threading_Volatile_Write1 (void *ptr, gint8 value)
2779 {
2780         InterlockedWrite8 ((volatile gint8 *)ptr, value);
2781 }
2782
2783 void
2784 ves_icall_System_Threading_Volatile_Write2 (void *ptr, gint16 value)
2785 {
2786         InterlockedWrite16 ((volatile gint16 *)ptr, value);
2787 }
2788
2789 void
2790 ves_icall_System_Threading_Volatile_Write4 (void *ptr, gint32 value)
2791 {
2792         InterlockedWrite ((volatile gint32 *)ptr, value);
2793 }
2794
2795 void
2796 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
2797 {
2798 #if SIZEOF_VOID_P == 4
2799         if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2800                 mono_interlocked_lock ();
2801                 *(gint64*)ptr = value;
2802                 mono_interlocked_unlock ();
2803                 return;
2804         }
2805 #endif
2806
2807         InterlockedWrite64 ((volatile gint64 *)ptr, value);
2808 }
2809
2810 void
2811 ves_icall_System_Threading_Volatile_WriteIntPtr (void *ptr, void *value)
2812 {
2813         InterlockedWritePointer ((volatile gpointer *)ptr, value);
2814 }
2815
2816 void
2817 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
2818 {
2819         LongDoubleUnion u;
2820
2821 #if SIZEOF_VOID_P == 4
2822         if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2823                 mono_interlocked_lock ();
2824                 *(double*)ptr = value;
2825                 mono_interlocked_unlock ();
2826                 return;
2827         }
2828 #endif
2829
2830         u.fval = value;
2831
2832         InterlockedWrite64 ((volatile gint64 *)ptr, u.ival);
2833 }
2834
2835 void
2836 ves_icall_System_Threading_Volatile_WriteFloat (void *ptr, float value)
2837 {
2838         IntFloatUnion u;
2839
2840         u.fval = value;
2841
2842         InterlockedWrite ((volatile gint32 *)ptr, u.ival);
2843 }
2844
2845 void
2846 ves_icall_System_Threading_Volatile_Write_T (void *ptr, MonoObject *value)
2847 {
2848         mono_gc_wbarrier_generic_store_atomic (ptr, value);
2849 }
2850
2851 static void
2852 free_context (void *user_data)
2853 {
2854         ContextStaticData *data = user_data;
2855
2856         mono_threads_lock ();
2857
2858         /*
2859          * There is no guarantee that, by the point this reference queue callback
2860          * has been invoked, the GC handle associated with the object will fail to
2861          * resolve as one might expect. So if we don't free and remove the GC
2862          * handle here, free_context_static_data_helper () could end up resolving
2863          * a GC handle to an actually-dead context which would contain a pointer
2864          * to an already-freed static data segment, resulting in a crash when
2865          * accessing it.
2866          */
2867         g_hash_table_remove (contexts, GUINT_TO_POINTER (data->gc_handle));
2868
2869         mono_threads_unlock ();
2870
2871         mono_gchandle_free (data->gc_handle);
2872         mono_free_static_data (data->static_data);
2873         g_free (data);
2874 }
2875
2876 void
2877 mono_threads_register_app_context (MonoAppContext *ctx, MonoError *error)
2878 {
2879         error_init (error);
2880         mono_threads_lock ();
2881
2882         //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
2883
2884         if (!contexts)
2885                 contexts = g_hash_table_new (NULL, NULL);
2886
2887         if (!context_queue)
2888                 context_queue = mono_gc_reference_queue_new (free_context);
2889
2890         gpointer gch = GUINT_TO_POINTER (mono_gchandle_new_weakref (&ctx->obj, FALSE));
2891         g_hash_table_insert (contexts, gch, gch);
2892
2893         /*
2894          * We use this intermediate structure to contain a duplicate pointer to
2895          * the static data because we can't rely on being able to resolve the GC
2896          * handle in the reference queue callback.
2897          */
2898         ContextStaticData *data = g_new0 (ContextStaticData, 1);
2899         data->gc_handle = GPOINTER_TO_UINT (gch);
2900         ctx->data = data;
2901
2902         context_adjust_static_data (ctx);
2903         mono_gc_reference_queue_add (context_queue, &ctx->obj, data);
2904
2905         mono_threads_unlock ();
2906
2907         MONO_PROFILER_RAISE (context_loaded, (ctx));
2908 }
2909
2910 void
2911 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx, MonoError *error)
2912 {
2913         error_init (error);
2914         mono_threads_register_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_register_app_context */
2915 }
2916
2917 void
2918 mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error)
2919 {
2920         /*
2921          * NOTE: Since finalizers are unreliable for the purposes of ensuring
2922          * cleanup in exceptional circumstances, we don't actually do any
2923          * cleanup work here. We instead do this via a reference queue.
2924          */
2925
2926         //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
2927
2928         MONO_PROFILER_RAISE (context_unloaded, (ctx));
2929 }
2930
2931 void
2932 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx, MonoError *error)
2933 {
2934         error_init (error);
2935         mono_threads_release_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_release_app_context */
2936 }
2937
2938 void mono_thread_init (MonoThreadStartCB start_cb,
2939                        MonoThreadAttachCB attach_cb)
2940 {
2941         mono_coop_mutex_init_recursive (&threads_mutex);
2942
2943         mono_os_mutex_init_recursive(&interlocked_mutex);
2944         mono_os_mutex_init_recursive(&joinable_threads_mutex);
2945         
2946         mono_os_event_init (&background_change_event, FALSE);
2947         
2948         mono_init_static_data_info (&thread_static_info);
2949         mono_init_static_data_info (&context_static_info);
2950
2951         mono_thread_start_cb = start_cb;
2952         mono_thread_attach_cb = attach_cb;
2953 }
2954
2955 static gpointer
2956 thread_attach (MonoThreadInfo *info)
2957 {
2958         return mono_gc_thread_attach (info);
2959 }
2960
2961 static void
2962 thread_detach (MonoThreadInfo *info)
2963 {
2964         MonoInternalThread *internal;
2965         guint32 gchandle;
2966
2967         /* If a delegate is passed to native code and invoked on a thread we dont
2968          * know about, marshal will register it with mono_threads_attach_coop, but
2969          * we have no way of knowing when that thread goes away.  SGen has a TSD
2970          * so we assume that if the domain is still registered, we can detach
2971          * the thread */
2972
2973         g_assert (info);
2974
2975         if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
2976                 return;
2977
2978         internal = (MonoInternalThread*) mono_gchandle_get_target (gchandle);
2979         g_assert (internal);
2980
2981         mono_gchandle_free (gchandle);
2982
2983         mono_thread_detach_internal (internal);
2984 }
2985
2986 static void
2987 thread_detach_with_lock (MonoThreadInfo *info)
2988 {
2989         return mono_gc_thread_detach_with_lock (info);
2990 }
2991
2992 static gboolean
2993 thread_in_critical_region (MonoThreadInfo *info)
2994 {
2995         return mono_gc_thread_in_critical_region (info);
2996 }
2997
2998 static gboolean
2999 ip_in_critical_region (MonoDomain *domain, gpointer ip)
3000 {
3001         MonoJitInfo *ji;
3002         MonoMethod *method;
3003
3004         /*
3005          * We pass false for 'try_aot' so this becomes async safe.
3006          * It won't find aot methods whose jit info is not yet loaded,
3007          * so we preload their jit info in the JIT.
3008          */
3009         ji = mono_jit_info_table_find_internal (domain, ip, FALSE, FALSE);
3010         if (!ji)
3011                 return FALSE;
3012
3013         method = mono_jit_info_get_method (ji);
3014         g_assert (method);
3015
3016         return mono_gc_is_critical_method (method);
3017 }
3018
3019 void
3020 mono_thread_callbacks_init (void)
3021 {
3022         MonoThreadInfoCallbacks cb;
3023
3024         memset (&cb, 0, sizeof(cb));
3025         cb.thread_attach = thread_attach;
3026         cb.thread_detach = thread_detach;
3027         cb.thread_detach_with_lock = thread_detach_with_lock;
3028         cb.ip_in_critical_region = ip_in_critical_region;
3029         cb.thread_in_critical_region = thread_in_critical_region;
3030         mono_thread_info_callbacks_init (&cb);
3031 }
3032
3033 /**
3034  * mono_thread_cleanup:
3035  */
3036 void
3037 mono_thread_cleanup (void)
3038 {
3039 #if !defined(RUN_IN_SUBTHREAD) && !defined(HOST_WIN32)
3040         /* The main thread must abandon any held mutexes (particularly
3041          * important for named mutexes as they are shared across
3042          * processes, see bug 74680.)  This will happen when the
3043          * thread exits, but if it's not running in a subthread it
3044          * won't exit in time.
3045          */
3046         mono_w32mutex_abandon ();
3047 #endif
3048
3049 #if 0
3050         /* This stuff needs more testing, it seems one of these
3051          * critical sections can be locked when mono_thread_cleanup is
3052          * called.
3053          */
3054         mono_coop_mutex_destroy (&threads_mutex);
3055         mono_os_mutex_destroy (&interlocked_mutex);
3056         mono_os_mutex_destroy (&delayed_free_table_mutex);
3057         mono_os_mutex_destroy (&small_id_mutex);
3058         mono_os_event_destroy (&background_change_event);
3059 #endif
3060 }
3061
3062 void
3063 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
3064 {
3065         mono_thread_cleanup_fn = func;
3066 }
3067
3068 /**
3069  * mono_thread_set_manage_callback:
3070  */
3071 void
3072 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
3073 {
3074         thread->internal_thread->manage_callback = func;
3075 }
3076
3077 G_GNUC_UNUSED
3078 static void print_tids (gpointer key, gpointer value, gpointer user)
3079 {
3080         /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3081          * sizeof(uint) and a cast to uint would overflow
3082          */
3083         /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3084          * print this as a pointer.
3085          */
3086         g_message ("Waiting for: %p", key);
3087 }
3088
3089 struct wait_data 
3090 {
3091         MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3092         MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3093         guint32 num;
3094 };
3095
3096 static void
3097 wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
3098 {
3099         guint32 i;
3100         MonoThreadInfoWaitRet ret;
3101         
3102         THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
3103
3104         /* Add the thread state change event, so it wakes
3105          * up if a thread changes to background mode. */
3106
3107         MONO_ENTER_GC_SAFE;
3108         if (check_state_change)
3109                 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, &background_change_event, FALSE, timeout, TRUE);
3110         else
3111                 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, NULL, TRUE, timeout, TRUE);
3112         MONO_EXIT_GC_SAFE;
3113
3114         if (ret == MONO_THREAD_INFO_WAIT_RET_FAILED) {
3115                 /* See the comment in build_wait_tids() */
3116                 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
3117                 return;
3118         }
3119         
3120         for( i = 0; i < wait->num; i++)
3121                 mono_threads_close_thread_handle (wait->handles [i]);
3122
3123         if (ret == MONO_THREAD_INFO_WAIT_RET_TIMEOUT)
3124                 return;
3125         
3126         if (ret < wait->num) {
3127                 MonoInternalThread *internal;
3128
3129                 internal = wait->threads [ret];
3130
3131                 mono_threads_lock ();
3132                 if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
3133                         g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
3134                 mono_threads_unlock ();
3135         }
3136 }
3137
3138 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
3139 {
3140         struct wait_data *wait=(struct wait_data *)user;
3141
3142         if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
3143                 MonoInternalThread *thread=(MonoInternalThread *)value;
3144
3145                 /* Ignore background threads, we abort them later */
3146                 /* Do not lock here since it is not needed and the caller holds threads_lock */
3147                 if (thread->state & ThreadState_Background) {
3148                         THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3149                         return; /* just leave, ignore */
3150                 }
3151                 
3152                 if (mono_gc_is_finalizer_internal_thread (thread)) {
3153                         THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3154                         return;
3155                 }
3156
3157                 if (thread == mono_thread_internal_current ()) {
3158                         THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3159                         return;
3160                 }
3161
3162                 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
3163                         THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3164                         return;
3165                 }
3166
3167                 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
3168                         THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
3169                         return;
3170                 }
3171
3172                 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
3173                 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
3174                         wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
3175                         wait->threads[wait->num]=thread;
3176                         wait->num++;
3177
3178                         THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3179                 } else {
3180                         THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3181                 }
3182                 
3183                 
3184         } else {
3185                 /* Just ignore the rest, we can't do anything with
3186                  * them yet
3187                  */
3188         }
3189 }
3190
3191 static gboolean
3192 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
3193 {
3194         struct wait_data *wait=(struct wait_data *)user;
3195         MonoNativeThreadId self = mono_native_thread_id_get ();
3196         MonoInternalThread *thread = (MonoInternalThread *)value;
3197
3198         if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
3199                 return FALSE;
3200
3201         if (mono_native_thread_id_equals (thread_get_tid (thread), self))
3202                 return FALSE;
3203         if (mono_gc_is_finalizer_internal_thread (thread))
3204                 return FALSE;
3205
3206         if ((thread->state & ThreadState_Background) && !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3207                 wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
3208                 wait->threads[wait->num] = thread;
3209                 wait->num++;
3210
3211                 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
3212                 mono_thread_internal_abort (thread);
3213         }
3214
3215         return TRUE;
3216 }
3217
3218 /** 
3219  * mono_threads_set_shutting_down:
3220  *
3221  * Is called by a thread that wants to shut down Mono. If the runtime is already
3222  * shutting down, the calling thread is suspended/stopped, and this function never
3223  * returns.
3224  */
3225 void
3226 mono_threads_set_shutting_down (void)
3227 {
3228         MonoInternalThread *current_thread = mono_thread_internal_current ();
3229
3230         mono_threads_lock ();
3231
3232         if (shutting_down) {
3233                 mono_threads_unlock ();
3234
3235                 /* Make sure we're properly suspended/stopped */
3236
3237                 LOCK_THREAD (current_thread);
3238
3239                 if (current_thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
3240                         UNLOCK_THREAD (current_thread);
3241                         mono_thread_execute_interruption ();
3242                 } else {
3243                         UNLOCK_THREAD (current_thread);
3244                 }
3245
3246                 /*since we're killing the thread, detach it.*/
3247                 mono_thread_detach_internal (current_thread);
3248
3249                 /* Wake up other threads potentially waiting for us */
3250                 mono_thread_info_exit (0);
3251         } else {
3252                 shutting_down = TRUE;
3253
3254                 /* Not really a background state change, but this will
3255                  * interrupt the main thread if it is waiting for all
3256                  * the other threads.
3257                  */
3258                 mono_os_event_set (&background_change_event);
3259                 
3260                 mono_threads_unlock ();
3261         }
3262 }
3263
3264 /**
3265  * mono_thread_manage:
3266  */
3267 void
3268 mono_thread_manage (void)
3269 {
3270         struct wait_data wait_data;
3271         struct wait_data *wait = &wait_data;
3272
3273         memset (wait, 0, sizeof (struct wait_data));
3274         /* join each thread that's still running */
3275         THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3276         
3277         mono_threads_lock ();
3278         if(threads==NULL) {
3279                 THREAD_DEBUG (g_message("%s: No threads", __func__));
3280                 mono_threads_unlock ();
3281                 return;
3282         }
3283         mono_threads_unlock ();
3284         
3285         do {
3286                 mono_threads_lock ();
3287                 if (shutting_down) {
3288                         /* somebody else is shutting down */
3289                         mono_threads_unlock ();
3290                         break;
3291                 }
3292                 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3293                         mono_g_hash_table_foreach (threads, print_tids, NULL));
3294         
3295                 mono_os_event_reset (&background_change_event);
3296                 wait->num=0;
3297                 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3298                 memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3299                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3300                 mono_threads_unlock ();
3301                 if (wait->num > 0)
3302                         /* Something to wait for */
3303                         wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3304                 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3305         } while(wait->num>0);
3306
3307         /* Mono is shutting down, so just wait for the end */
3308         if (!mono_runtime_try_shutdown ()) {
3309                 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3310                 mono_thread_suspend (mono_thread_internal_current ());
3311                 mono_thread_execute_interruption ();
3312         }
3313
3314         /* 
3315          * Remove everything but the finalizer thread and self.
3316          * Also abort all the background threads
3317          * */
3318         do {
3319                 mono_threads_lock ();
3320
3321                 wait->num = 0;
3322                 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3323                 memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3324                 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3325
3326                 mono_threads_unlock ();
3327
3328                 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3329                 if (wait->num > 0) {
3330                         /* Something to wait for */
3331                         wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3332                 }
3333         } while (wait->num > 0);
3334         
3335         /* 
3336          * give the subthreads a chance to really quit (this is mainly needed
3337          * to get correct user and system times from getrusage/wait/time(1)).
3338          * This could be removed if we avoid pthread_detach() and use pthread_join().
3339          */
3340         mono_thread_info_yield ();
3341 }
3342
3343 static void
3344 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3345 {
3346         MonoInternalThread *thread = (MonoInternalThread*)value;
3347         struct wait_data *wait = (struct wait_data*)user_data;
3348
3349         /* 
3350          * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3351          * limitation.
3352          * This needs no locking.
3353          */
3354         if ((thread->state & ThreadState_Suspended) != 0 || 
3355                 (thread->state & ThreadState_Stopped) != 0)
3356                 return;
3357
3358         if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3359                 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3360                 wait->threads [wait->num] = thread;
3361                 wait->num++;
3362         }
3363 }
3364
3365 /*
3366  * mono_thread_suspend_all_other_threads:
3367  *
3368  *  Suspend all managed threads except the finalizer thread and this thread. It is
3369  * not possible to resume them later.
3370  */
3371 void mono_thread_suspend_all_other_threads (void)
3372 {
3373         struct wait_data wait_data;
3374         struct wait_data *wait = &wait_data;
3375         int i;
3376         MonoNativeThreadId self = mono_native_thread_id_get ();
3377         guint32 eventidx = 0;
3378         gboolean starting, finished;
3379
3380         memset (wait, 0, sizeof (struct wait_data));
3381         /*
3382          * The other threads could be in an arbitrary state at this point, i.e.
3383          * they could be starting up, shutting down etc. This means that there could be
3384          * threads which are not even in the threads hash table yet.
3385          */
3386
3387         /* 
3388          * First we set a barrier which will be checked by all threads before they
3389          * are added to the threads hash table, and they will exit if the flag is set.
3390          * This ensures that no threads could be added to the hash later.
3391          * We will use shutting_down as the barrier for now.
3392          */
3393         g_assert (shutting_down);
3394
3395         /*
3396          * We make multiple calls to WaitForMultipleObjects since:
3397          * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3398          * - some threads could exit without becoming suspended
3399          */
3400         finished = FALSE;
3401         while (!finished) {
3402                 /*
3403                  * Make a copy of the hashtable since we can't do anything with
3404                  * threads while threads_mutex is held.
3405                  */
3406                 wait->num = 0;
3407                 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3408                 memset (wait->threads, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3409                 mono_threads_lock ();
3410                 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3411                 mono_threads_unlock ();
3412
3413                 eventidx = 0;
3414                 /* Get the suspended events that we'll be waiting for */
3415                 for (i = 0; i < wait->num; ++i) {
3416                         MonoInternalThread *thread = wait->threads [i];
3417
3418                         if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3419                              || mono_gc_is_finalizer_internal_thread (thread)
3420                              || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3421                         ) {
3422                                 mono_threads_close_thread_handle (wait->handles [i]);
3423                                 wait->threads [i] = NULL;
3424                                 continue;
3425                         }
3426
3427                         LOCK_THREAD (thread);
3428
3429                         if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3430                                 UNLOCK_THREAD (thread);
3431                                 mono_threads_close_thread_handle (wait->handles [i]);
3432                                 wait->threads [i] = NULL;
3433                                 continue;
3434                         }
3435
3436                         ++eventidx;
3437
3438                         /* Convert abort requests into suspend requests */
3439                         if ((thread->state & ThreadState_AbortRequested) != 0)
3440                                 thread->state &= ~ThreadState_AbortRequested;
3441                         
3442                         thread->state |= ThreadState_SuspendRequested;
3443                         mono_os_event_reset (thread->suspended);
3444
3445                         /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3446                         async_suspend_internal (thread, TRUE);
3447
3448                         mono_threads_close_thread_handle (wait->handles [i]);
3449                         wait->threads [i] = NULL;
3450                 }
3451                 if (eventidx <= 0) {
3452                         /* 
3453                          * If there are threads which are starting up, we wait until they
3454                          * are suspended when they try to register in the threads hash.
3455                          * This is guaranteed to finish, since the threads which can create new
3456                          * threads get suspended after a while.
3457                          * FIXME: The finalizer thread can still create new threads.
3458                          */
3459                         mono_threads_lock ();
3460                         if (threads_starting_up)
3461                                 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3462                         else
3463                                 starting = FALSE;
3464                         mono_threads_unlock ();
3465                         if (starting)
3466                                 mono_thread_info_sleep (100, NULL);
3467                         else
3468                                 finished = TRUE;
3469                 }
3470         }
3471 }
3472
3473 typedef struct {
3474         MonoInternalThread *thread;
3475         MonoStackFrameInfo *frames;
3476         int nframes, max_frames;
3477         int nthreads, max_threads;
3478         MonoInternalThread **threads;
3479 } ThreadDumpUserData;
3480
3481 static gboolean thread_dump_requested;
3482
3483 /* This needs to be async safe */
3484 static gboolean
3485 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3486 {
3487         ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3488
3489         if (ud->nframes < ud->max_frames) {
3490                 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3491                 ud->nframes ++;
3492         }
3493
3494         return FALSE;
3495 }
3496
3497 /* This needs to be async safe */
3498 static SuspendThreadResult
3499 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3500 {
3501         ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3502         MonoInternalThread *thread = user_data->thread;
3503
3504 #if 0
3505 /* This no longer works with remote unwinding */
3506         g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3507         mono_thread_internal_describe (thread, text);
3508         g_string_append (text, "\n");
3509 #endif
3510
3511         if (thread == mono_thread_internal_current ())
3512                 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3513         else
3514                 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3515
3516         return MonoResumeThread;
3517 }
3518
3519 typedef struct {
3520         int nthreads, max_threads;
3521         MonoInternalThread **threads;
3522 } CollectThreadsUserData;
3523
3524 static void
3525 collect_thread (gpointer key, gpointer value, gpointer user)
3526 {
3527         CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3528         MonoInternalThread *thread = (MonoInternalThread *)value;
3529
3530         if (ud->nthreads < ud->max_threads)
3531                 ud->threads [ud->nthreads ++] = thread;
3532 }
3533
3534 /*
3535  * Collect running threads into the THREADS array.
3536  * THREADS should be an array allocated on the stack.
3537  */
3538 static int
3539 collect_threads (MonoInternalThread **thread_array, int max_threads)
3540 {
3541         CollectThreadsUserData ud;
3542
3543         memset (&ud, 0, sizeof (ud));
3544         /* This array contains refs, but its on the stack, so its ok */
3545         ud.threads = thread_array;
3546         ud.max_threads = max_threads;
3547
3548         mono_threads_lock ();
3549         mono_g_hash_table_foreach (threads, collect_thread, &ud);
3550         mono_threads_unlock ();
3551
3552         return ud.nthreads;
3553 }
3554
3555 static void
3556 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud)
3557 {
3558         GString* text = g_string_new (0);
3559         char *name;
3560         GError *error = NULL;
3561         int i;
3562
3563         ud->thread = thread;
3564         ud->nframes = 0;
3565
3566         /* Collect frames for the thread */
3567         if (thread == mono_thread_internal_current ()) {
3568                 get_thread_dump (mono_thread_info_current (), ud);
3569         } else {
3570                 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
3571         }
3572
3573         /*
3574          * Do all the non async-safe work outside of get_thread_dump.
3575          */
3576         if (thread->name) {
3577                 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
3578                 g_assert (!error);
3579                 g_string_append_printf (text, "\n\"%s\"", name);
3580                 g_free (name);
3581         }
3582         else if (thread->threadpool_thread) {
3583                 g_string_append (text, "\n\"<threadpool thread>\"");
3584         } else {
3585                 g_string_append (text, "\n\"<unnamed thread>\"");
3586         }
3587
3588         for (i = 0; i < ud->nframes; ++i) {
3589                 MonoStackFrameInfo *frame = &ud->frames [i];
3590                 MonoMethod *method = NULL;
3591
3592                 if (frame->type == FRAME_TYPE_MANAGED)
3593                         method = mono_jit_info_get_method (frame->ji);
3594
3595                 if (method) {
3596                         gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
3597                         g_string_append_printf (text, "  %s\n", location);
3598                         g_free (location);
3599                 } else {
3600                         g_string_append_printf (text, "  at <unknown> <0x%05x>\n", frame->native_offset);
3601                 }
3602         }
3603
3604         fprintf (stdout, "%s", text->str);
3605
3606 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
3607         OutputDebugStringA(text->str);
3608 #endif
3609
3610         g_string_free (text, TRUE);
3611         fflush (stdout);
3612 }
3613
3614 void
3615 mono_threads_perform_thread_dump (void)
3616 {
3617         ThreadDumpUserData ud;
3618         MonoInternalThread *thread_array [128];
3619         int tindex, nthreads;
3620
3621         if (!thread_dump_requested)
3622                 return;
3623
3624         printf ("Full thread dump:\n");
3625
3626         /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
3627         nthreads = collect_threads (thread_array, 128);
3628
3629         memset (&ud, 0, sizeof (ud));
3630         ud.frames = g_new0 (MonoStackFrameInfo, 256);
3631         ud.max_frames = 256;
3632
3633         for (tindex = 0; tindex < nthreads; ++tindex)
3634                 dump_thread (thread_array [tindex], &ud);
3635
3636         g_free (ud.frames);
3637
3638         thread_dump_requested = FALSE;
3639 }
3640
3641 /* Obtain the thread dump of all threads */
3642 static gboolean
3643 mono_threads_get_thread_dump (MonoArray **out_threads, MonoArray **out_stack_frames, MonoError *error)
3644 {
3645
3646         ThreadDumpUserData ud;
3647         MonoInternalThread *thread_array [128];
3648         MonoDomain *domain = mono_domain_get ();
3649         MonoDebugSourceLocation *location;
3650         int tindex, nthreads;
3651
3652         error_init (error);
3653         
3654         *out_threads = NULL;
3655         *out_stack_frames = NULL;
3656
3657         /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
3658         nthreads = collect_threads (thread_array, 128);
3659
3660         memset (&ud, 0, sizeof (ud));
3661         ud.frames = g_new0 (MonoStackFrameInfo, 256);
3662         ud.max_frames = 256;
3663
3664         *out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
3665         if (!is_ok (error))
3666                 goto leave;
3667         *out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
3668         if (!is_ok (error))
3669                 goto leave;
3670
3671         for (tindex = 0; tindex < nthreads; ++tindex) {
3672                 MonoInternalThread *thread = thread_array [tindex];
3673                 MonoArray *thread_frames;
3674                 int i;
3675
3676                 ud.thread = thread;
3677                 ud.nframes = 0;
3678
3679                 /* Collect frames for the thread */
3680                 if (thread == mono_thread_internal_current ()) {
3681                         get_thread_dump (mono_thread_info_current (), &ud);
3682                 } else {
3683                         mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
3684                 }
3685
3686                 mono_array_setref_fast (*out_threads, tindex, mono_thread_current_for_thread (thread));
3687
3688                 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
3689                 if (!is_ok (error))
3690                         goto leave;
3691                 mono_array_setref_fast (*out_stack_frames, tindex, thread_frames);
3692
3693                 for (i = 0; i < ud.nframes; ++i) {
3694                         MonoStackFrameInfo *frame = &ud.frames [i];
3695                         MonoMethod *method = NULL;
3696                         MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
3697                         if (!is_ok (error))
3698                                 goto leave;
3699
3700                         sf->native_offset = frame->native_offset;
3701
3702                         if (frame->type == FRAME_TYPE_MANAGED)
3703                                 method = mono_jit_info_get_method (frame->ji);
3704
3705                         if (method) {
3706                                 sf->method_address = (gsize) frame->ji->code_start;
3707
3708                                 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
3709                                 if (!is_ok (error))
3710                                         goto leave;
3711                                 MONO_OBJECT_SETREF (sf, method, rm);
3712
3713                                 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
3714                                 if (location) {
3715                                         sf->il_offset = location->il_offset;
3716
3717                                         if (location && location->source_file) {
3718                                                 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
3719                                                 if (!is_ok (error))
3720                                                         goto leave;
3721                                                 MONO_OBJECT_SETREF (sf, filename, filename);
3722                                                 sf->line = location->row;
3723                                                 sf->column = location->column;
3724                                         }
3725                                         mono_debug_free_source_location (location);
3726                                 } else {
3727                                         sf->il_offset = -1;
3728                                 }
3729                         }
3730                         mono_array_setref (thread_frames, i, sf);
3731                 }
3732         }
3733
3734 leave:
3735         g_free (ud.frames);
3736         return is_ok (error);
3737 }
3738
3739 /**
3740  * mono_threads_request_thread_dump:
3741  *
3742  *   Ask all threads except the current to print their stacktrace to stdout.
3743  */
3744 void
3745 mono_threads_request_thread_dump (void)
3746 {
3747         /*The new thread dump code runs out of the finalizer thread. */
3748         thread_dump_requested = TRUE;
3749         mono_gc_finalize_notify ();
3750 }
3751
3752 struct ref_stack {
3753         gpointer *refs;
3754         gint allocated; /* +1 so that refs [allocated] == NULL */
3755         gint bottom;
3756 };
3757
3758 typedef struct ref_stack RefStack;
3759
3760 static RefStack *
3761 ref_stack_new (gint initial_size)
3762 {
3763         RefStack *rs;
3764
3765         initial_size = MAX (initial_size, 16) + 1;
3766         rs = g_new0 (RefStack, 1);
3767         rs->refs = g_new0 (gpointer, initial_size);
3768         rs->allocated = initial_size;
3769         return rs;
3770 }
3771
3772 static void
3773 ref_stack_destroy (gpointer ptr)
3774 {
3775         RefStack *rs = (RefStack *)ptr;
3776
3777         if (rs != NULL) {
3778                 g_free (rs->refs);
3779                 g_free (rs);
3780         }
3781 }
3782
3783 static void
3784 ref_stack_push (RefStack *rs, gpointer ptr)
3785 {
3786         g_assert (rs != NULL);
3787
3788         if (rs->bottom >= rs->allocated) {
3789                 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
3790                 rs->allocated <<= 1;
3791                 rs->refs [rs->allocated] = NULL;
3792         }
3793         rs->refs [rs->bottom++] = ptr;
3794 }
3795
3796 static void
3797 ref_stack_pop (RefStack *rs)
3798 {
3799         if (rs == NULL || rs->bottom == 0)
3800                 return;
3801
3802         rs->bottom--;
3803         rs->refs [rs->bottom] = NULL;
3804 }
3805
3806 static gboolean
3807 ref_stack_find (RefStack *rs, gpointer ptr)
3808 {
3809         gpointer *refs;
3810
3811         if (rs == NULL)
3812                 return FALSE;
3813
3814         for (refs = rs->refs; refs && *refs; refs++) {
3815                 if (*refs == ptr)
3816                         return TRUE;
3817         }
3818         return FALSE;
3819 }
3820
3821 /*
3822  * mono_thread_push_appdomain_ref:
3823  *
3824  *   Register that the current thread may have references to objects in domain 
3825  * @domain on its stack. Each call to this function should be paired with a 
3826  * call to pop_appdomain_ref.
3827  */
3828 void 
3829 mono_thread_push_appdomain_ref (MonoDomain *domain)
3830 {
3831         MonoInternalThread *thread = mono_thread_internal_current ();
3832
3833         if (thread) {
3834                 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3835                 SPIN_LOCK (thread->lock_thread_id);
3836                 if (thread->appdomain_refs == NULL)
3837                         thread->appdomain_refs = ref_stack_new (16);
3838                 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
3839                 SPIN_UNLOCK (thread->lock_thread_id);
3840         }
3841 }
3842
3843 void
3844 mono_thread_pop_appdomain_ref (void)
3845 {
3846         MonoInternalThread *thread = mono_thread_internal_current ();
3847
3848         if (thread) {
3849                 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3850                 SPIN_LOCK (thread->lock_thread_id);
3851                 ref_stack_pop ((RefStack *)thread->appdomain_refs);
3852                 SPIN_UNLOCK (thread->lock_thread_id);
3853         }
3854 }
3855
3856 gboolean
3857 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3858 {
3859         gboolean res;
3860         SPIN_LOCK (thread->lock_thread_id);
3861         res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
3862         SPIN_UNLOCK (thread->lock_thread_id);
3863         return res;
3864 }
3865
3866 gboolean
3867 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3868 {
3869         return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3870 }
3871
3872 typedef struct abort_appdomain_data {
3873         struct wait_data wait;
3874         MonoDomain *domain;
3875 } abort_appdomain_data;
3876
3877 static void
3878 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3879 {
3880         MonoInternalThread *thread = (MonoInternalThread*)value;
3881         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3882         MonoDomain *domain = data->domain;
3883
3884         if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3885                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3886
3887                 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3888                         data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
3889                         data->wait.threads [data->wait.num] = thread;
3890                         data->wait.num++;
3891                 } else {
3892                         /* Just ignore the rest, we can't do anything with
3893                          * them yet
3894                          */
3895                 }
3896         }
3897 }
3898
3899 /*
3900  * mono_threads_abort_appdomain_threads:
3901  *
3902  *   Abort threads which has references to the given appdomain.
3903  */
3904 gboolean
3905 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3906 {
3907         abort_appdomain_data user_data;
3908         gint64 start_time;
3909         int orig_timeout = timeout;
3910         int i;
3911
3912         THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3913
3914         start_time = mono_msec_ticks ();
3915         do {
3916                 mono_threads_lock ();
3917
3918                 user_data.domain = domain;
3919                 user_data.wait.num = 0;
3920                 /* This shouldn't take any locks */
3921                 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3922                 mono_threads_unlock ();
3923
3924                 if (user_data.wait.num > 0) {
3925                         /* Abort the threads outside the threads lock */
3926                         for (i = 0; i < user_data.wait.num; ++i)
3927                                 mono_thread_internal_abort (user_data.wait.threads [i]);
3928
3929                         /*
3930                          * We should wait for the threads either to abort, or to leave the
3931                          * domain. We can't do the latter, so we wait with a timeout.
3932                          */
3933                         wait_for_tids (&user_data.wait, 100, FALSE);
3934                 }
3935
3936                 /* Update remaining time */
3937                 timeout -= mono_msec_ticks () - start_time;
3938                 start_time = mono_msec_ticks ();
3939
3940                 if (orig_timeout != -1 && timeout < 0)
3941                         return FALSE;
3942         }
3943         while (user_data.wait.num > 0);
3944
3945         THREAD_DEBUG (g_message ("%s: abort done", __func__));
3946
3947         return TRUE;
3948 }
3949
3950 /*
3951  * mono_thread_get_undeniable_exception:
3952  *
3953  *   Return an exception which needs to be raised when leaving a catch clause.
3954  * This is used for undeniable exception propagation.
3955  */
3956 MonoException*
3957 mono_thread_get_undeniable_exception (void)
3958 {
3959         MonoInternalThread *thread = mono_thread_internal_current ();
3960
3961         if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
3962                 return NULL;
3963
3964         // We don't want to have our exception effect calls made by
3965         // the catching block
3966
3967         if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
3968                 return NULL;
3969
3970         /*
3971          * FIXME: Clear the abort exception and return an AppDomainUnloaded 
3972          * exception if the thread no longer references a dying appdomain.
3973          */ 
3974         thread->abort_exc->trace_ips = NULL;
3975         thread->abort_exc->stack_trace = NULL;
3976         return thread->abort_exc;
3977 }
3978
3979 #if MONO_SMALL_CONFIG
3980 #define NUM_STATIC_DATA_IDX 4
3981 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3982         64, 256, 1024, 4096
3983 };
3984 #else
3985 #define NUM_STATIC_DATA_IDX 8
3986 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3987         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3988 };
3989 #endif
3990
3991 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
3992 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
3993
3994 static void
3995 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
3996 {
3997         gpointer *static_data = (gpointer *)addr;
3998
3999         for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4000                 void **ptr = (void **)static_data [i];
4001
4002                 if (!ptr)
4003                         continue;
4004
4005                 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4006                         void **p = ptr + idx;
4007
4008                         if (*p)
4009                                 mark_func ((MonoObject**)p, gc_data);
4010                 });
4011         }
4012 }
4013
4014 static void
4015 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4016 {
4017         mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4018 }
4019
4020 static void
4021 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4022 {
4023         mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4024 }
4025
4026 /*
4027  *  mono_alloc_static_data
4028  *
4029  *   Allocate memory blocks for storing threads or context static data
4030  */
4031 static void 
4032 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
4033 {
4034         guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4035         int i;
4036
4037         gpointer* static_data = *static_data_ptr;
4038         if (!static_data) {
4039                 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4040                 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4041
4042                 if (mono_gc_user_markers_supported ()) {
4043                         if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4044                                 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4045
4046                         if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4047                                 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4048                 }
4049
4050                 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4051                         threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4052                         threadlocal ? "managed thread-static variables" : "managed context-static variables");
4053                 *static_data_ptr = static_data;
4054                 static_data [0] = static_data;
4055         }
4056
4057         for (i = 1; i <= idx; ++i) {
4058                 if (static_data [i])
4059                         continue;
4060
4061                 if (mono_gc_user_markers_supported ())
4062                         static_data [i] = g_malloc0 (static_data_size [i]);
4063                 else
4064                         static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4065                                 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4066                                 threadlocal ? "managed thread-static variables" : "managed context-static variables");
4067         }
4068 }
4069
4070 static void 
4071 mono_free_static_data (gpointer* static_data)
4072 {
4073         int i;
4074         for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4075                 gpointer p = static_data [i];
4076                 if (!p)
4077                         continue;
4078                 /*
4079                  * At this point, the static data pointer array is still registered with the
4080                  * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4081                  * data.  Freeing the individual arrays without first nulling their slots
4082                  * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4083                  * such an already freed array.  See bug #13813.
4084                  */
4085                 static_data [i] = NULL;
4086                 mono_memory_write_barrier ();
4087                 if (mono_gc_user_markers_supported ())
4088                         g_free (p);
4089                 else
4090                         mono_gc_free_fixed (p);
4091         }
4092         mono_gc_free_fixed (static_data);
4093 }
4094
4095 /*
4096  *  mono_init_static_data_info
4097  *
4098  *   Initializes static data counters
4099  */
4100 static void mono_init_static_data_info (StaticDataInfo *static_data)
4101 {
4102         static_data->idx = 0;
4103         static_data->offset = 0;
4104         static_data->freelist = NULL;
4105 }
4106
4107 /*
4108  *  mono_alloc_static_data_slot
4109  *
4110  *   Generates an offset for static data. static_data contains the counters
4111  *  used to generate it.
4112  */
4113 static guint32
4114 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4115 {
4116         if (!static_data->idx && !static_data->offset) {
4117                 /* 
4118                  * we use the first chunk of the first allocation also as
4119                  * an array for the rest of the data 
4120                  */
4121                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4122         }
4123         static_data->offset += align - 1;
4124         static_data->offset &= ~(align - 1);
4125         if (static_data->offset + size >= static_data_size [static_data->idx]) {
4126                 static_data->idx ++;
4127                 g_assert (size <= static_data_size [static_data->idx]);
4128                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4129                 static_data->offset = 0;
4130         }
4131         guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4132         static_data->offset += size;
4133         return offset;
4134 }
4135
4136 /*
4137  * LOCKING: requires that threads_mutex is held
4138  */
4139 static void
4140 context_adjust_static_data (MonoAppContext *ctx)
4141 {
4142         if (context_static_info.offset || context_static_info.idx > 0) {
4143                 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4144                 mono_alloc_static_data (&ctx->static_data, offset, FALSE);
4145                 ctx->data->static_data = ctx->static_data;
4146         }
4147 }
4148
4149 /*
4150  * LOCKING: requires that threads_mutex is held
4151  */
4152 static void 
4153 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4154 {
4155         MonoInternalThread *thread = (MonoInternalThread *)value;
4156         guint32 offset = GPOINTER_TO_UINT (user);
4157
4158         mono_alloc_static_data (&(thread->static_data), offset, TRUE);
4159 }
4160
4161 /*
4162  * LOCKING: requires that threads_mutex is held
4163  */
4164 static void
4165 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4166 {
4167         MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target (GPOINTER_TO_INT (key));
4168
4169         if (!ctx)
4170                 return;
4171
4172         guint32 offset = GPOINTER_TO_UINT (user);
4173         mono_alloc_static_data (&ctx->static_data, offset, FALSE);
4174         ctx->data->static_data = ctx->static_data;
4175 }
4176
4177 static StaticDataFreeList*
4178 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
4179 {
4180         StaticDataFreeList* prev = NULL;
4181         StaticDataFreeList* tmp = static_data->freelist;
4182         while (tmp) {
4183                 if (tmp->size == size) {
4184                         if (prev)
4185                                 prev->next = tmp->next;
4186                         else
4187                                 static_data->freelist = tmp->next;
4188                         return tmp;
4189                 }
4190                 prev = tmp;
4191                 tmp = tmp->next;
4192         }
4193         return NULL;
4194 }
4195
4196 #if SIZEOF_VOID_P == 4
4197 #define ONE_P 1
4198 #else
4199 #define ONE_P 1ll
4200 #endif
4201
4202 static void
4203 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4204 {
4205         int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4206         if (!sets [idx])
4207                 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4208         MonoBitSet *rb = sets [idx];
4209         offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4210         offset /= sizeof (uintptr_t);
4211         /* offset is now the bitmap offset */
4212         for (int i = 0; i < numbits; ++i) {
4213                 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4214                         mono_bitset_set_fast (rb, offset + i);
4215         }
4216 }
4217
4218 static void
4219 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4220 {
4221         int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4222         MonoBitSet *rb = sets [idx];
4223         offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4224         offset /= sizeof (uintptr_t);
4225         /* offset is now the bitmap offset */
4226         for (int i = 0; i < size / sizeof (uintptr_t); i++)
4227                 mono_bitset_clear_fast (rb, offset + i);
4228 }
4229
4230 guint32
4231 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4232 {
4233         g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4234
4235         StaticDataInfo *info;
4236         MonoBitSet **sets;
4237
4238         if (static_type == SPECIAL_STATIC_THREAD) {
4239                 info = &thread_static_info;
4240                 sets = thread_reference_bitmaps;
4241         } else {
4242                 info = &context_static_info;
4243                 sets = context_reference_bitmaps;
4244         }
4245
4246         mono_threads_lock ();
4247
4248         StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4249         guint32 offset;
4250
4251         if (item) {
4252                 offset = item->offset;
4253                 g_free (item);
4254         } else {
4255                 offset = mono_alloc_static_data_slot (info, size, align);
4256         }
4257
4258         update_reference_bitmap (sets, offset, bitmap, numbits);
4259
4260         if (static_type == SPECIAL_STATIC_THREAD) {
4261                 /* This can be called during startup */
4262                 if (threads != NULL)
4263                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4264         } else {
4265                 if (contexts != NULL)
4266                         g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4267
4268                 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4269         }
4270
4271         mono_threads_unlock ();
4272
4273         return offset;
4274 }
4275
4276 gpointer
4277 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4278 {
4279         guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4280
4281         if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4282                 return get_thread_static_data (thread, offset);
4283         } else {
4284                 return get_context_static_data (thread->current_appcontext, offset);
4285         }
4286 }
4287
4288 gpointer
4289 mono_get_special_static_data (guint32 offset)
4290 {
4291         return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4292 }
4293
4294 typedef struct {
4295         guint32 offset;
4296         guint32 size;
4297 } OffsetSize;
4298
4299 /*
4300  * LOCKING: requires that threads_mutex is held
4301  */
4302 static void 
4303 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4304 {
4305         MonoInternalThread *thread = (MonoInternalThread *)value;
4306         OffsetSize *data = (OffsetSize *)user;
4307         int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4308         int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4309         char *ptr;
4310
4311         if (!thread->static_data || !thread->static_data [idx])
4312                 return;
4313         ptr = ((char*) thread->static_data [idx]) + off;
4314         mono_gc_bzero_atomic (ptr, data->size);
4315 }
4316
4317 /*
4318  * LOCKING: requires that threads_mutex is held
4319  */
4320 static void
4321 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4322 {
4323         MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target (GPOINTER_TO_INT (key));
4324
4325         if (!ctx)
4326                 return;
4327
4328         OffsetSize *data = (OffsetSize *)user;
4329         int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4330         int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4331         char *ptr;
4332
4333         if (!ctx->static_data || !ctx->static_data [idx])
4334                 return;
4335
4336         ptr = ((char*) ctx->static_data [idx]) + off;
4337         mono_gc_bzero_atomic (ptr, data->size);
4338 }
4339
4340 static void
4341 do_free_special_slot (guint32 offset, guint32 size)
4342 {
4343         guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4344         MonoBitSet **sets;
4345         StaticDataInfo *info;
4346
4347         if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4348                 info = &thread_static_info;
4349                 sets = thread_reference_bitmaps;
4350         } else {
4351                 info = &context_static_info;
4352                 sets = context_reference_bitmaps;
4353         }
4354
4355         guint32 data_offset = offset;
4356         ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4357         OffsetSize data = { data_offset, size };
4358
4359         clear_reference_bitmap (sets, data.offset, data.size);
4360
4361         if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4362                 if (threads != NULL)
4363                         mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4364         } else {
4365                 if (contexts != NULL)
4366                         g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4367         }
4368
4369         if (!mono_runtime_is_shutting_down ()) {
4370                 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4371
4372                 item->offset = offset;
4373                 item->size = size;
4374
4375                 item->next = info->freelist;
4376                 info->freelist = item;
4377         }
4378 }
4379
4380 static void
4381 do_free_special (gpointer key, gpointer value, gpointer data)
4382 {
4383         MonoClassField *field = (MonoClassField *)key;
4384         guint32 offset = GPOINTER_TO_UINT (value);
4385         gint32 align;
4386         guint32 size;
4387         size = mono_type_size (field->type, &align);
4388         do_free_special_slot (offset, size);
4389 }
4390
4391 void
4392 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4393 {
4394         mono_threads_lock ();
4395
4396         g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4397
4398         mono_threads_unlock ();
4399 }
4400
4401 #ifdef HOST_WIN32
4402 static void CALLBACK dummy_apc (ULONG_PTR param)
4403 {
4404 }
4405 #endif
4406
4407 /*
4408  * mono_thread_execute_interruption
4409  * 
4410  * Performs the operation that the requested thread state requires (abort,
4411  * suspend or stop)
4412  */
4413 static MonoException*
4414 mono_thread_execute_interruption (void)
4415 {
4416         MonoInternalThread *thread = mono_thread_internal_current ();
4417         MonoThread *sys_thread = mono_thread_current ();
4418
4419         LOCK_THREAD (thread);
4420
4421         /* MonoThread::interruption_requested can only be changed with atomics */
4422         if (!mono_thread_clear_interruption_requested (thread)) {
4423                 UNLOCK_THREAD (thread);
4424                 return NULL;
4425         }
4426
4427         /* this will consume pending APC calls */
4428 #ifdef HOST_WIN32
4429         WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
4430 #endif
4431         /* Clear the interrupted flag of the thread so it can wait again */
4432         mono_thread_info_clear_self_interrupt ();
4433
4434         /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4435         if (sys_thread->pending_exception) {
4436                 MonoException *exc;
4437
4438                 exc = sys_thread->pending_exception;
4439                 sys_thread->pending_exception = NULL;
4440
4441                 UNLOCK_THREAD (thread);
4442                 return exc;
4443         } else if (thread->state & (ThreadState_AbortRequested)) {
4444                 UNLOCK_THREAD (thread);
4445                 g_assert (sys_thread->pending_exception == NULL);
4446                 if (thread->abort_exc == NULL) {
4447                         /* 
4448                          * This might be racy, but it has to be called outside the lock
4449                          * since it calls managed code.
4450                          */
4451                         MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
4452                 }
4453                 return thread->abort_exc;
4454         } else if (thread->state & (ThreadState_SuspendRequested)) {
4455                 /* calls UNLOCK_THREAD (thread) */
4456                 self_suspend_internal ();
4457                 return NULL;
4458         } else if (thread->thread_interrupt_requested) {
4459
4460                 thread->thread_interrupt_requested = FALSE;
4461                 UNLOCK_THREAD (thread);
4462                 
4463                 return(mono_get_exception_thread_interrupted ());
4464         }
4465         
4466         UNLOCK_THREAD (thread);
4467         
4468         return NULL;
4469 }
4470
4471 /*
4472  * mono_thread_request_interruption
4473  *
4474  * A signal handler can call this method to request the interruption of a
4475  * thread. The result of the interruption will depend on the current state of
4476  * the thread. If the result is an exception that needs to be throw, it is 
4477  * provided as return value.
4478  */
4479 MonoException*
4480 mono_thread_request_interruption (gboolean running_managed)
4481 {
4482         MonoInternalThread *thread = mono_thread_internal_current ();
4483
4484         /* The thread may already be stopping */
4485         if (thread == NULL) 
4486                 return NULL;
4487
4488         if (!mono_thread_set_interruption_requested (thread))
4489                 return NULL;
4490
4491         if (!running_managed || is_running_protected_wrapper ()) {
4492                 /* Can't stop while in unmanaged code. Increase the global interruption
4493                    request count. When exiting the unmanaged method the count will be
4494                    checked and the thread will be interrupted. */
4495
4496                 /* this will awake the thread if it is in WaitForSingleObject 
4497                    or similar */
4498                 /* Our implementation of this function ignores the func argument */
4499 #ifdef HOST_WIN32
4500                 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->native_handle, (ULONG_PTR)NULL);
4501 #else
4502                 mono_thread_info_self_interrupt ();
4503 #endif
4504                 return NULL;
4505         }
4506         else {
4507                 return mono_thread_execute_interruption ();
4508         }
4509 }
4510
4511 /*This function should be called by a thread after it has exited all of
4512  * its handle blocks at interruption time.*/
4513 MonoException*
4514 mono_thread_resume_interruption (gboolean exec)
4515 {
4516         MonoInternalThread *thread = mono_thread_internal_current ();
4517         gboolean still_aborting;
4518
4519         /* The thread may already be stopping */
4520         if (thread == NULL)
4521                 return NULL;
4522
4523         LOCK_THREAD (thread);
4524         still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
4525         UNLOCK_THREAD (thread);
4526
4527         /*This can happen if the protected block called Thread::ResetAbort*/
4528         if (!still_aborting)
4529                 return NULL;
4530
4531         if (!mono_thread_set_interruption_requested (thread))
4532                 return NULL;
4533
4534         mono_thread_info_self_interrupt ();
4535
4536         if (exec)
4537                 return mono_thread_execute_interruption ();
4538         else
4539                 return NULL;
4540 }
4541
4542 gboolean mono_thread_interruption_requested ()
4543 {
4544         if (thread_interruption_requested) {
4545                 MonoInternalThread *thread = mono_thread_internal_current ();
4546                 /* The thread may already be stopping */
4547                 if (thread != NULL) 
4548                         return mono_thread_get_interruption_requested (thread);
4549         }
4550         return FALSE;
4551 }
4552
4553 static MonoException*
4554 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4555 {
4556         MonoInternalThread *thread = mono_thread_internal_current ();
4557
4558         /* The thread may already be stopping */
4559         if (!thread)
4560                 return NULL;
4561         if (!mono_thread_get_interruption_requested (thread))
4562                 return NULL;
4563         if (!bypass_abort_protection && is_running_protected_wrapper ())
4564                 return NULL;
4565
4566         return mono_thread_execute_interruption ();
4567 }
4568
4569 /*
4570  * Performs the interruption of the current thread, if one has been requested,
4571  * and the thread is not running a protected wrapper.
4572  * Return the exception which needs to be thrown, if any.
4573  */
4574 MonoException*
4575 mono_thread_interruption_checkpoint (void)
4576 {
4577         return mono_thread_interruption_checkpoint_request (FALSE);
4578 }
4579
4580 /*
4581  * Performs the interruption of the current thread, if one has been requested.
4582  * Return the exception which needs to be thrown, if any.
4583  */
4584 MonoException*
4585 mono_thread_force_interruption_checkpoint_noraise (void)
4586 {
4587         return mono_thread_interruption_checkpoint_request (TRUE);
4588 }
4589
4590 /*
4591  * mono_set_pending_exception:
4592  *
4593  *   Set the pending exception of the current thread to EXC.
4594  * The exception will be thrown when execution returns to managed code.
4595  */
4596 void
4597 mono_set_pending_exception (MonoException *exc)
4598 {
4599         MonoThread *thread = mono_thread_current ();
4600
4601         /* The thread may already be stopping */
4602         if (thread == NULL)
4603                 return;
4604
4605         MONO_OBJECT_SETREF (thread, pending_exception, exc);
4606
4607     mono_thread_request_interruption (FALSE);
4608 }
4609
4610 /**
4611  * mono_thread_interruption_request_flag:
4612  *
4613  * Returns the address of a flag that will be non-zero if an interruption has
4614  * been requested for a thread. The thread to interrupt may not be the current
4615  * thread, so an additional call to mono_thread_interruption_requested() or
4616  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4617  * zero.
4618  */
4619 gint32* mono_thread_interruption_request_flag ()
4620 {
4621         return &thread_interruption_requested;
4622 }
4623
4624 void 
4625 mono_thread_init_apartment_state (void)
4626 {
4627 #ifdef HOST_WIN32
4628         MonoInternalThread* thread = mono_thread_internal_current ();
4629
4630         /* Positive return value indicates success, either
4631          * S_OK if this is first CoInitialize call, or
4632          * S_FALSE if CoInitialize already called, but with same
4633          * threading model. A negative value indicates failure,
4634          * probably due to trying to change the threading model.
4635          */
4636         if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA) 
4637                         ? COINIT_APARTMENTTHREADED 
4638                         : COINIT_MULTITHREADED) < 0) {
4639                 thread->apartment_state = ThreadApartmentState_Unknown;
4640         }
4641 #endif
4642 }
4643
4644 void 
4645 mono_thread_cleanup_apartment_state (void)
4646 {
4647 #ifdef HOST_WIN32
4648         MonoInternalThread* thread = mono_thread_internal_current ();
4649
4650         if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4651                 CoUninitialize ();
4652         }
4653 #endif
4654 }
4655
4656 void
4657 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4658 {
4659         LOCK_THREAD (thread);
4660         thread->state |= state;
4661         UNLOCK_THREAD (thread);
4662 }
4663
4664 /**
4665  * mono_thread_test_and_set_state:
4666  * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
4667  * \returns TRUE if \p set was OR'd in.
4668  */
4669 gboolean
4670 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
4671 {
4672         LOCK_THREAD (thread);
4673
4674         if ((thread->state & test) != 0) {
4675                 UNLOCK_THREAD (thread);
4676                 return FALSE;
4677         }
4678
4679         thread->state |= set;
4680         UNLOCK_THREAD (thread);
4681
4682         return TRUE;
4683 }
4684
4685 void
4686 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4687 {
4688         LOCK_THREAD (thread);
4689         thread->state &= ~state;
4690         UNLOCK_THREAD (thread);
4691 }
4692
4693 gboolean
4694 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4695 {
4696         gboolean ret = FALSE;
4697
4698         LOCK_THREAD (thread);
4699
4700         if ((thread->state & test) != 0) {
4701                 ret = TRUE;
4702         }
4703         
4704         UNLOCK_THREAD (thread);
4705         
4706         return ret;
4707 }
4708
4709 static void
4710 self_interrupt_thread (void *_unused)
4711 {
4712         MonoException *exc;
4713         MonoThreadInfo *info;
4714
4715         exc = mono_thread_execute_interruption ();
4716         if (!exc) {
4717                 if (mono_threads_is_coop_enabled ()) {
4718                         /* We can return from an async call in coop, as
4719                          * it's simply called when exiting the safepoint */
4720                         return;
4721                 }
4722
4723                 g_error ("%s: we can't resume from an async call", __func__);
4724         }
4725
4726         info = mono_thread_info_current ();
4727
4728         /* We must use _with_context since we didn't trampoline into the runtime */
4729         mono_raise_exception_with_context (exc, &info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx); /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
4730 }
4731
4732 static gboolean
4733 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
4734 {
4735         if (!ji)
4736                 return FALSE;
4737         return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
4738 }
4739
4740 static gboolean
4741 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
4742 {
4743         MonoJitInfo **dest = (MonoJitInfo **)data;
4744         *dest = frame->ji;
4745         return TRUE;
4746 }
4747
4748 static MonoJitInfo*
4749 mono_thread_info_get_last_managed (MonoThreadInfo *info)
4750 {
4751         MonoJitInfo *ji = NULL;
4752         if (!info)
4753                 return NULL;
4754
4755         /*
4756          * The suspended thread might be holding runtime locks. Make sure we don't try taking
4757          * any runtime locks while unwinding. In coop case we shouldn't safepoint in regions
4758          * where we hold runtime locks.
4759          */
4760         if (!mono_threads_is_coop_enabled ())
4761                 mono_thread_info_set_is_async_context (TRUE);
4762         mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
4763         if (!mono_threads_is_coop_enabled ())
4764                 mono_thread_info_set_is_async_context (FALSE);
4765         return ji;
4766 }
4767
4768 typedef struct {
4769         MonoInternalThread *thread;
4770         gboolean install_async_abort;
4771         MonoThreadInfoInterruptToken *interrupt_token;
4772 } AbortThreadData;
4773
4774 static SuspendThreadResult
4775 async_abort_critical (MonoThreadInfo *info, gpointer ud)
4776 {
4777         AbortThreadData *data = (AbortThreadData *)ud;
4778         MonoInternalThread *thread = data->thread;
4779         MonoJitInfo *ji = NULL;
4780         gboolean protected_wrapper;
4781         gboolean running_managed;
4782
4783         if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
4784                 return MonoResumeThread;
4785
4786         /*someone is already interrupting it*/
4787         if (!mono_thread_set_interruption_requested (thread))
4788                 return MonoResumeThread;
4789
4790         ji = mono_thread_info_get_last_managed (info);
4791         protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
4792         running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
4793
4794         if (!protected_wrapper && running_managed) {
4795                 /*We are in managed code*/
4796                 /*Set the thread to call */
4797                 if (data->install_async_abort)
4798                         mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
4799                 return MonoResumeThread;
4800         } else {
4801                 /* 
4802                  * This will cause waits to be broken.
4803                  * It will also prevent the thread from entering a wait, so if the thread returns
4804                  * from the wait before it receives the abort signal, it will just spin in the wait
4805                  * functions in the io-layer until the signal handler calls QueueUserAPC which will
4806                  * make it return.
4807                  */
4808                 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
4809
4810                 return MonoResumeThread;
4811         }
4812 }
4813
4814 static void
4815 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
4816 {
4817         AbortThreadData data;
4818
4819         g_assert (thread != mono_thread_internal_current ());
4820
4821         data.thread = thread;
4822         data.install_async_abort = install_async_abort;
4823         data.interrupt_token = NULL;
4824
4825         mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
4826         if (data.interrupt_token)
4827                 mono_thread_info_finish_interrupt (data.interrupt_token);
4828         /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
4829 }
4830
4831 static void
4832 self_abort_internal (MonoError *error)
4833 {
4834         MonoException *exc;
4835
4836         error_init (error);
4837
4838         /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
4839          * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
4840
4841         /*
4842         Self aborts ignore the protected block logic and raise the TAE regardless. This is verified by one of the tests in mono/tests/abort-cctor.cs.
4843         */
4844         exc = mono_thread_request_interruption (TRUE);
4845         if (exc)
4846                 mono_error_set_exception_instance (error, exc);
4847         else
4848                 mono_thread_info_self_interrupt ();
4849 }
4850
4851 typedef struct {
4852         MonoInternalThread *thread;
4853         gboolean interrupt;
4854         MonoThreadInfoInterruptToken *interrupt_token;
4855 } SuspendThreadData;
4856
4857 static SuspendThreadResult
4858 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
4859 {
4860         SuspendThreadData *data = (SuspendThreadData *)ud;
4861         MonoInternalThread *thread = data->thread;
4862         MonoJitInfo *ji = NULL;
4863         gboolean protected_wrapper;
4864         gboolean running_managed;
4865
4866         ji = mono_thread_info_get_last_managed (info);
4867         protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
4868         running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
4869
4870         if (running_managed && !protected_wrapper) {
4871                 if (mono_threads_is_coop_enabled ()) {
4872                         mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
4873                         return MonoResumeThread;
4874                 } else {
4875                         thread->state &= ~ThreadState_SuspendRequested;
4876                         thread->state |= ThreadState_Suspended;
4877                         return KeepSuspended;
4878                 }
4879         } else {
4880                 mono_thread_set_interruption_requested (thread);
4881                 if (data->interrupt)
4882                         data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
4883
4884                 return MonoResumeThread;
4885         }
4886 }
4887
4888 /* LOCKING: called with @thread synch_cs held, and releases it */
4889 static void
4890 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
4891 {
4892         SuspendThreadData data;
4893
4894         g_assert (thread != mono_thread_internal_current ());
4895
4896         // MOSTLY_ASYNC_SAFE_PRINTF ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
4897
4898         thread->self_suspended = FALSE;
4899
4900         data.thread = thread;
4901         data.interrupt = interrupt;
4902         data.interrupt_token = NULL;
4903
4904         mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
4905         if (data.interrupt_token)
4906                 mono_thread_info_finish_interrupt (data.interrupt_token);
4907
4908         UNLOCK_THREAD (thread);
4909 }
4910
4911 /* LOCKING: called with @thread synch_cs held, and releases it */
4912 static void
4913 self_suspend_internal (void)
4914 {
4915         MonoInternalThread *thread;
4916         MonoOSEvent *event;
4917         MonoOSEventWaitRet res;
4918
4919         thread = mono_thread_internal_current ();
4920
4921         // MOSTLY_ASYNC_SAFE_PRINTF ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
4922
4923         thread->self_suspended = TRUE;
4924
4925         thread->state &= ~ThreadState_SuspendRequested;
4926         thread->state |= ThreadState_Suspended;
4927
4928         UNLOCK_THREAD (thread);
4929
4930         event = thread->suspended;
4931
4932         MONO_ENTER_GC_SAFE;
4933         res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
4934         g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
4935         MONO_EXIT_GC_SAFE;
4936 }
4937
4938 static void
4939 suspend_for_shutdown_async_call (gpointer unused)
4940 {
4941         for (;;)
4942                 mono_thread_info_yield ();
4943 }
4944
4945 static SuspendThreadResult
4946 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
4947 {
4948         mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
4949         return MonoResumeThread;
4950 }
4951
4952 void
4953 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
4954 {
4955         g_assert (thread != mono_thread_internal_current ());
4956
4957         mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
4958 }
4959
4960 /**
4961  * mono_thread_is_foreign:
4962  * \param thread the thread to query
4963  *
4964  * This function allows one to determine if a thread was created by the mono runtime and has
4965  * a well defined lifecycle or it's a foreign one, created by the native environment.
4966  *
4967  * \returns TRUE if \p thread was not created by the runtime.
4968  */
4969 mono_bool
4970 mono_thread_is_foreign (MonoThread *thread)
4971 {
4972         MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
4973         return info->runtime_thread == FALSE;
4974 }
4975
4976 /*
4977  * mono_add_joinable_thread:
4978  *
4979  *   Add TID to the list of joinable threads.
4980  * LOCKING: Acquires the threads lock.
4981  */
4982 void
4983 mono_threads_add_joinable_thread (gpointer tid)
4984 {
4985 #ifndef HOST_WIN32
4986         /*
4987          * We cannot detach from threads because it causes problems like
4988          * 2fd16f60/r114307. So we collect them and join them when
4989          * we have time (in he finalizer thread).
4990          */
4991         joinable_threads_lock ();
4992         if (!joinable_threads)
4993                 joinable_threads = g_hash_table_new (NULL, NULL);
4994         g_hash_table_insert (joinable_threads, tid, tid);
4995         joinable_thread_count ++;
4996         joinable_threads_unlock ();
4997
4998         mono_gc_finalize_notify ();
4999 #endif
5000 }
5001
5002 /*
5003  * mono_threads_join_threads:
5004  *
5005  *   Join all joinable threads. This is called from the finalizer thread.
5006  * LOCKING: Acquires the threads lock.
5007  */
5008 void
5009 mono_threads_join_threads (void)
5010 {
5011 #ifndef HOST_WIN32
5012         GHashTableIter iter;
5013         gpointer key;
5014         gpointer tid;
5015         pthread_t thread;
5016         gboolean found;
5017
5018         /* Fastpath */
5019         if (!joinable_thread_count)
5020                 return;
5021
5022         while (TRUE) {
5023                 joinable_threads_lock ();
5024                 found = FALSE;
5025                 if (g_hash_table_size (joinable_threads)) {
5026                         g_hash_table_iter_init (&iter, joinable_threads);
5027                         g_hash_table_iter_next (&iter, &key, (void**)&tid);
5028                         thread = (pthread_t)tid;
5029                         g_hash_table_remove (joinable_threads, key);
5030                         joinable_thread_count --;
5031                         found = TRUE;
5032                 }
5033                 joinable_threads_unlock ();
5034                 if (found) {
5035                         if (thread != pthread_self ()) {
5036                                 MONO_ENTER_GC_SAFE;
5037                                 /* This shouldn't block */
5038                                 mono_threads_join_lock ();
5039                                 mono_native_thread_join (thread);
5040                                 mono_threads_join_unlock ();
5041                                 MONO_EXIT_GC_SAFE;
5042                         }
5043                 } else {
5044                         break;
5045                 }
5046         }
5047 #endif
5048 }
5049
5050 /*
5051  * mono_thread_join:
5052  *
5053  *   Wait for thread TID to exit.
5054  * LOCKING: Acquires the threads lock.
5055  */
5056 void
5057 mono_thread_join (gpointer tid)
5058 {
5059 #ifndef HOST_WIN32
5060         pthread_t thread;
5061         gboolean found = FALSE;
5062
5063         joinable_threads_lock ();
5064         if (!joinable_threads)
5065                 joinable_threads = g_hash_table_new (NULL, NULL);
5066         if (g_hash_table_lookup (joinable_threads, tid)) {
5067                 g_hash_table_remove (joinable_threads, tid);
5068                 joinable_thread_count --;
5069                 found = TRUE;
5070         }
5071         joinable_threads_unlock ();
5072         if (!found)
5073                 return;
5074         thread = (pthread_t)tid;
5075         MONO_ENTER_GC_SAFE;
5076         mono_native_thread_join (thread);
5077         MONO_EXIT_GC_SAFE;
5078 #endif
5079 }
5080
5081 void
5082 mono_thread_internal_unhandled_exception (MonoObject* exc)
5083 {
5084         MonoClass *klass = exc->vtable->klass;
5085         if (is_threadabort_exception (klass)) {
5086                 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5087         } else if (!is_appdomainunloaded_exception (klass)
5088                 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
5089                 mono_unhandled_exception (exc);
5090                 if (mono_environment_exitcode_get () == 1) {
5091                         mono_environment_exitcode_set (255);
5092                         mono_invoke_unhandled_exception_hook (exc);
5093                         g_assert_not_reached ();
5094                 }
5095         }
5096 }
5097
5098 void
5099 ves_icall_System_Threading_Thread_GetStackTraces (MonoArray **out_threads, MonoArray **out_stack_traces)
5100 {
5101         MonoError error;
5102         mono_threads_get_thread_dump (out_threads, out_stack_traces, &error);
5103         mono_error_set_pending_exception (&error);
5104 }
5105
5106 /*
5107  * mono_threads_attach_coop: called by native->managed wrappers
5108  *
5109  *  - @dummy:
5110  *    - blocking mode: contains gc unsafe transition cookie
5111  *    - non-blocking mode: contains random data
5112  *  - @return: the original domain which needs to be restored, or NULL.
5113  */
5114 gpointer
5115 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
5116 {
5117         MonoDomain *orig;
5118         MonoThreadInfo *info;
5119         gboolean external;
5120
5121         orig = mono_domain_get ();
5122
5123         if (!domain) {
5124                 /* Happens when called from AOTed code which is only used in the root domain. */
5125                 domain = mono_get_root_domain ();
5126                 g_assert (domain);
5127         }
5128
5129         /* On coop, when we detached, we moved the thread from  RUNNING->BLOCKING.
5130          * If we try to reattach we do a BLOCKING->RUNNING transition.  If the thread
5131          * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
5132          * we're only responsible for making the cookie. */
5133         if (mono_threads_is_blocking_transition_enabled ())
5134                 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
5135
5136         if (!mono_thread_internal_current ()) {
5137                 mono_thread_attach_full (domain, FALSE);
5138
5139                 // #678164
5140                 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
5141         }
5142
5143         if (orig != domain)
5144                 mono_domain_set (domain, TRUE);
5145
5146         if (mono_threads_is_blocking_transition_enabled ()) {
5147                 if (external) {
5148                         /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
5149                          * return the right cookie. */
5150                         *dummy = mono_threads_enter_gc_unsafe_region_cookie ();
5151                 } else {
5152                         /* thread state (BLOCKING|RUNNING) -> RUNNING */
5153                         *dummy = mono_threads_enter_gc_unsafe_region (dummy);
5154                 }
5155         }
5156
5157         return orig;
5158 }
5159
5160 /*
5161  * mono_threads_detach_coop: called by native->managed wrappers
5162  *
5163  *  - @cookie: the original domain which needs to be restored, or NULL.
5164  *  - @dummy:
5165  *    - blocking mode: contains gc unsafe transition cookie
5166  *    - non-blocking mode: contains random data
5167  */
5168 void
5169 mono_threads_detach_coop (gpointer cookie, gpointer *dummy)
5170 {
5171         MonoDomain *domain, *orig;
5172
5173         orig = (MonoDomain*) cookie;
5174
5175         domain = mono_domain_get ();
5176         g_assert (domain);
5177
5178         if (mono_threads_is_blocking_transition_enabled ()) {
5179                 /* it won't do anything if cookie is NULL
5180                  * thread state RUNNING -> (RUNNING|BLOCKING) */
5181                 mono_threads_exit_gc_unsafe_region (*dummy, dummy);
5182         }
5183
5184         if (orig != domain) {
5185                 if (!orig)
5186                         mono_domain_unset ();
5187                 else
5188                         mono_domain_set (orig, TRUE);
5189         }
5190 }
5191
5192 #if 0
5193 /* Returns TRUE if the current thread is ready to be interrupted. */
5194 gboolean
5195 mono_threads_is_ready_to_be_interrupted (void)
5196 {
5197         MonoInternalThread *thread;
5198
5199         thread = mono_thread_internal_current ();
5200         LOCK_THREAD (thread);
5201         if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
5202                 UNLOCK_THREAD (thread);
5203                 return FALSE;
5204         }
5205
5206         if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
5207                 UNLOCK_THREAD (thread);
5208                 return FALSE;
5209         }
5210
5211         UNLOCK_THREAD (thread);
5212         return TRUE;
5213 }
5214 #endif
5215
5216 void
5217 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
5218 {
5219         g_string_append_printf (text, ", thread handle : %p", internal->handle);
5220
5221         if (internal->thread_info) {
5222                 g_string_append (text, ", state : ");
5223                 mono_thread_info_describe_interrupt_token ((MonoThreadInfo*) internal->thread_info, text);
5224         }
5225
5226         if (internal->owned_mutexes) {
5227                 int i;
5228
5229                 g_string_append (text, ", owns : [");
5230                 for (i = 0; i < internal->owned_mutexes->len; i++)
5231                         g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
5232                 g_string_append (text, "]");
5233         }
5234 }
5235
5236 gboolean
5237 mono_thread_internal_is_current (MonoInternalThread *internal)
5238 {
5239         g_assert (internal);
5240         return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
5241 }