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 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/domain-internals.h>
22 #include <mono/metadata/profiler-private.h>
23 #include <mono/metadata/threads.h>
24 #include <mono/metadata/threadpool.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/environment.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/gc-internal.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/runtime.h>
32 #include <mono/io-layer/io-layer.h>
34 #include <mono/io-layer/threads.h>
36 #include <mono/metadata/object-internals.h>
37 #include <mono/metadata/mono-debug-debugger.h>
38 #include <mono/utils/mono-compiler.h>
39 #include <mono/utils/mono-mmap.h>
40 #include <mono/utils/mono-membar.h>
41 #include <mono/utils/mono-time.h>
42 #include <mono/utils/mono-threads.h>
43 #include <mono/utils/hazard-pointer.h>
44 #include <mono/utils/mono-tls.h>
45 #include <mono/utils/atomic.h>
46 #include <mono/utils/mono-memory-model.h>
48 #include <mono/metadata/gc-internal.h>
50 #ifdef PLATFORM_ANDROID
53 extern int tkill (pid_t tid, int signal);
56 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
57 #define THREAD_DEBUG(a)
58 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
59 #define THREAD_WAIT_DEBUG(a)
60 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
61 #define LIBGC_DEBUG(a)
63 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
64 #define SPIN_LOCK(i) do { \
65 if (SPIN_TRYLOCK (i)) \
69 #define SPIN_UNLOCK(i) i = 0
71 #define LOCK_THREAD(thread) lock_thread((thread))
72 #define UNLOCK_THREAD(thread) unlock_thread((thread))
74 /* Provide this for systems with glib < 2.6 */
75 #ifndef G_GSIZE_FORMAT
76 # if GLIB_SIZEOF_LONG == 8
77 # define G_GSIZE_FORMAT "lu"
79 # define G_GSIZE_FORMAT "u"
85 guint32 (*func)(void *);
101 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
102 struct _MonoThreadDomainTls {
103 MonoThreadDomainTls *next;
111 MonoThreadDomainTls *freelist;
114 /* Number of cached culture objects in the MonoThread->cached_culture_info array
115 * (per-type): we use the first NUM entries for CultureInfo and the last for
116 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
118 #define NUM_CACHED_CULTURES 4
119 #define CULTURES_START_IDX 0
120 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
122 /* Controls access to the 'threads' hash table */
123 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
124 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
125 static CRITICAL_SECTION threads_mutex;
127 /* Controls access to context static data */
128 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
129 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
130 static CRITICAL_SECTION contexts_mutex;
132 /* Controls access to the 'joinable_threads' hash table */
133 #define joinable_threads_lock() EnterCriticalSection (&joinable_threads_mutex)
134 #define joinable_threads_unlock() LeaveCriticalSection (&joinable_threads_mutex)
135 static CRITICAL_SECTION joinable_threads_mutex;
137 /* Holds current status of static data heap */
138 static StaticDataInfo thread_static_info;
139 static StaticDataInfo context_static_info;
141 /* The hash of existing threads (key is thread ID, value is
142 * MonoInternalThread*) that need joining before exit
144 static MonoGHashTable *threads=NULL;
147 * Threads which are starting up and they are not in the 'threads' hash yet.
148 * When handle_store is called for a thread, it will be removed from this hash table.
149 * Protected by mono_threads_lock ().
151 static MonoGHashTable *threads_starting_up = NULL;
153 /* Maps a MonoThread to its start argument */
154 /* Protected by mono_threads_lock () */
155 static MonoGHashTable *thread_start_args = NULL;
157 /* The TLS key that holds the MonoObject assigned to each thread */
158 static MonoNativeTlsKey current_object_key;
161 /* Protected by the threads lock */
162 static GHashTable *joinable_threads;
163 static int joinable_thread_count;
165 #ifdef MONO_HAVE_FAST_TLS
166 /* we need to use both the Tls* functions and __thread because
167 * the gc needs to see all the threads
169 MONO_FAST_TLS_DECLARE(tls_current_object);
170 #define SET_CURRENT_OBJECT(x) do { \
171 MONO_FAST_TLS_SET (tls_current_object, x); \
172 mono_native_tls_set_value (current_object_key, x); \
174 #define GET_CURRENT_OBJECT() ((MonoInternalThread*) MONO_FAST_TLS_GET (tls_current_object))
176 #define SET_CURRENT_OBJECT(x) mono_native_tls_set_value (current_object_key, x)
177 #define GET_CURRENT_OBJECT() (MonoInternalThread*) mono_native_tls_get_value (current_object_key)
180 /* function called at thread start */
181 static MonoThreadStartCB mono_thread_start_cb = NULL;
183 /* function called at thread attach */
184 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
186 /* function called at thread cleanup */
187 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
189 /* function called to notify the runtime about a pending exception on the current thread */
190 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
192 /* The default stack size for each thread */
193 static guint32 default_stacksize = 0;
194 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
196 static void thread_adjust_static_data (MonoInternalThread *thread);
197 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
198 static void mono_init_static_data_info (StaticDataInfo *static_data);
199 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
200 static gboolean mono_thread_resume (MonoInternalThread* thread);
201 static void signal_thread_state_change (MonoInternalThread *thread);
202 static void abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort);
203 static void suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt);
204 static void self_suspend_internal (MonoInternalThread *thread);
205 static gboolean resume_thread_internal (MonoInternalThread *thread);
207 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
208 static void ref_stack_destroy (gpointer rs);
210 /* Spin lock for InterlockedXXX 64 bit functions */
211 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
212 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
213 static CRITICAL_SECTION interlocked_mutex;
215 /* global count of thread interruptions requested */
216 static gint32 thread_interruption_requested = 0;
218 /* Event signaled when a thread changes its background mode */
219 static HANDLE background_change_event;
221 static gboolean shutting_down = FALSE;
223 static gint32 managed_thread_id_counter = 0;
226 get_next_managed_thread_id (void)
228 return InterlockedIncrement (&managed_thread_id_counter);
232 mono_thread_get_tls_key (void)
234 return current_object_key;
238 mono_thread_get_tls_offset (void)
241 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
245 /* handle_store() and handle_remove() manage the array of threads that
246 * still need to be waited for when the main thread exits.
248 * If handle_store() returns FALSE the thread must not be started
249 * because Mono is shutting down.
251 static gboolean handle_store(MonoThread *thread, gboolean force_attach)
253 mono_threads_lock ();
255 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->internal_thread->tid));
257 if (threads_starting_up)
258 mono_g_hash_table_remove (threads_starting_up, thread);
260 if (shutting_down && !force_attach) {
261 mono_threads_unlock ();
266 MONO_GC_REGISTER_ROOT_FIXED (threads);
267 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
270 /* We don't need to duplicate thread->handle, because it is
271 * only closed when the thread object is finalized by the GC.
273 g_assert (thread->internal_thread);
274 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
275 thread->internal_thread);
277 mono_threads_unlock ();
282 static gboolean handle_remove(MonoInternalThread *thread)
285 gsize tid = thread->tid;
287 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
289 mono_threads_lock ();
292 /* We have to check whether the thread object for the
293 * tid is still the same in the table because the
294 * thread might have been destroyed and the tid reused
295 * in the meantime, in which case the tid would be in
296 * the table, but with another thread object.
298 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
299 mono_g_hash_table_remove (threads, (gpointer)tid);
308 mono_threads_unlock ();
310 /* Don't close the handle here, wait for the object finalizer
311 * to do it. Otherwise, the following race condition applies:
313 * 1) Thread exits (and handle_remove() closes the handle)
315 * 2) Some other handle is reassigned the same slot
317 * 3) Another thread tries to join the first thread, and
318 * blocks waiting for the reassigned handle to be signalled
319 * (which might never happen). This is possible, because the
320 * thread calling Join() still has a reference to the first
326 static void ensure_synch_cs_set (MonoInternalThread *thread)
328 CRITICAL_SECTION *synch_cs;
330 if (thread->synch_cs != NULL) {
334 synch_cs = g_new0 (CRITICAL_SECTION, 1);
335 InitializeCriticalSection (synch_cs);
337 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
338 synch_cs, NULL) != NULL) {
339 /* Another thread must have installed this CS */
340 DeleteCriticalSection (synch_cs);
346 lock_thread (MonoInternalThread *thread)
348 if (!thread->synch_cs)
349 ensure_synch_cs_set (thread);
351 g_assert (thread->synch_cs);
352 EnterCriticalSection (thread->synch_cs);
356 unlock_thread (MonoInternalThread *thread)
358 LeaveCriticalSection (thread->synch_cs);
362 * NOTE: this function can be called also for threads different from the current one:
363 * make sure no code called from it will ever assume it is run on the thread that is
364 * getting cleaned up.
366 static void thread_cleanup (MonoInternalThread *thread)
368 g_assert (thread != NULL);
370 if (thread->abort_state_handle) {
371 mono_gchandle_free (thread->abort_state_handle);
372 thread->abort_state_handle = 0;
374 thread->abort_exc = NULL;
375 thread->current_appcontext = NULL;
378 * This is necessary because otherwise we might have
379 * cross-domain references which will not get cleaned up when
380 * the target domain is unloaded.
382 if (thread->cached_culture_info) {
384 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
385 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
388 if (thread->synch_cs)
389 LOCK_THREAD (thread);
391 g_assert (shutting_down);
393 thread->state |= ThreadState_Stopped;
394 thread->state &= ~ThreadState_Background;
396 if (thread->synch_cs)
397 UNLOCK_THREAD (thread);
400 An interruption request has leaked to cleanup. Adjust the global counter.
402 This can happen is the abort source thread finds the abortee (this) thread
403 in unmanaged code. If this thread never trips back to managed code or check
404 the local flag it will be left set and positively unbalance the global counter.
406 Leaving the counter unbalanced will cause a performance degradation since all threads
407 will now keep checking their local flags all the time.
409 if (InterlockedExchange (&thread->interruption_requested, 0))
410 InterlockedDecrement (&thread_interruption_requested);
412 /* if the thread is not in the hash it has been removed already */
413 if (!handle_remove (thread)) {
414 if (thread == mono_thread_internal_current ()) {
415 mono_domain_unset ();
416 mono_memory_barrier ();
418 /* This needs to be called even if handle_remove () fails */
419 if (mono_thread_cleanup_fn)
420 mono_thread_cleanup_fn (thread);
423 mono_release_type_locks (thread);
425 mono_profiler_thread_end (thread->tid);
427 if (thread == mono_thread_internal_current ()) {
429 * This will signal async signal handlers that the thread has exited.
430 * The profiler callback needs this to be set, so it cannot be done earlier.
432 mono_domain_unset ();
433 mono_memory_barrier ();
436 if (thread == mono_thread_internal_current ())
437 mono_thread_pop_appdomain_ref ();
439 thread->cached_culture_info = NULL;
441 mono_free_static_data (thread->static_data, TRUE);
442 thread->static_data = NULL;
443 ref_stack_destroy (thread->appdomain_refs);
444 thread->appdomain_refs = NULL;
446 if (mono_thread_cleanup_fn)
447 mono_thread_cleanup_fn (thread);
449 if (mono_gc_is_moving ()) {
450 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
451 thread->thread_pinning_ref = NULL;
456 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
459 g_assert ((offset & 0x80000000) == 0);
460 offset &= 0x7fffffff;
461 idx = (offset >> 24) - 1;
462 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
466 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
468 static MonoClassField *current_thread_field = NULL;
472 if (!current_thread_field) {
473 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
474 g_assert (current_thread_field);
477 mono_class_vtable (domain, mono_defaults.thread_class);
478 mono_domain_lock (domain);
479 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
480 mono_domain_unlock (domain);
483 return get_thread_static_data (thread, offset);
487 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
489 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
491 g_assert (current->obj.vtable->domain == domain);
493 g_assert (!*current_thread_ptr);
494 *current_thread_ptr = current;
498 create_thread_object (MonoDomain *domain)
500 MonoVTable *vt = mono_class_vtable (domain, mono_defaults.thread_class);
501 return (MonoThread*)mono_gc_alloc_mature (vt);
505 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
507 MonoThread *thread = create_thread_object (domain);
508 MONO_OBJECT_SETREF (thread, internal_thread, internal);
512 static MonoInternalThread*
513 create_internal_thread (void)
515 MonoInternalThread *thread;
518 vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
519 thread = (MonoInternalThread*)mono_gc_alloc_mature (vt);
521 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
522 InitializeCriticalSection (thread->synch_cs);
524 thread->apartment_state = ThreadApartmentState_Unknown;
525 thread->managed_id = get_next_managed_thread_id ();
526 if (mono_gc_is_moving ()) {
527 thread->thread_pinning_ref = thread;
528 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref);
535 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
537 MonoDomain *domain = mono_get_root_domain ();
539 if (!candidate || candidate->obj.vtable->domain != domain)
540 candidate = new_thread_with_internal (domain, thread);
541 set_current_thread_for_domain (domain, thread, candidate);
542 g_assert (!thread->root_domain_thread);
543 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
546 static guint32 WINAPI start_wrapper_internal(void *data)
548 MonoThreadInfo *info;
549 StartInfo *start_info = (StartInfo *)data;
550 guint32 (*start_func)(void *);
554 * We don't create a local to hold start_info->obj, so hopefully it won't get pinned during a
557 MonoInternalThread *internal = start_info->obj->internal_thread;
558 MonoObject *start_delegate = start_info->delegate;
559 MonoDomain *domain = start_info->obj->obj.vtable->domain;
561 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
563 /* We can be sure start_info->obj->tid and
564 * start_info->obj->handle have been set, because the thread
565 * was created suspended, and these values were set before the
569 info = mono_thread_info_current ();
571 internal->thread_info = info;
576 SET_CURRENT_OBJECT (internal);
578 mono_monitor_init_tls ();
580 /* Every thread references the appdomain which created it */
581 mono_thread_push_appdomain_ref (domain);
583 if (!mono_domain_set (domain, FALSE)) {
584 /* No point in raising an appdomain_unloaded exception here */
585 /* FIXME: Cleanup here */
586 mono_thread_pop_appdomain_ref ();
590 start_func = start_info->func;
591 start_arg = start_info->start_arg;
593 /* We have to do this here because mono_thread_new_init()
594 requires that root_domain_thread is set up. */
595 thread_adjust_static_data (internal);
596 init_root_domain_thread (internal, start_info->obj);
598 /* This MUST be called before any managed code can be
599 * executed, as it calls the callback function that (for the
600 * jit) sets the lmf marker.
602 mono_thread_new_init (tid, &tid, start_func);
603 internal->stack_ptr = &tid;
605 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
607 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), internal));
609 /* On 2.0 profile (and higher), set explicitly since state might have been
611 if (internal->apartment_state == ThreadApartmentState_Unknown)
612 internal->apartment_state = ThreadApartmentState_MTA;
614 mono_thread_init_apartment_state ();
616 if(internal->start_notify!=NULL) {
617 /* Let the thread that called Start() know we're
620 ReleaseSemaphore (internal->start_notify, 1, NULL);
623 mono_threads_lock ();
624 mono_g_hash_table_remove (thread_start_args, start_info->obj);
625 mono_threads_unlock ();
627 mono_thread_set_execution_context (start_info->obj->ec_to_set);
628 start_info->obj->ec_to_set = NULL;
631 THREAD_DEBUG (g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
635 * Call this after calling start_notify, since the profiler callback might want
636 * to lock the thread, and the lock is held by thread_start () which waits for
639 mono_profiler_thread_start (tid);
641 /* start_func is set only for unmanaged start functions */
643 start_func (start_arg);
646 g_assert (start_delegate != NULL);
647 args [0] = start_arg;
648 /* we may want to handle the exception here. See comment below on unhandled exceptions */
649 mono_runtime_delegate_invoke (start_delegate, args, NULL);
652 /* If the thread calls ExitThread at all, this remaining code
653 * will not be executed, but the main thread will eventually
654 * call thread_cleanup() on this thread's behalf.
657 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
659 /* Do any cleanup needed for apartment state. This
660 * cannot be done in thread_cleanup since thread_cleanup could be
661 * called for a thread other than the current thread.
662 * mono_thread_cleanup_apartment_state cleans up apartment
663 * for the current thead */
664 mono_thread_cleanup_apartment_state ();
666 thread_cleanup (internal);
668 /* Remove the reference to the thread object in the TLS data,
669 * so the thread object can be finalized. This won't be
670 * reached if the thread threw an uncaught exception, so those
671 * thread handles will stay referenced :-( (This is due to
672 * missing support for scanning thread-specific data in the
673 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
676 SET_CURRENT_OBJECT (NULL);
681 static guint32 WINAPI start_wrapper(void *data)
685 /* Avoid scanning the frames above this frame during a GC */
686 mono_gc_set_stack_end ((void*)&dummy);
688 return start_wrapper_internal (data);
694 * Common thread creation code.
695 * LOCKING: Acquires the threads lock.
698 create_thread (MonoThread *thread, MonoInternalThread *internal, StartInfo *start_info, gboolean threadpool_thread, guint32 stack_size,
699 gboolean throw_on_failure)
701 HANDLE thread_handle;
702 MonoNativeThreadId tid;
703 guint32 create_flags;
705 mono_threads_lock ();
708 mono_threads_unlock ();
712 * The thread start argument may be an object reference, and there is
713 * no ref to keep it alive when the new thread is started but not yet
714 * registered with the collector. So we store it in a GC tracked hash
717 if (thread_start_args == NULL) {
718 MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
719 thread_start_args = mono_g_hash_table_new (NULL, NULL);
721 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
722 if (threads_starting_up == NULL) {
723 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
724 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
726 mono_g_hash_table_insert (threads_starting_up, thread, thread);
727 mono_threads_unlock ();
729 internal->start_notify = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
730 if (!internal->start_notify) {
731 mono_threads_lock ();
732 mono_g_hash_table_remove (threads_starting_up, thread);
733 mono_threads_unlock ();
734 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
740 stack_size = default_stacksize_for_thread (internal);
742 /* Create suspended, so we can do some housekeeping before the thread
745 create_flags = CREATE_SUSPENDED;
746 thread_handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)start_wrapper, start_info,
747 stack_size, create_flags, &tid);
748 if (thread_handle == NULL) {
749 /* The thread couldn't be created, so throw an exception */
750 mono_threads_lock ();
751 mono_g_hash_table_remove (threads_starting_up, thread);
752 mono_threads_unlock ();
754 if (throw_on_failure)
755 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
757 g_warning ("%s: CreateThread error 0x%x", __func__, GetLastError ());
760 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
762 internal->handle = thread_handle;
763 internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (tid);
765 internal->threadpool_thread = threadpool_thread;
766 if (threadpool_thread)
767 mono_thread_set_state (internal, ThreadState_Background);
769 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
771 /* Only store the handle when the thread is about to be
772 * launched, to avoid the main thread deadlocking while trying
773 * to clean up a thread that will never be signalled.
775 if (!handle_store (thread, FALSE))
778 mono_thread_info_resume (tid);
780 if (internal->start_notify) {
782 * Wait for the thread to set up its TLS data etc, so
783 * theres no potential race condition if someone tries
784 * to look up the data believing the thread has
787 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
789 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
790 CloseHandle (internal->start_notify);
791 internal->start_notify = NULL;
794 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
799 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
801 if (mono_thread_start_cb) {
802 mono_thread_start_cb (tid, stack_start, func);
806 void mono_threads_set_default_stacksize (guint32 stacksize)
808 default_stacksize = stacksize;
811 guint32 mono_threads_get_default_stacksize (void)
813 return default_stacksize;
817 * mono_thread_create_internal:
821 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
824 MonoInternalThread *internal;
825 StartInfo *start_info;
828 thread = create_thread_object (domain);
829 internal = create_internal_thread ();
830 MONO_OBJECT_SETREF (thread, internal_thread, internal);
832 start_info = g_new0 (StartInfo, 1);
833 start_info->func = func;
834 start_info->obj = thread;
835 start_info->start_arg = arg;
837 res = create_thread (thread, internal, start_info, threadpool_thread, stack_size, TRUE);
841 /* Check that the managed and unmanaged layout of MonoInternalThread matches */
842 if (mono_check_corlib_version () == NULL)
843 g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
849 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
851 mono_thread_create_internal (domain, func, arg, FALSE, 0);
855 mono_thread_attach (MonoDomain *domain)
857 return mono_thread_attach_full (domain, FALSE);
861 mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
863 MonoThreadInfo *info;
864 MonoInternalThread *thread;
865 MonoThread *current_thread;
866 HANDLE thread_handle;
869 if ((thread = mono_thread_internal_current ())) {
870 if (domain != mono_domain_get ())
871 mono_domain_set (domain, TRUE);
872 /* Already attached */
873 return mono_thread_current ();
876 if (!mono_gc_register_thread (&domain)) {
877 g_error ("Thread %"G_GSIZE_FORMAT" 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.", GetCurrentThreadId ());
880 thread = create_internal_thread ();
882 thread_handle = mono_thread_info_open_handle ();
883 g_assert (thread_handle);
885 tid=GetCurrentThreadId ();
887 thread->handle=thread_handle;
889 #ifdef PLATFORM_ANDROID
890 thread->android_tid = (gpointer) gettid ();
892 thread->stack_ptr = &tid;
894 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
896 info = mono_thread_info_current ();
898 thread->thread_info = info;
900 current_thread = new_thread_with_internal (domain, thread);
902 if (!handle_store (current_thread, force_attach)) {
903 /* Mono is shutting down, so just wait for the end */
908 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
910 SET_CURRENT_OBJECT (thread);
911 mono_domain_set (domain, TRUE);
913 mono_monitor_init_tls ();
915 thread_adjust_static_data (thread);
917 init_root_domain_thread (thread, current_thread);
918 if (domain != mono_get_root_domain ())
919 set_current_thread_for_domain (domain, thread, current_thread);
922 if (mono_thread_attach_cb) {
926 mono_thread_info_get_stack_bounds (&staddr, &stsize);
929 mono_thread_attach_cb (tid, &tid);
931 mono_thread_attach_cb (tid, staddr + stsize);
934 // FIXME: Need a separate callback
935 mono_profiler_thread_start (tid);
937 return current_thread;
941 mono_thread_detach (MonoThread *thread)
943 g_return_if_fail (thread != NULL);
945 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->internal_thread->tid));
947 thread_cleanup (thread->internal_thread);
949 SET_CURRENT_OBJECT (NULL);
950 mono_domain_unset ();
952 /* Don't need to CloseHandle this thread, even though we took a
953 * reference in mono_thread_attach (), because the GC will do it
954 * when the Thread object is finalised.
961 MonoInternalThread *thread = mono_thread_internal_current ();
963 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
965 thread_cleanup (thread);
966 SET_CURRENT_OBJECT (NULL);
967 mono_domain_unset ();
969 /* we could add a callback here for embedders to use. */
970 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
971 exit (mono_environment_exitcode_get ());
972 mono_thread_info_exit ();
976 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
978 MonoInternalThread *internal = create_internal_thread ();
980 internal->state = ThreadState_Unstarted;
982 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
986 ves_icall_System_Threading_Thread_Thread_internal (MonoThread *this,
989 StartInfo *start_info;
990 MonoInternalThread *internal;
993 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
995 if (!this->internal_thread)
996 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
997 internal = this->internal_thread;
999 LOCK_THREAD (internal);
1001 if ((internal->state & ThreadState_Unstarted) == 0) {
1002 UNLOCK_THREAD (internal);
1003 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1007 if ((internal->state & ThreadState_Aborted) != 0) {
1008 UNLOCK_THREAD (internal);
1011 /* This is freed in start_wrapper */
1012 start_info = g_new0 (StartInfo, 1);
1013 start_info->func = NULL;
1014 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1015 start_info->delegate = start;
1016 start_info->obj = this;
1017 g_assert (this->obj.vtable->domain == mono_domain_get ());
1019 res = create_thread (this, internal, start_info, FALSE, 0, FALSE);
1021 UNLOCK_THREAD (internal);
1025 internal->state &= ~ThreadState_Unstarted;
1027 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1029 UNLOCK_THREAD (internal);
1030 return internal->handle;
1034 * This is called from the finalizer of the internal thread object. Since threads keep a reference to their
1035 * thread object while running, by the time this function is called, the thread has already exited/detached,
1036 * i.e. thread_cleanup () has ran.
1039 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1041 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1044 CloseHandle (thread);
1046 if (this->synch_cs) {
1047 CRITICAL_SECTION *synch_cs = this->synch_cs;
1048 this->synch_cs = NULL;
1049 DeleteCriticalSection (synch_cs);
1054 void *name = this->name;
1060 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1063 MonoInternalThread *thread = mono_thread_internal_current ();
1065 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1067 mono_thread_current_check_pending_interrupt ();
1070 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1072 res = SleepEx(ms,TRUE);
1074 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1076 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1077 MonoException* exc = mono_thread_execute_interruption (thread);
1079 mono_raise_exception (exc);
1091 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1096 ves_icall_System_Threading_Thread_GetDomainID (void)
1098 return mono_domain_get()->domain_id;
1102 ves_icall_System_Threading_Thread_Yield (void)
1104 return mono_thread_info_yield ();
1108 * mono_thread_get_name:
1110 * Return the name of the thread. NAME_LEN is set to the length of the name.
1111 * Return NULL if the thread has no name. The returned memory is owned by the
1115 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1119 LOCK_THREAD (this_obj);
1121 if (!this_obj->name) {
1125 *name_len = this_obj->name_len;
1126 res = g_new (gunichar2, this_obj->name_len);
1127 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1130 UNLOCK_THREAD (this_obj);
1136 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1140 LOCK_THREAD (this_obj);
1142 if (!this_obj->name)
1145 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1147 UNLOCK_THREAD (this_obj);
1153 mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean managed)
1155 LOCK_THREAD (this_obj);
1157 if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1158 UNLOCK_THREAD (this_obj);
1160 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1164 this_obj->name = g_new (gunichar2, mono_string_length (name));
1165 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1166 this_obj->name_len = mono_string_length (name);
1169 this_obj->name = NULL;
1172 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1174 UNLOCK_THREAD (this_obj);
1176 if (this_obj->name) {
1177 char *tname = mono_string_to_utf8 (name);
1178 mono_profiler_thread_name (this_obj->tid, tname);
1184 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1186 mono_thread_set_name_internal (this_obj, name, TRUE);
1189 /* If the array is already in the requested domain, we just return it,
1190 otherwise we return a copy in that domain. */
1192 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1199 if (mono_object_domain (arr) == domain)
1202 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1203 memmove (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1208 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1210 return byte_array_to_domain (arr, mono_get_root_domain ());
1214 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1216 return byte_array_to_domain (arr, mono_domain_get ());
1220 mono_thread_current (void)
1222 MonoDomain *domain = mono_domain_get ();
1223 MonoInternalThread *internal = mono_thread_internal_current ();
1224 MonoThread **current_thread_ptr;
1226 g_assert (internal);
1227 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1229 if (!*current_thread_ptr) {
1230 g_assert (domain != mono_get_root_domain ());
1231 *current_thread_ptr = new_thread_with_internal (domain, internal);
1233 return *current_thread_ptr;
1237 mono_thread_internal_current (void)
1239 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1240 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1244 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1245 int ms, HANDLE thread)
1247 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1250 mono_thread_current_check_pending_interrupt ();
1254 if ((this->state & ThreadState_Unstarted) != 0) {
1255 UNLOCK_THREAD (this);
1257 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1261 UNLOCK_THREAD (this);
1266 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1268 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1270 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1272 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1274 if(ret==WAIT_OBJECT_0) {
1275 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1280 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1286 mono_wait_uninterrupted (MonoInternalThread *thread, gboolean multiple, guint32 numhandles, gpointer *handles, gboolean waitall, gint32 ms, gboolean alertable)
1294 start = (ms == -1) ? 0 : mono_100ns_ticks ();
1297 ret = WaitForMultipleObjectsEx (numhandles, handles, waitall, wait, alertable);
1299 ret = WaitForSingleObjectEx (handles [0], ms, alertable);
1301 if (ret != WAIT_IO_COMPLETION)
1304 exc = mono_thread_execute_interruption (thread);
1306 mono_raise_exception (exc);
1311 /* Re-calculate ms according to the time passed */
1312 diff_ms = (mono_100ns_ticks () - start) / 10000;
1313 if (diff_ms >= ms) {
1317 wait = ms - diff_ms;
1323 /* FIXME: exitContext isnt documented */
1324 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1330 MonoObject *waitHandle;
1331 MonoInternalThread *thread = mono_thread_internal_current ();
1333 /* Do this WaitSleepJoin check before creating objects */
1334 mono_thread_current_check_pending_interrupt ();
1336 numhandles = mono_array_length(mono_handles);
1337 handles = g_new0(HANDLE, numhandles);
1339 for(i = 0; i < numhandles; i++) {
1340 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1341 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1348 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1350 ret = mono_wait_uninterrupted (thread, TRUE, numhandles, handles, TRUE, ms, TRUE);
1352 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1356 if(ret==WAIT_FAILED) {
1357 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1359 } else if(ret==WAIT_TIMEOUT) {
1360 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1367 /* FIXME: exitContext isnt documented */
1368 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1370 HANDLE handles [MAXIMUM_WAIT_OBJECTS];
1374 MonoObject *waitHandle;
1375 MonoInternalThread *thread = mono_thread_internal_current ();
1377 /* Do this WaitSleepJoin check before creating objects */
1378 mono_thread_current_check_pending_interrupt ();
1380 numhandles = mono_array_length(mono_handles);
1381 if (numhandles > MAXIMUM_WAIT_OBJECTS)
1384 for(i = 0; i < numhandles; i++) {
1385 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1386 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1393 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1395 ret = mono_wait_uninterrupted (thread, TRUE, numhandles, handles, FALSE, ms, TRUE);
1397 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1399 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1402 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1404 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1405 return ret - WAIT_OBJECT_0;
1407 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1408 return ret - WAIT_ABANDONED_0;
1415 /* FIXME: exitContext isnt documented */
1416 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1419 MonoInternalThread *thread = mono_thread_internal_current ();
1421 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1427 mono_thread_current_check_pending_interrupt ();
1429 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1431 ret = mono_wait_uninterrupted (thread, FALSE, 1, &handle, FALSE, ms, TRUE);
1433 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1435 if(ret==WAIT_FAILED) {
1436 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1438 } else if(ret==WAIT_TIMEOUT) {
1439 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1447 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1450 MonoInternalThread *thread = mono_thread_internal_current ();
1455 mono_thread_current_check_pending_interrupt ();
1457 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1459 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1461 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1463 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1466 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1473 mutex = CreateMutex (NULL, owned, NULL);
1475 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1477 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1485 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1486 return(ReleaseMutex (handle));
1489 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1495 *error = ERROR_SUCCESS;
1497 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1499 *error = GetLastError ();
1506 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1513 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1515 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1516 mono_string_chars (name));
1518 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1526 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1530 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1535 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1539 *error = ERROR_SUCCESS;
1541 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1543 *error = GetLastError ();
1549 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1556 event = CreateEvent (NULL, manual, initial, NULL);
1558 event = CreateEvent (NULL, manual, initial,
1559 mono_string_chars (name));
1561 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1569 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1570 return (SetEvent(handle));
1573 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1574 return (ResetEvent(handle));
1578 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1579 CloseHandle (handle);
1582 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1588 *error = ERROR_SUCCESS;
1590 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1592 *error = GetLastError ();
1598 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1600 return InterlockedIncrement (location);
1603 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1605 #if SIZEOF_VOID_P == 4
1606 if (G_UNLIKELY ((size_t)location & 0x7)) {
1608 mono_interlocked_lock ();
1611 mono_interlocked_unlock ();
1615 return InterlockedIncrement64 (location);
1618 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1620 return InterlockedDecrement(location);
1623 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1625 #if SIZEOF_VOID_P == 4
1626 if (G_UNLIKELY ((size_t)location & 0x7)) {
1628 mono_interlocked_lock ();
1631 mono_interlocked_unlock ();
1635 return InterlockedDecrement64 (location);
1638 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1640 return InterlockedExchange(location, value);
1643 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1646 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1647 mono_gc_wbarrier_generic_nostore (location);
1651 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1653 return InterlockedExchangePointer(location, value);
1656 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1658 IntFloatUnion val, ret;
1661 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1667 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1669 #if SIZEOF_VOID_P == 4
1670 if (G_UNLIKELY ((size_t)location & 0x7)) {
1672 mono_interlocked_lock ();
1675 mono_interlocked_unlock ();
1679 return InterlockedExchange64 (location, value);
1683 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1685 LongDoubleUnion val, ret;
1688 ret.ival = (gint64)InterlockedExchange64((gint64 *) location, val.ival);
1693 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1695 return InterlockedCompareExchange(location, value, comparand);
1698 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1701 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1702 mono_gc_wbarrier_generic_nostore (location);
1706 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1708 return InterlockedCompareExchangePointer(location, value, comparand);
1711 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1713 IntFloatUnion val, ret, cmp;
1716 cmp.fval = comparand;
1717 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1723 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1725 #if SIZEOF_VOID_P == 8
1726 LongDoubleUnion val, comp, ret;
1729 comp.fval = comparand;
1730 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1736 mono_interlocked_lock ();
1738 if (old == comparand)
1740 mono_interlocked_unlock ();
1747 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1749 #if SIZEOF_VOID_P == 4
1750 if (G_UNLIKELY ((size_t)location & 0x7)) {
1752 mono_interlocked_lock ();
1754 if (old == comparand)
1756 mono_interlocked_unlock ();
1760 return InterlockedCompareExchange64 (location, value, comparand);
1764 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1767 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1768 mono_gc_wbarrier_generic_nostore (location);
1773 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1776 res = InterlockedExchangePointer ((gpointer *)location, value);
1777 mono_gc_wbarrier_generic_nostore (location);
1782 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1784 return InterlockedAdd (location, value);
1788 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1790 #if SIZEOF_VOID_P == 4
1791 if (G_UNLIKELY ((size_t)location & 0x7)) {
1793 mono_interlocked_lock ();
1796 mono_interlocked_unlock ();
1800 return InterlockedAdd64 (location, value);
1804 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1806 #if SIZEOF_VOID_P == 4
1807 if (G_UNLIKELY ((size_t)location & 0x7)) {
1809 mono_interlocked_lock ();
1811 mono_interlocked_unlock ();
1815 return InterlockedRead64 (location);
1819 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1821 mono_memory_barrier ();
1825 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
1827 mono_thread_clr_state (this, state);
1829 if (state & ThreadState_Background) {
1830 /* If the thread changes the background mode, the main thread has to
1831 * be notified, since it has to rebuild the list of threads to
1834 SetEvent (background_change_event);
1839 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
1841 mono_thread_set_state (this, state);
1843 if (state & ThreadState_Background) {
1844 /* If the thread changes the background mode, the main thread has to
1845 * be notified, since it has to rebuild the list of threads to
1848 SetEvent (background_change_event);
1853 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
1859 state = this->state;
1861 UNLOCK_THREAD (this);
1866 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
1868 MonoInternalThread *current;
1873 current = mono_thread_internal_current ();
1875 this->thread_interrupt_requested = TRUE;
1876 throw = current != this && (this->state & ThreadState_WaitSleepJoin);
1878 UNLOCK_THREAD (this);
1881 abort_thread_internal (this, TRUE, FALSE);
1885 void mono_thread_current_check_pending_interrupt ()
1887 MonoInternalThread *thread = mono_thread_internal_current ();
1888 gboolean throw = FALSE;
1890 LOCK_THREAD (thread);
1892 if (thread->thread_interrupt_requested) {
1894 thread->thread_interrupt_requested = FALSE;
1897 UNLOCK_THREAD (thread);
1900 mono_raise_exception (mono_get_exception_thread_interrupted ());
1905 mono_thread_get_abort_signal (void)
1909 #elif defined(PLATFORM_ANDROID)
1911 #elif !defined (SIGRTMIN)
1916 #endif /* SIGUSR1 */
1918 static int abort_signum = -1;
1920 if (abort_signum != -1)
1921 return abort_signum;
1922 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1923 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1924 struct sigaction sinfo;
1925 sigaction (i, NULL, &sinfo);
1926 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1931 /* fallback to the old way */
1933 #endif /* HOST_WIN32 */
1937 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1939 MonoException* exc = mono_thread_request_interruption (FALSE);
1940 if (exc) mono_raise_exception (exc);
1942 #endif /* HOST_WIN32 */
1945 * signal_thread_state_change
1947 * Tells the thread that his state has changed and it has to enter the new
1948 * state as soon as possible.
1950 static void signal_thread_state_change (MonoInternalThread *thread)
1952 if (thread == mono_thread_internal_current ()) {
1953 /* Do it synchronously */
1954 MonoException *exc = mono_thread_request_interruption (FALSE);
1956 mono_raise_exception (exc);
1960 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1962 /* fixme: store the state somewhere */
1963 mono_thread_kill (thread, mono_thread_get_abort_signal ());
1966 * This will cause waits to be broken.
1967 * It will also prevent the thread from entering a wait, so if the thread returns
1968 * from the wait before it receives the abort signal, it will just spin in the wait
1969 * functions in the io-layer until the signal handler calls QueueUserAPC which will
1972 wapi_interrupt_thread (thread->handle);
1973 #endif /* HOST_WIN32 */
1977 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
1979 LOCK_THREAD (thread);
1981 if ((thread->state & ThreadState_AbortRequested) != 0 ||
1982 (thread->state & ThreadState_StopRequested) != 0 ||
1983 (thread->state & ThreadState_Stopped) != 0)
1985 UNLOCK_THREAD (thread);
1989 if ((thread->state & ThreadState_Unstarted) != 0) {
1990 thread->state |= ThreadState_Aborted;
1991 UNLOCK_THREAD (thread);
1995 thread->state |= ThreadState_AbortRequested;
1996 if (thread->abort_state_handle)
1997 mono_gchandle_free (thread->abort_state_handle);
1999 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2000 g_assert (thread->abort_state_handle);
2002 thread->abort_state_handle = 0;
2004 thread->abort_exc = NULL;
2007 * abort_exc is set in mono_thread_execute_interruption(),
2008 * triggered by the call to signal_thread_state_change(),
2009 * below. There's a point between where we have
2010 * abort_state_handle set, but abort_exc NULL, but that's not
2014 UNLOCK_THREAD (thread);
2016 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2018 /* During shutdown, we can't wait for other threads */
2020 /* Make sure the thread is awake */
2021 mono_thread_resume (thread);
2023 abort_thread_internal (thread, TRUE, TRUE);
2027 ves_icall_System_Threading_Thread_ResetAbort (void)
2029 MonoInternalThread *thread = mono_thread_internal_current ();
2030 gboolean was_aborting;
2032 LOCK_THREAD (thread);
2033 was_aborting = thread->state & ThreadState_AbortRequested;
2034 thread->state &= ~ThreadState_AbortRequested;
2035 UNLOCK_THREAD (thread);
2037 if (!was_aborting) {
2038 const char *msg = "Unable to reset abort because no abort was requested";
2039 mono_raise_exception (mono_get_exception_thread_state (msg));
2041 thread->abort_exc = NULL;
2042 if (thread->abort_state_handle) {
2043 mono_gchandle_free (thread->abort_state_handle);
2044 /* This is actually not necessary - the handle
2045 only counts if the exception is set */
2046 thread->abort_state_handle = 0;
2051 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2053 LOCK_THREAD (thread);
2055 thread->state &= ~ThreadState_AbortRequested;
2057 if (thread->abort_exc) {
2058 thread->abort_exc = NULL;
2059 if (thread->abort_state_handle) {
2060 mono_gchandle_free (thread->abort_state_handle);
2061 /* This is actually not necessary - the handle
2062 only counts if the exception is set */
2063 thread->abort_state_handle = 0;
2067 UNLOCK_THREAD (thread);
2071 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2073 MonoInternalThread *thread = this->internal_thread;
2074 MonoObject *state, *deserialized = NULL, *exc;
2077 if (!thread->abort_state_handle)
2080 state = mono_gchandle_get_target (thread->abort_state_handle);
2083 domain = mono_domain_get ();
2084 if (mono_object_domain (state) == domain)
2087 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2089 if (!deserialized) {
2090 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2092 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2093 mono_raise_exception (invalid_op_exc);
2096 return deserialized;
2100 mono_thread_suspend (MonoInternalThread *thread)
2102 LOCK_THREAD (thread);
2104 if ((thread->state & ThreadState_Unstarted) != 0 ||
2105 (thread->state & ThreadState_Aborted) != 0 ||
2106 (thread->state & ThreadState_Stopped) != 0)
2108 UNLOCK_THREAD (thread);
2112 if ((thread->state & ThreadState_Suspended) != 0 ||
2113 (thread->state & ThreadState_SuspendRequested) != 0 ||
2114 (thread->state & ThreadState_StopRequested) != 0)
2116 UNLOCK_THREAD (thread);
2120 thread->state |= ThreadState_SuspendRequested;
2122 UNLOCK_THREAD (thread);
2124 suspend_thread_internal (thread, FALSE);
2129 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2131 if (!mono_thread_suspend (thread))
2132 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2136 mono_thread_resume (MonoInternalThread *thread)
2138 LOCK_THREAD (thread);
2140 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2141 thread->state &= ~ThreadState_SuspendRequested;
2142 UNLOCK_THREAD (thread);
2146 if ((thread->state & ThreadState_Suspended) == 0 ||
2147 (thread->state & ThreadState_Unstarted) != 0 ||
2148 (thread->state & ThreadState_Aborted) != 0 ||
2149 (thread->state & ThreadState_Stopped) != 0)
2151 UNLOCK_THREAD (thread);
2155 return resume_thread_internal (thread);
2159 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2161 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2162 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2166 mono_threads_is_critical_method (MonoMethod *method)
2168 switch (method->wrapper_type) {
2169 case MONO_WRAPPER_RUNTIME_INVOKE:
2170 case MONO_WRAPPER_XDOMAIN_INVOKE:
2171 case MONO_WRAPPER_XDOMAIN_DISPATCH:
2178 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2183 if (mono_threads_is_critical_method (m)) {
2184 *((gboolean*)data) = TRUE;
2191 is_running_protected_wrapper (void)
2193 gboolean found = FALSE;
2194 mono_stack_walk (find_wrapper, &found);
2198 void mono_thread_internal_stop (MonoInternalThread *thread)
2200 LOCK_THREAD (thread);
2202 if ((thread->state & ThreadState_StopRequested) != 0 ||
2203 (thread->state & ThreadState_Stopped) != 0)
2205 UNLOCK_THREAD (thread);
2209 /* Make sure the thread is awake */
2210 mono_thread_resume (thread);
2212 thread->state |= ThreadState_StopRequested;
2213 thread->state &= ~ThreadState_AbortRequested;
2215 UNLOCK_THREAD (thread);
2217 abort_thread_internal (thread, TRUE, TRUE);
2220 void mono_thread_stop (MonoThread *thread)
2222 mono_thread_internal_stop (thread->internal_thread);
2226 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2229 mono_atomic_load_acquire (tmp, gint8, (volatile gint8 *) ptr);
2234 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2237 mono_atomic_load_acquire (tmp, gint16, (volatile gint16 *) ptr);
2242 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2245 mono_atomic_load_acquire (tmp, gint32, (volatile gint32 *) ptr);
2250 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2253 mono_atomic_load_acquire (tmp, gint64, (volatile gint64 *) ptr);
2258 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2261 mono_atomic_load_acquire (tmp, volatile void *, (volatile void **) ptr);
2262 return (void *) tmp;
2266 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
2268 volatile MonoObject *tmp;
2269 mono_atomic_load_acquire (tmp, volatile MonoObject *, (volatile MonoObject **) ptr);
2270 return (MonoObject *) tmp;
2274 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
2277 mono_atomic_load_acquire (tmp, double, (volatile double *) ptr);
2282 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
2285 mono_atomic_load_acquire (tmp, float, (volatile float *) ptr);
2290 ves_icall_System_Threading_Volatile_Read1 (void *ptr)
2292 return InterlockedRead8 (ptr);
2296 ves_icall_System_Threading_Volatile_Read2 (void *ptr)
2298 return InterlockedRead16 (ptr);
2302 ves_icall_System_Threading_Volatile_Read4 (void *ptr)
2304 return InterlockedRead (ptr);
2308 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
2310 #if SIZEOF_VOID_P == 4
2311 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2313 mono_interlocked_lock ();
2314 val = *(gint64*)ptr;
2315 mono_interlocked_unlock ();
2319 return InterlockedRead64 (ptr);
2323 ves_icall_System_Threading_Volatile_ReadIntPtr (void *ptr)
2325 return InterlockedReadPointer (ptr);
2329 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
2333 #if SIZEOF_VOID_P == 4
2334 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2336 mono_interlocked_lock ();
2337 val = *(double*)ptr;
2338 mono_interlocked_unlock ();
2343 u.ival = InterlockedRead64 (ptr);
2349 ves_icall_System_Threading_Volatile_ReadFloat (void *ptr)
2353 u.ival = InterlockedRead (ptr);
2359 ves_icall_System_Threading_Volatile_Read_T (void *ptr)
2361 return InterlockedReadPointer (ptr);
2365 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2367 mono_atomic_store_release ((volatile gint8 *) ptr, value);
2371 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2373 mono_atomic_store_release ((volatile gint16 *) ptr, value);
2377 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2379 mono_atomic_store_release ((volatile gint32 *) ptr, value);
2383 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2385 mono_atomic_store_release ((volatile gint64 *) ptr, value);
2389 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2391 mono_atomic_store_release ((volatile void **) ptr, value);
2395 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
2397 mono_gc_wbarrier_generic_store_atomic (ptr, value);
2401 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
2403 mono_atomic_store_release ((volatile double *) ptr, value);
2407 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
2409 mono_atomic_store_release ((volatile float *) ptr, value);
2413 ves_icall_System_Threading_Volatile_Write1 (void *ptr, gint8 value)
2415 InterlockedWrite8 (ptr, value);
2419 ves_icall_System_Threading_Volatile_Write2 (void *ptr, gint16 value)
2421 InterlockedWrite16 (ptr, value);
2425 ves_icall_System_Threading_Volatile_Write4 (void *ptr, gint32 value)
2427 InterlockedWrite (ptr, value);
2431 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
2433 #if SIZEOF_VOID_P == 4
2434 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2435 mono_interlocked_lock ();
2436 *(gint64*)ptr = value;
2437 mono_interlocked_unlock ();
2442 InterlockedWrite64 (ptr, value);
2446 ves_icall_System_Threading_Volatile_WriteIntPtr (void *ptr, void *value)
2448 InterlockedWritePointer (ptr, value);
2452 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
2456 #if SIZEOF_VOID_P == 4
2457 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2458 mono_interlocked_lock ();
2459 *(double*)ptr = value;
2460 mono_interlocked_unlock ();
2467 InterlockedWrite64 (ptr, u.ival);
2471 ves_icall_System_Threading_Volatile_WriteFloat (void *ptr, float value)
2477 InterlockedWrite (ptr, u.ival);
2481 ves_icall_System_Threading_Volatile_Write_T (void *ptr, MonoObject *value)
2483 mono_gc_wbarrier_generic_store_atomic (ptr, value);
2487 mono_thread_init_tls (void)
2489 MONO_FAST_TLS_INIT (tls_current_object);
2490 mono_native_tls_alloc (¤t_object_key, NULL);
2493 void mono_thread_init (MonoThreadStartCB start_cb,
2494 MonoThreadAttachCB attach_cb)
2496 InitializeCriticalSection(&threads_mutex);
2497 InitializeCriticalSection(&interlocked_mutex);
2498 InitializeCriticalSection(&contexts_mutex);
2499 InitializeCriticalSection(&joinable_threads_mutex);
2501 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2502 g_assert(background_change_event != NULL);
2504 mono_init_static_data_info (&thread_static_info);
2505 mono_init_static_data_info (&context_static_info);
2507 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2509 mono_thread_start_cb = start_cb;
2510 mono_thread_attach_cb = attach_cb;
2512 /* Get a pseudo handle to the current process. This is just a
2513 * kludge so that wapi can build a process handle if needed.
2514 * As a pseudo handle is returned, we don't need to clean
2517 GetCurrentProcess ();
2520 void mono_thread_cleanup (void)
2522 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2523 /* The main thread must abandon any held mutexes (particularly
2524 * important for named mutexes as they are shared across
2525 * processes, see bug 74680.) This will happen when the
2526 * thread exits, but if it's not running in a subthread it
2527 * won't exit in time.
2529 /* Using non-w32 API is a nasty kludge, but I couldn't find
2530 * anything in the documentation that would let me do this
2531 * here yet still be safe to call on windows.
2533 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2537 /* This stuff needs more testing, it seems one of these
2538 * critical sections can be locked when mono_thread_cleanup is
2541 DeleteCriticalSection (&threads_mutex);
2542 DeleteCriticalSection (&interlocked_mutex);
2543 DeleteCriticalSection (&contexts_mutex);
2544 DeleteCriticalSection (&delayed_free_table_mutex);
2545 DeleteCriticalSection (&small_id_mutex);
2546 CloseHandle (background_change_event);
2549 mono_native_tls_free (current_object_key);
2553 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2555 mono_thread_cleanup_fn = func;
2559 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2561 thread->internal_thread->manage_callback = func;
2564 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2566 mono_thread_notify_pending_exc_fn = func;
2570 static void print_tids (gpointer key, gpointer value, gpointer user)
2572 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2573 * sizeof(uint) and a cast to uint would overflow
2575 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2576 * print this as a pointer.
2578 g_message ("Waiting for: %p", key);
2583 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2584 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2588 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2592 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2594 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2596 if(ret==WAIT_FAILED) {
2597 /* See the comment in build_wait_tids() */
2598 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2602 for(i=0; i<wait->num; i++)
2603 CloseHandle (wait->handles[i]);
2605 if (ret == WAIT_TIMEOUT)
2608 for(i=0; i<wait->num; i++) {
2609 gsize tid = wait->threads[i]->tid;
2612 * On !win32, when the thread handle becomes signalled, it just means the thread has exited user code,
2613 * it can still run io-layer etc. code. So wait for it to really exit.
2615 mono_thread_join ((gpointer)tid);
2617 mono_threads_lock ();
2618 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2619 /* This thread must have been killed, because
2620 * it hasn't cleaned itself up. (It's just
2621 * possible that the thread exited before the
2622 * parent thread had a chance to store the
2623 * handle, and now there is another pointer to
2624 * the already-exited thread stored. In this
2625 * case, we'll just get two
2626 * mono_profiler_thread_end() calls for the
2630 mono_threads_unlock ();
2631 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2632 thread_cleanup (wait->threads[i]);
2634 mono_threads_unlock ();
2639 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2641 guint32 i, ret, count;
2643 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2645 /* Add the thread state change event, so it wakes up if a thread changes
2646 * to background mode.
2649 if (count < MAXIMUM_WAIT_OBJECTS) {
2650 wait->handles [count] = background_change_event;
2654 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2656 if(ret==WAIT_FAILED) {
2657 /* See the comment in build_wait_tids() */
2658 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2662 for(i=0; i<wait->num; i++)
2663 CloseHandle (wait->handles[i]);
2665 if (ret == WAIT_TIMEOUT)
2668 if (ret < wait->num) {
2669 gsize tid = wait->threads[ret]->tid;
2670 mono_threads_lock ();
2671 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2672 /* See comment in wait_for_tids about thread cleanup */
2673 mono_threads_unlock ();
2674 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2675 thread_cleanup (wait->threads [ret]);
2677 mono_threads_unlock ();
2681 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2683 struct wait_data *wait=(struct wait_data *)user;
2685 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2687 MonoInternalThread *thread=(MonoInternalThread *)value;
2689 /* Ignore background threads, we abort them later */
2690 /* Do not lock here since it is not needed and the caller holds threads_lock */
2691 if (thread->state & ThreadState_Background) {
2692 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2693 return; /* just leave, ignore */
2696 if (mono_gc_is_finalizer_internal_thread (thread)) {
2697 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2701 if (thread == mono_thread_internal_current ()) {
2702 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2706 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2707 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2711 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2712 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2716 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2717 if (handle == NULL) {
2718 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2722 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2723 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2724 wait->handles[wait->num]=handle;
2725 wait->threads[wait->num]=thread;
2728 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2730 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2735 /* Just ignore the rest, we can't do anything with
2742 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2744 struct wait_data *wait=(struct wait_data *)user;
2745 gsize self = GetCurrentThreadId ();
2746 MonoInternalThread *thread = value;
2749 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2752 /* The finalizer thread is not a background thread */
2753 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2754 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2756 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2760 /* printf ("A: %d\n", wait->num); */
2761 wait->handles[wait->num]=thread->handle;
2762 wait->threads[wait->num]=thread;
2765 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2766 mono_thread_internal_stop (thread);
2770 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2774 * mono_threads_set_shutting_down:
2776 * Is called by a thread that wants to shut down Mono. If the runtime is already
2777 * shutting down, the calling thread is suspended/stopped, and this function never
2781 mono_threads_set_shutting_down (void)
2783 MonoInternalThread *current_thread = mono_thread_internal_current ();
2785 mono_threads_lock ();
2787 if (shutting_down) {
2788 mono_threads_unlock ();
2790 /* Make sure we're properly suspended/stopped */
2792 LOCK_THREAD (current_thread);
2794 if ((current_thread->state & ThreadState_SuspendRequested) ||
2795 (current_thread->state & ThreadState_AbortRequested) ||
2796 (current_thread->state & ThreadState_StopRequested)) {
2797 UNLOCK_THREAD (current_thread);
2798 mono_thread_execute_interruption (current_thread);
2800 current_thread->state |= ThreadState_Stopped;
2801 UNLOCK_THREAD (current_thread);
2804 /*since we're killing the thread, unset the current domain.*/
2805 mono_domain_unset ();
2807 /* Wake up other threads potentially waiting for us */
2808 mono_thread_info_exit ();
2810 shutting_down = TRUE;
2812 /* Not really a background state change, but this will
2813 * interrupt the main thread if it is waiting for all
2814 * the other threads.
2816 SetEvent (background_change_event);
2818 mono_threads_unlock ();
2822 void mono_thread_manage (void)
2824 struct wait_data wait_data;
2825 struct wait_data *wait = &wait_data;
2827 memset (wait, 0, sizeof (struct wait_data));
2828 /* join each thread that's still running */
2829 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2831 mono_threads_lock ();
2833 THREAD_DEBUG (g_message("%s: No threads", __func__));
2834 mono_threads_unlock ();
2837 mono_threads_unlock ();
2840 mono_threads_lock ();
2841 if (shutting_down) {
2842 /* somebody else is shutting down */
2843 mono_threads_unlock ();
2846 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2847 mono_g_hash_table_foreach (threads, print_tids, NULL));
2849 ResetEvent (background_change_event);
2851 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2852 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2853 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2854 mono_threads_unlock ();
2856 /* Something to wait for */
2857 wait_for_tids_or_state_change (wait, INFINITE);
2859 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2860 } while(wait->num>0);
2862 /* Mono is shutting down, so just wait for the end */
2863 if (!mono_runtime_try_shutdown ()) {
2864 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
2865 mono_thread_suspend (mono_thread_internal_current ());
2866 mono_thread_execute_interruption (mono_thread_internal_current ());
2870 * Remove everything but the finalizer thread and self.
2871 * Also abort all the background threads
2874 mono_threads_lock ();
2877 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2878 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2879 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2881 mono_threads_unlock ();
2883 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2885 /* Something to wait for */
2886 wait_for_tids (wait, INFINITE);
2888 } while (wait->num > 0);
2891 * give the subthreads a chance to really quit (this is mainly needed
2892 * to get correct user and system times from getrusage/wait/time(1)).
2893 * This could be removed if we avoid pthread_detach() and use pthread_join().
2896 mono_thread_info_yield ();
2900 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2902 MonoInternalThread *thread=(MonoInternalThread *)value;
2904 if(thread->tid != (gsize)user) {
2905 /*TerminateThread (thread->handle, -1);*/
2909 void mono_thread_abort_all_other_threads (void)
2911 gsize self = GetCurrentThreadId ();
2913 mono_threads_lock ();
2914 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2915 mono_g_hash_table_size (threads));
2916 mono_g_hash_table_foreach (threads, print_tids, NULL));
2918 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2920 mono_threads_unlock ();
2924 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2926 MonoInternalThread *thread = (MonoInternalThread*)value;
2927 struct wait_data *wait = (struct wait_data*)user_data;
2931 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2933 * This needs no locking.
2935 if ((thread->state & ThreadState_Suspended) != 0 ||
2936 (thread->state & ThreadState_Stopped) != 0)
2939 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2940 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2944 wait->handles [wait->num] = handle;
2945 wait->threads [wait->num] = thread;
2951 * mono_thread_suspend_all_other_threads:
2953 * Suspend all managed threads except the finalizer thread and this thread. It is
2954 * not possible to resume them later.
2956 void mono_thread_suspend_all_other_threads (void)
2958 struct wait_data wait_data;
2959 struct wait_data *wait = &wait_data;
2961 gsize self = GetCurrentThreadId ();
2963 guint32 eventidx = 0;
2964 gboolean starting, finished;
2966 memset (wait, 0, sizeof (struct wait_data));
2968 * The other threads could be in an arbitrary state at this point, i.e.
2969 * they could be starting up, shutting down etc. This means that there could be
2970 * threads which are not even in the threads hash table yet.
2974 * First we set a barrier which will be checked by all threads before they
2975 * are added to the threads hash table, and they will exit if the flag is set.
2976 * This ensures that no threads could be added to the hash later.
2977 * We will use shutting_down as the barrier for now.
2979 g_assert (shutting_down);
2982 * We make multiple calls to WaitForMultipleObjects since:
2983 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2984 * - some threads could exit without becoming suspended
2989 * Make a copy of the hashtable since we can't do anything with
2990 * threads while threads_mutex is held.
2993 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2994 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2995 mono_threads_lock ();
2996 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2997 mono_threads_unlock ();
2999 events = g_new0 (gpointer, wait->num);
3001 /* Get the suspended events that we'll be waiting for */
3002 for (i = 0; i < wait->num; ++i) {
3003 MonoInternalThread *thread = wait->threads [i];
3004 gboolean signal_suspend = FALSE;
3006 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3007 //CloseHandle (wait->handles [i]);
3008 wait->threads [i] = NULL; /* ignore this thread in next loop */
3012 LOCK_THREAD (thread);
3014 if (thread->suspended_event == NULL) {
3015 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3016 if (thread->suspended_event == NULL) {
3017 /* Forget this one and go on to the next */
3018 UNLOCK_THREAD (thread);
3023 if ((thread->state & ThreadState_Suspended) != 0 ||
3024 (thread->state & ThreadState_StopRequested) != 0 ||
3025 (thread->state & ThreadState_Stopped) != 0) {
3026 UNLOCK_THREAD (thread);
3027 CloseHandle (wait->handles [i]);
3028 wait->threads [i] = NULL; /* ignore this thread in next loop */
3032 if ((thread->state & ThreadState_SuspendRequested) == 0)
3033 signal_suspend = TRUE;
3035 events [eventidx++] = thread->suspended_event;
3037 /* Convert abort requests into suspend requests */
3038 if ((thread->state & ThreadState_AbortRequested) != 0)
3039 thread->state &= ~ThreadState_AbortRequested;
3041 thread->state |= ThreadState_SuspendRequested;
3043 UNLOCK_THREAD (thread);
3045 /* Signal the thread to suspend */
3046 if (mono_thread_info_new_interrupt_enabled ())
3047 suspend_thread_internal (thread, TRUE);
3048 else if (signal_suspend)
3049 signal_thread_state_change (thread);
3052 /*Only wait on the suspend event if we are using the old path */
3053 if (eventidx > 0 && !mono_thread_info_new_interrupt_enabled ()) {
3054 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3055 for (i = 0; i < wait->num; ++i) {
3056 MonoInternalThread *thread = wait->threads [i];
3061 LOCK_THREAD (thread);
3062 if ((thread->state & ThreadState_Suspended) != 0) {
3063 CloseHandle (thread->suspended_event);
3064 thread->suspended_event = NULL;
3066 UNLOCK_THREAD (thread);
3070 if (eventidx <= 0) {
3072 * If there are threads which are starting up, we wait until they
3073 * are suspended when they try to register in the threads hash.
3074 * This is guaranteed to finish, since the threads which can create new
3075 * threads get suspended after a while.
3076 * FIXME: The finalizer thread can still create new threads.
3078 mono_threads_lock ();
3079 if (threads_starting_up)
3080 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3083 mono_threads_unlock ();
3095 collect_threads (gpointer key, gpointer value, gpointer user_data)
3097 MonoInternalThread *thread = (MonoInternalThread*)value;
3098 struct wait_data *wait = (struct wait_data*)user_data;
3101 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3102 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3106 wait->handles [wait->num] = handle;
3107 wait->threads [wait->num] = thread;
3112 static gboolean thread_dump_requested;
3114 static G_GNUC_UNUSED gboolean
3115 print_stack_frame_to_string (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3117 GString *p = (GString*)data;
3118 MonoMethod *method = NULL;
3120 method = mono_jit_info_get_method (frame->ji);
3123 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
3124 g_string_append_printf (p, " %s\n", location);
3127 g_string_append_printf (p, " at <unknown> <0x%05x>\n", frame->native_offset);
3133 print_thread_dump (MonoInternalThread *thread, MonoThreadInfo *info)
3135 GString* text = g_string_new (0);
3137 GError *error = NULL;
3140 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &error);
3142 g_string_append_printf (text, "\n\"%s\"", name);
3145 else if (thread->threadpool_thread)
3146 g_string_append (text, "\n\"<threadpool thread>\"");
3148 g_string_append (text, "\n\"<unnamed thread>\"");
3151 /* This no longer works with remote unwinding */
3153 wapi_desc = wapi_current_thread_desc ();
3154 g_string_append_printf (text, " tid=0x%p this=0x%p %s\n", (gpointer)(gsize)thread->tid, thread, wapi_desc);
3159 mono_get_eh_callbacks ()->mono_walk_stack_with_state (print_stack_frame_to_string, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, text);
3160 mono_thread_info_resume (mono_thread_info_get_tid (info));
3162 fprintf (stdout, "%s", text->str);
3164 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
3165 OutputDebugStringA(text->str);
3168 g_string_free (text, TRUE);
3173 dump_thread (gpointer key, gpointer value, gpointer user)
3175 MonoInternalThread *thread = (MonoInternalThread *)value;
3176 MonoThreadInfo *info;
3178 if (thread == mono_thread_internal_current ())
3182 FIXME This still can hang if we stop a thread during malloc.
3183 FIXME This can hang if we suspend on a critical method and the GC kicks in. A fix might be to have function
3184 that takes a callback and runs it with the target suspended.
3185 We probably should loop a bit around trying to get it to either managed code
3188 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
3193 print_thread_dump (thread, info);
3197 mono_threads_perform_thread_dump (void)
3199 if (!thread_dump_requested)
3202 printf ("Full thread dump:\n");
3205 * Make a copy of the hashtable since we can't do anything with
3206 * threads while threads_mutex is held.
3208 mono_threads_lock ();
3209 mono_g_hash_table_foreach (threads, dump_thread, NULL);
3210 mono_threads_unlock ();
3212 thread_dump_requested = FALSE;
3216 * mono_threads_request_thread_dump:
3218 * Ask all threads except the current to print their stacktrace to stdout.
3221 mono_threads_request_thread_dump (void)
3223 struct wait_data wait_data;
3224 struct wait_data *wait = &wait_data;
3227 /*The new thread dump code runs out of the finalizer thread. */
3228 if (mono_thread_info_new_interrupt_enabled ()) {
3229 thread_dump_requested = TRUE;
3230 mono_gc_finalize_notify ();
3235 memset (wait, 0, sizeof (struct wait_data));
3238 * Make a copy of the hashtable since we can't do anything with
3239 * threads while threads_mutex is held.
3241 mono_threads_lock ();
3242 mono_g_hash_table_foreach (threads, collect_threads, wait);
3243 mono_threads_unlock ();
3245 for (i = 0; i < wait->num; ++i) {
3246 MonoInternalThread *thread = wait->threads [i];
3248 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3249 (thread != mono_thread_internal_current ()) &&
3250 !thread->thread_dump_requested) {
3251 thread->thread_dump_requested = TRUE;
3253 signal_thread_state_change (thread);
3256 CloseHandle (wait->handles [i]);
3262 gint allocated; /* +1 so that refs [allocated] == NULL */
3266 typedef struct ref_stack RefStack;
3269 ref_stack_new (gint initial_size)
3273 initial_size = MAX (initial_size, 16) + 1;
3274 rs = g_new0 (RefStack, 1);
3275 rs->refs = g_new0 (gpointer, initial_size);
3276 rs->allocated = initial_size;
3281 ref_stack_destroy (gpointer ptr)
3292 ref_stack_push (RefStack *rs, gpointer ptr)
3294 g_assert (rs != NULL);
3296 if (rs->bottom >= rs->allocated) {
3297 rs->refs = g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
3298 rs->allocated <<= 1;
3299 rs->refs [rs->allocated] = NULL;
3301 rs->refs [rs->bottom++] = ptr;
3305 ref_stack_pop (RefStack *rs)
3307 if (rs == NULL || rs->bottom == 0)
3311 rs->refs [rs->bottom] = NULL;
3315 ref_stack_find (RefStack *rs, gpointer ptr)
3322 for (refs = rs->refs; refs && *refs; refs++) {
3330 * mono_thread_push_appdomain_ref:
3332 * Register that the current thread may have references to objects in domain
3333 * @domain on its stack. Each call to this function should be paired with a
3334 * call to pop_appdomain_ref.
3337 mono_thread_push_appdomain_ref (MonoDomain *domain)
3339 MonoInternalThread *thread = mono_thread_internal_current ();
3342 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3343 SPIN_LOCK (thread->lock_thread_id);
3344 if (thread->appdomain_refs == NULL)
3345 thread->appdomain_refs = ref_stack_new (16);
3346 ref_stack_push (thread->appdomain_refs, domain);
3347 SPIN_UNLOCK (thread->lock_thread_id);
3352 mono_thread_pop_appdomain_ref (void)
3354 MonoInternalThread *thread = mono_thread_internal_current ();
3357 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3358 SPIN_LOCK (thread->lock_thread_id);
3359 ref_stack_pop (thread->appdomain_refs);
3360 SPIN_UNLOCK (thread->lock_thread_id);
3365 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3368 SPIN_LOCK (thread->lock_thread_id);
3369 res = ref_stack_find (thread->appdomain_refs, domain);
3370 SPIN_UNLOCK (thread->lock_thread_id);
3375 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3377 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3380 typedef struct abort_appdomain_data {
3381 struct wait_data wait;
3383 } abort_appdomain_data;
3386 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3388 MonoInternalThread *thread = (MonoInternalThread*)value;
3389 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3390 MonoDomain *domain = data->domain;
3392 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3393 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3395 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3396 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3399 data->wait.handles [data->wait.num] = handle;
3400 data->wait.threads [data->wait.num] = thread;
3403 /* Just ignore the rest, we can't do anything with
3411 * mono_threads_abort_appdomain_threads:
3413 * Abort threads which has references to the given appdomain.
3416 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3418 #ifdef __native_client__
3422 abort_appdomain_data user_data;
3424 int orig_timeout = timeout;
3427 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3429 start_time = mono_msec_ticks ();
3431 mono_threads_lock ();
3433 user_data.domain = domain;
3434 user_data.wait.num = 0;
3435 /* This shouldn't take any locks */
3436 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3437 mono_threads_unlock ();
3439 if (user_data.wait.num > 0) {
3440 /* Abort the threads outside the threads lock */
3441 for (i = 0; i < user_data.wait.num; ++i)
3442 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3445 * We should wait for the threads either to abort, or to leave the
3446 * domain. We can't do the latter, so we wait with a timeout.
3448 wait_for_tids (&user_data.wait, 100);
3451 /* Update remaining time */
3452 timeout -= mono_msec_ticks () - start_time;
3453 start_time = mono_msec_ticks ();
3455 if (orig_timeout != -1 && timeout < 0)
3458 while (user_data.wait.num > 0);
3460 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3466 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3468 MonoInternalThread *thread = (MonoInternalThread*)value;
3469 MonoDomain *domain = (MonoDomain*)user_data;
3472 /* No locking needed here */
3473 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3475 if (thread->cached_culture_info) {
3476 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3477 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3478 if (obj && obj->vtable->domain == domain)
3479 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3485 * mono_threads_clear_cached_culture:
3487 * Clear the cached_current_culture from all threads if it is in the
3491 mono_threads_clear_cached_culture (MonoDomain *domain)
3493 mono_threads_lock ();
3494 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3495 mono_threads_unlock ();
3499 * mono_thread_get_undeniable_exception:
3501 * Return an exception which needs to be raised when leaving a catch clause.
3502 * This is used for undeniable exception propagation.
3505 mono_thread_get_undeniable_exception (void)
3507 MonoInternalThread *thread = mono_thread_internal_current ();
3509 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3511 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3512 * exception if the thread no longer references a dying appdomain.
3514 thread->abort_exc->trace_ips = NULL;
3515 thread->abort_exc->stack_trace = NULL;
3516 return thread->abort_exc;
3522 #if MONO_SMALL_CONFIG
3523 #define NUM_STATIC_DATA_IDX 4
3524 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3528 #define NUM_STATIC_DATA_IDX 8
3529 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3530 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3534 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3537 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3540 gpointer *static_data = addr;
3541 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3544 if (!static_data [i])
3546 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3547 ptr = static_data [i];
3548 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3549 uintptr_t bmap = static_reference_bitmaps [i][j];
3552 if ((bmap & 1) && *p) {
3563 * mono_alloc_static_data
3565 * Allocate memory blocks for storing threads or context static data
3568 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3570 guint idx = (offset >> 24) - 1;
3573 gpointer* static_data = *static_data_ptr;
3575 static void* tls_desc = NULL;
3576 if (mono_gc_user_markers_supported () && !tls_desc)
3577 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3578 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3579 *static_data_ptr = static_data;
3580 static_data [0] = static_data;
3583 for (i = 1; i <= idx; ++i) {
3584 if (static_data [i])
3586 if (mono_gc_user_markers_supported () && threadlocal)
3587 static_data [i] = g_malloc0 (static_data_size [i]);
3589 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3594 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3597 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3598 gpointer p = static_data [i];
3602 * At this point, the static data pointer array is still registered with the
3603 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
3604 * data. Freeing the individual arrays without first nulling their slots
3605 * would make it possible for mark_tls_slots() to encounter a pointer to
3606 * such an already freed array. See bug #13813.
3608 static_data [i] = NULL;
3609 mono_memory_write_barrier ();
3610 if (mono_gc_user_markers_supported () && threadlocal)
3613 mono_gc_free_fixed (p);
3615 mono_gc_free_fixed (static_data);
3619 * mono_init_static_data_info
3621 * Initializes static data counters
3623 static void mono_init_static_data_info (StaticDataInfo *static_data)
3625 static_data->idx = 0;
3626 static_data->offset = 0;
3627 static_data->freelist = NULL;
3631 * mono_alloc_static_data_slot
3633 * Generates an offset for static data. static_data contains the counters
3634 * used to generate it.
3637 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3641 if (!static_data->idx && !static_data->offset) {
3643 * we use the first chunk of the first allocation also as
3644 * an array for the rest of the data
3646 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3648 static_data->offset += align - 1;
3649 static_data->offset &= ~(align - 1);
3650 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3651 static_data->idx ++;
3652 g_assert (size <= static_data_size [static_data->idx]);
3653 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3654 static_data->offset = 0;
3656 offset = static_data->offset | ((static_data->idx + 1) << 24);
3657 static_data->offset += size;
3662 * ensure thread static fields already allocated are valid for thread
3663 * This function is called when a thread is created or on thread attach.
3666 thread_adjust_static_data (MonoInternalThread *thread)
3670 mono_threads_lock ();
3671 if (thread_static_info.offset || thread_static_info.idx > 0) {
3672 /* get the current allocated size */
3673 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3674 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3676 mono_threads_unlock ();
3680 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3682 MonoInternalThread *thread = value;
3683 guint32 offset = GPOINTER_TO_UINT (user);
3685 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3688 static MonoThreadDomainTls*
3689 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3691 MonoThreadDomainTls* prev = NULL;
3692 MonoThreadDomainTls* tmp = static_data->freelist;
3694 if (tmp->size == size) {
3696 prev->next = tmp->next;
3698 static_data->freelist = tmp->next;
3708 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int numbits)
3711 int idx = (offset >> 24) - 1;
3713 if (!static_reference_bitmaps [idx])
3714 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3715 rb = static_reference_bitmaps [idx];
3717 offset /= sizeof (gpointer);
3718 /* offset is now the bitmap offset */
3719 for (i = 0; i < numbits; ++i) {
3720 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3721 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3726 clear_reference_bitmap (guint32 offset, guint32 size)
3728 int idx = (offset >> 24) - 1;
3730 rb = static_reference_bitmaps [idx];
3732 offset /= sizeof (gpointer);
3733 size /= sizeof (gpointer);
3735 /* offset is now the bitmap offset */
3736 for (; offset < size; ++offset)
3737 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3741 * The offset for a special static variable is composed of three parts:
3742 * a bit that indicates the type of static data (0:thread, 1:context),
3743 * an index in the array of chunks of memory for the thread (thread->static_data)
3744 * and an offset in that chunk of mem. This allows allocating less memory in the
3749 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
3752 if (static_type == SPECIAL_STATIC_THREAD) {
3753 MonoThreadDomainTls *item;
3754 mono_threads_lock ();
3755 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3756 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3758 offset = item->offset;
3761 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3763 update_tls_reference_bitmap (offset, bitmap, numbits);
3764 /* This can be called during startup */
3765 if (threads != NULL)
3766 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3767 mono_threads_unlock ();
3769 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3770 mono_contexts_lock ();
3771 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3772 mono_contexts_unlock ();
3773 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3779 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
3781 /* The high bit means either thread (0) or static (1) data. */
3783 guint32 static_type = (offset & 0x80000000);
3786 offset &= 0x7fffffff;
3787 idx = (offset >> 24) - 1;
3789 if (static_type == 0) {
3790 return get_thread_static_data (thread, offset);
3792 /* Allocate static data block under demand, since we don't have a list
3795 MonoAppContext *context = mono_context_get ();
3796 if (!context->static_data || !context->static_data [idx]) {
3797 mono_contexts_lock ();
3798 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3799 mono_contexts_unlock ();
3801 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3806 mono_get_special_static_data (guint32 offset)
3808 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
3817 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3819 MonoInternalThread *thread = value;
3820 TlsOffsetSize *data = user;
3821 int idx = (data->offset >> 24) - 1;
3824 if (!thread->static_data || !thread->static_data [idx])
3826 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3827 mono_gc_bzero_atomic (ptr, data->size);
3831 do_free_special_slot (guint32 offset, guint32 size)
3833 guint32 static_type = (offset & 0x80000000);
3834 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3835 if (static_type == 0) {
3837 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3838 data.offset = offset & 0x7fffffff;
3840 clear_reference_bitmap (data.offset, data.size);
3841 if (threads != NULL)
3842 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3843 item->offset = offset;
3846 if (!mono_runtime_is_shutting_down ()) {
3847 item->next = thread_static_info.freelist;
3848 thread_static_info.freelist = item;
3850 /* We could be called during shutdown after mono_thread_cleanup () is called */
3854 /* FIXME: free context static data as well */
3859 do_free_special (gpointer key, gpointer value, gpointer data)
3861 MonoClassField *field = key;
3862 guint32 offset = GPOINTER_TO_UINT (value);
3865 size = mono_type_size (field->type, &align);
3866 do_free_special_slot (offset, size);
3870 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3872 mono_threads_lock ();
3873 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3874 mono_threads_unlock ();
3878 mono_special_static_data_free_slot (guint32 offset, guint32 size)
3880 mono_threads_lock ();
3881 do_free_special_slot (offset, size);
3882 mono_threads_unlock ();
3886 * allocates room in the thread local area for storing an instance of the struct type
3887 * the allocation is kept track of in domain->tlsrec_list.
3890 mono_thread_alloc_tls (MonoReflectionType *type)
3892 MonoDomain *domain = mono_domain_get ();
3894 MonoTlsDataRecord *tlsrec;
3897 gsize default_bitmap [4] = {0};
3898 uint32_t tls_offset;
3902 klass = mono_class_from_mono_type (type->type);
3903 /* TlsDatum is a struct, so we subtract the object header size offset */
3904 bitmap = mono_class_compute_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, - (int)(sizeof (MonoObject) / sizeof (gpointer)), &max_set, FALSE);
3905 size = mono_type_size (type->type, &align);
3906 tls_offset = mono_alloc_special_static_data (SPECIAL_STATIC_THREAD, size, align, (uintptr_t*)bitmap, max_set + 1);
3907 if (bitmap != default_bitmap)
3909 tlsrec = g_new0 (MonoTlsDataRecord, 1);
3910 tlsrec->tls_offset = tls_offset;
3911 tlsrec->size = size;
3912 mono_domain_lock (domain);
3913 tlsrec->next = domain->tlsrec_list;
3914 domain->tlsrec_list = tlsrec;
3915 mono_domain_unlock (domain);
3920 mono_thread_destroy_tls (uint32_t tls_offset)
3922 MonoTlsDataRecord *prev = NULL;
3923 MonoTlsDataRecord *cur;
3925 MonoDomain *domain = mono_domain_get ();
3926 mono_domain_lock (domain);
3927 cur = domain->tlsrec_list;
3929 if (cur->tls_offset == tls_offset) {
3931 prev->next = cur->next;
3933 domain->tlsrec_list = cur->next;
3941 mono_domain_unlock (domain);
3943 mono_special_static_data_free_slot (tls_offset, size);
3947 * This is just to ensure cleanup: the finalizers should have taken care, so this is not perf-critical.
3950 mono_thread_destroy_domain_tls (MonoDomain *domain)
3952 while (domain->tlsrec_list)
3953 mono_thread_destroy_tls (domain->tlsrec_list->tls_offset);
3956 static MonoClassField *local_slots = NULL;
3959 /* local tls data to get locals_slot from a thread */
3962 /* index in the locals_slot array */
3967 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3969 LocalSlotID *sid = user_data;
3970 MonoInternalThread *thread = (MonoInternalThread*)value;
3971 MonoArray *slots_array;
3973 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3974 * it is for the right domain, so we need to check if it is allocated an initialized
3975 * for the current thread.
3977 /*g_print ("handling thread %p\n", thread);*/
3978 if (!thread->static_data || !thread->static_data [sid->idx])
3980 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3981 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3983 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3987 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3995 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3997 g_warning ("local_slots field not found in Thread class");
4001 domain = mono_domain_get ();
4002 mono_domain_lock (domain);
4003 if (domain->special_static_fields)
4004 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
4005 mono_domain_unlock (domain);
4008 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
4009 sid.offset = GPOINTER_TO_UINT (addr);
4010 sid.offset &= 0x7fffffff;
4011 sid.idx = (sid.offset >> 24) - 1;
4012 mono_threads_lock ();
4013 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
4014 mono_threads_unlock ();
4016 /* FIXME: clear the slot for MonoAppContexts, too */
4021 static void CALLBACK dummy_apc (ULONG_PTR param)
4027 * mono_thread_execute_interruption
4029 * Performs the operation that the requested thread state requires (abort,
4032 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
4034 LOCK_THREAD (thread);
4036 /* MonoThread::interruption_requested can only be changed with atomics */
4037 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
4038 /* this will consume pending APC calls */
4040 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
4042 InterlockedDecrement (&thread_interruption_requested);
4044 /* Clear the interrupted flag of the thread so it can wait again */
4045 wapi_clear_interruption ();
4049 if ((thread->state & ThreadState_AbortRequested) != 0) {
4050 UNLOCK_THREAD (thread);
4051 if (thread->abort_exc == NULL) {
4053 * This might be racy, but it has to be called outside the lock
4054 * since it calls managed code.
4056 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
4058 return thread->abort_exc;
4060 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
4061 self_suspend_internal (thread);
4064 else if ((thread->state & ThreadState_StopRequested) != 0) {
4065 /* FIXME: do this through the JIT? */
4067 UNLOCK_THREAD (thread);
4069 mono_thread_exit ();
4071 } else if (thread->pending_exception) {
4074 exc = thread->pending_exception;
4075 thread->pending_exception = NULL;
4077 UNLOCK_THREAD (thread);
4079 } else if (thread->thread_interrupt_requested) {
4081 thread->thread_interrupt_requested = FALSE;
4082 UNLOCK_THREAD (thread);
4084 return(mono_get_exception_thread_interrupted ());
4087 UNLOCK_THREAD (thread);
4093 * mono_thread_request_interruption
4095 * A signal handler can call this method to request the interruption of a
4096 * thread. The result of the interruption will depend on the current state of
4097 * the thread. If the result is an exception that needs to be throw, it is
4098 * provided as return value.
4101 mono_thread_request_interruption (gboolean running_managed)
4103 MonoInternalThread *thread = mono_thread_internal_current ();
4105 /* The thread may already be stopping */
4110 if (thread->interrupt_on_stop &&
4111 thread->state & ThreadState_StopRequested &&
4112 thread->state & ThreadState_Background)
4116 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4118 InterlockedIncrement (&thread_interruption_requested);
4120 if (!running_managed || is_running_protected_wrapper ()) {
4121 /* Can't stop while in unmanaged code. Increase the global interruption
4122 request count. When exiting the unmanaged method the count will be
4123 checked and the thread will be interrupted. */
4125 if (mono_thread_notify_pending_exc_fn && !running_managed)
4126 /* The JIT will notify the thread about the interruption */
4127 /* This shouldn't take any locks */
4128 mono_thread_notify_pending_exc_fn ();
4130 /* this will awake the thread if it is in WaitForSingleObject
4132 /* Our implementation of this function ignores the func argument */
4134 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4136 wapi_thread_interrupt_self ();
4141 return mono_thread_execute_interruption (thread);
4145 /*This function should be called by a thread after it has exited all of
4146 * its handle blocks at interruption time.*/
4148 mono_thread_resume_interruption (void)
4150 MonoInternalThread *thread = mono_thread_internal_current ();
4151 gboolean still_aborting;
4153 /* The thread may already be stopping */
4157 LOCK_THREAD (thread);
4158 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4159 UNLOCK_THREAD (thread);
4161 /*This can happen if the protected block called Thread::ResetAbort*/
4162 if (!still_aborting)
4165 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4167 InterlockedIncrement (&thread_interruption_requested);
4170 wapi_self_interrupt ();
4172 return mono_thread_execute_interruption (thread);
4175 gboolean mono_thread_interruption_requested ()
4177 if (thread_interruption_requested) {
4178 MonoInternalThread *thread = mono_thread_internal_current ();
4179 /* The thread may already be stopping */
4181 return (thread->interruption_requested);
4186 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4188 MonoInternalThread *thread = mono_thread_internal_current ();
4190 /* The thread may already be stopping */
4194 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4195 MonoException* exc = mono_thread_execute_interruption (thread);
4196 if (exc) mono_raise_exception (exc);
4201 * Performs the interruption of the current thread, if one has been requested,
4202 * and the thread is not running a protected wrapper.
4204 void mono_thread_interruption_checkpoint ()
4206 mono_thread_interruption_checkpoint_request (FALSE);
4210 * Performs the interruption of the current thread, if one has been requested.
4212 void mono_thread_force_interruption_checkpoint ()
4214 mono_thread_interruption_checkpoint_request (TRUE);
4218 * mono_thread_get_and_clear_pending_exception:
4220 * Return any pending exceptions for the current thread and clear it as a side effect.
4223 mono_thread_get_and_clear_pending_exception (void)
4225 MonoInternalThread *thread = mono_thread_internal_current ();
4227 /* The thread may already be stopping */
4231 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4232 return mono_thread_execute_interruption (thread);
4235 if (thread->pending_exception) {
4236 MonoException *exc = thread->pending_exception;
4238 thread->pending_exception = NULL;
4246 * mono_set_pending_exception:
4248 * Set the pending exception of the current thread to EXC.
4249 * The exception will be thrown when execution returns to managed code.
4252 mono_set_pending_exception (MonoException *exc)
4254 MonoInternalThread *thread = mono_thread_internal_current ();
4256 /* The thread may already be stopping */
4260 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4262 mono_thread_request_interruption (FALSE);
4266 * mono_thread_interruption_request_flag:
4268 * Returns the address of a flag that will be non-zero if an interruption has
4269 * been requested for a thread. The thread to interrupt may not be the current
4270 * thread, so an additional call to mono_thread_interruption_requested() or
4271 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4274 gint32* mono_thread_interruption_request_flag ()
4276 return &thread_interruption_requested;
4280 mono_thread_init_apartment_state (void)
4283 MonoInternalThread* thread = mono_thread_internal_current ();
4285 /* Positive return value indicates success, either
4286 * S_OK if this is first CoInitialize call, or
4287 * S_FALSE if CoInitialize already called, but with same
4288 * threading model. A negative value indicates failure,
4289 * probably due to trying to change the threading model.
4291 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4292 ? COINIT_APARTMENTTHREADED
4293 : COINIT_MULTITHREADED) < 0) {
4294 thread->apartment_state = ThreadApartmentState_Unknown;
4300 mono_thread_cleanup_apartment_state (void)
4303 MonoInternalThread* thread = mono_thread_internal_current ();
4305 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4312 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4314 LOCK_THREAD (thread);
4315 thread->state |= state;
4316 UNLOCK_THREAD (thread);
4320 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4322 LOCK_THREAD (thread);
4323 thread->state &= ~state;
4324 UNLOCK_THREAD (thread);
4328 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4330 gboolean ret = FALSE;
4332 LOCK_THREAD (thread);
4334 if ((thread->state & test) != 0) {
4338 UNLOCK_THREAD (thread);
4343 //static MonoClassField *execution_context_field;
4346 get_execution_context_addr (void)
4348 MonoDomain *domain = mono_domain_get ();
4349 guint32 offset = domain->execution_context_field_offset;
4352 MonoClassField *field = mono_class_get_field_from_name (mono_defaults.thread_class, "_ec");
4355 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4357 mono_domain_lock (domain);
4358 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, field));
4359 mono_domain_unlock (domain);
4362 domain->execution_context_field_offset = offset;
4365 return (MonoObject**) mono_get_special_static_data (offset);
4369 mono_thread_get_execution_context (void)
4371 return *get_execution_context_addr ();
4375 mono_thread_set_execution_context (MonoObject *ec)
4377 *get_execution_context_addr () = ec;
4380 static gboolean has_tls_get = FALSE;
4383 mono_runtime_set_has_tls_get (gboolean val)
4389 mono_runtime_has_tls_get (void)
4395 mono_thread_kill (MonoInternalThread *thread, int signal)
4397 #ifdef __native_client__
4398 /* Workaround pthread_kill abort() in NaCl glibc. */
4402 /* Win32 uses QueueUserAPC and callers of this are guarded */
4403 g_assert_not_reached ();
4405 # ifdef PTHREAD_POINTER_ID
4406 return pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
4408 # ifdef PLATFORM_ANDROID
4409 if (thread->android_tid != 0) {
4411 int old_errno = errno;
4413 ret = tkill ((pid_t) thread->android_tid, signal);
4422 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());
4424 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());
4431 self_interrupt_thread (void *_unused)
4433 MonoThreadInfo *info = mono_thread_info_current ();
4434 MonoException *exc = mono_thread_execute_interruption (mono_thread_internal_current ());
4435 if (exc) /*We must use _with_context since we didn't trampoline into the runtime*/
4436 mono_raise_exception_with_context (exc, &info->suspend_state.ctx);
4437 g_assert_not_reached (); /*this MUST not happen since we can't resume from an async call*/
4441 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
4445 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
4449 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
4451 MonoJitInfo **dest = data;
4457 mono_thread_info_get_last_managed (MonoThreadInfo *info)
4459 MonoJitInfo *ji = NULL;
4462 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &ji);
4467 abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort)
4470 MonoThreadInfo *info = NULL;
4471 gboolean protected_wrapper;
4472 gboolean running_managed;
4474 if (!mono_thread_info_new_interrupt_enabled ()) {
4475 signal_thread_state_change (thread);
4480 FIXME this is insanely broken, it doesn't cause interruption to happen
4481 synchronously since passing FALSE to mono_thread_request_interruption makes sure it returns NULL
4483 if (thread == mono_thread_internal_current ()) {
4484 /* Do it synchronously */
4485 MonoException *exc = mono_thread_request_interruption (can_raise_exception);
4487 mono_raise_exception (exc);
4489 wapi_interrupt_thread (thread->handle);
4494 /*FIXME we need to check 2 conditions here, request to interrupt this thread or if the target died*/
4495 if (!(info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, TRUE))) {
4499 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (&info->suspend_state)) {
4500 mono_thread_info_resume (mono_thread_info_get_tid (info));
4504 /*someone is already interrupting it*/
4505 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1) {
4506 mono_thread_info_resume (mono_thread_info_get_tid (info));
4509 InterlockedIncrement (&thread_interruption_requested);
4511 ji = mono_thread_info_get_last_managed (info);
4512 protected_wrapper = ji && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
4513 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
4515 if (!protected_wrapper && running_managed) {
4516 /*We are in managed code*/
4517 /*Set the thread to call */
4518 if (install_async_abort)
4519 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
4520 mono_thread_info_resume (mono_thread_info_get_tid (info));
4522 gpointer interrupt_handle;
4524 * This will cause waits to be broken.
4525 * It will also prevent the thread from entering a wait, so if the thread returns
4526 * from the wait before it receives the abort signal, it will just spin in the wait
4527 * functions in the io-layer until the signal handler calls QueueUserAPC which will
4531 interrupt_handle = wapi_prepare_interrupt_thread (thread->handle);
4533 mono_thread_info_resume (mono_thread_info_get_tid (info));
4535 wapi_finish_interrupt_thread (interrupt_handle);
4538 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
4542 transition_to_suspended (MonoInternalThread *thread)
4544 if ((thread->state & ThreadState_SuspendRequested) == 0) {
4545 g_assert (0); /*FIXME we should not reach this */
4546 /*Make sure we balance the suspend count.*/
4547 mono_thread_info_resume ((MonoNativeThreadId)(gpointer)(gsize)thread->tid);
4549 thread->state &= ~ThreadState_SuspendRequested;
4550 thread->state |= ThreadState_Suspended;
4551 mono_thread_info_finish_suspend ();
4553 UNLOCK_THREAD (thread);
4557 suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
4559 if (!mono_thread_info_new_interrupt_enabled ()) {
4560 signal_thread_state_change (thread);
4564 LOCK_THREAD (thread);
4565 if (thread == mono_thread_internal_current ()) {
4566 transition_to_suspended (thread);
4567 mono_thread_info_self_suspend ();
4569 MonoThreadInfo *info;
4571 gboolean protected_wrapper;
4572 gboolean running_managed;
4574 /*A null info usually means the thread is already dead. */
4575 if (!(info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, interrupt))) {
4576 UNLOCK_THREAD (thread);
4580 ji = mono_thread_info_get_last_managed (info);
4581 protected_wrapper = ji && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
4582 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
4584 if (running_managed && !protected_wrapper) {
4585 transition_to_suspended (thread);
4587 gpointer interrupt_handle;
4589 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 0)
4590 InterlockedIncrement (&thread_interruption_requested);
4593 interrupt_handle = wapi_prepare_interrupt_thread (thread->handle);
4595 mono_thread_info_resume (mono_thread_info_get_tid (info));
4598 wapi_finish_interrupt_thread (interrupt_handle);
4600 UNLOCK_THREAD (thread);
4605 /*This is called with @thread synch_cs held and it must release it*/
4607 self_suspend_internal (MonoInternalThread *thread)
4609 if (!mono_thread_info_new_interrupt_enabled ()) {
4610 thread->state &= ~ThreadState_SuspendRequested;
4611 thread->state |= ThreadState_Suspended;
4612 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
4613 if (thread->suspend_event == NULL) {
4614 UNLOCK_THREAD (thread);
4617 if (thread->suspended_event)
4618 SetEvent (thread->suspended_event);
4620 UNLOCK_THREAD (thread);
4622 if (shutting_down) {
4623 /* After we left the lock, the runtime might shut down so everything becomes invalid */
4628 WaitForSingleObject (thread->suspend_event, INFINITE);
4630 LOCK_THREAD (thread);
4632 CloseHandle (thread->suspend_event);
4633 thread->suspend_event = NULL;
4634 thread->state &= ~ThreadState_Suspended;
4636 /* The thread that requested the resume will have replaced this event
4637 * and will be waiting for it
4639 SetEvent (thread->resume_event);
4641 UNLOCK_THREAD (thread);
4645 transition_to_suspended (thread);
4646 mono_thread_info_self_suspend ();
4649 /*This is called with @thread synch_cs held and it must release it*/
4651 resume_thread_internal (MonoInternalThread *thread)
4653 if (!mono_thread_info_new_interrupt_enabled ()) {
4654 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
4655 if (thread->resume_event == NULL) {
4656 UNLOCK_THREAD (thread);
4660 /* Awake the thread */
4661 SetEvent (thread->suspend_event);
4663 UNLOCK_THREAD (thread);
4665 /* Wait for the thread to awake */
4666 WaitForSingleObject (thread->resume_event, INFINITE);
4667 CloseHandle (thread->resume_event);
4668 thread->resume_event = NULL;
4672 UNLOCK_THREAD (thread);
4673 /* Awake the thread */
4674 if (!mono_thread_info_resume ((MonoNativeThreadId)(gpointer)(gsize)thread->tid))
4676 LOCK_THREAD (thread);
4677 thread->state &= ~ThreadState_Suspended;
4678 UNLOCK_THREAD (thread);
4684 * mono_thread_is_foreign:
4685 * @thread: the thread to query
4687 * This function allows one to determine if a thread was created by the mono runtime and has
4688 * a well defined lifecycle or it's a foreigh one, created by the native environment.
4690 * Returns: true if @thread was not created by the runtime.
4693 mono_thread_is_foreign (MonoThread *thread)
4695 MonoThreadInfo *info = thread->internal_thread->thread_info;
4696 return info->runtime_thread == FALSE;
4700 * mono_add_joinable_thread:
4702 * Add TID to the list of joinable threads.
4703 * LOCKING: Acquires the threads lock.
4706 mono_threads_add_joinable_thread (gpointer tid)
4710 * We cannot detach from threads because it causes problems like
4711 * 2fd16f60/r114307. So we collect them and join them when
4712 * we have time (in he finalizer thread).
4714 joinable_threads_lock ();
4715 if (!joinable_threads)
4716 joinable_threads = g_hash_table_new (NULL, NULL);
4717 g_hash_table_insert (joinable_threads, tid, tid);
4718 joinable_thread_count ++;
4719 joinable_threads_unlock ();
4721 mono_gc_finalize_notify ();
4726 * mono_threads_join_threads:
4728 * Join all joinable threads. This is called from the finalizer thread.
4729 * LOCKING: Acquires the threads lock.
4732 mono_threads_join_threads (void)
4735 GHashTableIter iter;
4742 if (!joinable_thread_count)
4746 joinable_threads_lock ();
4748 if (g_hash_table_size (joinable_threads)) {
4749 g_hash_table_iter_init (&iter, joinable_threads);
4750 g_hash_table_iter_next (&iter, &key, (void**)&tid);
4751 thread = (pthread_t)tid;
4752 g_hash_table_remove (joinable_threads, key);
4753 joinable_thread_count --;
4756 joinable_threads_unlock ();
4758 if (thread != pthread_self ())
4759 /* This shouldn't block */
4760 pthread_join (thread, NULL);
4771 * Wait for thread TID to exit.
4772 * LOCKING: Acquires the threads lock.
4775 mono_thread_join (gpointer tid)
4780 joinable_threads_lock ();
4781 if (!joinable_threads)
4782 joinable_threads = g_hash_table_new (NULL, NULL);
4783 if (g_hash_table_lookup (joinable_threads, tid)) {
4784 g_hash_table_remove (joinable_threads, tid);
4785 joinable_thread_count --;
4787 joinable_threads_unlock ();
4788 thread = (pthread_t)tid;
4789 pthread_join (thread, NULL);