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