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