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