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