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