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