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