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