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