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