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