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