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