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