2004-06-23 Martin Baulig <martin@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 || ret == WAIT_IO_COMPLETION) {
709                 /* Do we want to try again if we get
710                  * WAIT_IO_COMPLETION? The documentation for
711                  * WaitHandle doesn't give any clues.  (We'd have to
712                  * fiddle with the timeout if we retry.)
713                  */
714 #ifdef THREAD_WAIT_DEBUG
715                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
716                           GetCurrentThreadId ());
717 #endif
718                 return(FALSE);
719         }
720         
721         return(TRUE);
722 }
723
724 /* FIXME: exitContext isnt documented */
725 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
726 {
727         HANDLE *handles;
728         guint32 numhandles;
729         guint32 ret;
730         guint32 i;
731         MonoObject *waitHandle;
732         MonoClass *klass;
733                 
734         MONO_ARCH_SAVE_REGS;
735
736         numhandles = mono_array_length(mono_handles);
737         handles = g_new0(HANDLE, numhandles);
738
739         if (wait_handle_os_handle_field == 0) {
740                 /* Get the field os_handle which will contain the actual handle */
741                 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");   
742                 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
743         }
744                 
745         for(i = 0; i < numhandles; i++) {       
746                 waitHandle = mono_array_get(mono_handles, MonoObject*, i);              
747                 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
748         }
749         
750         if(ms== -1) {
751                 ms=INFINITE;
752         }
753
754         ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
755
756         g_free(handles);
757
758 #ifdef THREAD_WAIT_DEBUG
759         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
760                   GetCurrentThreadId (), ret);
761 #endif
762
763         /*
764          * These need to be here.  See MSDN dos on WaitForMultipleObjects.
765          */
766         if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
767                 return ret - WAIT_OBJECT_0;
768         }
769         else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
770                 return ret - WAIT_ABANDONED_0;
771         }
772         else {
773                 return ret;
774         }
775 }
776
777 /* FIXME: exitContext isnt documented */
778 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
779 {
780         guint32 ret;
781         
782         MONO_ARCH_SAVE_REGS;
783
784 #ifdef THREAD_WAIT_DEBUG
785         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
786                   GetCurrentThreadId (), handle, ms);
787 #endif
788         
789         if(ms== -1) {
790                 ms=INFINITE;
791         }
792         
793         ret=WaitForSingleObjectEx (handle, ms, TRUE);
794
795         if(ret==WAIT_FAILED) {
796 #ifdef THREAD_WAIT_DEBUG
797                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
798                           GetCurrentThreadId ());
799 #endif
800                 return(FALSE);
801         } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
802                 /* Do we want to try again if we get
803                  * WAIT_IO_COMPLETION? The documentation for
804                  * WaitHandle doesn't give any clues.  (We'd have to
805                  * fiddle with the timeout if we retry.)
806                  */
807 #ifdef THREAD_WAIT_DEBUG
808                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
809                           GetCurrentThreadId ());
810 #endif
811                 return(FALSE);
812         }
813         
814         return(TRUE);
815 }
816
817 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name)
818
819         MONO_ARCH_SAVE_REGS;
820    
821         return(CreateMutex (NULL, owned,
822                             name==NULL?NULL:mono_string_chars (name)));
823 }                                                                   
824
825 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) { 
826         MONO_ARCH_SAVE_REGS;
827
828         ReleaseMutex(handle);
829 }
830
831 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
832         MONO_ARCH_SAVE_REGS;
833
834         return(CreateEvent (NULL, manual, initial,
835                             name==NULL?NULL:mono_string_chars (name)));
836 }
837
838 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
839         MONO_ARCH_SAVE_REGS;
840
841         return (SetEvent(handle));
842 }
843
844 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
845         MONO_ARCH_SAVE_REGS;
846
847         return (ResetEvent(handle));
848 }
849
850 void
851 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
852         MONO_ARCH_SAVE_REGS;
853
854         CloseHandle (handle);
855 }
856
857 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
858 {
859         MONO_ARCH_SAVE_REGS;
860
861         return InterlockedIncrement (location);
862 }
863
864 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
865 {
866         gint32 lowret;
867         gint32 highret;
868
869         MONO_ARCH_SAVE_REGS;
870
871         EnterCriticalSection(&interlocked_mutex);
872
873         lowret = InterlockedIncrement((gint32 *) location);
874         if (0 == lowret)
875                 highret = InterlockedIncrement((gint32 *) location + 1);
876         else
877                 highret = *((gint32 *) location + 1);
878
879         LeaveCriticalSection(&interlocked_mutex);
880
881         return (gint64) highret << 32 | (gint64) lowret;
882 }
883
884 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
885 {
886         MONO_ARCH_SAVE_REGS;
887
888         return InterlockedDecrement(location);
889 }
890
891 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
892 {
893         gint32 lowret;
894         gint32 highret;
895
896         MONO_ARCH_SAVE_REGS;
897
898         EnterCriticalSection(&interlocked_mutex);
899
900         lowret = InterlockedDecrement((gint32 *) location);
901         if (-1 == lowret)
902                 highret = InterlockedDecrement((gint32 *) location + 1);
903         else
904                 highret = *((gint32 *) location + 1);
905
906         LeaveCriticalSection(&interlocked_mutex);
907
908         return (gint64) highret << 32 | (gint64) lowret;
909 }
910
911 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
912 {
913         MONO_ARCH_SAVE_REGS;
914
915         return InterlockedExchange(location1, value);
916 }
917
918 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
919 {
920         MONO_ARCH_SAVE_REGS;
921
922         return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
923 }
924
925 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
926 {
927         IntFloatUnion val, ret;
928
929         MONO_ARCH_SAVE_REGS;
930
931         val.fval = value;
932         ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
933
934         return ret.fval;
935 }
936
937 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
938 {
939         MONO_ARCH_SAVE_REGS;
940
941         return InterlockedCompareExchange(location1, value, comparand);
942 }
943
944 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
945 {
946         MONO_ARCH_SAVE_REGS;
947
948         return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
949 }
950
951 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
952 {
953         IntFloatUnion val, ret, cmp;
954
955         MONO_ARCH_SAVE_REGS;
956
957         val.fval = value;
958         cmp.fval = comparand;
959         ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
960
961         return ret.fval;
962 }
963
964 int  
965 mono_thread_get_abort_signal (void)
966 {
967 #ifdef __MINGW32__
968         return -1;
969 #else
970 #ifndef SIGRTMIN
971         return SIGUSR1;
972 #else
973         return SIGRTMIN;
974 #endif
975 #endif /* __MINGW32__ */
976 }
977
978 #ifdef __MINGW32__
979 static guint32 interruption_request_apc (gpointer param)
980 {
981         MonoException* exc = mono_thread_request_interruption (FALSE);
982         if (exc) mono_raise_exception (exc);
983         return 0;
984 }
985 #endif /* __MINGW32__ */
986
987 /*
988  * signal_thread_state_change
989  *
990  * Tells the thread that his state has changed and it has to enter the new
991  * state as soon as possible.
992  */
993 static void signal_thread_state_change (MonoThread *thread)
994 {
995 #ifdef __MINGW32__
996         QueueUserAPC (interruption_request_apc, thread->handle, NULL);
997 #else
998         /* fixme: store the state somewhere */
999 #ifdef PTHREAD_POINTER_ID
1000         pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1001 #else
1002         pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1003 #endif
1004 #endif /* __MINGW32__ */
1005 }
1006
1007 void
1008 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1009 {
1010         MONO_ARCH_SAVE_REGS;
1011
1012         mono_monitor_enter (thread->synch_lock);
1013
1014         if ((thread->state & ThreadState_AbortRequested) != 0 || 
1015                 (thread->state & ThreadState_StopRequested) != 0) 
1016         {
1017                 mono_monitor_exit (thread->synch_lock);
1018                 return;
1019         }
1020
1021         thread->state |= ThreadState_AbortRequested;
1022         thread->abort_state = state;
1023         thread->abort_exc = NULL;
1024
1025         mono_monitor_exit (thread->synch_lock);
1026
1027 #ifdef THREAD_DEBUG
1028         g_message (G_GNUC_PRETTY_FUNCTION
1029                    ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1030                    thread, thread->tid);
1031 #endif
1032         
1033         /* Make sure the thread is awake */
1034         ves_icall_System_Threading_Thread_Resume (thread);
1035         
1036         signal_thread_state_change (thread);
1037 }
1038
1039 void
1040 ves_icall_System_Threading_Thread_ResetAbort (void)
1041 {
1042         MonoThread *thread = mono_thread_current ();
1043
1044         MONO_ARCH_SAVE_REGS;
1045         
1046         mono_monitor_enter (thread->synch_lock);
1047         
1048         thread->state &= ~ThreadState_AbortRequested;
1049         
1050         if (!thread->abort_exc) {
1051                 const char *msg = "Unable to reset abort because no abort was requested";
1052                 mono_monitor_exit (thread->synch_lock);
1053                 mono_raise_exception (mono_get_exception_thread_state (msg));
1054         } else {
1055                 thread->abort_exc = NULL;
1056                 thread->abort_state = NULL;
1057         }
1058         
1059         mono_monitor_exit (thread->synch_lock);
1060 }
1061
1062 void
1063 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1064 {
1065         MONO_ARCH_SAVE_REGS;
1066
1067         mono_monitor_enter (thread->synch_lock);
1068
1069         if ((thread->state & ThreadState_Suspended) != 0 || 
1070                 (thread->state & ThreadState_SuspendRequested) != 0 ||
1071                 (thread->state & ThreadState_StopRequested) != 0) 
1072         {
1073                 mono_monitor_exit (thread->synch_lock);
1074                 return;
1075         }
1076         
1077         thread->state |= ThreadState_SuspendRequested;
1078         mono_monitor_exit (thread->synch_lock);
1079
1080         signal_thread_state_change (thread);
1081 }
1082
1083 void
1084 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1085 {
1086         MONO_ARCH_SAVE_REGS;
1087
1088         mono_monitor_enter (thread->synch_lock);
1089
1090         if ((thread->state & ThreadState_SuspendRequested) != 0) {
1091                 thread->state &= ~ThreadState_SuspendRequested;
1092                 mono_monitor_exit (thread->synch_lock);
1093                 return;
1094         }
1095                 
1096         if ((thread->state & ThreadState_Suspended) == 0) 
1097         {
1098                 mono_monitor_exit (thread->synch_lock);
1099                 return;
1100         }
1101         
1102         thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1103         
1104         /* Awake the thread */
1105         SetEvent (thread->suspend_event);
1106
1107         mono_monitor_exit (thread->synch_lock);
1108
1109         /* Wait for the thread to awake */
1110         WaitForSingleObject (thread->resume_event, INFINITE);
1111         CloseHandle (thread->resume_event);
1112         thread->resume_event = NULL;
1113 }
1114
1115 void mono_thread_stop (MonoThread *thread)
1116 {
1117         mono_monitor_enter (thread->synch_lock);
1118
1119         if ((thread->state & ThreadState_StopRequested) != 0 ||
1120                 (thread->state & ThreadState_Stopped) != 0)
1121         {
1122                 mono_monitor_exit (thread->synch_lock);
1123                 return;
1124         }
1125         
1126         /* Make sure the thread is awake */
1127         ves_icall_System_Threading_Thread_Resume (thread);
1128         
1129         thread->state |= ThreadState_StopRequested;
1130         thread->state &= ~ThreadState_AbortRequested;
1131         
1132         mono_monitor_exit (thread->synch_lock);
1133         
1134         signal_thread_state_change (thread);
1135 }
1136
1137 gint8
1138 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1139 {
1140         return *((volatile gint8 *) (ptr));
1141 }
1142
1143 gint16
1144 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1145 {
1146         return *((volatile gint16 *) (ptr));
1147 }
1148
1149 gint32
1150 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1151 {
1152         return *((volatile gint32 *) (ptr));
1153 }
1154
1155 gint64
1156 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1157 {
1158         return *((volatile gint64 *) (ptr));
1159 }
1160
1161 void *
1162 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1163 {
1164         return (void *)  *((volatile void **) ptr);
1165 }
1166
1167 void
1168 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1169 {
1170         *((volatile gint8 *) ptr) = value;
1171 }
1172
1173 void
1174 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1175 {
1176         *((volatile gint16 *) ptr) = value;
1177 }
1178
1179 void
1180 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1181 {
1182         *((volatile gint32 *) ptr) = value;
1183 }
1184
1185 void
1186 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1187 {
1188         *((volatile gint64 *) ptr) = value;
1189 }
1190
1191 void
1192 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1193 {
1194         *((volatile void **) ptr) = value;
1195 }
1196
1197 void mono_thread_init (MonoThreadStartCB start_cb,
1198                        MonoThreadAttachCB attach_cb)
1199 {
1200         InitializeCriticalSection(&threads_mutex);
1201         InitializeCriticalSection(&interlocked_mutex);
1202         InitializeCriticalSection(&contexts_mutex);
1203         InitializeCriticalSection(&interruption_mutex);
1204         
1205         mono_init_static_data_info (&thread_static_info);
1206         mono_init_static_data_info (&context_static_info);
1207
1208         current_object_key=TlsAlloc();
1209 #ifdef THREAD_DEBUG
1210         g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1211                    current_object_key);
1212 #endif
1213
1214         mono_thread_start_cb = start_cb;
1215         mono_thread_attach_cb = attach_cb;
1216
1217         slothash_key=TlsAlloc();
1218
1219         /* Get a pseudo handle to the current process.  This is just a
1220          * kludge so that wapi can build a process handle if needed.
1221          * As a pseudo handle is returned, we don't need to clean
1222          * anything up.
1223          */
1224         GetCurrentProcess ();
1225 }
1226
1227 void
1228 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1229 {
1230         mono_thread_cleanup = func;
1231 }
1232
1233 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1234 {
1235         mono_thread_callbacks = callbacks;
1236 }
1237
1238 #ifdef THREAD_DEBUG
1239 static void print_tids (gpointer key, gpointer value, gpointer user)
1240 {
1241         g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1242 }
1243 #endif
1244
1245 struct wait_data 
1246 {
1247         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1248         MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1249         guint32 num;
1250 };
1251
1252 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1253 {
1254         guint32 i, ret;
1255         
1256 #ifdef THREAD_DEBUG
1257         g_message(G_GNUC_PRETTY_FUNCTION
1258                   ": %d threads to wait for in this batch", wait->num);
1259 #endif
1260
1261         ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1262
1263         if(ret==WAIT_FAILED) {
1264                 /* See the comment in build_wait_tids() */
1265 #ifdef THREAD_DEBUG
1266                 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1267 #endif
1268                 return;
1269         }
1270         
1271
1272         for(i=0; i<wait->num; i++) {
1273                 guint32 tid=wait->threads[i]->tid;
1274                 CloseHandle (wait->handles[i]);
1275                 
1276                 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1277                         /* This thread must have been killed, because
1278                          * it hasn't cleaned itself up. (It's just
1279                          * possible that the thread exited before the
1280                          * parent thread had a chance to store the
1281                          * handle, and now there is another pointer to
1282                          * the already-exited thread stored.  In this
1283                          * case, we'll just get two
1284                          * mono_profiler_thread_end() calls for the
1285                          * same thread.)
1286                          */
1287         
1288 #ifdef THREAD_DEBUG
1289                         g_message (G_GNUC_PRETTY_FUNCTION
1290                                    ": cleaning up after thread %d", tid);
1291 #endif
1292                         thread_cleanup (wait->threads[i]);
1293                 }
1294         }
1295 }
1296
1297 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1298 {
1299         struct wait_data *wait=(struct wait_data *)user;
1300
1301         if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1302                 HANDLE handle;
1303                 MonoThread *thread=(MonoThread *)value;
1304
1305                 /* Ignore background threads, we abort them later */
1306                 if (thread->state & ThreadState_Background)
1307                         return; /* just leave, ignore */
1308                 
1309                 if (mono_gc_is_finalizer_thread (thread))
1310                         return;
1311
1312                 if (thread == mono_thread_current ())
1313                         return;
1314
1315                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1316                 if (handle == NULL)
1317                         return;
1318                 
1319                 wait->handles[wait->num]=handle;
1320                 wait->threads[wait->num]=thread;
1321                 wait->num++;
1322         } else {
1323                 /* Just ignore the rest, we can't do anything with
1324                  * them yet
1325                  */
1326         }
1327 }
1328
1329 static gboolean
1330 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1331 {
1332         struct wait_data *wait=(struct wait_data *)user;
1333         guint32 self = GetCurrentThreadId ();
1334         MonoThread *thread = (MonoThread *) value;
1335         HANDLE handle;
1336
1337         /* The finalizer thread is not a background thread */
1338         if (thread->tid != self && thread->state & ThreadState_Background) {
1339         
1340                 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1341                 if (handle == NULL)
1342                         return FALSE;
1343                 
1344                 wait->handles[wait->num]=thread->handle;
1345                 wait->threads[wait->num]=thread;
1346                 wait->num++;
1347         
1348                 if(thread->state & ThreadState_AbortRequested ||
1349                    thread->state & ThreadState_Aborted) {
1350 #ifdef THREAD_DEBUG
1351                         g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1352 #endif
1353                         return(TRUE);
1354                 }
1355                 
1356 #ifdef THREAD_DEBUG
1357                 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1358 #endif
1359                 mono_thread_stop (thread);
1360                 return TRUE;
1361         }
1362
1363         return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
1364 }
1365
1366 void mono_thread_manage (void)
1367 {
1368         struct wait_data *wait=g_new0 (struct wait_data, 1);
1369         
1370         /* join each thread that's still running */
1371 #ifdef THREAD_DEBUG
1372         g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1373 #endif
1374         
1375         EnterCriticalSection (&threads_mutex);
1376         if(threads==NULL) {
1377 #ifdef THREAD_DEBUG
1378                 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1379 #endif
1380                 LeaveCriticalSection (&threads_mutex);
1381                 return;
1382         }
1383         LeaveCriticalSection (&threads_mutex);
1384         
1385         do {
1386                 EnterCriticalSection (&threads_mutex);
1387 #ifdef THREAD_DEBUG
1388                 g_message(G_GNUC_PRETTY_FUNCTION
1389                           ":There are %d threads to join",
1390                           mono_g_hash_table_size (threads));
1391                 mono_g_hash_table_foreach (threads, print_tids, NULL);
1392 #endif
1393         
1394                 wait->num=0;
1395                 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1396                 LeaveCriticalSection (&threads_mutex);
1397                 if(wait->num>0) {
1398                         /* Something to wait for */
1399                         wait_for_tids (wait, INFINITE);
1400                 }
1401         } while(wait->num>0);
1402         
1403         mono_thread_pool_cleanup ();
1404
1405         EnterCriticalSection(&threads_mutex);
1406
1407         /* 
1408          * Remove everything but the finalizer thread and self.
1409          * Also abort all the background threads
1410          * */
1411         wait->num = 0;
1412         mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1413
1414         LeaveCriticalSection(&threads_mutex);
1415
1416         if(wait->num>0) {
1417                 /* Something to wait for */
1418                 wait_for_tids (wait, INFINITE);
1419         }
1420
1421         g_free (wait);
1422 }
1423
1424 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1425 {
1426         MonoThread *thread=(MonoThread *)value;
1427         guint32 self=GPOINTER_TO_UINT (user);
1428         
1429         if(thread->tid!=self) {
1430                 /*TerminateThread (thread->handle, -1);*/
1431         }
1432 }
1433
1434 void mono_thread_abort_all_other_threads (void)
1435 {
1436         guint32 self=GetCurrentThreadId ();
1437
1438         EnterCriticalSection (&threads_mutex);
1439 #ifdef THREAD_DEBUG
1440         g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1441                   mono_g_hash_table_size (threads));
1442         mono_g_hash_table_foreach (threads, print_tids, NULL);
1443 #endif
1444
1445         mono_g_hash_table_foreach (threads, terminate_thread,
1446                                    GUINT_TO_POINTER (self));
1447         
1448         LeaveCriticalSection (&threads_mutex);
1449 }
1450
1451 /*
1452  * mono_thread_push_appdomain_ref:
1453  *
1454  *   Register that the current thread may have references to objects in domain 
1455  * @domain on its stack. Each call to this function should be paired with a 
1456  * call to pop_appdomain_ref.
1457  */
1458 void 
1459 mono_thread_push_appdomain_ref (MonoDomain *domain)
1460 {
1461         MonoThread *thread = mono_thread_current ();
1462
1463         if (thread) {
1464                 //printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name);
1465                 EnterCriticalSection (&threads_mutex);
1466                 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1467                 LeaveCriticalSection (&threads_mutex);
1468         }
1469 }
1470
1471 void
1472 mono_thread_pop_appdomain_ref (void)
1473 {
1474         MonoThread *thread = mono_thread_current ();
1475
1476         if (thread) {
1477                 //printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name);
1478                 EnterCriticalSection (&threads_mutex);
1479                 // FIXME: How can the list be empty ?
1480                 if (thread->appdomain_refs)
1481                         thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1482                 LeaveCriticalSection (&threads_mutex);
1483         }
1484 }
1485
1486 static gboolean
1487 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1488 {
1489         gboolean res;
1490         EnterCriticalSection (&threads_mutex);
1491         res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1492         LeaveCriticalSection (&threads_mutex);
1493         return res;
1494 }
1495
1496 typedef struct abort_appdomain_data {
1497         struct wait_data wait;
1498         MonoDomain *domain;
1499 } abort_appdomain_data;
1500
1501 static void
1502 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1503 {
1504         MonoThread *thread = (MonoThread*)value;
1505         abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1506         MonoDomain *domain = data->domain;
1507
1508         if (mono_thread_has_appdomain_ref (thread, domain)) {
1509                 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
1510                 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1511
1512                 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1513                         data->wait.handles [data->wait.num] = thread->handle;
1514                         data->wait.threads [data->wait.num] = thread;
1515                         data->wait.num++;
1516                 } else {
1517                         /* Just ignore the rest, we can't do anything with
1518                          * them yet
1519                          */
1520                 }
1521         }
1522 }
1523
1524 /*
1525  * mono_threads_abort_appdomain_threads:
1526  *
1527  *   Abort threads which has references to the given appdomain.
1528  */
1529 gboolean
1530 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1531 {
1532         abort_appdomain_data user_data;
1533         guint32 start_time;
1534
1535         /* printf ("ABORT BEGIN.\n"); */
1536
1537         start_time = GetTickCount ();
1538         do {
1539                 EnterCriticalSection (&threads_mutex);
1540
1541                 user_data.domain = domain;
1542                 user_data.wait.num = 0;
1543                 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1544                 LeaveCriticalSection (&threads_mutex);
1545
1546                 if (user_data.wait.num > 0)
1547                         wait_for_tids (&user_data.wait, timeout);
1548
1549                 /* Update remaining time */
1550                 timeout -= GetTickCount () - start_time;
1551                 start_time = GetTickCount ();
1552
1553                 if (timeout < 0)
1554                         return FALSE;
1555         }
1556         while (user_data.wait.num > 0);
1557
1558         /* printf ("ABORT DONE.\n"); */
1559
1560         return TRUE;
1561 }
1562
1563 /*
1564  * mono_thread_get_pending_exception:
1565  *
1566  *   Return an exception which needs to be raised when leaving a catch clause.
1567  * This is used for undeniable exception propagation.
1568  */
1569 MonoException*
1570 mono_thread_get_pending_exception (void)
1571 {
1572         MonoThread *thread = mono_thread_current ();
1573
1574         MONO_ARCH_SAVE_REGS;
1575
1576         if (thread && thread->abort_exc) {
1577                 /*
1578                  * FIXME: Clear the abort exception and return an AppDomainUnloaded 
1579                  * exception if the thread no longer references a dying appdomain.
1580                  */
1581                 thread->abort_exc->trace_ips = NULL;
1582                 thread->abort_exc->stack_trace = NULL;
1583                 return thread->abort_exc;
1584         }
1585
1586         return NULL;
1587 }
1588
1589 #define NUM_STATIC_DATA_IDX 8
1590 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1591         1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1592 };
1593
1594
1595 /*
1596  *  mono_alloc_static_data
1597  *
1598  *   Allocate memory blocks for storing threads or context static data
1599  */
1600 static void 
1601 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1602 {
1603         guint idx = (offset >> 24) - 1;
1604         int i;
1605
1606         gpointer* static_data = *static_data_ptr;
1607         if (!static_data) {
1608 #if HAVE_BOEHM_GC
1609                 static_data = GC_MALLOC (static_data_size [0]);
1610 #else
1611                 static_data = g_malloc0 (static_data_size [0]);
1612 #endif
1613                 *static_data_ptr = static_data;
1614                 static_data [0] = static_data;
1615         }
1616         
1617         for (i = 1; i < idx; ++i) {
1618                 if (static_data [i])
1619                         continue;
1620 #if HAVE_BOEHM_GC
1621                 static_data [i] = GC_MALLOC (static_data_size [i]);
1622 #else
1623                 static_data [i] = g_malloc0 (static_data_size [i]);
1624 #endif
1625         }
1626 }
1627
1628 /*
1629  *  mono_init_static_data_info
1630  *
1631  *   Initializes static data counters
1632  */
1633 static void mono_init_static_data_info (StaticDataInfo *static_data)
1634 {
1635         static_data->idx = 0;
1636         static_data->offset = 0;
1637 }
1638
1639 /*
1640  *  mono_alloc_static_data_slot
1641  *
1642  *   Generates an offset for static data. static_data contains the counters
1643  *  used to generate it.
1644  */
1645 static guint32
1646 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1647 {
1648         guint32 offset;
1649
1650         if (!static_data->idx && !static_data->offset) {
1651                 /* 
1652                  * we use the first chunk of the first allocation also as
1653                  * an array for the rest of the data 
1654                  */
1655                 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1656         }
1657         static_data->offset += align - 1;
1658         static_data->offset &= ~(align - 1);
1659         if (static_data->offset + size >= static_data_size [static_data->idx]) {
1660                 static_data->idx ++;
1661                 g_assert (size <= static_data_size [static_data->idx]);
1662                 /* 
1663                  * massive unloading and reloading of domains with thread-static
1664                  * data may eventually exceed the allocated storage...
1665                  * Need to check what the MS runtime does in that case.
1666                  * Note that for each appdomain, we need to allocate a separate
1667                  * thread data slot for security reasons. We could keep track
1668                  * of the slots per-domain and when the domain is unloaded
1669                  * out the slots on a sort of free list.
1670                  */
1671                 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1672                 static_data->offset = 0;
1673         }
1674         offset = static_data->offset | ((static_data->idx + 1) << 24);
1675         static_data->offset += size;
1676         return offset;
1677 }
1678
1679 /* 
1680  * ensure thread static fields already allocated are valid for thread
1681  * This function is called when a thread is created or on thread attach.
1682  */
1683 static void
1684 thread_adjust_static_data (MonoThread *thread)
1685 {
1686         guint32 offset;
1687
1688         EnterCriticalSection (&threads_mutex);
1689         if (thread_static_info.offset || thread_static_info.idx > 0) {
1690                 /* get the current allocated size */
1691                 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1692                 mono_alloc_static_data (&(thread->static_data), offset);
1693         }
1694         LeaveCriticalSection (&threads_mutex);
1695 }
1696
1697 static void 
1698 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1699 {
1700         MonoThread *thread = value;
1701         guint32 offset = GPOINTER_TO_UINT (user);
1702         
1703         mono_alloc_static_data (&(thread->static_data), offset);
1704 }
1705
1706 /*
1707  * The offset for a special static variable is composed of three parts:
1708  * a bit that indicates the type of static data (0:thread, 1:context),
1709  * an index in the array of chunks of memory for the thread (thread->static_data)
1710  * and an offset in that chunk of mem. This allows allocating less memory in the 
1711  * common case.
1712  */
1713
1714 guint32
1715 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
1716 {
1717         guint32 offset;
1718         if (static_type == SPECIAL_STATIC_THREAD)
1719         {
1720                 EnterCriticalSection (&threads_mutex);
1721                 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
1722                 /* This can be called during startup */
1723                 if (threads != NULL)
1724                         mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
1725                 LeaveCriticalSection (&threads_mutex);
1726         }
1727         else
1728         {
1729                 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
1730                 EnterCriticalSection (&contexts_mutex);
1731                 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
1732                 LeaveCriticalSection (&contexts_mutex);
1733                 offset |= 0x80000000;   // Set the high bit to indicate context static data
1734         }
1735         return offset;
1736 }
1737
1738 gpointer
1739 mono_get_special_static_data (guint32 offset)
1740 {
1741         // The high bit means either thread (0) or static (1) data.
1742
1743         guint32 static_type = (offset & 0x80000000);
1744         int idx;
1745
1746         offset &= 0x7fffffff;
1747         idx = (offset >> 24) - 1;
1748
1749         if (static_type == 0)
1750         {
1751                 MonoThread *thread = mono_thread_current ();
1752                 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
1753         }
1754         else
1755         {
1756                 // Allocate static data block under demand, since we don't have a list
1757                 // of contexts
1758                 MonoAppContext *context = mono_context_get ();
1759                 if (!context->static_data || !context->static_data [idx]) {
1760                         EnterCriticalSection (&contexts_mutex);
1761                         mono_alloc_static_data (&(context->static_data), offset);
1762                         LeaveCriticalSection (&contexts_mutex);
1763                 }
1764                 return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
1765         }
1766 }
1767
1768 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
1769 {
1770         MonoThread *thread=(MonoThread *)value;
1771         guint32 self=GPOINTER_TO_UINT (user);
1772
1773 #ifdef LIBGC_DEBUG
1774         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1775 #endif
1776         
1777         if(thread->tid==self)
1778                 return;
1779
1780         SuspendThread (thread->handle);
1781 }
1782
1783 void mono_gc_stop_world (void)
1784 {
1785         guint32 self=GetCurrentThreadId ();
1786
1787 #ifdef LIBGC_DEBUG
1788         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1789 #endif
1790
1791         EnterCriticalSection (&threads_mutex);
1792
1793         if (threads != NULL)
1794                 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
1795         
1796         LeaveCriticalSection (&threads_mutex);
1797 }
1798
1799 static void gc_start_world (gpointer key, gpointer value, gpointer user)
1800 {
1801         MonoThread *thread=(MonoThread *)value;
1802         guint32 self=GPOINTER_TO_UINT (user);
1803         
1804 #ifdef LIBGC_DEBUG
1805         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
1806 #endif
1807         
1808         if(thread->tid==self)
1809                 return;
1810
1811         ResumeThread (thread->handle);
1812 }
1813
1814 void mono_gc_start_world (void)
1815 {
1816         guint32 self=GetCurrentThreadId ();
1817
1818 #ifdef LIBGC_DEBUG
1819         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
1820 #endif
1821
1822         EnterCriticalSection (&threads_mutex);
1823
1824         if (threads != NULL)
1825                 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
1826         
1827         LeaveCriticalSection (&threads_mutex);
1828 }
1829
1830
1831 static guint32 dummy_apc (gpointer param)
1832 {
1833         return 0;
1834 }
1835
1836 /*
1837  * mono_thread_execute_interruption
1838  * 
1839  * Performs the operation that the requested thread state requires (abort,
1840  * suspend or stop)
1841  */
1842 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
1843 {
1844         mono_monitor_enter (thread->synch_lock);
1845         
1846         if (thread->interruption_requested) {
1847                 /* this will consume pending APC calls */
1848                 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
1849                 EnterCriticalSection (&interruption_mutex);
1850                 thread_interruption_requested--;
1851                 LeaveCriticalSection (&interruption_mutex);
1852                 thread->interruption_requested = FALSE;
1853         }
1854
1855         if ((thread->state & ThreadState_AbortRequested) != 0) {
1856                 thread->abort_exc = mono_get_exception_thread_abort ();
1857                 mono_monitor_exit (thread->synch_lock);
1858                 return thread->abort_exc;
1859         }
1860         else if ((thread->state & ThreadState_SuspendRequested) != 0) {
1861                 thread->state &= ~ThreadState_SuspendRequested;
1862                 thread->state |= ThreadState_Suspended;
1863                 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1864                 mono_monitor_exit (thread->synch_lock);
1865                 
1866                 WaitForSingleObject (thread->suspend_event, INFINITE);
1867                 
1868                 mono_monitor_enter (thread->synch_lock);
1869                 CloseHandle (thread->suspend_event);
1870                 thread->suspend_event = NULL;
1871                 thread->state &= ~ThreadState_Suspended;
1872         
1873                 /* The thread that requested the resume will have replaced this event
1874              * and will be waiting for it
1875                  */
1876                 SetEvent (thread->resume_event);
1877                 mono_monitor_exit (thread->synch_lock);
1878                 return NULL;
1879         }
1880         else if ((thread->state & ThreadState_StopRequested) != 0) {
1881                 /* FIXME: do this through the JIT? */
1882                 mono_monitor_exit (thread->synch_lock);
1883                 ExitThread (-1);
1884                 return NULL;
1885         }
1886         
1887         mono_monitor_exit (thread->synch_lock);
1888         return NULL;
1889 }
1890
1891 /*
1892  * mono_thread_request_interruption
1893  *
1894  * A signal handler can call this method to request the interruption of a
1895  * thread. The result of the interruption will depend on the current state of
1896  * the thread. If the result is an exception that needs to be throw, it is 
1897  * provided as return value.
1898  */
1899 MonoException* mono_thread_request_interruption (gboolean running_managed)
1900 {
1901         MonoThread *thread = mono_thread_current ();
1902
1903         /* The thread may already be stopping */
1904         if (thread == NULL) 
1905                 return NULL;
1906         
1907         mono_monitor_enter (thread->synch_lock);
1908         
1909         if (thread->interruption_requested) {
1910                 mono_monitor_exit (thread->synch_lock);
1911                 return NULL;
1912         }
1913
1914         if (!running_managed) {
1915                 /* Can't stop while in unmanaged code. Increase the global interruption
1916                    request count. When exiting the unmanaged method the count will be
1917                    checked and the thread will be interrupted. */
1918                 
1919                 EnterCriticalSection (&interruption_mutex);
1920                 thread_interruption_requested++;
1921                 LeaveCriticalSection (&interruption_mutex);
1922                 
1923                 thread->interruption_requested = TRUE;
1924                 mono_monitor_exit (thread->synch_lock);
1925                 
1926                 /* this will awake the thread if it is in WaitForSingleObject 
1927                or similar */
1928                 QueueUserAPC (dummy_apc, thread->handle, NULL);
1929                 
1930                 return NULL;
1931         }
1932         else {
1933                 mono_monitor_exit (thread->synch_lock);
1934                 return mono_thread_execute_interruption (thread);
1935         }
1936 }
1937
1938 gboolean mono_thread_interruption_requested ()
1939 {
1940         if (thread_interruption_requested) {
1941                 MonoThread *thread = mono_thread_current ();
1942                 /* The thread may already be stopping */
1943                 if (thread != NULL) 
1944                         return (thread->interruption_requested);
1945         }
1946         return FALSE;
1947 }
1948
1949 /*
1950  * Performs the interruption of the current thread, if one has been requested.
1951  */
1952 void mono_thread_interruption_checkpoint ()
1953 {
1954         MonoThread *thread = mono_thread_current ();
1955         
1956         /* The thread may already be stopping */
1957         if (thread == NULL) 
1958                 return;
1959         
1960         if (thread->interruption_requested) {
1961                 MonoException* exc = mono_thread_execute_interruption (thread);
1962                 if (exc) mono_raise_exception (exc);
1963         }
1964 }
1965
1966 /*
1967  * Returns the address of a flag that will be non-zero if an interruption has
1968  * been requested for a thread. The thread to interrupt may not be the current
1969  * thread, so an additional call to mono_thread_interruption_requested() or
1970  * mono_thread_interruption_checkpoint() is allways needed if the flag is not
1971  * zero.
1972  */
1973 gint32* mono_thread_interruption_request_flag ()
1974 {
1975         return &thread_interruption_requested;
1976 }
1977
1978 #ifdef WITH_INCLUDED_LIBGC
1979
1980 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
1981 {
1982         MonoThread *thread=(MonoThread *)value;
1983         guint32 *selfp=(guint32 *)user, self = *selfp;
1984
1985 #ifdef LIBGC_DEBUG
1986         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
1987 #endif
1988         
1989         if(thread->tid==self) {
1990 #ifdef LIBGC_DEBUG
1991                 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
1992 #endif
1993                 GC_push_all_stack (selfp, thread->stack_ptr);
1994                 return;
1995         }
1996
1997 #ifdef PLATFORM_WIN32
1998         GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
1999 #else
2000         mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2001 #endif
2002 }
2003
2004 void mono_gc_push_all_stacks (void)
2005 {
2006         guint32 self=GetCurrentThreadId ();
2007
2008 #ifdef LIBGC_DEBUG
2009         g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2010 #endif
2011
2012         EnterCriticalSection (&threads_mutex);
2013
2014         if (threads != NULL)
2015                 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2016         
2017         LeaveCriticalSection (&threads_mutex);
2018 }
2019
2020 #endif /* WITH_INCLUDED_LIBGC */