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