[runtime] Convert more icalls to use handles. (#15862)
[mono-project.git] / mono / metadata / threads.c
blob398b7e5daa3ed825f136d2e19e1b21998cb2a04d
1 /**
2 * \file
3 * Thread support internal calls
5 * Author:
6 * Dick Porter (dick@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
8 * Patrik Torstensson (patrik.torstensson@labs2.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <config.h>
18 #include <glib.h>
19 #include <string.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/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/mono-hash-internals.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/runtime.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/debug-internals.h>
35 #include <mono/utils/monobitset.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
40 #include <mono/utils/mono-threads.h>
41 #include <mono/utils/mono-threads-coop.h>
42 #include <mono/utils/mono-tls.h>
43 #include <mono/utils/atomic.h>
44 #include <mono/utils/mono-memory-model.h>
45 #include <mono/utils/mono-error-internals.h>
46 #include <mono/utils/os-event.h>
47 #include <mono/utils/mono-threads-debug.h>
48 #include <mono/utils/unlocked.h>
49 #include <mono/metadata/w32handle.h>
50 #include <mono/metadata/w32event.h>
51 #include <mono/metadata/w32mutex.h>
53 #include <mono/metadata/reflection-internals.h>
54 #include <mono/metadata/abi-details.h>
55 #include <mono/metadata/w32error.h>
56 #include <mono/utils/w32api.h>
57 #include <mono/utils/mono-os-wait.h>
58 #include <mono/metadata/exception-internals.h>
59 #include <mono/utils/mono-state.h>
60 #include <mono/metadata/w32subset.h>
62 #ifdef HAVE_SYS_WAIT_H
63 #include <sys/wait.h>
64 #endif
66 #ifdef HAVE_SIGNAL_H
67 #include <signal.h>
68 #endif
70 #if defined(HOST_WIN32)
71 #include <objbase.h>
72 #include <sys/timeb.h>
73 extern gboolean
74 mono_native_thread_join_handle (HANDLE thread_handle, gboolean close_handle);
75 #endif
77 #if defined(HOST_FUCHSIA)
78 #include <zircon/syscalls.h>
79 #endif
81 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
82 #define USE_TKILL_ON_ANDROID 1
83 #endif
85 #ifdef HOST_ANDROID
86 #include <errno.h>
88 #ifdef USE_TKILL_ON_ANDROID
89 extern int tkill (pid_t tid, int signal);
90 #endif
91 #endif
93 #include "icall-decl.h"
95 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
96 #define THREAD_DEBUG(a)
97 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
98 #define THREAD_WAIT_DEBUG(a)
99 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
100 #define LIBGC_DEBUG(a)
102 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
103 #define SPIN_LOCK(i) do { \
104 if (SPIN_TRYLOCK (i)) \
105 break; \
106 } while (1)
108 #define SPIN_UNLOCK(i) i = 0
110 #define LOCK_THREAD(thread) lock_thread((thread))
111 #define UNLOCK_THREAD(thread) unlock_thread((thread))
113 typedef union {
114 gint32 ival;
115 gfloat fval;
116 } IntFloatUnion;
118 typedef union {
119 gint64 ival;
120 gdouble fval;
121 } LongDoubleUnion;
123 typedef struct _StaticDataFreeList StaticDataFreeList;
124 struct _StaticDataFreeList {
125 StaticDataFreeList *next;
126 guint32 offset;
127 guint32 size;
130 typedef struct {
131 int idx;
132 int offset;
133 StaticDataFreeList *freelist;
134 } StaticDataInfo;
136 /* Controls access to the 'threads' hash table */
137 static void mono_threads_lock (void);
138 static void mono_threads_unlock (void);
139 static MonoCoopMutex threads_mutex;
141 /* Controls access to the 'joinable_threads' hash table */
142 #define joinable_threads_lock() mono_coop_mutex_lock (&joinable_threads_mutex)
143 #define joinable_threads_unlock() mono_coop_mutex_unlock (&joinable_threads_mutex)
144 static MonoCoopMutex joinable_threads_mutex;
146 /* Holds current status of static data heap */
147 static StaticDataInfo thread_static_info;
148 static StaticDataInfo context_static_info;
150 /* The hash of existing threads (key is thread ID, value is
151 * MonoInternalThread*) that need joining before exit
153 static MonoGHashTable *threads=NULL;
155 /* List of app context GC handles.
156 * Added to from mono_threads_register_app_context ().
158 static GHashTable *contexts = NULL;
160 /* Cleanup queue for contexts. */
161 static MonoReferenceQueue *context_queue;
164 * Threads which are starting up and they are not in the 'threads' hash yet.
165 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
166 * Protected by mono_threads_lock ().
168 static MonoGHashTable *threads_starting_up = NULL;
170 /* Contains tids */
171 /* Protected by the threads lock */
172 static GHashTable *joinable_threads;
173 static gint32 joinable_thread_count;
175 /* mono_threads_join_threads will take threads from joinable_threads list and wait for them. */
176 /* When this happens, the tid is not on the list anymore so mono_thread_join assumes the thread has complete */
177 /* and will return back to the caller. This could cause a race since caller of join assumes thread has completed */
178 /* and on some OS it could cause errors. Keeping the tid's currently pending a native thread join call */
179 /* in a separate table (only affecting callers interested in this internal join detail) and look at that table in mono_thread_join */
180 /* will close this race. */
181 static GHashTable *pending_native_thread_join_calls;
182 static MonoCoopCond pending_native_thread_join_calls_event;
184 static GHashTable *pending_joinable_threads;
185 static gint32 pending_joinable_thread_count;
187 static MonoCoopCond zero_pending_joinable_thread_event;
189 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info);
190 static gboolean threads_wait_pending_joinable_threads (uint32_t timeout);
191 static gchar* thread_dump_dir = NULL;
193 #define SET_CURRENT_OBJECT mono_tls_set_thread
194 #define GET_CURRENT_OBJECT mono_tls_get_thread
196 /* function called at thread start */
197 static MonoThreadStartCB mono_thread_start_cb = NULL;
199 /* function called at thread attach */
200 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
202 /* function called at thread cleanup */
203 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
205 /* The default stack size for each thread */
206 static guint32 default_stacksize = 0;
207 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
209 static void context_adjust_static_data (MonoAppContextHandle ctx);
210 static void mono_free_static_data (gpointer* static_data);
211 static void mono_init_static_data_info (StaticDataInfo *static_data);
212 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
213 static gboolean mono_thread_resume (MonoInternalThread* thread);
214 static void async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort);
215 static void self_abort_internal (MonoError *error);
216 static void async_suspend_internal (MonoInternalThread *thread, gboolean interrupt);
217 static void self_suspend_internal (void);
219 static gboolean
220 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync);
222 MONO_COLD void
223 mono_set_pending_exception_handle (MonoExceptionHandle exc);
225 static MonoException*
226 mono_thread_execute_interruption_ptr (void);
228 static void
229 mono_thread_execute_interruption_void (void);
231 static gboolean
232 mono_thread_execute_interruption (MonoExceptionHandle *pexc);
234 static void ref_stack_destroy (gpointer rs);
236 #if SIZEOF_VOID_P == 4
237 /* Spin lock for unaligned InterlockedXXX 64 bit functions on 32bit platforms. */
238 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
239 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
240 static mono_mutex_t interlocked_mutex;
241 #endif
243 /* global count of thread interruptions requested */
244 static gint32 thread_interruption_requested = 0;
246 /* Event signaled when a thread changes its background mode */
247 static MonoOSEvent background_change_event;
249 static gboolean shutting_down = FALSE;
251 static gint32 managed_thread_id_counter = 0;
253 static void
254 mono_threads_lock (void)
256 mono_locks_coop_acquire (&threads_mutex, ThreadsLock);
259 static void
260 mono_threads_unlock (void)
262 mono_locks_coop_release (&threads_mutex, ThreadsLock);
266 static guint32
267 get_next_managed_thread_id (void)
269 return mono_atomic_inc_i32 (&managed_thread_id_counter);
273 * We separate interruptions/exceptions into either sync (they can be processed anytime,
274 * normally as soon as they are set, and are set by the same thread) and async (they can't
275 * be processed inside abort protected blocks and are normally set by other threads). We
276 * can have both a pending sync and async interruption. In this case, the sync exception is
277 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
278 * also handle all sync type exceptions before the async type exceptions.
280 enum {
281 INTERRUPT_SYNC_REQUESTED_BIT = 0x1,
282 INTERRUPT_ASYNC_REQUESTED_BIT = 0x2,
283 INTERRUPT_REQUESTED_MASK = 0x3,
284 ABORT_PROT_BLOCK_SHIFT = 2,
285 ABORT_PROT_BLOCK_BITS = 8,
286 ABORT_PROT_BLOCK_MASK = (((1 << ABORT_PROT_BLOCK_BITS) - 1) << ABORT_PROT_BLOCK_SHIFT)
289 static int
290 mono_thread_get_abort_prot_block_count (MonoInternalThread *thread)
292 gsize state = thread->thread_state;
293 return (state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT;
296 gboolean
297 mono_threads_is_current_thread_in_protected_block (void)
299 MonoInternalThread *thread = mono_thread_internal_current ();
301 return mono_thread_get_abort_prot_block_count (thread) > 0;
304 void
305 mono_threads_begin_abort_protected_block (void)
307 MonoInternalThread *thread = mono_thread_internal_current ();
308 gsize old_state, new_state;
309 int new_val;
310 do {
311 old_state = thread->thread_state;
313 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) + 1;
314 //bounds check abort_prot_count
315 g_assert (new_val > 0);
316 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
318 new_state = old_state + (1 << ABORT_PROT_BLOCK_SHIFT);
319 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
321 /* Defer async request since we won't be able to process until exiting the block */
322 if (new_val == 1 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
323 mono_atomic_dec_i32 (&thread_interruption_requested);
324 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
325 if (thread_interruption_requested < 0)
326 g_warning ("bad thread_interruption_requested state");
327 } else {
328 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
332 static gboolean
333 mono_thread_state_has_interruption (gsize state)
335 /* pending exception, self abort */
336 if (state & INTERRUPT_SYNC_REQUESTED_BIT)
337 return TRUE;
339 /* abort, interruption, suspend */
340 if ((state & INTERRUPT_ASYNC_REQUESTED_BIT) && !(state & ABORT_PROT_BLOCK_MASK))
341 return TRUE;
343 return FALSE;
346 gboolean
347 mono_threads_end_abort_protected_block (void)
349 MonoInternalThread *thread = mono_thread_internal_current ();
350 gsize old_state, new_state;
351 int new_val;
352 do {
353 old_state = thread->thread_state;
355 //bounds check abort_prot_count
356 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) - 1;
357 g_assert (new_val >= 0);
358 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
360 new_state = old_state - (1 << ABORT_PROT_BLOCK_SHIFT);
361 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
363 if (new_val == 0 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
364 mono_atomic_inc_i32 (&thread_interruption_requested);
365 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
366 } else {
367 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
370 return mono_thread_state_has_interruption (new_state);
373 static gboolean
374 mono_thread_get_interruption_requested (MonoInternalThread *thread)
376 gsize state = thread->thread_state;
378 return mono_thread_state_has_interruption (state);
382 * Returns TRUE is there was a state change
383 * We clear a single interruption request, sync has priority.
385 static gboolean
386 mono_thread_clear_interruption_requested (MonoInternalThread *thread)
388 gsize old_state, new_state;
389 do {
390 old_state = thread->thread_state;
392 // no interruption to process
393 if (!(old_state & INTERRUPT_SYNC_REQUESTED_BIT) &&
394 (!(old_state & INTERRUPT_ASYNC_REQUESTED_BIT) || (old_state & ABORT_PROT_BLOCK_MASK)))
395 return FALSE;
397 if (old_state & INTERRUPT_SYNC_REQUESTED_BIT)
398 new_state = old_state & ~INTERRUPT_SYNC_REQUESTED_BIT;
399 else
400 new_state = old_state & ~INTERRUPT_ASYNC_REQUESTED_BIT;
401 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
403 mono_atomic_dec_i32 (&thread_interruption_requested);
404 THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
405 if (thread_interruption_requested < 0)
406 g_warning ("bad thread_interruption_requested state");
407 return TRUE;
410 static gboolean
411 mono_thread_clear_interruption_requested_handle (MonoInternalThreadHandle thread)
413 // Internal threads are pinned so shallow coop/handle.
414 return mono_thread_clear_interruption_requested (mono_internal_thread_handle_ptr (thread));
417 /* Returns TRUE is there was a state change and the interruption can be processed */
418 static gboolean
419 mono_thread_set_interruption_requested (MonoInternalThread *thread)
421 //always force when the current thread is doing it to itself.
422 gboolean sync = thread == mono_thread_internal_current ();
423 /* Normally synchronous interruptions can bypass abort protection. */
424 return mono_thread_set_interruption_requested_flags (thread, sync);
427 /* Returns TRUE if there was a state change and the interruption can be
428 * processed. This variant defers a self abort when inside an abort protected
429 * block. Normally this should only be done when a thread has received an
430 * outside indication that it should abort. (For example when the JIT sets a
431 * flag in an finally block.)
434 static gboolean
435 mono_thread_set_self_interruption_respect_abort_prot (void)
437 MonoInternalThread *thread = mono_thread_internal_current ();
438 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
439 * which is unusual. */
440 return mono_thread_set_interruption_requested_flags (thread, FALSE);
443 /* Returns TRUE if there was a state change and the interruption can be processed. */
444 static gboolean
445 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync)
447 gsize old_state, new_state;
448 do {
449 old_state = thread->thread_state;
451 //Already set
452 if ((sync && (old_state & INTERRUPT_SYNC_REQUESTED_BIT)) ||
453 (!sync && (old_state & INTERRUPT_ASYNC_REQUESTED_BIT)))
454 return FALSE;
456 if (sync)
457 new_state = old_state | INTERRUPT_SYNC_REQUESTED_BIT;
458 else
459 new_state = old_state | INTERRUPT_ASYNC_REQUESTED_BIT;
460 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
462 if (sync || !(new_state & ABORT_PROT_BLOCK_MASK)) {
463 mono_atomic_inc_i32 (&thread_interruption_requested);
464 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
465 } else {
466 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
469 return sync || !(new_state & ABORT_PROT_BLOCK_MASK);
472 static inline MonoNativeThreadId
473 thread_get_tid (MonoInternalThread *thread)
475 /* We store the tid as a guint64 to keep the object layout constant between platforms */
476 return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
479 static void
480 free_synch_cs (MonoCoopMutex *synch_cs)
482 g_assert (synch_cs);
483 mono_coop_mutex_destroy (synch_cs);
484 g_free (synch_cs);
487 static void
488 free_longlived_thread_data (void *user_data)
490 MonoLongLivedThreadData *lltd = (MonoLongLivedThreadData*)user_data;
491 free_synch_cs (lltd->synch_cs);
493 g_free (lltd);
496 static void
497 init_longlived_thread_data (MonoLongLivedThreadData *lltd)
499 mono_refcount_init (lltd, free_longlived_thread_data);
500 mono_refcount_inc (lltd);
501 /* Initial refcount is 2: decremented once by
502 * mono_thread_detach_internal and once by the MonoInternalThread
503 * finalizer - whichever one happens later will deallocate. */
505 lltd->synch_cs = g_new0 (MonoCoopMutex, 1);
506 mono_coop_mutex_init_recursive (lltd->synch_cs);
508 mono_memory_barrier ();
511 static void
512 dec_longlived_thread_data (MonoLongLivedThreadData *lltd)
514 mono_refcount_dec (lltd);
517 static inline void
518 lock_thread (MonoInternalThread *thread)
520 g_assert (thread->longlived);
521 g_assert (thread->longlived->synch_cs);
523 mono_coop_mutex_lock (thread->longlived->synch_cs);
526 static inline void
527 unlock_thread (MonoInternalThread *thread)
529 mono_coop_mutex_unlock (thread->longlived->synch_cs);
532 static void
533 lock_thread_handle (MonoInternalThreadHandle thread)
535 lock_thread (mono_internal_thread_handle_ptr (thread));
538 static void
539 unlock_thread_handle (MonoInternalThreadHandle thread)
541 unlock_thread (mono_internal_thread_handle_ptr (thread));
544 static inline gboolean
545 is_appdomainunloaded_exception (MonoClass *klass)
547 #ifdef ENABLE_NETCORE
548 return FALSE;
549 #else
550 return klass == mono_class_get_appdomain_unloaded_exception_class ();
551 #endif
554 static inline gboolean
555 is_threadabort_exception (MonoClass *klass)
557 return klass == mono_defaults.threadabortexception_class;
561 * A special static data offset (guint32) consists of 3 parts:
563 * [0] 6-bit index into the array of chunks.
564 * [6] 25-bit offset into the array.
565 * [31] Bit indicating thread or context static.
568 typedef union {
569 struct {
570 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
571 guint32 type : 1;
572 guint32 offset : 25;
573 guint32 index : 6;
574 #else
575 guint32 index : 6;
576 guint32 offset : 25;
577 guint32 type : 1;
578 #endif
579 } fields;
580 guint32 raw;
581 } SpecialStaticOffset;
583 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
584 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
586 static guint32
587 MAKE_SPECIAL_STATIC_OFFSET (guint32 index, guint32 offset, guint32 type)
589 SpecialStaticOffset special_static_offset;
590 memset (&special_static_offset, 0, sizeof (special_static_offset));
591 special_static_offset.fields.index = index;
592 special_static_offset.fields.offset = offset;
593 special_static_offset.fields.type = type;
594 return special_static_offset.raw;
597 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
598 (((SpecialStaticOffset *) &(x))->fields.f)
600 static gpointer
601 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
603 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_THREAD);
605 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
606 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
608 return ((char *) thread->static_data [idx]) + off;
611 static gpointer
612 get_context_static_data (MonoAppContext *ctx, guint32 offset)
614 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT);
616 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
617 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
619 return ((char *) ctx->static_data [idx]) + off;
622 static MonoThread**
623 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
625 static MonoClassField *current_thread_field = NULL;
627 guint32 offset;
629 if (!current_thread_field) {
630 current_thread_field = mono_class_get_field_from_name_full (mono_defaults.thread_class, "current_thread", NULL);
631 g_assert (current_thread_field);
634 ERROR_DECL (thread_vt_error);
635 mono_class_vtable_checked (domain, mono_defaults.thread_class, thread_vt_error);
636 mono_error_assert_ok (thread_vt_error);
637 mono_domain_lock (domain);
638 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
639 mono_domain_unlock (domain);
640 g_assert (offset);
642 return (MonoThread **)get_thread_static_data (thread, offset);
645 static void
646 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
648 #ifndef ENABLE_NETCORE
649 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
651 g_assert (current->obj.vtable->domain == domain);
653 g_assert (!*current_thread_ptr);
654 *current_thread_ptr = current;
655 #endif
658 static MonoThread*
659 create_thread_object (MonoDomain *domain, MonoInternalThread *internal)
661 #ifdef ENABLE_NETCORE
662 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
663 return internal;
664 #else
665 MonoThread *thread;
666 MonoVTable *vtable;
667 ERROR_DECL (error);
669 vtable = mono_class_vtable_checked (domain, mono_defaults.thread_class, error);
670 mono_error_assert_ok (error);
672 thread = (MonoThread*)mono_object_new_mature (vtable, error);
673 /* only possible failure mode is OOM, from which we don't expect to recover. */
674 mono_error_assert_ok (error);
676 MONO_OBJECT_SETREF_INTERNAL (thread, internal_thread, internal);
678 return thread;
679 #endif
682 static void
683 init_internal_thread_object (MonoInternalThread *thread)
685 thread->longlived = g_new0 (MonoLongLivedThreadData, 1);
686 init_longlived_thread_data (thread->longlived);
688 thread->apartment_state = ThreadApartmentState_Unknown;
689 thread->managed_id = get_next_managed_thread_id ();
690 if (mono_gc_is_moving ()) {
691 thread->thread_pinning_ref = thread;
692 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Pinning Reference");
695 thread->priority = MONO_THREAD_PRIORITY_NORMAL;
697 thread->suspended = g_new0 (MonoOSEvent, 1);
698 mono_os_event_init (thread->suspended, TRUE);
701 static MonoInternalThread*
702 create_internal_thread_object (void)
704 ERROR_DECL (error);
705 MonoInternalThread *thread;
706 MonoVTable *vt;
708 vt = mono_class_vtable_checked (mono_get_root_domain (), mono_defaults.internal_thread_class, error);
709 mono_error_assert_ok (error);
710 thread = (MonoInternalThread*) mono_object_new_mature (vt, error);
711 /* only possible failure mode is OOM, from which we don't exect to recover */
712 mono_error_assert_ok (error);
714 init_internal_thread_object (thread);
716 return thread;
719 static void
720 mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPriority priority)
722 g_assert (internal);
724 g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
725 g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
726 g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
728 #ifdef HOST_WIN32
729 BOOL res;
730 DWORD last_error;
732 g_assert (internal->native_handle);
734 MONO_ENTER_GC_SAFE;
735 res = SetThreadPriority (internal->native_handle, (int)priority - 2);
736 last_error = GetLastError ();
737 MONO_EXIT_GC_SAFE;
738 if (!res)
739 g_error ("%s: SetThreadPriority failed, error %d", __func__, last_error);
740 #elif defined(HOST_FUCHSIA)
741 int z_priority;
743 if (priority == MONO_THREAD_PRIORITY_LOWEST)
744 z_priority = ZX_PRIORITY_LOWEST;
745 else if (priority == MONO_THREAD_PRIORITY_BELOW_NORMAL)
746 z_priority = ZX_PRIORITY_LOW;
747 else if (priority == MONO_THREAD_PRIORITY_NORMAL)
748 z_priority = ZX_PRIORITY_DEFAULT;
749 else if (priority == MONO_THREAD_PRIORITY_ABOVE_NORMAL)
750 z_priority = ZX_PRIORITY_HIGH;
751 else if (priority == MONO_THREAD_PRIORITY_HIGHEST)
752 z_priority = ZX_PRIORITY_HIGHEST;
753 else
754 return;
757 // When this API becomes available on an arbitrary thread, we can use it,
758 // not available on current Zircon
760 #else /* !HOST_WIN32 and not HOST_FUCHSIA */
761 pthread_t tid;
762 int policy;
763 struct sched_param param;
764 gint res;
766 tid = thread_get_tid (internal);
768 MONO_ENTER_GC_SAFE;
769 res = pthread_getschedparam (tid, &policy, &param);
770 MONO_EXIT_GC_SAFE;
771 if (res != 0)
772 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
774 #ifdef _POSIX_PRIORITY_SCHEDULING
775 int max, min;
777 /* Necessary to get valid priority range */
779 MONO_ENTER_GC_SAFE;
780 #if defined(__PASE__)
781 /* only priorities allowed by IBM i */
782 min = PRIORITY_MIN;
783 max = PRIORITY_MAX;
784 #else
785 min = sched_get_priority_min (policy);
786 max = sched_get_priority_max (policy);
787 #endif
788 MONO_EXIT_GC_SAFE;
790 if (max > 0 && min >= 0 && max > min) {
791 double srange, drange, sposition, dposition;
792 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
793 drange = max - min;
794 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
795 dposition = (sposition / srange) * drange;
796 param.sched_priority = (int)(dposition + min);
797 } else
798 #endif
800 switch (policy) {
801 case SCHED_FIFO:
802 case SCHED_RR:
803 param.sched_priority = 50;
804 break;
805 #ifdef SCHED_BATCH
806 case SCHED_BATCH:
807 #endif
808 case SCHED_OTHER:
809 param.sched_priority = 0;
810 break;
811 default:
812 g_warning ("%s: unknown policy %d", __func__, policy);
813 return;
817 MONO_ENTER_GC_SAFE;
818 #if defined(__PASE__)
819 /* only scheduling param allowed by IBM i */
820 res = pthread_setschedparam (tid, SCHED_OTHER, &param);
821 #else
822 res = pthread_setschedparam (tid, policy, &param);
823 #endif
824 MONO_EXIT_GC_SAFE;
825 if (res != 0) {
826 if (res == EPERM) {
827 #if !defined(_AIX)
828 /* AIX doesn't like doing this and will spam this every time;
829 * weirdly, i doesn't complain
831 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
832 #endif
833 return;
835 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
837 #endif /* HOST_WIN32 */
840 static void
841 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal);
843 static gboolean
844 mono_thread_attach_internal (MonoThread *thread, gboolean force_attach, gboolean force_domain)
846 MonoThreadInfo *info;
847 MonoInternalThread *internal;
848 MonoDomain *domain, *root_domain;
849 guint32 gchandle;
851 g_assert (thread);
853 info = mono_thread_info_current ();
854 g_assert (info);
856 internal = thread->internal_thread;
857 g_assert (internal);
859 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
860 * - the MonoInternalThread TLS key is destroyed: set it to NULL
861 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
862 * - it calls MonoThreadInfoCallbacks.thread_detach
863 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
864 mono_thread_info_set_internal_thread_gchandle (info, mono_gchandle_new_internal ((MonoObject*) internal, FALSE));
866 internal->handle = mono_threads_open_thread_handle (info->handle);
867 internal->native_handle = MONO_NATIVE_THREAD_HANDLE_TO_GPOINTER (mono_threads_open_native_thread_handle (info->native_handle));
868 internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
869 internal->thread_info = info;
870 internal->small_id = info->small_id;
872 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Setting current_object_key to %p", __func__, mono_native_thread_id_get (), internal));
874 SET_CURRENT_OBJECT (internal);
876 domain = mono_object_domain (thread);
878 mono_thread_push_appdomain_ref (domain);
879 if (!mono_domain_set_fast (domain, force_domain)) {
880 mono_thread_pop_appdomain_ref ();
881 goto fail;
884 mono_threads_lock ();
886 if (shutting_down && !force_attach) {
887 mono_threads_unlock ();
888 mono_thread_pop_appdomain_ref ();
889 goto fail;
892 if (threads_starting_up)
893 mono_g_hash_table_remove (threads_starting_up, thread);
895 if (!threads) {
896 threads = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Table");
899 /* We don't need to duplicate thread->handle, because it is
900 * only closed when the thread object is finalized by the GC. */
901 mono_g_hash_table_insert_internal (threads, (gpointer)(gsize)(internal->tid), internal);
903 /* We have to do this here because mono_thread_start_cb
904 * requires that root_domain_thread is set up. */
905 if (thread_static_info.offset || thread_static_info.idx > 0) {
906 /* get the current allocated size */
907 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (thread_static_info.idx, thread_static_info.offset, 0);
908 mono_alloc_static_data (&internal->static_data, offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), TRUE);
911 mono_threads_unlock ();
913 root_domain = mono_get_root_domain ();
915 g_assert (!internal->root_domain_thread);
916 if (domain != root_domain)
917 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, create_thread_object (root_domain, internal));
918 else
919 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, thread);
921 if (domain != root_domain)
922 set_current_thread_for_domain (root_domain, internal, internal->root_domain_thread);
924 set_current_thread_for_domain (domain, internal, thread);
926 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, internal->tid, internal->handle));
928 return TRUE;
930 fail:
931 mono_threads_lock ();
932 if (threads_starting_up)
933 mono_g_hash_table_remove (threads_starting_up, thread);
934 mono_threads_unlock ();
936 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
937 g_error ("%s: failed to get gchandle, info %p", __func__, info);
939 mono_gchandle_free_internal (gchandle);
941 mono_thread_info_unset_internal_thread_gchandle (info);
943 SET_CURRENT_OBJECT(NULL);
945 return FALSE;
948 static void
949 mono_thread_detach_internal (MonoInternalThread *thread)
951 MonoThreadInfo *info;
952 MonoInternalThread *value;
953 gboolean removed;
954 guint32 gchandle;
956 g_assert (mono_thread_internal_is_current (thread));
958 g_assert (thread != NULL);
959 SET_CURRENT_OBJECT (thread);
961 info = thread->thread_info;
962 g_assert (info);
964 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
966 MONO_PROFILER_RAISE (thread_stopping, (thread->tid));
969 * Prevent race condition between thread shutdown and runtime shutdown.
970 * Including all runtime threads in the pending joinable count will make
971 * sure shutdown will wait for it to get onto the joinable thread list before
972 * critical resources have been cleanup (like GC memory). Threads getting onto
973 * the joinable thread list should just about to exit and not blocking a potential
974 * join call. Owner of threads attached to the runtime but not identified as runtime
975 * threads needs to make sure thread detach calls won't race with runtime shutdown.
977 threads_add_pending_joinable_runtime_thread (info);
979 #ifndef HOST_WIN32
980 mono_w32mutex_abandon (thread);
981 #endif
983 mono_gchandle_free_internal (thread->abort_state_handle);
984 thread->abort_state_handle = 0;
986 thread->abort_exc = NULL;
987 thread->current_appcontext = NULL;
989 LOCK_THREAD (thread);
991 thread->state |= ThreadState_Stopped;
992 thread->state &= ~ThreadState_Background;
994 UNLOCK_THREAD (thread);
997 An interruption request has leaked to cleanup. Adjust the global counter.
999 This can happen is the abort source thread finds the abortee (this) thread
1000 in unmanaged code. If this thread never trips back to managed code or check
1001 the local flag it will be left set and positively unbalance the global counter.
1003 Leaving the counter unbalanced will cause a performance degradation since all threads
1004 will now keep checking their local flags all the time.
1006 mono_thread_clear_interruption_requested (thread);
1008 mono_threads_lock ();
1010 g_assert (threads);
1012 if (!mono_g_hash_table_lookup_extended (threads, (gpointer)thread->tid, NULL, (gpointer*) &value)) {
1013 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__, thread, thread->tid);
1014 } else if (thread != value) {
1015 /* We have to check whether the thread object for the tid is still the same in the table because the
1016 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
1017 * the table, but with another thread object. */
1018 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__, thread, thread->tid, value, value->tid);
1021 removed = mono_g_hash_table_remove (threads, (gpointer)thread->tid);
1022 g_assert (removed);
1024 mono_threads_unlock ();
1026 /* Don't close the handle here, wait for the object finalizer
1027 * to do it. Otherwise, the following race condition applies:
1029 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
1031 * 2) Some other handle is reassigned the same slot
1033 * 3) Another thread tries to join the first thread, and
1034 * blocks waiting for the reassigned handle to be signalled
1035 * (which might never happen). This is possible, because the
1036 * thread calling Join() still has a reference to the first
1037 * thread's object.
1040 mono_release_type_locks (thread);
1042 MONO_PROFILER_RAISE (thread_stopped, (thread->tid));
1043 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->stack_start_limit)));
1044 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->handle_stack)));
1047 * This will signal async signal handlers that the thread has exited.
1048 * The profiler callback needs this to be set, so it cannot be done earlier.
1050 mono_domain_unset ();
1051 mono_memory_barrier ();
1053 mono_thread_pop_appdomain_ref ();
1055 mono_free_static_data (thread->static_data);
1056 thread->static_data = NULL;
1057 ref_stack_destroy (thread->appdomain_refs);
1058 thread->appdomain_refs = NULL;
1060 g_assert (thread->suspended);
1061 mono_os_event_destroy (thread->suspended);
1062 g_free (thread->suspended);
1063 thread->suspended = NULL;
1065 if (mono_thread_cleanup_fn)
1066 mono_thread_cleanup_fn (thread_get_tid (thread));
1068 mono_memory_barrier ();
1070 if (mono_gc_is_moving ()) {
1071 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
1072 thread->thread_pinning_ref = NULL;
1075 /* There is no more any guarantee that `thread` is alive */
1076 mono_memory_barrier ();
1078 SET_CURRENT_OBJECT (NULL);
1079 mono_domain_unset ();
1081 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
1082 g_error ("%s: failed to get gchandle, info = %p", __func__, info);
1084 mono_gchandle_free_internal (gchandle);
1086 mono_thread_info_unset_internal_thread_gchandle (info);
1088 /* Possibly free synch_cs, if the finalizer for InternalThread already
1089 * ran also. */
1090 dec_longlived_thread_data (thread->longlived);
1092 MONO_PROFILER_RAISE (thread_exited, (thread->tid));
1094 /* Don't need to close the handle to this thread, even though we took a
1095 * reference in mono_thread_attach (), because the GC will do it
1096 * when the Thread object is finalised.
1100 typedef struct {
1101 gint32 ref;
1102 MonoThread *thread;
1103 MonoObject *start_delegate;
1104 MonoObject *start_delegate_arg;
1105 MonoThreadStart start_func;
1106 gpointer start_func_arg;
1107 gboolean force_attach;
1108 gboolean failed;
1109 MonoCoopSem registered;
1110 } StartInfo;
1112 static void
1113 fire_attach_profiler_events (MonoNativeThreadId tid)
1115 MONO_PROFILER_RAISE (thread_started, ((uintptr_t) tid));
1117 MonoThreadInfo *info = mono_thread_info_current ();
1119 MONO_PROFILER_RAISE (gc_root_register, (
1120 (const mono_byte*)(info->stack_start_limit),
1121 (char *) info->stack_end - (char *) info->stack_start_limit,
1122 MONO_ROOT_SOURCE_STACK,
1123 (void *) tid,
1124 "Thread Stack"));
1126 // The handle stack is a pseudo-root similar to the finalizer queues.
1127 MONO_PROFILER_RAISE (gc_root_register, (
1128 (const mono_byte*)info->handle_stack,
1130 MONO_ROOT_SOURCE_HANDLE,
1131 (void *) tid,
1132 "Handle Stack"));
1135 static guint32 WINAPI
1136 start_wrapper_internal (StartInfo *start_info, gsize *stack_ptr)
1138 ERROR_DECL (error);
1139 MonoThreadStart start_func;
1140 void *start_func_arg;
1141 gsize tid;
1143 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1144 * GC stack walk.
1146 MonoThread *thread;
1147 MonoInternalThread *internal;
1148 MonoObject *start_delegate;
1149 MonoObject *start_delegate_arg;
1151 thread = start_info->thread;
1152 internal = thread->internal_thread;
1154 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper", __func__, mono_native_thread_id_get ()));
1156 if (!mono_thread_attach_internal (thread, start_info->force_attach, FALSE)) {
1157 start_info->failed = TRUE;
1159 mono_coop_sem_post (&start_info->registered);
1161 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1162 mono_coop_sem_destroy (&start_info->registered);
1163 g_free (start_info);
1166 return 0;
1169 mono_thread_internal_set_priority (internal, (MonoThreadPriority)internal->priority);
1171 tid = internal->tid;
1173 start_delegate = start_info->start_delegate;
1174 start_delegate_arg = start_info->start_delegate_arg;
1175 start_func = start_info->start_func;
1176 start_func_arg = start_info->start_func_arg;
1178 /* This MUST be called before any managed code can be
1179 * executed, as it calls the callback function that (for the
1180 * jit) sets the lmf marker.
1183 if (mono_thread_start_cb)
1184 mono_thread_start_cb (tid, stack_ptr, (gpointer)start_func);
1186 /* On 2.0 profile (and higher), set explicitly since state might have been
1187 Unknown */
1188 if (internal->apartment_state == ThreadApartmentState_Unknown)
1189 internal->apartment_state = ThreadApartmentState_MTA;
1191 mono_thread_init_apartment_state ();
1193 /* Let the thread that called Start() know we're ready */
1194 mono_coop_sem_post (&start_info->registered);
1196 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1197 mono_coop_sem_destroy (&start_info->registered);
1198 g_free (start_info);
1201 /* start_info is not valid anymore */
1202 start_info = NULL;
1205 * Call this after calling start_notify, since the profiler callback might want
1206 * to lock the thread, and the lock is held by thread_start () which waits for
1207 * start_notify.
1209 fire_attach_profiler_events ((MonoNativeThreadId) tid);
1211 /* if the name was set before starting, we didn't invoke the profiler callback */
1212 if (internal->name) {
1213 char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
1214 MONO_PROFILER_RAISE (thread_name, (internal->tid, tname));
1215 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), tname);
1216 g_free (tname);
1219 /* start_func is set only for unmanaged start functions */
1220 if (start_func) {
1221 start_func (start_func_arg);
1222 } else {
1223 #ifdef ENABLE_NETCORE
1224 static MonoMethod *cb;
1226 /* Call a callback in the RuntimeThread class */
1227 g_assert (start_delegate == NULL);
1228 if (!cb) {
1229 cb = mono_class_get_method_from_name_checked (internal->obj.vtable->klass, "StartCallback", 0, 0, error);
1230 g_assert (cb);
1231 mono_error_assert_ok (error);
1233 mono_runtime_invoke_checked (cb, internal, NULL, error);
1234 #else
1235 void *args [1];
1237 g_assert (start_delegate != NULL);
1239 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1240 args [0] = (gpointer) start_delegate_arg;
1241 mono_runtime_delegate_invoke_checked (start_delegate, args, error);
1242 #endif
1244 if (!mono_error_ok (error)) {
1245 MonoException *ex = mono_error_convert_to_exception (error);
1247 g_assert (ex != NULL);
1248 MonoClass *klass = mono_object_class (ex);
1249 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
1250 !is_threadabort_exception (klass)) {
1251 mono_unhandled_exception_internal (&ex->object);
1252 mono_invoke_unhandled_exception_hook (&ex->object);
1253 g_assert_not_reached ();
1255 } else {
1256 mono_error_cleanup (error);
1260 /* If the thread calls ExitThread at all, this remaining code
1261 * will not be executed, but the main thread will eventually
1262 * call mono_thread_detach_internal() on this thread's behalf.
1265 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
1267 /* Do any cleanup needed for apartment state. This
1268 * cannot be done in mono_thread_detach_internal since
1269 * mono_thread_detach_internal could be called for a
1270 * thread other than the current thread.
1271 * mono_thread_cleanup_apartment_state cleans up apartment
1272 * for the current thead */
1273 mono_thread_cleanup_apartment_state ();
1275 mono_thread_detach_internal (internal);
1277 return 0;
1280 static mono_thread_start_return_t WINAPI
1281 start_wrapper (gpointer data)
1283 StartInfo *start_info;
1284 MonoThreadInfo *info;
1285 gsize res;
1287 start_info = (StartInfo*) data;
1288 g_assert (start_info);
1290 info = mono_thread_info_attach ();
1291 info->runtime_thread = TRUE;
1293 /* Run the actual main function of the thread */
1294 res = start_wrapper_internal (start_info, (gsize*)info->stack_end);
1296 mono_thread_info_exit (res);
1298 g_assert_not_reached ();
1302 * create_thread:
1304 * Common thread creation code.
1305 * LOCKING: Acquires the threads lock.
1307 static gboolean
1308 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
1309 MonoThreadCreateFlags flags, MonoError *error)
1311 StartInfo *start_info = NULL;
1312 MonoNativeThreadId tid;
1313 gboolean ret;
1314 gsize stack_set_size;
1316 if (start_delegate)
1317 g_assert (!start_func && !start_func_arg);
1318 if (start_func)
1319 g_assert (!start_delegate);
1321 if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
1322 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
1323 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1325 if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
1326 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
1327 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1331 * Join joinable threads to prevent running out of threads since the finalizer
1332 * thread might be blocked/backlogged.
1334 mono_threads_join_threads ();
1336 error_init (error);
1338 mono_threads_lock ();
1339 if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
1340 mono_threads_unlock ();
1341 mono_error_set_execution_engine (error, "Couldn't create thread. Runtime is shutting down.");
1342 return FALSE;
1344 if (threads_starting_up == NULL) {
1345 threads_starting_up = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Starting Table");
1347 mono_g_hash_table_insert_internal (threads_starting_up, thread, thread);
1348 mono_threads_unlock ();
1350 internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
1351 if (internal->threadpool_thread)
1352 mono_thread_set_state (internal, ThreadState_Background);
1354 internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
1356 start_info = g_new0 (StartInfo, 1);
1357 start_info->ref = 2;
1358 start_info->thread = thread;
1359 start_info->start_delegate = start_delegate;
1360 start_info->start_delegate_arg = thread->start_obj;
1361 start_info->start_func = start_func;
1362 start_info->start_func_arg = start_func_arg;
1363 start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
1364 start_info->failed = FALSE;
1365 mono_coop_sem_init (&start_info->registered, 0);
1367 if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
1368 stack_set_size = default_stacksize_for_thread (internal);
1369 else
1370 stack_set_size = 0;
1372 if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
1373 /* The thread couldn't be created, so set an exception */
1374 mono_threads_lock ();
1375 mono_g_hash_table_remove (threads_starting_up, thread);
1376 mono_threads_unlock ();
1377 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1378 /* ref is not going to be decremented in start_wrapper_internal */
1379 mono_atomic_dec_i32 (&start_info->ref);
1380 ret = FALSE;
1381 goto done;
1384 internal->stack_size = (int) stack_set_size;
1386 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1389 * Wait for the thread to set up its TLS data etc, so
1390 * theres no potential race condition if someone tries
1391 * to look up the data believing the thread has
1392 * started
1395 mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1397 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Done launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1399 ret = !start_info->failed;
1401 done:
1402 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1403 mono_coop_sem_destroy (&start_info->registered);
1404 g_free (start_info);
1407 return ret;
1411 * mono_thread_new_init:
1413 void
1414 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1416 if (mono_thread_start_cb) {
1417 mono_thread_start_cb (tid, stack_start, func);
1422 * mono_threads_set_default_stacksize:
1424 void
1425 mono_threads_set_default_stacksize (guint32 stacksize)
1427 default_stacksize = stacksize;
1431 * mono_threads_get_default_stacksize:
1433 guint32
1434 mono_threads_get_default_stacksize (void)
1436 return default_stacksize;
1440 * mono_thread_create_internal:
1442 * ARG should not be a GC reference.
1444 MonoInternalThread*
1445 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1447 MonoThread *thread;
1448 MonoInternalThread *internal;
1449 gboolean res;
1451 error_init (error);
1453 internal = create_internal_thread_object ();
1455 thread = create_thread_object (domain, internal);
1457 LOCK_THREAD (internal);
1459 res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1460 (void)res;
1462 UNLOCK_THREAD (internal);
1464 return_val_if_nok (error, NULL);
1465 return internal;
1468 MonoInternalThreadHandle
1469 mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1471 // FIXME invert
1472 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_create_internal (domain, func, arg, flags, error));
1476 * mono_thread_create:
1478 void
1479 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1481 MONO_ENTER_GC_UNSAFE;
1482 ERROR_DECL (error);
1483 if (!mono_thread_create_checked (domain, func, arg, error))
1484 mono_error_cleanup (error);
1485 MONO_EXIT_GC_UNSAFE;
1488 gboolean
1489 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1491 return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1495 * mono_thread_attach:
1497 MonoThread *
1498 mono_thread_attach (MonoDomain *domain)
1500 MonoInternalThread *internal;
1501 MonoThread *thread;
1502 MonoThreadInfo *info;
1503 MonoNativeThreadId tid;
1505 if (mono_thread_internal_current_is_attached ()) {
1506 if (domain != mono_domain_get ())
1507 mono_domain_set_fast (domain, TRUE);
1508 /* Already attached */
1509 return mono_thread_current ();
1512 info = mono_thread_info_attach ();
1513 g_assert (info);
1515 tid=mono_native_thread_id_get ();
1517 if (mono_runtime_get_no_exec ())
1518 return NULL;
1520 internal = create_internal_thread_object ();
1522 thread = create_thread_object (domain, internal);
1524 if (!mono_thread_attach_internal (thread, FALSE, TRUE)) {
1525 /* Mono is shutting down, so just wait for the end */
1526 for (;;)
1527 mono_thread_info_sleep (10000, NULL);
1530 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, internal->handle));
1532 if (mono_thread_attach_cb)
1533 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1535 fire_attach_profiler_events (tid);
1537 return thread;
1541 * mono_thread_detach:
1543 void
1544 mono_thread_detach (MonoThread *thread)
1546 if (thread)
1547 mono_thread_detach_internal (thread->internal_thread);
1551 * mono_thread_detach_if_exiting:
1553 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1554 * This should be used at the end of embedding code which calls into managed code, and which
1555 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1557 mono_bool
1558 mono_thread_detach_if_exiting (void)
1560 if (mono_thread_info_is_exiting ()) {
1561 MonoInternalThread *thread;
1563 thread = mono_thread_internal_current ();
1564 if (thread) {
1565 // Switch to GC Unsafe thread state before detaching;
1566 // don't expect to undo this switch, hence unbalanced.
1567 gpointer dummy;
1568 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy);
1570 mono_thread_detach_internal (thread);
1571 mono_thread_info_detach ();
1572 return TRUE;
1575 return FALSE;
1578 gboolean
1579 mono_thread_internal_current_is_attached (void)
1581 MonoInternalThread *internal;
1583 internal = GET_CURRENT_OBJECT ();
1584 if (!internal)
1585 return FALSE;
1587 return TRUE;
1591 * mono_thread_exit:
1593 void
1594 mono_thread_exit (void)
1596 MonoInternalThread *thread = mono_thread_internal_current ();
1598 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
1600 mono_thread_detach_internal (thread);
1602 /* we could add a callback here for embedders to use. */
1603 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1604 exit (mono_environment_exitcode_get ());
1606 mono_thread_info_exit (0);
1609 static void
1610 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle)
1612 MonoInternalThread * const internal = create_internal_thread_object ();
1614 internal->state = ThreadState_Unstarted;
1616 int const thread_gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, this_obj_handle), TRUE);
1618 MonoThreadObject *this_obj = MONO_HANDLE_RAW (this_obj_handle);
1620 mono_atomic_cas_ptr ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1622 mono_gchandle_free_internal (thread_gchandle);
1625 #ifndef ENABLE_NETCORE
1626 void
1627 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle, MonoError *error)
1629 mono_thread_construct_internal (this_obj_handle);
1631 #endif
1633 MonoThreadObjectHandle
1634 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError *error)
1636 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
1639 static MonoInternalThread*
1640 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle)
1642 return MONO_HANDLE_GETVAL(thread_handle, internal_thread); // InternalThreads are always pinned.
1645 static void
1646 mono_error_set_exception_thread_state (MonoError *error, const char *exception_message)
1648 mono_error_set_generic_error (error, "System.Threading", "ThreadStateException", "%s", exception_message);
1651 static void
1652 mono_error_set_exception_thread_not_started_or_dead (MonoError *error)
1654 mono_error_set_exception_thread_state (error, "Thread has not been started, or is dead.");
1657 #ifndef ENABLE_NETCORE
1658 MonoBoolean
1659 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle, MonoObjectHandle start_handle, MonoError *error)
1661 MonoInternalThread *internal;
1662 gboolean res;
1663 MonoThread *this_obj = MONO_HANDLE_RAW (thread_handle);
1664 MonoObject *start = MONO_HANDLE_RAW (start_handle);
1666 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1668 internal = thread_handle_to_internal_ptr (thread_handle);
1670 if (!internal) {
1671 mono_thread_construct_internal (thread_handle);
1672 internal = thread_handle_to_internal_ptr (thread_handle);
1673 g_assert (internal);
1676 LOCK_THREAD (internal);
1678 if ((internal->state & ThreadState_Unstarted) == 0) {
1679 UNLOCK_THREAD (internal);
1680 mono_error_set_exception_thread_state (error, "Thread has already been started.");
1681 return FALSE;
1684 if ((internal->state & ThreadState_Aborted) != 0) {
1685 UNLOCK_THREAD (internal);
1686 return TRUE;
1689 res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
1690 if (!res) {
1691 UNLOCK_THREAD (internal);
1692 return FALSE;
1695 internal->state &= ~ThreadState_Unstarted;
1697 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, thread));
1699 UNLOCK_THREAD (internal);
1700 return TRUE;
1702 #endif
1705 * This is called from the finalizer of the internal thread object.
1707 void
1708 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle, MonoError *error)
1710 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (this_obj_handle);
1711 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this_obj, this_obj->handle));
1714 * Since threads keep a reference to their thread object while running, by
1715 * the time this function is called, the thread has already exited/detached,
1716 * i.e. mono_thread_detach_internal () has ran. The exception is during
1717 * shutdown, when mono_thread_detach_internal () can be called after this.
1719 if (this_obj->handle) {
1720 mono_threads_close_thread_handle (this_obj->handle);
1721 this_obj->handle = NULL;
1724 mono_threads_close_native_thread_handle (MONO_GPOINTER_TO_NATIVE_THREAD_HANDLE (this_obj->native_handle));
1725 this_obj->native_handle = NULL;
1727 /* Possibly free synch_cs, if the thread already detached also. */
1728 dec_longlived_thread_data (this_obj->longlived);
1731 if (this_obj->name) {
1732 void *name = this_obj->name;
1733 this_obj->name = NULL;
1734 g_free (name);
1738 void
1739 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoError *error)
1741 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1743 if (mono_thread_current_check_pending_interrupt ())
1744 return;
1746 MonoInternalThread * const thread = mono_thread_internal_current ();
1748 HANDLE_LOOP_PREPARE;
1750 while (TRUE) {
1751 gboolean alerted = FALSE;
1753 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1755 (void)mono_thread_info_sleep (ms, &alerted);
1757 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1759 if (!alerted)
1760 return;
1762 SETUP_ICALL_FRAME;
1764 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
1766 const gboolean interrupt = mono_thread_execute_interruption (&exc);
1768 if (interrupt)
1769 mono_set_pending_exception_handle (exc);
1771 CLEAR_ICALL_FRAME;
1773 if (interrupt)
1774 return;
1775 if (ms == MONO_INFINITE_WAIT) // FIXME: !MONO_INFINITE_WAIT
1776 continue;
1777 return;
1781 void
1782 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error)
1786 #ifndef ENABLE_NETCORE
1787 gint32
1788 ves_icall_System_Threading_Thread_GetDomainID (MonoError *error)
1790 return mono_domain_get()->domain_id;
1792 #endif
1795 * mono_thread_get_name_utf8:
1796 * \returns the name of the thread in UTF-8.
1797 * Return NULL if the thread has no name.
1798 * The returned memory is owned by the caller (g_free it).
1800 char *
1801 mono_thread_get_name_utf8 (MonoThread *thread)
1803 if (thread == NULL)
1804 return NULL;
1806 MonoInternalThread *internal = thread->internal_thread;
1807 if (internal == NULL)
1808 return NULL;
1810 LOCK_THREAD (internal);
1812 char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
1814 UNLOCK_THREAD (internal);
1816 return tname;
1820 * mono_thread_get_managed_id:
1821 * \returns the \c Thread.ManagedThreadId value of \p thread.
1822 * Returns \c -1 if \p thread is NULL.
1824 int32_t
1825 mono_thread_get_managed_id (MonoThread *thread)
1827 if (thread == NULL)
1828 return -1;
1830 MonoInternalThread *internal = thread->internal_thread;
1831 if (internal == NULL)
1832 return -1;
1834 int32_t id = internal->managed_id;
1836 return id;
1839 #ifndef ENABLE_NETCORE
1840 MonoStringHandle
1841 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle, MonoError *error)
1843 // InternalThreads are always pinned, so shallowly coop-handleize.
1844 MonoInternalThread * const this_obj = mono_internal_thread_handle_ptr (thread_handle);
1846 MonoStringHandle str = MONO_HANDLE_NEW (MonoString, NULL);
1848 LOCK_THREAD (this_obj);
1850 if (this_obj->name)
1851 MONO_HANDLE_ASSIGN (str, mono_string_new_utf16_handle (mono_domain_get (), this_obj->name, this_obj->name_len, error));
1853 UNLOCK_THREAD (this_obj);
1855 return str;
1857 #endif
1859 void
1860 mono_thread_set_name_internal (MonoInternalThread *this_obj,
1861 MonoString *name,
1862 MonoSetThreadNameFlags flags, MonoError *error)
1864 MonoNativeThreadId tid = 0;
1866 LOCK_THREAD (this_obj);
1868 if (flags & MonoSetThreadNameFlag_Reset) {
1869 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1870 } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1871 UNLOCK_THREAD (this_obj);
1873 mono_error_set_invalid_operation (error, "%s", "Thread.Name can only be set once.");
1874 return;
1876 if (this_obj->name) {
1877 g_free (this_obj->name);
1878 this_obj->name_len = 0;
1880 if (name) {
1881 this_obj->name = g_memdup (mono_string_chars_internal (name), mono_string_length_internal (name) * sizeof (gunichar2));
1882 this_obj->name_len = mono_string_length_internal (name);
1884 if (flags & MonoSetThreadNameFlag_Permanent)
1885 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1887 else
1888 this_obj->name = NULL;
1890 if (!(this_obj->state & ThreadState_Stopped))
1891 tid = thread_get_tid (this_obj);
1893 UNLOCK_THREAD (this_obj);
1895 if (this_obj->name && tid) {
1896 char *tname = mono_string_to_utf8_checked_internal (name, error);
1897 return_if_nok (error);
1898 MONO_PROFILER_RAISE (thread_name, ((uintptr_t)tid, tname));
1899 mono_native_thread_set_name (tid, tname);
1900 mono_free (tname);
1904 void
1905 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1907 ERROR_DECL (error);
1908 mono_thread_set_name_internal (this_obj, name, MonoSetThreadNameFlag_Permanent, error);
1909 mono_error_set_pending_exception (error);
1912 #ifndef ENABLE_NETCORE
1914 * ves_icall_System_Threading_Thread_GetPriority_internal:
1915 * @param this_obj: The MonoInternalThread on which to operate.
1917 * Gets the priority of the given thread.
1918 * @return: The priority of the given thread.
1921 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj, MonoError *error)
1923 gint32 priority;
1925 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
1927 LOCK_THREAD (internal);
1928 priority = internal->priority;
1929 UNLOCK_THREAD (internal);
1931 return priority;
1933 #endif
1936 * ves_icall_System_Threading_Thread_SetPriority_internal:
1937 * @param this_obj: The MonoInternalThread on which to operate.
1938 * @param priority: The priority to set.
1940 * Sets the priority of the given thread.
1942 void
1943 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj, int priority, MonoError *error)
1945 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
1947 LOCK_THREAD (internal);
1948 internal->priority = priority;
1949 if (internal->thread_info != NULL)
1950 mono_thread_internal_set_priority (internal, (MonoThreadPriority)priority);
1951 UNLOCK_THREAD (internal);
1954 /* If the array is already in the requested domain, we just return it,
1955 otherwise we return a copy in that domain. */
1956 static MonoArrayHandle
1957 byte_array_to_domain (MonoArrayHandle arr, MonoDomain *domain, MonoError *error)
1959 HANDLE_FUNCTION_ENTER ()
1961 if (MONO_HANDLE_IS_NULL (arr))
1962 return MONO_HANDLE_NEW (MonoArray, NULL);
1964 if (MONO_HANDLE_DOMAIN (arr) == domain)
1965 return arr;
1967 size_t const size = mono_array_handle_length (arr);
1969 // Capture arrays into common representation for repetitious code.
1970 // These two variables could also be an array of size 2 and
1971 // repitition implemented with a loop.
1972 struct {
1973 MonoArrayHandle handle;
1974 gpointer p;
1975 guint gchandle;
1977 source = { arr },
1978 dest = { mono_array_new_handle (domain, mono_defaults.byte_class, size, error) };
1979 goto_if_nok (error, exit);
1981 // Pin both arrays.
1982 source.p = mono_array_handle_pin_with_size (source.handle, size, 0, &source.gchandle);
1983 dest.p = mono_array_handle_pin_with_size (dest.handle, size, 0, &dest.gchandle);
1985 memmove (dest.p, source.p, size);
1986 exit:
1987 // Unpin both arrays.
1988 mono_gchandle_free_internal (source.gchandle);
1989 mono_gchandle_free_internal (dest.gchandle);
1991 HANDLE_FUNCTION_RETURN_REF (MonoArray, dest.handle)
1994 #ifndef ENABLE_NETCORE
1995 MonoArrayHandle
1996 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr, MonoError *error)
1998 return byte_array_to_domain (arr, mono_get_root_domain (), error);
2001 MonoArrayHandle
2002 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr, MonoError *error)
2004 return byte_array_to_domain (arr, mono_domain_get (), error);
2006 #endif
2009 * mono_thread_current:
2011 MonoThread *
2012 mono_thread_current (void)
2014 #ifdef ENABLE_NETCORE
2015 return mono_thread_internal_current ();
2016 #else
2017 MonoDomain *domain = mono_domain_get ();
2018 MonoInternalThread *internal = mono_thread_internal_current ();
2019 MonoThread **current_thread_ptr;
2021 g_assert (internal);
2022 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2024 if (!*current_thread_ptr) {
2025 g_assert (domain != mono_get_root_domain ());
2026 *current_thread_ptr = create_thread_object (domain, internal);
2028 return *current_thread_ptr;
2029 #endif
2032 static MonoThreadObjectHandle
2033 mono_thread_current_handle (void)
2035 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
2038 /* Return the thread object belonging to INTERNAL in the current domain */
2039 static MonoThread *
2040 mono_thread_current_for_thread (MonoInternalThread *internal)
2042 #ifdef ENABLE_NETCORE
2043 return mono_thread_internal_current ();
2044 #else
2045 MonoDomain *domain = mono_domain_get ();
2046 MonoThread **current_thread_ptr;
2048 g_assert (internal);
2049 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2051 if (!*current_thread_ptr) {
2052 g_assert (domain != mono_get_root_domain ());
2053 *current_thread_ptr = create_thread_object (domain, internal);
2055 return *current_thread_ptr;
2056 #endif
2059 MonoInternalThread*
2060 mono_thread_internal_current (void)
2062 MonoInternalThread *res = GET_CURRENT_OBJECT ();
2063 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
2064 return res;
2067 MonoInternalThreadHandle
2068 mono_thread_internal_current_handle (void)
2070 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_internal_current ());
2073 static MonoThreadInfoWaitRet
2074 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
2076 MonoThreadInfoWaitRet ret;
2077 gint32 wait = ms;
2079 const gint64 start = (ms == -1) ? 0 : mono_msec_ticks ();
2080 while (TRUE) {
2081 MONO_ENTER_GC_SAFE;
2082 ret = mono_thread_info_wait_one_handle (thread_to_join, wait, TRUE);
2083 MONO_EXIT_GC_SAFE;
2085 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
2086 return ret;
2088 MonoException *exc = mono_thread_execute_interruption_ptr ();
2089 if (exc) {
2090 mono_error_set_exception_instance (error, exc);
2091 return ret;
2094 if (ms == -1)
2095 continue;
2097 /* Re-calculate ms according to the time passed */
2098 const gint32 diff_ms = (gint32)(mono_msec_ticks () - start);
2099 if (diff_ms >= ms) {
2100 ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
2101 return ret;
2103 wait = ms - diff_ms;
2106 return ret;
2109 MonoBoolean
2110 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle, int ms, MonoError *error)
2112 if (mono_thread_current_check_pending_interrupt ())
2113 return FALSE;
2115 // Internal threads are pinned so shallow coop/handle.
2116 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2117 MonoThreadHandle *handle = thread->handle;
2118 MonoInternalThread *cur_thread = mono_thread_internal_current ();
2119 gboolean ret = FALSE;
2121 LOCK_THREAD (thread);
2123 if ((thread->state & ThreadState_Unstarted) != 0) {
2124 UNLOCK_THREAD (thread);
2126 mono_error_set_exception_thread_state (error, "Thread has not been started.");
2127 return FALSE;
2130 UNLOCK_THREAD (thread);
2132 if (ms == -1)
2133 ms = MONO_INFINITE_WAIT;
2134 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
2136 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
2138 ret = mono_join_uninterrupted (handle, ms, error);
2140 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
2142 if (ret == MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
2143 THREAD_DEBUG (g_message ("%s: join successful", __func__));
2145 mono_error_assert_ok (error);
2147 /* Wait for the thread to really exit */
2148 MonoNativeThreadId tid = thread_get_tid (thread);
2149 mono_thread_join ((gpointer)(gsize)tid);
2151 return TRUE;
2154 THREAD_DEBUG (g_message ("%s: join failed", __func__));
2156 return FALSE;
2159 #define MANAGED_WAIT_FAILED 0x7fffffff
2161 static gint32
2162 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
2164 if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
2165 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
2166 } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
2167 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
2168 } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
2169 return WAIT_IO_COMPLETION;
2170 } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
2171 return WAIT_TIMEOUT;
2172 } else if (val == MONO_W32HANDLE_WAIT_RET_TOO_MANY_POSTS) {
2173 return WAIT_TOO_MANY_POSTS;
2174 } else if (val == MONO_W32HANDLE_WAIT_RET_NOT_OWNED_BY_CALLER) {
2175 return WAIT_NOT_OWNED_BY_CALLER;
2176 } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
2177 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2178 return MANAGED_WAIT_FAILED;
2179 } else {
2180 g_error ("%s: unknown val value %d", __func__, val);
2184 gint32
2185 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
2187 /* Do this WaitSleepJoin check before creating objects */
2188 if (mono_thread_current_check_pending_interrupt ())
2189 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2191 MonoInternalThread * const thread = mono_thread_internal_current ();
2193 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2195 gint64 start = 0;
2197 if (timeout == -1)
2198 timeout = MONO_INFINITE_WAIT;
2199 if (timeout != MONO_INFINITE_WAIT)
2200 start = mono_msec_ticks ();
2202 guint32 timeoutLeft = timeout;
2204 MonoW32HandleWaitRet ret;
2206 HANDLE_LOOP_PREPARE;
2208 for (;;) {
2210 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2211 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE, error);
2213 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
2214 break;
2216 SETUP_ICALL_FRAME;
2218 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
2220 const gboolean interrupt = mono_thread_execute_interruption (&exc);
2222 if (interrupt)
2223 mono_error_set_exception_handle (error, exc);
2225 CLEAR_ICALL_FRAME;
2227 if (interrupt)
2228 break;
2230 if (timeout != MONO_INFINITE_WAIT) {
2231 gint64 const elapsed = mono_msec_ticks () - start;
2232 if (elapsed >= timeout) {
2233 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
2234 break;
2237 timeoutLeft = timeout - elapsed;
2241 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2243 return map_native_wait_result_to_managed (ret, numhandles);
2246 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2247 gint32
2248 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
2250 MonoW32HandleWaitRet ret;
2251 MonoInternalThread *thread = mono_thread_internal_current ();
2253 if (ms == -1)
2254 ms = MONO_INFINITE_WAIT;
2256 if (mono_thread_current_check_pending_interrupt ())
2257 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2259 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2261 ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
2263 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2265 return map_native_wait_result_to_managed (ret, 1);
2268 #endif
2270 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
2272 return mono_atomic_inc_i32 (location);
2275 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
2277 #if SIZEOF_VOID_P == 4
2278 if (G_UNLIKELY ((size_t)location & 0x7)) {
2279 gint64 ret;
2280 mono_interlocked_lock ();
2281 (*location)++;
2282 ret = *location;
2283 mono_interlocked_unlock ();
2284 return ret;
2286 #endif
2287 return mono_atomic_inc_i64 (location);
2290 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
2292 return mono_atomic_dec_i32(location);
2295 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
2297 #if SIZEOF_VOID_P == 4
2298 if (G_UNLIKELY ((size_t)location & 0x7)) {
2299 gint64 ret;
2300 mono_interlocked_lock ();
2301 (*location)--;
2302 ret = *location;
2303 mono_interlocked_unlock ();
2304 return ret;
2306 #endif
2307 return mono_atomic_dec_i64 (location);
2310 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2312 return mono_atomic_xchg_i32(location, value);
2315 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
2317 MonoObject *res;
2318 res = (MonoObject *) mono_atomic_xchg_ptr((gpointer *) location, value);
2319 mono_gc_wbarrier_generic_nostore_internal (location);
2320 return res;
2323 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2325 return mono_atomic_xchg_ptr(location, value);
2328 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2330 IntFloatUnion val, ret;
2332 val.fval = value;
2333 ret.ival = mono_atomic_xchg_i32((gint32 *) location, val.ival);
2335 return ret.fval;
2338 gint64
2339 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2341 #if SIZEOF_VOID_P == 4
2342 if (G_UNLIKELY ((size_t)location & 0x7)) {
2343 gint64 ret;
2344 mono_interlocked_lock ();
2345 ret = *location;
2346 *location = value;
2347 mono_interlocked_unlock ();
2348 return ret;
2350 #endif
2351 return mono_atomic_xchg_i64 (location, value);
2354 gdouble
2355 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2357 LongDoubleUnion val, ret;
2359 val.fval = value;
2360 ret.ival = (gint64)mono_atomic_xchg_i64((gint64 *) location, val.ival);
2362 return ret.fval;
2365 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2367 return mono_atomic_cas_i32(location, value, comparand);
2370 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2372 gint32 r = mono_atomic_cas_i32(location, value, comparand);
2373 *success = r == comparand;
2374 return r;
2377 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
2379 MonoObject *res;
2380 res = (MonoObject *) mono_atomic_cas_ptr((gpointer *) location, value, comparand);
2381 mono_gc_wbarrier_generic_nostore_internal (location);
2382 return res;
2385 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2387 return mono_atomic_cas_ptr(location, value, comparand);
2390 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2392 IntFloatUnion val, ret, cmp;
2394 val.fval = value;
2395 cmp.fval = comparand;
2396 ret.ival = mono_atomic_cas_i32((gint32 *) location, val.ival, cmp.ival);
2398 return ret.fval;
2401 gdouble
2402 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2404 #if SIZEOF_VOID_P == 8
2405 LongDoubleUnion val, comp, ret;
2407 val.fval = value;
2408 comp.fval = comparand;
2409 ret.ival = (gint64)mono_atomic_cas_ptr((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2411 return ret.fval;
2412 #else
2413 gdouble old;
2415 mono_interlocked_lock ();
2416 old = *location;
2417 if (old == comparand)
2418 *location = value;
2419 mono_interlocked_unlock ();
2421 return old;
2422 #endif
2425 gint64
2426 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2428 #if SIZEOF_VOID_P == 4
2429 if (G_UNLIKELY ((size_t)location & 0x7)) {
2430 gint64 old;
2431 mono_interlocked_lock ();
2432 old = *location;
2433 if (old == comparand)
2434 *location = value;
2435 mono_interlocked_unlock ();
2436 return old;
2438 #endif
2439 return mono_atomic_cas_i64 (location, value, comparand);
2442 MonoObject*
2443 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2445 MonoObject *res;
2446 res = (MonoObject *)mono_atomic_cas_ptr ((volatile gpointer *)location, value, comparand);
2447 mono_gc_wbarrier_generic_nostore_internal (location);
2448 return res;
2451 MonoObject*
2452 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2454 MonoObject *res;
2455 MONO_CHECK_NULL (location, NULL);
2456 res = (MonoObject *)mono_atomic_xchg_ptr ((volatile gpointer *)location, value);
2457 mono_gc_wbarrier_generic_nostore_internal (location);
2458 return res;
2461 gint32
2462 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2464 return mono_atomic_add_i32 (location, value);
2467 gint64
2468 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2470 #if SIZEOF_VOID_P == 4
2471 if (G_UNLIKELY ((size_t)location & 0x7)) {
2472 gint64 ret;
2473 mono_interlocked_lock ();
2474 *location += value;
2475 ret = *location;
2476 mono_interlocked_unlock ();
2477 return ret;
2479 #endif
2480 return mono_atomic_add_i64 (location, value);
2483 gint64
2484 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2486 #if SIZEOF_VOID_P == 4
2487 if (G_UNLIKELY ((size_t)location & 0x7)) {
2488 gint64 ret;
2489 mono_interlocked_lock ();
2490 ret = *location;
2491 mono_interlocked_unlock ();
2492 return ret;
2494 #endif
2495 return mono_atomic_load_i64 (location);
2498 void
2499 ves_icall_System_Threading_Interlocked_MemoryBarrierProcessWide (void)
2501 mono_memory_barrier_process_wide ();
2504 void
2505 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2507 mono_memory_barrier ();
2510 void
2511 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj, guint32 state, MonoError *error)
2513 // InternalThreads are always pinned, so shallowly coop-handleize.
2514 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj), (MonoThreadState)state);
2517 void
2518 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle, guint32 state, MonoError *error)
2520 // InternalThreads are always pinned, so shallowly coop-handleize.
2521 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle), (MonoThreadState)state);
2524 guint32
2525 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle, MonoError *error)
2527 // InternalThreads are always pinned, so shallowly coop-handleize.
2528 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (thread_handle);
2530 guint32 state;
2532 LOCK_THREAD (this_obj);
2534 state = this_obj->state;
2536 UNLOCK_THREAD (this_obj);
2538 return state;
2541 void
2542 ves_icall_System_Threading_Thread_Interrupt_internal (MonoThreadObjectHandle thread_handle, MonoError *error)
2544 // Internal threads are pinned so shallow coop/handle.
2545 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2546 MonoInternalThread * const current = mono_thread_internal_current ();
2548 LOCK_THREAD (thread);
2550 thread->thread_interrupt_requested = TRUE;
2551 gboolean const throw_ = current != thread && (thread->state & ThreadState_WaitSleepJoin);
2553 UNLOCK_THREAD (thread);
2555 if (throw_)
2556 async_abort_internal (thread, FALSE);
2560 * mono_thread_current_check_pending_interrupt:
2561 * Checks if there's a interruption request and set the pending exception if so.
2562 * \returns true if a pending exception was set
2564 gboolean
2565 mono_thread_current_check_pending_interrupt (void)
2567 MonoInternalThread *thread = mono_thread_internal_current ();
2568 gboolean throw_ = FALSE;
2570 LOCK_THREAD (thread);
2572 if (thread->thread_interrupt_requested) {
2573 throw_ = TRUE;
2574 thread->thread_interrupt_requested = FALSE;
2577 UNLOCK_THREAD (thread);
2579 if (throw_) {
2580 ERROR_DECL (error);
2581 mono_error_set_thread_interrupted (error);
2582 mono_error_set_pending_exception (error);
2584 return throw_;
2587 static gboolean
2588 request_thread_abort (MonoInternalThread *thread, MonoObjectHandle *state, gboolean appdomain_unload)
2589 // state is a pointer to a handle in order to be optional,
2590 // and be passed unspecified from functions not using handles.
2591 // When raw pointers is gone, it need not be a pointer,
2592 // though this would still work efficiently.
2594 LOCK_THREAD (thread);
2596 /* With self abort we always throw a new exception */
2597 if (thread == mono_thread_internal_current ())
2598 thread->abort_exc = NULL;
2600 if (thread->state & (ThreadState_AbortRequested | ThreadState_Stopped))
2602 UNLOCK_THREAD (thread);
2603 return FALSE;
2606 if ((thread->state & ThreadState_Unstarted) != 0) {
2607 thread->state |= ThreadState_Aborted;
2608 UNLOCK_THREAD (thread);
2609 return FALSE;
2612 thread->state |= ThreadState_AbortRequested;
2613 if (appdomain_unload)
2614 thread->flags |= MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2615 else
2616 thread->flags &= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2618 mono_gchandle_free_internal (thread->abort_state_handle);
2619 thread->abort_state_handle = 0;
2622 if (state && !MONO_HANDLE_IS_NULL (*state)) {
2623 thread->abort_state_handle = mono_gchandle_from_handle (*state, FALSE);
2624 g_assert (thread->abort_state_handle);
2627 thread->abort_exc = NULL;
2629 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Abort requested for %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), thread, (gsize)thread->tid));
2631 /* During shutdown, we can't wait for other threads */
2632 if (!shutting_down)
2633 /* Make sure the thread is awake */
2634 mono_thread_resume (thread);
2636 UNLOCK_THREAD (thread);
2637 return TRUE;
2640 #ifndef ENABLE_NETCORE
2641 void
2642 ves_icall_System_Threading_Thread_Abort (MonoInternalThreadHandle thread_handle, MonoObjectHandle state, MonoError *error)
2644 // InternalThreads are always pinned, so shallowly coop-handleize.
2645 MonoInternalThread * const thread = mono_internal_thread_handle_ptr (thread_handle);
2646 gboolean is_self = thread == mono_thread_internal_current ();
2648 /* For self aborts we always process the abort */
2649 if (!request_thread_abort (thread, &state, FALSE) && !is_self)
2650 return;
2652 if (is_self) {
2653 self_abort_internal (error);
2654 } else {
2655 async_abort_internal (thread, TRUE);
2658 #endif
2661 * mono_thread_internal_abort:
2662 * Request thread \p thread to be aborted.
2663 * \p thread MUST NOT be the current thread.
2665 void
2666 mono_thread_internal_abort (MonoInternalThread *thread, gboolean appdomain_unload)
2668 g_assert (thread != mono_thread_internal_current ());
2670 if (!request_thread_abort (thread, NULL, appdomain_unload))
2671 return;
2672 async_abort_internal (thread, TRUE);
2675 #ifndef ENABLE_NETCORE
2676 void
2677 ves_icall_System_Threading_Thread_ResetAbort (MonoThreadObjectHandle this_obj, MonoError *error)
2679 MonoInternalThread *thread = mono_thread_internal_current ();
2680 gboolean was_aborting, is_domain_abort;
2682 LOCK_THREAD (thread);
2683 was_aborting = thread->state & ThreadState_AbortRequested;
2684 is_domain_abort = thread->flags & MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2686 if (was_aborting && !is_domain_abort)
2687 thread->state &= ~ThreadState_AbortRequested;
2688 UNLOCK_THREAD (thread);
2690 if (!was_aborting) {
2691 mono_error_set_exception_thread_state (error, "Unable to reset abort because no abort was requested");
2692 return;
2693 } else if (is_domain_abort) {
2694 /* Silently ignore abort resets in unloading appdomains */
2695 return;
2698 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2699 thread->abort_exc = NULL;
2700 mono_gchandle_free_internal (thread->abort_state_handle);
2701 /* This is actually not necessary - the handle
2702 only counts if the exception is set */
2703 thread->abort_state_handle = 0;
2705 #endif
2707 void
2708 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2710 LOCK_THREAD (thread);
2712 thread->state &= ~ThreadState_AbortRequested;
2714 if (thread->abort_exc) {
2715 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2716 thread->abort_exc = NULL;
2717 mono_gchandle_free_internal (thread->abort_state_handle);
2718 /* This is actually not necessary - the handle
2719 only counts if the exception is set */
2720 thread->abort_state_handle = 0;
2723 UNLOCK_THREAD (thread);
2726 #ifndef ENABLE_NETCORE
2727 MonoObjectHandle
2728 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThreadObjectHandle this_obj, MonoError *error)
2730 MonoInternalThread *thread = thread_handle_to_internal_ptr (this_obj);
2732 if (!thread->abort_state_handle)
2733 return NULL_HANDLE; // No state. No error.
2735 // Convert gc handle to coop handle.
2736 MonoObjectHandle state = mono_gchandle_get_target_handle (thread->abort_state_handle);
2737 g_assert (MONO_HANDLE_BOOL (state));
2739 MonoDomain *domain = mono_domain_get ();
2740 if (MONO_HANDLE_DOMAIN (state) == domain)
2741 return state; // No need to cross domain, return state directly.
2743 // Attempt move state cross-domain.
2744 MonoObjectHandle deserialized = mono_object_xdomain_representation (state, domain, error);
2746 // If deserialized is null, there must be an error, and vice versa.
2747 g_assert (is_ok (error) == MONO_HANDLE_BOOL (deserialized));
2749 if (MONO_HANDLE_BOOL (deserialized))
2750 return deserialized; // Cross-domain serialization succeeded. Return it.
2752 // Wrap error in InvalidOperationException.
2753 ERROR_DECL (error_creating_exception);
2754 MonoExceptionHandle invalid_op_exc = mono_exception_new_invalid_operation (
2755 "Thread.ExceptionState cannot access an ExceptionState from a different AppDomain", error_creating_exception);
2756 mono_error_assert_ok (error_creating_exception);
2757 g_assert (!is_ok (error) && 1);
2758 MONO_HANDLE_SET (invalid_op_exc, inner_ex, mono_error_convert_to_exception_handle (error));
2759 error_init_reuse (error);
2760 mono_error_set_exception_handle (error, invalid_op_exc);
2761 g_assert (!is_ok (error) && 2);
2763 // There is state, but we failed to return it.
2764 return NULL_HANDLE;
2766 #endif
2768 static gboolean
2769 mono_thread_suspend (MonoInternalThread *thread)
2771 LOCK_THREAD (thread);
2773 if (thread->state & (ThreadState_Unstarted | ThreadState_Aborted | ThreadState_Stopped))
2775 UNLOCK_THREAD (thread);
2776 return FALSE;
2779 if (thread->state & (ThreadState_Suspended | ThreadState_SuspendRequested | ThreadState_AbortRequested))
2781 UNLOCK_THREAD (thread);
2782 return TRUE;
2785 thread->state |= ThreadState_SuspendRequested;
2786 MONO_ENTER_GC_SAFE;
2787 mono_os_event_reset (thread->suspended);
2788 MONO_EXIT_GC_SAFE;
2790 if (thread == mono_thread_internal_current ()) {
2791 /* calls UNLOCK_THREAD (thread) */
2792 self_suspend_internal ();
2793 } else {
2794 /* calls UNLOCK_THREAD (thread) */
2795 async_suspend_internal (thread, FALSE);
2798 return TRUE;
2801 #ifndef ENABLE_NETCORE
2802 void
2803 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj, MonoError *error)
2805 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj)))
2806 mono_error_set_exception_thread_not_started_or_dead (error);
2809 #endif
2811 /* LOCKING: LOCK_THREAD(thread) must be held */
2812 static gboolean
2813 mono_thread_resume (MonoInternalThread *thread)
2815 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2816 // g_async_safe_printf ("RESUME (1) thread %p\n", thread_get_tid (thread));
2817 thread->state &= ~ThreadState_SuspendRequested;
2818 MONO_ENTER_GC_SAFE;
2819 mono_os_event_set (thread->suspended);
2820 MONO_EXIT_GC_SAFE;
2821 return TRUE;
2824 if ((thread->state & ThreadState_Suspended) == 0 ||
2825 (thread->state & ThreadState_Unstarted) != 0 ||
2826 (thread->state & ThreadState_Aborted) != 0 ||
2827 (thread->state & ThreadState_Stopped) != 0)
2829 // g_async_safe_printf ("RESUME (2) thread %p\n", thread_get_tid (thread));
2830 return FALSE;
2833 // g_async_safe_printf ("RESUME (3) thread %p\n", thread_get_tid (thread));
2835 MONO_ENTER_GC_SAFE;
2836 mono_os_event_set (thread->suspended);
2837 MONO_EXIT_GC_SAFE;
2839 if (!thread->self_suspended) {
2840 UNLOCK_THREAD (thread);
2842 /* Awake the thread */
2843 if (!mono_thread_info_resume (thread_get_tid (thread)))
2844 return FALSE;
2846 LOCK_THREAD (thread);
2849 thread->state &= ~ThreadState_Suspended;
2851 return TRUE;
2854 #ifndef ENABLE_NETCORE
2855 void
2856 ves_icall_System_Threading_Thread_Resume (MonoThreadObjectHandle thread_handle, MonoError *error)
2858 // Internal threads are pinned so shallow coop/handle.
2859 MonoInternalThread * const internal_thread = thread_handle_to_internal_ptr (thread_handle);
2860 gboolean exception = FALSE;
2862 if (!internal_thread) {
2863 exception = TRUE;
2864 } else {
2865 LOCK_THREAD (internal_thread);
2866 if (!mono_thread_resume (internal_thread))
2867 exception = TRUE;
2868 UNLOCK_THREAD (internal_thread);
2871 if (exception)
2872 mono_error_set_exception_thread_not_started_or_dead (error);
2874 #endif
2876 gboolean
2877 mono_threads_is_critical_method (MonoMethod *method)
2879 switch (method->wrapper_type) {
2880 case MONO_WRAPPER_RUNTIME_INVOKE:
2881 case MONO_WRAPPER_XDOMAIN_INVOKE:
2882 case MONO_WRAPPER_XDOMAIN_DISPATCH:
2883 return TRUE;
2885 return FALSE;
2888 static gboolean
2889 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2891 if (managed)
2892 return TRUE;
2894 if (mono_threads_is_critical_method (m)) {
2895 *((gboolean*)data) = TRUE;
2896 return TRUE;
2898 return FALSE;
2901 static gboolean
2902 is_running_protected_wrapper (void)
2904 gboolean found = FALSE;
2905 mono_stack_walk (find_wrapper, &found);
2906 return found;
2910 * mono_thread_stop:
2912 void
2913 mono_thread_stop (MonoThread *thread)
2915 MonoInternalThread *internal = thread->internal_thread;
2917 if (!request_thread_abort (internal, NULL, FALSE))
2918 return;
2920 if (internal == mono_thread_internal_current ()) {
2921 ERROR_DECL (error);
2922 self_abort_internal (error);
2924 This function is part of the embeding API and has no way to return the exception
2925 to be thrown. So what we do is keep the old behavior and raise the exception.
2927 mono_error_raise_exception_deprecated (error); /* OK to throw, see note */
2928 } else {
2929 async_abort_internal (internal, TRUE);
2933 gint8
2934 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2936 gint8 tmp = *(volatile gint8 *)ptr;
2937 mono_memory_barrier ();
2938 return tmp;
2941 gint16
2942 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2944 gint16 tmp = *(volatile gint16 *)ptr;
2945 mono_memory_barrier ();
2946 return tmp;
2949 gint32
2950 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2952 gint32 tmp = *(volatile gint32 *)ptr;
2953 mono_memory_barrier ();
2954 return tmp;
2957 gint64
2958 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2960 gint64 tmp = *(volatile gint64 *)ptr;
2961 mono_memory_barrier ();
2962 return tmp;
2965 void *
2966 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2968 volatile void *tmp = *(volatile void **)ptr;
2969 mono_memory_barrier ();
2970 return (void *) tmp;
2973 void *
2974 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
2976 volatile MonoObject *tmp = *(volatile MonoObject **)ptr;
2977 mono_memory_barrier ();
2978 return (MonoObject *) tmp;
2981 double
2982 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
2984 double tmp = *(volatile double *)ptr;
2985 mono_memory_barrier ();
2986 return tmp;
2989 float
2990 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
2992 float tmp = *(volatile float *)ptr;
2993 mono_memory_barrier ();
2994 return tmp;
2997 gint64
2998 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
3000 #if SIZEOF_VOID_P == 4
3001 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3002 gint64 val;
3003 mono_interlocked_lock ();
3004 val = *(gint64*)ptr;
3005 mono_interlocked_unlock ();
3006 return val;
3008 #endif
3009 return mono_atomic_load_i64 ((volatile gint64 *)ptr);
3012 guint64
3013 ves_icall_System_Threading_Volatile_ReadU8 (void *ptr)
3015 #if SIZEOF_VOID_P == 4
3016 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3017 guint64 val;
3018 mono_interlocked_lock ();
3019 val = *(guint64*)ptr;
3020 mono_interlocked_unlock ();
3021 return val;
3023 #endif
3024 return (guint64)mono_atomic_load_i64 ((volatile gint64 *)ptr);
3027 double
3028 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
3030 LongDoubleUnion u;
3032 #if SIZEOF_VOID_P == 4
3033 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3034 double val;
3035 mono_interlocked_lock ();
3036 val = *(double*)ptr;
3037 mono_interlocked_unlock ();
3038 return val;
3040 #endif
3042 u.ival = mono_atomic_load_i64 ((volatile gint64 *)ptr);
3044 return u.fval;
3047 void
3048 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
3050 mono_memory_barrier ();
3051 *(volatile gint8 *)ptr = value;
3054 void
3055 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
3057 mono_memory_barrier ();
3058 *(volatile gint16 *)ptr = value;
3061 void
3062 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
3064 mono_memory_barrier ();
3065 *(volatile gint32 *)ptr = value;
3068 void
3069 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
3071 mono_memory_barrier ();
3072 *(volatile gint64 *)ptr = value;
3075 void
3076 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
3078 mono_memory_barrier ();
3079 *(volatile void **)ptr = value;
3082 void
3083 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
3085 mono_memory_barrier ();
3086 mono_gc_wbarrier_generic_store_internal (ptr, value);
3089 void
3090 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
3092 mono_memory_barrier ();
3093 *(volatile double *)ptr = value;
3096 void
3097 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
3099 mono_memory_barrier ();
3100 *(volatile float *)ptr = value;
3103 void
3104 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
3106 #if SIZEOF_VOID_P == 4
3107 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3108 mono_interlocked_lock ();
3109 *(gint64*)ptr = value;
3110 mono_interlocked_unlock ();
3111 return;
3113 #endif
3115 mono_atomic_store_i64 ((volatile gint64 *)ptr, value);
3118 void
3119 ves_icall_System_Threading_Volatile_WriteU8 (void *ptr, guint64 value)
3121 #if SIZEOF_VOID_P == 4
3122 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3123 mono_interlocked_lock ();
3124 *(guint64*)ptr = value;
3125 mono_interlocked_unlock ();
3126 return;
3128 #endif
3130 mono_atomic_store_i64 ((volatile gint64 *)ptr, (gint64)value);
3133 void
3134 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
3136 LongDoubleUnion u;
3138 #if SIZEOF_VOID_P == 4
3139 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3140 mono_interlocked_lock ();
3141 *(double*)ptr = value;
3142 mono_interlocked_unlock ();
3143 return;
3145 #endif
3147 u.fval = value;
3149 mono_atomic_store_i64 ((volatile gint64 *)ptr, u.ival);
3152 static void
3153 free_context (void *user_data)
3155 ContextStaticData *data = (ContextStaticData*)user_data;
3157 mono_threads_lock ();
3160 * There is no guarantee that, by the point this reference queue callback
3161 * has been invoked, the GC handle associated with the object will fail to
3162 * resolve as one might expect. So if we don't free and remove the GC
3163 * handle here, free_context_static_data_helper () could end up resolving
3164 * a GC handle to an actually-dead context which would contain a pointer
3165 * to an already-freed static data segment, resulting in a crash when
3166 * accessing it.
3168 g_hash_table_remove (contexts, GUINT_TO_POINTER (data->gc_handle));
3170 mono_threads_unlock ();
3172 mono_gchandle_free_internal (data->gc_handle);
3173 mono_free_static_data (data->static_data);
3174 g_free (data);
3177 void
3178 mono_threads_register_app_context (MonoAppContextHandle ctx, MonoError *error)
3180 error_init (error);
3181 mono_threads_lock ();
3183 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3185 if (!contexts)
3186 contexts = g_hash_table_new (NULL, NULL);
3188 if (!context_queue)
3189 context_queue = mono_gc_reference_queue_new_internal (free_context);
3191 gpointer gch = GUINT_TO_POINTER (mono_gchandle_new_weakref_from_handle (MONO_HANDLE_CAST (MonoObject, ctx)));
3192 g_hash_table_insert (contexts, gch, gch);
3195 * We use this intermediate structure to contain a duplicate pointer to
3196 * the static data because we can't rely on being able to resolve the GC
3197 * handle in the reference queue callback.
3199 ContextStaticData *data = g_new0 (ContextStaticData, 1);
3200 data->gc_handle = GPOINTER_TO_UINT (gch);
3201 MONO_HANDLE_SETVAL (ctx, data, ContextStaticData*, data);
3203 context_adjust_static_data (ctx);
3204 mono_gc_reference_queue_add_handle (context_queue, ctx, data);
3206 mono_threads_unlock ();
3208 MONO_PROFILER_RAISE (context_loaded, (MONO_HANDLE_RAW (ctx)));
3211 void
3212 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx, MonoError *error)
3214 mono_threads_register_app_context (ctx, error);
3217 void
3218 mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error)
3221 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3222 * cleanup in exceptional circumstances, we don't actually do any
3223 * cleanup work here. We instead do this via a reference queue.
3226 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3228 MONO_PROFILER_RAISE (context_unloaded, (ctx));
3231 void
3232 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx, MonoError *error)
3234 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_release_app_context */
3237 void mono_thread_init (MonoThreadStartCB start_cb,
3238 MonoThreadAttachCB attach_cb)
3240 mono_coop_mutex_init_recursive (&threads_mutex);
3242 #if SIZEOF_VOID_P == 4
3243 mono_os_mutex_init (&interlocked_mutex);
3244 #endif
3245 mono_coop_mutex_init_recursive(&joinable_threads_mutex);
3247 mono_os_event_init (&background_change_event, FALSE);
3249 mono_coop_cond_init (&pending_native_thread_join_calls_event);
3250 mono_coop_cond_init (&zero_pending_joinable_thread_event);
3252 mono_init_static_data_info (&thread_static_info);
3253 mono_init_static_data_info (&context_static_info);
3255 mono_thread_start_cb = start_cb;
3256 mono_thread_attach_cb = attach_cb;
3260 static gpointer
3261 thread_attach (MonoThreadInfo *info)
3263 return mono_gc_thread_attach (info);
3266 static void
3267 thread_detach (MonoThreadInfo *info)
3269 MonoInternalThread *internal;
3270 guint32 gchandle;
3272 /* If a delegate is passed to native code and invoked on a thread we dont
3273 * know about, marshal will register it with mono_threads_attach_coop, but
3274 * we have no way of knowing when that thread goes away. SGen has a TSD
3275 * so we assume that if the domain is still registered, we can detach
3276 * the thread */
3278 g_assert (info);
3279 g_assert (mono_thread_info_is_current (info));
3281 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
3282 return;
3284 internal = (MonoInternalThread*) mono_gchandle_get_target_internal (gchandle);
3285 g_assert (internal);
3287 mono_thread_detach_internal (internal);
3290 static void
3291 thread_detach_with_lock (MonoThreadInfo *info)
3293 mono_gc_thread_detach_with_lock (info);
3296 static gboolean
3297 thread_in_critical_region (MonoThreadInfo *info)
3299 return mono_gc_thread_in_critical_region (info);
3302 static gboolean
3303 ip_in_critical_region (MonoDomain *domain, gpointer ip)
3305 MonoJitInfo *ji;
3306 MonoMethod *method;
3309 * We pass false for 'try_aot' so this becomes async safe.
3310 * It won't find aot methods whose jit info is not yet loaded,
3311 * so we preload their jit info in the JIT.
3313 ji = mono_jit_info_table_find_internal (domain, ip, FALSE, FALSE);
3314 if (!ji)
3315 return FALSE;
3317 method = mono_jit_info_get_method (ji);
3318 g_assert (method);
3320 return mono_gc_is_critical_method (method);
3323 static void
3324 thread_flags_changing (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3326 mono_gc_skip_thread_changing (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3329 static void
3330 thread_flags_changed (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3332 mono_gc_skip_thread_changed (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3335 void
3336 mono_thread_callbacks_init (void)
3338 MonoThreadInfoCallbacks cb;
3340 memset (&cb, 0, sizeof(cb));
3341 cb.thread_attach = thread_attach;
3342 cb.thread_detach = thread_detach;
3343 cb.thread_detach_with_lock = thread_detach_with_lock;
3344 cb.ip_in_critical_region = ip_in_critical_region;
3345 cb.thread_in_critical_region = thread_in_critical_region;
3346 cb.thread_flags_changing = thread_flags_changing;
3347 cb.thread_flags_changed = thread_flags_changed;
3348 mono_thread_info_callbacks_init (&cb);
3352 * mono_thread_cleanup:
3354 void
3355 mono_thread_cleanup (void)
3357 /* Wait for pending threads to park on joinable threads list */
3358 /* NOTE, waiting on this should be extremely rare and will only happen */
3359 /* under certain specific conditions. */
3360 gboolean wait_result = threads_wait_pending_joinable_threads (2000);
3361 if (!wait_result)
3362 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3364 mono_threads_join_threads ();
3366 #if !defined(HOST_WIN32)
3367 /* The main thread must abandon any held mutexes (particularly
3368 * important for named mutexes as they are shared across
3369 * processes, see bug 74680.) This will happen when the
3370 * thread exits, but if it's not running in a subthread it
3371 * won't exit in time.
3373 if (!mono_runtime_get_no_exec ())
3374 mono_w32mutex_abandon (mono_thread_internal_current ());
3375 #endif
3377 #if 0
3378 /* This stuff needs more testing, it seems one of these
3379 * critical sections can be locked when mono_thread_cleanup is
3380 * called.
3382 mono_coop_mutex_destroy (&threads_mutex);
3383 mono_os_mutex_destroy (&interlocked_mutex);
3384 mono_os_mutex_destroy (&delayed_free_table_mutex);
3385 mono_os_mutex_destroy (&small_id_mutex);
3386 mono_coop_cond_destroy (&zero_pending_joinable_thread_event);
3387 mono_coop_cond_destroy (&pending_native_thread_join_calls_event);
3388 mono_os_event_destroy (&background_change_event);
3389 #endif
3392 void
3393 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
3395 mono_thread_cleanup_fn = func;
3399 * mono_thread_set_manage_callback:
3401 void
3402 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
3404 thread->internal_thread->manage_callback = func;
3407 G_GNUC_UNUSED
3408 static void print_tids (gpointer key, gpointer value, gpointer user)
3410 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3411 * sizeof(uint) and a cast to uint would overflow
3413 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3414 * print this as a pointer.
3416 g_message ("Waiting for: %p", key);
3419 struct wait_data
3421 MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3422 MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3423 guint32 num;
3426 static void
3427 wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
3429 guint32 i;
3430 MonoThreadInfoWaitRet ret;
3432 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
3434 /* Add the thread state change event, so it wakes
3435 * up if a thread changes to background mode. */
3437 MONO_ENTER_GC_SAFE;
3438 if (check_state_change)
3439 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, &background_change_event, FALSE, timeout, TRUE);
3440 else
3441 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, NULL, TRUE, timeout, TRUE);
3442 MONO_EXIT_GC_SAFE;
3444 if (ret == MONO_THREAD_INFO_WAIT_RET_FAILED) {
3445 /* See the comment in build_wait_tids() */
3446 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
3447 return;
3450 for( i = 0; i < wait->num; i++)
3451 mono_threads_close_thread_handle (wait->handles [i]);
3453 if (ret >= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 && ret < (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + wait->num)) {
3454 MonoInternalThread *internal;
3456 internal = wait->threads [ret - MONO_THREAD_INFO_WAIT_RET_SUCCESS_0];
3458 mono_threads_lock ();
3459 if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
3460 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
3461 mono_threads_unlock ();
3465 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
3467 struct wait_data *wait=(struct wait_data *)user;
3469 if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
3470 MonoInternalThread *thread=(MonoInternalThread *)value;
3472 /* Ignore background threads, we abort them later */
3473 /* Do not lock here since it is not needed and the caller holds threads_lock */
3474 if (thread->state & ThreadState_Background) {
3475 THREAD_DEBUG (g_message ("%s: ignoring background thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3476 return; /* just leave, ignore */
3479 if (mono_gc_is_finalizer_internal_thread (thread)) {
3480 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3481 return;
3484 if (thread == mono_thread_internal_current ()) {
3485 THREAD_DEBUG (g_message ("%s: ignoring current thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3486 return;
3489 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
3490 THREAD_DEBUG (g_message ("%s: ignoring main thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3491 return;
3494 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
3495 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
3496 return;
3499 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
3500 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
3501 wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
3502 wait->threads[wait->num]=thread;
3503 wait->num++;
3505 THREAD_DEBUG (g_message ("%s: adding thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3506 } else {
3507 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3511 } else {
3512 /* Just ignore the rest, we can't do anything with
3513 * them yet
3518 static void
3519 abort_threads (gpointer key, gpointer value, gpointer user)
3521 struct wait_data *wait=(struct wait_data *)user;
3522 MonoNativeThreadId self = mono_native_thread_id_get ();
3523 MonoInternalThread *thread = (MonoInternalThread *)value;
3525 if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
3526 return;
3528 if (mono_native_thread_id_equals (thread_get_tid (thread), self))
3529 return;
3530 if (mono_gc_is_finalizer_internal_thread (thread))
3531 return;
3533 if ((thread->flags & MONO_THREAD_FLAG_DONT_MANAGE))
3534 return;
3536 wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
3537 wait->threads[wait->num] = thread;
3538 wait->num++;
3540 THREAD_DEBUG (g_print ("%s: Aborting id: %" G_GSIZE_FORMAT "\n", __func__, (gsize)thread->tid));
3541 mono_thread_internal_abort (thread, FALSE);
3544 /**
3545 * mono_threads_set_shutting_down:
3547 * Is called by a thread that wants to shut down Mono. If the runtime is already
3548 * shutting down, the calling thread is suspended/stopped, and this function never
3549 * returns.
3551 void
3552 mono_threads_set_shutting_down (void)
3554 MonoInternalThread *current_thread = mono_thread_internal_current ();
3556 mono_threads_lock ();
3558 if (shutting_down) {
3559 mono_threads_unlock ();
3561 /* Make sure we're properly suspended/stopped */
3563 LOCK_THREAD (current_thread);
3565 if (current_thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
3566 UNLOCK_THREAD (current_thread);
3567 mono_thread_execute_interruption_void ();
3568 } else {
3569 UNLOCK_THREAD (current_thread);
3572 /*since we're killing the thread, detach it.*/
3573 mono_thread_detach_internal (current_thread);
3575 /* Wake up other threads potentially waiting for us */
3576 mono_thread_info_exit (0);
3577 } else {
3578 shutting_down = TRUE;
3580 /* Not really a background state change, but this will
3581 * interrupt the main thread if it is waiting for all
3582 * the other threads.
3584 MONO_ENTER_GC_SAFE;
3585 mono_os_event_set (&background_change_event);
3586 MONO_EXIT_GC_SAFE;
3588 mono_threads_unlock ();
3593 * mono_thread_manage:
3595 void
3596 mono_thread_manage (void)
3598 struct wait_data wait_data;
3599 struct wait_data *wait = &wait_data;
3601 memset (wait, 0, sizeof (struct wait_data));
3602 /* join each thread that's still running */
3603 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3605 mono_threads_lock ();
3606 if(threads==NULL) {
3607 THREAD_DEBUG (g_message("%s: No threads", __func__));
3608 mono_threads_unlock ();
3609 return;
3612 mono_threads_unlock ();
3614 do {
3615 mono_threads_lock ();
3616 if (shutting_down) {
3617 /* somebody else is shutting down */
3618 mono_threads_unlock ();
3619 break;
3621 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3622 mono_g_hash_table_foreach (threads, print_tids, NULL));
3624 MONO_ENTER_GC_SAFE;
3625 mono_os_event_reset (&background_change_event);
3626 MONO_EXIT_GC_SAFE;
3627 wait->num=0;
3628 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3629 memset (wait->threads, 0, sizeof (wait->threads));
3630 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3631 mono_threads_unlock ();
3632 if (wait->num > 0)
3633 /* Something to wait for */
3634 wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3635 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3636 } while(wait->num>0);
3638 /* Mono is shutting down, so just wait for the end */
3639 if (!mono_runtime_try_shutdown ()) {
3640 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3641 mono_thread_suspend (mono_thread_internal_current ());
3642 mono_thread_execute_interruption_void ();
3645 #ifndef ENABLE_NETCORE
3647 * Under netcore, we don't abort any threads, just exit.
3648 * This is not a problem since we don't do runtime cleanup either.
3651 * Remove everything but the finalizer thread and self.
3652 * Also abort all the background threads
3653 * */
3654 do {
3655 mono_threads_lock ();
3657 wait->num = 0;
3658 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3659 memset (wait->threads, 0, sizeof (wait->threads));
3660 mono_g_hash_table_foreach (threads, abort_threads, wait);
3662 mono_threads_unlock ();
3664 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3665 if (wait->num > 0) {
3666 /* Something to wait for */
3667 wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3669 } while (wait->num > 0);
3670 #endif
3673 * give the subthreads a chance to really quit (this is mainly needed
3674 * to get correct user and system times from getrusage/wait/time(1)).
3675 * This could be removed if we avoid pthread_detach() and use pthread_join().
3677 mono_thread_info_yield ();
3680 static void
3681 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3683 MonoInternalThread *thread = (MonoInternalThread*)value;
3684 struct wait_data *wait = (struct wait_data*)user_data;
3687 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3688 * limitation.
3689 * This needs no locking.
3691 if ((thread->state & ThreadState_Suspended) != 0 ||
3692 (thread->state & ThreadState_Stopped) != 0)
3693 return;
3695 if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3696 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3697 wait->threads [wait->num] = thread;
3698 wait->num++;
3703 * mono_thread_suspend_all_other_threads:
3705 * Suspend all managed threads except the finalizer thread and this thread. It is
3706 * not possible to resume them later.
3708 void mono_thread_suspend_all_other_threads (void)
3710 struct wait_data wait_data;
3711 struct wait_data *wait = &wait_data;
3712 int i;
3713 MonoNativeThreadId self = mono_native_thread_id_get ();
3714 guint32 eventidx = 0;
3715 gboolean starting, finished;
3717 memset (wait, 0, sizeof (struct wait_data));
3719 * The other threads could be in an arbitrary state at this point, i.e.
3720 * they could be starting up, shutting down etc. This means that there could be
3721 * threads which are not even in the threads hash table yet.
3725 * First we set a barrier which will be checked by all threads before they
3726 * are added to the threads hash table, and they will exit if the flag is set.
3727 * This ensures that no threads could be added to the hash later.
3728 * We will use shutting_down as the barrier for now.
3730 g_assert (shutting_down);
3733 * We make multiple calls to WaitForMultipleObjects since:
3734 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3735 * - some threads could exit without becoming suspended
3737 finished = FALSE;
3738 while (!finished) {
3740 * Make a copy of the hashtable since we can't do anything with
3741 * threads while threads_mutex is held.
3743 wait->num = 0;
3744 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3745 memset (wait->threads, 0, sizeof (wait->threads));
3746 mono_threads_lock ();
3747 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3748 mono_threads_unlock ();
3750 eventidx = 0;
3751 /* Get the suspended events that we'll be waiting for */
3752 for (i = 0; i < wait->num; ++i) {
3753 MonoInternalThread *thread = wait->threads [i];
3755 if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3756 || mono_gc_is_finalizer_internal_thread (thread)
3757 || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3759 mono_threads_close_thread_handle (wait->handles [i]);
3760 wait->threads [i] = NULL;
3761 continue;
3764 LOCK_THREAD (thread);
3766 if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3767 UNLOCK_THREAD (thread);
3768 mono_threads_close_thread_handle (wait->handles [i]);
3769 wait->threads [i] = NULL;
3770 continue;
3773 ++eventidx;
3775 /* Convert abort requests into suspend requests */
3776 if ((thread->state & ThreadState_AbortRequested) != 0)
3777 thread->state &= ~ThreadState_AbortRequested;
3779 thread->state |= ThreadState_SuspendRequested;
3780 MONO_ENTER_GC_SAFE;
3781 mono_os_event_reset (thread->suspended);
3782 MONO_EXIT_GC_SAFE;
3784 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3785 async_suspend_internal (thread, TRUE);
3787 mono_threads_close_thread_handle (wait->handles [i]);
3788 wait->threads [i] = NULL;
3790 if (eventidx <= 0) {
3792 * If there are threads which are starting up, we wait until they
3793 * are suspended when they try to register in the threads hash.
3794 * This is guaranteed to finish, since the threads which can create new
3795 * threads get suspended after a while.
3796 * FIXME: The finalizer thread can still create new threads.
3798 mono_threads_lock ();
3799 if (threads_starting_up)
3800 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3801 else
3802 starting = FALSE;
3803 mono_threads_unlock ();
3804 if (starting)
3805 mono_thread_info_sleep (100, NULL);
3806 else
3807 finished = TRUE;
3812 typedef struct {
3813 MonoInternalThread *thread;
3814 MonoStackFrameInfo *frames;
3815 int nframes, max_frames;
3816 int nthreads, max_threads;
3817 MonoInternalThread **threads;
3818 } ThreadDumpUserData;
3820 static gboolean thread_dump_requested;
3822 /* This needs to be async safe */
3823 static gboolean
3824 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3826 ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3828 if (ud->nframes < ud->max_frames) {
3829 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3830 ud->nframes ++;
3833 return FALSE;
3836 /* This needs to be async safe */
3837 static SuspendThreadResult
3838 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3840 ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3841 MonoInternalThread *thread = user_data->thread;
3843 #if 0
3844 /* This no longer works with remote unwinding */
3845 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3846 mono_thread_internal_describe (thread, text);
3847 g_string_append (text, "\n");
3848 #endif
3850 if (thread == mono_thread_internal_current ())
3851 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3852 else
3853 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3855 return MonoResumeThread;
3858 typedef struct {
3859 int nthreads, max_threads;
3861 guint32 *threads;
3862 } CollectThreadsUserData;
3864 typedef struct {
3865 int nthreads, max_threads;
3866 MonoNativeThreadId *threads;
3867 } CollectThreadIdsUserData;
3869 static void
3870 collect_thread (gpointer key, gpointer value, gpointer user)
3872 CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3873 MonoInternalThread *thread = (MonoInternalThread *)value;
3875 if (ud->nthreads < ud->max_threads)
3876 ud->threads [ud->nthreads ++] = mono_gchandle_new_internal (&thread->obj, TRUE);
3879 static void
3880 collect_thread_id (gpointer key, gpointer value, gpointer user)
3882 CollectThreadIdsUserData *ud = (CollectThreadIdsUserData *)user;
3883 MonoInternalThread *thread = (MonoInternalThread *)value;
3885 if (ud->nthreads < ud->max_threads)
3886 ud->threads [ud->nthreads ++] = thread_get_tid (thread);
3890 * Collect running threads into the THREADS array.
3891 * THREADS should be an array allocated on the stack.
3893 static int
3894 collect_threads (guint32 *thread_handles, int max_threads)
3896 CollectThreadsUserData ud;
3898 mono_memory_barrier ();
3899 if (!threads)
3900 return 0;
3902 memset (&ud, 0, sizeof (ud));
3903 /* This array contains refs, but its on the stack, so its ok */
3904 ud.threads = thread_handles;
3905 ud.max_threads = max_threads;
3907 mono_threads_lock ();
3908 mono_g_hash_table_foreach (threads, collect_thread, &ud);
3909 mono_threads_unlock ();
3911 return ud.nthreads;
3914 static int
3915 collect_thread_ids (MonoNativeThreadId *thread_ids, int max_threads)
3917 CollectThreadIdsUserData ud;
3919 mono_memory_barrier ();
3920 if (!threads)
3921 return 0;
3923 memset (&ud, 0, sizeof (ud));
3924 /* This array contains refs, but its on the stack, so its ok */
3925 ud.threads = thread_ids;
3926 ud.max_threads = max_threads;
3928 mono_threads_lock ();
3929 mono_g_hash_table_foreach (threads, collect_thread_id, &ud);
3930 mono_threads_unlock ();
3932 return ud.nthreads;
3935 static void
3936 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud, FILE* output_file)
3938 GString* text = g_string_new (0);
3939 char *name;
3940 GError *gerror = NULL;
3941 int i;
3943 ud->thread = thread;
3944 ud->nframes = 0;
3946 /* Collect frames for the thread */
3947 if (thread == mono_thread_internal_current ()) {
3948 get_thread_dump (mono_thread_info_current (), ud);
3949 } else {
3950 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
3954 * Do all the non async-safe work outside of get_thread_dump.
3956 if (thread->name) {
3957 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &gerror);
3958 g_assert (!gerror);
3959 g_string_append_printf (text, "\n\"%s\"", name);
3960 g_free (name);
3962 else if (thread->threadpool_thread) {
3963 g_string_append (text, "\n\"<threadpool thread>\"");
3964 } else {
3965 g_string_append (text, "\n\"<unnamed thread>\"");
3968 for (i = 0; i < ud->nframes; ++i) {
3969 MonoStackFrameInfo *frame = &ud->frames [i];
3970 MonoMethod *method = NULL;
3972 if (frame->type == FRAME_TYPE_MANAGED)
3973 method = mono_jit_info_get_method (frame->ji);
3975 if (method) {
3976 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
3977 g_string_append_printf (text, " %s\n", location);
3978 g_free (location);
3979 } else {
3980 g_string_append_printf (text, " at <unknown> <0x%05x>\n", frame->native_offset);
3984 g_fprintf (output_file, "%s", text->str);
3986 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
3987 OutputDebugStringA(text->str);
3988 #endif
3990 g_string_free (text, TRUE);
3991 fflush (output_file);
3994 static void
3995 mono_get_time_of_day (struct timeval *tv) {
3996 #ifdef WIN32
3997 struct _timeb time;
3998 _ftime(&time);
3999 tv->tv_sec = time.time;
4000 tv->tv_usec = time.millitm * 1000;
4001 #else
4002 if (gettimeofday (tv, NULL) == -1) {
4003 g_error ("gettimeofday() failed; errno is %d (%s)", errno, strerror (errno));
4005 #endif
4008 static void
4009 mono_local_time (const struct timeval *tv, struct tm *tm) {
4010 #ifdef HAVE_LOCALTIME_R
4011 localtime_r(&tv->tv_sec, tm);
4012 #else
4013 time_t const tv_sec = tv->tv_sec; // Copy due to Win32/Posix contradiction.
4014 *tm = *localtime (&tv_sec);
4015 #endif
4018 void
4019 mono_threads_perform_thread_dump (void)
4021 FILE* output_file = NULL;
4022 ThreadDumpUserData ud;
4023 guint32 thread_array [128];
4024 int tindex, nthreads;
4026 if (!thread_dump_requested)
4027 return;
4029 if (thread_dump_dir != NULL) {
4030 GString* path = g_string_new (0);
4031 char time_str[80];
4032 struct timeval tv;
4033 long ms;
4034 struct tm tod;
4035 mono_get_time_of_day (&tv);
4036 mono_local_time(&tv, &tod);
4037 strftime(time_str, sizeof(time_str), MONO_STRFTIME_F "_" MONO_STRFTIME_T, &tod);
4038 ms = tv.tv_usec / 1000;
4039 g_string_append_printf (path, "%s/%s.%03ld.tdump", thread_dump_dir, time_str, ms);
4040 output_file = fopen (path->str, "w");
4041 g_string_free (path, TRUE);
4043 if (output_file == NULL) {
4044 g_print ("Full thread dump:\n");
4047 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4048 nthreads = collect_threads (thread_array, 128);
4050 memset (&ud, 0, sizeof (ud));
4051 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4052 ud.max_frames = 256;
4054 for (tindex = 0; tindex < nthreads; ++tindex) {
4055 guint32 handle = thread_array [tindex];
4056 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4057 dump_thread (thread, &ud, output_file != NULL ? output_file : stdout);
4058 mono_gchandle_free_internal (handle);
4061 if (output_file != NULL) {
4062 fclose (output_file);
4064 g_free (ud.frames);
4066 thread_dump_requested = FALSE;
4069 /* Obtain the thread dump of all threads */
4070 static gboolean
4071 mono_threads_get_thread_dump (MonoArray **out_threads, MonoArray **out_stack_frames, MonoError *error)
4074 ThreadDumpUserData ud;
4075 guint32 thread_array [128];
4076 MonoDomain *domain = mono_domain_get ();
4077 MonoDebugSourceLocation *location;
4078 int tindex, nthreads;
4080 error_init (error);
4082 *out_threads = NULL;
4083 *out_stack_frames = NULL;
4085 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4086 nthreads = collect_threads (thread_array, 128);
4088 memset (&ud, 0, sizeof (ud));
4089 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4090 ud.max_frames = 256;
4092 *out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
4093 goto_if_nok (error, leave);
4094 *out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
4095 goto_if_nok (error, leave);
4097 for (tindex = 0; tindex < nthreads; ++tindex) {
4098 guint32 handle = thread_array [tindex];
4099 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4101 MonoArray *thread_frames;
4102 int i;
4104 ud.thread = thread;
4105 ud.nframes = 0;
4107 /* Collect frames for the thread */
4108 if (thread == mono_thread_internal_current ()) {
4109 get_thread_dump (mono_thread_info_current (), &ud);
4110 } else {
4111 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
4114 mono_array_setref_fast (*out_threads, tindex, mono_thread_current_for_thread (thread));
4116 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
4117 goto_if_nok (error, leave);
4118 mono_array_setref_fast (*out_stack_frames, tindex, thread_frames);
4120 for (i = 0; i < ud.nframes; ++i) {
4121 MonoStackFrameInfo *frame = &ud.frames [i];
4122 MonoMethod *method = NULL;
4123 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
4124 goto_if_nok (error, leave);
4126 sf->native_offset = frame->native_offset;
4128 if (frame->type == FRAME_TYPE_MANAGED)
4129 method = mono_jit_info_get_method (frame->ji);
4131 if (method) {
4132 sf->method_address = (gsize) frame->ji->code_start;
4134 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
4135 goto_if_nok (error, leave);
4136 MONO_OBJECT_SETREF_INTERNAL (sf, method, rm);
4138 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
4139 if (location) {
4140 sf->il_offset = location->il_offset;
4142 if (location->source_file) {
4143 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
4144 goto_if_nok (error, leave);
4145 MONO_OBJECT_SETREF_INTERNAL (sf, filename, filename);
4146 sf->line = location->row;
4147 sf->column = location->column;
4149 mono_debug_free_source_location (location);
4150 } else {
4151 sf->il_offset = -1;
4154 mono_array_setref_internal (thread_frames, i, sf);
4157 mono_gchandle_free_internal (handle);
4160 leave:
4161 g_free (ud.frames);
4162 return is_ok (error);
4166 * mono_threads_request_thread_dump:
4168 * Ask all threads except the current to print their stacktrace to stdout.
4170 void
4171 mono_threads_request_thread_dump (void)
4173 /*The new thread dump code runs out of the finalizer thread. */
4174 thread_dump_requested = TRUE;
4175 mono_gc_finalize_notify ();
4178 struct ref_stack {
4179 gpointer *refs;
4180 gint allocated; /* +1 so that refs [allocated] == NULL */
4181 gint bottom;
4184 typedef struct ref_stack RefStack;
4186 static RefStack *
4187 ref_stack_new (gint initial_size)
4189 RefStack *rs;
4191 initial_size = MAX (initial_size, 16) + 1;
4192 rs = g_new0 (RefStack, 1);
4193 rs->refs = g_new0 (gpointer, initial_size);
4194 rs->allocated = initial_size;
4195 return rs;
4198 static void
4199 ref_stack_destroy (gpointer ptr)
4201 RefStack *rs = (RefStack *)ptr;
4203 if (rs != NULL) {
4204 g_free (rs->refs);
4205 g_free (rs);
4209 static void
4210 ref_stack_push (RefStack *rs, gpointer ptr)
4212 g_assert (rs != NULL);
4214 if (rs->bottom >= rs->allocated) {
4215 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
4216 rs->allocated <<= 1;
4217 rs->refs [rs->allocated] = NULL;
4219 rs->refs [rs->bottom++] = ptr;
4222 static void
4223 ref_stack_pop (RefStack *rs)
4225 if (rs == NULL || rs->bottom == 0)
4226 return;
4228 rs->bottom--;
4229 rs->refs [rs->bottom] = NULL;
4232 static gboolean
4233 ref_stack_find (RefStack *rs, gpointer ptr)
4235 gpointer *refs;
4237 if (rs == NULL)
4238 return FALSE;
4240 for (refs = rs->refs; refs && *refs; refs++) {
4241 if (*refs == ptr)
4242 return TRUE;
4244 return FALSE;
4248 * mono_thread_push_appdomain_ref:
4250 * Register that the current thread may have references to objects in domain
4251 * @domain on its stack. Each call to this function should be paired with a
4252 * call to pop_appdomain_ref.
4254 void
4255 mono_thread_push_appdomain_ref (MonoDomain *domain)
4257 MonoInternalThread *thread = mono_thread_internal_current ();
4259 if (thread) {
4260 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4261 SPIN_LOCK (thread->lock_thread_id);
4262 if (thread->appdomain_refs == NULL)
4263 thread->appdomain_refs = ref_stack_new (16);
4264 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
4265 SPIN_UNLOCK (thread->lock_thread_id);
4269 void
4270 mono_thread_pop_appdomain_ref (void)
4272 MonoInternalThread *thread = mono_thread_internal_current ();
4274 if (thread) {
4275 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4276 SPIN_LOCK (thread->lock_thread_id);
4277 ref_stack_pop ((RefStack *)thread->appdomain_refs);
4278 SPIN_UNLOCK (thread->lock_thread_id);
4282 gboolean
4283 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
4285 gboolean res;
4286 SPIN_LOCK (thread->lock_thread_id);
4287 res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
4288 SPIN_UNLOCK (thread->lock_thread_id);
4289 return res;
4292 gboolean
4293 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
4295 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
4298 typedef struct abort_appdomain_data {
4299 struct wait_data wait;
4300 MonoDomain *domain;
4301 } abort_appdomain_data;
4303 static void
4304 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
4306 MonoInternalThread *thread = (MonoInternalThread*)value;
4307 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
4308 MonoDomain *domain = data->domain;
4310 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
4311 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4313 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
4314 data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
4315 data->wait.threads [data->wait.num] = thread;
4316 data->wait.num++;
4317 } else {
4318 /* Just ignore the rest, we can't do anything with
4319 * them yet
4326 * mono_threads_abort_appdomain_threads:
4328 * Abort threads which has references to the given appdomain.
4330 gboolean
4331 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
4333 abort_appdomain_data user_data;
4334 gint64 start_time;
4335 int orig_timeout = timeout;
4336 int i;
4338 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
4340 start_time = mono_msec_ticks ();
4341 do {
4342 mono_threads_lock ();
4344 user_data.domain = domain;
4345 user_data.wait.num = 0;
4346 /* This shouldn't take any locks */
4347 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
4348 mono_threads_unlock ();
4350 if (user_data.wait.num > 0) {
4351 /* Abort the threads outside the threads lock */
4352 for (i = 0; i < user_data.wait.num; ++i)
4353 mono_thread_internal_abort (user_data.wait.threads [i], TRUE);
4356 * We should wait for the threads either to abort, or to leave the
4357 * domain. We can't do the latter, so we wait with a timeout.
4359 wait_for_tids (&user_data.wait, 100, FALSE);
4362 /* Update remaining time */
4363 timeout -= mono_msec_ticks () - start_time;
4364 start_time = mono_msec_ticks ();
4366 if (orig_timeout != -1 && timeout < 0)
4367 return FALSE;
4369 while (user_data.wait.num > 0);
4371 THREAD_DEBUG (g_message ("%s: abort done", __func__));
4373 return TRUE;
4376 /* This is a JIT icall. This icall is called from a finally block when
4377 * mono_install_handler_block_guard called by another thread has flipped the
4378 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4379 * the finally is in an abort protected block, we must defer the abort
4380 * exception until we leave the abort protected block. Otherwise we proceed
4381 * with a synchronous self-abort.
4383 void
4384 ves_icall_thread_finish_async_abort (void)
4386 /* We were called from the handler block and are about to
4387 * leave it. (If we end up postponing the abort because we're
4388 * in an abort protected block, the unwinder won't run and
4389 * won't clear the handler block itself which will confuse the
4390 * unwinder if we're in a try {} catch {} and we throw again.
4391 * ie, this:
4392 * static Constructor () {
4393 * try {
4394 * try {
4395 * } finally {
4396 * icall (); // Thread.Abort landed here,
4397 * // and caused the handler block to be installed
4398 * if (exvar)
4399 * ves_icall_thread_finish_async_abort (); // we're here
4401 * throw E ();
4402 * } catch (E) {
4403 * // unwinder will get confused here and synthesize a self abort
4407 * More interestingly, this doesn't only happen with icalls - a JIT
4408 * trampoline is native code that will cause a handler to be installed.
4409 * So the above situation can happen with any code in a "finally"
4410 * clause.
4412 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4413 /* Just set the async interruption requested bit. Rely on the icall
4414 * wrapper of this icall to process the thread interruption, respecting
4415 * any abort protection blocks in our call stack.
4417 mono_thread_set_self_interruption_respect_abort_prot ();
4421 * mono_thread_get_undeniable_exception:
4423 * Return an exception which needs to be raised when leaving a catch clause.
4424 * This is used for undeniable exception propagation.
4426 MonoException*
4427 mono_thread_get_undeniable_exception (void)
4429 MonoInternalThread *thread = mono_thread_internal_current ();
4431 if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
4432 return NULL;
4434 // We don't want to have our exception effect calls made by
4435 // the catching block
4437 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4438 return NULL;
4441 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4442 * exception if the thread no longer references a dying appdomain.
4444 thread->abort_exc->trace_ips = NULL;
4445 thread->abort_exc->stack_trace = NULL;
4446 return thread->abort_exc;
4449 #if MONO_SMALL_CONFIG
4450 #define NUM_STATIC_DATA_IDX 4
4451 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4452 64, 256, 1024, 4096
4454 #else
4455 #define NUM_STATIC_DATA_IDX 8
4456 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4457 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4459 #endif
4461 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
4462 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
4464 static void
4465 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
4467 gpointer *static_data = (gpointer *)addr;
4469 for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4470 void **ptr = (void **)static_data [i];
4472 if (!ptr)
4473 continue;
4475 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4476 void **p = ptr + idx;
4478 if (*p)
4479 mark_func ((MonoObject**)p, gc_data);
4484 static void
4485 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4487 mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4490 static void
4491 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4493 mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4497 * mono_alloc_static_data
4499 * Allocate memory blocks for storing threads or context static data
4501 static void
4502 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal)
4504 guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4505 int i;
4507 gpointer* static_data = *static_data_ptr;
4508 if (!static_data) {
4509 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4510 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4512 if (mono_gc_user_markers_supported ()) {
4513 if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4514 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4516 if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4517 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4520 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4521 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4522 alloc_key,
4523 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4524 *static_data_ptr = static_data;
4525 static_data [0] = static_data;
4528 for (i = 1; i <= idx; ++i) {
4529 if (static_data [i])
4530 continue;
4532 if (mono_gc_user_markers_supported ())
4533 static_data [i] = g_malloc0 (static_data_size [i]);
4534 else
4535 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4536 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4537 alloc_key,
4538 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4542 static void
4543 mono_free_static_data (gpointer* static_data)
4545 int i;
4546 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4547 gpointer p = static_data [i];
4548 if (!p)
4549 continue;
4551 * At this point, the static data pointer array is still registered with the
4552 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4553 * data. Freeing the individual arrays without first nulling their slots
4554 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4555 * such an already freed array. See bug #13813.
4557 static_data [i] = NULL;
4558 mono_memory_write_barrier ();
4559 if (mono_gc_user_markers_supported ())
4560 g_free (p);
4561 else
4562 mono_gc_free_fixed (p);
4564 mono_gc_free_fixed (static_data);
4568 * mono_init_static_data_info
4570 * Initializes static data counters
4572 static void mono_init_static_data_info (StaticDataInfo *static_data)
4574 static_data->idx = 0;
4575 static_data->offset = 0;
4576 static_data->freelist = NULL;
4580 * mono_alloc_static_data_slot
4582 * Generates an offset for static data. static_data contains the counters
4583 * used to generate it.
4585 static guint32
4586 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4588 if (!static_data->idx && !static_data->offset) {
4590 * we use the first chunk of the first allocation also as
4591 * an array for the rest of the data
4593 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4595 static_data->offset += align - 1;
4596 static_data->offset &= ~(align - 1);
4597 if (static_data->offset + size >= static_data_size [static_data->idx]) {
4598 static_data->idx ++;
4599 g_assert (size <= static_data_size [static_data->idx]);
4600 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4601 static_data->offset = 0;
4603 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4604 static_data->offset += size;
4605 return offset;
4609 * LOCKING: requires that threads_mutex is held
4611 static void
4612 context_adjust_static_data (MonoAppContextHandle ctx_handle)
4614 MonoAppContext *ctx = MONO_HANDLE_RAW (ctx_handle);
4615 if (context_static_info.offset || context_static_info.idx > 0) {
4616 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4617 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4618 ctx->data->static_data = ctx->static_data;
4623 * LOCKING: requires that threads_mutex is held
4625 static void
4626 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4628 MonoInternalThread *thread = (MonoInternalThread *)value;
4629 guint32 offset = GPOINTER_TO_UINT (user);
4631 mono_alloc_static_data (&(thread->static_data), offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid), TRUE);
4635 * LOCKING: requires that threads_mutex is held
4637 static void
4638 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4640 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4642 if (!ctx)
4643 return;
4645 guint32 offset = GPOINTER_TO_UINT (user);
4646 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4647 ctx->data->static_data = ctx->static_data;
4650 static StaticDataFreeList*
4651 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
4653 StaticDataFreeList* prev = NULL;
4654 StaticDataFreeList* tmp = static_data->freelist;
4655 while (tmp) {
4656 if (tmp->size == size) {
4657 if (prev)
4658 prev->next = tmp->next;
4659 else
4660 static_data->freelist = tmp->next;
4661 return tmp;
4663 prev = tmp;
4664 tmp = tmp->next;
4666 return NULL;
4669 #if SIZEOF_VOID_P == 4
4670 #define ONE_P 1
4671 #else
4672 #define ONE_P 1ll
4673 #endif
4675 static void
4676 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4678 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4679 if (!sets [idx])
4680 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4681 MonoBitSet *rb = sets [idx];
4682 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4683 offset /= sizeof (uintptr_t);
4684 /* offset is now the bitmap offset */
4685 for (int i = 0; i < numbits; ++i) {
4686 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4687 mono_bitset_set_fast (rb, offset + i);
4691 static void
4692 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4694 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4695 MonoBitSet *rb = sets [idx];
4696 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4697 offset /= sizeof (uintptr_t);
4698 /* offset is now the bitmap offset */
4699 for (int i = 0; i < size / sizeof (uintptr_t); i++)
4700 mono_bitset_clear_fast (rb, offset + i);
4703 guint32
4704 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4706 g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4708 StaticDataInfo *info;
4709 MonoBitSet **sets;
4711 if (static_type == SPECIAL_STATIC_THREAD) {
4712 info = &thread_static_info;
4713 sets = thread_reference_bitmaps;
4714 } else {
4715 info = &context_static_info;
4716 sets = context_reference_bitmaps;
4719 mono_threads_lock ();
4721 StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4722 guint32 offset;
4724 if (item) {
4725 offset = item->offset;
4726 g_free (item);
4727 } else {
4728 offset = mono_alloc_static_data_slot (info, size, align);
4731 update_reference_bitmap (sets, offset, bitmap, numbits);
4733 if (static_type == SPECIAL_STATIC_THREAD) {
4734 /* This can be called during startup */
4735 if (threads != NULL)
4736 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4737 } else {
4738 if (contexts != NULL)
4739 g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4741 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4744 mono_threads_unlock ();
4746 return offset;
4749 gpointer
4750 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4752 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4754 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4755 return get_thread_static_data (thread, offset);
4756 } else {
4757 return get_context_static_data (thread->current_appcontext, offset);
4761 gpointer
4762 mono_get_special_static_data (guint32 offset)
4764 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4767 typedef struct {
4768 guint32 offset;
4769 guint32 size;
4770 } OffsetSize;
4773 * LOCKING: requires that threads_mutex is held
4775 static void
4776 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4778 MonoInternalThread *thread = (MonoInternalThread *)value;
4779 OffsetSize *data = (OffsetSize *)user;
4780 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4781 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4782 char *ptr;
4784 if (!thread->static_data || !thread->static_data [idx])
4785 return;
4786 ptr = ((char*) thread->static_data [idx]) + off;
4787 mono_gc_bzero_atomic (ptr, data->size);
4791 * LOCKING: requires that threads_mutex is held
4793 static void
4794 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4796 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4798 if (!ctx)
4799 return;
4801 OffsetSize *data = (OffsetSize *)user;
4802 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4803 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4804 char *ptr;
4806 if (!ctx->static_data || !ctx->static_data [idx])
4807 return;
4809 ptr = ((char*) ctx->static_data [idx]) + off;
4810 mono_gc_bzero_atomic (ptr, data->size);
4813 static void
4814 do_free_special_slot (guint32 offset, guint32 size)
4816 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4817 MonoBitSet **sets;
4818 StaticDataInfo *info;
4820 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4821 info = &thread_static_info;
4822 sets = thread_reference_bitmaps;
4823 } else {
4824 info = &context_static_info;
4825 sets = context_reference_bitmaps;
4828 guint32 data_offset = offset;
4829 ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4830 OffsetSize data = { data_offset, size };
4832 clear_reference_bitmap (sets, data.offset, data.size);
4834 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4835 if (threads != NULL)
4836 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4837 } else {
4838 if (contexts != NULL)
4839 g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4842 if (!mono_runtime_is_shutting_down ()) {
4843 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4845 item->offset = offset;
4846 item->size = size;
4848 item->next = info->freelist;
4849 info->freelist = item;
4853 static void
4854 do_free_special (gpointer key, gpointer value, gpointer data)
4856 MonoClassField *field = (MonoClassField *)key;
4857 guint32 offset = GPOINTER_TO_UINT (value);
4858 gint32 align;
4859 guint32 size;
4860 size = mono_type_size (field->type, &align);
4861 do_free_special_slot (offset, size);
4864 void
4865 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4867 mono_threads_lock ();
4869 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4871 mono_threads_unlock ();
4874 #ifdef HOST_WIN32
4875 static void
4876 flush_thread_interrupt_queue (void)
4878 /* Consume pending APC calls for current thread.*/
4879 /* Since this function get's called from interrupt handler it must use a direct */
4880 /* Win32 API call and can't go through mono_coop_win32_wait_for_single_object_ex */
4881 /* or it will detect a pending interrupt and not entering the wait call needed */
4882 /* to consume pending APC's.*/
4883 MONO_ENTER_GC_SAFE;
4884 WaitForSingleObjectEx (GetCurrentThread (), 0, TRUE);
4885 MONO_EXIT_GC_SAFE;
4887 #else
4888 static void
4889 flush_thread_interrupt_queue (void)
4892 #endif
4895 * mono_thread_execute_interruption
4897 * Performs the operation that the requested thread state requires (abort,
4898 * suspend or stop)
4900 static gboolean
4901 mono_thread_execute_interruption (MonoExceptionHandle *pexc)
4903 gboolean fexc = FALSE;
4905 // Optimize away frame if caller supplied one.
4906 if (!pexc) {
4907 HANDLE_FUNCTION_ENTER ();
4908 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4909 fexc = mono_thread_execute_interruption (&exc);
4910 HANDLE_FUNCTION_RETURN_VAL (fexc);
4913 MONO_REQ_GC_UNSAFE_MODE;
4915 MonoInternalThreadHandle thread = mono_thread_internal_current_handle ();
4916 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4918 lock_thread_handle (thread);
4919 gboolean unlock = TRUE;
4921 /* MonoThread::interruption_requested can only be changed with atomics */
4922 if (!mono_thread_clear_interruption_requested_handle (thread))
4923 goto exit;
4925 MonoThreadObjectHandle sys_thread;
4926 sys_thread = mono_thread_current_handle ();
4928 flush_thread_interrupt_queue ();
4930 /* Clear the interrupted flag of the thread so it can wait again */
4931 mono_thread_info_clear_self_interrupt ();
4933 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4934 MONO_HANDLE_GET (exc, sys_thread, pending_exception);
4935 if (!MONO_HANDLE_IS_NULL (exc)) {
4936 // sys_thread->pending_exception = NULL;
4937 MONO_HANDLE_SETRAW (sys_thread, pending_exception, NULL);
4938 fexc = TRUE;
4939 goto exit;
4940 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_AbortRequested) {
4941 // Does the thread already have an abort exception?
4942 // If not, create a new one and set it on demand.
4943 // exc = thread->abort_exc;
4944 MONO_HANDLE_GET (exc, thread, abort_exc);
4945 if (MONO_HANDLE_IS_NULL (exc)) {
4946 ERROR_DECL (error);
4947 exc = mono_exception_new_thread_abort (error);
4948 mono_error_assert_ok (error); // FIXME
4949 // thread->abort_exc = exc;
4950 MONO_HANDLE_SET (thread, abort_exc, exc);
4952 fexc = TRUE;
4953 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_SuspendRequested) {
4954 /* calls UNLOCK_THREAD (thread) */
4955 self_suspend_internal ();
4956 unlock = FALSE;
4957 } else if (MONO_HANDLE_GETVAL (thread, thread_interrupt_requested)) {
4958 // thread->thread_interrupt_requested = FALSE
4959 MONO_HANDLE_SETVAL (thread, thread_interrupt_requested, MonoBoolean, FALSE);
4960 unlock_thread_handle (thread);
4961 unlock = FALSE;
4962 ERROR_DECL (error);
4963 exc = mono_exception_new_thread_interrupted (error);
4964 mono_error_assert_ok (error); // FIXME
4965 fexc = TRUE;
4967 exit:
4968 if (unlock)
4969 unlock_thread_handle (thread);
4971 if (fexc)
4972 MONO_HANDLE_ASSIGN (*pexc, exc);
4974 return fexc;
4977 static void
4978 mono_thread_execute_interruption_void (void)
4980 (void)mono_thread_execute_interruption (NULL);
4983 static MonoException*
4984 mono_thread_execute_interruption_ptr (void)
4986 HANDLE_FUNCTION_ENTER ();
4987 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4988 MonoException * const exc_raw = mono_thread_execute_interruption (&exc) ? MONO_HANDLE_RAW (exc) : NULL;
4989 HANDLE_FUNCTION_RETURN_VAL (exc_raw);
4993 * mono_thread_request_interruption_internal
4995 * A signal handler can call this method to request the interruption of a
4996 * thread. The result of the interruption will depend on the current state of
4997 * the thread. If the result is an exception that needs to be thrown, it is
4998 * provided as return value.
5000 static gboolean
5001 mono_thread_request_interruption_internal (gboolean running_managed, MonoExceptionHandle *pexc)
5003 MonoInternalThread *thread = mono_thread_internal_current ();
5005 /* The thread may already be stopping */
5006 if (thread == NULL)
5007 return FALSE;
5009 if (!mono_thread_set_interruption_requested (thread))
5010 return FALSE;
5012 if (!running_managed || is_running_protected_wrapper ()) {
5013 /* Can't stop while in unmanaged code. Increase the global interruption
5014 request count. When exiting the unmanaged method the count will be
5015 checked and the thread will be interrupted. */
5017 /* this will awake the thread if it is in WaitForSingleObject
5018 or similar */
5019 #ifdef HOST_WIN32
5020 mono_win32_interrupt_wait (thread->thread_info, thread->native_handle, (DWORD)thread->tid);
5021 #else
5022 mono_thread_info_self_interrupt ();
5023 #endif
5024 return FALSE;
5026 return mono_thread_execute_interruption (pexc);
5029 static void
5030 mono_thread_request_interruption_native (void)
5032 (void)mono_thread_request_interruption_internal (FALSE, NULL);
5035 static gboolean
5036 mono_thread_request_interruption_managed (MonoExceptionHandle *exc)
5038 return mono_thread_request_interruption_internal (TRUE, exc);
5041 /*This function should be called by a thread after it has exited all of
5042 * its handle blocks at interruption time.*/
5043 void
5044 mono_thread_resume_interruption (gboolean exec)
5046 MonoInternalThread *thread = mono_thread_internal_current ();
5047 gboolean still_aborting;
5049 /* The thread may already be stopping */
5050 if (thread == NULL)
5051 return;
5053 LOCK_THREAD (thread);
5054 still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
5055 UNLOCK_THREAD (thread);
5057 /*This can happen if the protected block called Thread::ResetAbort*/
5058 if (!still_aborting)
5059 return;
5061 if (!mono_thread_set_interruption_requested (thread))
5062 return;
5064 mono_thread_info_self_interrupt ();
5066 if (exec) // Ignore the exception here, it will be raised later.
5067 mono_thread_execute_interruption_void ();
5070 gboolean
5071 mono_thread_interruption_requested (void)
5073 if (thread_interruption_requested) {
5074 MonoInternalThread *thread = mono_thread_internal_current ();
5075 /* The thread may already be stopping */
5076 if (thread != NULL)
5077 return mono_thread_get_interruption_requested (thread);
5079 return FALSE;
5082 static MonoException*
5083 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
5085 MonoInternalThread *thread = mono_thread_internal_current ();
5087 /* The thread may already be stopping */
5088 if (!thread)
5089 return NULL;
5090 if (!mono_thread_get_interruption_requested (thread))
5091 return NULL;
5092 if (!bypass_abort_protection && !mono_thread_current ()->pending_exception && is_running_protected_wrapper ())
5093 return NULL;
5095 return mono_thread_execute_interruption_ptr ();
5099 * Performs the interruption of the current thread, if one has been requested,
5100 * and the thread is not running a protected wrapper.
5101 * Return the exception which needs to be thrown, if any.
5103 MonoException*
5104 mono_thread_interruption_checkpoint (void)
5106 return mono_thread_interruption_checkpoint_request (FALSE);
5109 gboolean
5110 mono_thread_interruption_checkpoint_bool (void)
5112 return mono_thread_interruption_checkpoint () != NULL;
5115 void
5116 mono_thread_interruption_checkpoint_void (void)
5118 mono_thread_interruption_checkpoint ();
5122 * Performs the interruption of the current thread, if one has been requested.
5123 * Return the exception which needs to be thrown, if any.
5125 MonoException*
5126 mono_thread_force_interruption_checkpoint_noraise (void)
5128 return mono_thread_interruption_checkpoint_request (TRUE);
5132 * mono_set_pending_exception:
5134 * Set the pending exception of the current thread to EXC.
5135 * The exception will be thrown when execution returns to managed code.
5137 void
5138 mono_set_pending_exception (MonoException *exc)
5140 MonoThread *thread = mono_thread_current ();
5142 /* The thread may already be stopping */
5143 if (thread == NULL)
5144 return;
5146 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5148 mono_thread_request_interruption_native ();
5152 * mono_runtime_set_pending_exception:
5154 * Set the pending exception of the current thread to \p exc.
5155 * The exception will be thrown when execution returns to managed code.
5156 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5157 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5158 * in which case the behavior will be undefined).
5159 * Return whether the pending exception was set or not.
5160 * It will not be set if:
5161 * * The thread or runtime is stopping or shutting down
5162 * * There already is a pending exception (and \p overwrite is false)
5164 mono_bool
5165 mono_runtime_set_pending_exception (MonoException *exc, mono_bool overwrite)
5167 MonoThread *thread = mono_thread_current ();
5169 /* The thread may already be stopping */
5170 if (thread == NULL)
5171 return FALSE;
5173 /* Don't overwrite any existing pending exceptions unless asked to */
5174 if (!overwrite && thread->pending_exception)
5175 return FALSE;
5177 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5179 mono_thread_request_interruption_native ();
5181 return TRUE;
5186 * mono_set_pending_exception_handle:
5188 * Set the pending exception of the current thread to EXC.
5189 * The exception will be thrown when execution returns to managed code.
5191 MONO_COLD void
5192 mono_set_pending_exception_handle (MonoExceptionHandle exc)
5194 MonoThread *thread = mono_thread_current ();
5196 /* The thread may already be stopping */
5197 if (thread == NULL)
5198 return;
5200 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, MONO_HANDLE_RAW (exc));
5202 mono_thread_request_interruption_native ();
5206 * mono_thread_interruption_request_flag:
5208 * Returns the address of a flag that will be non-zero if an interruption has
5209 * been requested for a thread. The thread to interrupt may not be the current
5210 * thread, so an additional call to mono_thread_interruption_requested() or
5211 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
5212 * zero.
5214 gint32*
5215 mono_thread_interruption_request_flag (void)
5217 return &thread_interruption_requested;
5220 void
5221 mono_thread_init_apartment_state (void)
5223 #ifdef HOST_WIN32
5224 MonoInternalThread* thread = mono_thread_internal_current ();
5226 /* Positive return value indicates success, either
5227 * S_OK if this is first CoInitialize call, or
5228 * S_FALSE if CoInitialize already called, but with same
5229 * threading model. A negative value indicates failure,
5230 * probably due to trying to change the threading model.
5232 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
5233 ? COINIT_APARTMENTTHREADED
5234 : COINIT_MULTITHREADED) < 0) {
5235 thread->apartment_state = ThreadApartmentState_Unknown;
5237 #endif
5240 void
5241 mono_thread_cleanup_apartment_state (void)
5243 #ifdef HOST_WIN32
5244 MonoInternalThread* thread = mono_thread_internal_current ();
5246 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
5247 CoUninitialize ();
5249 #endif
5252 static void
5253 mono_thread_notify_change_state (MonoThreadState old_state, MonoThreadState new_state)
5255 MonoThreadState diff = old_state ^ new_state;
5256 if (diff & ThreadState_Background) {
5257 /* If the thread changes the background mode, the main thread has to
5258 * be notified, since it has to rebuild the list of threads to
5259 * wait for.
5261 MONO_ENTER_GC_SAFE;
5262 mono_os_event_set (&background_change_event);
5263 MONO_EXIT_GC_SAFE;
5267 void
5268 mono_thread_clear_and_set_state (MonoInternalThread *thread, MonoThreadState clear, MonoThreadState set)
5270 LOCK_THREAD (thread);
5272 MonoThreadState const old_state = (MonoThreadState)thread->state;
5273 MonoThreadState const new_state = (old_state & ~clear) | set;
5274 thread->state = new_state;
5276 UNLOCK_THREAD (thread);
5278 mono_thread_notify_change_state (old_state, new_state);
5281 void
5282 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
5284 mono_thread_clear_and_set_state (thread, (MonoThreadState)0, state);
5288 * mono_thread_test_and_set_state:
5289 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5290 * \returns TRUE if \p set was OR'd in.
5292 gboolean
5293 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
5295 LOCK_THREAD (thread);
5297 MonoThreadState const old_state = (MonoThreadState)thread->state;
5299 if ((old_state & test) != 0) {
5300 UNLOCK_THREAD (thread);
5301 return FALSE;
5304 MonoThreadState const new_state = old_state | set;
5305 thread->state = new_state;
5307 UNLOCK_THREAD (thread);
5309 mono_thread_notify_change_state (old_state, new_state);
5311 return TRUE;
5314 void
5315 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
5317 mono_thread_clear_and_set_state (thread, state, (MonoThreadState)0);
5320 gboolean
5321 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
5323 LOCK_THREAD (thread);
5325 gboolean const ret = ((thread->state & test) != 0);
5327 UNLOCK_THREAD (thread);
5329 return ret;
5332 static void
5333 self_interrupt_thread (void *_unused)
5335 MonoException *exc;
5336 MonoThreadInfo *info;
5337 MonoContext ctx;
5339 exc = mono_thread_execute_interruption_ptr ();
5340 if (!exc) {
5341 if (mono_threads_are_safepoints_enabled ()) {
5342 /* We can return from an async call in coop, as
5343 * it's simply called when exiting the safepoint */
5344 /* If we're using hybrid suspend, we only self
5345 * interrupt if we were running, hence using
5346 * safepoints */
5347 return;
5350 g_error ("%s: we can't resume from an async call", __func__);
5353 info = mono_thread_info_current ();
5355 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5356 ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
5358 mono_raise_exception_with_context (exc, &ctx);
5361 static gboolean
5362 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
5364 if (!ji)
5365 return FALSE;
5366 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
5369 static gboolean
5370 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
5372 MonoJitInfo **dest = (MonoJitInfo **)data;
5373 *dest = frame->ji;
5374 return TRUE;
5377 static MonoJitInfo*
5378 mono_thread_info_get_last_managed (MonoThreadInfo *info)
5380 MonoJitInfo *ji = NULL;
5381 if (!info)
5382 return NULL;
5385 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5386 * any runtime locks while unwinding.
5388 mono_thread_info_set_is_async_context (TRUE);
5389 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
5390 mono_thread_info_set_is_async_context (FALSE);
5391 return ji;
5394 typedef struct {
5395 MonoInternalThread *thread;
5396 gboolean install_async_abort;
5397 MonoThreadInfoInterruptToken *interrupt_token;
5398 } AbortThreadData;
5400 static SuspendThreadResult
5401 async_abort_critical (MonoThreadInfo *info, gpointer ud)
5403 AbortThreadData *data = (AbortThreadData *)ud;
5404 MonoInternalThread *thread = data->thread;
5405 MonoJitInfo *ji = NULL;
5406 gboolean protected_wrapper;
5407 gboolean running_managed;
5409 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
5410 return MonoResumeThread;
5412 /*someone is already interrupting it*/
5413 if (!mono_thread_set_interruption_requested (thread))
5414 return MonoResumeThread;
5416 ji = mono_thread_info_get_last_managed (info);
5417 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5418 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5420 if (!protected_wrapper && running_managed) {
5421 /*We are in managed code*/
5422 /*Set the thread to call */
5423 if (data->install_async_abort)
5424 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5425 return MonoResumeThread;
5426 } else {
5428 * This will cause waits to be broken.
5429 * It will also prevent the thread from entering a wait, so if the thread returns
5430 * from the wait before it receives the abort signal, it will just spin in the wait
5431 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5432 * make it return.
5434 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
5436 return MonoResumeThread;
5440 static void
5441 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
5443 AbortThreadData data;
5445 g_assert (thread != mono_thread_internal_current ());
5447 data.thread = thread;
5448 data.install_async_abort = install_async_abort;
5449 data.interrupt_token = NULL;
5451 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
5452 if (data.interrupt_token)
5453 mono_thread_info_finish_interrupt (data.interrupt_token);
5454 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5457 static void
5458 self_abort_internal (MonoError *error)
5460 HANDLE_FUNCTION_ENTER ();
5462 error_init (error);
5464 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5465 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5468 Self aborts ignore the protected block logic and raise the TAE regardless. This is verified by one of the tests in mono/tests/abort-cctor.cs.
5470 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5471 if (mono_thread_request_interruption_managed (&exc))
5472 mono_error_set_exception_handle (error, exc);
5473 else
5474 mono_thread_info_self_interrupt ();
5476 HANDLE_FUNCTION_RETURN ();
5479 typedef struct {
5480 MonoInternalThread *thread;
5481 gboolean interrupt;
5482 MonoThreadInfoInterruptToken *interrupt_token;
5483 } SuspendThreadData;
5485 static SuspendThreadResult
5486 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
5488 SuspendThreadData *data = (SuspendThreadData *)ud;
5489 MonoInternalThread *thread = data->thread;
5490 MonoJitInfo *ji = NULL;
5491 gboolean protected_wrapper;
5492 gboolean running_managed;
5494 ji = mono_thread_info_get_last_managed (info);
5495 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5496 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5498 if (running_managed && !protected_wrapper) {
5499 if (mono_threads_are_safepoints_enabled ()) {
5500 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5501 return MonoResumeThread;
5502 } else {
5503 thread->state &= ~ThreadState_SuspendRequested;
5504 thread->state |= ThreadState_Suspended;
5505 return KeepSuspended;
5507 } else {
5508 mono_thread_set_interruption_requested (thread);
5509 if (data->interrupt)
5510 data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
5512 return MonoResumeThread;
5516 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5517 static void
5518 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
5520 SuspendThreadData data;
5522 g_assert (thread != mono_thread_internal_current ());
5524 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5526 thread->self_suspended = FALSE;
5528 data.thread = thread;
5529 data.interrupt = interrupt;
5530 data.interrupt_token = NULL;
5532 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
5533 if (data.interrupt_token)
5534 mono_thread_info_finish_interrupt (data.interrupt_token);
5536 UNLOCK_THREAD (thread);
5539 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5540 static void
5541 self_suspend_internal (void)
5543 MonoInternalThread *thread;
5544 MonoOSEvent *event;
5545 MonoOSEventWaitRet res;
5547 thread = mono_thread_internal_current ();
5549 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5551 thread->self_suspended = TRUE;
5553 thread->state &= ~ThreadState_SuspendRequested;
5554 thread->state |= ThreadState_Suspended;
5556 UNLOCK_THREAD (thread);
5558 event = thread->suspended;
5560 MONO_ENTER_GC_SAFE;
5561 res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
5562 g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
5563 MONO_EXIT_GC_SAFE;
5566 static void
5567 suspend_for_shutdown_async_call (gpointer unused)
5569 for (;;)
5570 mono_thread_info_yield ();
5573 static SuspendThreadResult
5574 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
5576 mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
5577 return MonoResumeThread;
5580 void
5581 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
5583 g_assert (thread != mono_thread_internal_current ());
5585 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
5589 * mono_thread_is_foreign:
5590 * \param thread the thread to query
5592 * This function allows one to determine if a thread was created by the mono runtime and has
5593 * a well defined lifecycle or it's a foreign one, created by the native environment.
5595 * \returns TRUE if \p thread was not created by the runtime.
5597 mono_bool
5598 mono_thread_is_foreign (MonoThread *thread)
5600 mono_bool result;
5601 MONO_ENTER_GC_UNSAFE;
5602 MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
5603 result = (info->runtime_thread == FALSE);
5604 MONO_EXIT_GC_UNSAFE;
5605 return result;
5608 #ifndef HOST_WIN32
5609 static void
5610 threads_native_thread_join_lock (gpointer tid, gpointer value)
5612 pthread_t thread = (pthread_t)tid;
5613 if (thread != pthread_self ()) {
5614 MONO_ENTER_GC_SAFE;
5615 /* This shouldn't block */
5616 mono_threads_join_lock ();
5617 mono_native_thread_join (thread);
5618 mono_threads_join_unlock ();
5619 MONO_EXIT_GC_SAFE;
5622 static void
5623 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5625 pthread_t thread = (pthread_t)tid;
5626 MONO_ENTER_GC_SAFE;
5627 mono_native_thread_join (thread);
5628 MONO_EXIT_GC_SAFE;
5631 static void
5632 threads_add_joinable_thread_nolock (gpointer tid)
5634 g_hash_table_insert (joinable_threads, tid, tid);
5636 #else
5637 static void
5638 threads_native_thread_join_lock (gpointer tid, gpointer value)
5640 MonoNativeThreadId thread_id = (MonoNativeThreadId)(guint64)tid;
5641 HANDLE thread_handle = (HANDLE)value;
5642 if (thread_id != GetCurrentThreadId () && thread_handle != NULL && thread_handle != INVALID_HANDLE_VALUE) {
5643 MONO_ENTER_GC_SAFE;
5644 /* This shouldn't block */
5645 mono_threads_join_lock ();
5646 mono_native_thread_join_handle (thread_handle, TRUE);
5647 mono_threads_join_unlock ();
5648 MONO_EXIT_GC_SAFE;
5652 static void
5653 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5655 HANDLE thread_handle = (HANDLE)value;
5656 MONO_ENTER_GC_SAFE;
5657 mono_native_thread_join_handle (thread_handle, TRUE);
5658 MONO_EXIT_GC_SAFE;
5661 static void
5662 threads_add_joinable_thread_nolock (gpointer tid)
5664 g_hash_table_insert (joinable_threads, tid, (gpointer)OpenThread (SYNCHRONIZE, TRUE, (MonoNativeThreadId)(guint64)tid));
5666 #endif
5668 static void
5669 threads_add_pending_joinable_thread (gpointer tid)
5671 joinable_threads_lock ();
5673 if (!pending_joinable_threads)
5674 pending_joinable_threads = g_hash_table_new (NULL, NULL);
5676 gpointer orig_key;
5677 gpointer value;
5679 if (!g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5680 g_hash_table_insert (pending_joinable_threads, tid, tid);
5681 UnlockedIncrement (&pending_joinable_thread_count);
5684 joinable_threads_unlock ();
5687 static void
5688 threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info)
5690 g_assert (mono_thread_info);
5692 if (mono_thread_info->runtime_thread) {
5693 threads_add_pending_joinable_thread ((gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info))));
5697 static void
5698 threads_remove_pending_joinable_thread_nolock (gpointer tid)
5700 gpointer orig_key;
5701 gpointer value;
5703 if (pending_joinable_threads && g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5704 g_hash_table_remove (pending_joinable_threads, tid);
5705 if (UnlockedDecrement (&pending_joinable_thread_count) == 0)
5706 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event);
5710 static gboolean
5711 threads_wait_pending_joinable_threads (uint32_t timeout)
5713 if (UnlockedRead (&pending_joinable_thread_count) > 0) {
5714 joinable_threads_lock ();
5715 if (timeout == MONO_INFINITE_WAIT) {
5716 while (UnlockedRead (&pending_joinable_thread_count) > 0)
5717 mono_coop_cond_wait (&zero_pending_joinable_thread_event, &joinable_threads_mutex);
5718 } else {
5719 gint64 start = mono_msec_ticks ();
5720 gint64 elapsed = 0;
5721 while (UnlockedRead (&pending_joinable_thread_count) > 0 && elapsed < timeout) {
5722 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event, &joinable_threads_mutex, timeout - (uint32_t)elapsed);
5723 elapsed = mono_msec_ticks () - start;
5726 joinable_threads_unlock ();
5729 return UnlockedRead (&pending_joinable_thread_count) == 0;
5732 static void
5733 threads_add_unique_joinable_thread_nolock (gpointer tid)
5735 if (!joinable_threads)
5736 joinable_threads = g_hash_table_new (NULL, NULL);
5738 gpointer orig_key;
5739 gpointer value;
5741 if (!g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5742 threads_add_joinable_thread_nolock (tid);
5743 UnlockedIncrement (&joinable_thread_count);
5747 void
5748 mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info)
5750 g_assert (thread_info);
5751 MonoThreadInfo *mono_thread_info = thread_info;
5753 if (mono_thread_info->runtime_thread) {
5754 gpointer tid = (gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info)));
5756 joinable_threads_lock ();
5758 // Add to joinable thread list, if not already included.
5759 threads_add_unique_joinable_thread_nolock (tid);
5761 // Remove thread from pending joinable list, if present.
5762 threads_remove_pending_joinable_thread_nolock (tid);
5764 joinable_threads_unlock ();
5766 mono_gc_finalize_notify ();
5770 static void
5771 threads_add_pending_native_thread_join_call_nolock (gpointer tid)
5773 if (!pending_native_thread_join_calls)
5774 pending_native_thread_join_calls = g_hash_table_new (NULL, NULL);
5776 gpointer orig_key;
5777 gpointer value;
5779 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value))
5780 g_hash_table_insert (pending_native_thread_join_calls, tid, tid);
5783 static void
5784 threads_remove_pending_native_thread_join_call_nolock (gpointer tid)
5786 if (pending_native_thread_join_calls)
5787 g_hash_table_remove (pending_native_thread_join_calls, tid);
5789 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event);
5792 static void
5793 threads_wait_pending_native_thread_join_call_nolock (gpointer tid)
5795 gpointer orig_key;
5796 gpointer value;
5798 while (g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value)) {
5799 mono_coop_cond_wait (&pending_native_thread_join_calls_event, &joinable_threads_mutex);
5804 * mono_add_joinable_thread:
5806 * Add TID to the list of joinable threads.
5807 * LOCKING: Acquires the threads lock.
5809 void
5810 mono_threads_add_joinable_thread (gpointer tid)
5813 * We cannot detach from threads because it causes problems like
5814 * 2fd16f60/r114307. So we collect them and join them when
5815 * we have time (in the finalizer thread).
5817 joinable_threads_lock ();
5818 threads_add_unique_joinable_thread_nolock (tid);
5819 joinable_threads_unlock ();
5821 mono_gc_finalize_notify ();
5825 * mono_threads_join_threads:
5827 * Join all joinable threads. This is called from the finalizer thread.
5828 * LOCKING: Acquires the threads lock.
5830 void
5831 mono_threads_join_threads (void)
5833 GHashTableIter iter;
5834 gpointer key = NULL;
5835 gpointer value = NULL;
5836 gboolean found = FALSE;
5838 /* Fastpath */
5839 if (!UnlockedRead (&joinable_thread_count))
5840 return;
5842 while (TRUE) {
5843 joinable_threads_lock ();
5844 if (found) {
5845 // Previous native thread join call completed.
5846 threads_remove_pending_native_thread_join_call_nolock (key);
5848 found = FALSE;
5849 if (g_hash_table_size (joinable_threads)) {
5850 g_hash_table_iter_init (&iter, joinable_threads);
5851 g_hash_table_iter_next (&iter, &key, (void**)&value);
5852 g_hash_table_remove (joinable_threads, key);
5853 UnlockedDecrement (&joinable_thread_count);
5854 found = TRUE;
5856 // Add to table of tid's with pending native thread join call.
5857 threads_add_pending_native_thread_join_call_nolock (key);
5859 joinable_threads_unlock ();
5860 if (found)
5861 threads_native_thread_join_lock (key, value);
5862 else
5863 break;
5868 * mono_thread_join:
5870 * Wait for thread TID to exit.
5871 * LOCKING: Acquires the threads lock.
5873 void
5874 mono_thread_join (gpointer tid)
5876 gboolean found = FALSE;
5877 gpointer orig_key;
5878 gpointer value;
5880 joinable_threads_lock ();
5881 if (!joinable_threads)
5882 joinable_threads = g_hash_table_new (NULL, NULL);
5884 if (g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5885 g_hash_table_remove (joinable_threads, tid);
5886 UnlockedDecrement (&joinable_thread_count);
5887 found = TRUE;
5889 // Add to table of tid's with pending native join call.
5890 threads_add_pending_native_thread_join_call_nolock (tid);
5893 if (!found) {
5894 // Wait for any pending native thread join call not yet completed for this tid.
5895 threads_wait_pending_native_thread_join_call_nolock (tid);
5898 joinable_threads_unlock ();
5900 if (!found)
5901 return;
5903 threads_native_thread_join_nolock (tid, value);
5905 joinable_threads_lock ();
5906 // Native thread join call completed for this tid.
5907 threads_remove_pending_native_thread_join_call_nolock (tid);
5908 joinable_threads_unlock ();
5911 void
5912 mono_thread_internal_unhandled_exception (MonoObject* exc)
5914 MonoClass *klass = exc->vtable->klass;
5915 if (is_threadabort_exception (klass)) {
5916 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5917 } else if (!is_appdomainunloaded_exception (klass)
5918 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
5919 mono_unhandled_exception_internal (exc);
5920 if (mono_environment_exitcode_get () == 1) {
5921 mono_environment_exitcode_set (255);
5922 mono_invoke_unhandled_exception_hook (exc);
5923 g_assert_not_reached ();
5928 void
5929 ves_icall_System_Threading_Thread_GetStackTraces (MonoArray **out_threads, MonoArray **out_stack_traces)
5931 ERROR_DECL (error);
5932 mono_threads_get_thread_dump (out_threads, out_stack_traces, error);
5933 mono_error_set_pending_exception (error);
5937 * mono_threads_attach_coop_internal: called by native->managed wrappers
5939 * - @cookie:
5940 * - blocking mode: contains gc unsafe transition cookie
5941 * - non-blocking mode: contains random data
5942 * - @stackdata: semi-opaque struct: stackpointer and function_name
5943 * - @return: the original domain which needs to be restored, or NULL.
5945 MonoDomain*
5946 mono_threads_attach_coop_internal (MonoDomain *domain, gpointer *cookie, MonoStackData *stackdata)
5948 MonoDomain *orig;
5949 MonoThreadInfo *info;
5950 gboolean external = FALSE;
5952 orig = mono_domain_get ();
5954 if (!domain) {
5955 /* Happens when called from AOTed code which is only used in the root domain. */
5956 domain = mono_get_root_domain ();
5957 g_assert (domain);
5960 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
5961 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
5962 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
5963 * we're only responsible for making the cookie. */
5964 if (mono_threads_is_blocking_transition_enabled ())
5965 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
5967 if (!mono_thread_internal_current ()) {
5968 mono_thread_attach (domain);
5970 // #678164
5971 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
5974 if (mono_threads_is_blocking_transition_enabled ()) {
5975 if (external) {
5976 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
5977 * return the right cookie. */
5978 *cookie = mono_threads_enter_gc_unsafe_region_cookie ();
5979 } else {
5980 /* thread state (BLOCKING|RUNNING) -> RUNNING */
5981 *cookie = mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata);
5985 if (orig != domain)
5986 mono_domain_set_fast (domain, TRUE);
5988 return orig;
5992 * mono_threads_attach_coop: called by native->managed wrappers
5994 * - @dummy:
5995 * - blocking mode: contains gc unsafe transition cookie
5996 * - non-blocking mode: contains random data
5997 * - a pointer to stack, used for some checks
5998 * - @return: the original domain which needs to be restored, or NULL.
6000 gpointer
6001 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
6003 MONO_STACKDATA (stackdata);
6004 stackdata.stackpointer = dummy;
6005 return mono_threads_attach_coop_internal (domain, dummy, &stackdata);
6009 * mono_threads_detach_coop_internal: called by native->managed wrappers
6011 * - @orig: the original domain which needs to be restored, or NULL.
6012 * - @stackdata: semi-opaque struct: stackpointer and function_name
6013 * - @cookie:
6014 * - blocking mode: contains gc unsafe transition cookie
6015 * - non-blocking mode: contains random data
6017 void
6018 mono_threads_detach_coop_internal (MonoDomain *orig, gpointer cookie, MonoStackData *stackdata)
6020 MonoDomain *domain = mono_domain_get ();
6021 g_assert (domain);
6023 if (orig != domain) {
6024 if (!orig)
6025 mono_domain_unset ();
6026 else
6027 mono_domain_set_fast (orig, TRUE);
6030 if (mono_threads_is_blocking_transition_enabled ()) {
6031 /* it won't do anything if cookie is NULL
6032 * thread state RUNNING -> (RUNNING|BLOCKING) */
6033 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie, stackdata);
6038 * mono_threads_detach_coop: called by native->managed wrappers
6040 * - @orig: the original domain which needs to be restored, or NULL.
6041 * - @dummy:
6042 * - blocking mode: contains gc unsafe transition cookie
6043 * - non-blocking mode: contains random data
6044 * - a pointer to stack, used for some checks
6046 void
6047 mono_threads_detach_coop (gpointer orig, gpointer *dummy)
6049 MONO_STACKDATA (stackdata);
6050 stackdata.stackpointer = dummy;
6051 mono_threads_detach_coop_internal ((MonoDomain*)orig, *dummy, &stackdata);
6054 #if 0
6055 /* Returns TRUE if the current thread is ready to be interrupted. */
6056 gboolean
6057 mono_threads_is_ready_to_be_interrupted (void)
6059 MonoInternalThread *thread;
6061 thread = mono_thread_internal_current ();
6062 LOCK_THREAD (thread);
6063 if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
6064 UNLOCK_THREAD (thread);
6065 return FALSE;
6068 if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6069 UNLOCK_THREAD (thread);
6070 return FALSE;
6073 UNLOCK_THREAD (thread);
6074 return TRUE;
6076 #endif
6078 void
6079 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
6081 g_string_append_printf (text, ", thread handle : %p", internal->handle);
6083 if (internal->thread_info) {
6084 g_string_append (text, ", state : ");
6085 mono_thread_info_describe_interrupt_token (internal->thread_info, text);
6088 if (internal->owned_mutexes) {
6089 int i;
6091 g_string_append (text, ", owns : [");
6092 for (i = 0; i < internal->owned_mutexes->len; i++)
6093 g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
6094 g_string_append (text, "]");
6098 gboolean
6099 mono_thread_internal_is_current (MonoInternalThread *internal)
6101 g_assert (internal);
6102 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
6105 void
6106 mono_set_thread_dump_dir (gchar* dir) {
6107 thread_dump_dir = dir;
6110 #ifdef DISABLE_CRASH_REPORTING
6111 gboolean
6112 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6114 return FALSE;
6117 gboolean
6118 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6120 return FALSE;
6123 #else
6125 static gboolean
6126 mono_threads_summarize_native_self (MonoThreadSummary *out, MonoContext *ctx)
6128 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6129 return FALSE;
6131 memset (out, 0, sizeof (MonoThreadSummary));
6132 out->ctx = ctx;
6134 MonoNativeThreadId current = mono_native_thread_id_get();
6135 out->native_thread_id = (intptr_t) current;
6137 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out);
6139 mono_native_thread_get_name (current, out->name, MONO_MAX_SUMMARY_NAME_LEN);
6141 return TRUE;
6144 // Not safe to call from signal handler
6145 gboolean
6146 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6148 gboolean success = mono_threads_summarize_native_self (out, ctx);
6150 // Finish this on the same thread
6152 if (success && mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6153 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out);
6155 return success;
6158 #define TIMEOUT_CRASH_REPORTER_FATAL 30
6159 #define MAX_NUM_THREADS 128
6160 typedef struct {
6161 gint32 has_owner; // state of this memory
6163 MonoSemType update; // notify of addition of threads
6165 int nthreads;
6166 MonoNativeThreadId thread_array [MAX_NUM_THREADS]; // ids of threads we're dumping
6168 int nthreads_attached; // Number of threads self-registered
6169 MonoThreadSummary *all_threads [MAX_NUM_THREADS];
6171 gboolean silent; // print to stdout
6172 } SummarizerGlobalState;
6174 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6175 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6176 #endif
6178 typedef struct {
6179 MonoSemType supervisor;
6180 pid_t pid;
6181 pid_t supervisor_pid;
6182 } SummarizerSupervisorState;
6184 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6185 static void
6186 summarizer_supervisor_wait (SummarizerSupervisorState *state)
6188 return;
6191 static pid_t
6192 summarizer_supervisor_start (SummarizerSupervisorState *state)
6194 // nonzero, so caller doesn't think it's the supervisor
6195 return (pid_t) 1;
6198 static void
6199 summarizer_supervisor_end (SummarizerSupervisorState *state)
6201 return;
6204 #else
6205 static void
6206 summarizer_supervisor_wait (SummarizerSupervisorState *state)
6208 sleep (TIMEOUT_CRASH_REPORTER_FATAL);
6210 // If we haven't been SIGKILL'ed yet, we signal our parent
6211 // and then exit
6212 #ifdef HAVE_KILL
6213 g_async_safe_printf("Crash Reporter has timed out, sending SIGSEGV\n");
6214 kill (state->pid, SIGSEGV);
6215 #else
6216 g_error ("kill () is not supported by this platform");
6217 #endif
6219 exit (1);
6222 static pid_t
6223 summarizer_supervisor_start (SummarizerSupervisorState *state)
6225 memset (state, 0, sizeof (*state));
6226 pid_t pid;
6228 state->pid = getpid();
6231 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6232 * it will deadlock. Call the syscall directly instead.
6234 #if defined(HOST_ANDROID)
6235 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6236 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6237 g_assert_not_reached ();
6238 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6239 pid = (pid_t) syscall (SYS_fork);
6240 #elif HAVE_FORK
6241 pid = (pid_t) fork ();
6242 #else
6243 g_assert_not_reached ();
6244 #endif
6246 if (pid != 0)
6247 state->supervisor_pid = pid;
6249 return pid;
6252 static void
6253 summarizer_supervisor_end (SummarizerSupervisorState *state)
6255 #ifdef HAVE_KILL
6256 kill (state->supervisor_pid, SIGKILL);
6257 #endif
6259 #if defined (HAVE_WAITPID)
6260 // Accessed on same thread that sets it.
6261 int status;
6262 waitpid (state->supervisor_pid, &status, 0);
6263 #endif
6265 #endif
6267 static gboolean
6268 summarizer_state_init (SummarizerGlobalState *state, MonoNativeThreadId current, int *my_index)
6270 gint32 started_state = mono_atomic_cas_i32 (&state->has_owner, 1 /* set */, 0 /* compare */);
6271 gboolean not_started = started_state == 0;
6272 if (not_started) {
6273 state->nthreads = collect_thread_ids (state->thread_array, MAX_NUM_THREADS);
6274 mono_os_sem_init (&state->update, 0);
6277 for (int i = 0; i < state->nthreads; i++) {
6278 if (state->thread_array [i] == current) {
6279 *my_index = i;
6280 break;
6284 return not_started;
6287 static void
6288 summarizer_signal_other_threads (SummarizerGlobalState *state, MonoNativeThreadId current, int current_idx)
6290 sigset_t sigset, old_sigset;
6291 sigemptyset(&sigset);
6292 sigaddset(&sigset, SIGTERM);
6294 for (int i=0; i < state->nthreads; i++) {
6295 sigprocmask (SIG_UNBLOCK, &sigset, &old_sigset);
6297 if (i == current_idx)
6298 continue;
6300 #ifdef HAVE_PTHREAD_KILL
6301 pthread_kill (state->thread_array [i], SIGTERM);
6303 if (!state->silent)
6304 g_async_safe_printf("Pkilling 0x%zx from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (state->thread_array [i]), MONO_NATIVE_THREAD_ID_TO_UINT (current));
6305 #else
6306 g_error ("pthread_kill () is not supported by this platform");
6307 #endif
6311 // Returns true when there are shared global references to "this_thread"
6312 static gboolean
6313 summarizer_post_dump (SummarizerGlobalState *state, MonoThreadSummary *this_thread, int current_idx)
6315 mono_memory_barrier ();
6317 gpointer old = mono_atomic_cas_ptr ((volatile gpointer *)&state->all_threads [current_idx], this_thread, NULL);
6319 if (old == GINT_TO_POINTER (-1)) {
6320 g_async_safe_printf ("Trying to register response after dumping period ended");
6321 return FALSE;
6322 } else if (old != NULL) {
6323 g_async_safe_printf ("Thread dump raced for thread slot.");
6324 return FALSE;
6327 // We added our pointer
6328 gint32 count = mono_atomic_inc_i32 ((volatile gint32 *) &state->nthreads_attached);
6329 if (count == state->nthreads)
6330 mono_os_sem_post (&state->update);
6332 return TRUE;
6335 // A lockless spinwait with a timeout
6336 // Used in environments where locks are unsafe
6338 // If set_pos is true, we wait until the expected number of threads have
6339 // responded and then count that the expected number are set. If it is not true,
6340 // then we wait for them to be unset.
6341 static void
6342 summary_timedwait (SummarizerGlobalState *state, int timeout_seconds)
6344 const gint64 milliseconds_in_second = 1000;
6345 gint64 timeout_total = milliseconds_in_second * timeout_seconds;
6347 gint64 end = mono_msec_ticks () + timeout_total;
6349 while (TRUE) {
6350 if (mono_atomic_load_i32 ((volatile gint32 *) &state->nthreads_attached) == state->nthreads)
6351 break;
6353 gint64 now = mono_msec_ticks ();
6354 gint64 remaining = end - now;
6355 if (remaining <= 0)
6356 break;
6358 mono_os_sem_timedwait (&state->update, remaining, MONO_SEM_FLAGS_NONE);
6361 return;
6364 static MonoThreadSummary *
6365 summarizer_try_read_thread (SummarizerGlobalState *state, int index)
6367 gpointer old_value = NULL;
6368 gpointer new_value = GINT_TO_POINTER(-1);
6370 do {
6371 old_value = state->all_threads [index];
6372 } while (mono_atomic_cas_ptr ((volatile gpointer *) &state->all_threads [index], new_value, old_value) != old_value);
6374 MonoThreadSummary *thread = (MonoThreadSummary *) old_value;
6375 return thread;
6378 static void
6379 summarizer_state_term (SummarizerGlobalState *state, gchar **out, gchar *mem, size_t provided_size, MonoThreadSummary *controlling)
6381 // See the array writes
6382 mono_memory_barrier ();
6384 MonoThreadSummary *threads [MAX_NUM_THREADS];
6385 memset (threads, 0, sizeof(threads));
6387 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6388 for (int i=0; i < state->nthreads; i++) {
6389 threads [i] = summarizer_try_read_thread (state, i);
6390 if (!threads [i])
6391 continue;
6393 // We are doing this dump on the controlling thread because this isn't
6394 // an async context sometimes. There's still some reliance on malloc here, but it's
6395 // much more stable to do it all from the controlling thread.
6397 // This is non-null, checked in mono_threads_summarize
6398 // with early exit there
6399 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads [i]);
6402 MonoStateWriter writer;
6403 memset (&writer, 0, sizeof (writer));
6405 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6406 mono_summarize_native_state_begin (&writer, mem, provided_size);
6407 for (int i=0; i < state->nthreads; i++) {
6408 MonoThreadSummary *thread = threads [i];
6409 if (!thread)
6410 continue;
6412 mono_summarize_native_state_add_thread (&writer, thread, thread->ctx, thread == controlling);
6413 // Set non-shared state to notify the waiting thread to clean up
6414 // without having to keep our shared state alive
6415 mono_atomic_store_i32 (&thread->done, 0x1);
6416 mono_os_sem_post (&thread->done_wait);
6418 *out = mono_summarize_native_state_end (&writer);
6419 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6421 mono_os_sem_destroy (&state->update);
6423 memset (state, 0, sizeof (*state));
6424 mono_atomic_store_i32 ((volatile gint32 *)&state->has_owner, 0);
6427 static void
6428 summarizer_state_wait (MonoThreadSummary *thread)
6430 gint64 milliseconds_in_second = 1000;
6432 // cond_wait can spuriously wake up, so we need to check
6433 // done
6434 while (!mono_atomic_load_i32 (&thread->done))
6435 mono_os_sem_timedwait (&thread->done_wait, milliseconds_in_second, MONO_SEM_FLAGS_NONE);
6438 static gboolean
6439 mono_threads_summarize_execute_internal (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size, gboolean this_thread_controls)
6441 static SummarizerGlobalState state;
6443 int current_idx;
6444 MonoNativeThreadId current = mono_native_thread_id_get ();
6445 gboolean thread_given_control = summarizer_state_init (&state, current, &current_idx);
6447 g_assert (this_thread_controls == thread_given_control);
6449 if (state.nthreads == 0) {
6450 if (!silent)
6451 g_async_safe_printf("No threads attached to runtime.\n");
6452 memset (&state, 0, sizeof (state));
6453 return FALSE;
6456 if (this_thread_controls) {
6457 g_assert (working_mem);
6459 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6460 state.silent = silent;
6461 summarizer_signal_other_threads (&state, current, current_idx);
6462 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6465 MonoStateMem mem;
6466 gboolean success = mono_state_alloc_mem (&mem, (long) current, sizeof (MonoThreadSummary));
6467 if (!success)
6468 return FALSE;
6470 MonoThreadSummary *this_thread = (MonoThreadSummary *) mem.mem;
6472 if (mono_threads_summarize_native_self (this_thread, ctx)) {
6473 // Init the synchronization between the controlling thread and the
6474 // providing thread
6475 mono_os_sem_init (&this_thread->done_wait, 0);
6477 // Store a reference to our stack memory into global state
6478 gboolean success = summarizer_post_dump (&state, this_thread, current_idx);
6479 if (!success && !state.silent)
6480 g_async_safe_printf("Thread 0x%zx reported itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6481 } else if (!state.silent) {
6482 g_async_safe_printf("Thread 0x%zx couldn't report itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6485 // From summarizer, wait and dump.
6486 if (this_thread_controls) {
6487 if (!state.silent)
6488 g_async_safe_printf("Entering thread summarizer pause from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6490 // Wait up to 2 seconds for all of the other threads to catch up
6491 summary_timedwait (&state, 2);
6493 if (!state.silent)
6494 g_async_safe_printf("Finished thread summarizer pause from 0x%zx.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6496 // Dump and cleanup all the stack memory
6497 summarizer_state_term (&state, out, working_mem, provided_size, this_thread);
6498 } else {
6499 // Wait here, keeping our stack memory alive
6500 // for the dumper
6501 summarizer_state_wait (this_thread);
6504 // FIXME: How many threads should be counted?
6505 if (hashes)
6506 *hashes = this_thread->hashes;
6508 mono_state_free_mem (&mem);
6510 return TRUE;
6513 gboolean
6514 mono_threads_summarize_execute (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size)
6516 return mono_threads_summarize_execute_internal (ctx, out, hashes, silent, working_mem, provided_size, FALSE);
6519 gboolean
6520 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6522 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6523 return FALSE;
6525 // The staggered values are due to the need to use inc_i64 for the first value
6526 static gint64 next_pending_request_id = 0;
6527 static gint64 request_available_to_run = 1;
6528 gint64 this_request_id = mono_atomic_inc_i64 ((volatile gint64 *) &next_pending_request_id);
6530 // This is a global queue of summary requests.
6531 // It's not safe to signal a thread while they're in the
6532 // middle of a dump. Dladdr is not reentrant. It's the one lock
6533 // we rely on being able to take.
6535 // We don't use it in almost any other place in managed code, so
6536 // our problem is in the stack dumping code racing with the signalling code.
6538 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6539 // If we're running from a crash handler block, we're not in any position to
6540 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6541 // We should simply return so we can die cleanly.
6543 // signal_handler_controller should be set only from a handler that expects itself to be the only
6544 // entry point, where the runtime already being dumping means we should just give up
6546 gboolean success = FALSE;
6548 while (TRUE) {
6549 gint64 next_request_id = mono_atomic_load_i64 ((volatile gint64 *) &request_available_to_run);
6551 if (next_request_id == this_request_id) {
6552 gboolean already_async = mono_thread_info_is_async_context ();
6553 if (!already_async)
6554 mono_thread_info_set_is_async_context (TRUE);
6556 SummarizerSupervisorState synch;
6557 if (summarizer_supervisor_start (&synch)) {
6558 g_assert (mem);
6559 success = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, mem, provided_size, TRUE);
6560 summarizer_supervisor_end (&synch);
6561 } else {
6562 summarizer_supervisor_wait (&synch);
6565 if (!already_async)
6566 mono_thread_info_set_is_async_context (FALSE);
6568 // Only the thread that gets the ticket can unblock future dumpers.
6569 mono_atomic_inc_i64 ((volatile gint64 *) &request_available_to_run);
6570 break;
6571 } else if (signal_handler_controller) {
6572 // We're done. We can't do anything.
6573 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6574 mono_summarize_double_fault_log ();
6575 break;
6576 } else {
6577 if (!silent)
6578 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6579 sleep (2);
6583 return success;
6586 #endif
6588 #ifdef ENABLE_NETCORE
6589 void
6590 ves_icall_System_Threading_Thread_StartInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6592 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6593 gboolean res;
6595 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p)", __func__, internal));
6597 LOCK_THREAD (internal);
6599 if ((internal->state & ThreadState_Unstarted) == 0) {
6600 UNLOCK_THREAD (internal);
6601 mono_error_set_exception_thread_state (error, "Thread has already been started.");
6602 return;
6605 if ((internal->state & ThreadState_Aborted) != 0) {
6606 UNLOCK_THREAD (internal);
6607 return;
6610 res = create_thread (internal, internal, NULL, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
6611 if (!res) {
6612 UNLOCK_THREAD (internal);
6613 return;
6616 internal->state &= ~ThreadState_Unstarted;
6618 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, (gsize)internal->tid, internal->handle));
6620 UNLOCK_THREAD (internal);
6623 void
6624 ves_icall_System_Threading_Thread_InitInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6626 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6628 // Need to initialize thread objects created from managed code
6629 init_internal_thread_object (internal);
6630 internal->state = ThreadState_Unstarted;
6631 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
6634 guint64
6635 ves_icall_System_Threading_Thread_GetCurrentOSThreadId (MonoError *error)
6637 return mono_native_thread_os_id_get ();
6640 #endif