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