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