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