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