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