2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * (C) 2001 Ximian, Inc.
14 #define _WIN32_WINNT 0x0500
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threadpool.h>
26 #include <mono/metadata/threads-types.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/environment.h>
29 #include <mono/metadata/monitor.h>
30 #include <mono/metadata/gc-internal.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/io-layer/io-layer.h>
33 #include <mono/metadata/object-internals.h>
35 #include <mono/os/gc_wrapper.h>
38 #undef THREAD_WAIT_DEBUG
42 guint32 (*func)(void *);
58 /* Number of cached culture objects in the MonoThread->culture_info array */
59 #define NUM_CACHED_CULTURES 4
62 * The "os_handle" field of the WaitHandle class.
64 static MonoClassField *wait_handle_os_handle_field = NULL;
66 /* Controls access to the 'threads' hash table */
67 static CRITICAL_SECTION threads_mutex;
69 /* Controls access to context static data */
70 static CRITICAL_SECTION contexts_mutex;
72 /* Holds current status of static data heap */
73 static StaticDataInfo thread_static_info;
74 static StaticDataInfo context_static_info;
76 /* The hash of existing threads (key is thread ID) that need joining
79 static MonoGHashTable *threads=NULL;
81 /* The TLS key that holds the MonoObject assigned to each thread */
82 static guint32 current_object_key = -1;
85 /* we need to use both the Tls* functions and __thread because
86 * the gc needs to see all the threads
88 static __thread MonoThread * tls_current_object;
89 #define SET_CURRENT_OBJECT(x) do { \
90 tls_current_object = x; \
91 TlsSetValue (current_object_key, x); \
93 #define GET_CURRENT_OBJECT() tls_current_object
95 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
96 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
99 /* function called at thread start */
100 static MonoThreadStartCB mono_thread_start_cb = NULL;
102 /* function called at thread attach */
103 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
105 /* function called at thread cleanup */
106 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
108 /* function called when a new thread has been created */
109 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
111 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
112 static guint32 slothash_key = -1;
114 /* The default stack size for each thread */
115 static guint32 default_stacksize = 0;
117 static void thread_adjust_static_data (MonoThread *thread);
118 static void mono_init_static_data_info (StaticDataInfo *static_data);
119 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
121 /* Spin lock for InterlockedXXX 64 bit functions */
122 static CRITICAL_SECTION interlocked_mutex;
124 /* Controls access to interruption flag */
125 static CRITICAL_SECTION interruption_mutex;
127 /* global count of thread interruptions requested */
128 static gint32 thread_interruption_requested = 0;
131 mono_thread_get_tls_key (void)
133 return current_object_key;
136 /* handle_store() and handle_remove() manage the array of threads that
137 * still need to be waited for when the main thread exits.
139 static void handle_store(MonoThread *thread)
141 EnterCriticalSection(&threads_mutex);
144 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
149 MONO_GC_REGISTER_ROOT (threads);
150 threads=mono_g_hash_table_new(NULL, NULL);
153 /* We don't need to duplicate thread->handle, because it is
154 * only closed when the thread object is finalized by the GC.
156 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
157 LeaveCriticalSection(&threads_mutex);
160 static void handle_remove(guint32 tid)
163 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
166 EnterCriticalSection(&threads_mutex);
169 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
171 LeaveCriticalSection(&threads_mutex);
173 /* Don't close the handle here, wait for the object finalizer
174 * to do it. Otherwise, the following race condition applies:
176 * 1) Thread exits (and handle_remove() closes the handle)
178 * 2) Some other handle is reassigned the same slot
180 * 3) Another thread tries to join the first thread, and
181 * blocks waiting for the reassigned handle to be signalled
182 * (which might never happen). This is possible, because the
183 * thread calling Join() still has a reference to the first
188 static void thread_cleanup (MonoThread *thread)
190 mono_release_type_locks (thread);
192 if (!mono_monitor_enter (thread->synch_lock))
195 thread->state |= ThreadState_Stopped;
196 mono_monitor_exit (thread->synch_lock);
198 mono_profiler_thread_end (thread->tid);
199 handle_remove (thread->tid);
201 mono_thread_pop_appdomain_ref ();
203 if (thread->serialized_culture_info)
204 g_free (thread->serialized_culture_info);
206 #ifndef HAVE_BOEHM_GC
207 if (thread->culture_info)
208 g_free (thread->culture_info);
209 if (thread->ui_culture_info)
210 g_free (thread->ui_culture_info);
213 if (mono_thread_cleanup)
214 mono_thread_cleanup (thread);
217 static guint32 start_wrapper(void *data)
219 struct StartInfo *start_info=(struct StartInfo *)data;
220 guint32 (*start_func)(void *);
223 MonoThread *thread=start_info->obj;
226 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
227 GetCurrentThreadId ());
230 /* We can be sure start_info->obj->tid and
231 * start_info->obj->handle have been set, because the thread
232 * was created suspended, and these values were set before the
238 SET_CURRENT_OBJECT (thread);
240 if (!mono_domain_set (start_info->domain, FALSE)) {
241 /* No point in raising an appdomain_unloaded exception here */
242 /* FIXME: Cleanup here */
246 start_func = start_info->func;
247 this = start_info->this;
249 /* This MUST be called before any managed code can be
250 * executed, as it calls the callback function that (for the
251 * jit) sets the lmf marker.
253 mono_thread_new_init (tid, &tid, start_func);
254 thread->stack_ptr = &tid;
257 g_message (G_GNUC_PRETTY_FUNCTION
258 ": (%d,%d) Setting thread stack to %p",
259 GetCurrentThreadId (), getpid (), thread->stack_ptr);
263 g_message (G_GNUC_PRETTY_FUNCTION
264 ": (%d) Setting current_object_key to %p",
265 GetCurrentThreadId (), thread);
268 mono_profiler_thread_start (tid);
270 if(thread->start_notify!=NULL) {
271 /* Let the thread that called Start() know we're
274 ReleaseSemaphore (thread->start_notify, 1, NULL);
279 /* Every thread references the appdomain which created it */
280 mono_thread_push_appdomain_ref (mono_domain_get ());
282 thread_adjust_static_data (thread);
284 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
288 #ifdef PLATFORM_WIN32
289 /* If the thread calls ExitThread at all, this remaining code
290 * will not be executed, but the main thread will eventually
291 * call thread_cleanup() on this thread's behalf.
295 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
296 GetCurrentThreadId ());
299 /* Remove the reference to the thread object in the TLS data,
300 * so the thread object can be finalized. This won't be
301 * reached if the thread threw an uncaught exception, so those
302 * thread handles will stay referenced :-( (This is due to
303 * missing support for scanning thread-specific data in the
304 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
307 SET_CURRENT_OBJECT (NULL);
310 thread_cleanup (thread);
315 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
317 if (mono_thread_start_cb) {
318 mono_thread_start_cb (tid, stack_start, func);
321 if (mono_thread_callbacks)
322 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
325 void mono_threads_set_default_stacksize (guint32 stacksize)
327 default_stacksize = stacksize;
330 guint32 mono_threads_get_default_stacksize (void)
332 return default_stacksize;
335 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
338 HANDLE thread_handle;
339 struct StartInfo *start_info;
342 thread=(MonoThread *)mono_object_new (domain,
343 mono_defaults.thread_class);
345 start_info=g_new0 (struct StartInfo, 1);
346 start_info->func = func;
347 start_info->obj = thread;
348 start_info->domain = domain;
349 start_info->this = arg;
351 /* Create suspended, so we can do some housekeeping before the thread
354 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
355 thread_handle = GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
356 CREATE_SUSPENDED, &tid);
358 thread_handle = CreateThread(NULL, default_stacksize, start_wrapper, start_info,
359 CREATE_SUSPENDED, &tid);
362 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
365 g_assert (thread_handle);
367 thread->handle=thread_handle;
370 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
372 handle_store(thread);
374 ResumeThread (thread_handle);
378 mono_thread_attach (MonoDomain *domain)
381 HANDLE thread_handle;
384 if ((thread = mono_thread_current ())) {
385 /* Already attached */
389 thread = (MonoThread *)mono_object_new (domain,
390 mono_defaults.thread_class);
392 thread_handle = GetCurrentThread ();
393 g_assert (thread_handle);
395 tid=GetCurrentThreadId ();
397 thread->handle=thread_handle;
399 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
402 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
406 handle_store(thread);
409 g_message (G_GNUC_PRETTY_FUNCTION
410 ": (%d) Setting current_object_key to %p",
411 GetCurrentThreadId (), thread);
414 SET_CURRENT_OBJECT (thread);
415 mono_domain_set (domain, TRUE);
417 thread_adjust_static_data (thread);
419 if (mono_thread_attach_cb) {
420 mono_thread_attach_cb (tid, &tid);
427 mono_thread_detach (MonoThread *thread)
429 g_return_if_fail (thread != NULL);
432 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
434 SET_CURRENT_OBJECT (NULL);
436 thread_cleanup (thread);
442 MonoThread *thread = mono_thread_current ();
444 SET_CURRENT_OBJECT (NULL);
445 thread_cleanup (thread);
450 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
453 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
454 guint32 (*start_func)(void *);
455 struct StartInfo *start_info;
463 g_message(G_GNUC_PRETTY_FUNCTION
464 ": Trying to start a new thread: this (%p) start (%p)",
468 im = mono_get_delegate_invoke (start->vtable->klass);
469 im = mono_marshal_get_delegate_invoke (im);
470 if (mono_thread_callbacks)
471 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
473 start_func = mono_compile_method (im);
475 if(start_func==NULL) {
476 g_warning(G_GNUC_PRETTY_FUNCTION
477 ": Can't locate start method!");
480 /* This is freed in start_wrapper */
481 start_info = g_new0 (struct StartInfo, 1);
482 start_info->func = start_func;
483 start_info->this = delegate;
484 start_info->obj = this;
485 start_info->domain = mono_domain_get ();
487 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
488 if(this->start_notify==NULL) {
489 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
493 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
494 thread=GC_CreateThread(NULL, default_stacksize, start_wrapper, start_info,
495 CREATE_SUSPENDED, &tid);
497 thread=CreateThread(NULL, default_stacksize, start_wrapper, start_info,
498 CREATE_SUSPENDED, &tid);
501 g_warning(G_GNUC_PRETTY_FUNCTION
502 ": CreateThread error 0x%x", GetLastError());
509 /* Don't call handle_store() here, delay it to Start.
510 * We can't join a thread (trying to will just block
511 * forever) until it actually starts running, so don't
512 * store the handle till then.
516 g_message(G_GNUC_PRETTY_FUNCTION
517 ": Started thread ID %d (handle %p)", tid, thread);
524 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
530 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
534 CloseHandle (thread);
537 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
543 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
544 GetCurrentThreadId (), this, this->tid);
547 /* Only store the handle when the thread is about to be
548 * launched, to avoid the main thread deadlocking while trying
549 * to clean up a thread that will never be signalled.
553 if (mono_thread_callbacks)
554 (* mono_thread_callbacks->start_resume) (this->tid);
556 ResumeThread(thread);
558 if (mono_thread_callbacks)
559 (* mono_thread_callbacks->end_resume) (this->tid);
561 if(this->start_notify!=NULL) {
562 /* Wait for the thread to set up its TLS data etc, so
563 * theres no potential race condition if someone tries
564 * to look up the data believing the thread has
569 g_message(G_GNUC_PRETTY_FUNCTION
570 ": (%d) waiting for thread %p (%d) to start",
571 GetCurrentThreadId (), this, this->tid);
574 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
575 CloseHandle (this->start_notify);
576 this->start_notify=NULL;
580 g_message(G_GNUC_PRETTY_FUNCTION
581 ": (%d) Done launching thread %p (%d)",
582 GetCurrentThreadId (), this, this->tid);
586 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
588 MonoThread *thread = mono_thread_current ();
593 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
596 mono_monitor_enter (thread->synch_lock);
597 thread->state |= ThreadState_WaitSleepJoin;
598 mono_monitor_exit (thread->synch_lock);
602 mono_monitor_enter (thread->synch_lock);
603 thread->state &= ~ThreadState_WaitSleepJoin;
604 mono_monitor_exit (thread->synch_lock);
608 ves_icall_System_Threading_Thread_GetDomainID (void)
612 return mono_domain_get()->domain_id;
616 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
621 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
625 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
628 g_free (this_obj->name);
630 this_obj->name = g_new (gunichar2, mono_string_length (name));
631 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
632 this_obj->name_len = mono_string_length (name);
635 this_obj->name = NULL;
639 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
645 /* No need to lock here */
646 if (this->culture_info) {
647 domain = mono_domain_get ();
648 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
649 res = this->culture_info [i];
650 if (res && res->vtable->domain == domain)
659 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
663 mono_monitor_enter (this->synch_lock);
664 if (this->serialized_culture_info) {
665 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
666 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
670 mono_monitor_exit (this->synch_lock);
676 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
679 MonoDomain *domain = mono_domain_get ();
681 mono_monitor_enter (this->synch_lock);
682 if (!this->culture_info) {
684 this->culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
686 this->culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
690 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
691 if (this->culture_info [i]) {
692 if (this->culture_info [i]->vtable->domain == domain)
700 if (i < NUM_CACHED_CULTURES)
701 this->culture_info [i] = culture;
702 mono_monitor_exit (this->synch_lock);
706 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
708 mono_monitor_enter (this->synch_lock);
709 if (this->serialized_culture_info)
710 g_free (this->serialized_culture_info);
711 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
712 this->serialized_culture_info_len = mono_array_length (arr);
713 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
714 mono_monitor_exit (this->synch_lock);
719 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
725 /* No need to lock here */
726 if (this->ui_culture_info) {
727 domain = mono_domain_get ();
728 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
729 res = this->ui_culture_info [i];
730 if (res && res->vtable->domain == domain)
739 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
743 mono_monitor_enter (this->synch_lock);
744 if (this->serialized_ui_culture_info) {
745 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
746 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
750 mono_monitor_exit (this->synch_lock);
756 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
759 MonoDomain *domain = mono_domain_get ();
761 mono_monitor_enter (this->synch_lock);
762 if (!this->ui_culture_info) {
764 this->ui_culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
766 this->ui_culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
770 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
771 if (this->ui_culture_info [i]) {
772 if (this->ui_culture_info [i]->vtable->domain == domain)
780 if (i < NUM_CACHED_CULTURES)
781 this->ui_culture_info [i] = culture;
782 mono_monitor_exit (this->synch_lock);
786 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
788 mono_monitor_enter (this->synch_lock);
789 if (this->serialized_ui_culture_info)
790 g_free (this->serialized_ui_culture_info);
791 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
792 this->serialized_ui_culture_info_len = mono_array_length (arr);
793 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
794 mono_monitor_exit (this->synch_lock);
797 /* the jit may read the compiled code of this function */
799 mono_thread_current (void)
804 thread = GET_CURRENT_OBJECT ();
805 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
809 return GET_CURRENT_OBJECT ();
813 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
814 int ms, HANDLE thread)
820 mono_monitor_enter (this->synch_lock);
821 this->state |= ThreadState_WaitSleepJoin;
822 mono_monitor_exit (this->synch_lock);
828 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
832 ret=WaitForSingleObjectEx (thread, ms, TRUE);
834 mono_monitor_enter (this->synch_lock);
835 this->state &= ~ThreadState_WaitSleepJoin;
836 mono_monitor_exit (this->synch_lock);
838 if(ret==WAIT_OBJECT_0) {
840 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
847 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
853 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
858 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
861 /* Object location stored here */
862 TlsSetValue(slothash_key, data);
865 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
871 data=TlsGetValue(slothash_key);
874 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
880 /* FIXME: exitContext isnt documented */
881 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
887 MonoObject *waitHandle;
892 numhandles = mono_array_length(mono_handles);
893 handles = g_new0(HANDLE, numhandles);
895 if (wait_handle_os_handle_field == 0) {
896 /* Get the field os_handle which will contain the actual handle */
897 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
898 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
901 for(i = 0; i < numhandles; i++) {
902 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
903 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
910 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
914 if(ret==WAIT_FAILED) {
915 #ifdef THREAD_WAIT_DEBUG
916 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
917 GetCurrentThreadId ());
920 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
921 /* Do we want to try again if we get
922 * WAIT_IO_COMPLETION? The documentation for
923 * WaitHandle doesn't give any clues. (We'd have to
924 * fiddle with the timeout if we retry.)
926 #ifdef THREAD_WAIT_DEBUG
927 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
928 GetCurrentThreadId ());
936 /* FIXME: exitContext isnt documented */
937 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
943 MonoObject *waitHandle;
948 numhandles = mono_array_length(mono_handles);
949 handles = g_new0(HANDLE, numhandles);
951 if (wait_handle_os_handle_field == 0) {
952 /* Get the field os_handle which will contain the actual handle */
953 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
954 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
957 for(i = 0; i < numhandles; i++) {
958 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
959 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
966 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
970 #ifdef THREAD_WAIT_DEBUG
971 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
972 GetCurrentThreadId (), ret);
976 * These need to be here. See MSDN dos on WaitForMultipleObjects.
978 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
979 return ret - WAIT_OBJECT_0;
981 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
982 return ret - WAIT_ABANDONED_0;
989 /* FIXME: exitContext isnt documented */
990 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
996 #ifdef THREAD_WAIT_DEBUG
997 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
998 GetCurrentThreadId (), handle, ms);
1005 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1007 if(ret==WAIT_FAILED) {
1008 #ifdef THREAD_WAIT_DEBUG
1009 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1010 GetCurrentThreadId ());
1013 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1014 /* Do we want to try again if we get
1015 * WAIT_IO_COMPLETION? The documentation for
1016 * WaitHandle doesn't give any clues. (We'd have to
1017 * fiddle with the timeout if we retry.)
1019 #ifdef THREAD_WAIT_DEBUG
1020 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1021 GetCurrentThreadId ());
1029 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1033 MONO_ARCH_SAVE_REGS;
1038 mutex = CreateMutex (NULL, owned, NULL);
1040 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1042 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1050 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1051 MONO_ARCH_SAVE_REGS;
1053 ReleaseMutex(handle);
1056 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1057 MONO_ARCH_SAVE_REGS;
1059 return(CreateEvent (NULL, manual, initial,
1060 name==NULL?NULL:mono_string_chars (name)));
1063 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1064 MONO_ARCH_SAVE_REGS;
1066 return (SetEvent(handle));
1069 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1070 MONO_ARCH_SAVE_REGS;
1072 return (ResetEvent(handle));
1076 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1077 MONO_ARCH_SAVE_REGS;
1079 CloseHandle (handle);
1082 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1084 MONO_ARCH_SAVE_REGS;
1086 return InterlockedIncrement (location);
1089 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1093 MONO_ARCH_SAVE_REGS;
1095 EnterCriticalSection(&interlocked_mutex);
1099 LeaveCriticalSection(&interlocked_mutex);
1105 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1107 MONO_ARCH_SAVE_REGS;
1109 return InterlockedDecrement(location);
1112 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1116 MONO_ARCH_SAVE_REGS;
1118 EnterCriticalSection(&interlocked_mutex);
1122 LeaveCriticalSection(&interlocked_mutex);
1127 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1129 MONO_ARCH_SAVE_REGS;
1131 return InterlockedExchange(location1, value);
1134 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1136 MONO_ARCH_SAVE_REGS;
1138 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1141 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1143 IntFloatUnion val, ret;
1145 MONO_ARCH_SAVE_REGS;
1148 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1153 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1155 MONO_ARCH_SAVE_REGS;
1157 return InterlockedCompareExchange(location1, value, comparand);
1160 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1162 MONO_ARCH_SAVE_REGS;
1164 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1167 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1169 IntFloatUnion val, ret, cmp;
1171 MONO_ARCH_SAVE_REGS;
1174 cmp.fval = comparand;
1175 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1181 mono_thread_get_abort_signal (void)
1191 #endif /* __MINGW32__ */
1195 static guint32 interruption_request_apc (gpointer param)
1197 MonoException* exc = mono_thread_request_interruption (FALSE);
1198 if (exc) mono_raise_exception (exc);
1201 #endif /* __MINGW32__ */
1204 * signal_thread_state_change
1206 * Tells the thread that his state has changed and it has to enter the new
1207 * state as soon as possible.
1209 static void signal_thread_state_change (MonoThread *thread)
1212 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1214 /* fixme: store the state somewhere */
1215 #ifdef PTHREAD_POINTER_ID
1216 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1218 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1220 #endif /* __MINGW32__ */
1224 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1226 MONO_ARCH_SAVE_REGS;
1228 mono_monitor_enter (thread->synch_lock);
1230 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1231 (thread->state & ThreadState_StopRequested) != 0)
1233 mono_monitor_exit (thread->synch_lock);
1237 thread->state |= ThreadState_AbortRequested;
1238 thread->abort_state = state;
1239 thread->abort_exc = NULL;
1241 mono_monitor_exit (thread->synch_lock);
1244 g_message (G_GNUC_PRETTY_FUNCTION
1245 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1246 thread, thread->tid);
1249 /* Make sure the thread is awake */
1250 ves_icall_System_Threading_Thread_Resume (thread);
1252 signal_thread_state_change (thread);
1256 ves_icall_System_Threading_Thread_ResetAbort (void)
1258 MonoThread *thread = mono_thread_current ();
1260 MONO_ARCH_SAVE_REGS;
1262 mono_monitor_enter (thread->synch_lock);
1264 thread->state &= ~ThreadState_AbortRequested;
1266 if (!thread->abort_exc) {
1267 const char *msg = "Unable to reset abort because no abort was requested";
1268 mono_monitor_exit (thread->synch_lock);
1269 mono_raise_exception (mono_get_exception_thread_state (msg));
1271 thread->abort_exc = NULL;
1272 thread->abort_state = NULL;
1275 mono_monitor_exit (thread->synch_lock);
1279 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1281 MONO_ARCH_SAVE_REGS;
1283 mono_monitor_enter (thread->synch_lock);
1285 if ((thread->state & ThreadState_Suspended) != 0 ||
1286 (thread->state & ThreadState_SuspendRequested) != 0 ||
1287 (thread->state & ThreadState_StopRequested) != 0)
1289 mono_monitor_exit (thread->synch_lock);
1293 thread->state |= ThreadState_SuspendRequested;
1294 mono_monitor_exit (thread->synch_lock);
1296 signal_thread_state_change (thread);
1300 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1302 MONO_ARCH_SAVE_REGS;
1304 mono_monitor_enter (thread->synch_lock);
1306 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1307 thread->state &= ~ThreadState_SuspendRequested;
1308 mono_monitor_exit (thread->synch_lock);
1312 if ((thread->state & ThreadState_Suspended) == 0)
1314 mono_monitor_exit (thread->synch_lock);
1318 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1320 /* Awake the thread */
1321 SetEvent (thread->suspend_event);
1323 mono_monitor_exit (thread->synch_lock);
1325 /* Wait for the thread to awake */
1326 WaitForSingleObject (thread->resume_event, INFINITE);
1327 CloseHandle (thread->resume_event);
1328 thread->resume_event = NULL;
1332 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1337 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1338 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1339 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1341 *((gboolean*)data) = TRUE;
1348 is_running_protected_wrapper (void)
1350 gboolean found = FALSE;
1351 mono_stack_walk (find_wrapper, &found);
1355 void mono_thread_stop (MonoThread *thread)
1357 mono_monitor_enter (thread->synch_lock);
1359 if ((thread->state & ThreadState_StopRequested) != 0 ||
1360 (thread->state & ThreadState_Stopped) != 0)
1362 mono_monitor_exit (thread->synch_lock);
1366 /* Make sure the thread is awake */
1367 ves_icall_System_Threading_Thread_Resume (thread);
1369 thread->state |= ThreadState_StopRequested;
1370 thread->state &= ~ThreadState_AbortRequested;
1372 mono_monitor_exit (thread->synch_lock);
1374 signal_thread_state_change (thread);
1378 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1380 return *((volatile gint8 *) (ptr));
1384 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1386 return *((volatile gint16 *) (ptr));
1390 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1392 return *((volatile gint32 *) (ptr));
1396 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1398 return *((volatile gint64 *) (ptr));
1402 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1404 return (void *) *((volatile void **) ptr);
1408 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1410 *((volatile gint8 *) ptr) = value;
1414 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1416 *((volatile gint16 *) ptr) = value;
1420 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1422 *((volatile gint32 *) ptr) = value;
1426 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1428 *((volatile gint64 *) ptr) = value;
1432 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1434 *((volatile void **) ptr) = value;
1437 void mono_thread_init (MonoThreadStartCB start_cb,
1438 MonoThreadAttachCB attach_cb)
1440 InitializeCriticalSection(&threads_mutex);
1441 InitializeCriticalSection(&interlocked_mutex);
1442 InitializeCriticalSection(&contexts_mutex);
1443 InitializeCriticalSection(&interruption_mutex);
1445 mono_init_static_data_info (&thread_static_info);
1446 mono_init_static_data_info (&context_static_info);
1448 current_object_key=TlsAlloc();
1450 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1451 current_object_key);
1454 mono_thread_start_cb = start_cb;
1455 mono_thread_attach_cb = attach_cb;
1457 slothash_key=TlsAlloc();
1459 /* Get a pseudo handle to the current process. This is just a
1460 * kludge so that wapi can build a process handle if needed.
1461 * As a pseudo handle is returned, we don't need to clean
1464 GetCurrentProcess ();
1468 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1470 mono_thread_cleanup = func;
1473 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1475 mono_thread_callbacks = callbacks;
1479 static void print_tids (gpointer key, gpointer value, gpointer user)
1481 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1487 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1488 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1492 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1497 g_message(G_GNUC_PRETTY_FUNCTION
1498 ": %d threads to wait for in this batch", wait->num);
1501 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1503 if(ret==WAIT_FAILED) {
1504 /* See the comment in build_wait_tids() */
1506 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1511 for(i=0; i<wait->num; i++)
1512 CloseHandle (wait->handles[i]);
1514 if (ret == WAIT_TIMEOUT)
1517 for(i=0; i<wait->num; i++) {
1518 guint32 tid=wait->threads[i]->tid;
1520 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1521 /* This thread must have been killed, because
1522 * it hasn't cleaned itself up. (It's just
1523 * possible that the thread exited before the
1524 * parent thread had a chance to store the
1525 * handle, and now there is another pointer to
1526 * the already-exited thread stored. In this
1527 * case, we'll just get two
1528 * mono_profiler_thread_end() calls for the
1533 g_message (G_GNUC_PRETTY_FUNCTION
1534 ": cleaning up after thread %d", tid);
1536 thread_cleanup (wait->threads[i]);
1541 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1543 struct wait_data *wait=(struct wait_data *)user;
1545 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1547 MonoThread *thread=(MonoThread *)value;
1549 /* Ignore background threads, we abort them later */
1550 if (thread->state & ThreadState_Background)
1551 return; /* just leave, ignore */
1553 if (mono_gc_is_finalizer_thread (thread))
1556 if (thread == mono_thread_current ())
1559 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1563 wait->handles[wait->num]=handle;
1564 wait->threads[wait->num]=thread;
1567 /* Just ignore the rest, we can't do anything with
1574 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1576 struct wait_data *wait=(struct wait_data *)user;
1577 guint32 self = GetCurrentThreadId ();
1578 MonoThread *thread = (MonoThread *) value;
1581 /* The finalizer thread is not a background thread */
1582 if (thread->tid != self && thread->state & ThreadState_Background) {
1584 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1588 wait->handles[wait->num]=thread->handle;
1589 wait->threads[wait->num]=thread;
1592 if(thread->state & ThreadState_AbortRequested ||
1593 thread->state & ThreadState_Aborted) {
1595 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1601 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1603 mono_thread_stop (thread);
1607 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1610 void mono_thread_manage (void)
1612 struct wait_data *wait=g_new0 (struct wait_data, 1);
1614 /* join each thread that's still running */
1616 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1619 EnterCriticalSection (&threads_mutex);
1622 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1624 LeaveCriticalSection (&threads_mutex);
1627 LeaveCriticalSection (&threads_mutex);
1630 EnterCriticalSection (&threads_mutex);
1632 g_message(G_GNUC_PRETTY_FUNCTION
1633 ":There are %d threads to join",
1634 mono_g_hash_table_size (threads));
1635 mono_g_hash_table_foreach (threads, print_tids, NULL);
1639 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1640 LeaveCriticalSection (&threads_mutex);
1642 /* Something to wait for */
1643 wait_for_tids (wait, INFINITE);
1645 } while(wait->num>0);
1647 mono_thread_pool_cleanup ();
1649 EnterCriticalSection(&threads_mutex);
1652 * Remove everything but the finalizer thread and self.
1653 * Also abort all the background threads
1656 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1658 LeaveCriticalSection(&threads_mutex);
1661 /* Something to wait for */
1662 wait_for_tids (wait, INFINITE);
1665 * give the subthreads a chance to really quit (this is mainly needed
1666 * to get correct user and system times from getrusage/wait/time(1)).
1667 * This could be removed if we avoid pthread_detach() and use pthread_join().
1669 #ifndef PLATFORM_WIN32
1676 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1678 MonoThread *thread=(MonoThread *)value;
1679 guint32 self=GPOINTER_TO_UINT (user);
1681 if(thread->tid!=self) {
1682 /*TerminateThread (thread->handle, -1);*/
1686 void mono_thread_abort_all_other_threads (void)
1688 guint32 self=GetCurrentThreadId ();
1690 EnterCriticalSection (&threads_mutex);
1692 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1693 mono_g_hash_table_size (threads));
1694 mono_g_hash_table_foreach (threads, print_tids, NULL);
1697 mono_g_hash_table_foreach (threads, terminate_thread,
1698 GUINT_TO_POINTER (self));
1700 LeaveCriticalSection (&threads_mutex);
1704 * mono_thread_push_appdomain_ref:
1706 * Register that the current thread may have references to objects in domain
1707 * @domain on its stack. Each call to this function should be paired with a
1708 * call to pop_appdomain_ref.
1711 mono_thread_push_appdomain_ref (MonoDomain *domain)
1713 MonoThread *thread = mono_thread_current ();
1716 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1717 EnterCriticalSection (&threads_mutex);
1718 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1719 LeaveCriticalSection (&threads_mutex);
1724 mono_thread_pop_appdomain_ref (void)
1726 MonoThread *thread = mono_thread_current ();
1729 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1730 EnterCriticalSection (&threads_mutex);
1731 /* FIXME: How can the list be empty ? */
1732 if (thread->appdomain_refs)
1733 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1734 LeaveCriticalSection (&threads_mutex);
1739 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1742 EnterCriticalSection (&threads_mutex);
1743 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1744 LeaveCriticalSection (&threads_mutex);
1748 typedef struct abort_appdomain_data {
1749 struct wait_data wait;
1751 } abort_appdomain_data;
1754 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1756 MonoThread *thread = (MonoThread*)value;
1757 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1758 MonoDomain *domain = data->domain;
1760 if (mono_thread_has_appdomain_ref (thread, domain)) {
1761 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1762 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1766 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1768 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1769 data->wait.handles [data->wait.num] = handle;
1770 data->wait.threads [data->wait.num] = thread;
1773 /* Just ignore the rest, we can't do anything with
1781 * mono_threads_abort_appdomain_threads:
1783 * Abort threads which has references to the given appdomain.
1786 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1788 abort_appdomain_data user_data;
1791 /* printf ("ABORT BEGIN.\n"); */
1793 start_time = GetTickCount ();
1795 EnterCriticalSection (&threads_mutex);
1797 user_data.domain = domain;
1798 user_data.wait.num = 0;
1799 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1800 LeaveCriticalSection (&threads_mutex);
1802 if (user_data.wait.num > 0)
1803 wait_for_tids (&user_data.wait, timeout);
1805 /* Update remaining time */
1806 timeout -= GetTickCount () - start_time;
1807 start_time = GetTickCount ();
1812 while (user_data.wait.num > 0);
1814 /* printf ("ABORT DONE.\n"); */
1820 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1822 MonoThread *thread = (MonoThread*)value;
1823 MonoDomain *domain = (MonoDomain*)user_data;
1826 /* No locking needed here */
1828 if (thread->culture_info) {
1829 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1830 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1831 thread->culture_info [i] = NULL;
1834 if (thread->ui_culture_info) {
1835 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1836 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1837 thread->ui_culture_info [i] = NULL;
1843 * mono_threads_clear_cached_culture:
1845 * Clear the cached_current_culture from all threads if it is in the
1849 mono_threads_clear_cached_culture (MonoDomain *domain)
1851 EnterCriticalSection (&threads_mutex);
1852 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1853 LeaveCriticalSection (&threads_mutex);
1857 * mono_thread_get_pending_exception:
1859 * Return an exception which needs to be raised when leaving a catch clause.
1860 * This is used for undeniable exception propagation.
1863 mono_thread_get_pending_exception (void)
1865 MonoThread *thread = mono_thread_current ();
1867 MONO_ARCH_SAVE_REGS;
1869 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1871 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1872 * exception if the thread no longer references a dying appdomain.
1874 thread->abort_exc->trace_ips = NULL;
1875 thread->abort_exc->stack_trace = NULL;
1876 return thread->abort_exc;
1882 #define NUM_STATIC_DATA_IDX 8
1883 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1884 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1889 * mono_alloc_static_data
1891 * Allocate memory blocks for storing threads or context static data
1894 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1896 guint idx = (offset >> 24) - 1;
1899 gpointer* static_data = *static_data_ptr;
1902 static_data = GC_MALLOC (static_data_size [0]);
1904 static_data = g_malloc0 (static_data_size [0]);
1906 *static_data_ptr = static_data;
1907 static_data [0] = static_data;
1910 for (i = 1; i < idx; ++i) {
1911 if (static_data [i])
1914 static_data [i] = GC_MALLOC (static_data_size [i]);
1916 static_data [i] = g_malloc0 (static_data_size [i]);
1922 * mono_init_static_data_info
1924 * Initializes static data counters
1926 static void mono_init_static_data_info (StaticDataInfo *static_data)
1928 static_data->idx = 0;
1929 static_data->offset = 0;
1933 * mono_alloc_static_data_slot
1935 * Generates an offset for static data. static_data contains the counters
1936 * used to generate it.
1939 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1943 if (!static_data->idx && !static_data->offset) {
1945 * we use the first chunk of the first allocation also as
1946 * an array for the rest of the data
1948 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1950 static_data->offset += align - 1;
1951 static_data->offset &= ~(align - 1);
1952 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1953 static_data->idx ++;
1954 g_assert (size <= static_data_size [static_data->idx]);
1956 * massive unloading and reloading of domains with thread-static
1957 * data may eventually exceed the allocated storage...
1958 * Need to check what the MS runtime does in that case.
1959 * Note that for each appdomain, we need to allocate a separate
1960 * thread data slot for security reasons. We could keep track
1961 * of the slots per-domain and when the domain is unloaded
1962 * out the slots on a sort of free list.
1964 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1965 static_data->offset = 0;
1967 offset = static_data->offset | ((static_data->idx + 1) << 24);
1968 static_data->offset += size;
1973 * ensure thread static fields already allocated are valid for thread
1974 * This function is called when a thread is created or on thread attach.
1977 thread_adjust_static_data (MonoThread *thread)
1981 EnterCriticalSection (&threads_mutex);
1982 if (thread_static_info.offset || thread_static_info.idx > 0) {
1983 /* get the current allocated size */
1984 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
1985 mono_alloc_static_data (&(thread->static_data), offset);
1987 LeaveCriticalSection (&threads_mutex);
1991 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
1993 MonoThread *thread = value;
1994 guint32 offset = GPOINTER_TO_UINT (user);
1996 mono_alloc_static_data (&(thread->static_data), offset);
2000 * The offset for a special static variable is composed of three parts:
2001 * a bit that indicates the type of static data (0:thread, 1:context),
2002 * an index in the array of chunks of memory for the thread (thread->static_data)
2003 * and an offset in that chunk of mem. This allows allocating less memory in the
2008 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2011 if (static_type == SPECIAL_STATIC_THREAD)
2013 EnterCriticalSection (&threads_mutex);
2014 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2015 /* This can be called during startup */
2016 if (threads != NULL)
2017 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2018 LeaveCriticalSection (&threads_mutex);
2022 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2023 EnterCriticalSection (&contexts_mutex);
2024 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2025 LeaveCriticalSection (&contexts_mutex);
2026 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2032 mono_get_special_static_data (guint32 offset)
2034 /* The high bit means either thread (0) or static (1) data. */
2036 guint32 static_type = (offset & 0x80000000);
2039 offset &= 0x7fffffff;
2040 idx = (offset >> 24) - 1;
2042 if (static_type == 0)
2044 MonoThread *thread = mono_thread_current ();
2045 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2049 /* Allocate static data block under demand, since we don't have a list
2052 MonoAppContext *context = mono_context_get ();
2053 if (!context->static_data || !context->static_data [idx]) {
2054 EnterCriticalSection (&contexts_mutex);
2055 mono_alloc_static_data (&(context->static_data), offset);
2056 LeaveCriticalSection (&contexts_mutex);
2058 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2062 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2064 MonoThread *thread=(MonoThread *)value;
2065 guint32 self=GPOINTER_TO_UINT (user);
2068 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2071 if(thread->tid==self)
2074 SuspendThread (thread->handle);
2077 void mono_gc_stop_world (void)
2079 guint32 self=GetCurrentThreadId ();
2082 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2085 EnterCriticalSection (&threads_mutex);
2087 if (threads != NULL)
2088 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2090 LeaveCriticalSection (&threads_mutex);
2093 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2095 MonoThread *thread=(MonoThread *)value;
2096 guint32 self=GPOINTER_TO_UINT (user);
2099 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2102 if(thread->tid==self)
2105 ResumeThread (thread->handle);
2108 void mono_gc_start_world (void)
2110 guint32 self=GetCurrentThreadId ();
2113 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2116 EnterCriticalSection (&threads_mutex);
2118 if (threads != NULL)
2119 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2121 LeaveCriticalSection (&threads_mutex);
2125 static guint32 dummy_apc (gpointer param)
2131 * mono_thread_execute_interruption
2133 * Performs the operation that the requested thread state requires (abort,
2136 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2138 mono_monitor_enter (thread->synch_lock);
2140 if (thread->interruption_requested) {
2141 /* this will consume pending APC calls */
2142 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2143 EnterCriticalSection (&interruption_mutex);
2144 thread_interruption_requested--;
2145 LeaveCriticalSection (&interruption_mutex);
2146 thread->interruption_requested = FALSE;
2149 if ((thread->state & ThreadState_AbortRequested) != 0) {
2150 if (thread->abort_exc == NULL)
2151 thread->abort_exc = mono_get_exception_thread_abort ();
2152 mono_monitor_exit (thread->synch_lock);
2153 return thread->abort_exc;
2155 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2156 thread->state &= ~ThreadState_SuspendRequested;
2157 thread->state |= ThreadState_Suspended;
2158 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2159 mono_monitor_exit (thread->synch_lock);
2161 WaitForSingleObject (thread->suspend_event, INFINITE);
2163 mono_monitor_enter (thread->synch_lock);
2164 CloseHandle (thread->suspend_event);
2165 thread->suspend_event = NULL;
2166 thread->state &= ~ThreadState_Suspended;
2168 /* The thread that requested the resume will have replaced this event
2169 * and will be waiting for it
2171 SetEvent (thread->resume_event);
2172 mono_monitor_exit (thread->synch_lock);
2175 else if ((thread->state & ThreadState_StopRequested) != 0) {
2176 /* FIXME: do this through the JIT? */
2177 mono_monitor_exit (thread->synch_lock);
2178 mono_thread_exit ();
2182 mono_monitor_exit (thread->synch_lock);
2187 * mono_thread_request_interruption
2189 * A signal handler can call this method to request the interruption of a
2190 * thread. The result of the interruption will depend on the current state of
2191 * the thread. If the result is an exception that needs to be throw, it is
2192 * provided as return value.
2194 MonoException* mono_thread_request_interruption (gboolean running_managed)
2196 MonoThread *thread = mono_thread_current ();
2198 /* The thread may already be stopping */
2202 mono_monitor_enter (thread->synch_lock);
2204 if (thread->interruption_requested) {
2205 mono_monitor_exit (thread->synch_lock);
2209 if (!running_managed || is_running_protected_wrapper ()) {
2210 /* Can't stop while in unmanaged code. Increase the global interruption
2211 request count. When exiting the unmanaged method the count will be
2212 checked and the thread will be interrupted. */
2214 EnterCriticalSection (&interruption_mutex);
2215 thread_interruption_requested++;
2216 LeaveCriticalSection (&interruption_mutex);
2218 thread->interruption_requested = TRUE;
2219 mono_monitor_exit (thread->synch_lock);
2221 /* this will awake the thread if it is in WaitForSingleObject
2223 QueueUserAPC (dummy_apc, thread->handle, NULL);
2228 mono_monitor_exit (thread->synch_lock);
2229 return mono_thread_execute_interruption (thread);
2233 gboolean mono_thread_interruption_requested ()
2235 if (thread_interruption_requested) {
2236 MonoThread *thread = mono_thread_current ();
2237 /* The thread may already be stopping */
2239 return (thread->interruption_requested);
2244 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2246 MonoThread *thread = mono_thread_current ();
2248 /* The thread may already be stopping */
2252 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2253 MonoException* exc = mono_thread_execute_interruption (thread);
2254 if (exc) mono_raise_exception (exc);
2259 * Performs the interruption of the current thread, if one has been requested,
2260 * and the thread is not running a protected wrapper.
2262 void mono_thread_interruption_checkpoint ()
2264 mono_thread_interruption_checkpoint_request (FALSE);
2268 * Performs the interruption of the current thread, if one has been requested.
2270 void mono_thread_force_interruption_checkpoint ()
2272 mono_thread_interruption_checkpoint_request (TRUE);
2276 * mono_thread_interruption_request_flag:
2278 * Returns the address of a flag that will be non-zero if an interruption has
2279 * been requested for a thread. The thread to interrupt may not be the current
2280 * thread, so an additional call to mono_thread_interruption_requested() or
2281 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2284 gint32* mono_thread_interruption_request_flag ()
2286 return &thread_interruption_requested;
2289 #ifdef WITH_INCLUDED_LIBGC
2291 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2293 MonoThread *thread=(MonoThread *)value;
2294 guint32 *selfp=(guint32 *)user, self = *selfp;
2297 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2300 if(thread->tid==self) {
2302 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2304 GC_push_all_stack (selfp, thread->stack_ptr);
2308 #ifdef PLATFORM_WIN32
2309 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2311 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2315 void mono_gc_push_all_stacks (void)
2317 guint32 self=GetCurrentThreadId ();
2320 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2323 EnterCriticalSection (&threads_mutex);
2325 if (threads != NULL)
2326 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2328 LeaveCriticalSection (&threads_mutex);
2331 #endif /* WITH_INCLUDED_LIBGC */