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