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;
889 MonoThread *thread = mono_thread_current ();
893 numhandles = mono_array_length(mono_handles);
894 handles = g_new0(HANDLE, numhandles);
896 if (wait_handle_os_handle_field == 0) {
897 /* Get the field os_handle which will contain the actual handle */
898 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
899 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
902 for(i = 0; i < numhandles; i++) {
903 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
904 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
911 mono_monitor_enter (thread->synch_lock);
912 thread->state |= ThreadState_WaitSleepJoin;
913 mono_monitor_exit (thread->synch_lock);
915 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
917 mono_monitor_enter (thread->synch_lock);
918 thread->state &= ~ThreadState_WaitSleepJoin;
919 mono_monitor_exit (thread->synch_lock);
923 if(ret==WAIT_FAILED) {
924 #ifdef THREAD_WAIT_DEBUG
925 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
926 GetCurrentThreadId ());
929 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
930 /* Do we want to try again if we get
931 * WAIT_IO_COMPLETION? The documentation for
932 * WaitHandle doesn't give any clues. (We'd have to
933 * fiddle with the timeout if we retry.)
935 #ifdef THREAD_WAIT_DEBUG
936 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
937 GetCurrentThreadId ());
945 /* FIXME: exitContext isnt documented */
946 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
952 MonoObject *waitHandle;
954 MonoThread *thread = mono_thread_current ();
958 numhandles = mono_array_length(mono_handles);
959 handles = g_new0(HANDLE, numhandles);
961 if (wait_handle_os_handle_field == 0) {
962 /* Get the field os_handle which will contain the actual handle */
963 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
964 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
967 for(i = 0; i < numhandles; i++) {
968 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
969 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
976 mono_monitor_enter (thread->synch_lock);
977 thread->state |= ThreadState_WaitSleepJoin;
978 mono_monitor_exit (thread->synch_lock);
980 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
982 mono_monitor_enter (thread->synch_lock);
983 thread->state &= ~ThreadState_WaitSleepJoin;
984 mono_monitor_exit (thread->synch_lock);
988 #ifdef THREAD_WAIT_DEBUG
989 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
990 GetCurrentThreadId (), ret);
994 * These need to be here. See MSDN dos on WaitForMultipleObjects.
996 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
997 return ret - WAIT_OBJECT_0;
999 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1000 return ret - WAIT_ABANDONED_0;
1007 /* FIXME: exitContext isnt documented */
1008 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1011 MonoThread *thread = mono_thread_current ();
1013 MONO_ARCH_SAVE_REGS;
1015 #ifdef THREAD_WAIT_DEBUG
1016 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1017 GetCurrentThreadId (), handle, ms);
1024 mono_monitor_enter (thread->synch_lock);
1025 thread->state |= ThreadState_WaitSleepJoin;
1026 mono_monitor_exit (thread->synch_lock);
1028 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1030 mono_monitor_enter (thread->synch_lock);
1031 thread->state &= ~ThreadState_WaitSleepJoin;
1032 mono_monitor_exit (thread->synch_lock);
1034 if(ret==WAIT_FAILED) {
1035 #ifdef THREAD_WAIT_DEBUG
1036 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1037 GetCurrentThreadId ());
1040 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1041 /* Do we want to try again if we get
1042 * WAIT_IO_COMPLETION? The documentation for
1043 * WaitHandle doesn't give any clues. (We'd have to
1044 * fiddle with the timeout if we retry.)
1046 #ifdef THREAD_WAIT_DEBUG
1047 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1048 GetCurrentThreadId ());
1056 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1060 MONO_ARCH_SAVE_REGS;
1065 mutex = CreateMutex (NULL, owned, NULL);
1067 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1069 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1077 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1078 MONO_ARCH_SAVE_REGS;
1080 ReleaseMutex(handle);
1083 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1084 MONO_ARCH_SAVE_REGS;
1086 return(CreateEvent (NULL, manual, initial,
1087 name==NULL?NULL:mono_string_chars (name)));
1090 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1091 MONO_ARCH_SAVE_REGS;
1093 return (SetEvent(handle));
1096 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1097 MONO_ARCH_SAVE_REGS;
1099 return (ResetEvent(handle));
1103 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1104 MONO_ARCH_SAVE_REGS;
1106 CloseHandle (handle);
1109 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1111 MONO_ARCH_SAVE_REGS;
1113 return InterlockedIncrement (location);
1116 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1120 MONO_ARCH_SAVE_REGS;
1122 EnterCriticalSection(&interlocked_mutex);
1126 LeaveCriticalSection(&interlocked_mutex);
1132 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1134 MONO_ARCH_SAVE_REGS;
1136 return InterlockedDecrement(location);
1139 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1143 MONO_ARCH_SAVE_REGS;
1145 EnterCriticalSection(&interlocked_mutex);
1149 LeaveCriticalSection(&interlocked_mutex);
1154 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1156 MONO_ARCH_SAVE_REGS;
1158 return InterlockedExchange(location1, value);
1161 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1163 MONO_ARCH_SAVE_REGS;
1165 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1168 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1170 IntFloatUnion val, ret;
1172 MONO_ARCH_SAVE_REGS;
1175 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1180 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1182 MONO_ARCH_SAVE_REGS;
1184 return InterlockedCompareExchange(location1, value, comparand);
1187 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1189 MONO_ARCH_SAVE_REGS;
1191 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1194 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1196 IntFloatUnion val, ret, cmp;
1198 MONO_ARCH_SAVE_REGS;
1201 cmp.fval = comparand;
1202 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1208 mono_thread_get_abort_signal (void)
1218 #endif /* __MINGW32__ */
1222 static guint32 interruption_request_apc (gpointer param)
1224 MonoException* exc = mono_thread_request_interruption (FALSE);
1225 if (exc) mono_raise_exception (exc);
1228 #endif /* __MINGW32__ */
1231 * signal_thread_state_change
1233 * Tells the thread that his state has changed and it has to enter the new
1234 * state as soon as possible.
1236 static void signal_thread_state_change (MonoThread *thread)
1239 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1241 /* fixme: store the state somewhere */
1242 #ifdef PTHREAD_POINTER_ID
1243 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1245 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1247 #endif /* __MINGW32__ */
1251 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1253 MONO_ARCH_SAVE_REGS;
1255 mono_monitor_enter (thread->synch_lock);
1257 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1258 (thread->state & ThreadState_StopRequested) != 0)
1260 mono_monitor_exit (thread->synch_lock);
1264 thread->state |= ThreadState_AbortRequested;
1265 thread->abort_state = state;
1266 thread->abort_exc = NULL;
1268 mono_monitor_exit (thread->synch_lock);
1271 g_message (G_GNUC_PRETTY_FUNCTION
1272 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1273 thread, thread->tid);
1276 /* Make sure the thread is awake */
1277 ves_icall_System_Threading_Thread_Resume (thread);
1279 signal_thread_state_change (thread);
1283 ves_icall_System_Threading_Thread_ResetAbort (void)
1285 MonoThread *thread = mono_thread_current ();
1287 MONO_ARCH_SAVE_REGS;
1289 mono_monitor_enter (thread->synch_lock);
1291 thread->state &= ~ThreadState_AbortRequested;
1293 if (!thread->abort_exc) {
1294 const char *msg = "Unable to reset abort because no abort was requested";
1295 mono_monitor_exit (thread->synch_lock);
1296 mono_raise_exception (mono_get_exception_thread_state (msg));
1298 thread->abort_exc = NULL;
1299 thread->abort_state = NULL;
1302 mono_monitor_exit (thread->synch_lock);
1306 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1308 MONO_ARCH_SAVE_REGS;
1310 mono_monitor_enter (thread->synch_lock);
1312 if ((thread->state & ThreadState_Suspended) != 0 ||
1313 (thread->state & ThreadState_SuspendRequested) != 0 ||
1314 (thread->state & ThreadState_StopRequested) != 0)
1316 mono_monitor_exit (thread->synch_lock);
1320 thread->state |= ThreadState_SuspendRequested;
1321 mono_monitor_exit (thread->synch_lock);
1323 signal_thread_state_change (thread);
1327 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1329 MONO_ARCH_SAVE_REGS;
1331 mono_monitor_enter (thread->synch_lock);
1333 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1334 thread->state &= ~ThreadState_SuspendRequested;
1335 mono_monitor_exit (thread->synch_lock);
1339 if ((thread->state & ThreadState_Suspended) == 0)
1341 mono_monitor_exit (thread->synch_lock);
1345 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1347 /* Awake the thread */
1348 SetEvent (thread->suspend_event);
1350 mono_monitor_exit (thread->synch_lock);
1352 /* Wait for the thread to awake */
1353 WaitForSingleObject (thread->resume_event, INFINITE);
1354 CloseHandle (thread->resume_event);
1355 thread->resume_event = NULL;
1359 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1364 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1365 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1366 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1368 *((gboolean*)data) = TRUE;
1375 is_running_protected_wrapper (void)
1377 gboolean found = FALSE;
1378 mono_stack_walk (find_wrapper, &found);
1382 void mono_thread_stop (MonoThread *thread)
1384 mono_monitor_enter (thread->synch_lock);
1386 if ((thread->state & ThreadState_StopRequested) != 0 ||
1387 (thread->state & ThreadState_Stopped) != 0)
1389 mono_monitor_exit (thread->synch_lock);
1393 /* Make sure the thread is awake */
1394 ves_icall_System_Threading_Thread_Resume (thread);
1396 thread->state |= ThreadState_StopRequested;
1397 thread->state &= ~ThreadState_AbortRequested;
1399 mono_monitor_exit (thread->synch_lock);
1401 signal_thread_state_change (thread);
1405 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1407 return *((volatile gint8 *) (ptr));
1411 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1413 return *((volatile gint16 *) (ptr));
1417 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1419 return *((volatile gint32 *) (ptr));
1423 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1425 return *((volatile gint64 *) (ptr));
1429 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1431 return (void *) *((volatile void **) ptr);
1435 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1437 *((volatile gint8 *) ptr) = value;
1441 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1443 *((volatile gint16 *) ptr) = value;
1447 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1449 *((volatile gint32 *) ptr) = value;
1453 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1455 *((volatile gint64 *) ptr) = value;
1459 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1461 *((volatile void **) ptr) = value;
1464 void mono_thread_init (MonoThreadStartCB start_cb,
1465 MonoThreadAttachCB attach_cb)
1467 InitializeCriticalSection(&threads_mutex);
1468 InitializeCriticalSection(&interlocked_mutex);
1469 InitializeCriticalSection(&contexts_mutex);
1470 InitializeCriticalSection(&interruption_mutex);
1472 mono_init_static_data_info (&thread_static_info);
1473 mono_init_static_data_info (&context_static_info);
1475 current_object_key=TlsAlloc();
1477 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1478 current_object_key);
1481 mono_thread_start_cb = start_cb;
1482 mono_thread_attach_cb = attach_cb;
1484 slothash_key=TlsAlloc();
1486 /* Get a pseudo handle to the current process. This is just a
1487 * kludge so that wapi can build a process handle if needed.
1488 * As a pseudo handle is returned, we don't need to clean
1491 GetCurrentProcess ();
1495 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1497 mono_thread_cleanup = func;
1500 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1502 mono_thread_callbacks = callbacks;
1506 static void print_tids (gpointer key, gpointer value, gpointer user)
1508 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1514 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1515 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1519 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1524 g_message(G_GNUC_PRETTY_FUNCTION
1525 ": %d threads to wait for in this batch", wait->num);
1528 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1530 if(ret==WAIT_FAILED) {
1531 /* See the comment in build_wait_tids() */
1533 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1538 for(i=0; i<wait->num; i++)
1539 CloseHandle (wait->handles[i]);
1541 if (ret == WAIT_TIMEOUT)
1544 for(i=0; i<wait->num; i++) {
1545 guint32 tid=wait->threads[i]->tid;
1547 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1548 /* This thread must have been killed, because
1549 * it hasn't cleaned itself up. (It's just
1550 * possible that the thread exited before the
1551 * parent thread had a chance to store the
1552 * handle, and now there is another pointer to
1553 * the already-exited thread stored. In this
1554 * case, we'll just get two
1555 * mono_profiler_thread_end() calls for the
1560 g_message (G_GNUC_PRETTY_FUNCTION
1561 ": cleaning up after thread %d", tid);
1563 thread_cleanup (wait->threads[i]);
1568 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1570 struct wait_data *wait=(struct wait_data *)user;
1572 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1574 MonoThread *thread=(MonoThread *)value;
1576 /* Ignore background threads, we abort them later */
1577 if (thread->state & ThreadState_Background)
1578 return; /* just leave, ignore */
1580 if (mono_gc_is_finalizer_thread (thread))
1583 if (thread == mono_thread_current ())
1586 if (thread == mono_thread_get_main ())
1589 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1593 wait->handles[wait->num]=handle;
1594 wait->threads[wait->num]=thread;
1597 /* Just ignore the rest, we can't do anything with
1604 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1606 struct wait_data *wait=(struct wait_data *)user;
1607 guint32 self = GetCurrentThreadId ();
1608 MonoThread *thread = (MonoThread *) value;
1611 /* The finalizer thread is not a background thread */
1612 if (thread->tid != self && thread->state & ThreadState_Background) {
1614 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1618 wait->handles[wait->num]=thread->handle;
1619 wait->threads[wait->num]=thread;
1622 if(thread->state & ThreadState_AbortRequested ||
1623 thread->state & ThreadState_Aborted) {
1625 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1631 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1633 mono_thread_stop (thread);
1637 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1640 void mono_thread_manage (void)
1642 struct wait_data *wait=g_new0 (struct wait_data, 1);
1644 /* join each thread that's still running */
1646 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1649 EnterCriticalSection (&threads_mutex);
1652 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1654 LeaveCriticalSection (&threads_mutex);
1657 LeaveCriticalSection (&threads_mutex);
1660 EnterCriticalSection (&threads_mutex);
1662 g_message(G_GNUC_PRETTY_FUNCTION
1663 ":There are %d threads to join",
1664 mono_g_hash_table_size (threads));
1665 mono_g_hash_table_foreach (threads, print_tids, NULL);
1669 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1670 LeaveCriticalSection (&threads_mutex);
1672 /* Something to wait for */
1673 wait_for_tids (wait, INFINITE);
1675 } while(wait->num>0);
1677 mono_thread_pool_cleanup ();
1679 EnterCriticalSection(&threads_mutex);
1682 * Remove everything but the finalizer thread and self.
1683 * Also abort all the background threads
1686 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1688 LeaveCriticalSection(&threads_mutex);
1691 /* Something to wait for */
1692 wait_for_tids (wait, INFINITE);
1695 * give the subthreads a chance to really quit (this is mainly needed
1696 * to get correct user and system times from getrusage/wait/time(1)).
1697 * This could be removed if we avoid pthread_detach() and use pthread_join().
1699 #ifndef PLATFORM_WIN32
1706 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1708 MonoThread *thread=(MonoThread *)value;
1709 guint32 self=GPOINTER_TO_UINT (user);
1711 if(thread->tid!=self) {
1712 /*TerminateThread (thread->handle, -1);*/
1716 void mono_thread_abort_all_other_threads (void)
1718 guint32 self=GetCurrentThreadId ();
1720 EnterCriticalSection (&threads_mutex);
1722 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1723 mono_g_hash_table_size (threads));
1724 mono_g_hash_table_foreach (threads, print_tids, NULL);
1727 mono_g_hash_table_foreach (threads, terminate_thread,
1728 GUINT_TO_POINTER (self));
1730 LeaveCriticalSection (&threads_mutex);
1734 * mono_thread_push_appdomain_ref:
1736 * Register that the current thread may have references to objects in domain
1737 * @domain on its stack. Each call to this function should be paired with a
1738 * call to pop_appdomain_ref.
1741 mono_thread_push_appdomain_ref (MonoDomain *domain)
1743 MonoThread *thread = mono_thread_current ();
1746 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1747 EnterCriticalSection (&threads_mutex);
1748 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1749 LeaveCriticalSection (&threads_mutex);
1754 mono_thread_pop_appdomain_ref (void)
1756 MonoThread *thread = mono_thread_current ();
1759 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1760 EnterCriticalSection (&threads_mutex);
1761 /* FIXME: How can the list be empty ? */
1762 if (thread->appdomain_refs)
1763 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1764 LeaveCriticalSection (&threads_mutex);
1769 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1772 EnterCriticalSection (&threads_mutex);
1773 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1774 LeaveCriticalSection (&threads_mutex);
1778 typedef struct abort_appdomain_data {
1779 struct wait_data wait;
1781 } abort_appdomain_data;
1784 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1786 MonoThread *thread = (MonoThread*)value;
1787 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1788 MonoDomain *domain = data->domain;
1790 if (mono_thread_has_appdomain_ref (thread, domain)) {
1791 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1792 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1796 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1798 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1799 data->wait.handles [data->wait.num] = handle;
1800 data->wait.threads [data->wait.num] = thread;
1803 /* Just ignore the rest, we can't do anything with
1811 * mono_threads_abort_appdomain_threads:
1813 * Abort threads which has references to the given appdomain.
1816 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1818 abort_appdomain_data user_data;
1821 /* printf ("ABORT BEGIN.\n"); */
1823 start_time = GetTickCount ();
1825 EnterCriticalSection (&threads_mutex);
1827 user_data.domain = domain;
1828 user_data.wait.num = 0;
1829 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1830 LeaveCriticalSection (&threads_mutex);
1832 if (user_data.wait.num > 0)
1833 wait_for_tids (&user_data.wait, timeout);
1835 /* Update remaining time */
1836 timeout -= GetTickCount () - start_time;
1837 start_time = GetTickCount ();
1842 while (user_data.wait.num > 0);
1844 /* printf ("ABORT DONE.\n"); */
1850 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1852 MonoThread *thread = (MonoThread*)value;
1853 MonoDomain *domain = (MonoDomain*)user_data;
1856 /* No locking needed here */
1858 if (thread->culture_info) {
1859 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1860 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1861 thread->culture_info [i] = NULL;
1864 if (thread->ui_culture_info) {
1865 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1866 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1867 thread->ui_culture_info [i] = NULL;
1873 * mono_threads_clear_cached_culture:
1875 * Clear the cached_current_culture from all threads if it is in the
1879 mono_threads_clear_cached_culture (MonoDomain *domain)
1881 EnterCriticalSection (&threads_mutex);
1882 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1883 LeaveCriticalSection (&threads_mutex);
1887 * mono_thread_get_pending_exception:
1889 * Return an exception which needs to be raised when leaving a catch clause.
1890 * This is used for undeniable exception propagation.
1893 mono_thread_get_pending_exception (void)
1895 MonoThread *thread = mono_thread_current ();
1897 MONO_ARCH_SAVE_REGS;
1899 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1901 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1902 * exception if the thread no longer references a dying appdomain.
1904 thread->abort_exc->trace_ips = NULL;
1905 thread->abort_exc->stack_trace = NULL;
1906 return thread->abort_exc;
1912 #define NUM_STATIC_DATA_IDX 8
1913 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1914 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1919 * mono_alloc_static_data
1921 * Allocate memory blocks for storing threads or context static data
1924 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1926 guint idx = (offset >> 24) - 1;
1929 gpointer* static_data = *static_data_ptr;
1932 static_data = GC_MALLOC (static_data_size [0]);
1934 static_data = g_malloc0 (static_data_size [0]);
1936 *static_data_ptr = static_data;
1937 static_data [0] = static_data;
1940 for (i = 1; i < idx; ++i) {
1941 if (static_data [i])
1944 static_data [i] = GC_MALLOC (static_data_size [i]);
1946 static_data [i] = g_malloc0 (static_data_size [i]);
1952 * mono_init_static_data_info
1954 * Initializes static data counters
1956 static void mono_init_static_data_info (StaticDataInfo *static_data)
1958 static_data->idx = 0;
1959 static_data->offset = 0;
1963 * mono_alloc_static_data_slot
1965 * Generates an offset for static data. static_data contains the counters
1966 * used to generate it.
1969 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
1973 if (!static_data->idx && !static_data->offset) {
1975 * we use the first chunk of the first allocation also as
1976 * an array for the rest of the data
1978 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
1980 static_data->offset += align - 1;
1981 static_data->offset &= ~(align - 1);
1982 if (static_data->offset + size >= static_data_size [static_data->idx]) {
1983 static_data->idx ++;
1984 g_assert (size <= static_data_size [static_data->idx]);
1986 * massive unloading and reloading of domains with thread-static
1987 * data may eventually exceed the allocated storage...
1988 * Need to check what the MS runtime does in that case.
1989 * Note that for each appdomain, we need to allocate a separate
1990 * thread data slot for security reasons. We could keep track
1991 * of the slots per-domain and when the domain is unloaded
1992 * out the slots on a sort of free list.
1994 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
1995 static_data->offset = 0;
1997 offset = static_data->offset | ((static_data->idx + 1) << 24);
1998 static_data->offset += size;
2003 * ensure thread static fields already allocated are valid for thread
2004 * This function is called when a thread is created or on thread attach.
2007 thread_adjust_static_data (MonoThread *thread)
2011 EnterCriticalSection (&threads_mutex);
2012 if (thread_static_info.offset || thread_static_info.idx > 0) {
2013 /* get the current allocated size */
2014 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2015 mono_alloc_static_data (&(thread->static_data), offset);
2017 LeaveCriticalSection (&threads_mutex);
2021 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2023 MonoThread *thread = value;
2024 guint32 offset = GPOINTER_TO_UINT (user);
2026 mono_alloc_static_data (&(thread->static_data), offset);
2030 * The offset for a special static variable is composed of three parts:
2031 * a bit that indicates the type of static data (0:thread, 1:context),
2032 * an index in the array of chunks of memory for the thread (thread->static_data)
2033 * and an offset in that chunk of mem. This allows allocating less memory in the
2038 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2041 if (static_type == SPECIAL_STATIC_THREAD)
2043 EnterCriticalSection (&threads_mutex);
2044 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2045 /* This can be called during startup */
2046 if (threads != NULL)
2047 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2048 LeaveCriticalSection (&threads_mutex);
2052 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2053 EnterCriticalSection (&contexts_mutex);
2054 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2055 LeaveCriticalSection (&contexts_mutex);
2056 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2062 mono_get_special_static_data (guint32 offset)
2064 /* The high bit means either thread (0) or static (1) data. */
2066 guint32 static_type = (offset & 0x80000000);
2069 offset &= 0x7fffffff;
2070 idx = (offset >> 24) - 1;
2072 if (static_type == 0)
2074 MonoThread *thread = mono_thread_current ();
2075 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2079 /* Allocate static data block under demand, since we don't have a list
2082 MonoAppContext *context = mono_context_get ();
2083 if (!context->static_data || !context->static_data [idx]) {
2084 EnterCriticalSection (&contexts_mutex);
2085 mono_alloc_static_data (&(context->static_data), offset);
2086 LeaveCriticalSection (&contexts_mutex);
2088 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2092 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2094 MonoThread *thread=(MonoThread *)value;
2095 guint32 self=GPOINTER_TO_UINT (user);
2098 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2101 if(thread->tid==self)
2104 SuspendThread (thread->handle);
2107 void mono_gc_stop_world (void)
2109 guint32 self=GetCurrentThreadId ();
2112 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2115 EnterCriticalSection (&threads_mutex);
2117 if (threads != NULL)
2118 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2120 LeaveCriticalSection (&threads_mutex);
2123 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2125 MonoThread *thread=(MonoThread *)value;
2126 guint32 self=GPOINTER_TO_UINT (user);
2129 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2132 if(thread->tid==self)
2135 ResumeThread (thread->handle);
2138 void mono_gc_start_world (void)
2140 guint32 self=GetCurrentThreadId ();
2143 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2146 EnterCriticalSection (&threads_mutex);
2148 if (threads != NULL)
2149 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2151 LeaveCriticalSection (&threads_mutex);
2155 static guint32 dummy_apc (gpointer param)
2161 * mono_thread_execute_interruption
2163 * Performs the operation that the requested thread state requires (abort,
2166 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2168 mono_monitor_enter (thread->synch_lock);
2170 if (thread->interruption_requested) {
2171 /* this will consume pending APC calls */
2172 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2173 EnterCriticalSection (&interruption_mutex);
2174 thread_interruption_requested--;
2175 LeaveCriticalSection (&interruption_mutex);
2176 thread->interruption_requested = FALSE;
2179 if ((thread->state & ThreadState_AbortRequested) != 0) {
2180 if (thread->abort_exc == NULL)
2181 thread->abort_exc = mono_get_exception_thread_abort ();
2182 mono_monitor_exit (thread->synch_lock);
2183 return thread->abort_exc;
2185 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2186 thread->state &= ~ThreadState_SuspendRequested;
2187 thread->state |= ThreadState_Suspended;
2188 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2189 mono_monitor_exit (thread->synch_lock);
2191 WaitForSingleObject (thread->suspend_event, INFINITE);
2193 mono_monitor_enter (thread->synch_lock);
2194 CloseHandle (thread->suspend_event);
2195 thread->suspend_event = NULL;
2196 thread->state &= ~ThreadState_Suspended;
2198 /* The thread that requested the resume will have replaced this event
2199 * and will be waiting for it
2201 SetEvent (thread->resume_event);
2202 mono_monitor_exit (thread->synch_lock);
2205 else if ((thread->state & ThreadState_StopRequested) != 0) {
2206 /* FIXME: do this through the JIT? */
2207 mono_monitor_exit (thread->synch_lock);
2208 mono_thread_exit ();
2212 mono_monitor_exit (thread->synch_lock);
2217 * mono_thread_request_interruption
2219 * A signal handler can call this method to request the interruption of a
2220 * thread. The result of the interruption will depend on the current state of
2221 * the thread. If the result is an exception that needs to be throw, it is
2222 * provided as return value.
2224 MonoException* mono_thread_request_interruption (gboolean running_managed)
2226 MonoThread *thread = mono_thread_current ();
2228 /* The thread may already be stopping */
2232 mono_monitor_enter (thread->synch_lock);
2234 if (thread->interruption_requested) {
2235 mono_monitor_exit (thread->synch_lock);
2239 if (!running_managed || is_running_protected_wrapper ()) {
2240 /* Can't stop while in unmanaged code. Increase the global interruption
2241 request count. When exiting the unmanaged method the count will be
2242 checked and the thread will be interrupted. */
2244 EnterCriticalSection (&interruption_mutex);
2245 thread_interruption_requested++;
2246 LeaveCriticalSection (&interruption_mutex);
2248 thread->interruption_requested = TRUE;
2249 mono_monitor_exit (thread->synch_lock);
2251 /* this will awake the thread if it is in WaitForSingleObject
2253 QueueUserAPC (dummy_apc, thread->handle, NULL);
2258 mono_monitor_exit (thread->synch_lock);
2259 return mono_thread_execute_interruption (thread);
2263 gboolean mono_thread_interruption_requested ()
2265 if (thread_interruption_requested) {
2266 MonoThread *thread = mono_thread_current ();
2267 /* The thread may already be stopping */
2269 return (thread->interruption_requested);
2274 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2276 MonoThread *thread = mono_thread_current ();
2278 /* The thread may already be stopping */
2282 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2283 MonoException* exc = mono_thread_execute_interruption (thread);
2284 if (exc) mono_raise_exception (exc);
2289 * Performs the interruption of the current thread, if one has been requested,
2290 * and the thread is not running a protected wrapper.
2292 void mono_thread_interruption_checkpoint ()
2294 mono_thread_interruption_checkpoint_request (FALSE);
2298 * Performs the interruption of the current thread, if one has been requested.
2300 void mono_thread_force_interruption_checkpoint ()
2302 mono_thread_interruption_checkpoint_request (TRUE);
2306 * mono_thread_interruption_request_flag:
2308 * Returns the address of a flag that will be non-zero if an interruption has
2309 * been requested for a thread. The thread to interrupt may not be the current
2310 * thread, so an additional call to mono_thread_interruption_requested() or
2311 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2314 gint32* mono_thread_interruption_request_flag ()
2316 return &thread_interruption_requested;
2319 #ifdef WITH_INCLUDED_LIBGC
2321 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2323 MonoThread *thread=(MonoThread *)value;
2324 guint32 *selfp=(guint32 *)user, self = *selfp;
2327 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2330 if(thread->tid==self) {
2332 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2334 GC_push_all_stack (selfp, thread->stack_ptr);
2338 #ifdef PLATFORM_WIN32
2339 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2341 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2345 void mono_gc_push_all_stacks (void)
2347 guint32 self=GetCurrentThreadId ();
2350 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2353 EnterCriticalSection (&threads_mutex);
2355 if (threads != NULL)
2356 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2358 LeaveCriticalSection (&threads_mutex);
2361 #endif /* WITH_INCLUDED_LIBGC */