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