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