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