Ensure special static slots respect alignment. (#20506)
[mono-project.git] / mono / metadata / threads.c
blob5354a51b9e75b738d76feaa07c6697ff49245421
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>
61 #include <mono/metadata/mono-config.h>
62 #include "mono/utils/mono-tls-inline.h"
64 #ifdef HAVE_SYS_WAIT_H
65 #include <sys/wait.h>
66 #endif
68 #include <signal.h>
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;
128 gint32 align;
131 typedef struct {
132 int idx;
133 int offset;
134 StaticDataFreeList *freelist;
135 } StaticDataInfo;
137 /* Controls access to the 'threads' hash table */
138 static void mono_threads_lock (void);
139 static void mono_threads_unlock (void);
140 static MonoCoopMutex threads_mutex;
142 /* Controls access to the 'joinable_threads' hash table */
143 #define joinable_threads_lock() mono_coop_mutex_lock (&joinable_threads_mutex)
144 #define joinable_threads_unlock() mono_coop_mutex_unlock (&joinable_threads_mutex)
145 static MonoCoopMutex joinable_threads_mutex;
147 /* Holds current status of static data heap */
148 static StaticDataInfo thread_static_info;
149 static StaticDataInfo context_static_info;
151 /* The hash of existing threads (key is thread ID, value is
152 * MonoInternalThread*) that need joining before exit
154 static MonoGHashTable *threads=NULL;
156 /* List of app context GC handles.
157 * Added to from mono_threads_register_app_context ().
159 static GHashTable *contexts = NULL;
161 /* Cleanup queue for contexts. */
162 static MonoReferenceQueue *context_queue;
165 * Threads which are starting up and they are not in the 'threads' hash yet.
166 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
167 * Protected by mono_threads_lock ().
169 static MonoGHashTable *threads_starting_up = NULL;
171 /* Contains tids */
172 /* Protected by the threads lock */
173 static GHashTable *joinable_threads;
174 static gint32 joinable_thread_count;
176 /* mono_threads_join_threads will take threads from joinable_threads list and wait for them. */
177 /* When this happens, the tid is not on the list anymore so mono_thread_join assumes the thread has complete */
178 /* and will return back to the caller. This could cause a race since caller of join assumes thread has completed */
179 /* and on some OS it could cause errors. Keeping the tid's currently pending a native thread join call */
180 /* in a separate table (only affecting callers interested in this internal join detail) and look at that table in mono_thread_join */
181 /* will close this race. */
182 static GHashTable *pending_native_thread_join_calls;
183 static MonoCoopCond pending_native_thread_join_calls_event;
185 static GHashTable *pending_joinable_threads;
186 static gint32 pending_joinable_thread_count;
188 static MonoCoopCond zero_pending_joinable_thread_event;
190 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info);
191 static gboolean threads_wait_pending_joinable_threads (uint32_t timeout);
192 static gchar* thread_dump_dir = NULL;
194 #define SET_CURRENT_OBJECT mono_tls_set_thread
195 #define GET_CURRENT_OBJECT mono_tls_get_thread
197 /* function called at thread start */
198 static MonoThreadStartCB mono_thread_start_cb = NULL;
200 /* function called at thread attach */
201 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
203 /* function called at thread cleanup */
204 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
206 /* The default stack size for each thread */
207 static guint32 default_stacksize = 0;
208 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
210 static void context_adjust_static_data (MonoAppContextHandle ctx);
211 static void mono_free_static_data (gpointer* static_data);
212 static void mono_init_static_data_info (StaticDataInfo *static_data);
213 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
214 static gboolean mono_thread_resume (MonoInternalThread* thread);
215 static void async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort);
216 static void self_abort_internal (MonoError *error);
217 static void async_suspend_internal (MonoInternalThread *thread, gboolean interrupt);
218 static void self_suspend_internal (void);
220 static gboolean
221 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync);
223 MONO_COLD void
224 mono_set_pending_exception_handle (MonoExceptionHandle exc);
226 static MonoException*
227 mono_thread_execute_interruption_ptr (void);
229 static void
230 mono_thread_execute_interruption_void (void);
232 static gboolean
233 mono_thread_execute_interruption (MonoExceptionHandle *pexc);
235 static void ref_stack_destroy (gpointer rs);
237 #if SIZEOF_VOID_P == 4
238 /* Spin lock for unaligned InterlockedXXX 64 bit functions on 32bit platforms. */
239 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
240 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
241 static mono_mutex_t interlocked_mutex;
242 #endif
244 /* global count of thread interruptions requested */
245 gint32 mono_thread_interruption_request_flag;
247 /* Event signaled when a thread changes its background mode */
248 static MonoOSEvent background_change_event;
250 static gboolean shutting_down = FALSE;
252 static gint32 managed_thread_id_counter = 0;
254 static void
255 mono_threads_lock (void)
257 mono_locks_coop_acquire (&threads_mutex, ThreadsLock);
260 static void
261 mono_threads_unlock (void)
263 mono_locks_coop_release (&threads_mutex, ThreadsLock);
267 static guint32
268 get_next_managed_thread_id (void)
270 return mono_atomic_inc_i32 (&managed_thread_id_counter);
274 * We separate interruptions/exceptions into either sync (they can be processed anytime,
275 * normally as soon as they are set, and are set by the same thread) and async (they can't
276 * be processed inside abort protected blocks and are normally set by other threads). We
277 * can have both a pending sync and async interruption. In this case, the sync exception is
278 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
279 * also handle all sync type exceptions before the async type exceptions.
281 enum {
282 INTERRUPT_SYNC_REQUESTED_BIT = 0x1,
283 INTERRUPT_ASYNC_REQUESTED_BIT = 0x2,
284 INTERRUPT_REQUESTED_MASK = 0x3,
285 ABORT_PROT_BLOCK_SHIFT = 2,
286 ABORT_PROT_BLOCK_BITS = 8,
287 ABORT_PROT_BLOCK_MASK = (((1 << ABORT_PROT_BLOCK_BITS) - 1) << ABORT_PROT_BLOCK_SHIFT)
290 static int
291 mono_thread_get_abort_prot_block_count (MonoInternalThread *thread)
293 gsize state = thread->thread_state;
294 return (state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT;
297 gboolean
298 mono_threads_is_current_thread_in_protected_block (void)
300 MonoInternalThread *thread = mono_thread_internal_current ();
302 return mono_thread_get_abort_prot_block_count (thread) > 0;
305 void
306 mono_threads_begin_abort_protected_block (void)
308 MonoInternalThread *thread = mono_thread_internal_current ();
309 gsize old_state, new_state;
310 int new_val;
311 do {
312 old_state = thread->thread_state;
314 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) + 1;
315 //bounds check abort_prot_count
316 g_assert (new_val > 0);
317 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
319 new_state = old_state + (1 << ABORT_PROT_BLOCK_SHIFT);
320 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
322 /* Defer async request since we won't be able to process until exiting the block */
323 if (new_val == 1 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
324 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag);
325 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, mono_thread_interruption_request_flag);
326 if (mono_thread_interruption_request_flag < 0)
327 g_warning ("bad mono_thread_interruption_request_flag state");
328 } else {
329 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
333 static gboolean
334 mono_thread_state_has_interruption (gsize state)
336 /* pending exception, self abort */
337 if (state & INTERRUPT_SYNC_REQUESTED_BIT)
338 return TRUE;
340 /* abort, interruption, suspend */
341 if ((state & INTERRUPT_ASYNC_REQUESTED_BIT) && !(state & ABORT_PROT_BLOCK_MASK))
342 return TRUE;
344 return FALSE;
347 gboolean
348 mono_threads_end_abort_protected_block (void)
350 MonoInternalThread *thread = mono_thread_internal_current ();
351 gsize old_state, new_state;
352 int new_val;
353 do {
354 old_state = thread->thread_state;
356 //bounds check abort_prot_count
357 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) - 1;
358 g_assert (new_val >= 0);
359 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
361 new_state = old_state - (1 << ABORT_PROT_BLOCK_SHIFT);
362 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
364 if (new_val == 0 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
365 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag);
366 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, mono_thread_interruption_request_flag);
367 } else {
368 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
371 return mono_thread_state_has_interruption (new_state);
374 static gboolean
375 mono_thread_get_interruption_requested (MonoInternalThread *thread)
377 gsize state = thread->thread_state;
379 return mono_thread_state_has_interruption (state);
383 * Returns TRUE is there was a state change
384 * We clear a single interruption request, sync has priority.
386 static gboolean
387 mono_thread_clear_interruption_requested (MonoInternalThread *thread)
389 gsize old_state, new_state;
390 do {
391 old_state = thread->thread_state;
393 // no interruption to process
394 if (!(old_state & INTERRUPT_SYNC_REQUESTED_BIT) &&
395 (!(old_state & INTERRUPT_ASYNC_REQUESTED_BIT) || (old_state & ABORT_PROT_BLOCK_MASK)))
396 return FALSE;
398 if (old_state & INTERRUPT_SYNC_REQUESTED_BIT)
399 new_state = old_state & ~INTERRUPT_SYNC_REQUESTED_BIT;
400 else
401 new_state = old_state & ~INTERRUPT_ASYNC_REQUESTED_BIT;
402 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
404 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag);
405 THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
406 if (mono_thread_interruption_request_flag < 0)
407 g_warning ("bad mono_thread_interruption_request_flag state");
408 return TRUE;
411 static gboolean
412 mono_thread_clear_interruption_requested_handle (MonoInternalThreadHandle thread)
414 // Internal threads are pinned so shallow coop/handle.
415 return mono_thread_clear_interruption_requested (mono_internal_thread_handle_ptr (thread));
418 /* Returns TRUE is there was a state change and the interruption can be processed */
419 static gboolean
420 mono_thread_set_interruption_requested (MonoInternalThread *thread)
422 //always force when the current thread is doing it to itself.
423 gboolean sync = thread == mono_thread_internal_current ();
424 /* Normally synchronous interruptions can bypass abort protection. */
425 return mono_thread_set_interruption_requested_flags (thread, sync);
428 /* Returns TRUE if there was a state change and the interruption can be
429 * processed. This variant defers a self abort when inside an abort protected
430 * block. Normally this should only be done when a thread has received an
431 * outside indication that it should abort. (For example when the JIT sets a
432 * flag in an finally block.)
435 static gboolean
436 mono_thread_set_self_interruption_respect_abort_prot (void)
438 MonoInternalThread *thread = mono_thread_internal_current ();
439 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
440 * which is unusual. */
441 return mono_thread_set_interruption_requested_flags (thread, FALSE);
444 /* Returns TRUE if there was a state change and the interruption can be processed. */
445 static gboolean
446 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync)
448 gsize old_state, new_state;
449 do {
450 old_state = thread->thread_state;
452 //Already set
453 if ((sync && (old_state & INTERRUPT_SYNC_REQUESTED_BIT)) ||
454 (!sync && (old_state & INTERRUPT_ASYNC_REQUESTED_BIT)))
455 return FALSE;
457 if (sync)
458 new_state = old_state | INTERRUPT_SYNC_REQUESTED_BIT;
459 else
460 new_state = old_state | INTERRUPT_ASYNC_REQUESTED_BIT;
461 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
463 if (sync || !(new_state & ABORT_PROT_BLOCK_MASK)) {
464 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag);
465 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, mono_thread_interruption_request_flag);
466 } else {
467 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, mono_thread_interruption_request_flag);
470 return sync || !(new_state & ABORT_PROT_BLOCK_MASK);
473 static MonoNativeThreadId
474 thread_get_tid (MonoInternalThread *thread)
476 /* We store the tid as a guint64 to keep the object layout constant between platforms */
477 return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
480 static void
481 free_synch_cs (MonoCoopMutex *synch_cs)
483 g_assert (synch_cs);
484 mono_coop_mutex_destroy (synch_cs);
485 g_free (synch_cs);
488 static void
489 free_longlived_thread_data (void *user_data)
491 MonoLongLivedThreadData *lltd = (MonoLongLivedThreadData*)user_data;
492 free_synch_cs (lltd->synch_cs);
494 g_free (lltd);
497 static void
498 init_longlived_thread_data (MonoLongLivedThreadData *lltd)
500 mono_refcount_init (lltd, free_longlived_thread_data);
501 mono_refcount_inc (lltd);
502 /* Initial refcount is 2: decremented once by
503 * mono_thread_detach_internal and once by the MonoInternalThread
504 * finalizer - whichever one happens later will deallocate. */
506 lltd->synch_cs = g_new0 (MonoCoopMutex, 1);
507 mono_coop_mutex_init_recursive (lltd->synch_cs);
509 mono_memory_barrier ();
512 static void
513 dec_longlived_thread_data (MonoLongLivedThreadData *lltd)
515 mono_refcount_dec (lltd);
518 static void
519 lock_thread (MonoInternalThread *thread)
521 g_assert (thread->longlived);
522 g_assert (thread->longlived->synch_cs);
524 mono_coop_mutex_lock (thread->longlived->synch_cs);
527 static void
528 unlock_thread (MonoInternalThread *thread)
530 mono_coop_mutex_unlock (thread->longlived->synch_cs);
533 static void
534 lock_thread_handle (MonoInternalThreadHandle thread)
536 lock_thread (mono_internal_thread_handle_ptr (thread));
539 static void
540 unlock_thread_handle (MonoInternalThreadHandle thread)
542 unlock_thread (mono_internal_thread_handle_ptr (thread));
545 static gboolean
546 is_appdomainunloaded_exception (MonoClass *klass)
548 #ifdef ENABLE_NETCORE
549 return FALSE;
550 #else
551 return klass == mono_class_get_appdomain_unloaded_exception_class ();
552 #endif
555 static gboolean
556 is_threadabort_exception (MonoClass *klass)
558 return klass == mono_defaults.threadabortexception_class;
562 * A special static data offset (guint32) consists of 3 parts:
564 * [0] 6-bit index into the array of chunks.
565 * [6] 25-bit offset into the array.
566 * [31] Bit indicating thread or context static.
569 typedef union {
570 struct {
571 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
572 guint32 type : 1;
573 guint32 offset : 25;
574 guint32 index : 6;
575 #else
576 guint32 index : 6;
577 guint32 offset : 25;
578 guint32 type : 1;
579 #endif
580 } fields;
581 guint32 raw;
582 } SpecialStaticOffset;
584 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
585 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
587 static guint32
588 MAKE_SPECIAL_STATIC_OFFSET (guint32 index, guint32 offset, guint32 type)
590 SpecialStaticOffset special_static_offset;
591 memset (&special_static_offset, 0, sizeof (special_static_offset));
592 special_static_offset.fields.index = index;
593 special_static_offset.fields.offset = offset;
594 special_static_offset.fields.type = type;
595 return special_static_offset.raw;
598 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
599 (((SpecialStaticOffset *) &(x))->fields.f)
601 static gpointer
602 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
604 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_THREAD);
606 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
607 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
609 return ((char *) thread->static_data [idx]) + off;
612 static gpointer
613 get_context_static_data (MonoAppContext *ctx, guint32 offset)
615 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT);
617 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
618 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
620 return ((char *) ctx->static_data [idx]) + off;
623 static MonoThread**
624 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
626 guint32 offset;
628 MONO_STATIC_POINTER_INIT (MonoClassField, 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);
633 MONO_STATIC_POINTER_INIT_END (MonoClassField, current_thread_field)
635 ERROR_DECL (thread_vt_error);
636 mono_class_vtable_checked (domain, mono_defaults.thread_class, thread_vt_error);
637 mono_error_assert_ok (thread_vt_error);
638 mono_domain_lock (domain);
639 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
640 mono_domain_unlock (domain);
641 g_assert (offset);
643 return (MonoThread **)get_thread_static_data (thread, offset);
646 static void
647 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
649 #ifndef ENABLE_NETCORE
650 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
652 g_assert (current->obj.vtable->domain == domain);
654 g_assert (!*current_thread_ptr);
655 *current_thread_ptr = current;
656 #endif
659 static MonoThread*
660 create_thread_object (MonoDomain *domain, MonoInternalThread *internal)
662 #ifdef ENABLE_NETCORE
663 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
664 return internal;
665 #else
666 MonoThread *thread;
667 MonoVTable *vtable;
668 ERROR_DECL (error);
670 vtable = mono_class_vtable_checked (domain, mono_defaults.thread_class, error);
671 mono_error_assert_ok (error);
673 thread = (MonoThread*)mono_object_new_mature (vtable, error);
674 /* only possible failure mode is OOM, from which we don't expect to recover. */
675 mono_error_assert_ok (error);
677 MONO_OBJECT_SETREF_INTERNAL (thread, internal_thread, internal);
679 return thread;
680 #endif
683 static void
684 init_internal_thread_object (MonoInternalThread *thread)
686 thread->longlived = g_new0 (MonoLongLivedThreadData, 1);
687 init_longlived_thread_data (thread->longlived);
689 thread->apartment_state = ThreadApartmentState_Unknown;
690 thread->managed_id = get_next_managed_thread_id ();
691 if (mono_gc_is_moving ()) {
692 thread->thread_pinning_ref = thread;
693 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Pinning Reference");
696 thread->priority = MONO_THREAD_PRIORITY_NORMAL;
698 thread->suspended = g_new0 (MonoOSEvent, 1);
699 mono_os_event_init (thread->suspended, TRUE);
702 static MonoInternalThread*
703 create_internal_thread_object (void)
705 ERROR_DECL (error);
706 MonoInternalThread *thread;
707 MonoVTable *vt;
709 vt = mono_class_vtable_checked (mono_get_root_domain (), mono_defaults.internal_thread_class, error);
710 mono_error_assert_ok (error);
711 thread = (MonoInternalThread*) mono_object_new_mature (vt, error);
712 /* only possible failure mode is OOM, from which we don't exect to recover */
713 mono_error_assert_ok (error);
715 init_internal_thread_object (thread);
717 return thread;
720 static void
721 mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPriority priority)
723 g_assert (internal);
725 g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
726 g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
727 g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
729 #ifdef HOST_WIN32
730 BOOL res;
731 DWORD last_error;
733 g_assert (internal->native_handle);
735 MONO_ENTER_GC_SAFE;
736 res = SetThreadPriority (internal->native_handle, (int)priority - 2);
737 last_error = GetLastError ();
738 MONO_EXIT_GC_SAFE;
739 if (!res)
740 g_error ("%s: SetThreadPriority failed, error %d", __func__, last_error);
741 #elif defined(HOST_FUCHSIA)
742 int z_priority;
744 if (priority == MONO_THREAD_PRIORITY_LOWEST)
745 z_priority = ZX_PRIORITY_LOWEST;
746 else if (priority == MONO_THREAD_PRIORITY_BELOW_NORMAL)
747 z_priority = ZX_PRIORITY_LOW;
748 else if (priority == MONO_THREAD_PRIORITY_NORMAL)
749 z_priority = ZX_PRIORITY_DEFAULT;
750 else if (priority == MONO_THREAD_PRIORITY_ABOVE_NORMAL)
751 z_priority = ZX_PRIORITY_HIGH;
752 else if (priority == MONO_THREAD_PRIORITY_HIGHEST)
753 z_priority = ZX_PRIORITY_HIGHEST;
754 else
755 return;
758 // When this API becomes available on an arbitrary thread, we can use it,
759 // not available on current Zircon
761 #else /* !HOST_WIN32 and not HOST_FUCHSIA */
762 pthread_t tid;
763 int policy;
764 struct sched_param param;
765 gint res;
767 tid = thread_get_tid (internal);
769 MONO_ENTER_GC_SAFE;
770 res = pthread_getschedparam (tid, &policy, &param);
771 MONO_EXIT_GC_SAFE;
772 if (res != 0)
773 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
775 #ifdef _POSIX_PRIORITY_SCHEDULING
776 int max, min;
778 /* Necessary to get valid priority range */
780 MONO_ENTER_GC_SAFE;
781 #if defined(__PASE__)
782 /* only priorities allowed by IBM i */
783 min = PRIORITY_MIN;
784 max = PRIORITY_MAX;
785 #else
786 min = sched_get_priority_min (policy);
787 max = sched_get_priority_max (policy);
788 #endif
789 MONO_EXIT_GC_SAFE;
791 /* Not tunable. Bail out */
792 if ((min == -1) || (max == -1))
793 return;
795 if (max > 0 && min >= 0 && max > min) {
796 double srange, drange, sposition, dposition;
797 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
798 drange = max - min;
799 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
800 dposition = (sposition / srange) * drange;
801 param.sched_priority = (int)(dposition + min);
802 } else
803 #endif
805 switch (policy) {
806 case SCHED_FIFO:
807 case SCHED_RR:
808 param.sched_priority = 50;
809 break;
810 #ifdef SCHED_BATCH
811 case SCHED_BATCH:
812 #endif
813 case SCHED_OTHER:
814 param.sched_priority = 0;
815 break;
816 default:
817 g_warning ("%s: unknown policy %d", __func__, policy);
818 return;
822 MONO_ENTER_GC_SAFE;
823 #if defined(__PASE__)
824 /* only scheduling param allowed by IBM i */
825 res = pthread_setschedparam (tid, SCHED_OTHER, &param);
826 #else
827 res = pthread_setschedparam (tid, policy, &param);
828 #endif
829 MONO_EXIT_GC_SAFE;
830 if (res != 0) {
831 if (res == EPERM) {
832 #if !defined(_AIX)
833 /* AIX doesn't like doing this and will spam this every time;
834 * weirdly, i doesn't complain
836 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
837 #endif
838 return;
840 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
842 #endif /* HOST_WIN32 */
845 static void
846 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal);
848 static gboolean
849 mono_thread_attach_internal (MonoThread *thread, gboolean force_attach, gboolean force_domain)
851 MonoThreadInfo *info;
852 MonoInternalThread *internal;
853 MonoDomain *domain, *root_domain;
854 guint32 gchandle;
856 g_assert (thread);
858 info = mono_thread_info_current ();
859 g_assert (info);
861 internal = thread->internal_thread;
862 g_assert (internal);
864 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
865 * - the MonoInternalThread TLS key is destroyed: set it to NULL
866 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
867 * - it calls MonoThreadInfoCallbacks.thread_detach
868 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
869 mono_thread_info_set_internal_thread_gchandle (info, mono_gchandle_new_internal ((MonoObject*) internal, FALSE));
871 internal->handle = mono_threads_open_thread_handle (info->handle);
872 internal->native_handle = MONO_NATIVE_THREAD_HANDLE_TO_GPOINTER (mono_threads_open_native_thread_handle (info->native_handle));
873 internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
874 internal->thread_info = info;
875 internal->small_id = info->small_id;
877 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Setting current_object_key to %p", __func__, mono_native_thread_id_get (), internal));
879 SET_CURRENT_OBJECT (internal);
881 domain = mono_object_domain (thread);
883 mono_thread_push_appdomain_ref (domain);
884 if (!mono_domain_set_fast (domain, force_domain)) {
885 mono_thread_pop_appdomain_ref ();
886 goto fail;
889 mono_threads_lock ();
891 if (shutting_down && !force_attach) {
892 mono_threads_unlock ();
893 mono_thread_pop_appdomain_ref ();
894 goto fail;
897 if (threads_starting_up)
898 mono_g_hash_table_remove (threads_starting_up, thread);
900 if (!threads) {
901 threads = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Table");
904 /* We don't need to duplicate thread->handle, because it is
905 * only closed when the thread object is finalized by the GC. */
906 mono_g_hash_table_insert_internal (threads, (gpointer)(gsize)(internal->tid), internal);
908 /* We have to do this here because mono_thread_start_cb
909 * requires that root_domain_thread is set up. */
910 if (thread_static_info.offset || thread_static_info.idx > 0) {
911 /* get the current allocated size */
912 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (thread_static_info.idx, thread_static_info.offset, 0);
913 mono_alloc_static_data (&internal->static_data, offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), TRUE);
916 mono_threads_unlock ();
918 root_domain = mono_get_root_domain ();
920 g_assert (!internal->root_domain_thread);
921 if (domain != root_domain)
922 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, create_thread_object (root_domain, internal));
923 else
924 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, thread);
926 if (domain != root_domain)
927 set_current_thread_for_domain (root_domain, internal, internal->root_domain_thread);
929 set_current_thread_for_domain (domain, internal, thread);
931 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, internal->tid, internal->handle));
933 return TRUE;
935 fail:
936 mono_threads_lock ();
937 if (threads_starting_up)
938 mono_g_hash_table_remove (threads_starting_up, thread);
939 mono_threads_unlock ();
941 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
942 g_error ("%s: failed to get gchandle, info %p", __func__, info);
944 mono_gchandle_free_internal (gchandle);
946 mono_thread_info_unset_internal_thread_gchandle (info);
948 SET_CURRENT_OBJECT(NULL);
950 return FALSE;
953 static void
954 mono_thread_detach_internal (MonoInternalThread *thread)
956 MonoThreadInfo *info;
957 MonoInternalThread *value;
958 gboolean removed;
959 guint32 gchandle;
961 g_assert (mono_thread_internal_is_current (thread));
963 g_assert (thread != NULL);
964 SET_CURRENT_OBJECT (thread);
966 info = thread->thread_info;
967 g_assert (info);
969 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
971 MONO_PROFILER_RAISE (thread_stopping, (thread->tid));
974 * Prevent race condition between thread shutdown and runtime shutdown.
975 * Including all runtime threads in the pending joinable count will make
976 * sure shutdown will wait for it to get onto the joinable thread list before
977 * critical resources have been cleanup (like GC memory). Threads getting onto
978 * the joinable thread list should just about to exit and not blocking a potential
979 * join call. Owner of threads attached to the runtime but not identified as runtime
980 * threads needs to make sure thread detach calls won't race with runtime shutdown.
982 threads_add_pending_joinable_runtime_thread (info);
984 #ifndef HOST_WIN32
985 mono_w32mutex_abandon (thread);
986 #endif
988 mono_gchandle_free_internal (thread->abort_state_handle);
989 thread->abort_state_handle = 0;
991 thread->abort_exc = NULL;
992 thread->current_appcontext = NULL;
994 LOCK_THREAD (thread);
996 thread->state |= ThreadState_Stopped;
997 thread->state &= ~ThreadState_Background;
999 UNLOCK_THREAD (thread);
1002 An interruption request has leaked to cleanup. Adjust the global counter.
1004 This can happen is the abort source thread finds the abortee (this) thread
1005 in unmanaged code. If this thread never trips back to managed code or check
1006 the local flag it will be left set and positively unbalance the global counter.
1008 Leaving the counter unbalanced will cause a performance degradation since all threads
1009 will now keep checking their local flags all the time.
1011 mono_thread_clear_interruption_requested (thread);
1013 mono_threads_lock ();
1015 g_assert (threads);
1017 if (!mono_g_hash_table_lookup_extended (threads, (gpointer)thread->tid, NULL, (gpointer*) &value)) {
1018 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__, thread, thread->tid);
1019 } else if (thread != value) {
1020 /* We have to check whether the thread object for the tid is still the same in the table because the
1021 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
1022 * the table, but with another thread object. */
1023 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__, thread, thread->tid, value, value->tid);
1026 removed = mono_g_hash_table_remove (threads, (gpointer)thread->tid);
1027 g_assert (removed);
1029 mono_threads_unlock ();
1031 /* Don't close the handle here, wait for the object finalizer
1032 * to do it. Otherwise, the following race condition applies:
1034 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
1036 * 2) Some other handle is reassigned the same slot
1038 * 3) Another thread tries to join the first thread, and
1039 * blocks waiting for the reassigned handle to be signalled
1040 * (which might never happen). This is possible, because the
1041 * thread calling Join() still has a reference to the first
1042 * thread's object.
1045 mono_release_type_locks (thread);
1047 MONO_PROFILER_RAISE (thread_stopped, (thread->tid));
1048 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->stack_start_limit)));
1049 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->handle_stack)));
1052 * This will signal async signal handlers that the thread has exited.
1053 * The profiler callback needs this to be set, so it cannot be done earlier.
1055 mono_domain_unset ();
1056 mono_memory_barrier ();
1058 mono_thread_pop_appdomain_ref ();
1060 mono_free_static_data (thread->static_data);
1061 thread->static_data = NULL;
1062 ref_stack_destroy (thread->appdomain_refs);
1063 thread->appdomain_refs = NULL;
1065 g_assert (thread->suspended);
1066 mono_os_event_destroy (thread->suspended);
1067 g_free (thread->suspended);
1068 thread->suspended = NULL;
1070 if (mono_thread_cleanup_fn)
1071 mono_thread_cleanup_fn (thread_get_tid (thread));
1073 mono_memory_barrier ();
1075 if (mono_gc_is_moving ()) {
1076 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
1077 thread->thread_pinning_ref = NULL;
1080 /* There is no more any guarantee that `thread` is alive */
1081 mono_memory_barrier ();
1083 SET_CURRENT_OBJECT (NULL);
1084 mono_domain_unset ();
1086 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
1087 g_error ("%s: failed to get gchandle, info = %p", __func__, info);
1089 mono_gchandle_free_internal (gchandle);
1091 mono_thread_info_unset_internal_thread_gchandle (info);
1093 /* Possibly free synch_cs, if the finalizer for InternalThread already
1094 * ran also. */
1095 dec_longlived_thread_data (thread->longlived);
1097 MONO_PROFILER_RAISE (thread_exited, (thread->tid));
1099 /* Don't need to close the handle to this thread, even though we took a
1100 * reference in mono_thread_attach (), because the GC will do it
1101 * when the Thread object is finalised.
1105 typedef struct {
1106 gint32 ref;
1107 MonoThread *thread;
1108 MonoObject *start_delegate;
1109 MonoObject *start_delegate_arg;
1110 MonoThreadStart start_func;
1111 gpointer start_func_arg;
1112 gboolean force_attach;
1113 gboolean failed;
1114 MonoCoopSem registered;
1115 } StartInfo;
1117 static void
1118 fire_attach_profiler_events (MonoNativeThreadId tid)
1120 MONO_PROFILER_RAISE (thread_started, ((uintptr_t) tid));
1122 MonoThreadInfo *info = mono_thread_info_current ();
1124 MONO_PROFILER_RAISE (gc_root_register, (
1125 (const mono_byte*)(info->stack_start_limit),
1126 (char *) info->stack_end - (char *) info->stack_start_limit,
1127 MONO_ROOT_SOURCE_STACK,
1128 (void *) tid,
1129 "Thread Stack"));
1131 // The handle stack is a pseudo-root similar to the finalizer queues.
1132 MONO_PROFILER_RAISE (gc_root_register, (
1133 (const mono_byte*)info->handle_stack,
1135 MONO_ROOT_SOURCE_HANDLE,
1136 (void *) tid,
1137 "Handle Stack"));
1140 static guint32 WINAPI
1141 start_wrapper_internal (StartInfo *start_info, gsize *stack_ptr)
1143 ERROR_DECL (error);
1144 MonoThreadStart start_func;
1145 void *start_func_arg;
1146 gsize tid;
1148 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1149 * GC stack walk.
1151 MonoThread *thread;
1152 MonoInternalThread *internal;
1153 MonoObject *start_delegate;
1154 MonoObject *start_delegate_arg;
1156 thread = start_info->thread;
1157 internal = thread->internal_thread;
1159 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper", __func__, mono_native_thread_id_get ()));
1161 if (!mono_thread_attach_internal (thread, start_info->force_attach, FALSE)) {
1162 start_info->failed = TRUE;
1164 mono_coop_sem_post (&start_info->registered);
1166 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1167 mono_coop_sem_destroy (&start_info->registered);
1168 g_free (start_info);
1171 return 0;
1174 mono_thread_internal_set_priority (internal, (MonoThreadPriority)internal->priority);
1176 tid = internal->tid;
1178 start_delegate = start_info->start_delegate;
1179 start_delegate_arg = start_info->start_delegate_arg;
1180 start_func = start_info->start_func;
1181 start_func_arg = start_info->start_func_arg;
1183 /* This MUST be called before any managed code can be
1184 * executed, as it calls the callback function that (for the
1185 * jit) sets the lmf marker.
1188 if (mono_thread_start_cb)
1189 mono_thread_start_cb (tid, stack_ptr, (gpointer)start_func);
1191 /* On 2.0 profile (and higher), set explicitly since state might have been
1192 Unknown */
1193 if (internal->apartment_state == ThreadApartmentState_Unknown)
1194 internal->apartment_state = ThreadApartmentState_MTA;
1196 mono_thread_init_apartment_state ();
1198 /* Let the thread that called Start() know we're ready */
1199 mono_coop_sem_post (&start_info->registered);
1201 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1202 mono_coop_sem_destroy (&start_info->registered);
1203 g_free (start_info);
1206 /* start_info is not valid anymore */
1207 start_info = NULL;
1210 * Call this after calling start_notify, since the profiler callback might want
1211 * to lock the thread, and the lock is held by thread_start () which waits for
1212 * start_notify.
1214 fire_attach_profiler_events ((MonoNativeThreadId) tid);
1216 /* if the name was set before starting, we didn't invoke the profiler callback */
1217 // This is a little racy, ok.
1219 if (internal->name.chars) {
1221 LOCK_THREAD (internal);
1223 if (internal->name.chars) {
1224 MONO_PROFILER_RAISE (thread_name, (internal->tid, internal->name.chars));
1225 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), internal->name.chars);
1228 UNLOCK_THREAD (internal);
1231 /* start_func is set only for unmanaged start functions */
1232 if (start_func) {
1233 start_func (start_func_arg);
1234 } else {
1235 #ifdef ENABLE_NETCORE
1236 /* Call a callback in the RuntimeThread class */
1237 g_assert (start_delegate == NULL);
1239 MONO_STATIC_POINTER_INIT (MonoMethod, cb)
1241 cb = mono_class_get_method_from_name_checked (internal->obj.vtable->klass, "StartCallback", 0, 0, error);
1242 g_assert (cb);
1243 mono_error_assert_ok (error);
1245 MONO_STATIC_POINTER_INIT_END (MonoMethod, cb)
1247 mono_runtime_invoke_checked (cb, internal, NULL, error);
1248 #else
1249 void *args [1];
1251 g_assert (start_delegate != NULL);
1253 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1254 args [0] = (gpointer) start_delegate_arg;
1255 mono_runtime_delegate_invoke_checked (start_delegate, args, error);
1256 #endif
1258 if (!is_ok (error)) {
1259 MonoException *ex = mono_error_convert_to_exception (error);
1261 g_assert (ex != NULL);
1262 MonoClass *klass = mono_object_class (ex);
1263 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
1264 !is_threadabort_exception (klass)) {
1265 mono_unhandled_exception_internal (&ex->object);
1266 mono_invoke_unhandled_exception_hook (&ex->object);
1267 g_assert_not_reached ();
1269 } else {
1270 mono_error_cleanup (error);
1274 /* If the thread calls ExitThread at all, this remaining code
1275 * will not be executed, but the main thread will eventually
1276 * call mono_thread_detach_internal() on this thread's behalf.
1279 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
1281 /* Do any cleanup needed for apartment state. This
1282 * cannot be done in mono_thread_detach_internal since
1283 * mono_thread_detach_internal could be called for a
1284 * thread other than the current thread.
1285 * mono_thread_cleanup_apartment_state cleans up apartment
1286 * for the current thead */
1287 mono_thread_cleanup_apartment_state ();
1289 mono_thread_detach_internal (internal);
1291 return 0;
1294 static mono_thread_start_return_t WINAPI
1295 start_wrapper (gpointer data)
1297 StartInfo *start_info;
1298 MonoThreadInfo *info;
1299 gsize res;
1301 start_info = (StartInfo*) data;
1302 g_assert (start_info);
1304 info = mono_thread_info_attach ();
1305 info->runtime_thread = TRUE;
1307 /* Run the actual main function of the thread */
1308 res = start_wrapper_internal (start_info, (gsize*)info->stack_end);
1310 mono_thread_info_exit (res);
1312 g_assert_not_reached ();
1316 * create_thread:
1318 * Common thread creation code.
1319 * LOCKING: Acquires the threads lock.
1321 static gboolean
1322 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
1323 MonoThreadCreateFlags flags, MonoError *error)
1325 StartInfo *start_info = NULL;
1326 MonoNativeThreadId tid;
1327 gboolean ret;
1328 gsize stack_set_size;
1330 if (start_delegate)
1331 g_assert (!start_func && !start_func_arg);
1332 if (start_func)
1333 g_assert (!start_delegate);
1335 if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
1336 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
1337 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1339 if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
1340 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
1341 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1345 * Join joinable threads to prevent running out of threads since the finalizer
1346 * thread might be blocked/backlogged.
1348 mono_threads_join_threads ();
1350 error_init (error);
1352 mono_threads_lock ();
1353 if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
1354 mono_threads_unlock ();
1355 mono_error_set_execution_engine (error, "Couldn't create thread. Runtime is shutting down.");
1356 return FALSE;
1358 if (threads_starting_up == NULL) {
1359 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");
1361 mono_g_hash_table_insert_internal (threads_starting_up, thread, thread);
1362 mono_threads_unlock ();
1364 #ifndef ENABLE_NETCORE
1365 internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
1366 if (internal->threadpool_thread)
1367 mono_thread_set_state (internal, ThreadState_Background);
1368 #endif
1370 internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
1372 start_info = g_new0 (StartInfo, 1);
1373 start_info->ref = 2;
1374 start_info->thread = thread;
1375 start_info->start_delegate = start_delegate;
1376 start_info->start_delegate_arg = thread->start_obj;
1377 start_info->start_func = start_func;
1378 start_info->start_func_arg = start_func_arg;
1379 start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
1380 start_info->failed = FALSE;
1381 mono_coop_sem_init (&start_info->registered, 0);
1383 if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
1384 stack_set_size = default_stacksize_for_thread (internal);
1385 else
1386 stack_set_size = 0;
1388 if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
1389 /* The thread couldn't be created, so set an exception */
1390 mono_threads_lock ();
1391 mono_g_hash_table_remove (threads_starting_up, thread);
1392 mono_threads_unlock ();
1393 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1394 /* ref is not going to be decremented in start_wrapper_internal */
1395 mono_atomic_dec_i32 (&start_info->ref);
1396 ret = FALSE;
1397 goto done;
1400 internal->stack_size = (int) stack_set_size;
1402 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1405 * Wait for the thread to set up its TLS data etc, so
1406 * theres no potential race condition if someone tries
1407 * to look up the data believing the thread has
1408 * started
1411 mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1413 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));
1415 ret = !start_info->failed;
1417 done:
1418 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1419 mono_coop_sem_destroy (&start_info->registered);
1420 g_free (start_info);
1423 return ret;
1427 * mono_thread_new_init:
1429 void
1430 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1432 if (mono_thread_start_cb) {
1433 mono_thread_start_cb (tid, stack_start, func);
1438 * mono_threads_set_default_stacksize:
1440 void
1441 mono_threads_set_default_stacksize (guint32 stacksize)
1443 default_stacksize = stacksize;
1447 * mono_threads_get_default_stacksize:
1449 guint32
1450 mono_threads_get_default_stacksize (void)
1452 return default_stacksize;
1456 * mono_thread_create_internal:
1458 * ARG should not be a GC reference.
1460 MonoInternalThread*
1461 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1463 MonoThread *thread;
1464 MonoInternalThread *internal;
1465 gboolean res;
1467 error_init (error);
1469 internal = create_internal_thread_object ();
1471 thread = create_thread_object (domain, internal);
1473 LOCK_THREAD (internal);
1475 res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1476 (void)res;
1478 UNLOCK_THREAD (internal);
1480 return_val_if_nok (error, NULL);
1481 return internal;
1484 MonoInternalThreadHandle
1485 mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1487 // FIXME invert
1488 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_create_internal (domain, func, arg, flags, error));
1492 * mono_thread_create:
1494 void
1495 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1497 MONO_ENTER_GC_UNSAFE;
1498 ERROR_DECL (error);
1499 if (!mono_thread_create_checked (domain, func, arg, error))
1500 mono_error_cleanup (error);
1501 MONO_EXIT_GC_UNSAFE;
1504 gboolean
1505 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1507 return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1511 * mono_thread_attach:
1513 MonoThread *
1514 mono_thread_attach (MonoDomain *domain)
1516 MonoInternalThread *internal;
1517 MonoThread *thread;
1518 MonoThreadInfo *info;
1519 MonoNativeThreadId tid;
1521 if (mono_thread_internal_current_is_attached ()) {
1522 if (domain != mono_domain_get ())
1523 mono_domain_set_fast (domain, TRUE);
1524 /* Already attached */
1525 return mono_thread_current ();
1528 info = mono_thread_info_attach ();
1529 g_assert (info);
1531 tid=mono_native_thread_id_get ();
1533 if (mono_runtime_get_no_exec ())
1534 return NULL;
1536 internal = create_internal_thread_object ();
1538 thread = create_thread_object (domain, internal);
1540 if (!mono_thread_attach_internal (thread, FALSE, TRUE)) {
1541 /* Mono is shutting down, so just wait for the end */
1542 for (;;)
1543 mono_thread_info_sleep (10000, NULL);
1546 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, internal->handle));
1548 if (mono_thread_attach_cb)
1549 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1551 fire_attach_profiler_events (tid);
1553 return thread;
1557 * mono_threads_attach_tools_thread:
1559 * Attach the current thread as a tool thread. DON'T USE THIS FUNCTION WITHOUT READING ALL DISCLAIMERS.
1561 * A tools thread is a very special kind of thread that needs access to core
1562 * runtime facilities but should not be counted as a regular thread for high
1563 * order facilities such as executing managed code or accessing the managed
1564 * heap.
1566 * This is intended only for low-level utilities than need to be able to use
1567 * some low-level runtime facilities when doing things like resolving
1568 * backtraces in their background processing thread.
1570 * Note in particular that the thread is not fully attached - it does not have
1571 * a "current domain" because it cannot run managed code or interact with
1572 * managed objects. However it can act on some metadata, and use our low-level
1573 * locks and the coop thread state machine (ie GC Safe and GC Unsafe
1574 * transitions make sense).
1576 void
1577 mono_threads_attach_tools_thread (void)
1579 MonoThreadInfo *info = mono_thread_info_attach ();
1580 g_assert (info);
1581 mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NO_GC | MONO_THREAD_INFO_FLAGS_NO_SAMPLE);
1585 * mono_thread_detach:
1587 void
1588 mono_thread_detach (MonoThread *thread)
1590 if (thread)
1591 mono_thread_detach_internal (thread->internal_thread);
1597 * mono_thread_detach_if_exiting:
1599 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1600 * This should be used at the end of embedding code which calls into managed code, and which
1601 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1603 mono_bool
1604 mono_thread_detach_if_exiting (void)
1606 if (mono_thread_info_is_exiting ()) {
1607 MonoInternalThread *thread;
1609 thread = mono_thread_internal_current ();
1610 if (thread) {
1611 // Switch to GC Unsafe thread state before detaching;
1612 // don't expect to undo this switch, hence unbalanced.
1613 gpointer dummy;
1614 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy);
1616 mono_thread_detach_internal (thread);
1617 mono_thread_info_detach ();
1618 return TRUE;
1621 return FALSE;
1624 gboolean
1625 mono_thread_internal_current_is_attached (void)
1627 MonoInternalThread *internal;
1629 internal = GET_CURRENT_OBJECT ();
1630 if (!internal)
1631 return FALSE;
1633 return TRUE;
1637 * mono_thread_exit:
1639 void
1640 mono_thread_exit (void)
1642 MonoInternalThread *thread = mono_thread_internal_current ();
1644 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
1646 mono_thread_detach_internal (thread);
1648 /* we could add a callback here for embedders to use. */
1649 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1650 exit (mono_environment_exitcode_get ());
1652 mono_thread_info_exit (0);
1655 static void
1656 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle)
1658 MonoInternalThread * const internal = create_internal_thread_object ();
1660 internal->state = ThreadState_Unstarted;
1662 int const thread_gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, this_obj_handle), TRUE);
1664 MonoThreadObject *this_obj = MONO_HANDLE_RAW (this_obj_handle);
1666 mono_atomic_cas_ptr ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1668 mono_gchandle_free_internal (thread_gchandle);
1671 #ifndef ENABLE_NETCORE
1672 void
1673 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle, MonoError *error)
1675 mono_thread_construct_internal (this_obj_handle);
1677 #endif
1679 void
1680 ves_icall_System_Threading_Thread_GetCurrentThread (MonoThread *volatile* thread)
1682 *thread = mono_thread_current ();
1685 static MonoInternalThread*
1686 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle)
1688 return MONO_HANDLE_GETVAL(thread_handle, internal_thread); // InternalThreads are always pinned.
1691 static void
1692 mono_error_set_exception_thread_state (MonoError *error, const char *exception_message)
1694 mono_error_set_generic_error (error, "System.Threading", "ThreadStateException", "%s", exception_message);
1697 static void
1698 mono_error_set_exception_thread_not_started_or_dead (MonoError *error)
1700 mono_error_set_exception_thread_state (error, "Thread has not been started, or is dead.");
1703 #ifndef ENABLE_NETCORE
1704 MonoBoolean
1705 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle, MonoObjectHandle start_handle, MonoError *error)
1707 MonoInternalThread *internal;
1708 gboolean res;
1709 MonoThread *this_obj = MONO_HANDLE_RAW (thread_handle);
1710 MonoObject *start = MONO_HANDLE_RAW (start_handle);
1712 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1714 internal = thread_handle_to_internal_ptr (thread_handle);
1716 if (!internal) {
1717 mono_thread_construct_internal (thread_handle);
1718 internal = thread_handle_to_internal_ptr (thread_handle);
1719 g_assert (internal);
1722 LOCK_THREAD (internal);
1724 if ((internal->state & ThreadState_Unstarted) == 0) {
1725 UNLOCK_THREAD (internal);
1726 mono_error_set_exception_thread_state (error, "Thread has already been started.");
1727 return FALSE;
1730 if ((internal->state & ThreadState_Aborted) != 0) {
1731 UNLOCK_THREAD (internal);
1732 return TRUE;
1735 res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
1736 if (!res) {
1737 UNLOCK_THREAD (internal);
1738 return FALSE;
1741 internal->state &= ~ThreadState_Unstarted;
1743 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, thread));
1745 UNLOCK_THREAD (internal);
1746 return TRUE;
1748 #endif
1750 static
1751 void
1752 mono_thread_name_cleanup (MonoThreadName* name)
1754 MonoThreadName const old_name = *name;
1755 memset (name, 0, sizeof (*name));
1756 if (old_name.free)
1757 g_free (old_name.chars);
1761 * This is called from the finalizer of the internal thread object.
1763 void
1764 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle, MonoError *error)
1766 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (this_obj_handle);
1767 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this_obj, this_obj->handle));
1770 * Since threads keep a reference to their thread object while running, by
1771 * the time this function is called, the thread has already exited/detached,
1772 * i.e. mono_thread_detach_internal () has ran. The exception is during
1773 * shutdown, when mono_thread_detach_internal () can be called after this.
1775 if (this_obj->handle) {
1776 mono_threads_close_thread_handle (this_obj->handle);
1777 this_obj->handle = NULL;
1780 mono_threads_close_native_thread_handle (MONO_GPOINTER_TO_NATIVE_THREAD_HANDLE (this_obj->native_handle));
1781 this_obj->native_handle = NULL;
1783 /* Possibly free synch_cs, if the thread already detached also. */
1784 dec_longlived_thread_data (this_obj->longlived);
1786 mono_thread_name_cleanup (&this_obj->name);
1789 static void
1790 mono_sleep_internal (gint32 ms, MonoBoolean allow_interruption, MonoError *error)
1792 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1794 if (mono_thread_current_check_pending_interrupt ())
1795 return;
1797 MonoInternalThread * const thread = mono_thread_internal_current ();
1799 HANDLE_LOOP_PREPARE;
1801 while (TRUE) {
1802 gboolean alerted = FALSE;
1804 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1806 (void)mono_thread_info_sleep (ms, &alerted);
1808 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1810 if (!alerted)
1811 return;
1813 if (allow_interruption) {
1814 SETUP_ICALL_FRAME;
1816 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
1818 const gboolean interrupt = mono_thread_execute_interruption (&exc);
1820 if (interrupt)
1821 mono_set_pending_exception_handle (exc);
1823 CLEAR_ICALL_FRAME;
1825 if (interrupt)
1826 return;
1829 if (ms == MONO_INFINITE_WAIT) // FIXME: !MONO_INFINITE_WAIT
1830 continue;
1831 return;
1835 #ifdef ENABLE_NETCORE
1836 void
1837 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoBoolean allow_interruption, MonoError *error)
1839 return mono_sleep_internal (ms, allow_interruption, error);
1841 #else
1842 void
1843 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoError *error)
1845 return mono_sleep_internal (ms, TRUE, error);
1848 void
1849 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error)
1852 #endif
1854 #ifndef ENABLE_NETCORE
1855 gint32
1856 ves_icall_System_Threading_Thread_GetDomainID (MonoError *error)
1858 return mono_domain_get()->domain_id;
1860 #endif
1863 * mono_thread_get_name_utf8:
1864 * \returns the name of the thread in UTF-8.
1865 * Return NULL if the thread has no name.
1866 * The returned memory is owned by the caller (g_free it).
1868 char *
1869 mono_thread_get_name_utf8 (MonoThread *thread)
1871 if (thread == NULL)
1872 return NULL;
1874 MonoInternalThread *internal = thread->internal_thread;
1876 // This is a little racy, ok.
1878 if (internal == NULL || !internal->name.chars)
1879 return NULL;
1881 LOCK_THREAD (internal);
1883 char *tname = (char*)g_memdup (internal->name.chars, internal->name.length + 1);
1885 UNLOCK_THREAD (internal);
1887 return tname;
1891 * mono_thread_get_managed_id:
1892 * \returns the \c Thread.ManagedThreadId value of \p thread.
1893 * Returns \c -1 if \p thread is NULL.
1895 int32_t
1896 mono_thread_get_managed_id (MonoThread *thread)
1898 if (thread == NULL)
1899 return -1;
1901 MonoInternalThread *internal = thread->internal_thread;
1902 if (internal == NULL)
1903 return -1;
1905 int32_t id = internal->managed_id;
1907 return id;
1910 #ifndef ENABLE_NETCORE
1911 MonoStringHandle
1912 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle, MonoError *error)
1914 // InternalThreads are always pinned, so shallowly coop-handleize.
1915 MonoInternalThread * const this_obj = mono_internal_thread_handle_ptr (thread_handle);
1917 MonoStringHandle str = NULL_HANDLE_STRING;
1919 // This is a little racy, ok.
1921 if (this_obj->name.chars) {
1922 LOCK_THREAD (this_obj);
1924 if (this_obj->name.chars)
1925 str = mono_string_new_utf8_len (mono_domain_get (), this_obj->name.chars, this_obj->name.length, error);
1927 UNLOCK_THREAD (this_obj);
1930 return str;
1932 #endif
1934 // Unusal function:
1935 // - MonoError is optional -- failure is usually not interesting, except the documented failure mode for managed callers.
1936 // - name16 only used on Windows.
1937 // - name8 is either constant, or g_free'able -- this function always takes ownership and never copies.
1939 void
1940 mono_thread_set_name (MonoInternalThread *this_obj,
1941 const char* name8, size_t name8_length, const gunichar2* name16,
1942 MonoSetThreadNameFlags flags, MonoError *error)
1944 // A special case for the threadpool worker.
1945 // It sets the name repeatedly, in case it has changed, per-spec,
1946 // and if not done carefully, this can be a performance problem.
1948 // This is racy but ok. The name will always be valid (or absent).
1949 // In an unusual race, the name might briefly not revert to what the spec requires.
1951 if ((flags & MonoSetThreadNameFlag_RepeatedlyButOptimized) && name8 == this_obj->name.chars) {
1952 // Length is presumed to match.
1953 return;
1956 MonoNativeThreadId tid = 0;
1958 const gboolean constant = !!(flags & MonoSetThreadNameFlag_Constant);
1960 #if HOST_WIN32 // On Windows, if name8 is supplied, then name16 must be also.
1961 g_assert (!name8 || name16);
1962 #endif
1964 LOCK_THREAD (this_obj);
1966 if (flags & MonoSetThreadNameFlag_Reset) {
1967 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1968 } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1969 UNLOCK_THREAD (this_obj);
1971 if (error)
1972 mono_error_set_invalid_operation (error, "%s", "Thread.Name can only be set once.");
1974 if (!constant)
1975 g_free ((char*)name8);
1976 return;
1979 mono_thread_name_cleanup (&this_obj->name);
1981 if (name8) {
1982 this_obj->name.chars = (char*)name8;
1983 this_obj->name.length = name8_length;
1984 this_obj->name.free = !constant;
1985 if (flags & MonoSetThreadNameFlag_Permanent)
1986 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1989 if (!(this_obj->state & ThreadState_Stopped))
1990 tid = thread_get_tid (this_obj);
1992 UNLOCK_THREAD (this_obj);
1994 if (name8 && tid) {
1995 MONO_PROFILER_RAISE (thread_name, ((uintptr_t)tid, name8));
1996 mono_native_thread_set_name (tid, name8);
1999 mono_thread_set_name_windows (this_obj->native_handle, name16);
2001 mono_free (0); // FIXME keep mono-publib.c in use and its functions exported
2004 void
2005 ves_icall_System_Threading_Thread_SetName_icall (MonoInternalThreadHandle thread_handle, const gunichar2* name16, gint32 name16_length, MonoError* error)
2007 long name8_length = 0;
2009 char* name8 = name16 ? g_utf16_to_utf8 (name16, name16_length, NULL, &name8_length, NULL) : NULL;
2011 mono_thread_set_name (mono_internal_thread_handle_ptr (thread_handle),
2012 name8, (gint32)name8_length, name16, MonoSetThreadNameFlag_Permanent, error);
2015 #ifndef ENABLE_NETCORE
2017 * ves_icall_System_Threading_Thread_GetPriority_internal:
2018 * @param this_obj: The MonoInternalThread on which to operate.
2020 * Gets the priority of the given thread.
2021 * @return: The priority of the given thread.
2024 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj, MonoError *error)
2026 gint32 priority;
2028 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
2030 LOCK_THREAD (internal);
2031 priority = internal->priority;
2032 UNLOCK_THREAD (internal);
2034 return priority;
2036 #endif
2039 * ves_icall_System_Threading_Thread_SetPriority_internal:
2040 * @param this_obj: The MonoInternalThread on which to operate.
2041 * @param priority: The priority to set.
2043 * Sets the priority of the given thread.
2045 void
2046 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj, int priority, MonoError *error)
2048 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
2050 LOCK_THREAD (internal);
2051 internal->priority = priority;
2052 if (internal->thread_info != NULL)
2053 mono_thread_internal_set_priority (internal, (MonoThreadPriority)priority);
2054 UNLOCK_THREAD (internal);
2057 /* If the array is already in the requested domain, we just return it,
2058 otherwise we return a copy in that domain. */
2059 static MonoArrayHandle
2060 byte_array_to_domain (MonoArrayHandle arr, MonoDomain *domain, MonoError *error)
2062 HANDLE_FUNCTION_ENTER ()
2064 if (MONO_HANDLE_IS_NULL (arr))
2065 return MONO_HANDLE_NEW (MonoArray, NULL);
2067 if (MONO_HANDLE_DOMAIN (arr) == domain)
2068 return arr;
2070 size_t const size = mono_array_handle_length (arr);
2072 // Capture arrays into common representation for repetitious code.
2073 // These two variables could also be an array of size 2 and
2074 // repetition implemented with a loop.
2075 struct {
2076 MonoArrayHandle handle;
2077 gpointer p;
2078 guint gchandle;
2080 source = { arr },
2081 dest = { mono_array_new_handle (domain, mono_defaults.byte_class, size, error) };
2082 goto_if_nok (error, exit);
2084 // Pin both arrays.
2085 source.p = mono_array_handle_pin_with_size (source.handle, size, 0, &source.gchandle);
2086 dest.p = mono_array_handle_pin_with_size (dest.handle, size, 0, &dest.gchandle);
2088 memmove (dest.p, source.p, size);
2089 exit:
2090 // Unpin both arrays.
2091 mono_gchandle_free_internal (source.gchandle);
2092 mono_gchandle_free_internal (dest.gchandle);
2094 HANDLE_FUNCTION_RETURN_REF (MonoArray, dest.handle)
2097 #ifndef ENABLE_NETCORE
2098 MonoArrayHandle
2099 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr, MonoError *error)
2101 return byte_array_to_domain (arr, mono_get_root_domain (), error);
2104 MonoArrayHandle
2105 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr, MonoError *error)
2107 return byte_array_to_domain (arr, mono_domain_get (), error);
2109 #endif
2112 * mono_thread_current:
2114 MonoThread *
2115 mono_thread_current (void)
2117 #ifdef ENABLE_NETCORE
2118 return mono_thread_internal_current ();
2119 #else
2120 MonoDomain *domain = mono_domain_get ();
2121 MonoInternalThread *internal = mono_thread_internal_current ();
2122 MonoThread **current_thread_ptr;
2124 g_assert (internal);
2125 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2127 if (!*current_thread_ptr) {
2128 g_assert (domain != mono_get_root_domain ());
2129 *current_thread_ptr = create_thread_object (domain, internal);
2131 return *current_thread_ptr;
2132 #endif
2135 static MonoThreadObjectHandle
2136 mono_thread_current_handle (void)
2138 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
2141 /* Return the thread object belonging to INTERNAL in the current domain */
2142 static MonoThread *
2143 mono_thread_current_for_thread (MonoInternalThread *internal)
2145 #ifdef ENABLE_NETCORE
2146 return mono_thread_internal_current ();
2147 #else
2148 MonoDomain *domain = mono_domain_get ();
2149 MonoThread **current_thread_ptr;
2151 g_assert (internal);
2152 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2154 if (!*current_thread_ptr) {
2155 g_assert (domain != mono_get_root_domain ());
2156 *current_thread_ptr = create_thread_object (domain, internal);
2158 return *current_thread_ptr;
2159 #endif
2162 MonoInternalThread*
2163 mono_thread_internal_current (void)
2165 MonoInternalThread *res = GET_CURRENT_OBJECT ();
2166 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
2167 return res;
2170 MonoInternalThreadHandle
2171 mono_thread_internal_current_handle (void)
2173 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_internal_current ());
2176 static MonoThreadInfoWaitRet
2177 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
2179 MonoThreadInfoWaitRet ret;
2180 gint32 wait = ms;
2182 const gint64 start = (ms == -1) ? 0 : mono_msec_ticks ();
2183 while (TRUE) {
2184 MONO_ENTER_GC_SAFE;
2185 ret = mono_thread_info_wait_one_handle (thread_to_join, wait, TRUE);
2186 MONO_EXIT_GC_SAFE;
2188 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
2189 return ret;
2191 MonoException *exc = mono_thread_execute_interruption_ptr ();
2192 if (exc) {
2193 mono_error_set_exception_instance (error, exc);
2194 return ret;
2197 if (ms == -1)
2198 continue;
2200 /* Re-calculate ms according to the time passed */
2201 const gint32 diff_ms = (gint32)(mono_msec_ticks () - start);
2202 if (diff_ms >= ms) {
2203 ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
2204 return ret;
2206 wait = ms - diff_ms;
2209 return ret;
2212 MonoBoolean
2213 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle, int ms, MonoError *error)
2215 if (mono_thread_current_check_pending_interrupt ())
2216 return FALSE;
2218 // Internal threads are pinned so shallow coop/handle.
2219 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2220 MonoThreadHandle *handle = thread->handle;
2221 MonoInternalThread *cur_thread = mono_thread_internal_current ();
2222 gboolean ret = FALSE;
2224 LOCK_THREAD (thread);
2226 if ((thread->state & ThreadState_Unstarted) != 0) {
2227 UNLOCK_THREAD (thread);
2229 mono_error_set_exception_thread_state (error, "Thread has not been started.");
2230 return FALSE;
2233 UNLOCK_THREAD (thread);
2235 if (ms == -1)
2236 ms = MONO_INFINITE_WAIT;
2237 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
2239 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
2241 ret = mono_join_uninterrupted (handle, ms, error);
2243 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
2245 if (ret == MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
2246 THREAD_DEBUG (g_message ("%s: join successful", __func__));
2248 mono_error_assert_ok (error);
2250 /* Wait for the thread to really exit */
2251 MonoNativeThreadId tid = thread_get_tid (thread);
2252 mono_thread_join ((gpointer)(gsize)tid);
2254 return TRUE;
2257 THREAD_DEBUG (g_message ("%s: join failed", __func__));
2259 return FALSE;
2262 #define MANAGED_WAIT_FAILED 0x7fffffff
2264 static gint32
2265 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
2267 if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
2268 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
2269 } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
2270 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
2271 } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
2272 return WAIT_IO_COMPLETION;
2273 } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
2274 return WAIT_TIMEOUT;
2275 } else if (val == MONO_W32HANDLE_WAIT_RET_TOO_MANY_POSTS) {
2276 return WAIT_TOO_MANY_POSTS;
2277 } else if (val == MONO_W32HANDLE_WAIT_RET_NOT_OWNED_BY_CALLER) {
2278 return WAIT_NOT_OWNED_BY_CALLER;
2279 } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
2280 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2281 return MANAGED_WAIT_FAILED;
2282 } else {
2283 g_error ("%s: unknown val value %d", __func__, val);
2287 gint32
2288 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
2290 /* Do this WaitSleepJoin check before creating objects */
2291 if (mono_thread_current_check_pending_interrupt ())
2292 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2294 MonoInternalThread * const thread = mono_thread_internal_current ();
2296 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2298 gint64 start = 0;
2300 if (timeout == -1)
2301 timeout = MONO_INFINITE_WAIT;
2302 if (timeout != MONO_INFINITE_WAIT)
2303 start = mono_msec_ticks ();
2305 guint32 timeoutLeft = timeout;
2307 MonoW32HandleWaitRet ret;
2309 HANDLE_LOOP_PREPARE;
2311 for (;;) {
2313 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2314 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE, error);
2316 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
2317 break;
2319 SETUP_ICALL_FRAME;
2321 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
2323 const gboolean interrupt = mono_thread_execute_interruption (&exc);
2325 if (interrupt)
2326 mono_error_set_exception_handle (error, exc);
2328 CLEAR_ICALL_FRAME;
2330 if (interrupt)
2331 break;
2333 if (timeout != MONO_INFINITE_WAIT) {
2334 gint64 const elapsed = mono_msec_ticks () - start;
2335 if (elapsed >= timeout) {
2336 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
2337 break;
2340 timeoutLeft = timeout - elapsed;
2344 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2346 return map_native_wait_result_to_managed (ret, numhandles);
2349 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2350 gint32
2351 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
2353 MonoW32HandleWaitRet ret;
2354 MonoInternalThread *thread = mono_thread_internal_current ();
2356 if (ms == -1)
2357 ms = MONO_INFINITE_WAIT;
2359 if (mono_thread_current_check_pending_interrupt ())
2360 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2362 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2364 ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
2366 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2368 return map_native_wait_result_to_managed (ret, 1);
2371 #endif
2373 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
2375 return mono_atomic_inc_i32 (location);
2378 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
2380 #if SIZEOF_VOID_P == 4
2381 if (G_UNLIKELY ((size_t)location & 0x7)) {
2382 gint64 ret;
2383 mono_interlocked_lock ();
2384 (*location)++;
2385 ret = *location;
2386 mono_interlocked_unlock ();
2387 return ret;
2389 #endif
2390 return mono_atomic_inc_i64 (location);
2393 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
2395 return mono_atomic_dec_i32(location);
2398 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
2400 #if SIZEOF_VOID_P == 4
2401 if (G_UNLIKELY ((size_t)location & 0x7)) {
2402 gint64 ret;
2403 mono_interlocked_lock ();
2404 (*location)--;
2405 ret = *location;
2406 mono_interlocked_unlock ();
2407 return ret;
2409 #endif
2410 return mono_atomic_dec_i64 (location);
2413 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2415 return mono_atomic_xchg_i32(location, value);
2418 void
2419 ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*res)
2421 // Coop-equivalency here via pointers to pointers.
2422 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2424 // This also handles generic T case, T constrained to a class.
2426 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2427 // presently breaks identity of location and would therefore never work.
2429 *res = (MonoObject*)mono_atomic_xchg_ptr ((volatile gpointer*)location, *value);
2430 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2433 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2435 return mono_atomic_xchg_ptr(location, value);
2438 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2440 IntFloatUnion val, ret;
2442 val.fval = value;
2443 ret.ival = mono_atomic_xchg_i32((gint32 *) location, val.ival);
2445 return ret.fval;
2448 gint64
2449 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2451 #if SIZEOF_VOID_P == 4
2452 if (G_UNLIKELY ((size_t)location & 0x7)) {
2453 gint64 ret;
2454 mono_interlocked_lock ();
2455 ret = *location;
2456 *location = value;
2457 mono_interlocked_unlock ();
2458 return ret;
2460 #endif
2461 return mono_atomic_xchg_i64 (location, value);
2464 gdouble
2465 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2467 LongDoubleUnion val, ret;
2469 val.fval = value;
2470 ret.ival = (gint64)mono_atomic_xchg_i64((gint64 *) location, val.ival);
2472 return ret.fval;
2475 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2477 return mono_atomic_cas_i32(location, value, comparand);
2480 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2482 gint32 r = mono_atomic_cas_i32(location, value, comparand);
2483 *success = r == comparand;
2484 return r;
2487 void
2488 ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*comparand, MonoObject *volatile* res)
2490 // Coop-equivalency here via pointers to pointers.
2491 // value and comparand and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2493 // This also handles generic T case, T constrained to a class.
2495 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2496 // presently breaks identity of location and would therefore never work.
2498 *res = (MonoObject*)mono_atomic_cas_ptr ((volatile gpointer*)location, *value, *comparand);
2499 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2502 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2504 return mono_atomic_cas_ptr(location, value, comparand);
2507 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2509 IntFloatUnion val, ret, cmp;
2511 val.fval = value;
2512 cmp.fval = comparand;
2513 ret.ival = mono_atomic_cas_i32((gint32 *) location, val.ival, cmp.ival);
2515 return ret.fval;
2518 gdouble
2519 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2521 #if SIZEOF_VOID_P == 8
2522 LongDoubleUnion val, comp, ret;
2524 val.fval = value;
2525 comp.fval = comparand;
2526 ret.ival = (gint64)mono_atomic_cas_ptr((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2528 return ret.fval;
2529 #else
2530 gdouble old;
2532 mono_interlocked_lock ();
2533 old = *location;
2534 if (old == comparand)
2535 *location = value;
2536 mono_interlocked_unlock ();
2538 return old;
2539 #endif
2542 gint64
2543 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2545 #if SIZEOF_VOID_P == 4
2546 if (G_UNLIKELY ((size_t)location & 0x7)) {
2547 gint64 old;
2548 mono_interlocked_lock ();
2549 old = *location;
2550 if (old == comparand)
2551 *location = value;
2552 mono_interlocked_unlock ();
2553 return old;
2555 #endif
2556 return mono_atomic_cas_i64 (location, value, comparand);
2559 gint32
2560 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2562 return mono_atomic_add_i32 (location, value);
2565 gint64
2566 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2568 #if SIZEOF_VOID_P == 4
2569 if (G_UNLIKELY ((size_t)location & 0x7)) {
2570 gint64 ret;
2571 mono_interlocked_lock ();
2572 *location += value;
2573 ret = *location;
2574 mono_interlocked_unlock ();
2575 return ret;
2577 #endif
2578 return mono_atomic_add_i64 (location, value);
2581 gint64
2582 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2584 #if SIZEOF_VOID_P == 4
2585 if (G_UNLIKELY ((size_t)location & 0x7)) {
2586 gint64 ret;
2587 mono_interlocked_lock ();
2588 ret = *location;
2589 mono_interlocked_unlock ();
2590 return ret;
2592 #endif
2593 return mono_atomic_load_i64 (location);
2596 void
2597 ves_icall_System_Threading_Interlocked_MemoryBarrierProcessWide (void)
2599 mono_memory_barrier_process_wide ();
2602 void
2603 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2605 mono_memory_barrier ();
2608 void
2609 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj, guint32 state, MonoError *error)
2611 // InternalThreads are always pinned, so shallowly coop-handleize.
2612 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj), (MonoThreadState)state);
2615 void
2616 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle, guint32 state, MonoError *error)
2618 // InternalThreads are always pinned, so shallowly coop-handleize.
2619 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle), (MonoThreadState)state);
2622 guint32
2623 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle, MonoError *error)
2625 // InternalThreads are always pinned, so shallowly coop-handleize.
2626 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (thread_handle);
2628 guint32 state;
2630 LOCK_THREAD (this_obj);
2632 state = this_obj->state;
2634 UNLOCK_THREAD (this_obj);
2636 return state;
2639 void
2640 ves_icall_System_Threading_Thread_Interrupt_internal (MonoThreadObjectHandle thread_handle, MonoError *error)
2642 // Internal threads are pinned so shallow coop/handle.
2643 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2644 MonoInternalThread * const current = mono_thread_internal_current ();
2646 LOCK_THREAD (thread);
2648 thread->thread_interrupt_requested = TRUE;
2649 gboolean const throw_ = current != thread && (thread->state & ThreadState_WaitSleepJoin);
2651 UNLOCK_THREAD (thread);
2653 if (throw_)
2654 async_abort_internal (thread, FALSE);
2658 * mono_thread_current_check_pending_interrupt:
2659 * Checks if there's a interruption request and set the pending exception if so.
2660 * \returns true if a pending exception was set
2662 gboolean
2663 mono_thread_current_check_pending_interrupt (void)
2665 MonoInternalThread *thread = mono_thread_internal_current ();
2666 gboolean throw_ = FALSE;
2668 LOCK_THREAD (thread);
2670 if (thread->thread_interrupt_requested) {
2671 throw_ = TRUE;
2672 thread->thread_interrupt_requested = FALSE;
2675 UNLOCK_THREAD (thread);
2677 if (throw_) {
2678 ERROR_DECL (error);
2679 mono_error_set_thread_interrupted (error);
2680 mono_error_set_pending_exception (error);
2682 return throw_;
2685 static gboolean
2686 request_thread_abort (MonoInternalThread *thread, MonoObjectHandle *state, gboolean appdomain_unload)
2687 // state is a pointer to a handle in order to be optional,
2688 // and be passed unspecified from functions not using handles.
2689 // When raw pointers is gone, it need not be a pointer,
2690 // though this would still work efficiently.
2692 LOCK_THREAD (thread);
2694 /* With self abort we always throw a new exception */
2695 if (thread == mono_thread_internal_current ())
2696 thread->abort_exc = NULL;
2698 if (thread->state & (ThreadState_AbortRequested | ThreadState_Stopped))
2700 UNLOCK_THREAD (thread);
2701 return FALSE;
2704 if ((thread->state & ThreadState_Unstarted) != 0) {
2705 thread->state |= ThreadState_Aborted;
2706 UNLOCK_THREAD (thread);
2707 return FALSE;
2710 thread->state |= ThreadState_AbortRequested;
2711 if (appdomain_unload)
2712 thread->flags |= MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2713 else
2714 thread->flags &= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2716 mono_gchandle_free_internal (thread->abort_state_handle);
2717 thread->abort_state_handle = 0;
2720 if (state && !MONO_HANDLE_IS_NULL (*state)) {
2721 thread->abort_state_handle = mono_gchandle_from_handle (*state, FALSE);
2722 g_assert (thread->abort_state_handle);
2725 thread->abort_exc = NULL;
2727 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));
2729 /* During shutdown, we can't wait for other threads */
2730 if (!shutting_down)
2731 /* Make sure the thread is awake */
2732 mono_thread_resume (thread);
2734 UNLOCK_THREAD (thread);
2735 return TRUE;
2738 #ifndef ENABLE_NETCORE
2739 void
2740 ves_icall_System_Threading_Thread_Abort (MonoInternalThreadHandle thread_handle, MonoObjectHandle state, MonoError *error)
2742 // InternalThreads are always pinned, so shallowly coop-handleize.
2743 MonoInternalThread * const thread = mono_internal_thread_handle_ptr (thread_handle);
2744 gboolean is_self = thread == mono_thread_internal_current ();
2746 /* For self aborts we always process the abort */
2747 if (!request_thread_abort (thread, &state, FALSE) && !is_self)
2748 return;
2750 if (is_self) {
2751 self_abort_internal (error);
2752 } else {
2753 async_abort_internal (thread, TRUE);
2756 #endif
2759 * mono_thread_internal_abort:
2760 * Request thread \p thread to be aborted.
2761 * \p thread MUST NOT be the current thread.
2763 void
2764 mono_thread_internal_abort (MonoInternalThread *thread, gboolean appdomain_unload)
2766 g_assert (thread != mono_thread_internal_current ());
2768 if (!request_thread_abort (thread, NULL, appdomain_unload))
2769 return;
2770 async_abort_internal (thread, TRUE);
2773 #ifndef ENABLE_NETCORE
2774 void
2775 ves_icall_System_Threading_Thread_ResetAbort (MonoThreadObjectHandle this_obj, MonoError *error)
2777 MonoInternalThread *thread = mono_thread_internal_current ();
2778 gboolean was_aborting, is_domain_abort;
2780 LOCK_THREAD (thread);
2781 was_aborting = thread->state & ThreadState_AbortRequested;
2782 is_domain_abort = thread->flags & MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2784 if (was_aborting && !is_domain_abort)
2785 thread->state &= ~ThreadState_AbortRequested;
2786 UNLOCK_THREAD (thread);
2788 if (!was_aborting) {
2789 mono_error_set_exception_thread_state (error, "Unable to reset abort because no abort was requested");
2790 return;
2791 } else if (is_domain_abort) {
2792 /* Silently ignore abort resets in unloading appdomains */
2793 return;
2796 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2797 thread->abort_exc = NULL;
2798 mono_gchandle_free_internal (thread->abort_state_handle);
2799 /* This is actually not necessary - the handle
2800 only counts if the exception is set */
2801 thread->abort_state_handle = 0;
2803 #endif
2805 void
2806 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2808 LOCK_THREAD (thread);
2810 thread->state &= ~ThreadState_AbortRequested;
2812 if (thread->abort_exc) {
2813 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2814 thread->abort_exc = NULL;
2815 mono_gchandle_free_internal (thread->abort_state_handle);
2816 /* This is actually not necessary - the handle
2817 only counts if the exception is set */
2818 thread->abort_state_handle = 0;
2821 UNLOCK_THREAD (thread);
2824 #ifndef ENABLE_NETCORE
2825 MonoObjectHandle
2826 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThreadObjectHandle this_obj, MonoError *error)
2828 MonoInternalThread *thread = thread_handle_to_internal_ptr (this_obj);
2830 if (!thread->abort_state_handle)
2831 return NULL_HANDLE; // No state. No error.
2833 // Convert gc handle to coop handle.
2834 MonoObjectHandle state = mono_gchandle_get_target_handle (thread->abort_state_handle);
2835 g_assert (MONO_HANDLE_BOOL (state));
2837 MonoDomain *domain = mono_domain_get ();
2838 if (MONO_HANDLE_DOMAIN (state) == domain)
2839 return state; // No need to cross domain, return state directly.
2841 // Attempt move state cross-domain.
2842 MonoObjectHandle deserialized = mono_object_xdomain_representation (state, domain, error);
2844 // If deserialized is null, there must be an error, and vice versa.
2845 g_assert (is_ok (error) == MONO_HANDLE_BOOL (deserialized));
2847 if (MONO_HANDLE_BOOL (deserialized))
2848 return deserialized; // Cross-domain serialization succeeded. Return it.
2850 // Wrap error in InvalidOperationException.
2851 ERROR_DECL (error_creating_exception);
2852 MonoExceptionHandle invalid_op_exc = mono_exception_new_invalid_operation (
2853 "Thread.ExceptionState cannot access an ExceptionState from a different AppDomain", error_creating_exception);
2854 mono_error_assert_ok (error_creating_exception);
2855 g_assert (!is_ok (error) && 1);
2856 MONO_HANDLE_SET (invalid_op_exc, inner_ex, mono_error_convert_to_exception_handle (error));
2857 error_init_reuse (error);
2858 mono_error_set_exception_handle (error, invalid_op_exc);
2859 g_assert (!is_ok (error) && 2);
2861 // There is state, but we failed to return it.
2862 return NULL_HANDLE;
2864 #endif
2866 static gboolean
2867 mono_thread_suspend (MonoInternalThread *thread)
2869 LOCK_THREAD (thread);
2871 if (thread->state & (ThreadState_Unstarted | ThreadState_Aborted | ThreadState_Stopped))
2873 UNLOCK_THREAD (thread);
2874 return FALSE;
2877 if (thread->state & (ThreadState_Suspended | ThreadState_SuspendRequested | ThreadState_AbortRequested))
2879 UNLOCK_THREAD (thread);
2880 return TRUE;
2883 thread->state |= ThreadState_SuspendRequested;
2884 MONO_ENTER_GC_SAFE;
2885 mono_os_event_reset (thread->suspended);
2886 MONO_EXIT_GC_SAFE;
2888 if (thread == mono_thread_internal_current ()) {
2889 /* calls UNLOCK_THREAD (thread) */
2890 self_suspend_internal ();
2891 } else {
2892 /* calls UNLOCK_THREAD (thread) */
2893 async_suspend_internal (thread, FALSE);
2896 return TRUE;
2899 #ifndef ENABLE_NETCORE
2900 void
2901 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj, MonoError *error)
2903 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj)))
2904 mono_error_set_exception_thread_not_started_or_dead (error);
2907 #endif
2909 /* LOCKING: LOCK_THREAD(thread) must be held */
2910 static gboolean
2911 mono_thread_resume (MonoInternalThread *thread)
2913 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2914 // g_async_safe_printf ("RESUME (1) thread %p\n", thread_get_tid (thread));
2915 thread->state &= ~ThreadState_SuspendRequested;
2916 MONO_ENTER_GC_SAFE;
2917 mono_os_event_set (thread->suspended);
2918 MONO_EXIT_GC_SAFE;
2919 return TRUE;
2922 if ((thread->state & ThreadState_Suspended) == 0 ||
2923 (thread->state & ThreadState_Unstarted) != 0 ||
2924 (thread->state & ThreadState_Aborted) != 0 ||
2925 (thread->state & ThreadState_Stopped) != 0)
2927 // g_async_safe_printf ("RESUME (2) thread %p\n", thread_get_tid (thread));
2928 return FALSE;
2931 // g_async_safe_printf ("RESUME (3) thread %p\n", thread_get_tid (thread));
2933 MONO_ENTER_GC_SAFE;
2934 mono_os_event_set (thread->suspended);
2935 MONO_EXIT_GC_SAFE;
2937 if (!thread->self_suspended) {
2938 UNLOCK_THREAD (thread);
2940 /* Awake the thread */
2941 if (!mono_thread_info_resume (thread_get_tid (thread)))
2942 return FALSE;
2944 LOCK_THREAD (thread);
2947 thread->state &= ~ThreadState_Suspended;
2949 return TRUE;
2952 #ifndef ENABLE_NETCORE
2953 void
2954 ves_icall_System_Threading_Thread_Resume (MonoThreadObjectHandle thread_handle, MonoError *error)
2956 // Internal threads are pinned so shallow coop/handle.
2957 MonoInternalThread * const internal_thread = thread_handle_to_internal_ptr (thread_handle);
2958 gboolean exception = FALSE;
2960 if (!internal_thread) {
2961 exception = TRUE;
2962 } else {
2963 LOCK_THREAD (internal_thread);
2964 if (!mono_thread_resume (internal_thread))
2965 exception = TRUE;
2966 UNLOCK_THREAD (internal_thread);
2969 if (exception)
2970 mono_error_set_exception_thread_not_started_or_dead (error);
2972 #endif
2974 gboolean
2975 mono_threads_is_critical_method (MonoMethod *method)
2977 switch (method->wrapper_type) {
2978 case MONO_WRAPPER_RUNTIME_INVOKE:
2979 case MONO_WRAPPER_XDOMAIN_INVOKE:
2980 case MONO_WRAPPER_XDOMAIN_DISPATCH:
2981 return TRUE;
2983 return FALSE;
2986 static gboolean
2987 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2989 if (managed)
2990 return TRUE;
2992 if (mono_threads_is_critical_method (m)) {
2993 *((gboolean*)data) = TRUE;
2994 return TRUE;
2996 return FALSE;
2999 static gboolean
3000 is_running_protected_wrapper (void)
3002 gboolean found = FALSE;
3003 mono_stack_walk (find_wrapper, &found);
3004 return found;
3008 * mono_thread_stop:
3010 void
3011 mono_thread_stop (MonoThread *thread)
3013 MonoInternalThread *internal = thread->internal_thread;
3015 if (!request_thread_abort (internal, NULL, FALSE))
3016 return;
3018 if (internal == mono_thread_internal_current ()) {
3019 ERROR_DECL (error);
3020 self_abort_internal (error);
3022 This function is part of the embeding API and has no way to return the exception
3023 to be thrown. So what we do is keep the old behavior and raise the exception.
3025 mono_error_raise_exception_deprecated (error); /* OK to throw, see note */
3026 } else {
3027 async_abort_internal (internal, TRUE);
3031 gint8
3032 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
3034 gint8 tmp = *(volatile gint8 *)ptr;
3035 mono_memory_barrier ();
3036 return tmp;
3039 gint16
3040 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
3042 gint16 tmp = *(volatile gint16 *)ptr;
3043 mono_memory_barrier ();
3044 return tmp;
3047 gint32
3048 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
3050 gint32 tmp = *(volatile gint32 *)ptr;
3051 mono_memory_barrier ();
3052 return tmp;
3055 gint64
3056 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
3058 gint64 tmp = *(volatile gint64 *)ptr;
3059 mono_memory_barrier ();
3060 return tmp;
3063 void *
3064 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
3066 volatile void *tmp = *(volatile void **)ptr;
3067 mono_memory_barrier ();
3068 return (void *) tmp;
3071 void *
3072 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
3074 volatile MonoObject *tmp = *(volatile MonoObject **)ptr;
3075 mono_memory_barrier ();
3076 return (MonoObject *) tmp;
3079 double
3080 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
3082 double tmp = *(volatile double *)ptr;
3083 mono_memory_barrier ();
3084 return tmp;
3087 float
3088 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
3090 float tmp = *(volatile float *)ptr;
3091 mono_memory_barrier ();
3092 return tmp;
3095 gint64
3096 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
3098 #if SIZEOF_VOID_P == 4
3099 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3100 gint64 val;
3101 mono_interlocked_lock ();
3102 val = *(gint64*)ptr;
3103 mono_interlocked_unlock ();
3104 return val;
3106 #endif
3107 return mono_atomic_load_i64 ((volatile gint64 *)ptr);
3110 guint64
3111 ves_icall_System_Threading_Volatile_ReadU8 (void *ptr)
3113 #if SIZEOF_VOID_P == 4
3114 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3115 guint64 val;
3116 mono_interlocked_lock ();
3117 val = *(guint64*)ptr;
3118 mono_interlocked_unlock ();
3119 return val;
3121 #endif
3122 return (guint64)mono_atomic_load_i64 ((volatile gint64 *)ptr);
3125 double
3126 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
3128 LongDoubleUnion u;
3130 #if SIZEOF_VOID_P == 4
3131 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3132 double val;
3133 mono_interlocked_lock ();
3134 val = *(double*)ptr;
3135 mono_interlocked_unlock ();
3136 return val;
3138 #endif
3140 u.ival = mono_atomic_load_i64 ((volatile gint64 *)ptr);
3142 return u.fval;
3145 void
3146 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
3148 mono_memory_barrier ();
3149 *(volatile gint8 *)ptr = value;
3152 void
3153 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
3155 mono_memory_barrier ();
3156 *(volatile gint16 *)ptr = value;
3159 void
3160 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
3162 mono_memory_barrier ();
3163 *(volatile gint32 *)ptr = value;
3166 void
3167 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
3169 mono_memory_barrier ();
3170 *(volatile gint64 *)ptr = value;
3173 void
3174 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
3176 mono_memory_barrier ();
3177 *(volatile void **)ptr = value;
3180 void
3181 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
3183 mono_memory_barrier ();
3184 mono_gc_wbarrier_generic_store_internal (ptr, value);
3187 void
3188 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
3190 mono_memory_barrier ();
3191 *(volatile double *)ptr = value;
3194 void
3195 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
3197 mono_memory_barrier ();
3198 *(volatile float *)ptr = value;
3201 void
3202 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
3204 #if SIZEOF_VOID_P == 4
3205 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3206 mono_interlocked_lock ();
3207 *(gint64*)ptr = value;
3208 mono_interlocked_unlock ();
3209 return;
3211 #endif
3213 mono_atomic_store_i64 ((volatile gint64 *)ptr, value);
3216 void
3217 ves_icall_System_Threading_Volatile_WriteU8 (void *ptr, guint64 value)
3219 #if SIZEOF_VOID_P == 4
3220 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3221 mono_interlocked_lock ();
3222 *(guint64*)ptr = value;
3223 mono_interlocked_unlock ();
3224 return;
3226 #endif
3228 mono_atomic_store_i64 ((volatile gint64 *)ptr, (gint64)value);
3231 void
3232 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
3234 LongDoubleUnion u;
3236 #if SIZEOF_VOID_P == 4
3237 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3238 mono_interlocked_lock ();
3239 *(double*)ptr = value;
3240 mono_interlocked_unlock ();
3241 return;
3243 #endif
3245 u.fval = value;
3247 mono_atomic_store_i64 ((volatile gint64 *)ptr, u.ival);
3250 static void
3251 free_context (void *user_data)
3253 ContextStaticData *data = (ContextStaticData*)user_data;
3255 mono_threads_lock ();
3258 * There is no guarantee that, by the point this reference queue callback
3259 * has been invoked, the GC handle associated with the object will fail to
3260 * resolve as one might expect. So if we don't free and remove the GC
3261 * handle here, free_context_static_data_helper () could end up resolving
3262 * a GC handle to an actually-dead context which would contain a pointer
3263 * to an already-freed static data segment, resulting in a crash when
3264 * accessing it.
3266 g_hash_table_remove (contexts, GUINT_TO_POINTER (data->gc_handle));
3268 mono_threads_unlock ();
3270 mono_gchandle_free_internal (data->gc_handle);
3271 mono_free_static_data (data->static_data);
3272 g_free (data);
3275 void
3276 mono_threads_register_app_context (MonoAppContextHandle ctx, MonoError *error)
3278 error_init (error);
3279 mono_threads_lock ();
3281 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3283 if (!contexts)
3284 contexts = g_hash_table_new (NULL, NULL);
3286 if (!context_queue)
3287 context_queue = mono_gc_reference_queue_new_internal (free_context);
3289 gpointer gch = GUINT_TO_POINTER (mono_gchandle_new_weakref_from_handle (MONO_HANDLE_CAST (MonoObject, ctx)));
3290 g_hash_table_insert (contexts, gch, gch);
3293 * We use this intermediate structure to contain a duplicate pointer to
3294 * the static data because we can't rely on being able to resolve the GC
3295 * handle in the reference queue callback.
3297 ContextStaticData *data = g_new0 (ContextStaticData, 1);
3298 data->gc_handle = GPOINTER_TO_UINT (gch);
3299 MONO_HANDLE_SETVAL (ctx, data, ContextStaticData*, data);
3301 context_adjust_static_data (ctx);
3302 mono_gc_reference_queue_add_handle (context_queue, ctx, data);
3304 mono_threads_unlock ();
3306 MONO_PROFILER_RAISE (context_loaded, (MONO_HANDLE_RAW (ctx)));
3309 #ifndef ENABLE_NETCORE
3310 void
3311 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx, MonoError *error)
3313 mono_threads_register_app_context (ctx, error);
3315 #endif
3317 void
3318 mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error)
3321 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3322 * cleanup in exceptional circumstances, we don't actually do any
3323 * cleanup work here. We instead do this via a reference queue.
3326 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3328 MONO_PROFILER_RAISE (context_unloaded, (ctx));
3331 #ifndef ENABLE_NETCORE
3332 void
3333 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx, MonoError *error)
3335 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_release_app_context */
3337 #endif
3339 void mono_thread_init (MonoThreadStartCB start_cb,
3340 MonoThreadAttachCB attach_cb)
3342 mono_coop_mutex_init_recursive (&threads_mutex);
3344 #if SIZEOF_VOID_P == 4
3345 mono_os_mutex_init (&interlocked_mutex);
3346 #endif
3347 mono_coop_mutex_init_recursive(&joinable_threads_mutex);
3349 mono_os_event_init (&background_change_event, FALSE);
3351 mono_coop_cond_init (&pending_native_thread_join_calls_event);
3352 mono_coop_cond_init (&zero_pending_joinable_thread_event);
3354 mono_init_static_data_info (&thread_static_info);
3355 mono_init_static_data_info (&context_static_info);
3357 mono_thread_start_cb = start_cb;
3358 mono_thread_attach_cb = attach_cb;
3362 static gpointer
3363 thread_attach (MonoThreadInfo *info)
3365 return mono_gc_thread_attach (info);
3368 static void
3369 thread_detach (MonoThreadInfo *info)
3371 MonoInternalThread *internal;
3372 guint32 gchandle;
3374 /* If a delegate is passed to native code and invoked on a thread we dont
3375 * know about, marshal will register it with mono_threads_attach_coop, but
3376 * we have no way of knowing when that thread goes away. SGen has a TSD
3377 * so we assume that if the domain is still registered, we can detach
3378 * the thread */
3380 g_assert (info);
3381 g_assert (mono_thread_info_is_current (info));
3383 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
3384 return;
3386 internal = (MonoInternalThread*) mono_gchandle_get_target_internal (gchandle);
3387 g_assert (internal);
3389 mono_thread_detach_internal (internal);
3391 mono_gc_thread_detach (info);
3394 static void
3395 thread_detach_with_lock (MonoThreadInfo *info)
3397 mono_gc_thread_detach_with_lock (info);
3400 static gboolean
3401 thread_in_critical_region (MonoThreadInfo *info)
3403 return mono_gc_thread_in_critical_region (info);
3406 static gboolean
3407 ip_in_critical_region (MonoDomain *domain, gpointer ip)
3409 MonoJitInfo *ji;
3410 MonoMethod *method;
3413 * We pass false for 'try_aot' so this becomes async safe.
3414 * It won't find aot methods whose jit info is not yet loaded,
3415 * so we preload their jit info in the JIT.
3417 ji = mono_jit_info_table_find_internal (domain, ip, FALSE, FALSE);
3418 if (!ji)
3419 return FALSE;
3421 method = mono_jit_info_get_method (ji);
3422 g_assert (method);
3424 return mono_gc_is_critical_method (method);
3427 static void
3428 thread_flags_changing (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3430 mono_gc_skip_thread_changing (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3433 static void
3434 thread_flags_changed (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3436 mono_gc_skip_thread_changed (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3439 void
3440 mono_thread_callbacks_init (void)
3442 MonoThreadInfoCallbacks cb;
3444 memset (&cb, 0, sizeof(cb));
3445 cb.thread_attach = thread_attach;
3446 cb.thread_detach = thread_detach;
3447 cb.thread_detach_with_lock = thread_detach_with_lock;
3448 cb.ip_in_critical_region = ip_in_critical_region;
3449 cb.thread_in_critical_region = thread_in_critical_region;
3450 cb.thread_flags_changing = thread_flags_changing;
3451 cb.thread_flags_changed = thread_flags_changed;
3452 mono_thread_info_callbacks_init (&cb);
3456 * mono_thread_cleanup:
3458 void
3459 mono_thread_cleanup (void)
3461 /* Wait for pending threads to park on joinable threads list */
3462 /* NOTE, waiting on this should be extremely rare and will only happen */
3463 /* under certain specific conditions. */
3464 gboolean wait_result = threads_wait_pending_joinable_threads (2000);
3465 if (!wait_result)
3466 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3468 mono_threads_join_threads ();
3470 #if !defined(HOST_WIN32)
3471 /* The main thread must abandon any held mutexes (particularly
3472 * important for named mutexes as they are shared across
3473 * processes, see bug 74680.) This will happen when the
3474 * thread exits, but if it's not running in a subthread it
3475 * won't exit in time.
3477 if (!mono_runtime_get_no_exec ())
3478 mono_w32mutex_abandon (mono_thread_internal_current ());
3479 #endif
3481 #if 0
3482 /* This stuff needs more testing, it seems one of these
3483 * critical sections can be locked when mono_thread_cleanup is
3484 * called.
3486 mono_coop_mutex_destroy (&threads_mutex);
3487 mono_os_mutex_destroy (&interlocked_mutex);
3488 mono_os_mutex_destroy (&delayed_free_table_mutex);
3489 mono_os_mutex_destroy (&small_id_mutex);
3490 mono_coop_cond_destroy (&zero_pending_joinable_thread_event);
3491 mono_coop_cond_destroy (&pending_native_thread_join_calls_event);
3492 mono_os_event_destroy (&background_change_event);
3493 #endif
3496 void
3497 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
3499 mono_thread_cleanup_fn = func;
3503 * mono_thread_set_manage_callback:
3505 void
3506 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
3508 thread->internal_thread->manage_callback = func;
3511 G_GNUC_UNUSED
3512 static void print_tids (gpointer key, gpointer value, gpointer user)
3514 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3515 * sizeof(uint) and a cast to uint would overflow
3517 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3518 * print this as a pointer.
3520 g_message ("Waiting for: %p", key);
3523 struct wait_data
3525 MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3526 MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3527 guint32 num;
3530 static void
3531 wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
3533 guint32 i;
3534 MonoThreadInfoWaitRet ret;
3536 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
3538 /* Add the thread state change event, so it wakes
3539 * up if a thread changes to background mode. */
3541 MONO_ENTER_GC_SAFE;
3542 if (check_state_change)
3543 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, &background_change_event, FALSE, timeout, TRUE);
3544 else
3545 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, NULL, TRUE, timeout, TRUE);
3546 MONO_EXIT_GC_SAFE;
3548 if (ret == MONO_THREAD_INFO_WAIT_RET_FAILED) {
3549 /* See the comment in build_wait_tids() */
3550 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
3551 return;
3554 for( i = 0; i < wait->num; i++)
3555 mono_threads_close_thread_handle (wait->handles [i]);
3557 if (ret >= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 && ret < (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + wait->num)) {
3558 MonoInternalThread *internal;
3560 internal = wait->threads [ret - MONO_THREAD_INFO_WAIT_RET_SUCCESS_0];
3562 mono_threads_lock ();
3563 if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
3564 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
3565 mono_threads_unlock ();
3569 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
3571 struct wait_data *wait=(struct wait_data *)user;
3573 if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
3574 MonoInternalThread *thread=(MonoInternalThread *)value;
3576 /* Ignore background threads, we abort them later */
3577 /* Do not lock here since it is not needed and the caller holds threads_lock */
3578 if (thread->state & ThreadState_Background) {
3579 THREAD_DEBUG (g_message ("%s: ignoring background thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3580 return; /* just leave, ignore */
3583 if (mono_gc_is_finalizer_internal_thread (thread)) {
3584 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3585 return;
3588 if (thread == mono_thread_internal_current ()) {
3589 THREAD_DEBUG (g_message ("%s: ignoring current thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3590 return;
3593 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
3594 THREAD_DEBUG (g_message ("%s: ignoring main thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3595 return;
3598 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
3599 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
3600 return;
3603 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
3604 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
3605 wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
3606 wait->threads[wait->num]=thread;
3607 wait->num++;
3609 THREAD_DEBUG (g_message ("%s: adding thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3610 } else {
3611 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3615 } else {
3616 /* Just ignore the rest, we can't do anything with
3617 * them yet
3622 static void
3623 abort_threads (gpointer key, gpointer value, gpointer user)
3625 struct wait_data *wait=(struct wait_data *)user;
3626 MonoNativeThreadId self = mono_native_thread_id_get ();
3627 MonoInternalThread *thread = (MonoInternalThread *)value;
3629 if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
3630 return;
3632 if (mono_native_thread_id_equals (thread_get_tid (thread), self))
3633 return;
3634 if (mono_gc_is_finalizer_internal_thread (thread))
3635 return;
3637 if ((thread->flags & MONO_THREAD_FLAG_DONT_MANAGE))
3638 return;
3640 wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
3641 wait->threads[wait->num] = thread;
3642 wait->num++;
3644 THREAD_DEBUG (g_print ("%s: Aborting id: %" G_GSIZE_FORMAT "\n", __func__, (gsize)thread->tid));
3645 mono_thread_internal_abort (thread, FALSE);
3648 /**
3649 * mono_threads_set_shutting_down:
3651 * Is called by a thread that wants to shut down Mono. If the runtime is already
3652 * shutting down, the calling thread is suspended/stopped, and this function never
3653 * returns.
3655 void
3656 mono_threads_set_shutting_down (void)
3658 MonoInternalThread *current_thread = mono_thread_internal_current ();
3660 mono_threads_lock ();
3662 if (shutting_down) {
3663 mono_threads_unlock ();
3665 /* Make sure we're properly suspended/stopped */
3667 LOCK_THREAD (current_thread);
3669 if (current_thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
3670 UNLOCK_THREAD (current_thread);
3671 mono_thread_execute_interruption_void ();
3672 } else {
3673 UNLOCK_THREAD (current_thread);
3676 /*since we're killing the thread, detach it.*/
3677 mono_thread_detach_internal (current_thread);
3679 /* Wake up other threads potentially waiting for us */
3680 mono_thread_info_exit (0);
3681 } else {
3682 shutting_down = TRUE;
3684 /* Not really a background state change, but this will
3685 * interrupt the main thread if it is waiting for all
3686 * the other threads.
3688 MONO_ENTER_GC_SAFE;
3689 mono_os_event_set (&background_change_event);
3690 MONO_EXIT_GC_SAFE;
3692 mono_threads_unlock ();
3697 * mono_thread_manage_internal:
3699 void
3700 mono_thread_manage_internal (void)
3702 MONO_REQ_GC_UNSAFE_MODE;
3704 struct wait_data wait_data;
3705 struct wait_data *wait = &wait_data;
3707 memset (wait, 0, sizeof (struct wait_data));
3708 /* join each thread that's still running */
3709 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3711 mono_threads_lock ();
3712 if(threads==NULL) {
3713 THREAD_DEBUG (g_message("%s: No threads", __func__));
3714 mono_threads_unlock ();
3715 return;
3718 mono_threads_unlock ();
3720 do {
3721 mono_threads_lock ();
3722 if (shutting_down) {
3723 /* somebody else is shutting down */
3724 mono_threads_unlock ();
3725 break;
3727 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3728 mono_g_hash_table_foreach (threads, print_tids, NULL));
3730 MONO_ENTER_GC_SAFE;
3731 mono_os_event_reset (&background_change_event);
3732 MONO_EXIT_GC_SAFE;
3733 wait->num=0;
3734 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3735 memset (wait->threads, 0, sizeof (wait->threads));
3736 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3737 mono_threads_unlock ();
3738 if (wait->num > 0)
3739 /* Something to wait for */
3740 wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3741 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3742 } while(wait->num>0);
3744 /* Mono is shutting down, so just wait for the end */
3745 if (!mono_runtime_try_shutdown ()) {
3746 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3747 mono_thread_suspend (mono_thread_internal_current ());
3748 mono_thread_execute_interruption_void ();
3751 #ifndef ENABLE_NETCORE
3753 * Under netcore, we don't abort any threads, just exit.
3754 * This is not a problem since we don't do runtime cleanup either.
3757 * Remove everything but the finalizer thread and self.
3758 * Also abort all the background threads
3759 * */
3760 do {
3761 mono_threads_lock ();
3763 wait->num = 0;
3764 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3765 memset (wait->threads, 0, sizeof (wait->threads));
3766 mono_g_hash_table_foreach (threads, abort_threads, wait);
3768 mono_threads_unlock ();
3770 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3771 if (wait->num > 0) {
3772 /* Something to wait for */
3773 wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3775 } while (wait->num > 0);
3776 #endif
3779 * give the subthreads a chance to really quit (this is mainly needed
3780 * to get correct user and system times from getrusage/wait/time(1)).
3781 * This could be removed if we avoid pthread_detach() and use pthread_join().
3783 mono_thread_info_yield ();
3786 #ifndef ENABLE_NETCORE
3787 static void
3788 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3790 MonoInternalThread *thread = (MonoInternalThread*)value;
3791 struct wait_data *wait = (struct wait_data*)user_data;
3794 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3795 * limitation.
3796 * This needs no locking.
3798 if ((thread->state & ThreadState_Suspended) != 0 ||
3799 (thread->state & ThreadState_Stopped) != 0)
3800 return;
3802 if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3803 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3804 wait->threads [wait->num] = thread;
3805 wait->num++;
3810 * mono_thread_suspend_all_other_threads:
3812 * Suspend all managed threads except the finalizer thread and this thread. It is
3813 * not possible to resume them later.
3815 void mono_thread_suspend_all_other_threads (void)
3817 struct wait_data wait_data;
3818 struct wait_data *wait = &wait_data;
3819 int i;
3820 MonoNativeThreadId self = mono_native_thread_id_get ();
3821 guint32 eventidx = 0;
3822 gboolean starting, finished;
3824 memset (wait, 0, sizeof (struct wait_data));
3826 * The other threads could be in an arbitrary state at this point, i.e.
3827 * they could be starting up, shutting down etc. This means that there could be
3828 * threads which are not even in the threads hash table yet.
3832 * First we set a barrier which will be checked by all threads before they
3833 * are added to the threads hash table, and they will exit if the flag is set.
3834 * This ensures that no threads could be added to the hash later.
3835 * We will use shutting_down as the barrier for now.
3837 g_assert (shutting_down);
3840 * We make multiple calls to WaitForMultipleObjects since:
3841 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3842 * - some threads could exit without becoming suspended
3844 finished = FALSE;
3845 while (!finished) {
3847 * Make a copy of the hashtable since we can't do anything with
3848 * threads while threads_mutex is held.
3850 wait->num = 0;
3851 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3852 memset (wait->threads, 0, sizeof (wait->threads));
3853 mono_threads_lock ();
3854 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3855 mono_threads_unlock ();
3857 eventidx = 0;
3858 /* Get the suspended events that we'll be waiting for */
3859 for (i = 0; i < wait->num; ++i) {
3860 MonoInternalThread *thread = wait->threads [i];
3862 if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3863 || mono_gc_is_finalizer_internal_thread (thread)
3864 || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3866 mono_threads_close_thread_handle (wait->handles [i]);
3867 wait->threads [i] = NULL;
3868 continue;
3871 LOCK_THREAD (thread);
3873 if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3874 UNLOCK_THREAD (thread);
3875 mono_threads_close_thread_handle (wait->handles [i]);
3876 wait->threads [i] = NULL;
3877 continue;
3880 ++eventidx;
3882 /* Convert abort requests into suspend requests */
3883 if ((thread->state & ThreadState_AbortRequested) != 0)
3884 thread->state &= ~ThreadState_AbortRequested;
3886 thread->state |= ThreadState_SuspendRequested;
3887 MONO_ENTER_GC_SAFE;
3888 mono_os_event_reset (thread->suspended);
3889 MONO_EXIT_GC_SAFE;
3891 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3892 async_suspend_internal (thread, TRUE);
3894 mono_threads_close_thread_handle (wait->handles [i]);
3895 wait->threads [i] = NULL;
3897 if (eventidx <= 0) {
3899 * If there are threads which are starting up, we wait until they
3900 * are suspended when they try to register in the threads hash.
3901 * This is guaranteed to finish, since the threads which can create new
3902 * threads get suspended after a while.
3903 * FIXME: The finalizer thread can still create new threads.
3905 mono_threads_lock ();
3906 if (threads_starting_up)
3907 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3908 else
3909 starting = FALSE;
3910 mono_threads_unlock ();
3911 if (starting)
3912 mono_thread_info_sleep (100, NULL);
3913 else
3914 finished = TRUE;
3918 #endif
3920 typedef struct {
3921 MonoInternalThread *thread;
3922 MonoStackFrameInfo *frames;
3923 int nframes, max_frames;
3924 int nthreads, max_threads;
3925 MonoInternalThread **threads;
3926 } ThreadDumpUserData;
3928 static gboolean thread_dump_requested;
3930 /* This needs to be async safe */
3931 static gboolean
3932 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3934 ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3936 if (ud->nframes < ud->max_frames) {
3937 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3938 ud->nframes ++;
3941 return FALSE;
3944 /* This needs to be async safe */
3945 static SuspendThreadResult
3946 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3948 ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3949 MonoInternalThread *thread = user_data->thread;
3951 #if 0
3952 /* This no longer works with remote unwinding */
3953 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3954 mono_thread_internal_describe (thread, text);
3955 g_string_append (text, "\n");
3956 #endif
3958 if (thread == mono_thread_internal_current ())
3959 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3960 else
3961 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3963 return MonoResumeThread;
3966 typedef struct {
3967 int nthreads, max_threads;
3969 guint32 *threads;
3970 } CollectThreadsUserData;
3972 typedef struct {
3973 int nthreads, max_threads;
3974 MonoNativeThreadId *threads;
3975 } CollectThreadIdsUserData;
3977 static void
3978 collect_thread (gpointer key, gpointer value, gpointer user)
3980 CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3981 MonoInternalThread *thread = (MonoInternalThread *)value;
3983 if (ud->nthreads < ud->max_threads)
3984 ud->threads [ud->nthreads ++] = mono_gchandle_new_internal (&thread->obj, TRUE);
3988 * Collect running threads into the THREADS array.
3989 * THREADS should be an array allocated on the stack.
3991 static int
3992 collect_threads (guint32 *thread_handles, int max_threads)
3994 CollectThreadsUserData ud;
3996 mono_memory_barrier ();
3997 if (!threads)
3998 return 0;
4000 memset (&ud, 0, sizeof (ud));
4001 /* This array contains refs, but its on the stack, so its ok */
4002 ud.threads = thread_handles;
4003 ud.max_threads = max_threads;
4005 mono_threads_lock ();
4006 mono_g_hash_table_foreach (threads, collect_thread, &ud);
4007 mono_threads_unlock ();
4009 return ud.nthreads;
4012 void
4013 mono_gstring_append_thread_name (GString* text, MonoInternalThread* thread)
4015 g_string_append (text, "\n\"");
4016 char const * const name = thread->name.chars;
4017 g_string_append (text, name ? name :
4018 thread->threadpool_thread ? "<threadpool thread>" :
4019 "<unnamed thread>");
4020 g_string_append (text, "\"");
4023 static void
4024 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud, FILE* output_file)
4026 GString* text = g_string_new (0);
4027 int i;
4029 ud->thread = thread;
4030 ud->nframes = 0;
4032 /* Collect frames for the thread */
4033 if (thread == mono_thread_internal_current ()) {
4034 get_thread_dump (mono_thread_info_current (), ud);
4035 } else {
4036 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
4040 * Do all the non async-safe work outside of get_thread_dump.
4042 mono_gstring_append_thread_name (text, thread);
4044 for (i = 0; i < ud->nframes; ++i) {
4045 MonoStackFrameInfo *frame = &ud->frames [i];
4046 MonoMethod *method = NULL;
4048 if (frame->type == FRAME_TYPE_MANAGED)
4049 method = mono_jit_info_get_method (frame->ji);
4051 if (method) {
4052 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
4053 g_string_append_printf (text, " %s\n", location);
4054 g_free (location);
4055 } else {
4056 g_string_append_printf (text, " at <unknown> <0x%05x>\n", frame->native_offset);
4060 g_fprintf (output_file, "%s", text->str);
4062 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
4063 OutputDebugStringA(text->str);
4064 #endif
4066 g_string_free (text, TRUE);
4067 fflush (output_file);
4070 static void
4071 mono_get_time_of_day (struct timeval *tv) {
4072 #ifdef WIN32
4073 struct _timeb time;
4074 _ftime(&time);
4075 tv->tv_sec = time.time;
4076 tv->tv_usec = time.millitm * 1000;
4077 #else
4078 if (gettimeofday (tv, NULL) == -1) {
4079 g_error ("gettimeofday() failed; errno is %d (%s)", errno, strerror (errno));
4081 #endif
4084 static void
4085 mono_local_time (const struct timeval *tv, struct tm *tm) {
4086 #ifdef HAVE_LOCALTIME_R
4087 localtime_r(&tv->tv_sec, tm);
4088 #else
4089 time_t const tv_sec = tv->tv_sec; // Copy due to Win32/Posix contradiction.
4090 *tm = *localtime (&tv_sec);
4091 #endif
4094 void
4095 mono_threads_perform_thread_dump (void)
4097 FILE* output_file = NULL;
4098 ThreadDumpUserData ud;
4099 guint32 thread_array [128];
4100 int tindex, nthreads;
4102 if (!thread_dump_requested)
4103 return;
4105 if (thread_dump_dir != NULL) {
4106 GString* path = g_string_new (0);
4107 char time_str[80];
4108 struct timeval tv;
4109 long ms;
4110 struct tm tod;
4111 mono_get_time_of_day (&tv);
4112 mono_local_time(&tv, &tod);
4113 strftime(time_str, sizeof(time_str), MONO_STRFTIME_F "_" MONO_STRFTIME_T, &tod);
4114 ms = tv.tv_usec / 1000;
4115 g_string_append_printf (path, "%s/%s.%03ld.tdump", thread_dump_dir, time_str, ms);
4116 output_file = fopen (path->str, "w");
4117 g_string_free (path, TRUE);
4119 if (output_file == NULL) {
4120 g_print ("Full thread dump:\n");
4123 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4124 nthreads = collect_threads (thread_array, 128);
4126 memset (&ud, 0, sizeof (ud));
4127 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4128 ud.max_frames = 256;
4130 for (tindex = 0; tindex < nthreads; ++tindex) {
4131 guint32 handle = thread_array [tindex];
4132 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4133 dump_thread (thread, &ud, output_file != NULL ? output_file : stdout);
4134 mono_gchandle_free_internal (handle);
4137 if (output_file != NULL) {
4138 fclose (output_file);
4140 g_free (ud.frames);
4142 thread_dump_requested = FALSE;
4145 #ifndef ENABLE_NETCORE
4146 /* Obtain the thread dump of all threads */
4147 void
4148 ves_icall_System_Threading_Thread_GetStackTraces (MonoArrayHandleOut out_threads_handle, MonoArrayHandleOut out_stack_frames_handle, MonoError *error)
4150 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4151 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4153 guint32 handle = 0;
4155 MonoStackFrameHandle stack_frame_handle = MONO_HANDLE_NEW (MonoStackFrame, NULL);
4156 MonoReflectionMethodHandle reflection_method_handle = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4157 MonoStringHandle filename_handle = MONO_HANDLE_NEW (MonoString, NULL);
4158 MonoArrayHandle thread_frames_handle = MONO_HANDLE_NEW (MonoArray, NULL);
4160 ThreadDumpUserData ud;
4161 guint32 thread_array [128];
4162 MonoDomain *domain = mono_domain_get ();
4163 MonoDebugSourceLocation *location;
4164 int tindex, nthreads;
4166 MonoArray* out_threads = NULL;
4167 MonoArray* out_stack_frames = NULL;
4169 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4170 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4172 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4173 nthreads = collect_threads (thread_array, 128);
4175 memset (&ud, 0, sizeof (ud));
4176 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4177 ud.max_frames = 256;
4179 out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
4180 goto_if_nok (error, leave);
4181 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, out_threads);
4182 out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
4183 goto_if_nok (error, leave);
4184 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, out_stack_frames);
4186 for (tindex = 0; tindex < nthreads; ++tindex) {
4188 mono_gchandle_free_internal (handle);
4189 handle = thread_array [tindex];
4190 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4192 MonoArray *thread_frames;
4193 int i;
4195 ud.thread = thread;
4196 ud.nframes = 0;
4198 /* Collect frames for the thread */
4199 if (thread == mono_thread_internal_current ()) {
4200 get_thread_dump (mono_thread_info_current (), &ud);
4201 } else {
4202 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
4205 mono_array_setref_fast (out_threads, tindex, mono_thread_current_for_thread (thread));
4207 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
4208 MONO_HANDLE_ASSIGN_RAW (thread_frames_handle, thread_frames);
4209 goto_if_nok (error, leave);
4210 mono_array_setref_fast (out_stack_frames, tindex, thread_frames);
4212 for (i = 0; i < ud.nframes; ++i) {
4213 MonoStackFrameInfo *frame = &ud.frames [i];
4214 MonoMethod *method = NULL;
4215 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
4216 MONO_HANDLE_ASSIGN_RAW (stack_frame_handle, sf);
4217 goto_if_nok (error, leave);
4219 sf->native_offset = frame->native_offset;
4221 if (frame->type == FRAME_TYPE_MANAGED)
4222 method = mono_jit_info_get_method (frame->ji);
4224 if (method) {
4225 sf->method_address = (gsize) frame->ji->code_start;
4227 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
4228 MONO_HANDLE_ASSIGN_RAW (reflection_method_handle, rm);
4229 goto_if_nok (error, leave);
4230 MONO_OBJECT_SETREF_INTERNAL (sf, method, rm);
4232 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
4233 if (location) {
4234 sf->il_offset = location->il_offset;
4236 if (location->source_file) {
4237 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
4238 MONO_HANDLE_ASSIGN_RAW (filename_handle, filename);
4239 goto_if_nok (error, leave);
4240 MONO_OBJECT_SETREF_INTERNAL (sf, filename, filename);
4241 sf->line = location->row;
4242 sf->column = location->column;
4244 mono_debug_free_source_location (location);
4245 } else {
4246 sf->il_offset = -1;
4249 mono_array_setref_internal (thread_frames, i, sf);
4252 mono_gchandle_free_internal (handle);
4253 handle = 0;
4256 leave:
4257 mono_gchandle_free_internal (handle);
4258 g_free (ud.frames);
4260 #endif
4263 * mono_threads_request_thread_dump:
4265 * Ask all threads except the current to print their stacktrace to stdout.
4267 void
4268 mono_threads_request_thread_dump (void)
4270 /*The new thread dump code runs out of the finalizer thread. */
4271 thread_dump_requested = TRUE;
4272 mono_gc_finalize_notify ();
4275 struct ref_stack {
4276 gpointer *refs;
4277 gint allocated; /* +1 so that refs [allocated] == NULL */
4278 gint bottom;
4281 typedef struct ref_stack RefStack;
4283 static RefStack *
4284 ref_stack_new (gint initial_size)
4286 RefStack *rs;
4288 initial_size = MAX (initial_size, 16) + 1;
4289 rs = g_new0 (RefStack, 1);
4290 rs->refs = g_new0 (gpointer, initial_size);
4291 rs->allocated = initial_size;
4292 return rs;
4295 static void
4296 ref_stack_destroy (gpointer ptr)
4298 RefStack *rs = (RefStack *)ptr;
4300 if (rs != NULL) {
4301 g_free (rs->refs);
4302 g_free (rs);
4306 static void
4307 ref_stack_push (RefStack *rs, gpointer ptr)
4309 g_assert (rs != NULL);
4311 if (rs->bottom >= rs->allocated) {
4312 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
4313 rs->allocated <<= 1;
4314 rs->refs [rs->allocated] = NULL;
4316 rs->refs [rs->bottom++] = ptr;
4319 static void
4320 ref_stack_pop (RefStack *rs)
4322 if (rs == NULL || rs->bottom == 0)
4323 return;
4325 rs->bottom--;
4326 rs->refs [rs->bottom] = NULL;
4329 static gboolean
4330 ref_stack_find (RefStack *rs, gpointer ptr)
4332 gpointer *refs;
4334 if (rs == NULL)
4335 return FALSE;
4337 for (refs = rs->refs; refs && *refs; refs++) {
4338 if (*refs == ptr)
4339 return TRUE;
4341 return FALSE;
4345 * mono_thread_push_appdomain_ref:
4347 * Register that the current thread may have references to objects in domain
4348 * @domain on its stack. Each call to this function should be paired with a
4349 * call to pop_appdomain_ref.
4351 void
4352 mono_thread_push_appdomain_ref (MonoDomain *domain)
4354 MonoInternalThread *thread = mono_thread_internal_current ();
4356 if (thread) {
4357 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4358 SPIN_LOCK (thread->lock_thread_id);
4359 if (thread->appdomain_refs == NULL)
4360 thread->appdomain_refs = ref_stack_new (16);
4361 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
4362 SPIN_UNLOCK (thread->lock_thread_id);
4366 void
4367 mono_thread_pop_appdomain_ref (void)
4369 MonoInternalThread *thread = mono_thread_internal_current ();
4371 if (thread) {
4372 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4373 SPIN_LOCK (thread->lock_thread_id);
4374 ref_stack_pop ((RefStack *)thread->appdomain_refs);
4375 SPIN_UNLOCK (thread->lock_thread_id);
4379 gboolean
4380 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
4382 gboolean res;
4383 SPIN_LOCK (thread->lock_thread_id);
4384 res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
4385 SPIN_UNLOCK (thread->lock_thread_id);
4386 return res;
4389 gboolean
4390 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
4392 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
4395 typedef struct abort_appdomain_data {
4396 struct wait_data wait;
4397 MonoDomain *domain;
4398 } abort_appdomain_data;
4400 static void
4401 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
4403 MonoInternalThread *thread = (MonoInternalThread*)value;
4404 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
4405 MonoDomain *domain = data->domain;
4407 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
4408 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4410 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
4411 data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
4412 data->wait.threads [data->wait.num] = thread;
4413 data->wait.num++;
4414 } else {
4415 /* Just ignore the rest, we can't do anything with
4416 * them yet
4423 * mono_threads_abort_appdomain_threads:
4425 * Abort threads which has references to the given appdomain.
4427 gboolean
4428 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
4430 abort_appdomain_data user_data;
4431 gint64 start_time;
4432 int orig_timeout = timeout;
4433 int i;
4435 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
4437 start_time = mono_msec_ticks ();
4438 do {
4439 mono_threads_lock ();
4441 user_data.domain = domain;
4442 user_data.wait.num = 0;
4443 /* This shouldn't take any locks */
4444 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
4445 mono_threads_unlock ();
4447 if (user_data.wait.num > 0) {
4448 /* Abort the threads outside the threads lock */
4449 for (i = 0; i < user_data.wait.num; ++i)
4450 mono_thread_internal_abort (user_data.wait.threads [i], TRUE);
4453 * We should wait for the threads either to abort, or to leave the
4454 * domain. We can't do the latter, so we wait with a timeout.
4456 wait_for_tids (&user_data.wait, 100, FALSE);
4459 /* Update remaining time */
4460 timeout -= mono_msec_ticks () - start_time;
4461 start_time = mono_msec_ticks ();
4463 if (orig_timeout != -1 && timeout < 0)
4464 return FALSE;
4466 while (user_data.wait.num > 0);
4468 THREAD_DEBUG (g_message ("%s: abort done", __func__));
4470 return TRUE;
4473 /* This is a JIT icall. This icall is called from a finally block when
4474 * mono_install_handler_block_guard called by another thread has flipped the
4475 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4476 * the finally is in an abort protected block, we must defer the abort
4477 * exception until we leave the abort protected block. Otherwise we proceed
4478 * with a synchronous self-abort.
4480 void
4481 ves_icall_thread_finish_async_abort (void)
4483 /* We were called from the handler block and are about to
4484 * leave it. (If we end up postponing the abort because we're
4485 * in an abort protected block, the unwinder won't run and
4486 * won't clear the handler block itself which will confuse the
4487 * unwinder if we're in a try {} catch {} and we throw again.
4488 * ie, this:
4489 * static Constructor () {
4490 * try {
4491 * try {
4492 * } finally {
4493 * icall (); // Thread.Abort landed here,
4494 * // and caused the handler block to be installed
4495 * if (exvar)
4496 * ves_icall_thread_finish_async_abort (); // we're here
4498 * throw E ();
4499 * } catch (E) {
4500 * // unwinder will get confused here and synthesize a self abort
4504 * More interestingly, this doesn't only happen with icalls - a JIT
4505 * trampoline is native code that will cause a handler to be installed.
4506 * So the above situation can happen with any code in a "finally"
4507 * clause.
4509 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4510 /* Just set the async interruption requested bit. Rely on the icall
4511 * wrapper of this icall to process the thread interruption, respecting
4512 * any abort protection blocks in our call stack.
4514 mono_thread_set_self_interruption_respect_abort_prot ();
4518 * mono_thread_get_undeniable_exception:
4520 * Return an exception which needs to be raised when leaving a catch clause.
4521 * This is used for undeniable exception propagation.
4523 MonoException*
4524 mono_thread_get_undeniable_exception (void)
4526 MonoInternalThread *thread = mono_thread_internal_current ();
4528 if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
4529 return NULL;
4531 // We don't want to have our exception effect calls made by
4532 // the catching block
4534 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4535 return NULL;
4538 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4539 * exception if the thread no longer references a dying appdomain.
4541 thread->abort_exc->trace_ips = NULL;
4542 thread->abort_exc->stack_trace = NULL;
4543 return thread->abort_exc;
4546 #if MONO_SMALL_CONFIG
4547 #define NUM_STATIC_DATA_IDX 4
4548 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4549 64, 256, 1024, 4096
4551 #else
4552 #define NUM_STATIC_DATA_IDX 8
4553 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4554 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4556 #endif
4558 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
4559 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
4561 static void
4562 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
4564 gpointer *static_data = (gpointer *)addr;
4566 for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4567 void **ptr = (void **)static_data [i];
4569 if (!ptr)
4570 continue;
4572 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4573 void **p = ptr + idx;
4575 if (*p)
4576 mark_func ((MonoObject**)p, gc_data);
4581 static void
4582 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4584 mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4587 static void
4588 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4590 mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4594 * mono_alloc_static_data
4596 * Allocate memory blocks for storing threads or context static data
4598 static void
4599 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal)
4601 guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4602 int i;
4604 gpointer* static_data = *static_data_ptr;
4605 if (!static_data) {
4606 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4607 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4609 if (mono_gc_user_markers_supported ()) {
4610 if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4611 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4613 if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4614 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4617 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4618 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4619 alloc_key,
4620 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4621 *static_data_ptr = static_data;
4622 static_data [0] = static_data;
4625 for (i = 1; i <= idx; ++i) {
4626 if (static_data [i])
4627 continue;
4629 if (mono_gc_user_markers_supported ())
4630 static_data [i] = g_malloc0 (static_data_size [i]);
4631 else
4632 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4633 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4634 alloc_key,
4635 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4639 static void
4640 mono_free_static_data (gpointer* static_data)
4642 int i;
4643 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4644 gpointer p = static_data [i];
4645 if (!p)
4646 continue;
4648 * At this point, the static data pointer array is still registered with the
4649 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4650 * data. Freeing the individual arrays without first nulling their slots
4651 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4652 * such an already freed array. See bug #13813.
4654 static_data [i] = NULL;
4655 mono_memory_write_barrier ();
4656 if (mono_gc_user_markers_supported ())
4657 g_free (p);
4658 else
4659 mono_gc_free_fixed (p);
4661 mono_gc_free_fixed (static_data);
4665 * mono_init_static_data_info
4667 * Initializes static data counters
4669 static void mono_init_static_data_info (StaticDataInfo *static_data)
4671 static_data->idx = 0;
4672 static_data->offset = 0;
4673 static_data->freelist = NULL;
4677 * mono_alloc_static_data_slot
4679 * Generates an offset for static data. static_data contains the counters
4680 * used to generate it.
4682 static guint32
4683 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4685 if (!static_data->idx && !static_data->offset) {
4687 * we use the first chunk of the first allocation also as
4688 * an array for the rest of the data
4690 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4692 static_data->offset += align - 1;
4693 static_data->offset &= ~(align - 1);
4694 if (static_data->offset + size >= static_data_size [static_data->idx]) {
4695 static_data->idx ++;
4696 g_assert (size <= static_data_size [static_data->idx]);
4697 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4698 static_data->offset = 0;
4700 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4701 static_data->offset += size;
4702 return offset;
4706 * LOCKING: requires that threads_mutex is held
4708 static void
4709 context_adjust_static_data (MonoAppContextHandle ctx_handle)
4711 MonoAppContext *ctx = MONO_HANDLE_RAW (ctx_handle);
4712 if (context_static_info.offset || context_static_info.idx > 0) {
4713 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4714 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4715 ctx->data->static_data = ctx->static_data;
4720 * LOCKING: requires that threads_mutex is held
4722 static void
4723 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4725 MonoInternalThread *thread = (MonoInternalThread *)value;
4726 guint32 offset = GPOINTER_TO_UINT (user);
4728 mono_alloc_static_data (&(thread->static_data), offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid), TRUE);
4732 * LOCKING: requires that threads_mutex is held
4734 static void
4735 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4737 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4739 if (!ctx)
4740 return;
4742 guint32 offset = GPOINTER_TO_UINT (user);
4743 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4744 ctx->data->static_data = ctx->static_data;
4747 static StaticDataFreeList*
4748 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, gint32 align)
4750 StaticDataFreeList* prev = NULL;
4751 StaticDataFreeList* tmp = static_data->freelist;
4752 while (tmp) {
4753 if (tmp->size == size && tmp->align == align) {
4754 if (prev)
4755 prev->next = tmp->next;
4756 else
4757 static_data->freelist = tmp->next;
4758 return tmp;
4760 prev = tmp;
4761 tmp = tmp->next;
4763 return NULL;
4766 #if SIZEOF_VOID_P == 4
4767 #define ONE_P 1
4768 #else
4769 #define ONE_P 1ll
4770 #endif
4772 static void
4773 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4775 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4776 if (!sets [idx])
4777 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4778 MonoBitSet *rb = sets [idx];
4779 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4780 offset /= sizeof (uintptr_t);
4781 /* offset is now the bitmap offset */
4782 for (int i = 0; i < numbits; ++i) {
4783 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4784 mono_bitset_set_fast (rb, offset + i);
4788 static void
4789 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4791 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4792 MonoBitSet *rb = sets [idx];
4793 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4794 offset /= sizeof (uintptr_t);
4795 /* offset is now the bitmap offset */
4796 for (int i = 0; i < size / sizeof (uintptr_t); i++)
4797 mono_bitset_clear_fast (rb, offset + i);
4800 guint32
4801 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4803 g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4805 StaticDataInfo *info;
4806 MonoBitSet **sets;
4808 if (static_type == SPECIAL_STATIC_THREAD) {
4809 info = &thread_static_info;
4810 sets = thread_reference_bitmaps;
4811 } else {
4812 info = &context_static_info;
4813 sets = context_reference_bitmaps;
4816 mono_threads_lock ();
4818 StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4819 guint32 offset;
4821 if (item) {
4822 offset = item->offset;
4823 g_free (item);
4824 } else {
4825 offset = mono_alloc_static_data_slot (info, size, align);
4828 update_reference_bitmap (sets, offset, bitmap, numbits);
4830 if (static_type == SPECIAL_STATIC_THREAD) {
4831 /* This can be called during startup */
4832 if (threads != NULL)
4833 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4834 } else {
4835 if (contexts != NULL)
4836 g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4838 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4841 mono_threads_unlock ();
4843 return offset;
4846 gpointer
4847 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4849 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4851 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4852 return get_thread_static_data (thread, offset);
4853 } else {
4854 return get_context_static_data (thread->current_appcontext, offset);
4858 gpointer
4859 mono_get_special_static_data (guint32 offset)
4861 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4864 typedef struct {
4865 guint32 offset;
4866 guint32 size;
4867 } OffsetSize;
4870 * LOCKING: requires that threads_mutex is held
4872 static void
4873 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4875 MonoInternalThread *thread = (MonoInternalThread *)value;
4876 OffsetSize *data = (OffsetSize *)user;
4877 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4878 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4879 char *ptr;
4881 if (!thread->static_data || !thread->static_data [idx])
4882 return;
4883 ptr = ((char*) thread->static_data [idx]) + off;
4884 mono_gc_bzero_atomic (ptr, data->size);
4888 * LOCKING: requires that threads_mutex is held
4890 static void
4891 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4893 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4895 if (!ctx)
4896 return;
4898 OffsetSize *data = (OffsetSize *)user;
4899 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4900 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4901 char *ptr;
4903 if (!ctx->static_data || !ctx->static_data [idx])
4904 return;
4906 ptr = ((char*) ctx->static_data [idx]) + off;
4907 mono_gc_bzero_atomic (ptr, data->size);
4910 static void
4911 do_free_special_slot (guint32 offset, guint32 size, gint32 align)
4913 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4914 MonoBitSet **sets;
4915 StaticDataInfo *info;
4917 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4918 info = &thread_static_info;
4919 sets = thread_reference_bitmaps;
4920 } else {
4921 info = &context_static_info;
4922 sets = context_reference_bitmaps;
4925 guint32 data_offset = offset;
4926 ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4927 OffsetSize data = { data_offset, size };
4929 clear_reference_bitmap (sets, data.offset, data.size);
4931 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4932 if (threads != NULL)
4933 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4934 } else {
4935 if (contexts != NULL)
4936 g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4939 if (!mono_runtime_is_shutting_down ()) {
4940 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4942 item->offset = offset;
4943 item->size = size;
4944 item->align = align;
4946 item->next = info->freelist;
4947 info->freelist = item;
4951 static void
4952 do_free_special (gpointer key, gpointer value, gpointer data)
4954 MonoClassField *field = (MonoClassField *)key;
4955 guint32 offset = GPOINTER_TO_UINT (value);
4956 gint32 align;
4957 guint32 size;
4958 size = mono_type_size (field->type, &align);
4959 do_free_special_slot (offset, size, align);
4962 void
4963 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4965 mono_threads_lock ();
4967 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4969 mono_threads_unlock ();
4972 #ifdef HOST_WIN32
4973 static void
4974 flush_thread_interrupt_queue (void)
4976 /* Consume pending APC calls for current thread.*/
4977 /* Since this function get's called from interrupt handler it must use a direct */
4978 /* Win32 API call and can't go through mono_coop_win32_wait_for_single_object_ex */
4979 /* or it will detect a pending interrupt and not entering the wait call needed */
4980 /* to consume pending APC's.*/
4981 MONO_ENTER_GC_SAFE;
4982 WaitForSingleObjectEx (GetCurrentThread (), 0, TRUE);
4983 MONO_EXIT_GC_SAFE;
4985 #else
4986 static void
4987 flush_thread_interrupt_queue (void)
4990 #endif
4993 * mono_thread_execute_interruption
4995 * Performs the operation that the requested thread state requires (abort,
4996 * suspend or stop)
4998 static gboolean
4999 mono_thread_execute_interruption (MonoExceptionHandle *pexc)
5001 gboolean fexc = FALSE;
5003 // Optimize away frame if caller supplied one.
5004 if (!pexc) {
5005 HANDLE_FUNCTION_ENTER ();
5006 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5007 fexc = mono_thread_execute_interruption (&exc);
5008 HANDLE_FUNCTION_RETURN_VAL (fexc);
5011 MONO_REQ_GC_UNSAFE_MODE;
5013 MonoInternalThreadHandle thread = mono_thread_internal_current_handle ();
5014 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5016 lock_thread_handle (thread);
5017 gboolean unlock = TRUE;
5019 /* MonoThread::interruption_requested can only be changed with atomics */
5020 if (!mono_thread_clear_interruption_requested_handle (thread))
5021 goto exit;
5023 MonoThreadObjectHandle sys_thread;
5024 sys_thread = mono_thread_current_handle ();
5026 flush_thread_interrupt_queue ();
5028 /* Clear the interrupted flag of the thread so it can wait again */
5029 mono_thread_info_clear_self_interrupt ();
5031 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
5032 MONO_HANDLE_GET (exc, sys_thread, pending_exception);
5033 if (!MONO_HANDLE_IS_NULL (exc)) {
5034 // sys_thread->pending_exception = NULL;
5035 MONO_HANDLE_SETRAW (sys_thread, pending_exception, NULL);
5036 fexc = TRUE;
5037 goto exit;
5038 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_AbortRequested) {
5039 // Does the thread already have an abort exception?
5040 // If not, create a new one and set it on demand.
5041 // exc = thread->abort_exc;
5042 MONO_HANDLE_GET (exc, thread, abort_exc);
5043 if (MONO_HANDLE_IS_NULL (exc)) {
5044 ERROR_DECL (error);
5045 exc = mono_exception_new_thread_abort (error);
5046 mono_error_assert_ok (error); // FIXME
5047 // thread->abort_exc = exc;
5048 MONO_HANDLE_SET (thread, abort_exc, exc);
5050 fexc = TRUE;
5051 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_SuspendRequested) {
5052 /* calls UNLOCK_THREAD (thread) */
5053 self_suspend_internal ();
5054 unlock = FALSE;
5055 } else if (MONO_HANDLE_GETVAL (thread, thread_interrupt_requested)) {
5056 // thread->thread_interrupt_requested = FALSE
5057 MONO_HANDLE_SETVAL (thread, thread_interrupt_requested, MonoBoolean, FALSE);
5058 unlock_thread_handle (thread);
5059 unlock = FALSE;
5060 ERROR_DECL (error);
5061 exc = mono_exception_new_thread_interrupted (error);
5062 mono_error_assert_ok (error); // FIXME
5063 fexc = TRUE;
5065 exit:
5066 if (unlock)
5067 unlock_thread_handle (thread);
5069 if (fexc)
5070 MONO_HANDLE_ASSIGN (*pexc, exc);
5072 return fexc;
5075 static void
5076 mono_thread_execute_interruption_void (void)
5078 (void)mono_thread_execute_interruption (NULL);
5081 static MonoException*
5082 mono_thread_execute_interruption_ptr (void)
5084 HANDLE_FUNCTION_ENTER ();
5085 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5086 MonoException * const exc_raw = mono_thread_execute_interruption (&exc) ? MONO_HANDLE_RAW (exc) : NULL;
5087 HANDLE_FUNCTION_RETURN_VAL (exc_raw);
5091 * mono_thread_request_interruption_internal
5093 * A signal handler can call this method to request the interruption of a
5094 * thread. The result of the interruption will depend on the current state of
5095 * the thread. If the result is an exception that needs to be thrown, it is
5096 * provided as return value.
5098 static gboolean
5099 mono_thread_request_interruption_internal (gboolean running_managed, MonoExceptionHandle *pexc)
5101 MonoInternalThread *thread = mono_thread_internal_current ();
5103 /* The thread may already be stopping */
5104 if (thread == NULL)
5105 return FALSE;
5107 if (!mono_thread_set_interruption_requested (thread))
5108 return FALSE;
5110 if (!running_managed || is_running_protected_wrapper ()) {
5111 /* Can't stop while in unmanaged code. Increase the global interruption
5112 request count. When exiting the unmanaged method the count will be
5113 checked and the thread will be interrupted. */
5115 /* this will awake the thread if it is in WaitForSingleObject
5116 or similar */
5117 #ifdef HOST_WIN32
5118 mono_win32_interrupt_wait (thread->thread_info, thread->native_handle, (DWORD)thread->tid);
5119 #else
5120 mono_thread_info_self_interrupt ();
5121 #endif
5122 return FALSE;
5124 return mono_thread_execute_interruption (pexc);
5127 static void
5128 mono_thread_request_interruption_native (void)
5130 (void)mono_thread_request_interruption_internal (FALSE, NULL);
5133 static gboolean
5134 mono_thread_request_interruption_managed (MonoExceptionHandle *exc)
5136 return mono_thread_request_interruption_internal (TRUE, exc);
5139 /*This function should be called by a thread after it has exited all of
5140 * its handle blocks at interruption time.*/
5141 void
5142 mono_thread_resume_interruption (gboolean exec)
5144 MonoInternalThread *thread = mono_thread_internal_current ();
5145 gboolean still_aborting;
5147 /* The thread may already be stopping */
5148 if (thread == NULL)
5149 return;
5151 LOCK_THREAD (thread);
5152 still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
5153 UNLOCK_THREAD (thread);
5155 /*This can happen if the protected block called Thread::ResetAbort*/
5156 if (!still_aborting)
5157 return;
5159 if (!mono_thread_set_interruption_requested (thread))
5160 return;
5162 mono_thread_info_self_interrupt ();
5164 if (exec) // Ignore the exception here, it will be raised later.
5165 mono_thread_execute_interruption_void ();
5168 gboolean
5169 mono_thread_interruption_requested (void)
5171 if (mono_thread_interruption_request_flag) {
5172 MonoInternalThread *thread = mono_thread_internal_current ();
5173 /* The thread may already be stopping */
5174 if (thread != NULL)
5175 return mono_thread_get_interruption_requested (thread);
5177 return FALSE;
5180 static MonoException*
5181 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
5183 MonoInternalThread *thread = mono_thread_internal_current ();
5185 /* The thread may already be stopping */
5186 if (!thread)
5187 return NULL;
5188 if (!mono_thread_get_interruption_requested (thread))
5189 return NULL;
5190 if (!bypass_abort_protection && !mono_thread_current ()->pending_exception && is_running_protected_wrapper ())
5191 return NULL;
5193 return mono_thread_execute_interruption_ptr ();
5197 * Performs the interruption of the current thread, if one has been requested,
5198 * and the thread is not running a protected wrapper.
5199 * Return the exception which needs to be thrown, if any.
5201 MonoException*
5202 mono_thread_interruption_checkpoint (void)
5204 return mono_thread_interruption_checkpoint_request (FALSE);
5207 gboolean
5208 mono_thread_interruption_checkpoint_bool (void)
5210 return mono_thread_interruption_checkpoint () != NULL;
5213 void
5214 mono_thread_interruption_checkpoint_void (void)
5216 mono_thread_interruption_checkpoint ();
5220 * Performs the interruption of the current thread, if one has been requested.
5221 * Return the exception which needs to be thrown, if any.
5223 MonoException*
5224 mono_thread_force_interruption_checkpoint_noraise (void)
5226 return mono_thread_interruption_checkpoint_request (TRUE);
5230 * mono_set_pending_exception:
5232 * Set the pending exception of the current thread to EXC.
5233 * The exception will be thrown when execution returns to managed code.
5235 void
5236 mono_set_pending_exception (MonoException *exc)
5238 MonoThread *thread = mono_thread_current ();
5240 /* The thread may already be stopping */
5241 if (thread == NULL)
5242 return;
5244 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5246 mono_thread_request_interruption_native ();
5250 * mono_runtime_set_pending_exception:
5252 * Set the pending exception of the current thread to \p exc.
5253 * The exception will be thrown when execution returns to managed code.
5254 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5255 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5256 * in which case the behavior will be undefined).
5257 * Return whether the pending exception was set or not.
5258 * It will not be set if:
5259 * * The thread or runtime is stopping or shutting down
5260 * * There already is a pending exception (and \p overwrite is false)
5262 mono_bool
5263 mono_runtime_set_pending_exception (MonoException *exc, mono_bool overwrite)
5265 MonoThread *thread = mono_thread_current ();
5267 /* The thread may already be stopping */
5268 if (thread == NULL)
5269 return FALSE;
5271 /* Don't overwrite any existing pending exceptions unless asked to */
5272 if (!overwrite && thread->pending_exception)
5273 return FALSE;
5275 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5277 mono_thread_request_interruption_native ();
5279 return TRUE;
5284 * mono_set_pending_exception_handle:
5286 * Set the pending exception of the current thread to EXC.
5287 * The exception will be thrown when execution returns to managed code.
5289 MONO_COLD void
5290 mono_set_pending_exception_handle (MonoExceptionHandle exc)
5292 MonoThread *thread = mono_thread_current ();
5294 /* The thread may already be stopping */
5295 if (thread == NULL)
5296 return;
5298 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, MONO_HANDLE_RAW (exc));
5300 mono_thread_request_interruption_native ();
5303 void
5304 mono_thread_init_apartment_state (void)
5306 #ifdef HOST_WIN32
5307 MonoInternalThread* thread = mono_thread_internal_current ();
5309 /* Positive return value indicates success, either
5310 * S_OK if this is first CoInitialize call, or
5311 * S_FALSE if CoInitialize already called, but with same
5312 * threading model. A negative value indicates failure,
5313 * probably due to trying to change the threading model.
5315 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
5316 ? COINIT_APARTMENTTHREADED
5317 : COINIT_MULTITHREADED) < 0) {
5318 thread->apartment_state = ThreadApartmentState_Unknown;
5320 #endif
5323 void
5324 mono_thread_cleanup_apartment_state (void)
5326 #ifdef HOST_WIN32
5327 MonoInternalThread* thread = mono_thread_internal_current ();
5329 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
5330 CoUninitialize ();
5332 #endif
5335 static void
5336 mono_thread_notify_change_state (MonoThreadState old_state, MonoThreadState new_state)
5338 MonoThreadState diff = old_state ^ new_state;
5339 if (diff & ThreadState_Background) {
5340 /* If the thread changes the background mode, the main thread has to
5341 * be notified, since it has to rebuild the list of threads to
5342 * wait for.
5344 MONO_ENTER_GC_SAFE;
5345 mono_os_event_set (&background_change_event);
5346 MONO_EXIT_GC_SAFE;
5350 void
5351 mono_thread_clear_and_set_state (MonoInternalThread *thread, MonoThreadState clear, MonoThreadState set)
5353 LOCK_THREAD (thread);
5355 MonoThreadState const old_state = (MonoThreadState)thread->state;
5356 MonoThreadState const new_state = (old_state & ~clear) | set;
5357 thread->state = new_state;
5359 UNLOCK_THREAD (thread);
5361 mono_thread_notify_change_state (old_state, new_state);
5364 void
5365 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
5367 mono_thread_clear_and_set_state (thread, (MonoThreadState)0, state);
5371 * mono_thread_test_and_set_state:
5372 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5373 * \returns TRUE if \p set was OR'd in.
5375 gboolean
5376 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
5378 LOCK_THREAD (thread);
5380 MonoThreadState const old_state = (MonoThreadState)thread->state;
5382 if ((old_state & test) != 0) {
5383 UNLOCK_THREAD (thread);
5384 return FALSE;
5387 MonoThreadState const new_state = old_state | set;
5388 thread->state = new_state;
5390 UNLOCK_THREAD (thread);
5392 mono_thread_notify_change_state (old_state, new_state);
5394 return TRUE;
5397 void
5398 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
5400 mono_thread_clear_and_set_state (thread, state, (MonoThreadState)0);
5403 gboolean
5404 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
5406 LOCK_THREAD (thread);
5408 gboolean const ret = ((thread->state & test) != 0);
5410 UNLOCK_THREAD (thread);
5412 return ret;
5415 static void
5416 self_interrupt_thread (void *_unused)
5418 MonoException *exc;
5419 MonoThreadInfo *info;
5420 MonoContext ctx;
5422 exc = mono_thread_execute_interruption_ptr ();
5423 if (!exc) {
5424 if (mono_threads_are_safepoints_enabled ()) {
5425 /* We can return from an async call in coop, as
5426 * it's simply called when exiting the safepoint */
5427 /* If we're using hybrid suspend, we only self
5428 * interrupt if we were running, hence using
5429 * safepoints */
5430 return;
5433 g_error ("%s: we can't resume from an async call", __func__);
5436 info = mono_thread_info_current ();
5438 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5439 ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
5441 mono_raise_exception_with_context (exc, &ctx);
5444 static gboolean
5445 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
5447 if (!ji)
5448 return FALSE;
5449 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
5452 static gboolean
5453 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
5455 MonoJitInfo **dest = (MonoJitInfo **)data;
5456 *dest = frame->ji;
5457 return TRUE;
5460 static MonoJitInfo*
5461 mono_thread_info_get_last_managed (MonoThreadInfo *info)
5463 MonoJitInfo *ji = NULL;
5464 if (!info)
5465 return NULL;
5468 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5469 * any runtime locks while unwinding.
5471 mono_thread_info_set_is_async_context (TRUE);
5472 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
5473 mono_thread_info_set_is_async_context (FALSE);
5474 return ji;
5477 typedef struct {
5478 MonoInternalThread *thread;
5479 gboolean install_async_abort;
5480 MonoThreadInfoInterruptToken *interrupt_token;
5481 } AbortThreadData;
5483 static SuspendThreadResult
5484 async_abort_critical (MonoThreadInfo *info, gpointer ud)
5486 AbortThreadData *data = (AbortThreadData *)ud;
5487 MonoInternalThread *thread = data->thread;
5488 MonoJitInfo *ji = NULL;
5489 gboolean protected_wrapper;
5490 gboolean running_managed;
5492 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
5493 return MonoResumeThread;
5495 /*someone is already interrupting it*/
5496 if (!mono_thread_set_interruption_requested (thread))
5497 return MonoResumeThread;
5499 ji = mono_thread_info_get_last_managed (info);
5500 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5501 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5503 if (!protected_wrapper && running_managed) {
5504 /*We are in managed code*/
5505 /*Set the thread to call */
5506 if (data->install_async_abort)
5507 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5508 return MonoResumeThread;
5509 } else {
5511 * This will cause waits to be broken.
5512 * It will also prevent the thread from entering a wait, so if the thread returns
5513 * from the wait before it receives the abort signal, it will just spin in the wait
5514 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5515 * make it return.
5517 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
5519 return MonoResumeThread;
5523 static void
5524 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
5526 AbortThreadData data;
5528 g_assert (thread != mono_thread_internal_current ());
5530 data.thread = thread;
5531 data.install_async_abort = install_async_abort;
5532 data.interrupt_token = NULL;
5534 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
5535 if (data.interrupt_token)
5536 mono_thread_info_finish_interrupt (data.interrupt_token);
5537 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5540 static void
5541 self_abort_internal (MonoError *error)
5543 HANDLE_FUNCTION_ENTER ();
5545 error_init (error);
5547 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5548 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5551 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.
5553 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5554 if (mono_thread_request_interruption_managed (&exc))
5555 mono_error_set_exception_handle (error, exc);
5556 else
5557 mono_thread_info_self_interrupt ();
5559 HANDLE_FUNCTION_RETURN ();
5562 typedef struct {
5563 MonoInternalThread *thread;
5564 gboolean interrupt;
5565 MonoThreadInfoInterruptToken *interrupt_token;
5566 } SuspendThreadData;
5568 static SuspendThreadResult
5569 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
5571 SuspendThreadData *data = (SuspendThreadData *)ud;
5572 MonoInternalThread *thread = data->thread;
5573 MonoJitInfo *ji = NULL;
5574 gboolean protected_wrapper;
5575 gboolean running_managed;
5577 ji = mono_thread_info_get_last_managed (info);
5578 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5579 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5581 if (running_managed && !protected_wrapper) {
5582 if (mono_threads_are_safepoints_enabled ()) {
5583 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5584 return MonoResumeThread;
5585 } else {
5586 thread->state &= ~ThreadState_SuspendRequested;
5587 thread->state |= ThreadState_Suspended;
5588 return KeepSuspended;
5590 } else {
5591 mono_thread_set_interruption_requested (thread);
5592 if (data->interrupt)
5593 data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
5595 return MonoResumeThread;
5599 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5600 static void
5601 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
5603 SuspendThreadData data;
5605 g_assert (thread != mono_thread_internal_current ());
5607 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5609 thread->self_suspended = FALSE;
5611 data.thread = thread;
5612 data.interrupt = interrupt;
5613 data.interrupt_token = NULL;
5615 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
5616 if (data.interrupt_token)
5617 mono_thread_info_finish_interrupt (data.interrupt_token);
5619 UNLOCK_THREAD (thread);
5622 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5623 static void
5624 self_suspend_internal (void)
5626 MonoInternalThread *thread;
5627 MonoOSEvent *event;
5628 MonoOSEventWaitRet res;
5630 thread = mono_thread_internal_current ();
5632 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5634 thread->self_suspended = TRUE;
5636 thread->state &= ~ThreadState_SuspendRequested;
5637 thread->state |= ThreadState_Suspended;
5639 UNLOCK_THREAD (thread);
5641 event = thread->suspended;
5643 MONO_ENTER_GC_SAFE;
5644 res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
5645 g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
5646 MONO_EXIT_GC_SAFE;
5649 static void
5650 suspend_for_shutdown_async_call (gpointer unused)
5652 for (;;)
5653 mono_thread_info_yield ();
5656 static SuspendThreadResult
5657 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
5659 mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
5660 return MonoResumeThread;
5663 void
5664 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
5666 g_assert (thread != mono_thread_internal_current ());
5668 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
5672 * mono_thread_is_foreign:
5673 * \param thread the thread to query
5675 * This function allows one to determine if a thread was created by the mono runtime and has
5676 * a well defined lifecycle or it's a foreign one, created by the native environment.
5678 * \returns TRUE if \p thread was not created by the runtime.
5680 mono_bool
5681 mono_thread_is_foreign (MonoThread *thread)
5683 mono_bool result;
5684 MONO_ENTER_GC_UNSAFE;
5685 MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
5686 result = (info->runtime_thread == FALSE);
5687 MONO_EXIT_GC_UNSAFE;
5688 return result;
5691 #ifndef HOST_WIN32
5692 static void
5693 threads_native_thread_join_lock (gpointer tid, gpointer value)
5696 * Have to cast to a pointer-sized integer first, as we can't narrow
5697 * from a pointer if pthread_t is an integer smaller than a pointer.
5699 pthread_t thread = (pthread_t)(intptr_t)tid;
5700 if (thread != pthread_self ()) {
5701 MONO_ENTER_GC_SAFE;
5702 /* This shouldn't block */
5703 mono_threads_join_lock ();
5704 mono_native_thread_join (thread);
5705 mono_threads_join_unlock ();
5706 MONO_EXIT_GC_SAFE;
5709 static void
5710 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5712 pthread_t thread = (pthread_t)(intptr_t)tid;
5713 MONO_ENTER_GC_SAFE;
5714 mono_native_thread_join (thread);
5715 MONO_EXIT_GC_SAFE;
5718 static void
5719 threads_add_joinable_thread_nolock (gpointer tid)
5721 g_hash_table_insert (joinable_threads, tid, tid);
5723 #else
5724 static void
5725 threads_native_thread_join_lock (gpointer tid, gpointer value)
5727 MonoNativeThreadId thread_id = (MonoNativeThreadId)(guint64)tid;
5728 HANDLE thread_handle = (HANDLE)value;
5729 if (thread_id != GetCurrentThreadId () && thread_handle != NULL && thread_handle != INVALID_HANDLE_VALUE) {
5730 MONO_ENTER_GC_SAFE;
5731 /* This shouldn't block */
5732 mono_threads_join_lock ();
5733 mono_native_thread_join_handle (thread_handle, TRUE);
5734 mono_threads_join_unlock ();
5735 MONO_EXIT_GC_SAFE;
5739 static void
5740 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5742 HANDLE thread_handle = (HANDLE)value;
5743 MONO_ENTER_GC_SAFE;
5744 mono_native_thread_join_handle (thread_handle, TRUE);
5745 MONO_EXIT_GC_SAFE;
5748 static void
5749 threads_add_joinable_thread_nolock (gpointer tid)
5751 g_hash_table_insert (joinable_threads, tid, (gpointer)OpenThread (SYNCHRONIZE, TRUE, (MonoNativeThreadId)(guint64)tid));
5753 #endif
5755 static void
5756 threads_add_pending_joinable_thread (gpointer tid)
5758 joinable_threads_lock ();
5760 if (!pending_joinable_threads)
5761 pending_joinable_threads = g_hash_table_new (NULL, NULL);
5763 gpointer orig_key;
5764 gpointer value;
5766 if (!g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5767 g_hash_table_insert (pending_joinable_threads, tid, tid);
5768 UnlockedIncrement (&pending_joinable_thread_count);
5771 joinable_threads_unlock ();
5774 static void
5775 threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info)
5777 g_assert (mono_thread_info);
5779 if (mono_thread_info->runtime_thread) {
5780 threads_add_pending_joinable_thread ((gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info))));
5784 static void
5785 threads_remove_pending_joinable_thread_nolock (gpointer tid)
5787 gpointer orig_key;
5788 gpointer value;
5790 if (pending_joinable_threads && g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5791 g_hash_table_remove (pending_joinable_threads, tid);
5792 if (UnlockedDecrement (&pending_joinable_thread_count) == 0)
5793 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event);
5797 static gboolean
5798 threads_wait_pending_joinable_threads (uint32_t timeout)
5800 if (UnlockedRead (&pending_joinable_thread_count) > 0) {
5801 joinable_threads_lock ();
5802 if (timeout == MONO_INFINITE_WAIT) {
5803 while (UnlockedRead (&pending_joinable_thread_count) > 0)
5804 mono_coop_cond_wait (&zero_pending_joinable_thread_event, &joinable_threads_mutex);
5805 } else {
5806 gint64 start = mono_msec_ticks ();
5807 gint64 elapsed = 0;
5808 while (UnlockedRead (&pending_joinable_thread_count) > 0 && elapsed < timeout) {
5809 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event, &joinable_threads_mutex, timeout - (uint32_t)elapsed);
5810 elapsed = mono_msec_ticks () - start;
5813 joinable_threads_unlock ();
5816 return UnlockedRead (&pending_joinable_thread_count) == 0;
5819 static void
5820 threads_add_unique_joinable_thread_nolock (gpointer tid)
5822 if (!joinable_threads)
5823 joinable_threads = g_hash_table_new (NULL, NULL);
5825 gpointer orig_key;
5826 gpointer value;
5828 if (!g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5829 threads_add_joinable_thread_nolock (tid);
5830 UnlockedIncrement (&joinable_thread_count);
5834 void
5835 mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info)
5837 g_assert (thread_info);
5838 MonoThreadInfo *mono_thread_info = thread_info;
5840 if (mono_thread_info->runtime_thread) {
5841 gpointer tid = (gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info)));
5843 joinable_threads_lock ();
5845 // Add to joinable thread list, if not already included.
5846 threads_add_unique_joinable_thread_nolock (tid);
5848 // Remove thread from pending joinable list, if present.
5849 threads_remove_pending_joinable_thread_nolock (tid);
5851 joinable_threads_unlock ();
5853 mono_gc_finalize_notify ();
5857 static void
5858 threads_add_pending_native_thread_join_call_nolock (gpointer tid)
5860 if (!pending_native_thread_join_calls)
5861 pending_native_thread_join_calls = g_hash_table_new (NULL, NULL);
5863 gpointer orig_key;
5864 gpointer value;
5866 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value))
5867 g_hash_table_insert (pending_native_thread_join_calls, tid, tid);
5870 static void
5871 threads_remove_pending_native_thread_join_call_nolock (gpointer tid)
5873 if (pending_native_thread_join_calls)
5874 g_hash_table_remove (pending_native_thread_join_calls, tid);
5876 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event);
5879 static void
5880 threads_wait_pending_native_thread_join_call_nolock (gpointer tid)
5882 gpointer orig_key;
5883 gpointer value;
5885 while (g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value)) {
5886 mono_coop_cond_wait (&pending_native_thread_join_calls_event, &joinable_threads_mutex);
5891 * mono_add_joinable_thread:
5893 * Add TID to the list of joinable threads.
5894 * LOCKING: Acquires the threads lock.
5896 void
5897 mono_threads_add_joinable_thread (gpointer tid)
5900 * We cannot detach from threads because it causes problems like
5901 * 2fd16f60/r114307. So we collect them and join them when
5902 * we have time (in the finalizer thread).
5904 joinable_threads_lock ();
5905 threads_add_unique_joinable_thread_nolock (tid);
5906 joinable_threads_unlock ();
5908 mono_gc_finalize_notify ();
5912 * mono_threads_join_threads:
5914 * Join all joinable threads. This is called from the finalizer thread.
5915 * LOCKING: Acquires the threads lock.
5917 void
5918 mono_threads_join_threads (void)
5920 GHashTableIter iter;
5921 gpointer key = NULL;
5922 gpointer value = NULL;
5923 gboolean found = FALSE;
5925 /* Fastpath */
5926 if (!UnlockedRead (&joinable_thread_count))
5927 return;
5929 while (TRUE) {
5930 joinable_threads_lock ();
5931 if (found) {
5932 // Previous native thread join call completed.
5933 threads_remove_pending_native_thread_join_call_nolock (key);
5935 found = FALSE;
5936 if (g_hash_table_size (joinable_threads)) {
5937 g_hash_table_iter_init (&iter, joinable_threads);
5938 g_hash_table_iter_next (&iter, &key, (void**)&value);
5939 g_hash_table_remove (joinable_threads, key);
5940 UnlockedDecrement (&joinable_thread_count);
5941 found = TRUE;
5943 // Add to table of tid's with pending native thread join call.
5944 threads_add_pending_native_thread_join_call_nolock (key);
5946 joinable_threads_unlock ();
5947 if (found)
5948 threads_native_thread_join_lock (key, value);
5949 else
5950 break;
5955 * mono_thread_join:
5957 * Wait for thread TID to exit.
5958 * LOCKING: Acquires the threads lock.
5960 void
5961 mono_thread_join (gpointer tid)
5963 gboolean found = FALSE;
5964 gpointer orig_key;
5965 gpointer value;
5967 joinable_threads_lock ();
5968 if (!joinable_threads)
5969 joinable_threads = g_hash_table_new (NULL, NULL);
5971 if (g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5972 g_hash_table_remove (joinable_threads, tid);
5973 UnlockedDecrement (&joinable_thread_count);
5974 found = TRUE;
5976 // Add to table of tid's with pending native join call.
5977 threads_add_pending_native_thread_join_call_nolock (tid);
5980 if (!found) {
5981 // Wait for any pending native thread join call not yet completed for this tid.
5982 threads_wait_pending_native_thread_join_call_nolock (tid);
5985 joinable_threads_unlock ();
5987 if (!found)
5988 return;
5990 threads_native_thread_join_nolock (tid, value);
5992 joinable_threads_lock ();
5993 // Native thread join call completed for this tid.
5994 threads_remove_pending_native_thread_join_call_nolock (tid);
5995 joinable_threads_unlock ();
5998 void
5999 mono_thread_internal_unhandled_exception (MonoObject* exc)
6001 MonoClass *klass = exc->vtable->klass;
6002 if (is_threadabort_exception (klass)) {
6003 mono_thread_internal_reset_abort (mono_thread_internal_current ());
6004 } else if (!is_appdomainunloaded_exception (klass)
6005 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
6006 mono_unhandled_exception_internal (exc);
6007 if (mono_environment_exitcode_get () == 1) {
6008 mono_environment_exitcode_set (255);
6009 mono_invoke_unhandled_exception_hook (exc);
6010 g_assert_not_reached ();
6016 * mono_threads_attach_coop_internal: called by native->managed wrappers
6018 * - @cookie:
6019 * - blocking mode: contains gc unsafe transition cookie
6020 * - non-blocking mode: contains random data
6021 * - @stackdata: semi-opaque struct: stackpointer and function_name
6022 * - @return: the original domain which needs to be restored, or NULL.
6024 MonoDomain*
6025 mono_threads_attach_coop_internal (MonoDomain *domain, gpointer *cookie, MonoStackData *stackdata)
6027 MonoDomain *orig;
6028 MonoThreadInfo *info;
6029 gboolean external = FALSE;
6031 orig = mono_domain_get ();
6033 if (!domain) {
6034 /* Happens when called from AOTed code which is only used in the root domain. */
6035 domain = mono_get_root_domain ();
6036 g_assert (domain);
6039 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
6040 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
6041 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
6042 * we're only responsible for making the cookie. */
6043 if (mono_threads_is_blocking_transition_enabled ())
6044 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
6046 if (!mono_thread_internal_current ()) {
6047 mono_thread_attach (domain);
6049 // #678164
6050 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
6053 if (mono_threads_is_blocking_transition_enabled ()) {
6054 if (external) {
6055 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
6056 * return the right cookie. */
6057 *cookie = mono_threads_enter_gc_unsafe_region_cookie ();
6058 } else {
6059 /* thread state (BLOCKING|RUNNING) -> RUNNING */
6060 *cookie = mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata);
6064 if (orig != domain)
6065 mono_domain_set_fast (domain, TRUE);
6067 return orig;
6071 * mono_threads_attach_coop: called by native->managed wrappers
6073 * - @dummy:
6074 * - blocking mode: contains gc unsafe transition cookie
6075 * - non-blocking mode: contains random data
6076 * - a pointer to stack, used for some checks
6077 * - @return: the original domain which needs to be restored, or NULL.
6079 gpointer
6080 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
6082 MONO_STACKDATA (stackdata);
6083 stackdata.stackpointer = dummy;
6084 return mono_threads_attach_coop_internal (domain, dummy, &stackdata);
6088 * mono_threads_detach_coop_internal: called by native->managed wrappers
6090 * - @orig: the original domain which needs to be restored, or NULL.
6091 * - @stackdata: semi-opaque struct: stackpointer and function_name
6092 * - @cookie:
6093 * - blocking mode: contains gc unsafe transition cookie
6094 * - non-blocking mode: contains random data
6096 void
6097 mono_threads_detach_coop_internal (MonoDomain *orig, gpointer cookie, MonoStackData *stackdata)
6099 MonoDomain *domain = mono_domain_get ();
6100 g_assert (domain);
6102 if (orig != domain) {
6103 if (!orig)
6104 mono_domain_unset ();
6105 else
6106 mono_domain_set_fast (orig, TRUE);
6109 if (mono_threads_is_blocking_transition_enabled ()) {
6110 /* it won't do anything if cookie is NULL
6111 * thread state RUNNING -> (RUNNING|BLOCKING) */
6112 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie, stackdata);
6117 * mono_threads_detach_coop: called by native->managed wrappers
6119 * - @orig: the original domain which needs to be restored, or NULL.
6120 * - @dummy:
6121 * - blocking mode: contains gc unsafe transition cookie
6122 * - non-blocking mode: contains random data
6123 * - a pointer to stack, used for some checks
6125 void
6126 mono_threads_detach_coop (gpointer orig, gpointer *dummy)
6128 MONO_STACKDATA (stackdata);
6129 stackdata.stackpointer = dummy;
6130 mono_threads_detach_coop_internal ((MonoDomain*)orig, *dummy, &stackdata);
6133 #if 0
6134 /* Returns TRUE if the current thread is ready to be interrupted. */
6135 gboolean
6136 mono_threads_is_ready_to_be_interrupted (void)
6138 MonoInternalThread *thread;
6140 thread = mono_thread_internal_current ();
6141 LOCK_THREAD (thread);
6142 if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
6143 UNLOCK_THREAD (thread);
6144 return FALSE;
6147 if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6148 UNLOCK_THREAD (thread);
6149 return FALSE;
6152 UNLOCK_THREAD (thread);
6153 return TRUE;
6155 #endif
6157 void
6158 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
6160 g_string_append_printf (text, ", thread handle : %p", internal->handle);
6162 if (internal->thread_info) {
6163 g_string_append (text, ", state : ");
6164 mono_thread_info_describe_interrupt_token (internal->thread_info, text);
6167 if (internal->owned_mutexes) {
6168 int i;
6170 g_string_append (text, ", owns : [");
6171 for (i = 0; i < internal->owned_mutexes->len; i++)
6172 g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
6173 g_string_append (text, "]");
6177 gboolean
6178 mono_thread_internal_is_current (MonoInternalThread *internal)
6180 g_assert (internal);
6181 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
6184 void
6185 mono_set_thread_dump_dir (gchar* dir) {
6186 thread_dump_dir = dir;
6189 #ifdef DISABLE_CRASH_REPORTING
6190 void
6191 mono_threads_summarize_init (void)
6195 gboolean
6196 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6198 return FALSE;
6201 gboolean
6202 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6204 return FALSE;
6207 #else
6209 static gboolean
6210 mono_threads_summarize_native_self (MonoThreadSummary *out, MonoContext *ctx)
6212 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6213 return FALSE;
6215 memset (out, 0, sizeof (MonoThreadSummary));
6216 out->ctx = ctx;
6218 MonoNativeThreadId current = mono_native_thread_id_get();
6219 out->native_thread_id = (intptr_t) current;
6221 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out);
6223 mono_native_thread_get_name (current, out->name, MONO_MAX_SUMMARY_NAME_LEN);
6225 return TRUE;
6228 // Not safe to call from signal handler
6229 gboolean
6230 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6232 gboolean success = mono_threads_summarize_native_self (out, ctx);
6234 // Finish this on the same thread
6236 if (success && mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6237 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out);
6239 return success;
6242 #define MAX_NUM_THREADS 128
6243 typedef struct {
6244 gint32 has_owner; // state of this memory
6246 MonoSemType update; // notify of addition of threads
6248 int nthreads;
6249 MonoNativeThreadId thread_array [MAX_NUM_THREADS]; // ids of threads we're dumping
6251 int nthreads_attached; // Number of threads self-registered
6252 MonoThreadSummary *all_threads [MAX_NUM_THREADS];
6254 gboolean silent; // print to stdout
6255 } SummarizerGlobalState;
6257 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && defined(HAVE_EXECVE) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6258 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6259 #endif
6261 static void
6262 summarizer_supervisor_init (void);
6264 typedef struct {
6265 MonoSemType supervisor;
6266 pid_t pid;
6267 pid_t supervisor_pid;
6268 } SummarizerSupervisorState;
6270 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6272 void
6273 summarizer_supervisor_init (void)
6275 return;
6278 static pid_t
6279 summarizer_supervisor_start (SummarizerSupervisorState *state)
6281 // nonzero, so caller doesn't think it's the supervisor
6282 return (pid_t) 1;
6285 static void
6286 summarizer_supervisor_end (SummarizerSupervisorState *state)
6288 return;
6291 #else
6292 static const char *hang_watchdog_path;
6294 void
6295 summarizer_supervisor_init (void)
6297 hang_watchdog_path = g_build_filename (mono_get_config_dir (), "..", "bin", "mono-hang-watchdog", NULL);
6298 g_assert (hang_watchdog_path);
6301 static pid_t
6302 summarizer_supervisor_start (SummarizerSupervisorState *state)
6304 memset (state, 0, sizeof (*state));
6305 pid_t pid;
6307 state->pid = getpid();
6310 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6311 * it will deadlock. Call the syscall directly instead.
6313 #if defined(HOST_ANDROID)
6314 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6315 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6316 g_assert_not_reached ();
6317 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6318 pid = (pid_t) syscall (SYS_fork);
6319 #elif HAVE_FORK
6320 pid = (pid_t) fork ();
6321 #else
6322 g_assert_not_reached ();
6323 #endif
6325 if (pid != 0)
6326 state->supervisor_pid = pid;
6327 else {
6328 char pid_str[20]; // pid is a uint64_t, 20 digits max in decimal form
6329 sprintf (pid_str, "%" PRIu64, (uint64_t)state->pid);
6330 const char *const args[] = { hang_watchdog_path, pid_str, NULL };
6331 execve (args[0], (char * const*)args, NULL); // run 'mono-hang-watchdog [pid]'
6332 g_async_safe_printf ("Could not exec mono-hang-watchdog, expected on path '%s' (errno %d)\n", hang_watchdog_path, errno);
6333 exit (1);
6336 return pid;
6339 static void
6340 summarizer_supervisor_end (SummarizerSupervisorState *state)
6342 #ifdef HAVE_KILL
6343 kill (state->supervisor_pid, SIGKILL);
6344 #endif
6346 #if defined (HAVE_WAITPID)
6347 // Accessed on same thread that sets it.
6348 int status;
6349 waitpid (state->supervisor_pid, &status, 0);
6350 #endif
6352 #endif
6354 static void
6355 collect_thread_id (gpointer key, gpointer value, gpointer user)
6357 CollectThreadIdsUserData *ud = (CollectThreadIdsUserData *)user;
6358 MonoInternalThread *thread = (MonoInternalThread *)value;
6360 if (ud->nthreads < ud->max_threads)
6361 ud->threads [ud->nthreads ++] = thread_get_tid (thread);
6364 static int
6365 collect_thread_ids (MonoNativeThreadId *thread_ids, int max_threads)
6367 CollectThreadIdsUserData ud;
6369 mono_memory_barrier ();
6370 if (!threads)
6371 return 0;
6373 memset (&ud, 0, sizeof (ud));
6374 /* This array contains refs, but its on the stack, so its ok */
6375 ud.threads = thread_ids;
6376 ud.max_threads = max_threads;
6378 mono_threads_lock ();
6379 mono_g_hash_table_foreach (threads, collect_thread_id, &ud);
6380 mono_threads_unlock ();
6382 return ud.nthreads;
6385 static gboolean
6386 summarizer_state_init (SummarizerGlobalState *state, MonoNativeThreadId current, int *my_index)
6388 gint32 started_state = mono_atomic_cas_i32 (&state->has_owner, 1 /* set */, 0 /* compare */);
6389 gboolean not_started = started_state == 0;
6390 if (not_started) {
6391 state->nthreads = collect_thread_ids (state->thread_array, MAX_NUM_THREADS);
6392 mono_os_sem_init (&state->update, 0);
6395 for (int i = 0; i < state->nthreads; i++) {
6396 if (state->thread_array [i] == current) {
6397 *my_index = i;
6398 break;
6402 return not_started;
6405 static void
6406 summarizer_signal_other_threads (SummarizerGlobalState *state, MonoNativeThreadId current, int current_idx)
6408 sigset_t sigset, old_sigset;
6409 sigemptyset(&sigset);
6410 sigaddset(&sigset, SIGTERM);
6412 for (int i=0; i < state->nthreads; i++) {
6413 sigprocmask (SIG_UNBLOCK, &sigset, &old_sigset);
6415 if (i == current_idx)
6416 continue;
6417 #ifdef HAVE_PTHREAD_KILL
6418 pthread_kill (state->thread_array [i], SIGTERM);
6420 if (!state->silent)
6421 g_async_safe_printf("Pkilling 0x%" G_GSIZE_FORMAT "x from 0x%" G_GSIZE_FORMAT "x\n", (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (state->thread_array [i]), (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (current));
6422 #else
6423 g_error ("pthread_kill () is not supported by this platform");
6424 #endif
6428 // Returns true when there are shared global references to "this_thread"
6429 static gboolean
6430 summarizer_post_dump (SummarizerGlobalState *state, MonoThreadSummary *this_thread, int current_idx)
6432 mono_memory_barrier ();
6434 gpointer old = mono_atomic_cas_ptr ((volatile gpointer *)&state->all_threads [current_idx], this_thread, NULL);
6436 if (old == GINT_TO_POINTER (-1)) {
6437 g_async_safe_printf ("Trying to register response after dumping period ended");
6438 return FALSE;
6439 } else if (old != NULL) {
6440 g_async_safe_printf ("Thread dump raced for thread slot.");
6441 return FALSE;
6444 // We added our pointer
6445 gint32 count = mono_atomic_inc_i32 ((volatile gint32 *) &state->nthreads_attached);
6446 if (count == state->nthreads)
6447 mono_os_sem_post (&state->update);
6449 return TRUE;
6452 // A lockless spinwait with a timeout
6453 // Used in environments where locks are unsafe
6455 // If set_pos is true, we wait until the expected number of threads have
6456 // responded and then count that the expected number are set. If it is not true,
6457 // then we wait for them to be unset.
6458 static void
6459 summary_timedwait (SummarizerGlobalState *state, int timeout_seconds)
6461 const gint64 milliseconds_in_second = 1000;
6462 gint64 timeout_total = milliseconds_in_second * timeout_seconds;
6464 gint64 end = mono_msec_ticks () + timeout_total;
6466 while (TRUE) {
6467 if (mono_atomic_load_i32 ((volatile gint32 *) &state->nthreads_attached) == state->nthreads)
6468 break;
6470 gint64 now = mono_msec_ticks ();
6471 gint64 remaining = end - now;
6472 if (remaining <= 0)
6473 break;
6475 mono_os_sem_timedwait (&state->update, remaining, MONO_SEM_FLAGS_NONE);
6478 return;
6481 static MonoThreadSummary *
6482 summarizer_try_read_thread (SummarizerGlobalState *state, int index)
6484 gpointer old_value = NULL;
6485 gpointer new_value = GINT_TO_POINTER(-1);
6487 do {
6488 old_value = state->all_threads [index];
6489 } while (mono_atomic_cas_ptr ((volatile gpointer *) &state->all_threads [index], new_value, old_value) != old_value);
6491 MonoThreadSummary *thread = (MonoThreadSummary *) old_value;
6492 return thread;
6495 static void
6496 summarizer_state_term (SummarizerGlobalState *state, gchar **out, gchar *mem, size_t provided_size, MonoThreadSummary *controlling)
6498 // See the array writes
6499 mono_memory_barrier ();
6501 MonoThreadSummary *threads [MAX_NUM_THREADS];
6502 memset (threads, 0, sizeof(threads));
6504 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6505 for (int i=0; i < state->nthreads; i++) {
6506 threads [i] = summarizer_try_read_thread (state, i);
6507 if (!threads [i])
6508 continue;
6510 // We are doing this dump on the controlling thread because this isn't
6511 // an async context sometimes. There's still some reliance on malloc here, but it's
6512 // much more stable to do it all from the controlling thread.
6514 // This is non-null, checked in mono_threads_summarize
6515 // with early exit there
6516 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads [i]);
6519 /* The value of the breadcrumb should match the "StackHash" value written by `mono_merp_write_fingerprint_payload` */
6520 mono_create_crash_hash_breadcrumb (controlling);
6522 MonoStateWriter writer;
6523 memset (&writer, 0, sizeof (writer));
6525 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6526 mono_summarize_native_state_begin (&writer, mem, provided_size);
6527 for (int i=0; i < state->nthreads; i++) {
6528 MonoThreadSummary *thread = threads [i];
6529 if (!thread)
6530 continue;
6532 mono_summarize_native_state_add_thread (&writer, thread, thread->ctx, thread == controlling);
6533 // Set non-shared state to notify the waiting thread to clean up
6534 // without having to keep our shared state alive
6535 mono_atomic_store_i32 (&thread->done, 0x1);
6536 mono_os_sem_post (&thread->done_wait);
6538 *out = mono_summarize_native_state_end (&writer);
6539 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6541 mono_os_sem_destroy (&state->update);
6543 memset (state, 0, sizeof (*state));
6544 mono_atomic_store_i32 ((volatile gint32 *)&state->has_owner, 0);
6547 static void
6548 summarizer_state_wait (MonoThreadSummary *thread)
6550 gint64 milliseconds_in_second = 1000;
6552 // cond_wait can spuriously wake up, so we need to check
6553 // done
6554 while (!mono_atomic_load_i32 (&thread->done))
6555 mono_os_sem_timedwait (&thread->done_wait, milliseconds_in_second, MONO_SEM_FLAGS_NONE);
6558 static gboolean
6559 mono_threads_summarize_execute_internal (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size, gboolean this_thread_controls)
6561 static SummarizerGlobalState state;
6563 int current_idx;
6564 MonoNativeThreadId current = mono_native_thread_id_get ();
6565 gboolean thread_given_control = summarizer_state_init (&state, current, &current_idx);
6567 g_assert (this_thread_controls == thread_given_control);
6569 if (state.nthreads == 0) {
6570 if (!silent)
6571 g_async_safe_printf("No threads attached to runtime.\n");
6572 memset (&state, 0, sizeof (state));
6573 return FALSE;
6576 if (this_thread_controls) {
6577 g_assert (working_mem);
6579 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6580 state.silent = silent;
6581 summarizer_signal_other_threads (&state, current, current_idx);
6582 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6585 MonoStateMem mem;
6586 gboolean success = mono_state_alloc_mem (&mem, (long) current, sizeof (MonoThreadSummary));
6587 if (!success)
6588 return FALSE;
6590 MonoThreadSummary *this_thread = (MonoThreadSummary *) mem.mem;
6592 if (mono_threads_summarize_native_self (this_thread, ctx)) {
6593 // Init the synchronization between the controlling thread and the
6594 // providing thread
6595 mono_os_sem_init (&this_thread->done_wait, 0);
6597 // Store a reference to our stack memory into global state
6598 gboolean success = summarizer_post_dump (&state, this_thread, current_idx);
6599 if (!success && !state.silent)
6600 g_async_safe_printf("Thread 0x%" G_GSIZE_FORMAT "x reported itself.\n", (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (current));
6601 } else if (!state.silent) {
6602 g_async_safe_printf("Thread 0x%" G_GSIZE_FORMAT "x couldn't report itself.\n", (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (current));
6605 // From summarizer, wait and dump.
6606 if (this_thread_controls) {
6607 if (!state.silent)
6608 g_async_safe_printf("Entering thread summarizer pause from 0x%" G_GSIZE_FORMAT "x\n", (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (current));
6610 // Wait up to 2 seconds for all of the other threads to catch up
6611 summary_timedwait (&state, 2);
6613 if (!state.silent)
6614 g_async_safe_printf("Finished thread summarizer pause from 0x%" G_GSIZE_FORMAT "x.\n", (gsize)MONO_NATIVE_THREAD_ID_TO_UINT (current));
6616 // Dump and cleanup all the stack memory
6617 summarizer_state_term (&state, out, working_mem, provided_size, this_thread);
6618 } else {
6619 // Wait here, keeping our stack memory alive
6620 // for the dumper
6621 summarizer_state_wait (this_thread);
6624 // FIXME: How many threads should be counted?
6625 if (hashes)
6626 *hashes = this_thread->hashes;
6628 mono_state_free_mem (&mem);
6630 return TRUE;
6633 void
6634 mono_threads_summarize_init (void)
6636 summarizer_supervisor_init ();
6639 gboolean
6640 mono_threads_summarize_execute (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size)
6642 gboolean result;
6643 gboolean already_async = mono_thread_info_is_async_context ();
6644 if (!already_async)
6645 mono_thread_info_set_is_async_context (TRUE);
6646 result = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, working_mem, provided_size, FALSE);
6647 if (!already_async)
6648 mono_thread_info_set_is_async_context (FALSE);
6649 return result;
6652 gboolean
6653 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6655 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6656 return FALSE;
6658 // The staggered values are due to the need to use inc_i64 for the first value
6659 static gint64 next_pending_request_id = 0;
6660 static gint64 request_available_to_run = 1;
6661 gint64 this_request_id = mono_atomic_inc_i64 ((volatile gint64 *) &next_pending_request_id);
6663 // This is a global queue of summary requests.
6664 // It's not safe to signal a thread while they're in the
6665 // middle of a dump. Dladdr is not reentrant. It's the one lock
6666 // we rely on being able to take.
6668 // We don't use it in almost any other place in managed code, so
6669 // our problem is in the stack dumping code racing with the signalling code.
6671 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6672 // If we're running from a crash handler block, we're not in any position to
6673 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6674 // We should simply return so we can die cleanly.
6676 // signal_handler_controller should be set only from a handler that expects itself to be the only
6677 // entry point, where the runtime already being dumping means we should just give up
6679 gboolean success = FALSE;
6681 while (TRUE) {
6682 gint64 next_request_id = mono_atomic_load_i64 ((volatile gint64 *) &request_available_to_run);
6684 if (next_request_id == this_request_id) {
6685 gboolean already_async = mono_thread_info_is_async_context ();
6686 if (!already_async)
6687 mono_thread_info_set_is_async_context (TRUE);
6689 SummarizerSupervisorState synch;
6690 if (summarizer_supervisor_start (&synch)) {
6691 g_assert (mem);
6692 success = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, mem, provided_size, TRUE);
6693 summarizer_supervisor_end (&synch);
6696 if (!already_async)
6697 mono_thread_info_set_is_async_context (FALSE);
6699 // Only the thread that gets the ticket can unblock future dumpers.
6700 mono_atomic_inc_i64 ((volatile gint64 *) &request_available_to_run);
6701 break;
6702 } else if (signal_handler_controller) {
6703 // We're done. We can't do anything.
6704 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6705 mono_summarize_double_fault_log ();
6706 break;
6707 } else {
6708 if (!silent)
6709 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6710 sleep (2);
6714 return success;
6717 #endif
6719 #ifdef ENABLE_NETCORE
6720 void
6721 ves_icall_System_Threading_Thread_StartInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6723 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6724 gboolean res;
6726 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p)", __func__, internal));
6728 #ifdef DISABLE_THREADS
6729 mono_error_set_not_supported (error, NULL);
6730 return;
6731 #endif
6733 LOCK_THREAD (internal);
6735 if ((internal->state & ThreadState_Unstarted) == 0) {
6736 UNLOCK_THREAD (internal);
6737 mono_error_set_exception_thread_state (error, "Thread has already been started.");
6738 return;
6741 if ((internal->state & ThreadState_Aborted) != 0) {
6742 UNLOCK_THREAD (internal);
6743 return;
6746 res = create_thread (internal, internal, NULL, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
6747 if (!res) {
6748 UNLOCK_THREAD (internal);
6749 return;
6752 internal->state &= ~ThreadState_Unstarted;
6754 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, (gsize)internal->tid, internal->handle));
6756 UNLOCK_THREAD (internal);
6759 void
6760 ves_icall_System_Threading_Thread_InitInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6762 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6764 // Need to initialize thread objects created from managed code
6765 init_internal_thread_object (internal);
6766 internal->state = ThreadState_Unstarted;
6767 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
6770 guint64
6771 ves_icall_System_Threading_Thread_GetCurrentOSThreadId (MonoError *error)
6773 return mono_native_thread_os_id_get ();
6776 gint32
6777 ves_icall_System_Threading_Thread_GetCurrentProcessorNumber (MonoError *error)
6779 return mono_native_thread_processor_id_get ();
6782 #endif