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