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