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