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