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>
34 #include <mono/utils/mono-compiler.h>
36 #include <mono/os/gc_wrapper.h>
38 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
39 #define THREAD_DEBUG(a)
40 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
41 #define THREAD_WAIT_DEBUG(a)
42 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
43 #define LIBGC_DEBUG(a)
47 guint32 (*func)(void *);
69 /* Number of cached culture objects in the MonoThread->cached_culture_info array
70 * (per-type): we use the first NUM entries for CultureInfo and the last for
71 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
73 #define NUM_CACHED_CULTURES 4
74 #define CULTURES_START_IDX 0
75 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
78 * The "os_handle" field of the WaitHandle class.
80 static MonoClassField *wait_handle_os_handle_field = NULL;
82 /* Controls access to the 'threads' hash table */
83 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
84 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
85 static CRITICAL_SECTION threads_mutex;
87 /* Controls access to context static data */
88 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
89 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
90 static CRITICAL_SECTION contexts_mutex;
92 /* Holds current status of static data heap */
93 static StaticDataInfo thread_static_info;
94 static StaticDataInfo context_static_info;
96 /* The hash of existing threads (key is thread ID) that need joining
99 static MonoGHashTable *threads=NULL;
101 /* The TLS key that holds the MonoObject assigned to each thread */
102 static guint32 current_object_key = -1;
104 #ifdef HAVE_KW_THREAD
105 /* we need to use both the Tls* functions and __thread because
106 * the gc needs to see all the threads
108 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
109 #define SET_CURRENT_OBJECT(x) do { \
110 tls_current_object = x; \
111 TlsSetValue (current_object_key, x); \
113 #define GET_CURRENT_OBJECT() tls_current_object
115 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
116 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
119 /* function called at thread start */
120 static MonoThreadStartCB mono_thread_start_cb = NULL;
122 /* function called at thread attach */
123 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
125 /* function called at thread cleanup */
126 static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
128 /* function called when a new thread has been created */
129 static MonoThreadCallbacks *mono_thread_callbacks = NULL;
131 /* The default stack size for each thread */
132 static guint32 default_stacksize = 0;
133 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
135 static void thread_adjust_static_data (MonoThread *thread);
136 static void mono_init_static_data_info (StaticDataInfo *static_data);
137 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
138 static gboolean mono_thread_resume (MonoThread* thread);
139 static void mono_thread_start (MonoThread *thread);
141 /* Spin lock for InterlockedXXX 64 bit functions */
142 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
143 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
144 static CRITICAL_SECTION interlocked_mutex;
146 /* global count of thread interruptions requested */
147 static gint32 thread_interruption_requested = 0;
149 /* Event signaled when a thread changes its background mode */
150 static HANDLE background_change_event;
153 mono_thread_get_tls_key (void)
155 return current_object_key;
159 mono_thread_get_tls_offset (void)
162 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
166 /* handle_store() and handle_remove() manage the array of threads that
167 * still need to be waited for when the main thread exits.
169 static void handle_store(MonoThread *thread)
171 mono_threads_lock ();
173 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
176 MONO_GC_REGISTER_ROOT (threads);
177 threads=mono_g_hash_table_new(NULL, NULL);
180 /* We don't need to duplicate thread->handle, because it is
181 * only closed when the thread object is finalized by the GC.
183 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
186 mono_threads_unlock ();
189 static void handle_remove(gsize tid)
191 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
193 mono_threads_lock ();
197 mono_g_hash_table_remove (threads, (gpointer)tid);
199 mono_threads_unlock ();
201 /* Don't close the handle here, wait for the object finalizer
202 * to do it. Otherwise, the following race condition applies:
204 * 1) Thread exits (and handle_remove() closes the handle)
206 * 2) Some other handle is reassigned the same slot
208 * 3) Another thread tries to join the first thread, and
209 * blocks waiting for the reassigned handle to be signalled
210 * (which might never happen). This is possible, because the
211 * thread calling Join() still has a reference to the first
216 static void thread_cleanup (MonoThread *thread)
218 g_assert (thread != NULL);
220 mono_release_type_locks (thread);
222 if (!mono_monitor_enter (thread->synch_lock))
225 thread->state |= ThreadState_Stopped;
226 mono_monitor_exit (thread->synch_lock);
228 mono_profiler_thread_end (thread->tid);
229 handle_remove (thread->tid);
231 mono_thread_pop_appdomain_ref ();
233 if (thread->serialized_culture_info)
234 g_free (thread->serialized_culture_info);
236 thread->cached_culture_info = NULL;
238 if (mono_thread_cleanup)
239 mono_thread_cleanup (thread);
242 static guint32 WINAPI start_wrapper(void *data)
244 struct StartInfo *start_info=(struct StartInfo *)data;
245 guint32 (*start_func)(void *);
248 MonoThread *thread=start_info->obj;
249 MonoObject *start_delegate = start_info->delegate;
251 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
253 /* We can be sure start_info->obj->tid and
254 * start_info->obj->handle have been set, because the thread
255 * was created suspended, and these values were set before the
261 SET_CURRENT_OBJECT (thread);
263 if (!mono_domain_set (start_info->domain, FALSE)) {
264 /* No point in raising an appdomain_unloaded exception here */
265 /* FIXME: Cleanup here */
269 start_func = start_info->func;
270 start_arg = start_info->start_arg;
272 /* This MUST be called before any managed code can be
273 * executed, as it calls the callback function that (for the
274 * jit) sets the lmf marker.
276 mono_thread_new_init (tid, &tid, start_func);
277 thread->stack_ptr = &tid;
279 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
281 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
283 mono_profiler_thread_start (tid);
285 if(thread->start_notify!=NULL) {
286 /* Let the thread that called Start() know we're
289 ReleaseSemaphore (thread->start_notify, 1, NULL);
294 /* Every thread references the appdomain which created it */
295 mono_thread_push_appdomain_ref (mono_domain_get ());
297 thread_adjust_static_data (thread);
299 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
303 /* start_func is set only for unamanged start functions */
305 start_func (start_arg);
308 g_assert (start_delegate != NULL);
309 args [0] = start_arg;
310 /* we may want to handle the exception here. See comment below on unhandled exceptions */
311 mono_runtime_delegate_invoke (start_delegate, args, NULL);
314 /* If the thread calls ExitThread at all, this remaining code
315 * will not be executed, but the main thread will eventually
316 * call thread_cleanup() on this thread's behalf.
319 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
321 /* Remove the reference to the thread object in the TLS data,
322 * so the thread object can be finalized. This won't be
323 * reached if the thread threw an uncaught exception, so those
324 * thread handles will stay referenced :-( (This is due to
325 * missing support for scanning thread-specific data in the
326 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
329 SET_CURRENT_OBJECT (NULL);
331 thread_cleanup (thread);
336 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
338 if (mono_thread_start_cb) {
339 mono_thread_start_cb (tid, stack_start, func);
342 if (mono_thread_callbacks)
343 (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
346 void mono_threads_set_default_stacksize (guint32 stacksize)
348 default_stacksize = stacksize;
351 guint32 mono_threads_get_default_stacksize (void)
353 return default_stacksize;
356 void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
359 HANDLE thread_handle;
360 struct StartInfo *start_info;
363 thread=(MonoThread *)mono_object_new (domain,
364 mono_defaults.thread_class);
366 start_info=g_new0 (struct StartInfo, 1);
367 start_info->func = func;
368 start_info->obj = thread;
369 start_info->domain = domain;
370 start_info->start_arg = arg;
372 /* Create suspended, so we can do some housekeeping before the thread
375 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
376 CREATE_SUSPENDED, &tid);
377 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
378 if (thread_handle == NULL) {
379 /* The thread couldn't be created, so throw an exception */
380 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
384 thread->handle=thread_handle;
387 MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
389 handle_store(thread);
391 ResumeThread (thread_handle);
395 mono_thread_attach (MonoDomain *domain)
398 HANDLE thread_handle;
401 if ((thread = mono_thread_current ())) {
402 if (domain != mono_domain_get ())
403 mono_domain_set (domain, TRUE);
404 /* Already attached */
408 if (!mono_gc_register_thread (&domain)) {
409 g_error ("Thread %p calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThread ());
412 thread = (MonoThread *)mono_object_new (domain,
413 mono_defaults.thread_class);
415 thread_handle = GetCurrentThread ();
416 g_assert (thread_handle);
418 tid=GetCurrentThreadId ();
420 #ifdef PLATFORM_WIN32
422 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
423 * refer to the thread from other threads for things like aborting.
425 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
426 THREAD_ALL_ACCESS, TRUE, 0);
429 thread->handle=thread_handle;
431 MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
433 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
435 handle_store(thread);
437 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
439 SET_CURRENT_OBJECT (thread);
440 mono_domain_set (domain, TRUE);
442 thread_adjust_static_data (thread);
444 if (mono_thread_attach_cb) {
445 mono_thread_attach_cb (tid, &tid);
452 mono_thread_detach (MonoThread *thread)
454 g_return_if_fail (thread != NULL);
456 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
457 SET_CURRENT_OBJECT (NULL);
459 thread_cleanup (thread);
461 /* Need to CloseHandle this thread, because we took a reference in
462 * mono_thread_attach ()
464 CloseHandle(thread->handle);
470 MonoThread *thread = mono_thread_current ();
472 SET_CURRENT_OBJECT (NULL);
473 thread_cleanup (thread);
475 /* we could add a callback here for embedders to use. */
476 if (thread == mono_thread_get_main ())
477 exit (mono_environment_exitcode_get ());
481 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
484 guint32 (*start_func)(void *);
485 struct StartInfo *start_info;
491 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
493 mono_monitor_enter (this->synch_lock);
495 if ((this->state & ThreadState_Unstarted) == 0) {
496 mono_monitor_exit (this->synch_lock);
497 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
501 if ((this->state & ThreadState_Aborted) != 0) {
502 mono_monitor_exit (this->synch_lock);
507 /* This is freed in start_wrapper */
508 start_info = g_new0 (struct StartInfo, 1);
509 start_info->func = start_func;
510 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
511 start_info->delegate = start;
512 start_info->obj = this;
513 start_info->domain = mono_domain_get ();
515 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
516 if(this->start_notify==NULL) {
517 mono_monitor_exit (this->synch_lock);
518 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
522 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
523 CREATE_SUSPENDED, &tid);
525 mono_monitor_exit (this->synch_lock);
526 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
533 /* Don't call handle_store() here, delay it to Start.
534 * We can't join a thread (trying to will just block
535 * forever) until it actually starts running, so don't
536 * store the handle till then.
539 mono_thread_start (this);
541 this->state &= ~ThreadState_Unstarted;
543 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
545 mono_monitor_exit (this->synch_lock);
550 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
555 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
557 CloseHandle (thread);
560 static void mono_thread_start (MonoThread *thread)
564 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
566 /* Only store the handle when the thread is about to be
567 * launched, to avoid the main thread deadlocking while trying
568 * to clean up a thread that will never be signalled.
570 handle_store (thread);
572 if (mono_thread_callbacks)
573 (* mono_thread_callbacks->start_resume) (thread->tid);
575 ResumeThread (thread->handle);
577 if (mono_thread_callbacks)
578 (* mono_thread_callbacks->end_resume) (thread->tid);
580 if(thread->start_notify!=NULL) {
581 /* Wait for the thread to set up its TLS data etc, so
582 * theres no potential race condition if someone tries
583 * to look up the data believing the thread has
587 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
589 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
590 CloseHandle (thread->start_notify);
591 thread->start_notify = NULL;
594 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
597 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
599 MonoThread *thread = mono_thread_current ();
603 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
605 mono_monitor_enter (thread->synch_lock);
606 thread->state |= ThreadState_WaitSleepJoin;
607 mono_monitor_exit (thread->synch_lock);
611 mono_monitor_enter (thread->synch_lock);
612 thread->state &= ~ThreadState_WaitSleepJoin;
613 mono_monitor_exit (thread->synch_lock);
617 ves_icall_System_Threading_Thread_GetDomainID (void)
621 return mono_domain_get()->domain_id;
625 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
628 mono_monitor_enter (this_obj->synch_lock);
633 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
635 mono_monitor_exit (this_obj->synch_lock);
640 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
642 mono_monitor_enter (this_obj->synch_lock);
644 if (this_obj->name) {
645 mono_monitor_exit (this_obj->synch_lock);
646 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
650 this_obj->name = g_new (gunichar2, mono_string_length (name));
651 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
652 this_obj->name_len = mono_string_length (name);
655 this_obj->name = NULL;
657 mono_monitor_exit (this_obj->synch_lock);
661 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
666 if (this->cached_culture_info) {
667 domain = mono_domain_get ();
668 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
669 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
670 if (res && res->vtable->domain == domain)
679 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
681 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
685 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
689 mono_monitor_enter (this->synch_lock);
690 if (this->serialized_culture_info) {
691 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
692 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
696 mono_monitor_exit (this->synch_lock);
702 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
705 MonoDomain *domain = mono_domain_get ();
708 int same_domain_slot = -1;
710 mono_monitor_enter (this->synch_lock);
711 if (!this->cached_culture_info)
712 this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
714 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
715 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
719 /* we continue, because there may be a slot used with the same domain */
723 if (obj->vtable->domain == domain) {
724 same_domain_slot = i;
728 if (same_domain_slot >= 0)
729 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
730 else if (free_slot >= 0)
731 mono_array_setref (this->cached_culture_info, free_slot, culture);
732 /* we may want to replace an existing entry here, even when no suitable slot is found */
733 mono_monitor_exit (this->synch_lock);
737 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
739 cache_culture (this, culture, CULTURES_START_IDX);
743 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
745 mono_monitor_enter (this->synch_lock);
746 if (this->serialized_culture_info)
747 g_free (this->serialized_culture_info);
748 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
749 this->serialized_culture_info_len = mono_array_length (arr);
750 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
751 mono_monitor_exit (this->synch_lock);
756 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
758 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
762 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
766 mono_monitor_enter (this->synch_lock);
767 if (this->serialized_ui_culture_info) {
768 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
769 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
773 mono_monitor_exit (this->synch_lock);
779 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
781 cache_culture (this, culture, UICULTURES_START_IDX);
785 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
787 mono_monitor_enter (this->synch_lock);
788 if (this->serialized_ui_culture_info)
789 g_free (this->serialized_ui_culture_info);
790 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
791 this->serialized_ui_culture_info_len = mono_array_length (arr);
792 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
793 mono_monitor_exit (this->synch_lock);
796 /* the jit may read the compiled code of this function */
798 mono_thread_current (void)
800 THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
801 return GET_CURRENT_OBJECT ();
804 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
805 int ms, HANDLE thread)
811 mono_monitor_enter (this->synch_lock);
813 if ((this->state & ThreadState_Unstarted) != 0) {
814 mono_monitor_exit (this->synch_lock);
815 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
819 this->state |= ThreadState_WaitSleepJoin;
820 mono_monitor_exit (this->synch_lock);
825 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
827 ret=WaitForSingleObjectEx (thread, ms, TRUE);
829 mono_monitor_enter (this->synch_lock);
830 this->state &= ~ThreadState_WaitSleepJoin;
831 mono_monitor_exit (this->synch_lock);
833 if(ret==WAIT_OBJECT_0) {
834 THREAD_DEBUG (g_message ("%s: join successful", __func__));
839 THREAD_DEBUG (g_message ("%s: join failed", __func__));
844 /* FIXME: exitContext isnt documented */
845 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
851 MonoObject *waitHandle;
853 MonoThread *thread = mono_thread_current ();
857 numhandles = mono_array_length(mono_handles);
858 handles = g_new0(HANDLE, numhandles);
860 if (wait_handle_os_handle_field == 0) {
861 /* Get the field os_handle which will contain the actual handle */
862 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
863 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
866 for(i = 0; i < numhandles; i++) {
867 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
868 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
875 mono_monitor_enter (thread->synch_lock);
876 thread->state |= ThreadState_WaitSleepJoin;
877 mono_monitor_exit (thread->synch_lock);
879 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
881 mono_monitor_enter (thread->synch_lock);
882 thread->state &= ~ThreadState_WaitSleepJoin;
883 mono_monitor_exit (thread->synch_lock);
887 if(ret==WAIT_FAILED) {
888 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
890 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
891 /* Do we want to try again if we get
892 * WAIT_IO_COMPLETION? The documentation for
893 * WaitHandle doesn't give any clues. (We'd have to
894 * fiddle with the timeout if we retry.)
896 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
903 /* FIXME: exitContext isnt documented */
904 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
910 MonoObject *waitHandle;
912 MonoThread *thread = mono_thread_current ();
916 numhandles = mono_array_length(mono_handles);
917 handles = g_new0(HANDLE, numhandles);
919 if (wait_handle_os_handle_field == 0) {
920 /* Get the field os_handle which will contain the actual handle */
921 klass = mono_class_from_name(mono_defaults.corlib, "System.Threading", "WaitHandle");
922 wait_handle_os_handle_field = mono_class_get_field_from_name(klass, "os_handle");
925 for(i = 0; i < numhandles; i++) {
926 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
927 mono_field_get_value(waitHandle, wait_handle_os_handle_field, &handles[i]);
934 mono_monitor_enter (thread->synch_lock);
935 thread->state |= ThreadState_WaitSleepJoin;
936 mono_monitor_exit (thread->synch_lock);
938 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
940 mono_monitor_enter (thread->synch_lock);
941 thread->state &= ~ThreadState_WaitSleepJoin;
942 mono_monitor_exit (thread->synch_lock);
946 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
949 * These need to be here. See MSDN dos on WaitForMultipleObjects.
951 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
952 return ret - WAIT_OBJECT_0;
954 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
955 return ret - WAIT_ABANDONED_0;
962 /* FIXME: exitContext isnt documented */
963 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
966 MonoThread *thread = mono_thread_current ();
970 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
976 mono_monitor_enter (thread->synch_lock);
977 thread->state |= ThreadState_WaitSleepJoin;
978 mono_monitor_exit (thread->synch_lock);
980 ret=WaitForSingleObjectEx (handle, ms, TRUE);
982 mono_monitor_enter (thread->synch_lock);
983 thread->state &= ~ThreadState_WaitSleepJoin;
984 mono_monitor_exit (thread->synch_lock);
986 if(ret==WAIT_FAILED) {
987 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
989 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
990 /* Do we want to try again if we get
991 * WAIT_IO_COMPLETION? The documentation for
992 * WaitHandle doesn't give any clues. (We'd have to
993 * fiddle with the timeout if we retry.)
995 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1002 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1006 MONO_ARCH_SAVE_REGS;
1011 mutex = CreateMutex (NULL, owned, NULL);
1013 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1015 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1023 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1024 MONO_ARCH_SAVE_REGS;
1026 ReleaseMutex(handle);
1029 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1035 MONO_ARCH_SAVE_REGS;
1037 *error = ERROR_SUCCESS;
1039 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1041 *error = GetLastError ();
1048 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1052 MONO_ARCH_SAVE_REGS;
1057 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1059 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1060 mono_string_chars (name));
1062 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1070 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1074 MONO_ARCH_SAVE_REGS;
1076 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1081 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1085 MONO_ARCH_SAVE_REGS;
1087 *error = ERROR_SUCCESS;
1089 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1091 *error = GetLastError ();
1097 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1101 MONO_ARCH_SAVE_REGS;
1106 event = CreateEvent (NULL, manual, initial, NULL);
1108 event = CreateEvent (NULL, manual, initial,
1109 mono_string_chars (name));
1111 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1119 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1120 MONO_ARCH_SAVE_REGS;
1122 return (SetEvent(handle));
1125 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1126 MONO_ARCH_SAVE_REGS;
1128 return (ResetEvent(handle));
1132 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1133 MONO_ARCH_SAVE_REGS;
1135 CloseHandle (handle);
1138 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1144 MONO_ARCH_SAVE_REGS;
1146 *error = ERROR_SUCCESS;
1148 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1150 *error = GetLastError ();
1156 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1158 MONO_ARCH_SAVE_REGS;
1160 return InterlockedIncrement (location);
1163 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1167 MONO_ARCH_SAVE_REGS;
1169 mono_interlocked_lock ();
1173 mono_interlocked_unlock ();
1179 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1181 MONO_ARCH_SAVE_REGS;
1183 return InterlockedDecrement(location);
1186 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1190 MONO_ARCH_SAVE_REGS;
1192 mono_interlocked_lock ();
1196 mono_interlocked_unlock ();
1201 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1203 MONO_ARCH_SAVE_REGS;
1205 return InterlockedExchange(location, value);
1208 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1210 MONO_ARCH_SAVE_REGS;
1212 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1215 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1217 IntFloatUnion val, ret;
1219 MONO_ARCH_SAVE_REGS;
1222 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1228 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1230 #if SIZEOF_VOID_P == 8
1231 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1236 * According to MSDN, this function is only atomic with regards to the
1237 * other Interlocked functions on 32 bit platforms.
1239 mono_interlocked_lock ();
1242 mono_interlocked_unlock ();
1249 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1251 #if SIZEOF_VOID_P == 8
1252 LongDoubleUnion val, ret;
1255 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1262 * According to MSDN, this function is only atomic with regards to the
1263 * other Interlocked functions on 32 bit platforms.
1265 mono_interlocked_lock ();
1268 mono_interlocked_unlock ();
1274 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1276 MONO_ARCH_SAVE_REGS;
1278 return InterlockedCompareExchange(location, value, comparand);
1281 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1283 MONO_ARCH_SAVE_REGS;
1285 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1288 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1290 IntFloatUnion val, ret, cmp;
1292 MONO_ARCH_SAVE_REGS;
1295 cmp.fval = comparand;
1296 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1302 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1304 #if SIZEOF_VOID_P == 8
1305 LongDoubleUnion val, comp, ret;
1308 comp.fval = comparand;
1309 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1315 mono_interlocked_lock ();
1317 if (old == comparand)
1319 mono_interlocked_unlock ();
1326 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1328 #if SIZEOF_VOID_P == 8
1329 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1333 mono_interlocked_lock ();
1335 if (old == comparand)
1337 mono_interlocked_unlock ();
1344 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1346 MONO_ARCH_SAVE_REGS;
1348 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1352 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1354 MONO_ARCH_SAVE_REGS;
1356 return InterlockedExchangePointer ((gpointer *)location, value);
1360 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1362 #if SIZEOF_VOID_P == 8
1363 /* Should be implemented as a JIT intrinsic */
1364 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1369 mono_interlocked_lock ();
1371 *location = orig + value;
1372 mono_interlocked_unlock ();
1379 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1381 #if SIZEOF_VOID_P == 8
1382 /* Should be implemented as a JIT intrinsic */
1383 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1388 mono_interlocked_lock ();
1390 *location = orig + value;
1391 mono_interlocked_unlock ();
1398 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1400 #if SIZEOF_VOID_P == 8
1401 /* 64 bit reads are already atomic */
1406 mono_interlocked_lock ();
1408 mono_interlocked_unlock ();
1415 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1417 /* Should be implemented as a JIT intrinsic */
1418 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1422 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1424 mono_monitor_enter (this->synch_lock);
1425 this->state &= ~state;
1426 if (state & ThreadState_Background) {
1427 /* If the thread changes the background mode, the main thread has to
1428 * be notified, since it has to rebuild the list of threads to
1431 SetEvent (background_change_event);
1433 mono_monitor_exit (this->synch_lock);
1437 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1439 mono_monitor_enter (this->synch_lock);
1440 this->state |= state;
1441 if (state & ThreadState_Background) {
1442 /* If the thread changes the background mode, the main thread has to
1443 * be notified, since it has to rebuild the list of threads to
1446 SetEvent (background_change_event);
1448 mono_monitor_exit (this->synch_lock);
1452 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1455 mono_monitor_enter (this->synch_lock);
1456 state = this->state;
1457 mono_monitor_exit (this->synch_lock);
1462 mono_thread_get_abort_signal (void)
1464 #if defined (__MINGW32__) || defined (_MSC_VER)
1470 static int abort_signum = -1;
1472 if (abort_signum != -1)
1473 return abort_signum;
1474 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1475 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1476 struct sigaction sinfo;
1477 sigaction (i, NULL, &sinfo);
1478 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1483 /* fallback to the old way */
1486 #endif /*defined (__MINGW32__) || defined (_MSC_VER) */
1489 #if defined (__MINGW32__) || defined (_MSC_VER)
1490 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1492 MonoException* exc = mono_thread_request_interruption (FALSE);
1493 if (exc) mono_raise_exception (exc);
1495 #endif /* defined (__MINGW32__) || defined (_MSC_VER) */
1498 * signal_thread_state_change
1500 * Tells the thread that his state has changed and it has to enter the new
1501 * state as soon as possible.
1503 static void signal_thread_state_change (MonoThread *thread)
1505 if (thread == mono_thread_current ()) {
1506 /* Do it synchronously */
1507 MonoException *exc = mono_thread_request_interruption (FALSE);
1509 mono_raise_exception (exc);
1512 #if defined (__MINGW32__) || defined (_MSC_VER)
1513 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1515 /* fixme: store the state somewhere */
1516 #ifdef PTHREAD_POINTER_ID
1517 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
1519 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
1521 #endif /* defined (__MINGW32__) || defined (__MSC_VER) */
1525 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
1527 MONO_ARCH_SAVE_REGS;
1529 mono_monitor_enter (thread->synch_lock);
1531 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1532 (thread->state & ThreadState_StopRequested) != 0 ||
1533 (thread->state & ThreadState_Stopped) != 0)
1535 mono_monitor_exit (thread->synch_lock);
1539 if ((thread->state & ThreadState_Unstarted) != 0) {
1540 thread->state |= ThreadState_Aborted;
1541 mono_monitor_exit (thread->synch_lock);
1545 thread->state |= ThreadState_AbortRequested;
1546 MONO_OBJECT_SETREF (thread, abort_state, state);
1547 thread->abort_exc = NULL;
1549 mono_monitor_exit (thread->synch_lock);
1551 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1553 /* Make sure the thread is awake */
1554 mono_thread_resume (thread);
1556 signal_thread_state_change (thread);
1560 ves_icall_System_Threading_Thread_ResetAbort (void)
1562 MonoThread *thread = mono_thread_current ();
1564 MONO_ARCH_SAVE_REGS;
1566 mono_monitor_enter (thread->synch_lock);
1568 thread->state &= ~ThreadState_AbortRequested;
1570 if (!thread->abort_exc) {
1571 const char *msg = "Unable to reset abort because no abort was requested";
1572 mono_monitor_exit (thread->synch_lock);
1573 mono_raise_exception (mono_get_exception_thread_state (msg));
1575 thread->abort_exc = NULL;
1576 thread->abort_state = NULL;
1579 mono_monitor_exit (thread->synch_lock);
1583 mono_thread_suspend (MonoThread *thread)
1585 MONO_ARCH_SAVE_REGS;
1587 mono_monitor_enter (thread->synch_lock);
1589 if ((thread->state & ThreadState_Unstarted) != 0 ||
1590 (thread->state & ThreadState_Aborted) != 0 ||
1591 (thread->state & ThreadState_Stopped) != 0)
1593 mono_monitor_exit (thread->synch_lock);
1597 if ((thread->state & ThreadState_Suspended) != 0 ||
1598 (thread->state & ThreadState_SuspendRequested) != 0 ||
1599 (thread->state & ThreadState_StopRequested) != 0)
1601 mono_monitor_exit (thread->synch_lock);
1605 thread->state |= ThreadState_SuspendRequested;
1606 mono_monitor_exit (thread->synch_lock);
1608 signal_thread_state_change (thread);
1613 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
1615 if (!mono_thread_suspend (thread))
1616 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1620 mono_thread_resume (MonoThread *thread)
1622 MONO_ARCH_SAVE_REGS;
1624 mono_monitor_enter (thread->synch_lock);
1626 if ((thread->state & ThreadState_SuspendRequested) != 0) {
1627 thread->state &= ~ThreadState_SuspendRequested;
1628 mono_monitor_exit (thread->synch_lock);
1632 if ((thread->state & ThreadState_Suspended) == 0 ||
1633 (thread->state & ThreadState_Unstarted) != 0 ||
1634 (thread->state & ThreadState_Aborted) != 0 ||
1635 (thread->state & ThreadState_Stopped) != 0)
1637 mono_monitor_exit (thread->synch_lock);
1641 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1643 /* Awake the thread */
1644 SetEvent (thread->suspend_event);
1646 mono_monitor_exit (thread->synch_lock);
1648 /* Wait for the thread to awake */
1649 WaitForSingleObject (thread->resume_event, INFINITE);
1650 CloseHandle (thread->resume_event);
1651 thread->resume_event = NULL;
1657 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
1659 if (!mono_thread_resume (thread))
1660 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
1664 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1669 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
1670 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
1671 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
1673 *((gboolean*)data) = TRUE;
1680 is_running_protected_wrapper (void)
1682 gboolean found = FALSE;
1683 mono_stack_walk (find_wrapper, &found);
1687 void mono_thread_stop (MonoThread *thread)
1689 mono_monitor_enter (thread->synch_lock);
1691 if ((thread->state & ThreadState_StopRequested) != 0 ||
1692 (thread->state & ThreadState_Stopped) != 0)
1694 mono_monitor_exit (thread->synch_lock);
1698 /* Make sure the thread is awake */
1699 mono_thread_resume (thread);
1701 thread->state |= ThreadState_StopRequested;
1702 thread->state &= ~ThreadState_AbortRequested;
1704 mono_monitor_exit (thread->synch_lock);
1706 signal_thread_state_change (thread);
1710 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
1712 return *((volatile gint8 *) (ptr));
1716 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
1718 return *((volatile gint16 *) (ptr));
1722 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
1724 return *((volatile gint32 *) (ptr));
1728 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
1730 return *((volatile gint64 *) (ptr));
1734 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
1736 return (void *) *((volatile void **) ptr);
1740 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
1742 *((volatile gint8 *) ptr) = value;
1746 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
1748 *((volatile gint16 *) ptr) = value;
1752 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
1754 *((volatile gint32 *) ptr) = value;
1758 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
1760 *((volatile gint64 *) ptr) = value;
1764 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
1766 *((volatile void **) ptr) = value;
1769 void mono_thread_init (MonoThreadStartCB start_cb,
1770 MonoThreadAttachCB attach_cb)
1772 InitializeCriticalSection(&threads_mutex);
1773 InitializeCriticalSection(&interlocked_mutex);
1774 InitializeCriticalSection(&contexts_mutex);
1775 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
1777 mono_init_static_data_info (&thread_static_info);
1778 mono_init_static_data_info (&context_static_info);
1780 current_object_key=TlsAlloc();
1781 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
1783 mono_thread_start_cb = start_cb;
1784 mono_thread_attach_cb = attach_cb;
1786 /* Get a pseudo handle to the current process. This is just a
1787 * kludge so that wapi can build a process handle if needed.
1788 * As a pseudo handle is returned, we don't need to clean
1791 GetCurrentProcess ();
1795 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
1797 mono_thread_cleanup = func;
1800 void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
1802 mono_thread_callbacks = callbacks;
1806 static void print_tids (gpointer key, gpointer value, gpointer user)
1808 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
1809 * sizeof(uint) and a cast to uint would overflow
1811 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
1812 * print this as a pointer.
1814 g_message ("Waiting for: %p", key);
1819 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1820 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
1824 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
1828 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
1830 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
1832 if(ret==WAIT_FAILED) {
1833 /* See the comment in build_wait_tids() */
1834 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
1838 for(i=0; i<wait->num; i++)
1839 CloseHandle (wait->handles[i]);
1841 if (ret == WAIT_TIMEOUT)
1844 for(i=0; i<wait->num; i++) {
1845 gsize tid = wait->threads[i]->tid;
1847 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1848 /* This thread must have been killed, because
1849 * it hasn't cleaned itself up. (It's just
1850 * possible that the thread exited before the
1851 * parent thread had a chance to store the
1852 * handle, and now there is another pointer to
1853 * the already-exited thread stored. In this
1854 * case, we'll just get two
1855 * mono_profiler_thread_end() calls for the
1859 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
1860 thread_cleanup (wait->threads[i]);
1865 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
1867 guint32 i, ret, count;
1869 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
1871 /* Add the thread state change event, so it wakes up if a thread changes
1872 * to background mode.
1875 if (count < MAXIMUM_WAIT_OBJECTS) {
1876 wait->handles [count] = background_change_event;
1880 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
1882 if(ret==WAIT_FAILED) {
1883 /* See the comment in build_wait_tids() */
1884 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
1888 for(i=0; i<wait->num; i++)
1889 CloseHandle (wait->handles[i]);
1891 if (ret == WAIT_TIMEOUT)
1894 if (ret < wait->num) {
1895 gsize tid = wait->threads[ret]->tid;
1896 mono_threads_lock ();
1897 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
1898 /* See comment in wait_for_tids about thread cleanup */
1899 mono_threads_unlock ();
1900 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
1901 thread_cleanup (wait->threads [ret]);
1903 mono_threads_unlock ();
1907 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
1909 struct wait_data *wait=(struct wait_data *)user;
1911 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
1913 MonoThread *thread=(MonoThread *)value;
1915 /* Ignore background threads, we abort them later */
1916 mono_monitor_enter (thread->synch_lock);
1917 if (thread->state & ThreadState_Background) {
1918 mono_monitor_exit (thread->synch_lock);
1919 return; /* just leave, ignore */
1921 mono_monitor_exit (thread->synch_lock);
1923 if (mono_gc_is_finalizer_thread (thread))
1926 if (thread == mono_thread_current ())
1929 if (thread == mono_thread_get_main ())
1932 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1936 wait->handles[wait->num]=handle;
1937 wait->threads[wait->num]=thread;
1940 /* Just ignore the rest, we can't do anything with
1947 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
1949 struct wait_data *wait=(struct wait_data *)user;
1950 gsize self = GetCurrentThreadId ();
1951 MonoThread *thread = (MonoThread *) value;
1954 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
1957 /* The finalizer thread is not a background thread */
1958 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
1960 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
1964 if(thread->state & ThreadState_AbortRequested ||
1965 thread->state & ThreadState_Aborted) {
1966 THREAD_DEBUG (g_message ("%s: Thread id %"G_GSIZE_FORMAT" already aborting", __func__, (gsize)thread->tid));
1970 /* printf ("A: %d\n", wait->num); */
1971 wait->handles[wait->num]=thread->handle;
1972 wait->threads[wait->num]=thread;
1975 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
1976 mono_thread_stop (thread);
1980 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
1983 void mono_thread_manage (void)
1985 struct wait_data *wait=g_new0 (struct wait_data, 1);
1987 /* join each thread that's still running */
1988 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
1990 mono_threads_lock ();
1992 THREAD_DEBUG (g_message("%s: No threads", __func__));
1993 mono_threads_unlock ();
1996 mono_threads_unlock ();
1999 mono_threads_lock ();
2000 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2001 mono_g_hash_table_foreach (threads, print_tids, NULL));
2003 ResetEvent (background_change_event);
2005 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2006 mono_threads_unlock ();
2008 /* Something to wait for */
2009 wait_for_tids_or_state_change (wait, INFINITE);
2011 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2012 } while(wait->num>0);
2014 mono_runtime_set_shutting_down ();
2016 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2017 mono_thread_pool_cleanup ();
2020 * Remove everything but the finalizer thread and self.
2021 * Also abort all the background threads
2024 mono_threads_lock ();
2027 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2029 mono_threads_unlock ();
2031 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2033 /* Something to wait for */
2034 wait_for_tids (wait, INFINITE);
2036 } while (wait->num > 0);
2038 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2039 /* The main thread must abandon any held mutexes (particularly
2040 * important for named mutexes as they are shared across
2041 * processes, see bug 74680.) This will happen when the
2042 * thread exits, but if it's not running in a subthread it
2043 * won't exit in time.
2045 /* Using non-w32 API is a nasty kludge, but I couldn't find
2046 * anything in the documentation that would let me do this
2047 * here yet still be safe to call on windows.
2049 _wapi_thread_abandon_mutexes (GetCurrentThread ());
2053 * give the subthreads a chance to really quit (this is mainly needed
2054 * to get correct user and system times from getrusage/wait/time(1)).
2055 * This could be removed if we avoid pthread_detach() and use pthread_join().
2057 #ifndef PLATFORM_WIN32
2064 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2066 MonoThread *thread=(MonoThread *)value;
2068 if(thread->tid != (gsize)user) {
2069 /*TerminateThread (thread->handle, -1);*/
2073 void mono_thread_abort_all_other_threads (void)
2075 gsize self = GetCurrentThreadId ();
2077 mono_threads_lock ();
2078 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2079 mono_g_hash_table_size (threads));
2080 mono_g_hash_table_foreach (threads, print_tids, NULL));
2082 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2084 mono_threads_unlock ();
2088 collect_threads (gpointer key, gpointer value, gpointer user_data)
2090 MonoThread *thread = (MonoThread*)value;
2091 struct wait_data *wait = (struct wait_data*)user_data;
2094 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2095 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2099 wait->handles [wait->num] = handle;
2100 wait->threads [wait->num] = thread;
2106 * mono_thread_suspend_all_other_threads:
2108 * Suspend all managed threads except the finalizer thread and this thread.
2110 void mono_thread_suspend_all_other_threads (void)
2112 struct wait_data *wait = g_new0 (struct wait_data, 1);
2114 gsize self = GetCurrentThreadId ();
2116 guint32 eventidx = 0;
2119 * Make a copy of the hashtable since we can't do anything with
2120 * threads while threads_mutex is held.
2122 mono_threads_lock ();
2123 mono_g_hash_table_foreach (threads, collect_threads, wait);
2124 mono_threads_unlock ();
2126 events = g_new0 (gpointer, wait->num);
2128 /* Get the suspended events that we'll be waiting for */
2129 for (i = 0; i < wait->num; ++i) {
2130 MonoThread *thread = wait->threads [i];
2132 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2133 //CloseHandle (wait->handles [i]);
2134 wait->threads [i] = NULL; /* ignore this thread in next loop */
2138 mono_monitor_enter (thread->synch_lock);
2140 if ((thread->state & ThreadState_Suspended) != 0 ||
2141 (thread->state & ThreadState_SuspendRequested) != 0 ||
2142 (thread->state & ThreadState_StopRequested) != 0 ||
2143 (thread->state & ThreadState_Stopped) != 0) {
2144 mono_monitor_exit (thread->synch_lock);
2145 CloseHandle (wait->handles [i]);
2146 wait->threads [i] = NULL; /* ignore this thread in next loop */
2150 /* Convert abort requests into suspend requests */
2151 if ((thread->state & ThreadState_AbortRequested) != 0)
2152 thread->state &= ~ThreadState_AbortRequested;
2154 thread->state |= ThreadState_SuspendRequested;
2156 if (thread->suspended_event == NULL)
2157 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2159 events [eventidx++] = thread->suspended_event;
2160 mono_monitor_exit (thread->synch_lock);
2162 /* Signal the thread to suspend */
2163 signal_thread_state_change (thread);
2166 WaitForMultipleObjectsEx (eventidx, events, TRUE, INFINITE, FALSE);
2167 for (i = 0; i < wait->num; ++i) {
2168 MonoThread *thread = wait->threads [i];
2173 mono_monitor_enter (thread->synch_lock);
2174 CloseHandle (thread->suspended_event);
2175 thread->suspended_event = NULL;
2176 mono_monitor_exit (thread->synch_lock);
2184 * mono_threads_request_thread_dump:
2186 * Ask all threads except the current to print their stacktrace to stdout.
2189 mono_threads_request_thread_dump (void)
2191 struct wait_data *wait = g_new0 (struct wait_data, 1);
2195 * Make a copy of the hashtable since we can't do anything with
2196 * threads while threads_mutex is held.
2198 mono_threads_lock ();
2199 mono_g_hash_table_foreach (threads, collect_threads, wait);
2200 mono_threads_unlock ();
2202 for (i = 0; i < wait->num; ++i) {
2203 MonoThread *thread = wait->threads [i];
2205 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2206 thread->thread_dump_requested = TRUE;
2208 signal_thread_state_change (thread);
2211 CloseHandle (wait->handles [i]);
2216 * mono_thread_push_appdomain_ref:
2218 * Register that the current thread may have references to objects in domain
2219 * @domain on its stack. Each call to this function should be paired with a
2220 * call to pop_appdomain_ref.
2223 mono_thread_push_appdomain_ref (MonoDomain *domain)
2225 MonoThread *thread = mono_thread_current ();
2228 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2229 mono_threads_lock ();
2230 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2231 mono_threads_unlock ();
2236 mono_thread_pop_appdomain_ref (void)
2238 MonoThread *thread = mono_thread_current ();
2241 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2242 mono_threads_lock ();
2243 /* FIXME: How can the list be empty ? */
2244 if (thread->appdomain_refs)
2245 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2246 mono_threads_unlock ();
2251 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2254 mono_threads_lock ();
2255 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2256 mono_threads_unlock ();
2260 typedef struct abort_appdomain_data {
2261 struct wait_data wait;
2263 } abort_appdomain_data;
2266 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2268 MonoThread *thread = (MonoThread*)value;
2269 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2270 MonoDomain *domain = data->domain;
2272 if (mono_thread_has_appdomain_ref (thread, domain)) {
2273 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2277 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2279 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2281 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2282 data->wait.handles [data->wait.num] = handle;
2283 data->wait.threads [data->wait.num] = thread;
2286 /* Just ignore the rest, we can't do anything with
2294 * mono_threads_abort_appdomain_threads:
2296 * Abort threads which has references to the given appdomain.
2299 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2301 abort_appdomain_data user_data;
2304 /* printf ("ABORT BEGIN.\n"); */
2306 start_time = GetTickCount ();
2308 mono_threads_lock ();
2310 user_data.domain = domain;
2311 user_data.wait.num = 0;
2312 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
2313 mono_threads_unlock ();
2315 if (user_data.wait.num > 0)
2317 * We should wait for the threads either to abort, or to leave the
2318 * domain. We can't do the latter, so we wait with a timeout.
2320 wait_for_tids (&user_data.wait, 100);
2322 /* Update remaining time */
2323 timeout -= GetTickCount () - start_time;
2324 start_time = GetTickCount ();
2329 while (user_data.wait.num > 0);
2331 /* printf ("ABORT DONE.\n"); */
2337 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
2339 MonoThread *thread = (MonoThread*)value;
2340 MonoDomain *domain = (MonoDomain*)user_data;
2343 /* No locking needed here */
2344 /* FIXME: why no locking? writes to the cache are protected with synch_lock above */
2346 if (thread->cached_culture_info) {
2347 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
2348 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
2349 if (obj && obj->vtable->domain == domain)
2350 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
2356 * mono_threads_clear_cached_culture:
2358 * Clear the cached_current_culture from all threads if it is in the
2362 mono_threads_clear_cached_culture (MonoDomain *domain)
2364 mono_threads_lock ();
2365 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
2366 mono_threads_unlock ();
2370 * mono_thread_get_pending_exception:
2372 * Return an exception which needs to be raised when leaving a catch clause.
2373 * This is used for undeniable exception propagation.
2376 mono_thread_get_pending_exception (void)
2378 MonoThread *thread = mono_thread_current ();
2380 MONO_ARCH_SAVE_REGS;
2382 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
2384 * FIXME: Clear the abort exception and return an AppDomainUnloaded
2385 * exception if the thread no longer references a dying appdomain.
2387 thread->abort_exc->trace_ips = NULL;
2388 thread->abort_exc->stack_trace = NULL;
2389 return thread->abort_exc;
2395 #define NUM_STATIC_DATA_IDX 8
2396 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
2397 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
2402 * mono_alloc_static_data
2404 * Allocate memory blocks for storing threads or context static data
2407 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
2409 guint idx = (offset >> 24) - 1;
2412 gpointer* static_data = *static_data_ptr;
2414 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
2415 *static_data_ptr = static_data;
2416 static_data [0] = static_data;
2419 for (i = 1; i <= idx; ++i) {
2420 if (static_data [i])
2422 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
2427 * mono_init_static_data_info
2429 * Initializes static data counters
2431 static void mono_init_static_data_info (StaticDataInfo *static_data)
2433 static_data->idx = 0;
2434 static_data->offset = 0;
2438 * mono_alloc_static_data_slot
2440 * Generates an offset for static data. static_data contains the counters
2441 * used to generate it.
2444 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
2448 if (!static_data->idx && !static_data->offset) {
2450 * we use the first chunk of the first allocation also as
2451 * an array for the rest of the data
2453 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
2455 static_data->offset += align - 1;
2456 static_data->offset &= ~(align - 1);
2457 if (static_data->offset + size >= static_data_size [static_data->idx]) {
2458 static_data->idx ++;
2459 g_assert (size <= static_data_size [static_data->idx]);
2461 * massive unloading and reloading of domains with thread-static
2462 * data may eventually exceed the allocated storage...
2463 * Need to check what the MS runtime does in that case.
2464 * Note that for each appdomain, we need to allocate a separate
2465 * thread data slot for security reasons. We could keep track
2466 * of the slots per-domain and when the domain is unloaded
2467 * out the slots on a sort of free list.
2469 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
2470 static_data->offset = 0;
2472 offset = static_data->offset | ((static_data->idx + 1) << 24);
2473 static_data->offset += size;
2478 * ensure thread static fields already allocated are valid for thread
2479 * This function is called when a thread is created or on thread attach.
2482 thread_adjust_static_data (MonoThread *thread)
2486 mono_threads_lock ();
2487 if (thread_static_info.offset || thread_static_info.idx > 0) {
2488 /* get the current allocated size */
2489 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
2490 mono_alloc_static_data (&(thread->static_data), offset);
2492 mono_threads_unlock ();
2496 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
2498 MonoThread *thread = value;
2499 guint32 offset = GPOINTER_TO_UINT (user);
2501 mono_alloc_static_data (&(thread->static_data), offset);
2505 * The offset for a special static variable is composed of three parts:
2506 * a bit that indicates the type of static data (0:thread, 1:context),
2507 * an index in the array of chunks of memory for the thread (thread->static_data)
2508 * and an offset in that chunk of mem. This allows allocating less memory in the
2513 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
2516 if (static_type == SPECIAL_STATIC_THREAD)
2518 mono_threads_lock ();
2519 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
2520 /* This can be called during startup */
2521 if (threads != NULL)
2522 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
2523 mono_threads_unlock ();
2527 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
2528 mono_contexts_lock ();
2529 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
2530 mono_contexts_unlock ();
2531 offset |= 0x80000000; /* Set the high bit to indicate context static data */
2537 mono_get_special_static_data (guint32 offset)
2539 /* The high bit means either thread (0) or static (1) data. */
2541 guint32 static_type = (offset & 0x80000000);
2544 offset &= 0x7fffffff;
2545 idx = (offset >> 24) - 1;
2547 if (static_type == 0)
2549 MonoThread *thread = mono_thread_current ();
2550 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2554 /* Allocate static data block under demand, since we don't have a list
2557 MonoAppContext *context = mono_context_get ();
2558 if (!context->static_data || !context->static_data [idx]) {
2559 mono_contexts_lock ();
2560 mono_alloc_static_data (&(context->static_data), offset);
2561 mono_contexts_unlock ();
2563 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
2567 static MonoClassField *local_slots = NULL;
2570 /* local tls data to get locals_slot from a thread */
2573 /* index in the locals_slot array */
2578 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
2580 LocalSlotID *sid = user_data;
2581 MonoThread *thread = (MonoThread*)value;
2582 MonoArray *slots_array;
2584 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
2585 * it is for the right domain, so we need to check if it is allocated an initialized
2586 * for the current thread.
2588 /*g_print ("handling thread %p\n", thread);*/
2589 if (!thread->static_data || !thread->static_data [sid->idx])
2591 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
2592 if (!slots_array || sid->slot >= mono_array_length (slots_array))
2594 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
2598 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
2606 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
2608 g_warning ("local_slots field not found in Thread class");
2612 domain = mono_domain_get ();
2613 mono_domain_lock (domain);
2614 if (domain->special_static_fields)
2615 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
2616 mono_domain_unlock (domain);
2619 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
2620 sid.offset = GPOINTER_TO_UINT (addr);
2621 sid.offset &= 0x7fffffff;
2622 sid.idx = (sid.offset >> 24) - 1;
2623 mono_threads_lock ();
2624 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
2625 mono_threads_unlock ();
2627 /* FIXME: clear the slot for MonoAppContexts, too */
2631 static void gc_stop_world (gpointer key, gpointer value, gpointer user)
2633 MonoThread *thread=(MonoThread *)value;
2635 LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, __func__, (gsize)user, (gsize)thread->tid));
2637 if(thread->tid == (gsize)user)
2640 SuspendThread (thread->handle);
2643 void mono_gc_stop_world (void)
2645 gsize self = GetCurrentThreadId ();
2647 LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %p", __func__, self, threads));
2649 mono_threads_lock ();
2651 if (threads != NULL)
2652 mono_g_hash_table_foreach (threads, gc_stop_world, (gpointer)self);
2654 mono_threads_unlock ();
2657 static void gc_start_world (gpointer key, gpointer value, gpointer user)
2659 MonoThread *thread=(MonoThread *)value;
2661 LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, __func__, (gsize)user, (gsize)thread->tid));
2663 if(thread->tid == (gsize)user)
2666 ResumeThread (thread->handle);
2669 void mono_gc_start_world (void)
2671 gsize self = GetCurrentThreadId ();
2673 LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %p", __func__, self, threads));
2675 mono_threads_lock ();
2677 if (threads != NULL)
2678 mono_g_hash_table_foreach (threads, gc_start_world, (gpointer)self);
2680 mono_threads_unlock ();
2684 static CALLBACK void dummy_apc (ULONG_PTR param)
2688 static guint32 dummy_apc (gpointer param)
2695 * mono_thread_execute_interruption
2697 * Performs the operation that the requested thread state requires (abort,
2700 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
2702 mono_monitor_enter (thread->synch_lock);
2704 if (thread->interruption_requested) {
2705 /* this will consume pending APC calls */
2706 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
2707 InterlockedDecrement (&thread_interruption_requested);
2708 thread->interruption_requested = FALSE;
2711 if ((thread->state & ThreadState_AbortRequested) != 0) {
2712 if (thread->abort_exc == NULL)
2713 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
2714 mono_monitor_exit (thread->synch_lock);
2715 return thread->abort_exc;
2717 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
2718 thread->state &= ~ThreadState_SuspendRequested;
2719 thread->state |= ThreadState_Suspended;
2720 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2721 if (thread->suspended_event)
2722 SetEvent (thread->suspended_event);
2723 mono_monitor_exit (thread->synch_lock);
2725 WaitForSingleObject (thread->suspend_event, INFINITE);
2727 mono_monitor_enter (thread->synch_lock);
2728 CloseHandle (thread->suspend_event);
2729 thread->suspend_event = NULL;
2730 thread->state &= ~ThreadState_Suspended;
2732 /* The thread that requested the resume will have replaced this event
2733 * and will be waiting for it
2735 SetEvent (thread->resume_event);
2736 mono_monitor_exit (thread->synch_lock);
2739 else if ((thread->state & ThreadState_StopRequested) != 0) {
2740 /* FIXME: do this through the JIT? */
2741 mono_monitor_exit (thread->synch_lock);
2742 mono_thread_exit ();
2746 mono_monitor_exit (thread->synch_lock);
2751 * mono_thread_request_interruption
2753 * A signal handler can call this method to request the interruption of a
2754 * thread. The result of the interruption will depend on the current state of
2755 * the thread. If the result is an exception that needs to be throw, it is
2756 * provided as return value.
2758 MonoException* mono_thread_request_interruption (gboolean running_managed)
2760 MonoThread *thread = mono_thread_current ();
2762 /* The thread may already be stopping */
2766 mono_monitor_enter (thread->synch_lock);
2768 if (thread->interruption_requested) {
2769 mono_monitor_exit (thread->synch_lock);
2773 if (!running_managed || is_running_protected_wrapper ()) {
2774 /* Can't stop while in unmanaged code. Increase the global interruption
2775 request count. When exiting the unmanaged method the count will be
2776 checked and the thread will be interrupted. */
2778 InterlockedIncrement (&thread_interruption_requested);
2779 thread->interruption_requested = TRUE;
2780 mono_monitor_exit (thread->synch_lock);
2782 /* this will awake the thread if it is in WaitForSingleObject
2784 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
2788 mono_monitor_exit (thread->synch_lock);
2789 return mono_thread_execute_interruption (thread);
2793 gboolean mono_thread_interruption_requested ()
2795 if (thread_interruption_requested) {
2796 MonoThread *thread = mono_thread_current ();
2797 /* The thread may already be stopping */
2799 return (thread->interruption_requested);
2804 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
2806 MonoThread *thread = mono_thread_current ();
2808 /* The thread may already be stopping */
2812 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
2813 MonoException* exc = mono_thread_execute_interruption (thread);
2814 if (exc) mono_raise_exception (exc);
2819 * Performs the interruption of the current thread, if one has been requested,
2820 * and the thread is not running a protected wrapper.
2822 void mono_thread_interruption_checkpoint ()
2824 mono_thread_interruption_checkpoint_request (FALSE);
2828 * Performs the interruption of the current thread, if one has been requested.
2830 void mono_thread_force_interruption_checkpoint ()
2832 mono_thread_interruption_checkpoint_request (TRUE);
2836 * mono_thread_interruption_request_flag:
2838 * Returns the address of a flag that will be non-zero if an interruption has
2839 * been requested for a thread. The thread to interrupt may not be the current
2840 * thread, so an additional call to mono_thread_interruption_requested() or
2841 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
2844 gint32* mono_thread_interruption_request_flag ()
2846 return &thread_interruption_requested;
2849 static void debugger_create_all_threads (gpointer key, gpointer value, gpointer user)
2851 MonoThread *thread = (MonoThread *)value;
2852 (* mono_thread_callbacks->thread_created) (thread->tid, thread->stack_ptr, NULL);
2856 mono_debugger_create_all_threads (void)
2858 mono_threads_lock ();
2859 mono_g_hash_table_foreach (threads, debugger_create_all_threads, NULL);
2860 mono_threads_unlock ();