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