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