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