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