2008-08-22 Robert Jordan <robertj@gmx.net>
[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         if (this == mono_thread_current ())
1939                 return;
1940         
1941         EnterCriticalSection (this->synch_cs);
1942         
1943         this->thread_interrupt_requested = TRUE;
1944         
1945         if (this->state & ThreadState_WaitSleepJoin) {
1946                 throw = TRUE;
1947         }
1948         
1949         LeaveCriticalSection (this->synch_cs);
1950         
1951         if (throw) {
1952                 signal_thread_state_change (this);
1953         }
1954 }
1955
1956 void mono_thread_current_check_pending_interrupt ()
1957 {
1958         MonoThread *thread = mono_thread_current ();
1959         gboolean throw = FALSE;
1960
1961         mono_debugger_check_interruption ();
1962
1963         ensure_synch_cs_set (thread);
1964         
1965         EnterCriticalSection (thread->synch_cs);
1966         
1967         if (thread->thread_interrupt_requested) {
1968                 throw = TRUE;
1969                 thread->thread_interrupt_requested = FALSE;
1970         }
1971         
1972         LeaveCriticalSection (thread->synch_cs);
1973
1974         if (throw) {
1975                 mono_raise_exception (mono_get_exception_thread_interrupted ());
1976         }
1977 }
1978
1979 int  
1980 mono_thread_get_abort_signal (void)
1981 {
1982 #ifdef PLATFORM_WIN32
1983         return -1;
1984 #else
1985 #ifndef SIGRTMIN
1986         return SIGUSR1;
1987 #else
1988         static int abort_signum = -1;
1989         int i;
1990         if (abort_signum != -1)
1991                 return abort_signum;
1992         /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1993         for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1994                 struct sigaction sinfo;
1995                 sigaction (i, NULL, &sinfo);
1996                 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1997                         abort_signum = i;
1998                         return i;
1999                 }
2000         }
2001         /* fallback to the old way */
2002         return SIGRTMIN;
2003 #endif
2004 #endif /* PLATFORM_WIN32 */
2005 }
2006
2007 #ifdef PLATFORM_WIN32
2008 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2009 {
2010         MonoException* exc = mono_thread_request_interruption (FALSE);
2011         if (exc) mono_raise_exception (exc);
2012 }
2013 #endif /* PLATFORM_WIN32 */
2014
2015 /*
2016  * signal_thread_state_change
2017  *
2018  * Tells the thread that his state has changed and it has to enter the new
2019  * state as soon as possible.
2020  */
2021 static void signal_thread_state_change (MonoThread *thread)
2022 {
2023         if (thread == mono_thread_current ()) {
2024                 /* Do it synchronously */
2025                 MonoException *exc = mono_thread_request_interruption (FALSE); 
2026                 if (exc)
2027                         mono_raise_exception (exc);
2028         }
2029
2030 #ifdef PLATFORM_WIN32
2031         QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2032 #else
2033         /* fixme: store the state somewhere */
2034 #ifdef PTHREAD_POINTER_ID
2035         pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2036 #else
2037         pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2038 #endif
2039 #endif /* PLATFORM_WIN32 */
2040 }
2041
2042 void
2043 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2044 {
2045         MONO_ARCH_SAVE_REGS;
2046
2047         ensure_synch_cs_set (thread);
2048         
2049         EnterCriticalSection (thread->synch_cs);
2050         
2051         if ((thread->state & ThreadState_AbortRequested) != 0 || 
2052                 (thread->state & ThreadState_StopRequested) != 0 ||
2053                 (thread->state & ThreadState_Stopped) != 0)
2054         {
2055                 LeaveCriticalSection (thread->synch_cs);
2056                 return;
2057         }
2058
2059         if ((thread->state & ThreadState_Unstarted) != 0) {
2060                 thread->state |= ThreadState_Aborted;
2061                 LeaveCriticalSection (thread->synch_cs);
2062                 return;
2063         }
2064
2065         thread->state |= ThreadState_AbortRequested;
2066         MONO_OBJECT_SETREF (thread, abort_state, state);
2067         thread->abort_exc = NULL;
2068
2069         LeaveCriticalSection (thread->synch_cs);
2070
2071         THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2072
2073         /* During shutdown, we can't wait for other threads */
2074         if (!shutting_down)
2075                 /* Make sure the thread is awake */
2076                 mono_thread_resume (thread);
2077         
2078         signal_thread_state_change (thread);
2079 }
2080
2081 void
2082 ves_icall_System_Threading_Thread_ResetAbort (void)
2083 {
2084         MonoThread *thread = mono_thread_current ();
2085
2086         MONO_ARCH_SAVE_REGS;
2087
2088         ensure_synch_cs_set (thread);
2089         
2090         EnterCriticalSection (thread->synch_cs);
2091
2092         thread->state &= ~ThreadState_AbortRequested;
2093         
2094         if (!thread->abort_exc) {
2095                 const char *msg = "Unable to reset abort because no abort was requested";
2096                 LeaveCriticalSection (thread->synch_cs);
2097                 mono_raise_exception (mono_get_exception_thread_state (msg));
2098         } else {
2099                 thread->abort_exc = NULL;
2100                 thread->abort_state = NULL;
2101         }
2102         
2103         LeaveCriticalSection (thread->synch_cs);
2104 }
2105
2106 static gboolean
2107 mono_thread_suspend (MonoThread *thread)
2108 {
2109         MONO_ARCH_SAVE_REGS;
2110
2111         ensure_synch_cs_set (thread);
2112         
2113         EnterCriticalSection (thread->synch_cs);
2114
2115         if ((thread->state & ThreadState_Unstarted) != 0 || 
2116                 (thread->state & ThreadState_Aborted) != 0 || 
2117                 (thread->state & ThreadState_Stopped) != 0)
2118         {
2119                 LeaveCriticalSection (thread->synch_cs);
2120                 return FALSE;
2121         }
2122
2123         if ((thread->state & ThreadState_Suspended) != 0 || 
2124                 (thread->state & ThreadState_SuspendRequested) != 0 ||
2125                 (thread->state & ThreadState_StopRequested) != 0) 
2126         {
2127                 LeaveCriticalSection (thread->synch_cs);
2128                 return TRUE;
2129         }
2130         
2131         thread->state |= ThreadState_SuspendRequested;
2132
2133         LeaveCriticalSection (thread->synch_cs);
2134
2135         signal_thread_state_change (thread);
2136         return TRUE;
2137 }
2138
2139 void
2140 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2141 {
2142         if (!mono_thread_suspend (thread))
2143                 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2144 }
2145
2146 static gboolean
2147 mono_thread_resume (MonoThread *thread)
2148 {
2149         MONO_ARCH_SAVE_REGS;
2150
2151         ensure_synch_cs_set (thread);
2152         
2153         EnterCriticalSection (thread->synch_cs);
2154
2155         if ((thread->state & ThreadState_SuspendRequested) != 0) {
2156                 thread->state &= ~ThreadState_SuspendRequested;
2157                 LeaveCriticalSection (thread->synch_cs);
2158                 return TRUE;
2159         }
2160
2161         if ((thread->state & ThreadState_Suspended) == 0 ||
2162                 (thread->state & ThreadState_Unstarted) != 0 || 
2163                 (thread->state & ThreadState_Aborted) != 0 || 
2164                 (thread->state & ThreadState_Stopped) != 0)
2165         {
2166                 LeaveCriticalSection (thread->synch_cs);
2167                 return FALSE;
2168         }
2169         
2170         thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2171         if (thread->resume_event == NULL) {
2172                 LeaveCriticalSection (thread->synch_cs);
2173                 return(FALSE);
2174         }
2175         
2176         /* Awake the thread */
2177         SetEvent (thread->suspend_event);
2178
2179         LeaveCriticalSection (thread->synch_cs);
2180
2181         /* Wait for the thread to awake */
2182         WaitForSingleObject (thread->resume_event, INFINITE);
2183         CloseHandle (thread->resume_event);
2184         thread->resume_event = NULL;
2185
2186         return TRUE;
2187 }
2188
2189 void
2190 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2191 {
2192         if (!mono_thread_resume (thread))
2193                 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2194 }
2195
2196 static gboolean
2197 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2198 {
2199         if (managed)
2200                 return TRUE;
2201
2202         if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2203                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2204                 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH) 
2205         {
2206                 *((gboolean*)data) = TRUE;
2207                 return TRUE;
2208         }
2209         return FALSE;
2210 }
2211
2212 static gboolean 
2213 is_running_protected_wrapper (void)
2214 {
2215         gboolean found = FALSE;
2216         mono_stack_walk (find_wrapper, &found);
2217         return found;
2218 }
2219
2220 void mono_thread_stop (MonoThread *thread)
2221 {
2222         ensure_synch_cs_set (thread);
2223         
2224         EnterCriticalSection (thread->synch_cs);
2225
2226         if ((thread->state & ThreadState_StopRequested) != 0 ||
2227                 (thread->state & ThreadState_Stopped) != 0)
2228         {
2229                 LeaveCriticalSection (thread->synch_cs);
2230                 return;
2231         }
2232         
2233         /* Make sure the thread is awake */
2234         mono_thread_resume (thread);
2235
2236         thread->state |= ThreadState_StopRequested;
2237         thread->state &= ~ThreadState_AbortRequested;
2238         
2239         LeaveCriticalSection (thread->synch_cs);
2240         
2241         signal_thread_state_change (thread);
2242 }
2243
2244 gint8
2245 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2246 {
2247         return *((volatile gint8 *) (ptr));
2248 }
2249
2250 gint16
2251 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2252 {
2253         return *((volatile gint16 *) (ptr));
2254 }
2255
2256 gint32
2257 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2258 {
2259         return *((volatile gint32 *) (ptr));
2260 }
2261
2262 gint64
2263 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2264 {
2265         return *((volatile gint64 *) (ptr));
2266 }
2267
2268 void *
2269 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2270 {
2271         return (void *)  *((volatile void **) ptr);
2272 }
2273
2274 void
2275 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2276 {
2277         *((volatile gint8 *) ptr) = value;
2278 }
2279
2280 void
2281 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2282 {
2283         *((volatile gint16 *) ptr) = value;
2284 }
2285
2286 void
2287 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2288 {
2289         *((volatile gint32 *) ptr) = value;
2290 }
2291
2292 void
2293 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2294 {
2295         *((volatile gint64 *) ptr) = value;
2296 }
2297
2298 void
2299 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2300 {
2301         *((volatile void **) ptr) = value;
2302 }
2303
2304 void mono_thread_init (MonoThreadStartCB start_cb,
2305                        MonoThreadAttachCB attach_cb)
2306 {
2307         MONO_GC_REGISTER_ROOT (small_id_table);
2308         InitializeCriticalSection(&threads_mutex);
2309         InitializeCriticalSection(&interlocked_mutex);
2310         InitializeCriticalSection(&contexts_mutex);
2311         InitializeCriticalSection(&delayed_free_table_mutex);
2312         InitializeCriticalSection(&small_id_mutex);
2313         
2314         background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2315         g_assert(background_change_event != NULL);
2316         
2317         mono_init_static_data_info (&thread_static_info);
2318         mono_init_static_data_info (&context_static_info);
2319
2320         current_object_key=TlsAlloc();
2321         THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2322
2323         mono_thread_start_cb = start_cb;
2324         mono_thread_attach_cb = attach_cb;
2325
2326         delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2327
2328         /* Get a pseudo handle to the current process.  This is just a
2329          * kludge so that wapi can build a process handle if needed.
2330          * As a pseudo handle is returned, we don't need to clean
2331          * anything up.
2332          */
2333         GetCurrentProcess ();
2334 }
2335
2336 void mono_thread_cleanup (void)
2337 {
2338         mono_thread_hazardous_try_free_all ();
2339
2340 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2341         /* The main thread must abandon any held mutexes (particularly
2342          * important for named mutexes as they are shared across
2343          * processes, see bug 74680.)  This will happen when the
2344          * thread exits, but if it's not running in a subthread it
2345          * won't exit in time.
2346          */
2347         /* Using non-w32 API is a nasty kludge, but I couldn't find
2348          * anything in the documentation that would let me do this
2349          * here yet still be safe to call on windows.
2350          */
2351         _wapi_thread_signal_self (mono_environment_exitcode_get ());
2352 #endif
2353
2354 #if 0
2355         /* This stuff needs more testing, it seems one of these
2356          * critical sections can be locked when mono_thread_cleanup is
2357          * called.
2358          */
2359         DeleteCriticalSection (&threads_mutex);
2360         DeleteCriticalSection (&interlocked_mutex);
2361         DeleteCriticalSection (&contexts_mutex);
2362         DeleteCriticalSection (&delayed_free_table_mutex);
2363         DeleteCriticalSection (&small_id_mutex);
2364         CloseHandle (background_change_event);
2365 #endif
2366
2367         g_array_free (delayed_free_table, TRUE);
2368         delayed_free_table = NULL;
2369
2370         TlsFree (current_object_key);
2371 }
2372
2373 void
2374 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2375 {
2376         mono_thread_cleanup_fn = func;
2377 }
2378
2379 void
2380 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2381 {
2382         thread->manage_callback = func;
2383 }
2384
2385 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2386 {
2387         mono_thread_notify_pending_exc_fn = func;
2388 }
2389
2390 G_GNUC_UNUSED
2391 static void print_tids (gpointer key, gpointer value, gpointer user)
2392 {
2393         /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2394          * sizeof(uint) and a cast to uint would overflow
2395          */
2396         /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2397          * print this as a pointer.
2398          */
2399         g_message ("Waiting for: %p", key);
2400 }
2401
2402 struct wait_data 
2403 {
2404         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2405         MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2406         guint32 num;
2407 };
2408
2409 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2410 {
2411         guint32 i, ret;
2412         
2413         THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2414
2415         ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2416
2417         if(ret==WAIT_FAILED) {
2418                 /* See the comment in build_wait_tids() */
2419                 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2420                 return;
2421         }
2422         
2423         for(i=0; i<wait->num; i++)
2424                 CloseHandle (wait->handles[i]);
2425
2426         if (ret == WAIT_TIMEOUT)
2427                 return;
2428
2429         for(i=0; i<wait->num; i++) {
2430                 gsize tid = wait->threads[i]->tid;
2431                 
2432                 mono_threads_lock ();
2433                 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2434                         /* This thread must have been killed, because
2435                          * it hasn't cleaned itself up. (It's just
2436                          * possible that the thread exited before the
2437                          * parent thread had a chance to store the
2438                          * handle, and now there is another pointer to
2439                          * the already-exited thread stored.  In this
2440                          * case, we'll just get two
2441                          * mono_profiler_thread_end() calls for the
2442                          * same thread.)
2443                          */
2444         
2445                         mono_threads_unlock ();
2446                         THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2447                         thread_cleanup (wait->threads[i]);
2448                 } else {
2449                         mono_threads_unlock ();
2450                 }
2451         }
2452 }
2453
2454 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2455 {
2456         guint32 i, ret, count;
2457         
2458         THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2459
2460         /* Add the thread state change event, so it wakes up if a thread changes
2461          * to background mode.
2462          */
2463         count = wait->num;
2464         if (count < MAXIMUM_WAIT_OBJECTS) {
2465                 wait->handles [count] = background_change_event;
2466                 count++;
2467         }
2468
2469         ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2470
2471         if(ret==WAIT_FAILED) {
2472                 /* See the comment in build_wait_tids() */
2473                 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2474                 return;
2475         }
2476         
2477         for(i=0; i<wait->num; i++)
2478                 CloseHandle (wait->handles[i]);
2479
2480         if (ret == WAIT_TIMEOUT)
2481                 return;
2482         
2483         if (ret < wait->num) {
2484                 gsize tid = wait->threads[ret]->tid;
2485                 mono_threads_lock ();
2486                 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2487                         /* See comment in wait_for_tids about thread cleanup */
2488                         mono_threads_unlock ();
2489                         THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2490                         thread_cleanup (wait->threads [ret]);
2491                 } else
2492                         mono_threads_unlock ();
2493         }
2494 }
2495
2496 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2497 {
2498         struct wait_data *wait=(struct wait_data *)user;
2499
2500         if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2501                 HANDLE handle;
2502                 MonoThread *thread=(MonoThread *)value;
2503
2504                 /* Ignore background threads, we abort them later */
2505                 /* Do not lock here since it is not needed and the caller holds threads_lock */
2506                 if (thread->state & ThreadState_Background) {
2507                         THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2508                         return; /* just leave, ignore */
2509                 }
2510                 
2511                 if (mono_gc_is_finalizer_thread (thread)) {
2512                         THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2513                         return;
2514                 }
2515
2516                 if (thread == mono_thread_current ()) {
2517                         THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2518                         return;
2519                 }
2520
2521                 if (thread == mono_thread_get_main ()) {
2522                         THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2523                         return;
2524                 }
2525
2526                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2527                 if (handle == NULL) {
2528                         THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2529                         return;
2530                 }
2531                 
2532                 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2533                 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2534                         wait->handles[wait->num]=handle;
2535                         wait->threads[wait->num]=thread;
2536                         wait->num++;
2537
2538                         THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2539                 } else {
2540                         THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2541                 }
2542                 
2543                 
2544         } else {
2545                 /* Just ignore the rest, we can't do anything with
2546                  * them yet
2547                  */
2548         }
2549 }
2550
2551 static gboolean
2552 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2553 {
2554         struct wait_data *wait=(struct wait_data *)user;
2555         gsize self = GetCurrentThreadId ();
2556         MonoThread *thread = (MonoThread *) value;
2557         HANDLE handle;
2558
2559         if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2560                 return FALSE;
2561
2562         /* The finalizer thread is not a background thread */
2563         if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2564         
2565                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2566                 if (handle == NULL)
2567                         return FALSE;
2568
2569                 /* printf ("A: %d\n", wait->num); */
2570                 wait->handles[wait->num]=thread->handle;
2571                 wait->threads[wait->num]=thread;
2572                 wait->num++;
2573
2574                 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2575                 mono_thread_stop (thread);
2576                 return TRUE;
2577         }
2578
2579         return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
2580 }
2581
2582 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
2583
2584 /** 
2585  * mono_threads_set_shutting_down:
2586  *
2587  * Is called by a thread that wants to shut down Mono. If the runtime is already
2588  * shutting down, the calling thread is suspended/stopped, and this function never
2589  * returns.
2590  */
2591 void
2592 mono_threads_set_shutting_down (void)
2593 {
2594         MonoThread *current_thread = mono_thread_current ();
2595
2596         mono_threads_lock ();
2597
2598         if (shutting_down) {
2599                 mono_threads_unlock ();
2600
2601                 /* Make sure we're properly suspended/stopped */
2602
2603                 EnterCriticalSection (current_thread->synch_cs);
2604
2605                 if ((current_thread->state & ThreadState_SuspendRequested) ||
2606                     (current_thread->state & ThreadState_AbortRequested) ||
2607                     (current_thread->state & ThreadState_StopRequested)) {
2608                         LeaveCriticalSection (current_thread->synch_cs);
2609                         mono_thread_execute_interruption (current_thread);
2610                 } else {
2611                         current_thread->state |= ThreadState_Stopped;
2612                         LeaveCriticalSection (current_thread->synch_cs);
2613                 }
2614
2615                 /* Wake up other threads potentially waiting for us */
2616                 ExitThread (0);
2617         } else {
2618                 shutting_down = TRUE;
2619
2620                 /* Not really a background state change, but this will
2621                  * interrupt the main thread if it is waiting for all
2622                  * the other threads.
2623                  */
2624                 SetEvent (background_change_event);
2625                 
2626                 mono_threads_unlock ();
2627         }
2628 }
2629
2630 /** 
2631  * mono_threads_is_shutting_down:
2632  *
2633  * Returns whether a thread has commenced shutdown of Mono.  Note that
2634  * if the function returns FALSE the caller must not assume that
2635  * shutdown is not in progress, because the situation might have
2636  * changed since the function returned.  For that reason this function
2637  * is of very limited utility.
2638  */
2639 gboolean
2640 mono_threads_is_shutting_down (void)
2641 {
2642         return shutting_down;
2643 }
2644
2645 void mono_thread_manage (void)
2646 {
2647         struct wait_data *wait=g_new0 (struct wait_data, 1);
2648
2649         /* join each thread that's still running */
2650         THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2651         
2652         mono_threads_lock ();
2653         if(threads==NULL) {
2654                 THREAD_DEBUG (g_message("%s: No threads", __func__));
2655                 mono_threads_unlock ();
2656                 return;
2657         }
2658         mono_threads_unlock ();
2659         
2660         do {
2661                 mono_threads_lock ();
2662                 if (shutting_down) {
2663                         /* somebody else is shutting down */
2664                         mono_threads_unlock ();
2665                         break;
2666                 }
2667                 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2668                         mono_g_hash_table_foreach (threads, print_tids, NULL));
2669         
2670                 ResetEvent (background_change_event);
2671                 wait->num=0;
2672                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2673                 mono_threads_unlock ();
2674                 if(wait->num>0) {
2675                         /* Something to wait for */
2676                         wait_for_tids_or_state_change (wait, INFINITE);
2677                 }
2678                 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2679         } while(wait->num>0);
2680
2681         mono_threads_set_shutting_down ();
2682
2683         /* No new threads will be created after this point */
2684
2685         mono_runtime_set_shutting_down ();
2686
2687         THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2688         mono_thread_pool_cleanup ();
2689
2690         /* 
2691          * Remove everything but the finalizer thread and self.
2692          * Also abort all the background threads
2693          * */
2694         do {
2695                 mono_threads_lock ();
2696
2697                 wait->num = 0;
2698                 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2699
2700                 mono_threads_unlock ();
2701
2702                 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2703                 if(wait->num>0) {
2704                         /* Something to wait for */
2705                         wait_for_tids (wait, INFINITE);
2706                 }
2707         } while (wait->num > 0);
2708         
2709         /* 
2710          * give the subthreads a chance to really quit (this is mainly needed
2711          * to get correct user and system times from getrusage/wait/time(1)).
2712          * This could be removed if we avoid pthread_detach() and use pthread_join().
2713          */
2714 #ifndef PLATFORM_WIN32
2715         sched_yield ();
2716 #endif
2717
2718         g_free (wait);
2719 }
2720
2721 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2722 {
2723         MonoThread *thread=(MonoThread *)value;
2724         
2725         if(thread->tid != (gsize)user) {
2726                 /*TerminateThread (thread->handle, -1);*/
2727         }
2728 }
2729
2730 void mono_thread_abort_all_other_threads (void)
2731 {
2732         gsize self = GetCurrentThreadId ();
2733
2734         mono_threads_lock ();
2735         THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2736                                  mono_g_hash_table_size (threads));
2737                       mono_g_hash_table_foreach (threads, print_tids, NULL));
2738
2739         mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2740         
2741         mono_threads_unlock ();
2742 }
2743
2744 static void
2745 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2746 {
2747         MonoThread *thread = (MonoThread*)value;
2748         struct wait_data *wait = (struct wait_data*)user_data;
2749         HANDLE handle;
2750
2751         /* 
2752          * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2753          * limitation.
2754          * This needs no locking.
2755          */
2756         if ((thread->state & ThreadState_Suspended) != 0 || 
2757                 (thread->state & ThreadState_Stopped) != 0)
2758                 return;
2759
2760         if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2761                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2762                 if (handle == NULL)
2763                         return;
2764
2765                 wait->handles [wait->num] = handle;
2766                 wait->threads [wait->num] = thread;
2767                 wait->num++;
2768         }
2769 }
2770
2771 /*
2772  * mono_thread_suspend_all_other_threads:
2773  *
2774  *  Suspend all managed threads except the finalizer thread and this thread. It is
2775  * not possible to resume them later.
2776  */
2777 void mono_thread_suspend_all_other_threads (void)
2778 {
2779         struct wait_data *wait = g_new0 (struct wait_data, 1);
2780         int i;
2781         gsize self = GetCurrentThreadId ();
2782         gpointer *events;
2783         guint32 eventidx = 0;
2784         gboolean starting, finished;
2785
2786         /*
2787          * The other threads could be in an arbitrary state at this point, i.e.
2788          * they could be starting up, shutting down etc. This means that there could be
2789          * threads which are not even in the threads hash table yet.
2790          */
2791
2792         /* 
2793          * First we set a barrier which will be checked by all threads before they
2794          * are added to the threads hash table, and they will exit if the flag is set.
2795          * This ensures that no threads could be added to the hash later.
2796          * We will use shutting_down as the barrier for now.
2797          */
2798         g_assert (shutting_down);
2799
2800         /*
2801          * We make multiple calls to WaitForMultipleObjects since:
2802          * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2803          * - some threads could exit without becoming suspended
2804          */
2805         finished = FALSE;
2806         while (!finished) {
2807                 /*
2808                  * Make a copy of the hashtable since we can't do anything with
2809                  * threads while threads_mutex is held.
2810                  */
2811                 wait->num = 0;
2812                 mono_threads_lock ();
2813                 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2814                 mono_threads_unlock ();
2815
2816                 events = g_new0 (gpointer, wait->num);
2817                 eventidx = 0;
2818                 /* Get the suspended events that we'll be waiting for */
2819                 for (i = 0; i < wait->num; ++i) {
2820                         MonoThread *thread = wait->threads [i];
2821
2822                         if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2823                                 //CloseHandle (wait->handles [i]);
2824                                 wait->threads [i] = NULL; /* ignore this thread in next loop */
2825                                 continue;
2826                         }
2827
2828                         ensure_synch_cs_set (thread);
2829                 
2830                         EnterCriticalSection (thread->synch_cs);
2831
2832                         if ((thread->state & ThreadState_Suspended) != 0 || 
2833                                 (thread->state & ThreadState_SuspendRequested) != 0 ||
2834                                 (thread->state & ThreadState_StopRequested) != 0 ||
2835                                 (thread->state & ThreadState_Stopped) != 0) {
2836                                 LeaveCriticalSection (thread->synch_cs);
2837                                 CloseHandle (wait->handles [i]);
2838                                 wait->threads [i] = NULL; /* ignore this thread in next loop */
2839                                 continue;
2840                         }
2841
2842                         /* Convert abort requests into suspend requests */
2843                         if ((thread->state & ThreadState_AbortRequested) != 0)
2844                                 thread->state &= ~ThreadState_AbortRequested;
2845                         
2846                         thread->state |= ThreadState_SuspendRequested;
2847
2848                         if (thread->suspended_event == NULL) {
2849                                 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2850                                 if (thread->suspended_event == NULL) {
2851                                         /* Forget this one and go on to the next */
2852                                         LeaveCriticalSection (thread->synch_cs);
2853                                         continue;
2854                                 }
2855                         }
2856
2857                         events [eventidx++] = thread->suspended_event;
2858                         LeaveCriticalSection (thread->synch_cs);
2859
2860                         /* Signal the thread to suspend */
2861                         signal_thread_state_change (thread);
2862                 }
2863
2864                 if (eventidx > 0) {
2865                         WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2866                         for (i = 0; i < wait->num; ++i) {
2867                                 MonoThread *thread = wait->threads [i];
2868
2869                                 if (thread == NULL)
2870                                         continue;
2871                         
2872                                 EnterCriticalSection (thread->synch_cs);
2873                                 if ((thread->state & ThreadState_Suspended) != 0) {
2874                                         CloseHandle (thread->suspended_event);
2875                                         thread->suspended_event = NULL;
2876                                 }
2877                                 LeaveCriticalSection (thread->synch_cs);
2878                         }
2879                 } else {
2880                         /* 
2881                          * If there are threads which are starting up, we wait until they
2882                          * are suspended when they try to register in the threads hash.
2883                          * This is guaranteed to finish, since the threads which can create new
2884                          * threads get suspended after a while.
2885                          * FIXME: The finalizer thread can still create new threads.
2886                          */
2887                         mono_threads_lock ();
2888                         starting = mono_g_hash_table_size (threads_starting_up) > 0;
2889                         mono_threads_unlock ();
2890                         if (starting)
2891                                 Sleep (100);
2892                         else
2893                                 finished = TRUE;
2894                 }
2895
2896                 g_free (events);
2897         }
2898
2899         g_free (wait);
2900 }
2901
2902 static void
2903 collect_threads (gpointer key, gpointer value, gpointer user_data)
2904 {
2905         MonoThread *thread = (MonoThread*)value;
2906         struct wait_data *wait = (struct wait_data*)user_data;
2907         HANDLE handle;
2908
2909         if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2910                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2911                 if (handle == NULL)
2912                         return;
2913
2914                 wait->handles [wait->num] = handle;
2915                 wait->threads [wait->num] = thread;
2916                 wait->num++;
2917         }
2918 }
2919
2920 /**
2921  * mono_threads_request_thread_dump:
2922  *
2923  *   Ask all threads except the current to print their stacktrace to stdout.
2924  */
2925 void
2926 mono_threads_request_thread_dump (void)
2927 {
2928         struct wait_data *wait = g_new0 (struct wait_data, 1);
2929         int i;
2930
2931         /* 
2932          * Make a copy of the hashtable since we can't do anything with
2933          * threads while threads_mutex is held.
2934          */
2935         mono_threads_lock ();
2936         mono_g_hash_table_foreach (threads, collect_threads, wait);
2937         mono_threads_unlock ();
2938
2939         for (i = 0; i < wait->num; ++i) {
2940                 MonoThread *thread = wait->threads [i];
2941
2942                 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2943                         thread->thread_dump_requested = TRUE;
2944
2945                         signal_thread_state_change (thread);
2946                 }
2947
2948                 CloseHandle (wait->handles [i]);
2949         }
2950 }
2951
2952 /*
2953  * mono_thread_push_appdomain_ref:
2954  *
2955  *   Register that the current thread may have references to objects in domain 
2956  * @domain on its stack. Each call to this function should be paired with a 
2957  * call to pop_appdomain_ref.
2958  */
2959 void 
2960 mono_thread_push_appdomain_ref (MonoDomain *domain)
2961 {
2962         MonoThread *thread = mono_thread_current ();
2963
2964         if (thread) {
2965                 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2966                 mono_threads_lock ();
2967                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2968                 mono_threads_unlock ();
2969         }
2970 }
2971
2972 void
2973 mono_thread_pop_appdomain_ref (void)
2974 {
2975         MonoThread *thread = mono_thread_current ();
2976
2977         if (thread) {
2978                 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2979                 mono_threads_lock ();
2980                 /* FIXME: How can the list be empty ? */
2981                 if (thread->appdomain_refs)
2982                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2983                 mono_threads_unlock ();
2984         }
2985 }
2986
2987 gboolean
2988 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2989 {
2990         gboolean res;
2991         mono_threads_lock ();
2992         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2993         mono_threads_unlock ();
2994         return res;
2995 }
2996
2997 typedef struct abort_appdomain_data {
2998         struct wait_data wait;
2999         MonoDomain *domain;
3000 } abort_appdomain_data;
3001
3002 static void
3003 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3004 {
3005         MonoThread *thread = (MonoThread*)value;
3006         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3007         MonoDomain *domain = data->domain;
3008
3009         if (mono_thread_has_appdomain_ref (thread, domain)) {
3010                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3011
3012                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
3013
3014                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3015                         HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3016                         if (handle == NULL)
3017                                 return;
3018                         data->wait.handles [data->wait.num] = handle;
3019                         data->wait.threads [data->wait.num] = thread;
3020                         data->wait.num++;
3021                 } else {
3022                         /* Just ignore the rest, we can't do anything with
3023                          * them yet
3024                          */
3025                 }
3026         }
3027 }
3028
3029 /*
3030  * mono_threads_abort_appdomain_threads:
3031  *
3032  *   Abort threads which has references to the given appdomain.
3033  */
3034 gboolean
3035 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3036 {
3037         abort_appdomain_data user_data;
3038         guint32 start_time;
3039         int orig_timeout = timeout;
3040
3041         THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3042
3043         start_time = mono_msec_ticks ();
3044         do {
3045                 mono_threads_lock ();
3046
3047                 user_data.domain = domain;
3048                 user_data.wait.num = 0;
3049                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
3050                 mono_threads_unlock ();
3051
3052                 if (user_data.wait.num > 0)
3053                         /*
3054                          * We should wait for the threads either to abort, or to leave the
3055                          * domain. We can't do the latter, so we wait with a timeout.
3056                          */
3057                         wait_for_tids (&user_data.wait, 100);
3058
3059                 /* Update remaining time */
3060                 timeout -= mono_msec_ticks () - start_time;
3061                 start_time = mono_msec_ticks ();
3062
3063                 if (orig_timeout != -1 && timeout < 0)
3064                         return FALSE;
3065         }
3066         while (user_data.wait.num > 0);
3067
3068         THREAD_DEBUG (g_message ("%s: abort done", __func__));
3069
3070         return TRUE;
3071 }
3072
3073 static void
3074 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3075 {
3076         MonoThread *thread = (MonoThread*)value;
3077         MonoDomain *domain = (MonoDomain*)user_data;
3078         int i;
3079
3080         /* No locking needed here */
3081         /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3082
3083         if (thread->cached_culture_info) {
3084                 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3085                         MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3086                         if (obj && obj->vtable->domain == domain)
3087                                 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3088                 }
3089         }
3090 }
3091         
3092 /*
3093  * mono_threads_clear_cached_culture:
3094  *
3095  *   Clear the cached_current_culture from all threads if it is in the
3096  * given appdomain.
3097  */
3098 void
3099 mono_threads_clear_cached_culture (MonoDomain *domain)
3100 {
3101         mono_threads_lock ();
3102         mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3103         mono_threads_unlock ();
3104 }
3105
3106 /*
3107  * mono_thread_get_undeniable_exception:
3108  *
3109  *   Return an exception which needs to be raised when leaving a catch clause.
3110  * This is used for undeniable exception propagation.
3111  */
3112 MonoException*
3113 mono_thread_get_undeniable_exception (void)
3114 {
3115         MonoThread *thread = mono_thread_current ();
3116
3117         MONO_ARCH_SAVE_REGS;
3118
3119         if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3120                 /*
3121                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
3122                  * exception if the thread no longer references a dying appdomain.
3123                  */
3124                 thread->abort_exc->trace_ips = NULL;
3125                 thread->abort_exc->stack_trace = NULL;
3126                 return thread->abort_exc;
3127         }
3128
3129         return NULL;
3130 }
3131
3132 #define NUM_STATIC_DATA_IDX 8
3133 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3134         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3135 };
3136
3137
3138 /*
3139  *  mono_alloc_static_data
3140  *
3141  *   Allocate memory blocks for storing threads or context static data
3142  */
3143 static void 
3144 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3145 {
3146         guint idx = (offset >> 24) - 1;
3147         int i;
3148
3149         gpointer* static_data = *static_data_ptr;
3150         if (!static_data) {
3151                 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3152                 *static_data_ptr = static_data;
3153                 static_data [0] = static_data;
3154         }
3155
3156         for (i = 1; i <= idx; ++i) {
3157                 if (static_data [i])
3158                         continue;
3159                 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3160         }
3161 }
3162
3163 /*
3164  *  mono_init_static_data_info
3165  *
3166  *   Initializes static data counters
3167  */
3168 static void mono_init_static_data_info (StaticDataInfo *static_data)
3169 {
3170         static_data->idx = 0;
3171         static_data->offset = 0;
3172         static_data->freelist = NULL;
3173 }
3174
3175 /*
3176  *  mono_alloc_static_data_slot
3177  *
3178  *   Generates an offset for static data. static_data contains the counters
3179  *  used to generate it.
3180  */
3181 static guint32
3182 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3183 {
3184         guint32 offset;
3185
3186         if (!static_data->idx && !static_data->offset) {
3187                 /* 
3188                  * we use the first chunk of the first allocation also as
3189                  * an array for the rest of the data 
3190                  */
3191                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3192         }
3193         static_data->offset += align - 1;
3194         static_data->offset &= ~(align - 1);
3195         if (static_data->offset + size >= static_data_size [static_data->idx]) {
3196                 static_data->idx ++;
3197                 g_assert (size <= static_data_size [static_data->idx]);
3198                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3199                 static_data->offset = 0;
3200         }
3201         offset = static_data->offset | ((static_data->idx + 1) << 24);
3202         static_data->offset += size;
3203         return offset;
3204 }
3205
3206 /* 
3207  * ensure thread static fields already allocated are valid for thread
3208  * This function is called when a thread is created or on thread attach.
3209  */
3210 static void
3211 thread_adjust_static_data (MonoThread *thread)
3212 {
3213         guint32 offset;
3214
3215         mono_threads_lock ();
3216         if (thread_static_info.offset || thread_static_info.idx > 0) {
3217                 /* get the current allocated size */
3218                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3219                 mono_alloc_static_data (&(thread->static_data), offset);
3220         }
3221         mono_threads_unlock ();
3222 }
3223
3224 static void 
3225 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3226 {
3227         MonoThread *thread = value;
3228         guint32 offset = GPOINTER_TO_UINT (user);
3229         
3230         mono_alloc_static_data (&(thread->static_data), offset);
3231 }
3232
3233 static MonoThreadDomainTls*
3234 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3235 {
3236         MonoThreadDomainTls* prev = NULL;
3237         MonoThreadDomainTls* tmp = static_data->freelist;
3238         while (tmp) {
3239                 if (tmp->size == size) {
3240                         if (prev)
3241                                 prev->next = tmp->next;
3242                         else
3243                                 static_data->freelist = tmp->next;
3244                         return tmp;
3245                 }
3246                 tmp = tmp->next;
3247         }
3248         return NULL;
3249 }
3250
3251 /*
3252  * The offset for a special static variable is composed of three parts:
3253  * a bit that indicates the type of static data (0:thread, 1:context),
3254  * an index in the array of chunks of memory for the thread (thread->static_data)
3255  * and an offset in that chunk of mem. This allows allocating less memory in the 
3256  * common case.
3257  */
3258
3259 guint32
3260 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3261 {
3262         guint32 offset;
3263         if (static_type == SPECIAL_STATIC_THREAD)
3264         {
3265                 MonoThreadDomainTls *item;
3266                 mono_threads_lock ();
3267                 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3268                 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3269                 if (item) {
3270                         offset = item->offset;
3271                         g_free (item);
3272                 } else {
3273                         offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3274                 }
3275                 /* This can be called during startup */
3276                 if (threads != NULL)
3277                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3278                 mono_threads_unlock ();
3279         }
3280         else
3281         {
3282                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3283                 mono_contexts_lock ();
3284                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3285                 mono_contexts_unlock ();
3286                 offset |= 0x80000000;   /* Set the high bit to indicate context static data */
3287         }
3288         return offset;
3289 }
3290
3291 gpointer
3292 mono_get_special_static_data (guint32 offset)
3293 {
3294         /* The high bit means either thread (0) or static (1) data. */
3295
3296         guint32 static_type = (offset & 0x80000000);
3297         int idx;
3298
3299         offset &= 0x7fffffff;
3300         idx = (offset >> 24) - 1;
3301
3302         if (static_type == 0)
3303         {
3304                 MonoThread *thread = mono_thread_current ();
3305                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3306         }
3307         else
3308         {
3309                 /* Allocate static data block under demand, since we don't have a list
3310                 // of contexts
3311                 */
3312                 MonoAppContext *context = mono_context_get ();
3313                 if (!context->static_data || !context->static_data [idx]) {
3314                         mono_contexts_lock ();
3315                         mono_alloc_static_data (&(context->static_data), offset);
3316                         mono_contexts_unlock ();
3317                 }
3318                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
3319         }
3320 }
3321
3322 typedef struct {
3323         guint32 offset;
3324         guint32 size;
3325 } TlsOffsetSize;
3326
3327 static void 
3328 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3329 {
3330         MonoThread *thread = value;
3331         TlsOffsetSize *data = user;
3332         int idx = (data->offset >> 24) - 1;
3333         char *ptr;
3334
3335         if (!thread->static_data || !thread->static_data [idx])
3336                 return;
3337         ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3338         memset (ptr, 0, data->size);
3339 }
3340
3341 static void
3342 do_free_special (gpointer key, gpointer value, gpointer data)
3343 {
3344         MonoClassField *field = key;
3345         guint32 offset = GPOINTER_TO_UINT (value);
3346         guint32 static_type = (offset & 0x80000000);
3347         gint32 align;
3348         guint32 size;
3349         size = mono_type_size (field->type, &align);
3350         /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3351         if (static_type == 0) {
3352                 TlsOffsetSize data;
3353                 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3354                 data.offset = offset & 0x7fffffff;
3355                 data.size = size;
3356                 if (threads != NULL)
3357                         mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3358                 item->offset = offset;
3359                 item->size = size;
3360                 item->next = thread_static_info.freelist;
3361                 thread_static_info.freelist = item;
3362         } else {
3363                 /* FIXME: free context static data as well */
3364         }
3365 }
3366
3367 void
3368 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3369 {
3370         mono_threads_lock ();
3371         g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3372         mono_threads_unlock ();
3373 }
3374
3375 static MonoClassField *local_slots = NULL;
3376
3377 typedef struct {
3378         /* local tls data to get locals_slot from a thread */
3379         guint32 offset;
3380         int idx;
3381         /* index in the locals_slot array */
3382         int slot;
3383 } LocalSlotID;
3384
3385 static void
3386 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3387 {
3388         LocalSlotID *sid = user_data;
3389         MonoThread *thread = (MonoThread*)value;
3390         MonoArray *slots_array;
3391         /*
3392          * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3393          * it is for the right domain, so we need to check if it is allocated an initialized
3394          * for the current thread.
3395          */
3396         /*g_print ("handling thread %p\n", thread);*/
3397         if (!thread->static_data || !thread->static_data [sid->idx])
3398                 return;
3399         slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3400         if (!slots_array || sid->slot >= mono_array_length (slots_array))
3401                 return;
3402         mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3403 }
3404
3405 void
3406 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3407 {
3408         MonoDomain *domain;
3409         LocalSlotID sid;
3410         sid.slot = slot;
3411         if (thread_local) {
3412                 void *addr = NULL;
3413                 if (!local_slots) {
3414                         local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3415                         if (!local_slots) {
3416                                 g_warning ("local_slots field not found in Thread class");
3417                                 return;
3418                         }
3419                 }
3420                 domain = mono_domain_get ();
3421                 mono_domain_lock (domain);
3422                 if (domain->special_static_fields)
3423                         addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3424                 mono_domain_unlock (domain);
3425                 if (!addr)
3426                         return;
3427                 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3428                 sid.offset = GPOINTER_TO_UINT (addr);
3429                 sid.offset &= 0x7fffffff;
3430                 sid.idx = (sid.offset >> 24) - 1;
3431                 mono_threads_lock ();
3432                 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3433                 mono_threads_unlock ();
3434         } else {
3435                 /* FIXME: clear the slot for MonoAppContexts, too */
3436         }
3437 }
3438
3439 #ifdef PLATFORM_WIN32
3440 static void CALLBACK dummy_apc (ULONG_PTR param)
3441 {
3442 }
3443 #else
3444 static guint32 dummy_apc (gpointer param)
3445 {
3446         return 0;
3447 }
3448 #endif
3449
3450 /*
3451  * mono_thread_execute_interruption
3452  * 
3453  * Performs the operation that the requested thread state requires (abort,
3454  * suspend or stop)
3455  */
3456 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3457 {
3458         ensure_synch_cs_set (thread);
3459         
3460         EnterCriticalSection (thread->synch_cs);
3461
3462         if (thread->interruption_requested) {
3463                 /* this will consume pending APC calls */
3464                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3465                 InterlockedDecrement (&thread_interruption_requested);
3466                 thread->interruption_requested = FALSE;
3467         }
3468
3469         if ((thread->state & ThreadState_AbortRequested) != 0) {
3470                 if (thread->abort_exc == NULL)
3471                         MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3472                 LeaveCriticalSection (thread->synch_cs);
3473                 return thread->abort_exc;
3474         }
3475         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3476                 thread->state &= ~ThreadState_SuspendRequested;
3477                 thread->state |= ThreadState_Suspended;
3478                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3479                 if (thread->suspend_event == NULL) {
3480                         LeaveCriticalSection (thread->synch_cs);
3481                         return(NULL);
3482                 }
3483                 if (thread->suspended_event)
3484                         SetEvent (thread->suspended_event);
3485
3486                 LeaveCriticalSection (thread->synch_cs);
3487
3488                 if (shutting_down) {
3489                         /* After we left the lock, the runtime might shut down so everything becomes invalid */
3490                         for (;;)
3491                                 Sleep (1000);
3492                 }
3493                 
3494                 WaitForSingleObject (thread->suspend_event, INFINITE);
3495                 
3496                 EnterCriticalSection (thread->synch_cs);
3497
3498                 CloseHandle (thread->suspend_event);
3499                 thread->suspend_event = NULL;
3500                 thread->state &= ~ThreadState_Suspended;
3501         
3502                 /* The thread that requested the resume will have replaced this event
3503                  * and will be waiting for it
3504                  */
3505                 SetEvent (thread->resume_event);
3506
3507                 LeaveCriticalSection (thread->synch_cs);
3508                 
3509                 return NULL;
3510         }
3511         else if ((thread->state & ThreadState_StopRequested) != 0) {
3512                 /* FIXME: do this through the JIT? */
3513
3514                 LeaveCriticalSection (thread->synch_cs);
3515                 
3516                 mono_thread_exit ();
3517                 return NULL;
3518         } else if (thread->thread_interrupt_requested) {
3519
3520                 thread->thread_interrupt_requested = FALSE;
3521                 LeaveCriticalSection (thread->synch_cs);
3522                 
3523                 return(mono_get_exception_thread_interrupted ());
3524         }
3525         
3526         LeaveCriticalSection (thread->synch_cs);
3527         
3528         return NULL;
3529 }
3530
3531 /*
3532  * mono_thread_request_interruption
3533  *
3534  * A signal handler can call this method to request the interruption of a
3535  * thread. The result of the interruption will depend on the current state of
3536  * the thread. If the result is an exception that needs to be throw, it is 
3537  * provided as return value.
3538  */
3539 MonoException*
3540 mono_thread_request_interruption (gboolean running_managed)
3541 {
3542         MonoThread *thread = mono_thread_current ();
3543
3544         /* The thread may already be stopping */
3545         if (thread == NULL) 
3546                 return NULL;
3547         
3548         if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3549                 return NULL;
3550
3551         if (!running_managed || is_running_protected_wrapper ()) {
3552                 /* Can't stop while in unmanaged code. Increase the global interruption
3553                    request count. When exiting the unmanaged method the count will be
3554                    checked and the thread will be interrupted. */
3555                 
3556                 InterlockedIncrement (&thread_interruption_requested);
3557
3558                 if (mono_thread_notify_pending_exc_fn && !running_managed)
3559                         /* The JIT will notify the thread about the interruption */
3560                         /* This shouldn't take any locks */
3561                         mono_thread_notify_pending_exc_fn ();
3562
3563                 /* this will awake the thread if it is in WaitForSingleObject 
3564                    or similar */
3565                 /* Our implementation of this function ignores the func argument */
3566                 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3567                 return NULL;
3568         }
3569         else {
3570                 return mono_thread_execute_interruption (thread);
3571         }
3572 }
3573
3574 gboolean mono_thread_interruption_requested ()
3575 {
3576         if (thread_interruption_requested) {
3577                 MonoThread *thread = mono_thread_current ();
3578                 /* The thread may already be stopping */
3579                 if (thread != NULL) 
3580                         return (thread->interruption_requested);
3581         }
3582         return FALSE;
3583 }
3584
3585 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3586 {
3587         MonoThread *thread = mono_thread_current ();
3588
3589         /* The thread may already be stopping */
3590         if (thread == NULL)
3591                 return;
3592
3593         mono_debugger_check_interruption ();
3594
3595         if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3596                 MonoException* exc = mono_thread_execute_interruption (thread);
3597                 if (exc) mono_raise_exception (exc);
3598         }
3599 }
3600
3601 /*
3602  * Performs the interruption of the current thread, if one has been requested,
3603  * and the thread is not running a protected wrapper.
3604  */
3605 void mono_thread_interruption_checkpoint ()
3606 {
3607         mono_thread_interruption_checkpoint_request (FALSE);
3608 }
3609
3610 /*
3611  * Performs the interruption of the current thread, if one has been requested.
3612  */
3613 void mono_thread_force_interruption_checkpoint ()
3614 {
3615         mono_thread_interruption_checkpoint_request (TRUE);
3616 }
3617
3618 /*
3619  * mono_thread_get_and_clear_pending_exception:
3620  *
3621  *   Return any pending exceptions for the current thread and clear it as a side effect.
3622  */
3623 MonoException*
3624 mono_thread_get_and_clear_pending_exception (void)
3625 {
3626         MonoThread *thread = mono_thread_current ();
3627
3628         /* The thread may already be stopping */
3629         if (thread == NULL)
3630                 return NULL;
3631
3632         if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3633                 return mono_thread_execute_interruption (thread);
3634         }
3635         
3636         if (thread->pending_exception) {
3637                 MonoException *exc = thread->pending_exception;
3638
3639                 thread->pending_exception = NULL;
3640                 return exc;
3641         }
3642
3643         return NULL;
3644 }
3645
3646 /*
3647  * mono_set_pending_exception:
3648  *
3649  *   Set the pending exception of the current thread to EXC. On platforms which 
3650  * support it, the exception will be thrown when execution returns to managed code. 
3651  * On other platforms, this function is equivalent to mono_raise_exception (). 
3652  * Internal calls which report exceptions using this function instead of 
3653  * raise_exception () might be called by JITted code using a more efficient calling 
3654  * convention.
3655  */
3656 void
3657 mono_set_pending_exception (MonoException *exc)
3658 {
3659         MonoThread *thread = mono_thread_current ();
3660
3661         /* The thread may already be stopping */
3662         if (thread == NULL)
3663                 return;
3664
3665         if (mono_thread_notify_pending_exc_fn) {
3666                 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3667
3668                 mono_thread_notify_pending_exc_fn ();
3669         } else {
3670                 /* No way to notify the JIT about the exception, have to throw it now */
3671                 mono_raise_exception (exc);
3672         }
3673 }
3674
3675 /**
3676  * mono_thread_interruption_request_flag:
3677  *
3678  * Returns the address of a flag that will be non-zero if an interruption has
3679  * been requested for a thread. The thread to interrupt may not be the current
3680  * thread, so an additional call to mono_thread_interruption_requested() or
3681  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3682  * zero.
3683  */
3684 gint32* mono_thread_interruption_request_flag ()
3685 {
3686         return &thread_interruption_requested;
3687 }
3688
3689 void 
3690 mono_thread_init_apartment_state (void)
3691 {
3692         MonoThread* thread;
3693         thread = mono_thread_current ();
3694
3695 #ifdef PLATFORM_WIN32
3696         /* Positive return value indicates success, either
3697          * S_OK if this is first CoInitialize call, or
3698          * S_FALSE if CoInitialize already called, but with same
3699          * threading model. A negative value indicates failure,
3700          * probably due to trying to change the threading model.
3701          */
3702         if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA) 
3703                         ? COINIT_APARTMENTTHREADED 
3704                         : COINIT_MULTITHREADED) < 0) {
3705                 thread->apartment_state = ThreadApartmentState_Unknown;
3706         }
3707 #endif
3708 }
3709
3710 void 
3711 mono_thread_cleanup_apartment_state (void)
3712 {
3713 #ifdef PLATFORM_WIN32
3714         MonoThread* thread;
3715         thread = mono_thread_current ();
3716
3717         if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3718                 CoUninitialize ();
3719         }
3720 #endif
3721 }
3722
3723 void
3724 mono_thread_set_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 void
3734 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3735 {
3736         ensure_synch_cs_set (thread);
3737         
3738         EnterCriticalSection (thread->synch_cs);
3739         thread->state &= ~state;
3740         LeaveCriticalSection (thread->synch_cs);
3741 }
3742
3743 gboolean
3744 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3745 {
3746         gboolean ret = FALSE;
3747
3748         ensure_synch_cs_set (thread);
3749         
3750         EnterCriticalSection (thread->synch_cs);
3751
3752         if ((thread->state & test) != 0) {
3753                 ret = TRUE;
3754         }
3755         
3756         LeaveCriticalSection (thread->synch_cs);
3757         
3758         return ret;
3759 }