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