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