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 *);
59 /* Number of cached culture objects in the MonoThread->culture_info array */
60 #define NUM_CACHED_CULTURES 4
63 * The "os_handle" field of the WaitHandle class.
65 static MonoClassField *wait_handle_os_handle_field = NULL;
67 /* Controls access to the 'threads' hash table */
68 static CRITICAL_SECTION threads_mutex;
70 /* Controls access to context static data */
71 static CRITICAL_SECTION contexts_mutex;
73 /* Holds current status of static data heap */
74 static StaticDataInfo thread_static_info;
75 static StaticDataInfo context_static_info;
77 /* The hash of existing threads (key is thread ID) that need joining
80 static MonoGHashTable *threads=NULL;
82 /* The TLS key that holds the MonoObject assigned to each thread */
83 static guint32 current_object_key = -1;
86 /* we need to use both the Tls* functions and __thread because
87 * the gc needs to see all the threads
89 static __thread MonoThread * tls_current_object;
90 #define SET_CURRENT_OBJECT(x) do { \
91 tls_current_object = x; \
92 TlsSetValue (current_object_key, x); \
94 #define GET_CURRENT_OBJECT() tls_current_object
96 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
97 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
100 /* function called at thread start */
101 static MonoThreadStartCB mono_thread_start_cb = NULL;
103 /* function called at thread attach */
104 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
106 /* function called at thread cleanup */
107 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
109 /* function called when a new thread has been created */
110 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
112 /* The TLS key that holds the LocalDataStoreSlot hash in each thread */
113 static guint32 slothash_key = -1;
115 /* The default stack size for each thread */
116 static guint32 default_stacksize = 0;
117 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
119 static void thread_adjust_static_data (MonoThread *thread);
120 static void mono_init_static_data_info (StaticDataInfo *static_data);
121 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
123 /* Spin lock for InterlockedXXX 64 bit functions */
124 static CRITICAL_SECTION interlocked_mutex;
126 /* Controls access to interruption flag */
127 static CRITICAL_SECTION interruption_mutex;
129 /* global count of thread interruptions requested */
130 static gint32 thread_interruption_requested = 0;
133 mono_thread_get_tls_key (void)
135 return current_object_key;
138 /* handle_store() and handle_remove() manage the array of threads that
139 * still need to be waited for when the main thread exits.
141 static void handle_store(MonoThread *thread)
143 EnterCriticalSection(&threads_mutex);
146 g_message(G_GNUC_PRETTY_FUNCTION ": thread %p ID %d", thread,
151 MONO_GC_REGISTER_ROOT (threads);
152 threads=mono_g_hash_table_new(NULL, NULL);
155 /* We don't need to duplicate thread->handle, because it is
156 * only closed when the thread object is finalized by the GC.
158 mono_g_hash_table_insert(threads, GUINT_TO_POINTER(thread->tid), thread);
159 LeaveCriticalSection(&threads_mutex);
162 static void handle_remove(guint32 tid)
165 g_message(G_GNUC_PRETTY_FUNCTION ": thread ID %d", tid);
168 EnterCriticalSection(&threads_mutex);
171 mono_g_hash_table_remove (threads, GUINT_TO_POINTER(tid));
173 LeaveCriticalSection(&threads_mutex);
175 /* Don't close the handle here, wait for the object finalizer
176 * to do it. Otherwise, the following race condition applies:
178 * 1) Thread exits (and handle_remove() closes the handle)
180 * 2) Some other handle is reassigned the same slot
182 * 3) Another thread tries to join the first thread, and
183 * blocks waiting for the reassigned handle to be signalled
184 * (which might never happen). This is possible, because the
185 * thread calling Join() still has a reference to the first
190 static void thread_cleanup (MonoThread *thread)
192 mono_release_type_locks (thread);
194 if (!mono_monitor_enter (thread->synch_lock))
197 thread->state |= ThreadState_Stopped;
198 mono_monitor_exit (thread->synch_lock);
200 mono_profiler_thread_end (thread->tid);
201 handle_remove (thread->tid);
203 mono_thread_pop_appdomain_ref ();
205 if (thread->serialized_culture_info)
206 g_free (thread->serialized_culture_info);
208 #ifndef HAVE_BOEHM_GC
209 if (thread->culture_info)
210 g_free (thread->culture_info);
211 if (thread->ui_culture_info)
212 g_free (thread->ui_culture_info);
215 if (mono_thread_cleanup)
216 mono_thread_cleanup (thread);
219 static guint32 start_wrapper(void *data)
221 struct StartInfo *start_info=(struct StartInfo *)data;
222 guint32 (*start_func)(void *);
225 MonoThread *thread=start_info->obj;
226 MonoObject *start_delegate = start_info->delegate;
227 MonoObject *start_obj = start_info->start_arg;
230 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper",
231 GetCurrentThreadId ());
234 /* We can be sure start_info->obj->tid and
235 * start_info->obj->handle have been set, because the thread
236 * was created suspended, and these values were set before the
242 SET_CURRENT_OBJECT (thread);
244 if (!mono_domain_set (start_info->domain, FALSE)) {
245 /* No point in raising an appdomain_unloaded exception here */
246 /* FIXME: Cleanup here */
250 start_func = start_info->func;
251 start_arg = start_info->start_arg;
253 /* This MUST be called before any managed code can be
254 * executed, as it calls the callback function that (for the
255 * jit) sets the lmf marker.
257 mono_thread_new_init (tid, &tid, start_func);
258 thread->stack_ptr = &tid;
261 g_message (G_GNUC_PRETTY_FUNCTION
262 ": (%d,%d) Setting thread stack to %p",
263 GetCurrentThreadId (), getpid (), thread->stack_ptr);
267 g_message (G_GNUC_PRETTY_FUNCTION
268 ": (%d) Setting current_object_key to %p",
269 GetCurrentThreadId (), thread);
272 mono_profiler_thread_start (tid);
274 if(thread->start_notify!=NULL) {
275 /* Let the thread that called Start() know we're
278 ReleaseSemaphore (thread->start_notify, 1, NULL);
283 /* Every thread references the appdomain which created it */
284 mono_thread_push_appdomain_ref (mono_domain_get ());
286 thread_adjust_static_data (thread);
288 g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
291 /* start_func is set only for unamanged start functions */
293 start_func (start_arg);
296 g_assert (start_delegate != NULL);
297 args [0] = start_arg;
298 /* we may want to handle the exception here. See comment below on unhandled exceptions */
299 mono_runtime_delegate_invoke (start_delegate, args, NULL);
301 #ifdef PLATFORM_WIN32
302 /* If the thread calls ExitThread at all, this remaining code
303 * will not be executed, but the main thread will eventually
304 * call thread_cleanup() on this thread's behalf.
308 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Start wrapper terminating",
309 GetCurrentThreadId ());
312 /* Remove the reference to the thread object in the TLS data,
313 * so the thread object can be finalized. This won't be
314 * reached if the thread threw an uncaught exception, so those
315 * thread handles will stay referenced :-( (This is due to
316 * missing support for scanning thread-specific data in the
317 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
320 SET_CURRENT_OBJECT (NULL);
323 thread_cleanup (thread);
328 void mono_thread_new_init (guint32 tid, gpointer stack_start, gpointer func)
330 if (mono_thread_start_cb) {
331 mono_thread_start_cb (tid, stack_start, func);
334 if (mono_thread_callbacks)
335 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
338 void mono_threads_set_default_stacksize (guint32 stacksize)
340 default_stacksize = stacksize;
343 guint32 mono_threads_get_default_stacksize (void)
345 return default_stacksize;
348 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
351 HANDLE thread_handle;
352 struct StartInfo *start_info;
355 thread=(MonoThread *)mono_object_new (domain,
356 mono_defaults.thread_class);
358 start_info=g_new0 (struct StartInfo, 1);
359 start_info->func = func;
360 start_info->obj = thread;
361 start_info->domain = domain;
362 start_info->start_arg = arg;
364 /* Create suspended, so we can do some housekeeping before the thread
367 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
368 thread_handle = GC_CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
369 CREATE_SUSPENDED, &tid);
371 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), start_wrapper, start_info,
372 CREATE_SUSPENDED, &tid);
375 g_message(G_GNUC_PRETTY_FUNCTION ": Started thread ID %d (handle %p)",
378 g_assert (thread_handle);
380 thread->handle=thread_handle;
383 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
385 handle_store(thread);
387 ResumeThread (thread_handle);
391 mono_thread_attach (MonoDomain *domain)
394 HANDLE thread_handle;
397 if ((thread = mono_thread_current ())) {
398 /* Already attached */
402 thread = (MonoThread *)mono_object_new (domain,
403 mono_defaults.thread_class);
405 thread_handle = GetCurrentThread ();
406 g_assert (thread_handle);
408 tid=GetCurrentThreadId ();
410 #ifdef PLATFORM_WIN32
412 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
413 * refer to the thread from other threads for things like aborting.
415 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
416 THREAD_ALL_ACCESS, TRUE, 0);
419 thread->handle=thread_handle;
421 thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
424 g_message(G_GNUC_PRETTY_FUNCTION ": Attached thread ID %d (handle %p)",
428 handle_store(thread);
431 g_message (G_GNUC_PRETTY_FUNCTION
432 ": (%d) Setting current_object_key to %p",
433 GetCurrentThreadId (), thread);
436 SET_CURRENT_OBJECT (thread);
437 mono_domain_set (domain, TRUE);
439 thread_adjust_static_data (thread);
441 if (mono_thread_attach_cb) {
442 mono_thread_attach_cb (tid, &tid);
449 mono_thread_detach (MonoThread *thread)
451 g_return_if_fail (thread != NULL);
454 g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
456 SET_CURRENT_OBJECT (NULL);
458 thread_cleanup (thread);
464 MonoThread *thread = mono_thread_current ();
466 SET_CURRENT_OBJECT (NULL);
467 thread_cleanup (thread);
469 /* we could add a callback here for embedders to use. */
470 if (thread == mono_thread_get_main ())
471 exit (mono_environment_exitcode_get ());
475 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
478 MonoMulticastDelegate *delegate = (MonoMulticastDelegate*)start;
479 guint32 (*start_func)(void *);
480 struct StartInfo *start_info;
488 g_message(G_GNUC_PRETTY_FUNCTION
489 ": Trying to start a new thread: this (%p) start (%p)",
493 /* FIXME: remove the code inside BROKEN_THREAD_START once martin gets rid of the
494 * thread_start_compile_func stuff.
496 #define BROKEN_THREAD_START
497 #ifdef BROKEN_THREAD_START
498 im = mono_get_delegate_invoke (start->vtable->klass);
499 im = mono_marshal_get_delegate_invoke (im);
500 if (mono_thread_callbacks)
501 start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
503 start_func = mono_compile_method (im);
505 if(start_func==NULL) {
506 g_warning(G_GNUC_PRETTY_FUNCTION
507 ": Can't locate start method!");
514 /* This is freed in start_wrapper */
515 start_info = g_new0 (struct StartInfo, 1);
516 start_info->func = start_func;
517 #ifdef BROKEN_THREAD_START
518 start_info->start_arg = start;
520 start_info->start_arg = this->start_obj;
522 start_info->delegate = start;
523 start_info->obj = this;
524 start_info->domain = mono_domain_get ();
526 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
527 if(this->start_notify==NULL) {
528 g_warning (G_GNUC_PRETTY_FUNCTION ": CreateSemaphore error 0x%x", GetLastError ());
532 #if defined(PLATFORM_WIN32) && defined(HAVE_BOEHM_GC)
533 thread=GC_CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
534 CREATE_SUSPENDED, &tid);
536 thread=CreateThread(NULL, default_stacksize_for_thread (this), start_wrapper, start_info,
537 CREATE_SUSPENDED, &tid);
540 g_warning(G_GNUC_PRETTY_FUNCTION
541 ": CreateThread error 0x%x", GetLastError());
548 /* Don't call handle_store() here, delay it to Start.
549 * We can't join a thread (trying to will just block
550 * forever) until it actually starts running, so don't
551 * store the handle till then.
555 g_message(G_GNUC_PRETTY_FUNCTION
556 ": Started thread ID %d (handle %p)", tid, thread);
563 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
569 g_message (G_GNUC_PRETTY_FUNCTION ": Closing thread %p, handle %p",
573 CloseHandle (thread);
576 void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
582 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Launching thread %p (%d)",
583 GetCurrentThreadId (), this, this->tid);
586 /* Only store the handle when the thread is about to be
587 * launched, to avoid the main thread deadlocking while trying
588 * to clean up a thread that will never be signalled.
592 if (mono_thread_callbacks)
593 (* mono_thread_callbacks->start_resume) (this->tid);
595 ResumeThread(thread);
597 if (mono_thread_callbacks)
598 (* mono_thread_callbacks->end_resume) (this->tid);
600 if(this->start_notify!=NULL) {
601 /* Wait for the thread to set up its TLS data etc, so
602 * theres no potential race condition if someone tries
603 * to look up the data believing the thread has
608 g_message(G_GNUC_PRETTY_FUNCTION
609 ": (%d) waiting for thread %p (%d) to start",
610 GetCurrentThreadId (), this, this->tid);
613 WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
614 CloseHandle (this->start_notify);
615 this->start_notify=NULL;
619 g_message(G_GNUC_PRETTY_FUNCTION
620 ": (%d) Done launching thread %p (%d)",
621 GetCurrentThreadId (), this, this->tid);
625 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
627 MonoThread *thread = mono_thread_current ();
632 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
635 mono_monitor_enter (thread->synch_lock);
636 thread->state |= ThreadState_WaitSleepJoin;
637 mono_monitor_exit (thread->synch_lock);
641 mono_monitor_enter (thread->synch_lock);
642 thread->state &= ~ThreadState_WaitSleepJoin;
643 mono_monitor_exit (thread->synch_lock);
647 ves_icall_System_Threading_Thread_GetDomainID (void)
651 return mono_domain_get()->domain_id;
655 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
660 return mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
664 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
667 g_free (this_obj->name);
669 this_obj->name = g_new (gunichar2, mono_string_length (name));
670 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
671 this_obj->name_len = mono_string_length (name);
674 this_obj->name = NULL;
678 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
684 /* No need to lock here */
685 if (this->culture_info) {
686 domain = mono_domain_get ();
687 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
688 res = this->culture_info [i];
689 if (res && res->vtable->domain == domain)
698 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
702 mono_monitor_enter (this->synch_lock);
703 if (this->serialized_culture_info) {
704 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
705 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
709 mono_monitor_exit (this->synch_lock);
715 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
718 MonoDomain *domain = mono_domain_get ();
720 mono_monitor_enter (this->synch_lock);
721 if (!this->culture_info) {
723 this->culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
725 this->culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
729 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
730 if (this->culture_info [i]) {
731 if (this->culture_info [i]->vtable->domain == domain)
739 if (i < NUM_CACHED_CULTURES)
740 this->culture_info [i] = culture;
741 mono_monitor_exit (this->synch_lock);
745 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
747 mono_monitor_enter (this->synch_lock);
748 if (this->serialized_culture_info)
749 g_free (this->serialized_culture_info);
750 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
751 this->serialized_culture_info_len = mono_array_length (arr);
752 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
753 mono_monitor_exit (this->synch_lock);
758 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
764 /* No need to lock here */
765 if (this->ui_culture_info) {
766 domain = mono_domain_get ();
767 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
768 res = this->ui_culture_info [i];
769 if (res && res->vtable->domain == domain)
778 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
782 mono_monitor_enter (this->synch_lock);
783 if (this->serialized_ui_culture_info) {
784 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
785 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
789 mono_monitor_exit (this->synch_lock);
795 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
798 MonoDomain *domain = mono_domain_get ();
800 mono_monitor_enter (this->synch_lock);
801 if (!this->ui_culture_info) {
803 this->ui_culture_info = GC_MALLOC (sizeof (MonoObject*) * NUM_CACHED_CULTURES);
805 this->ui_culture_info = g_new0 (MonoObject*, NUM_CACHED_CULTURES);
809 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
810 if (this->ui_culture_info [i]) {
811 if (this->ui_culture_info [i]->vtable->domain == domain)
819 if (i < NUM_CACHED_CULTURES)
820 this->ui_culture_info [i] = culture;
821 mono_monitor_exit (this->synch_lock);
825 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
827 mono_monitor_enter (this->synch_lock);
828 if (this->serialized_ui_culture_info)
829 g_free (this->serialized_ui_culture_info);
830 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
831 this->serialized_ui_culture_info_len = mono_array_length (arr);
832 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
833 mono_monitor_exit (this->synch_lock);
836 /* the jit may read the compiled code of this function */
838 mono_thread_current (void)
843 thread = GET_CURRENT_OBJECT ();
844 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", thread);
848 return GET_CURRENT_OBJECT ();
852 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
853 int ms, HANDLE thread)
859 mono_monitor_enter (this->synch_lock);
860 this->state |= ThreadState_WaitSleepJoin;
861 mono_monitor_exit (this->synch_lock);
867 g_message (G_GNUC_PRETTY_FUNCTION ": joining thread handle %p, %d ms",
871 ret=WaitForSingleObjectEx (thread, ms, TRUE);
873 mono_monitor_enter (this->synch_lock);
874 this->state &= ~ThreadState_WaitSleepJoin;
875 mono_monitor_exit (this->synch_lock);
877 if(ret==WAIT_OBJECT_0) {
879 g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
886 g_message (G_GNUC_PRETTY_FUNCTION ": join failed");
892 void ves_icall_System_Threading_Thread_SlotHash_store(MonoObject *data)
897 g_message(G_GNUC_PRETTY_FUNCTION ": Storing key %p", data);
900 /* Object location stored here */
901 TlsSetValue(slothash_key, data);
904 MonoObject *ves_icall_System_Threading_Thread_SlotHash_lookup(void)
910 data=TlsGetValue(slothash_key);
913 g_message(G_GNUC_PRETTY_FUNCTION ": Retrieved key %p", data);
919 /* FIXME: exitContext isnt documented */
920 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
926 MonoObject *waitHandle;
928 MonoThread *thread = mono_thread_current ();
932 numhandles = mono_array_length(mono_handles);
933 handles = g_new0(HANDLE, numhandles);
935 if (wait_handle_os_handle_field == 0) {
936 /* Get the field os_handle which will contain the actual handle */
937 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
938 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
941 for(i = 0; i < numhandles; i++) {
942 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
943 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
950 mono_monitor_enter (thread->synch_lock);
951 thread->state |= ThreadState_WaitSleepJoin;
952 mono_monitor_exit (thread->synch_lock);
954 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
956 mono_monitor_enter (thread->synch_lock);
957 thread->state &= ~ThreadState_WaitSleepJoin;
958 mono_monitor_exit (thread->synch_lock);
962 if(ret==WAIT_FAILED) {
963 #ifdef THREAD_WAIT_DEBUG
964 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
965 GetCurrentThreadId ());
968 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
969 /* Do we want to try again if we get
970 * WAIT_IO_COMPLETION? The documentation for
971 * WaitHandle doesn't give any clues. (We'd have to
972 * fiddle with the timeout if we retry.)
974 #ifdef THREAD_WAIT_DEBUG
975 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
976 GetCurrentThreadId ());
984 /* FIXME: exitContext isnt documented */
985 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
991 MonoObject *waitHandle;
993 MonoThread *thread = mono_thread_current ();
997 numhandles = mono_array_length(mono_handles);
998 handles = g_new0(HANDLE, numhandles);
1000 if (wait_handle_os_handle_field == 0) {
1001 /* Get the field os_handle which will contain the actual handle */
1002 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
1003 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
1006 for(i = 0; i < numhandles; i++) {
1007 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1008 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
1015 mono_monitor_enter (thread->synch_lock);
1016 thread->state |= ThreadState_WaitSleepJoin;
1017 mono_monitor_exit (thread->synch_lock);
1019 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1021 mono_monitor_enter (thread->synch_lock);
1022 thread->state &= ~ThreadState_WaitSleepJoin;
1023 mono_monitor_exit (thread->synch_lock);
1027 #ifdef THREAD_WAIT_DEBUG
1028 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
1029 GetCurrentThreadId (), ret);
1033 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1035 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1036 return ret - WAIT_OBJECT_0;
1038 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1039 return ret - WAIT_ABANDONED_0;
1046 /* FIXME: exitContext isnt documented */
1047 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1050 MonoThread *thread = mono_thread_current ();
1052 MONO_ARCH_SAVE_REGS;
1054 #ifdef THREAD_WAIT_DEBUG
1055 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) waiting for %p, %d ms",
1056 GetCurrentThreadId (), handle, ms);
1063 mono_monitor_enter (thread->synch_lock);
1064 thread->state |= ThreadState_WaitSleepJoin;
1065 mono_monitor_exit (thread->synch_lock);
1067 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1069 mono_monitor_enter (thread->synch_lock);
1070 thread->state &= ~ThreadState_WaitSleepJoin;
1071 mono_monitor_exit (thread->synch_lock);
1073 if(ret==WAIT_FAILED) {
1074 #ifdef THREAD_WAIT_DEBUG
1075 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
1076 GetCurrentThreadId ());
1079 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1080 /* Do we want to try again if we get
1081 * WAIT_IO_COMPLETION? The documentation for
1082 * WaitHandle doesn't give any clues. (We'd have to
1083 * fiddle with the timeout if we retry.)
1085 #ifdef THREAD_WAIT_DEBUG
1086 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
1087 GetCurrentThreadId ());
1095 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1099 MONO_ARCH_SAVE_REGS;
1104 mutex = CreateMutex (NULL, owned, NULL);
1106 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1108 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1116 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1117 MONO_ARCH_SAVE_REGS;
1119 ReleaseMutex(handle);
1122 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name) {
1123 MONO_ARCH_SAVE_REGS;
1125 return(CreateEvent (NULL, manual, initial,
1126 name==NULL?NULL:mono_string_chars (name)));
1129 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1130 MONO_ARCH_SAVE_REGS;
1132 return (SetEvent(handle));
1135 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1136 MONO_ARCH_SAVE_REGS;
1138 return (ResetEvent(handle));
1142 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1143 MONO_ARCH_SAVE_REGS;
1145 CloseHandle (handle);
1148 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1150 MONO_ARCH_SAVE_REGS;
1152 return InterlockedIncrement (location);
1155 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1159 MONO_ARCH_SAVE_REGS;
1161 EnterCriticalSection(&interlocked_mutex);
1165 LeaveCriticalSection(&interlocked_mutex);
1171 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1173 MONO_ARCH_SAVE_REGS;
1175 return InterlockedDecrement(location);
1178 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1182 MONO_ARCH_SAVE_REGS;
1184 EnterCriticalSection(&interlocked_mutex);
1188 LeaveCriticalSection(&interlocked_mutex);
1193 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location1, gint32 value)
1195 MONO_ARCH_SAVE_REGS;
1197 return InterlockedExchange(location1, value);
1200 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location1, MonoObject *value)
1202 MONO_ARCH_SAVE_REGS;
1204 return (MonoObject *) InterlockedExchangePointer((gpointer *) location1, value);
1207 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location1, gfloat value)
1209 IntFloatUnion val, ret;
1211 MONO_ARCH_SAVE_REGS;
1214 ret.ival = InterlockedExchange((gint32 *) location1, val.ival);
1219 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location1, gint32 value, gint32 comparand)
1221 MONO_ARCH_SAVE_REGS;
1223 return InterlockedCompareExchange(location1, value, comparand);
1226 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location1, MonoObject *value, MonoObject *comparand)
1228 MONO_ARCH_SAVE_REGS;
1230 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location1, value, comparand);
1233 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location1, gfloat value, gfloat comparand)
1235 IntFloatUnion val, ret, cmp;
1237 MONO_ARCH_SAVE_REGS;
1240 cmp.fval = comparand;
1241 ret.ival = InterlockedCompareExchange((gint32 *) location1, val.ival, cmp.ival);
1247 mono_thread_get_abort_signal (void)
1257 #endif /* __MINGW32__ */
1261 static CALLBACK void interruption_request_apc (ULONG_PTR param)
1263 MonoException* exc = mono_thread_request_interruption (FALSE);
1264 if (exc) mono_raise_exception (exc);
1267 #endif /* __MINGW32__ */
1270 * signal_thread_state_change
1272 * Tells the thread that his state has changed and it has to enter the new
1273 * state as soon as possible.
1275 static void signal_thread_state_change (MonoThread *thread)
1277 if (thread == mono_thread_current ()) {
1278 /* Do it synchronously */
1279 MonoException *exc = mono_thread_request_interruption (FALSE);
1281 mono_raise_exception (exc);
1285 QueueUserAPC (interruption_request_apc, thread->handle, NULL);
1287 /* fixme: store the state somewhere */
1288 #ifdef PTHREAD_POINTER_ID
1289 pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
1291 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1293 #endif /* __MINGW32__ */
1297 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1299 MONO_ARCH_SAVE_REGS;
1301 mono_monitor_enter (thread->synch_lock);
1303 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1304 (thread->state & ThreadState_StopRequested) != 0)
1306 mono_monitor_exit (thread->synch_lock);
1310 thread->state |= ThreadState_AbortRequested;
1311 thread->abort_state = state;
1312 thread->abort_exc = NULL;
1314 mono_monitor_exit (thread->synch_lock);
1317 g_message (G_GNUC_PRETTY_FUNCTION
1318 ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
1319 thread, thread->tid);
1322 /* Make sure the thread is awake */
1323 ves_icall_System_Threading_Thread_Resume (thread);
1325 signal_thread_state_change (thread);
1329 ves_icall_System_Threading_Thread_ResetAbort (void)
1331 MonoThread *thread = mono_thread_current ();
1333 MONO_ARCH_SAVE_REGS;
1335 mono_monitor_enter (thread->synch_lock);
1337 thread->state &= ~ThreadState_AbortRequested;
1339 if (!thread->abort_exc) {
1340 const char *msg = "Unable to reset abort because no abort was requested";
1341 mono_monitor_exit (thread->synch_lock);
1342 mono_raise_exception (mono_get_exception_thread_state (msg));
1344 thread->abort_exc = NULL;
1345 thread->abort_state = NULL;
1348 mono_monitor_exit (thread->synch_lock);
1352 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1354 MONO_ARCH_SAVE_REGS;
1356 mono_monitor_enter (thread->synch_lock);
1358 if ((thread->state & ThreadState_Suspended) != 0 ||
1359 (thread->state & ThreadState_SuspendRequested) != 0 ||
1360 (thread->state & ThreadState_StopRequested) != 0)
1362 mono_monitor_exit (thread->synch_lock);
1366 thread->state |= ThreadState_SuspendRequested;
1367 mono_monitor_exit (thread->synch_lock);
1369 signal_thread_state_change (thread);
1373 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1375 MONO_ARCH_SAVE_REGS;
1377 mono_monitor_enter (thread->synch_lock);
1379 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1380 thread->state &= ~ThreadState_SuspendRequested;
1381 mono_monitor_exit (thread->synch_lock);
1385 if ((thread->state & ThreadState_Suspended) == 0)
1387 mono_monitor_exit (thread->synch_lock);
1391 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1393 /* Awake the thread */
1394 SetEvent (thread->suspend_event);
1396 mono_monitor_exit (thread->synch_lock);
1398 /* Wait for the thread to awake */
1399 WaitForSingleObject (thread->resume_event, INFINITE);
1400 CloseHandle (thread->resume_event);
1401 thread->resume_event = NULL;
1405 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1410 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1411 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1412 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1414 *((gboolean*)data) = TRUE;
1421 is_running_protected_wrapper (void)
1423 gboolean found = FALSE;
1424 mono_stack_walk (find_wrapper, &found);
1428 void mono_thread_stop (MonoThread *thread)
1430 mono_monitor_enter (thread->synch_lock);
1432 if ((thread->state & ThreadState_StopRequested) != 0 ||
1433 (thread->state & ThreadState_Stopped) != 0)
1435 mono_monitor_exit (thread->synch_lock);
1439 /* Make sure the thread is awake */
1440 ves_icall_System_Threading_Thread_Resume (thread);
1442 thread->state |= ThreadState_StopRequested;
1443 thread->state &= ~ThreadState_AbortRequested;
1445 mono_monitor_exit (thread->synch_lock);
1447 signal_thread_state_change (thread);
1451 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1453 return *((volatile gint8 *) (ptr));
1457 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1459 return *((volatile gint16 *) (ptr));
1463 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1465 return *((volatile gint32 *) (ptr));
1469 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1471 return *((volatile gint64 *) (ptr));
1475 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1477 return (void *) *((volatile void **) ptr);
1481 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1483 *((volatile gint8 *) ptr) = value;
1487 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1489 *((volatile gint16 *) ptr) = value;
1493 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1495 *((volatile gint32 *) ptr) = value;
1499 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1501 *((volatile gint64 *) ptr) = value;
1505 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1507 *((volatile void **) ptr) = value;
1510 void mono_thread_init (MonoThreadStartCB start_cb,
1511 MonoThreadAttachCB attach_cb)
1513 InitializeCriticalSection(&threads_mutex);
1514 InitializeCriticalSection(&interlocked_mutex);
1515 InitializeCriticalSection(&contexts_mutex);
1516 InitializeCriticalSection(&interruption_mutex);
1518 mono_init_static_data_info (&thread_static_info);
1519 mono_init_static_data_info (&context_static_info);
1521 current_object_key=TlsAlloc();
1523 g_message (G_GNUC_PRETTY_FUNCTION ": Allocated current_object_key %d",
1524 current_object_key);
1527 mono_thread_start_cb = start_cb;
1528 mono_thread_attach_cb = attach_cb;
1530 slothash_key=TlsAlloc();
1532 /* Get a pseudo handle to the current process. This is just a
1533 * kludge so that wapi can build a process handle if needed.
1534 * As a pseudo handle is returned, we don't need to clean
1537 GetCurrentProcess ();
1541 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1543 mono_thread_cleanup = func;
1546 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1548 mono_thread_callbacks = callbacks;
1552 static void print_tids (gpointer key, gpointer value, gpointer user)
1554 g_message ("Waiting for: %d", GPOINTER_TO_UINT(key));
1560 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1561 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1565 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1570 g_message(G_GNUC_PRETTY_FUNCTION
1571 ": %d threads to wait for in this batch", wait->num);
1574 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1576 if(ret==WAIT_FAILED) {
1577 /* See the comment in build_wait_tids() */
1579 g_message (G_GNUC_PRETTY_FUNCTION ": Wait failed");
1584 for(i=0; i<wait->num; i++)
1585 CloseHandle (wait->handles[i]);
1587 if (ret == WAIT_TIMEOUT)
1590 for(i=0; i<wait->num; i++) {
1591 guint32 tid=wait->threads[i]->tid;
1593 if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
1594 /* This thread must have been killed, because
1595 * it hasn't cleaned itself up. (It's just
1596 * possible that the thread exited before the
1597 * parent thread had a chance to store the
1598 * handle, and now there is another pointer to
1599 * the already-exited thread stored. In this
1600 * case, we'll just get two
1601 * mono_profiler_thread_end() calls for the
1606 g_message (G_GNUC_PRETTY_FUNCTION
1607 ": cleaning up after thread %d", tid);
1609 thread_cleanup (wait->threads[i]);
1614 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1616 struct wait_data *wait=(struct wait_data *)user;
1618 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1620 MonoThread *thread=(MonoThread *)value;
1622 /* Ignore background threads, we abort them later */
1623 if (thread->state & ThreadState_Background)
1624 return; /* just leave, ignore */
1626 if (mono_gc_is_finalizer_thread (thread))
1629 if (thread == mono_thread_current ())
1632 if (thread == mono_thread_get_main ())
1635 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1639 wait->handles[wait->num]=handle;
1640 wait->threads[wait->num]=thread;
1643 /* Just ignore the rest, we can't do anything with
1650 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1652 struct wait_data *wait=(struct wait_data *)user;
1653 guint32 self = GetCurrentThreadId ();
1654 MonoThread *thread = (MonoThread *) value;
1657 /* The finalizer thread is not a background thread */
1658 if (thread->tid != self && thread->state & ThreadState_Background) {
1660 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1664 wait->handles[wait->num]=thread->handle;
1665 wait->threads[wait->num]=thread;
1668 if(thread->state & ThreadState_AbortRequested ||
1669 thread->state & ThreadState_Aborted) {
1671 g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
1677 g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
1679 mono_thread_stop (thread);
1683 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1686 void mono_thread_manage (void)
1688 struct wait_data *wait=g_new0 (struct wait_data, 1);
1690 /* join each thread that's still running */
1692 g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
1695 EnterCriticalSection (&threads_mutex);
1698 g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
1700 LeaveCriticalSection (&threads_mutex);
1703 LeaveCriticalSection (&threads_mutex);
1706 EnterCriticalSection (&threads_mutex);
1708 g_message(G_GNUC_PRETTY_FUNCTION
1709 ":There are %d threads to join",
1710 mono_g_hash_table_size (threads));
1711 mono_g_hash_table_foreach (threads, print_tids, NULL);
1715 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
1716 LeaveCriticalSection (&threads_mutex);
1718 /* Something to wait for */
1719 wait_for_tids (wait, INFINITE);
1721 } while(wait->num>0);
1723 mono_thread_pool_cleanup ();
1725 EnterCriticalSection(&threads_mutex);
1728 * Remove everything but the finalizer thread and self.
1729 * Also abort all the background threads
1732 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
1734 LeaveCriticalSection(&threads_mutex);
1737 /* Something to wait for */
1738 wait_for_tids (wait, INFINITE);
1741 * give the subthreads a chance to really quit (this is mainly needed
1742 * to get correct user and system times from getrusage/wait/time(1)).
1743 * This could be removed if we avoid pthread_detach() and use pthread_join().
1745 #ifndef PLATFORM_WIN32
1752 static void terminate_thread (gpointer key, gpointer value, gpointer user)
1754 MonoThread *thread=(MonoThread *)value;
1755 guint32 self=GPOINTER_TO_UINT (user);
1757 if(thread->tid!=self) {
1758 /*TerminateThread (thread->handle, -1);*/
1762 void mono_thread_abort_all_other_threads (void)
1764 guint32 self=GetCurrentThreadId ();
1766 EnterCriticalSection (&threads_mutex);
1768 g_message(G_GNUC_PRETTY_FUNCTION ":There are %d threads to abort",
1769 mono_g_hash_table_size (threads));
1770 mono_g_hash_table_foreach (threads, print_tids, NULL);
1773 mono_g_hash_table_foreach (threads, terminate_thread,
1774 GUINT_TO_POINTER (self));
1776 LeaveCriticalSection (&threads_mutex);
1779 static void suspend_thread (gpointer key, gpointer value, gpointer user)
1781 MonoThread *thread=(MonoThread *)value;
1782 guint32 self=GPOINTER_TO_UINT (user);
1784 if ((thread->tid!=self) && !mono_gc_is_finalizer_thread (thread))
1785 SuspendThread (thread->handle);
1789 * mono_thread_suspend_all_other_threads:
1791 * Suspend all managed threads except the finalizer thread and this thread.
1793 void mono_thread_suspend_all_other_threads (void)
1795 guint32 self=GetCurrentThreadId ();
1797 EnterCriticalSection (&threads_mutex);
1798 mono_g_hash_table_foreach (threads, suspend_thread,
1799 GUINT_TO_POINTER (self));
1800 LeaveCriticalSection (&threads_mutex);
1804 * mono_thread_push_appdomain_ref:
1806 * Register that the current thread may have references to objects in domain
1807 * @domain on its stack. Each call to this function should be paired with a
1808 * call to pop_appdomain_ref.
1811 mono_thread_push_appdomain_ref (MonoDomain *domain)
1813 MonoThread *thread = mono_thread_current ();
1816 /* printf ("PUSH REF: %x -> %s.\n", thread->tid, domain->friendly_name); */
1817 EnterCriticalSection (&threads_mutex);
1818 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
1819 LeaveCriticalSection (&threads_mutex);
1824 mono_thread_pop_appdomain_ref (void)
1826 MonoThread *thread = mono_thread_current ();
1829 /* printf ("POP REF: %x -> %s.\n", thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
1830 EnterCriticalSection (&threads_mutex);
1831 /* FIXME: How can the list be empty ? */
1832 if (thread->appdomain_refs)
1833 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
1834 LeaveCriticalSection (&threads_mutex);
1839 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
1842 EnterCriticalSection (&threads_mutex);
1843 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
1844 LeaveCriticalSection (&threads_mutex);
1848 typedef struct abort_appdomain_data {
1849 struct wait_data wait;
1851 } abort_appdomain_data;
1854 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
1856 MonoThread *thread = (MonoThread*)value;
1857 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
1858 MonoDomain *domain = data->domain;
1860 if (mono_thread_has_appdomain_ref (thread, domain)) {
1861 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
1862 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1866 ves_icall_System_Threading_Thread_Abort (thread, NULL);
1868 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
1869 data->wait.handles [data->wait.num] = handle;
1870 data->wait.threads [data->wait.num] = thread;
1873 /* Just ignore the rest, we can't do anything with
1881 * mono_threads_abort_appdomain_threads:
1883 * Abort threads which has references to the given appdomain.
1886 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
1888 abort_appdomain_data user_data;
1891 /* printf ("ABORT BEGIN.\n"); */
1893 start_time = GetTickCount ();
1895 EnterCriticalSection (&threads_mutex);
1897 user_data.domain = domain;
1898 user_data.wait.num = 0;
1899 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
1900 LeaveCriticalSection (&threads_mutex);
1902 if (user_data.wait.num > 0)
1903 wait_for_tids (&user_data.wait, timeout);
1905 /* Update remaining time */
1906 timeout -= GetTickCount () - start_time;
1907 start_time = GetTickCount ();
1912 while (user_data.wait.num > 0);
1914 /* printf ("ABORT DONE.\n"); */
1920 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
1922 MonoThread *thread = (MonoThread*)value;
1923 MonoDomain *domain = (MonoDomain*)user_data;
1926 /* No locking needed here */
1928 if (thread->culture_info) {
1929 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1930 if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
1931 thread->culture_info [i] = NULL;
1934 if (thread->ui_culture_info) {
1935 for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
1936 if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
1937 thread->ui_culture_info [i] = NULL;
1943 * mono_threads_clear_cached_culture:
1945 * Clear the cached_current_culture from all threads if it is in the
1949 mono_threads_clear_cached_culture (MonoDomain *domain)
1951 EnterCriticalSection (&threads_mutex);
1952 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
1953 LeaveCriticalSection (&threads_mutex);
1957 * mono_thread_get_pending_exception:
1959 * Return an exception which needs to be raised when leaving a catch clause.
1960 * This is used for undeniable exception propagation.
1963 mono_thread_get_pending_exception (void)
1965 MonoThread *thread = mono_thread_current ();
1967 MONO_ARCH_SAVE_REGS;
1969 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
1971 * FIXME: Clear the abort exception and return an AppDomainUnloaded
1972 * exception if the thread no longer references a dying appdomain.
1974 thread->abort_exc->trace_ips = NULL;
1975 thread->abort_exc->stack_trace = NULL;
1976 return thread->abort_exc;
1982 #define NUM_STATIC_DATA_IDX 8
1983 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
1984 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
1989 * mono_alloc_static_data
1991 * Allocate memory blocks for storing threads or context static data
1994 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
1996 guint idx = (offset >> 24) - 1;
1999 gpointer* static_data = *static_data_ptr;
2002 static_data = GC_MALLOC (static_data_size [0]);
2004 static_data = g_malloc0 (static_data_size [0]);
2006 *static_data_ptr = static_data;
2007 static_data [0] = static_data;
2010 for (i = 1; i < idx; ++i) {
2011 if (static_data [i])
2014 static_data [i] = GC_MALLOC (static_data_size [i]);
2016 static_data [i] = g_malloc0 (static_data_size [i]);
2022 * mono_init_static_data_info
2024 * Initializes static data counters
2026 static void mono_init_static_data_info (StaticDataInfo *static_data)
2028 static_data->idx = 0;
2029 static_data->offset = 0;
2033 * mono_alloc_static_data_slot
2035 * Generates an offset for static data. static_data contains the counters
2036 * used to generate it.
2039 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2043 if (!static_data->idx && !static_data->offset) {
2045 * we use the first chunk of the first allocation also as
2046 * an array for the rest of the data
2048 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2050 static_data->offset += align - 1;
2051 static_data->offset &= ~(align - 1);
2052 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2053 static_data->idx ++;
2054 g_assert (size <= static_data_size [static_data->idx]);
2056 * massive unloading and reloading of domains with thread-static
2057 * data may eventually exceed the allocated storage...
2058 * Need to check what the MS runtime does in that case.
2059 * Note that for each appdomain, we need to allocate a separate
2060 * thread data slot for security reasons. We could keep track
2061 * of the slots per-domain and when the domain is unloaded
2062 * out the slots on a sort of free list.
2064 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2065 static_data->offset = 0;
2067 offset = static_data->offset | ((static_data->idx + 1) << 24);
2068 static_data->offset += size;
2073 * ensure thread static fields already allocated are valid for thread
2074 * This function is called when a thread is created or on thread attach.
2077 thread_adjust_static_data (MonoThread *thread)
2081 EnterCriticalSection (&threads_mutex);
2082 if (thread_static_info.offset || thread_static_info.idx > 0) {
2083 /* get the current allocated size */
2084 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2085 mono_alloc_static_data (&(thread->static_data), offset);
2087 LeaveCriticalSection (&threads_mutex);
2091 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2093 MonoThread *thread = value;
2094 guint32 offset = GPOINTER_TO_UINT (user);
2096 mono_alloc_static_data (&(thread->static_data), offset);
2100 * The offset for a special static variable is composed of three parts:
2101 * a bit that indicates the type of static data (0:thread, 1:context),
2102 * an index in the array of chunks of memory for the thread (thread->static_data)
2103 * and an offset in that chunk of mem. This allows allocating less memory in the
2108 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2111 if (static_type == SPECIAL_STATIC_THREAD)
2113 EnterCriticalSection (&threads_mutex);
2114 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2115 /* This can be called during startup */
2116 if (threads != NULL)
2117 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2118 LeaveCriticalSection (&threads_mutex);
2122 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2123 EnterCriticalSection (&contexts_mutex);
2124 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2125 LeaveCriticalSection (&contexts_mutex);
2126 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2132 mono_get_special_static_data (guint32 offset)
2134 /* The high bit means either thread (0) or static (1) data. */
2136 guint32 static_type = (offset & 0x80000000);
2139 offset &= 0x7fffffff;
2140 idx = (offset >> 24) - 1;
2142 if (static_type == 0)
2144 MonoThread *thread = mono_thread_current ();
2145 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2149 /* Allocate static data block under demand, since we don't have a list
2152 MonoAppContext *context = mono_context_get ();
2153 if (!context->static_data || !context->static_data [idx]) {
2154 EnterCriticalSection (&contexts_mutex);
2155 mono_alloc_static_data (&(context->static_data), offset);
2156 LeaveCriticalSection (&contexts_mutex);
2158 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2162 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2164 MonoThread *thread=(MonoThread *)value;
2165 guint32 self=GPOINTER_TO_UINT (user);
2168 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2171 if(thread->tid==self)
2174 SuspendThread (thread->handle);
2177 void mono_gc_stop_world (void)
2179 guint32 self=GetCurrentThreadId ();
2182 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2185 EnterCriticalSection (&threads_mutex);
2187 if (threads != NULL)
2188 mono_g_hash_table_foreach (threads, gc_stop_world, GUINT_TO_POINTER (self));
2190 LeaveCriticalSection (&threads_mutex);
2193 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2195 MonoThread *thread=(MonoThread *)value;
2196 guint32 self=GPOINTER_TO_UINT (user);
2199 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d", self, thread->tid);
2202 if(thread->tid==self)
2205 ResumeThread (thread->handle);
2208 void mono_gc_start_world (void)
2210 guint32 self=GetCurrentThreadId ();
2213 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2216 EnterCriticalSection (&threads_mutex);
2218 if (threads != NULL)
2219 mono_g_hash_table_foreach (threads, gc_start_world, GUINT_TO_POINTER (self));
2221 LeaveCriticalSection (&threads_mutex);
2225 static CALLBACK void dummy_apc (ULONG_PTR param)
2229 static guint32 dummy_apc (gpointer param)
2236 * mono_thread_execute_interruption
2238 * Performs the operation that the requested thread state requires (abort,
2241 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2243 mono_monitor_enter (thread->synch_lock);
2245 if (thread->interruption_requested) {
2246 /* this will consume pending APC calls */
2247 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2248 EnterCriticalSection (&interruption_mutex);
2249 thread_interruption_requested--;
2250 LeaveCriticalSection (&interruption_mutex);
2251 thread->interruption_requested = FALSE;
2254 if ((thread->state & ThreadState_AbortRequested) != 0) {
2255 if (thread->abort_exc == NULL)
2256 thread->abort_exc = mono_get_exception_thread_abort ();
2257 mono_monitor_exit (thread->synch_lock);
2258 return thread->abort_exc;
2260 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2261 thread->state &= ~ThreadState_SuspendRequested;
2262 thread->state |= ThreadState_Suspended;
2263 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2264 mono_monitor_exit (thread->synch_lock);
2266 WaitForSingleObject (thread->suspend_event, INFINITE);
2268 mono_monitor_enter (thread->synch_lock);
2269 CloseHandle (thread->suspend_event);
2270 thread->suspend_event = NULL;
2271 thread->state &= ~ThreadState_Suspended;
2273 /* The thread that requested the resume will have replaced this event
2274 * and will be waiting for it
2276 SetEvent (thread->resume_event);
2277 mono_monitor_exit (thread->synch_lock);
2280 else if ((thread->state & ThreadState_StopRequested) != 0) {
2281 /* FIXME: do this through the JIT? */
2282 mono_monitor_exit (thread->synch_lock);
2283 mono_thread_exit ();
2287 mono_monitor_exit (thread->synch_lock);
2292 * mono_thread_request_interruption
2294 * A signal handler can call this method to request the interruption of a
2295 * thread. The result of the interruption will depend on the current state of
2296 * the thread. If the result is an exception that needs to be throw, it is
2297 * provided as return value.
2299 MonoException* mono_thread_request_interruption (gboolean running_managed)
2301 MonoThread *thread = mono_thread_current ();
2303 /* The thread may already be stopping */
2307 mono_monitor_enter (thread->synch_lock);
2309 if (thread->interruption_requested) {
2310 mono_monitor_exit (thread->synch_lock);
2314 if (!running_managed || is_running_protected_wrapper ()) {
2315 /* Can't stop while in unmanaged code. Increase the global interruption
2316 request count. When exiting the unmanaged method the count will be
2317 checked and the thread will be interrupted. */
2319 EnterCriticalSection (&interruption_mutex);
2320 thread_interruption_requested++;
2321 LeaveCriticalSection (&interruption_mutex);
2323 thread->interruption_requested = TRUE;
2324 mono_monitor_exit (thread->synch_lock);
2326 /* this will awake the thread if it is in WaitForSingleObject
2328 QueueUserAPC (dummy_apc, thread->handle, NULL);
2333 mono_monitor_exit (thread->synch_lock);
2334 return mono_thread_execute_interruption (thread);
2338 gboolean mono_thread_interruption_requested ()
2340 if (thread_interruption_requested) {
2341 MonoThread *thread = mono_thread_current ();
2342 /* The thread may already be stopping */
2344 return (thread->interruption_requested);
2349 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2351 MonoThread *thread = mono_thread_current ();
2353 /* The thread may already be stopping */
2357 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2358 MonoException* exc = mono_thread_execute_interruption (thread);
2359 if (exc) mono_raise_exception (exc);
2364 * Performs the interruption of the current thread, if one has been requested,
2365 * and the thread is not running a protected wrapper.
2367 void mono_thread_interruption_checkpoint ()
2369 mono_thread_interruption_checkpoint_request (FALSE);
2373 * Performs the interruption of the current thread, if one has been requested.
2375 void mono_thread_force_interruption_checkpoint ()
2377 mono_thread_interruption_checkpoint_request (TRUE);
2381 * mono_thread_interruption_request_flag:
2383 * Returns the address of a flag that will be non-zero if an interruption has
2384 * been requested for a thread. The thread to interrupt may not be the current
2385 * thread, so an additional call to mono_thread_interruption_requested() or
2386 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2389 gint32* mono_thread_interruption_request_flag ()
2391 return &thread_interruption_requested;
2394 #ifdef WITH_INCLUDED_LIBGC
2396 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)
2398 MonoThread *thread=(MonoThread *)value;
2399 guint32 *selfp=(guint32 *)user, self = *selfp;
2402 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %d - %p", self, thread->tid, thread->stack_ptr);
2405 if(thread->tid==self) {
2407 g_message (G_GNUC_PRETTY_FUNCTION ": %p - %p", selfp, thread->stack_ptr);
2409 GC_push_all_stack (selfp, thread->stack_ptr);
2413 #ifdef PLATFORM_WIN32
2414 GC_win32_push_thread_stack (thread->handle, thread->stack_ptr);
2416 mono_wapi_push_thread_stack (thread->handle, thread->stack_ptr);
2420 void mono_gc_push_all_stacks (void)
2422 guint32 self=GetCurrentThreadId ();
2425 g_message (G_GNUC_PRETTY_FUNCTION ": %d - %p", self, threads);
2428 EnterCriticalSection (&threads_mutex);
2430 if (threads != NULL)
2431 mono_g_hash_table_foreach (threads, gc_push_all_stacks, &self);
2433 LeaveCriticalSection (&threads_mutex);
2436 #endif /* WITH_INCLUDED_LIBGC */