remove GenericVectorTests from rsp (#17366)
[mono-project.git] / mono / metadata / threads.c
blobcfb9876d49731788b2949ba9e2f7526e39a60fd6
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>
63 #ifdef HAVE_SYS_WAIT_H
64 #include <sys/wait.h>
65 #endif
67 #ifdef HAVE_SIGNAL_H
68 #include <signal.h>
69 #endif
71 #if defined(HOST_WIN32)
72 #include <objbase.h>
73 #include <sys/timeb.h>
74 extern gboolean
75 mono_native_thread_join_handle (HANDLE thread_handle, gboolean close_handle);
76 #endif
78 #if defined(HOST_FUCHSIA)
79 #include <zircon/syscalls.h>
80 #endif
82 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
83 #define USE_TKILL_ON_ANDROID 1
84 #endif
86 #ifdef HOST_ANDROID
87 #include <errno.h>
89 #ifdef USE_TKILL_ON_ANDROID
90 extern int tkill (pid_t tid, int signal);
91 #endif
92 #endif
94 #include "icall-decl.h"
96 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
97 #define THREAD_DEBUG(a)
98 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
99 #define THREAD_WAIT_DEBUG(a)
100 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
101 #define LIBGC_DEBUG(a)
103 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
104 #define SPIN_LOCK(i) do { \
105 if (SPIN_TRYLOCK (i)) \
106 break; \
107 } while (1)
109 #define SPIN_UNLOCK(i) i = 0
111 #define LOCK_THREAD(thread) lock_thread((thread))
112 #define UNLOCK_THREAD(thread) unlock_thread((thread))
114 typedef union {
115 gint32 ival;
116 gfloat fval;
117 } IntFloatUnion;
119 typedef union {
120 gint64 ival;
121 gdouble fval;
122 } LongDoubleUnion;
124 typedef struct _StaticDataFreeList StaticDataFreeList;
125 struct _StaticDataFreeList {
126 StaticDataFreeList *next;
127 guint32 offset;
128 guint32 size;
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 static MonoClassField *current_thread_field = NULL;
628 guint32 offset;
630 if (!current_thread_field) {
631 current_thread_field = mono_class_get_field_from_name_full (mono_defaults.thread_class, "current_thread", NULL);
632 g_assert (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 static MonoMethod *cb;
1238 /* Call a callback in the RuntimeThread class */
1239 g_assert (start_delegate == NULL);
1240 if (!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_runtime_invoke_checked (cb, internal, NULL, error);
1246 #else
1247 void *args [1];
1249 g_assert (start_delegate != NULL);
1251 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1252 args [0] = (gpointer) start_delegate_arg;
1253 mono_runtime_delegate_invoke_checked (start_delegate, args, error);
1254 #endif
1256 if (!is_ok (error)) {
1257 MonoException *ex = mono_error_convert_to_exception (error);
1259 g_assert (ex != NULL);
1260 MonoClass *klass = mono_object_class (ex);
1261 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
1262 !is_threadabort_exception (klass)) {
1263 mono_unhandled_exception_internal (&ex->object);
1264 mono_invoke_unhandled_exception_hook (&ex->object);
1265 g_assert_not_reached ();
1267 } else {
1268 mono_error_cleanup (error);
1272 /* If the thread calls ExitThread at all, this remaining code
1273 * will not be executed, but the main thread will eventually
1274 * call mono_thread_detach_internal() on this thread's behalf.
1277 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
1279 /* Do any cleanup needed for apartment state. This
1280 * cannot be done in mono_thread_detach_internal since
1281 * mono_thread_detach_internal could be called for a
1282 * thread other than the current thread.
1283 * mono_thread_cleanup_apartment_state cleans up apartment
1284 * for the current thead */
1285 mono_thread_cleanup_apartment_state ();
1287 mono_thread_detach_internal (internal);
1289 return 0;
1292 static mono_thread_start_return_t WINAPI
1293 start_wrapper (gpointer data)
1295 StartInfo *start_info;
1296 MonoThreadInfo *info;
1297 gsize res;
1299 start_info = (StartInfo*) data;
1300 g_assert (start_info);
1302 info = mono_thread_info_attach ();
1303 info->runtime_thread = TRUE;
1305 /* Run the actual main function of the thread */
1306 res = start_wrapper_internal (start_info, (gsize*)info->stack_end);
1308 mono_thread_info_exit (res);
1310 g_assert_not_reached ();
1314 * create_thread:
1316 * Common thread creation code.
1317 * LOCKING: Acquires the threads lock.
1319 static gboolean
1320 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
1321 MonoThreadCreateFlags flags, MonoError *error)
1323 StartInfo *start_info = NULL;
1324 MonoNativeThreadId tid;
1325 gboolean ret;
1326 gsize stack_set_size;
1328 if (start_delegate)
1329 g_assert (!start_func && !start_func_arg);
1330 if (start_func)
1331 g_assert (!start_delegate);
1333 if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
1334 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
1335 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1337 if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
1338 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
1339 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1343 * Join joinable threads to prevent running out of threads since the finalizer
1344 * thread might be blocked/backlogged.
1346 mono_threads_join_threads ();
1348 error_init (error);
1350 mono_threads_lock ();
1351 if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
1352 mono_threads_unlock ();
1353 mono_error_set_execution_engine (error, "Couldn't create thread. Runtime is shutting down.");
1354 return FALSE;
1356 if (threads_starting_up == NULL) {
1357 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");
1359 mono_g_hash_table_insert_internal (threads_starting_up, thread, thread);
1360 mono_threads_unlock ();
1362 internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
1363 if (internal->threadpool_thread)
1364 mono_thread_set_state (internal, ThreadState_Background);
1366 internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
1368 start_info = g_new0 (StartInfo, 1);
1369 start_info->ref = 2;
1370 start_info->thread = thread;
1371 start_info->start_delegate = start_delegate;
1372 start_info->start_delegate_arg = thread->start_obj;
1373 start_info->start_func = start_func;
1374 start_info->start_func_arg = start_func_arg;
1375 start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
1376 start_info->failed = FALSE;
1377 mono_coop_sem_init (&start_info->registered, 0);
1379 if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
1380 stack_set_size = default_stacksize_for_thread (internal);
1381 else
1382 stack_set_size = 0;
1384 if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
1385 /* The thread couldn't be created, so set an exception */
1386 mono_threads_lock ();
1387 mono_g_hash_table_remove (threads_starting_up, thread);
1388 mono_threads_unlock ();
1389 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1390 /* ref is not going to be decremented in start_wrapper_internal */
1391 mono_atomic_dec_i32 (&start_info->ref);
1392 ret = FALSE;
1393 goto done;
1396 internal->stack_size = (int) stack_set_size;
1398 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1401 * Wait for the thread to set up its TLS data etc, so
1402 * theres no potential race condition if someone tries
1403 * to look up the data believing the thread has
1404 * started
1407 mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1409 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));
1411 ret = !start_info->failed;
1413 done:
1414 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1415 mono_coop_sem_destroy (&start_info->registered);
1416 g_free (start_info);
1419 return ret;
1423 * mono_thread_new_init:
1425 void
1426 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1428 if (mono_thread_start_cb) {
1429 mono_thread_start_cb (tid, stack_start, func);
1434 * mono_threads_set_default_stacksize:
1436 void
1437 mono_threads_set_default_stacksize (guint32 stacksize)
1439 default_stacksize = stacksize;
1443 * mono_threads_get_default_stacksize:
1445 guint32
1446 mono_threads_get_default_stacksize (void)
1448 return default_stacksize;
1452 * mono_thread_create_internal:
1454 * ARG should not be a GC reference.
1456 MonoInternalThread*
1457 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1459 MonoThread *thread;
1460 MonoInternalThread *internal;
1461 gboolean res;
1463 error_init (error);
1465 internal = create_internal_thread_object ();
1467 thread = create_thread_object (domain, internal);
1469 LOCK_THREAD (internal);
1471 res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1472 (void)res;
1474 UNLOCK_THREAD (internal);
1476 return_val_if_nok (error, NULL);
1477 return internal;
1480 MonoInternalThreadHandle
1481 mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1483 // FIXME invert
1484 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_create_internal (domain, func, arg, flags, error));
1488 * mono_thread_create:
1490 void
1491 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1493 MONO_ENTER_GC_UNSAFE;
1494 ERROR_DECL (error);
1495 if (!mono_thread_create_checked (domain, func, arg, error))
1496 mono_error_cleanup (error);
1497 MONO_EXIT_GC_UNSAFE;
1500 gboolean
1501 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1503 return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1507 * mono_thread_attach:
1509 MonoThread *
1510 mono_thread_attach (MonoDomain *domain)
1512 MonoInternalThread *internal;
1513 MonoThread *thread;
1514 MonoThreadInfo *info;
1515 MonoNativeThreadId tid;
1517 if (mono_thread_internal_current_is_attached ()) {
1518 if (domain != mono_domain_get ())
1519 mono_domain_set_fast (domain, TRUE);
1520 /* Already attached */
1521 return mono_thread_current ();
1524 info = mono_thread_info_attach ();
1525 g_assert (info);
1527 tid=mono_native_thread_id_get ();
1529 if (mono_runtime_get_no_exec ())
1530 return NULL;
1532 internal = create_internal_thread_object ();
1534 thread = create_thread_object (domain, internal);
1536 if (!mono_thread_attach_internal (thread, FALSE, TRUE)) {
1537 /* Mono is shutting down, so just wait for the end */
1538 for (;;)
1539 mono_thread_info_sleep (10000, NULL);
1542 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, internal->handle));
1544 if (mono_thread_attach_cb)
1545 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1547 fire_attach_profiler_events (tid);
1549 return thread;
1553 * mono_thread_detach:
1555 void
1556 mono_thread_detach (MonoThread *thread)
1558 if (thread)
1559 mono_thread_detach_internal (thread->internal_thread);
1563 * mono_thread_detach_if_exiting:
1565 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1566 * This should be used at the end of embedding code which calls into managed code, and which
1567 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1569 mono_bool
1570 mono_thread_detach_if_exiting (void)
1572 if (mono_thread_info_is_exiting ()) {
1573 MonoInternalThread *thread;
1575 thread = mono_thread_internal_current ();
1576 if (thread) {
1577 // Switch to GC Unsafe thread state before detaching;
1578 // don't expect to undo this switch, hence unbalanced.
1579 gpointer dummy;
1580 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy);
1582 mono_thread_detach_internal (thread);
1583 mono_thread_info_detach ();
1584 return TRUE;
1587 return FALSE;
1590 gboolean
1591 mono_thread_internal_current_is_attached (void)
1593 MonoInternalThread *internal;
1595 internal = GET_CURRENT_OBJECT ();
1596 if (!internal)
1597 return FALSE;
1599 return TRUE;
1603 * mono_thread_exit:
1605 void
1606 mono_thread_exit (void)
1608 MonoInternalThread *thread = mono_thread_internal_current ();
1610 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
1612 mono_thread_detach_internal (thread);
1614 /* we could add a callback here for embedders to use. */
1615 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1616 exit (mono_environment_exitcode_get ());
1618 mono_thread_info_exit (0);
1621 static void
1622 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle)
1624 MonoInternalThread * const internal = create_internal_thread_object ();
1626 internal->state = ThreadState_Unstarted;
1628 int const thread_gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, this_obj_handle), TRUE);
1630 MonoThreadObject *this_obj = MONO_HANDLE_RAW (this_obj_handle);
1632 mono_atomic_cas_ptr ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1634 mono_gchandle_free_internal (thread_gchandle);
1637 #ifndef ENABLE_NETCORE
1638 void
1639 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle, MonoError *error)
1641 mono_thread_construct_internal (this_obj_handle);
1643 #endif
1645 MonoThreadObjectHandle
1646 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError *error)
1648 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
1651 static MonoInternalThread*
1652 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle)
1654 return MONO_HANDLE_GETVAL(thread_handle, internal_thread); // InternalThreads are always pinned.
1657 static void
1658 mono_error_set_exception_thread_state (MonoError *error, const char *exception_message)
1660 mono_error_set_generic_error (error, "System.Threading", "ThreadStateException", "%s", exception_message);
1663 static void
1664 mono_error_set_exception_thread_not_started_or_dead (MonoError *error)
1666 mono_error_set_exception_thread_state (error, "Thread has not been started, or is dead.");
1669 #ifndef ENABLE_NETCORE
1670 MonoBoolean
1671 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle, MonoObjectHandle start_handle, MonoError *error)
1673 MonoInternalThread *internal;
1674 gboolean res;
1675 MonoThread *this_obj = MONO_HANDLE_RAW (thread_handle);
1676 MonoObject *start = MONO_HANDLE_RAW (start_handle);
1678 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1680 internal = thread_handle_to_internal_ptr (thread_handle);
1682 if (!internal) {
1683 mono_thread_construct_internal (thread_handle);
1684 internal = thread_handle_to_internal_ptr (thread_handle);
1685 g_assert (internal);
1688 LOCK_THREAD (internal);
1690 if ((internal->state & ThreadState_Unstarted) == 0) {
1691 UNLOCK_THREAD (internal);
1692 mono_error_set_exception_thread_state (error, "Thread has already been started.");
1693 return FALSE;
1696 if ((internal->state & ThreadState_Aborted) != 0) {
1697 UNLOCK_THREAD (internal);
1698 return TRUE;
1701 res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
1702 if (!res) {
1703 UNLOCK_THREAD (internal);
1704 return FALSE;
1707 internal->state &= ~ThreadState_Unstarted;
1709 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, thread));
1711 UNLOCK_THREAD (internal);
1712 return TRUE;
1714 #endif
1716 static
1717 void
1718 mono_thread_name_cleanup (MonoThreadName* name)
1720 MonoThreadName const old_name = *name;
1721 // Do not reset generation.
1722 name->chars = 0;
1723 name->length = 0;
1724 name->free = 0;
1725 //memset (name, 0, sizeof (*name));
1726 if (old_name.free)
1727 g_free (old_name.chars);
1731 * This is called from the finalizer of the internal thread object.
1733 void
1734 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle, MonoError *error)
1736 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (this_obj_handle);
1737 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this_obj, this_obj->handle));
1740 * Since threads keep a reference to their thread object while running, by
1741 * the time this function is called, the thread has already exited/detached,
1742 * i.e. mono_thread_detach_internal () has ran. The exception is during
1743 * shutdown, when mono_thread_detach_internal () can be called after this.
1745 if (this_obj->handle) {
1746 mono_threads_close_thread_handle (this_obj->handle);
1747 this_obj->handle = NULL;
1750 mono_threads_close_native_thread_handle (MONO_GPOINTER_TO_NATIVE_THREAD_HANDLE (this_obj->native_handle));
1751 this_obj->native_handle = NULL;
1753 /* Possibly free synch_cs, if the thread already detached also. */
1754 dec_longlived_thread_data (this_obj->longlived);
1756 mono_thread_name_cleanup (&this_obj->name);
1759 void
1760 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoError *error)
1762 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1764 if (mono_thread_current_check_pending_interrupt ())
1765 return;
1767 MonoInternalThread * const thread = mono_thread_internal_current ();
1769 HANDLE_LOOP_PREPARE;
1771 while (TRUE) {
1772 gboolean alerted = FALSE;
1774 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1776 (void)mono_thread_info_sleep (ms, &alerted);
1778 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1780 if (!alerted)
1781 return;
1783 SETUP_ICALL_FRAME;
1785 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
1787 const gboolean interrupt = mono_thread_execute_interruption (&exc);
1789 if (interrupt)
1790 mono_set_pending_exception_handle (exc);
1792 CLEAR_ICALL_FRAME;
1794 if (interrupt)
1795 return;
1796 if (ms == MONO_INFINITE_WAIT) // FIXME: !MONO_INFINITE_WAIT
1797 continue;
1798 return;
1802 void
1803 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error)
1807 #ifndef ENABLE_NETCORE
1808 gint32
1809 ves_icall_System_Threading_Thread_GetDomainID (MonoError *error)
1811 return mono_domain_get()->domain_id;
1813 #endif
1816 * mono_thread_get_name_utf8:
1817 * \returns the name of the thread in UTF-8.
1818 * Return NULL if the thread has no name.
1819 * The returned memory is owned by the caller (g_free it).
1821 char *
1822 mono_thread_get_name_utf8 (MonoThread *thread)
1824 if (thread == NULL)
1825 return NULL;
1827 MonoInternalThread *internal = thread->internal_thread;
1829 // This is a little racy, ok.
1831 if (internal == NULL || !internal->name.chars)
1832 return NULL;
1834 LOCK_THREAD (internal);
1836 char *tname = (char*)g_memdup (internal->name.chars, internal->name.length + 1);
1838 UNLOCK_THREAD (internal);
1840 return tname;
1844 * mono_thread_get_managed_id:
1845 * \returns the \c Thread.ManagedThreadId value of \p thread.
1846 * Returns \c -1 if \p thread is NULL.
1848 int32_t
1849 mono_thread_get_managed_id (MonoThread *thread)
1851 if (thread == NULL)
1852 return -1;
1854 MonoInternalThread *internal = thread->internal_thread;
1855 if (internal == NULL)
1856 return -1;
1858 int32_t id = internal->managed_id;
1860 return id;
1863 #ifndef ENABLE_NETCORE
1864 MonoStringHandle
1865 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle, MonoError *error)
1867 // InternalThreads are always pinned, so shallowly coop-handleize.
1868 MonoInternalThread * const this_obj = mono_internal_thread_handle_ptr (thread_handle);
1870 MonoStringHandle str = NULL_HANDLE_STRING;
1872 // This is a little racy, ok.
1874 if (this_obj->name.chars) {
1875 LOCK_THREAD (this_obj);
1877 if (this_obj->name.chars)
1878 str = mono_string_new_utf8_len (mono_domain_get (), this_obj->name.chars, this_obj->name.length, error);
1880 UNLOCK_THREAD (this_obj);
1883 return str;
1885 #endif
1887 // Unusal function:
1888 // - MonoError is optional -- failure is usually not interesting, except the documented failure mode for managed callers.
1889 // - name16 only used on Windows.
1890 // - name8 is either constant, or g_free'able -- this function always takes ownership and never copies.
1892 gsize
1893 mono_thread_set_name (MonoInternalThread *this_obj,
1894 const char* name8, size_t name8_length, const gunichar2* name16,
1895 MonoSetThreadNameFlags flags, MonoError *error)
1897 MonoNativeThreadId tid = 0;
1899 // A counter to optimize redundant sets.
1900 // It is not exactly thread safe but no use of it could be.
1901 gsize name_generation;
1903 const gboolean constant = !!(flags & MonoSetThreadNameFlag_Constant);
1905 #if HOST_WIN32 // On Windows, if name8 is supplied, then name16 must be also.
1906 g_assert (!name8 || name16);
1907 #endif
1909 LOCK_THREAD (this_obj);
1911 name_generation = this_obj->name.generation;
1913 if (flags & MonoSetThreadNameFlag_Reset) {
1914 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1915 } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1916 UNLOCK_THREAD (this_obj);
1918 if (error)
1919 mono_error_set_invalid_operation (error, "%s", "Thread.Name can only be set once.");
1921 if (!constant)
1922 g_free ((char*)name8);
1923 return name_generation;
1926 name_generation = ++this_obj->name.generation;
1928 mono_thread_name_cleanup (&this_obj->name);
1930 if (name8) {
1931 this_obj->name.chars = (char*)name8;
1932 this_obj->name.length = name8_length;
1933 this_obj->name.free = !constant;
1934 if (flags & MonoSetThreadNameFlag_Permanent)
1935 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1938 if (!(this_obj->state & ThreadState_Stopped))
1939 tid = thread_get_tid (this_obj);
1941 UNLOCK_THREAD (this_obj);
1943 if (name8 && tid) {
1944 MONO_PROFILER_RAISE (thread_name, ((uintptr_t)tid, name8));
1945 mono_native_thread_set_name (tid, name8);
1948 mono_thread_set_name_windows (this_obj->native_handle, name16);
1950 mono_free (0); // FIXME keep mono-publib.c in use and its functions exported
1952 return name_generation;
1956 void
1957 ves_icall_System_Threading_Thread_SetName_icall (MonoInternalThreadHandle thread_handle, const gunichar2* name16, gint32 name16_length, MonoError* error)
1959 long name8_length = 0;
1961 char* name8 = name16 ? g_utf16_to_utf8 (name16, name16_length, NULL, &name8_length, NULL) : NULL;
1963 mono_thread_set_name (mono_internal_thread_handle_ptr (thread_handle),
1964 name8, (gint32)name8_length, name16, MonoSetThreadNameFlag_Permanent, error);
1967 #ifndef ENABLE_NETCORE
1969 * ves_icall_System_Threading_Thread_GetPriority_internal:
1970 * @param this_obj: The MonoInternalThread on which to operate.
1972 * Gets the priority of the given thread.
1973 * @return: The priority of the given thread.
1976 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj, MonoError *error)
1978 gint32 priority;
1980 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
1982 LOCK_THREAD (internal);
1983 priority = internal->priority;
1984 UNLOCK_THREAD (internal);
1986 return priority;
1988 #endif
1991 * ves_icall_System_Threading_Thread_SetPriority_internal:
1992 * @param this_obj: The MonoInternalThread on which to operate.
1993 * @param priority: The priority to set.
1995 * Sets the priority of the given thread.
1997 void
1998 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj, int priority, MonoError *error)
2000 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
2002 LOCK_THREAD (internal);
2003 internal->priority = priority;
2004 if (internal->thread_info != NULL)
2005 mono_thread_internal_set_priority (internal, (MonoThreadPriority)priority);
2006 UNLOCK_THREAD (internal);
2009 /* If the array is already in the requested domain, we just return it,
2010 otherwise we return a copy in that domain. */
2011 static MonoArrayHandle
2012 byte_array_to_domain (MonoArrayHandle arr, MonoDomain *domain, MonoError *error)
2014 HANDLE_FUNCTION_ENTER ()
2016 if (MONO_HANDLE_IS_NULL (arr))
2017 return MONO_HANDLE_NEW (MonoArray, NULL);
2019 if (MONO_HANDLE_DOMAIN (arr) == domain)
2020 return arr;
2022 size_t const size = mono_array_handle_length (arr);
2024 // Capture arrays into common representation for repetitious code.
2025 // These two variables could also be an array of size 2 and
2026 // repitition implemented with a loop.
2027 struct {
2028 MonoArrayHandle handle;
2029 gpointer p;
2030 guint gchandle;
2032 source = { arr },
2033 dest = { mono_array_new_handle (domain, mono_defaults.byte_class, size, error) };
2034 goto_if_nok (error, exit);
2036 // Pin both arrays.
2037 source.p = mono_array_handle_pin_with_size (source.handle, size, 0, &source.gchandle);
2038 dest.p = mono_array_handle_pin_with_size (dest.handle, size, 0, &dest.gchandle);
2040 memmove (dest.p, source.p, size);
2041 exit:
2042 // Unpin both arrays.
2043 mono_gchandle_free_internal (source.gchandle);
2044 mono_gchandle_free_internal (dest.gchandle);
2046 HANDLE_FUNCTION_RETURN_REF (MonoArray, dest.handle)
2049 #ifndef ENABLE_NETCORE
2050 MonoArrayHandle
2051 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr, MonoError *error)
2053 return byte_array_to_domain (arr, mono_get_root_domain (), error);
2056 MonoArrayHandle
2057 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr, MonoError *error)
2059 return byte_array_to_domain (arr, mono_domain_get (), error);
2061 #endif
2064 * mono_thread_current:
2066 MonoThread *
2067 mono_thread_current (void)
2069 #ifdef ENABLE_NETCORE
2070 return mono_thread_internal_current ();
2071 #else
2072 MonoDomain *domain = mono_domain_get ();
2073 MonoInternalThread *internal = mono_thread_internal_current ();
2074 MonoThread **current_thread_ptr;
2076 g_assert (internal);
2077 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2079 if (!*current_thread_ptr) {
2080 g_assert (domain != mono_get_root_domain ());
2081 *current_thread_ptr = create_thread_object (domain, internal);
2083 return *current_thread_ptr;
2084 #endif
2087 static MonoThreadObjectHandle
2088 mono_thread_current_handle (void)
2090 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
2093 /* Return the thread object belonging to INTERNAL in the current domain */
2094 static MonoThread *
2095 mono_thread_current_for_thread (MonoInternalThread *internal)
2097 #ifdef ENABLE_NETCORE
2098 return mono_thread_internal_current ();
2099 #else
2100 MonoDomain *domain = mono_domain_get ();
2101 MonoThread **current_thread_ptr;
2103 g_assert (internal);
2104 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2106 if (!*current_thread_ptr) {
2107 g_assert (domain != mono_get_root_domain ());
2108 *current_thread_ptr = create_thread_object (domain, internal);
2110 return *current_thread_ptr;
2111 #endif
2114 MonoInternalThread*
2115 mono_thread_internal_current (void)
2117 MonoInternalThread *res = GET_CURRENT_OBJECT ();
2118 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
2119 return res;
2122 MonoInternalThreadHandle
2123 mono_thread_internal_current_handle (void)
2125 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_internal_current ());
2128 static MonoThreadInfoWaitRet
2129 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
2131 MonoThreadInfoWaitRet ret;
2132 gint32 wait = ms;
2134 const gint64 start = (ms == -1) ? 0 : mono_msec_ticks ();
2135 while (TRUE) {
2136 MONO_ENTER_GC_SAFE;
2137 ret = mono_thread_info_wait_one_handle (thread_to_join, wait, TRUE);
2138 MONO_EXIT_GC_SAFE;
2140 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
2141 return ret;
2143 MonoException *exc = mono_thread_execute_interruption_ptr ();
2144 if (exc) {
2145 mono_error_set_exception_instance (error, exc);
2146 return ret;
2149 if (ms == -1)
2150 continue;
2152 /* Re-calculate ms according to the time passed */
2153 const gint32 diff_ms = (gint32)(mono_msec_ticks () - start);
2154 if (diff_ms >= ms) {
2155 ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
2156 return ret;
2158 wait = ms - diff_ms;
2161 return ret;
2164 MonoBoolean
2165 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle, int ms, MonoError *error)
2167 if (mono_thread_current_check_pending_interrupt ())
2168 return FALSE;
2170 // Internal threads are pinned so shallow coop/handle.
2171 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2172 MonoThreadHandle *handle = thread->handle;
2173 MonoInternalThread *cur_thread = mono_thread_internal_current ();
2174 gboolean ret = FALSE;
2176 LOCK_THREAD (thread);
2178 if ((thread->state & ThreadState_Unstarted) != 0) {
2179 UNLOCK_THREAD (thread);
2181 mono_error_set_exception_thread_state (error, "Thread has not been started.");
2182 return FALSE;
2185 UNLOCK_THREAD (thread);
2187 if (ms == -1)
2188 ms = MONO_INFINITE_WAIT;
2189 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
2191 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
2193 ret = mono_join_uninterrupted (handle, ms, error);
2195 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
2197 if (ret == MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
2198 THREAD_DEBUG (g_message ("%s: join successful", __func__));
2200 mono_error_assert_ok (error);
2202 /* Wait for the thread to really exit */
2203 MonoNativeThreadId tid = thread_get_tid (thread);
2204 mono_thread_join ((gpointer)(gsize)tid);
2206 return TRUE;
2209 THREAD_DEBUG (g_message ("%s: join failed", __func__));
2211 return FALSE;
2214 #define MANAGED_WAIT_FAILED 0x7fffffff
2216 static gint32
2217 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
2219 if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
2220 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
2221 } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
2222 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
2223 } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
2224 return WAIT_IO_COMPLETION;
2225 } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
2226 return WAIT_TIMEOUT;
2227 } else if (val == MONO_W32HANDLE_WAIT_RET_TOO_MANY_POSTS) {
2228 return WAIT_TOO_MANY_POSTS;
2229 } else if (val == MONO_W32HANDLE_WAIT_RET_NOT_OWNED_BY_CALLER) {
2230 return WAIT_NOT_OWNED_BY_CALLER;
2231 } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
2232 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2233 return MANAGED_WAIT_FAILED;
2234 } else {
2235 g_error ("%s: unknown val value %d", __func__, val);
2239 gint32
2240 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
2242 /* Do this WaitSleepJoin check before creating objects */
2243 if (mono_thread_current_check_pending_interrupt ())
2244 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2246 MonoInternalThread * const thread = mono_thread_internal_current ();
2248 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2250 gint64 start = 0;
2252 if (timeout == -1)
2253 timeout = MONO_INFINITE_WAIT;
2254 if (timeout != MONO_INFINITE_WAIT)
2255 start = mono_msec_ticks ();
2257 guint32 timeoutLeft = timeout;
2259 MonoW32HandleWaitRet ret;
2261 HANDLE_LOOP_PREPARE;
2263 for (;;) {
2265 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2266 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE, error);
2268 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
2269 break;
2271 SETUP_ICALL_FRAME;
2273 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
2275 const gboolean interrupt = mono_thread_execute_interruption (&exc);
2277 if (interrupt)
2278 mono_error_set_exception_handle (error, exc);
2280 CLEAR_ICALL_FRAME;
2282 if (interrupt)
2283 break;
2285 if (timeout != MONO_INFINITE_WAIT) {
2286 gint64 const elapsed = mono_msec_ticks () - start;
2287 if (elapsed >= timeout) {
2288 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
2289 break;
2292 timeoutLeft = timeout - elapsed;
2296 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2298 return map_native_wait_result_to_managed (ret, numhandles);
2301 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2302 gint32
2303 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
2305 MonoW32HandleWaitRet ret;
2306 MonoInternalThread *thread = mono_thread_internal_current ();
2308 if (ms == -1)
2309 ms = MONO_INFINITE_WAIT;
2311 if (mono_thread_current_check_pending_interrupt ())
2312 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2314 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2316 ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
2318 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2320 return map_native_wait_result_to_managed (ret, 1);
2323 #endif
2325 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
2327 return mono_atomic_inc_i32 (location);
2330 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
2332 #if SIZEOF_VOID_P == 4
2333 if (G_UNLIKELY ((size_t)location & 0x7)) {
2334 gint64 ret;
2335 mono_interlocked_lock ();
2336 (*location)++;
2337 ret = *location;
2338 mono_interlocked_unlock ();
2339 return ret;
2341 #endif
2342 return mono_atomic_inc_i64 (location);
2345 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
2347 return mono_atomic_dec_i32(location);
2350 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
2352 #if SIZEOF_VOID_P == 4
2353 if (G_UNLIKELY ((size_t)location & 0x7)) {
2354 gint64 ret;
2355 mono_interlocked_lock ();
2356 (*location)--;
2357 ret = *location;
2358 mono_interlocked_unlock ();
2359 return ret;
2361 #endif
2362 return mono_atomic_dec_i64 (location);
2365 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2367 return mono_atomic_xchg_i32(location, value);
2370 void
2371 ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*res)
2373 // Coop-equivalency here via pointers to pointers.
2374 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2376 // This also handles generic T case, T constrained to a class.
2378 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2379 // presently breaks identity of location and would therefore never work.
2381 *res = (MonoObject*)mono_atomic_xchg_ptr ((volatile gpointer*)location, *value);
2382 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2385 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2387 return mono_atomic_xchg_ptr(location, value);
2390 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2392 IntFloatUnion val, ret;
2394 val.fval = value;
2395 ret.ival = mono_atomic_xchg_i32((gint32 *) location, val.ival);
2397 return ret.fval;
2400 gint64
2401 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2403 #if SIZEOF_VOID_P == 4
2404 if (G_UNLIKELY ((size_t)location & 0x7)) {
2405 gint64 ret;
2406 mono_interlocked_lock ();
2407 ret = *location;
2408 *location = value;
2409 mono_interlocked_unlock ();
2410 return ret;
2412 #endif
2413 return mono_atomic_xchg_i64 (location, value);
2416 gdouble
2417 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2419 LongDoubleUnion val, ret;
2421 val.fval = value;
2422 ret.ival = (gint64)mono_atomic_xchg_i64((gint64 *) location, val.ival);
2424 return ret.fval;
2427 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2429 return mono_atomic_cas_i32(location, value, comparand);
2432 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2434 gint32 r = mono_atomic_cas_i32(location, value, comparand);
2435 *success = r == comparand;
2436 return r;
2439 void
2440 ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*comparand, MonoObject *volatile* res)
2442 // Coop-equivalency here via pointers to pointers.
2443 // value and comparand and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2445 // This also handles generic T case, T constrained to a class.
2447 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2448 // presently breaks identity of location and would therefore never work.
2450 *res = (MonoObject*)mono_atomic_cas_ptr ((volatile gpointer*)location, *value, *comparand);
2451 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2454 void
2455 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*comparand, MonoObject *volatile* res)
2457 ves_icall_System_Threading_Interlocked_CompareExchange_Object (location, value, comparand, res);
2460 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2462 return mono_atomic_cas_ptr(location, value, comparand);
2465 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2467 IntFloatUnion val, ret, cmp;
2469 val.fval = value;
2470 cmp.fval = comparand;
2471 ret.ival = mono_atomic_cas_i32((gint32 *) location, val.ival, cmp.ival);
2473 return ret.fval;
2476 gdouble
2477 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2479 #if SIZEOF_VOID_P == 8
2480 LongDoubleUnion val, comp, ret;
2482 val.fval = value;
2483 comp.fval = comparand;
2484 ret.ival = (gint64)mono_atomic_cas_ptr((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2486 return ret.fval;
2487 #else
2488 gdouble old;
2490 mono_interlocked_lock ();
2491 old = *location;
2492 if (old == comparand)
2493 *location = value;
2494 mono_interlocked_unlock ();
2496 return old;
2497 #endif
2500 gint64
2501 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2503 #if SIZEOF_VOID_P == 4
2504 if (G_UNLIKELY ((size_t)location & 0x7)) {
2505 gint64 old;
2506 mono_interlocked_lock ();
2507 old = *location;
2508 if (old == comparand)
2509 *location = value;
2510 mono_interlocked_unlock ();
2511 return old;
2513 #endif
2514 return mono_atomic_cas_i64 (location, value, comparand);
2517 void
2518 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*res)
2520 // Coop-equivalency here via pointers to pointers.
2521 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2523 // This is not entirely convincing due to lack of volatile in the caller.
2525 MONO_CHECK_NULL (location, );
2526 ves_icall_System_Threading_Interlocked_Exchange_Object (location, value, res);
2529 gint32
2530 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2532 return mono_atomic_add_i32 (location, value);
2535 gint64
2536 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2538 #if SIZEOF_VOID_P == 4
2539 if (G_UNLIKELY ((size_t)location & 0x7)) {
2540 gint64 ret;
2541 mono_interlocked_lock ();
2542 *location += value;
2543 ret = *location;
2544 mono_interlocked_unlock ();
2545 return ret;
2547 #endif
2548 return mono_atomic_add_i64 (location, value);
2551 gint64
2552 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2554 #if SIZEOF_VOID_P == 4
2555 if (G_UNLIKELY ((size_t)location & 0x7)) {
2556 gint64 ret;
2557 mono_interlocked_lock ();
2558 ret = *location;
2559 mono_interlocked_unlock ();
2560 return ret;
2562 #endif
2563 return mono_atomic_load_i64 (location);
2566 void
2567 ves_icall_System_Threading_Interlocked_MemoryBarrierProcessWide (void)
2569 mono_memory_barrier_process_wide ();
2572 void
2573 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2575 mono_memory_barrier ();
2578 void
2579 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj, guint32 state, MonoError *error)
2581 // InternalThreads are always pinned, so shallowly coop-handleize.
2582 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj), (MonoThreadState)state);
2585 void
2586 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle, guint32 state, MonoError *error)
2588 // InternalThreads are always pinned, so shallowly coop-handleize.
2589 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle), (MonoThreadState)state);
2592 guint32
2593 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle, MonoError *error)
2595 // InternalThreads are always pinned, so shallowly coop-handleize.
2596 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (thread_handle);
2598 guint32 state;
2600 LOCK_THREAD (this_obj);
2602 state = this_obj->state;
2604 UNLOCK_THREAD (this_obj);
2606 return state;
2609 void
2610 ves_icall_System_Threading_Thread_Interrupt_internal (MonoThreadObjectHandle thread_handle, MonoError *error)
2612 // Internal threads are pinned so shallow coop/handle.
2613 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2614 MonoInternalThread * const current = mono_thread_internal_current ();
2616 LOCK_THREAD (thread);
2618 thread->thread_interrupt_requested = TRUE;
2619 gboolean const throw_ = current != thread && (thread->state & ThreadState_WaitSleepJoin);
2621 UNLOCK_THREAD (thread);
2623 if (throw_)
2624 async_abort_internal (thread, FALSE);
2628 * mono_thread_current_check_pending_interrupt:
2629 * Checks if there's a interruption request and set the pending exception if so.
2630 * \returns true if a pending exception was set
2632 gboolean
2633 mono_thread_current_check_pending_interrupt (void)
2635 MonoInternalThread *thread = mono_thread_internal_current ();
2636 gboolean throw_ = FALSE;
2638 LOCK_THREAD (thread);
2640 if (thread->thread_interrupt_requested) {
2641 throw_ = TRUE;
2642 thread->thread_interrupt_requested = FALSE;
2645 UNLOCK_THREAD (thread);
2647 if (throw_) {
2648 ERROR_DECL (error);
2649 mono_error_set_thread_interrupted (error);
2650 mono_error_set_pending_exception (error);
2652 return throw_;
2655 static gboolean
2656 request_thread_abort (MonoInternalThread *thread, MonoObjectHandle *state, gboolean appdomain_unload)
2657 // state is a pointer to a handle in order to be optional,
2658 // and be passed unspecified from functions not using handles.
2659 // When raw pointers is gone, it need not be a pointer,
2660 // though this would still work efficiently.
2662 LOCK_THREAD (thread);
2664 /* With self abort we always throw a new exception */
2665 if (thread == mono_thread_internal_current ())
2666 thread->abort_exc = NULL;
2668 if (thread->state & (ThreadState_AbortRequested | ThreadState_Stopped))
2670 UNLOCK_THREAD (thread);
2671 return FALSE;
2674 if ((thread->state & ThreadState_Unstarted) != 0) {
2675 thread->state |= ThreadState_Aborted;
2676 UNLOCK_THREAD (thread);
2677 return FALSE;
2680 thread->state |= ThreadState_AbortRequested;
2681 if (appdomain_unload)
2682 thread->flags |= MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2683 else
2684 thread->flags &= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2686 mono_gchandle_free_internal (thread->abort_state_handle);
2687 thread->abort_state_handle = 0;
2690 if (state && !MONO_HANDLE_IS_NULL (*state)) {
2691 thread->abort_state_handle = mono_gchandle_from_handle (*state, FALSE);
2692 g_assert (thread->abort_state_handle);
2695 thread->abort_exc = NULL;
2697 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));
2699 /* During shutdown, we can't wait for other threads */
2700 if (!shutting_down)
2701 /* Make sure the thread is awake */
2702 mono_thread_resume (thread);
2704 UNLOCK_THREAD (thread);
2705 return TRUE;
2708 #ifndef ENABLE_NETCORE
2709 void
2710 ves_icall_System_Threading_Thread_Abort (MonoInternalThreadHandle thread_handle, MonoObjectHandle state, MonoError *error)
2712 // InternalThreads are always pinned, so shallowly coop-handleize.
2713 MonoInternalThread * const thread = mono_internal_thread_handle_ptr (thread_handle);
2714 gboolean is_self = thread == mono_thread_internal_current ();
2716 /* For self aborts we always process the abort */
2717 if (!request_thread_abort (thread, &state, FALSE) && !is_self)
2718 return;
2720 if (is_self) {
2721 self_abort_internal (error);
2722 } else {
2723 async_abort_internal (thread, TRUE);
2726 #endif
2729 * mono_thread_internal_abort:
2730 * Request thread \p thread to be aborted.
2731 * \p thread MUST NOT be the current thread.
2733 void
2734 mono_thread_internal_abort (MonoInternalThread *thread, gboolean appdomain_unload)
2736 g_assert (thread != mono_thread_internal_current ());
2738 if (!request_thread_abort (thread, NULL, appdomain_unload))
2739 return;
2740 async_abort_internal (thread, TRUE);
2743 #ifndef ENABLE_NETCORE
2744 void
2745 ves_icall_System_Threading_Thread_ResetAbort (MonoThreadObjectHandle this_obj, MonoError *error)
2747 MonoInternalThread *thread = mono_thread_internal_current ();
2748 gboolean was_aborting, is_domain_abort;
2750 LOCK_THREAD (thread);
2751 was_aborting = thread->state & ThreadState_AbortRequested;
2752 is_domain_abort = thread->flags & MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2754 if (was_aborting && !is_domain_abort)
2755 thread->state &= ~ThreadState_AbortRequested;
2756 UNLOCK_THREAD (thread);
2758 if (!was_aborting) {
2759 mono_error_set_exception_thread_state (error, "Unable to reset abort because no abort was requested");
2760 return;
2761 } else if (is_domain_abort) {
2762 /* Silently ignore abort resets in unloading appdomains */
2763 return;
2766 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2767 thread->abort_exc = NULL;
2768 mono_gchandle_free_internal (thread->abort_state_handle);
2769 /* This is actually not necessary - the handle
2770 only counts if the exception is set */
2771 thread->abort_state_handle = 0;
2773 #endif
2775 void
2776 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2778 LOCK_THREAD (thread);
2780 thread->state &= ~ThreadState_AbortRequested;
2782 if (thread->abort_exc) {
2783 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2784 thread->abort_exc = NULL;
2785 mono_gchandle_free_internal (thread->abort_state_handle);
2786 /* This is actually not necessary - the handle
2787 only counts if the exception is set */
2788 thread->abort_state_handle = 0;
2791 UNLOCK_THREAD (thread);
2794 #ifndef ENABLE_NETCORE
2795 MonoObjectHandle
2796 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThreadObjectHandle this_obj, MonoError *error)
2798 MonoInternalThread *thread = thread_handle_to_internal_ptr (this_obj);
2800 if (!thread->abort_state_handle)
2801 return NULL_HANDLE; // No state. No error.
2803 // Convert gc handle to coop handle.
2804 MonoObjectHandle state = mono_gchandle_get_target_handle (thread->abort_state_handle);
2805 g_assert (MONO_HANDLE_BOOL (state));
2807 MonoDomain *domain = mono_domain_get ();
2808 if (MONO_HANDLE_DOMAIN (state) == domain)
2809 return state; // No need to cross domain, return state directly.
2811 // Attempt move state cross-domain.
2812 MonoObjectHandle deserialized = mono_object_xdomain_representation (state, domain, error);
2814 // If deserialized is null, there must be an error, and vice versa.
2815 g_assert (is_ok (error) == MONO_HANDLE_BOOL (deserialized));
2817 if (MONO_HANDLE_BOOL (deserialized))
2818 return deserialized; // Cross-domain serialization succeeded. Return it.
2820 // Wrap error in InvalidOperationException.
2821 ERROR_DECL (error_creating_exception);
2822 MonoExceptionHandle invalid_op_exc = mono_exception_new_invalid_operation (
2823 "Thread.ExceptionState cannot access an ExceptionState from a different AppDomain", error_creating_exception);
2824 mono_error_assert_ok (error_creating_exception);
2825 g_assert (!is_ok (error) && 1);
2826 MONO_HANDLE_SET (invalid_op_exc, inner_ex, mono_error_convert_to_exception_handle (error));
2827 error_init_reuse (error);
2828 mono_error_set_exception_handle (error, invalid_op_exc);
2829 g_assert (!is_ok (error) && 2);
2831 // There is state, but we failed to return it.
2832 return NULL_HANDLE;
2834 #endif
2836 static gboolean
2837 mono_thread_suspend (MonoInternalThread *thread)
2839 LOCK_THREAD (thread);
2841 if (thread->state & (ThreadState_Unstarted | ThreadState_Aborted | ThreadState_Stopped))
2843 UNLOCK_THREAD (thread);
2844 return FALSE;
2847 if (thread->state & (ThreadState_Suspended | ThreadState_SuspendRequested | ThreadState_AbortRequested))
2849 UNLOCK_THREAD (thread);
2850 return TRUE;
2853 thread->state |= ThreadState_SuspendRequested;
2854 MONO_ENTER_GC_SAFE;
2855 mono_os_event_reset (thread->suspended);
2856 MONO_EXIT_GC_SAFE;
2858 if (thread == mono_thread_internal_current ()) {
2859 /* calls UNLOCK_THREAD (thread) */
2860 self_suspend_internal ();
2861 } else {
2862 /* calls UNLOCK_THREAD (thread) */
2863 async_suspend_internal (thread, FALSE);
2866 return TRUE;
2869 #ifndef ENABLE_NETCORE
2870 void
2871 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj, MonoError *error)
2873 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj)))
2874 mono_error_set_exception_thread_not_started_or_dead (error);
2877 #endif
2879 /* LOCKING: LOCK_THREAD(thread) must be held */
2880 static gboolean
2881 mono_thread_resume (MonoInternalThread *thread)
2883 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2884 // g_async_safe_printf ("RESUME (1) thread %p\n", thread_get_tid (thread));
2885 thread->state &= ~ThreadState_SuspendRequested;
2886 MONO_ENTER_GC_SAFE;
2887 mono_os_event_set (thread->suspended);
2888 MONO_EXIT_GC_SAFE;
2889 return TRUE;
2892 if ((thread->state & ThreadState_Suspended) == 0 ||
2893 (thread->state & ThreadState_Unstarted) != 0 ||
2894 (thread->state & ThreadState_Aborted) != 0 ||
2895 (thread->state & ThreadState_Stopped) != 0)
2897 // g_async_safe_printf ("RESUME (2) thread %p\n", thread_get_tid (thread));
2898 return FALSE;
2901 // g_async_safe_printf ("RESUME (3) thread %p\n", thread_get_tid (thread));
2903 MONO_ENTER_GC_SAFE;
2904 mono_os_event_set (thread->suspended);
2905 MONO_EXIT_GC_SAFE;
2907 if (!thread->self_suspended) {
2908 UNLOCK_THREAD (thread);
2910 /* Awake the thread */
2911 if (!mono_thread_info_resume (thread_get_tid (thread)))
2912 return FALSE;
2914 LOCK_THREAD (thread);
2917 thread->state &= ~ThreadState_Suspended;
2919 return TRUE;
2922 #ifndef ENABLE_NETCORE
2923 void
2924 ves_icall_System_Threading_Thread_Resume (MonoThreadObjectHandle thread_handle, MonoError *error)
2926 // Internal threads are pinned so shallow coop/handle.
2927 MonoInternalThread * const internal_thread = thread_handle_to_internal_ptr (thread_handle);
2928 gboolean exception = FALSE;
2930 if (!internal_thread) {
2931 exception = TRUE;
2932 } else {
2933 LOCK_THREAD (internal_thread);
2934 if (!mono_thread_resume (internal_thread))
2935 exception = TRUE;
2936 UNLOCK_THREAD (internal_thread);
2939 if (exception)
2940 mono_error_set_exception_thread_not_started_or_dead (error);
2942 #endif
2944 gboolean
2945 mono_threads_is_critical_method (MonoMethod *method)
2947 switch (method->wrapper_type) {
2948 case MONO_WRAPPER_RUNTIME_INVOKE:
2949 case MONO_WRAPPER_XDOMAIN_INVOKE:
2950 case MONO_WRAPPER_XDOMAIN_DISPATCH:
2951 return TRUE;
2953 return FALSE;
2956 static gboolean
2957 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2959 if (managed)
2960 return TRUE;
2962 if (mono_threads_is_critical_method (m)) {
2963 *((gboolean*)data) = TRUE;
2964 return TRUE;
2966 return FALSE;
2969 static gboolean
2970 is_running_protected_wrapper (void)
2972 gboolean found = FALSE;
2973 mono_stack_walk (find_wrapper, &found);
2974 return found;
2978 * mono_thread_stop:
2980 void
2981 mono_thread_stop (MonoThread *thread)
2983 MonoInternalThread *internal = thread->internal_thread;
2985 if (!request_thread_abort (internal, NULL, FALSE))
2986 return;
2988 if (internal == mono_thread_internal_current ()) {
2989 ERROR_DECL (error);
2990 self_abort_internal (error);
2992 This function is part of the embeding API and has no way to return the exception
2993 to be thrown. So what we do is keep the old behavior and raise the exception.
2995 mono_error_raise_exception_deprecated (error); /* OK to throw, see note */
2996 } else {
2997 async_abort_internal (internal, TRUE);
3001 gint8
3002 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
3004 gint8 tmp = *(volatile gint8 *)ptr;
3005 mono_memory_barrier ();
3006 return tmp;
3009 gint16
3010 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
3012 gint16 tmp = *(volatile gint16 *)ptr;
3013 mono_memory_barrier ();
3014 return tmp;
3017 gint32
3018 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
3020 gint32 tmp = *(volatile gint32 *)ptr;
3021 mono_memory_barrier ();
3022 return tmp;
3025 gint64
3026 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
3028 gint64 tmp = *(volatile gint64 *)ptr;
3029 mono_memory_barrier ();
3030 return tmp;
3033 void *
3034 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
3036 volatile void *tmp = *(volatile void **)ptr;
3037 mono_memory_barrier ();
3038 return (void *) tmp;
3041 void *
3042 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
3044 volatile MonoObject *tmp = *(volatile MonoObject **)ptr;
3045 mono_memory_barrier ();
3046 return (MonoObject *) tmp;
3049 double
3050 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
3052 double tmp = *(volatile double *)ptr;
3053 mono_memory_barrier ();
3054 return tmp;
3057 float
3058 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
3060 float tmp = *(volatile float *)ptr;
3061 mono_memory_barrier ();
3062 return tmp;
3065 gint64
3066 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
3068 #if SIZEOF_VOID_P == 4
3069 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3070 gint64 val;
3071 mono_interlocked_lock ();
3072 val = *(gint64*)ptr;
3073 mono_interlocked_unlock ();
3074 return val;
3076 #endif
3077 return mono_atomic_load_i64 ((volatile gint64 *)ptr);
3080 guint64
3081 ves_icall_System_Threading_Volatile_ReadU8 (void *ptr)
3083 #if SIZEOF_VOID_P == 4
3084 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3085 guint64 val;
3086 mono_interlocked_lock ();
3087 val = *(guint64*)ptr;
3088 mono_interlocked_unlock ();
3089 return val;
3091 #endif
3092 return (guint64)mono_atomic_load_i64 ((volatile gint64 *)ptr);
3095 double
3096 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
3098 LongDoubleUnion u;
3100 #if SIZEOF_VOID_P == 4
3101 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3102 double val;
3103 mono_interlocked_lock ();
3104 val = *(double*)ptr;
3105 mono_interlocked_unlock ();
3106 return val;
3108 #endif
3110 u.ival = mono_atomic_load_i64 ((volatile gint64 *)ptr);
3112 return u.fval;
3115 void
3116 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
3118 mono_memory_barrier ();
3119 *(volatile gint8 *)ptr = value;
3122 void
3123 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
3125 mono_memory_barrier ();
3126 *(volatile gint16 *)ptr = value;
3129 void
3130 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
3132 mono_memory_barrier ();
3133 *(volatile gint32 *)ptr = value;
3136 void
3137 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
3139 mono_memory_barrier ();
3140 *(volatile gint64 *)ptr = value;
3143 void
3144 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
3146 mono_memory_barrier ();
3147 *(volatile void **)ptr = value;
3150 void
3151 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
3153 mono_memory_barrier ();
3154 mono_gc_wbarrier_generic_store_internal (ptr, value);
3157 void
3158 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
3160 mono_memory_barrier ();
3161 *(volatile double *)ptr = value;
3164 void
3165 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
3167 mono_memory_barrier ();
3168 *(volatile float *)ptr = value;
3171 void
3172 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
3174 #if SIZEOF_VOID_P == 4
3175 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3176 mono_interlocked_lock ();
3177 *(gint64*)ptr = value;
3178 mono_interlocked_unlock ();
3179 return;
3181 #endif
3183 mono_atomic_store_i64 ((volatile gint64 *)ptr, value);
3186 void
3187 ves_icall_System_Threading_Volatile_WriteU8 (void *ptr, guint64 value)
3189 #if SIZEOF_VOID_P == 4
3190 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3191 mono_interlocked_lock ();
3192 *(guint64*)ptr = value;
3193 mono_interlocked_unlock ();
3194 return;
3196 #endif
3198 mono_atomic_store_i64 ((volatile gint64 *)ptr, (gint64)value);
3201 void
3202 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
3204 LongDoubleUnion u;
3206 #if SIZEOF_VOID_P == 4
3207 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3208 mono_interlocked_lock ();
3209 *(double*)ptr = value;
3210 mono_interlocked_unlock ();
3211 return;
3213 #endif
3215 u.fval = value;
3217 mono_atomic_store_i64 ((volatile gint64 *)ptr, u.ival);
3220 static void
3221 free_context (void *user_data)
3223 ContextStaticData *data = (ContextStaticData*)user_data;
3225 mono_threads_lock ();
3228 * There is no guarantee that, by the point this reference queue callback
3229 * has been invoked, the GC handle associated with the object will fail to
3230 * resolve as one might expect. So if we don't free and remove the GC
3231 * handle here, free_context_static_data_helper () could end up resolving
3232 * a GC handle to an actually-dead context which would contain a pointer
3233 * to an already-freed static data segment, resulting in a crash when
3234 * accessing it.
3236 g_hash_table_remove (contexts, GUINT_TO_POINTER (data->gc_handle));
3238 mono_threads_unlock ();
3240 mono_gchandle_free_internal (data->gc_handle);
3241 mono_free_static_data (data->static_data);
3242 g_free (data);
3245 void
3246 mono_threads_register_app_context (MonoAppContextHandle ctx, MonoError *error)
3248 error_init (error);
3249 mono_threads_lock ();
3251 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3253 if (!contexts)
3254 contexts = g_hash_table_new (NULL, NULL);
3256 if (!context_queue)
3257 context_queue = mono_gc_reference_queue_new_internal (free_context);
3259 gpointer gch = GUINT_TO_POINTER (mono_gchandle_new_weakref_from_handle (MONO_HANDLE_CAST (MonoObject, ctx)));
3260 g_hash_table_insert (contexts, gch, gch);
3263 * We use this intermediate structure to contain a duplicate pointer to
3264 * the static data because we can't rely on being able to resolve the GC
3265 * handle in the reference queue callback.
3267 ContextStaticData *data = g_new0 (ContextStaticData, 1);
3268 data->gc_handle = GPOINTER_TO_UINT (gch);
3269 MONO_HANDLE_SETVAL (ctx, data, ContextStaticData*, data);
3271 context_adjust_static_data (ctx);
3272 mono_gc_reference_queue_add_handle (context_queue, ctx, data);
3274 mono_threads_unlock ();
3276 MONO_PROFILER_RAISE (context_loaded, (MONO_HANDLE_RAW (ctx)));
3279 #ifndef ENABLE_NETCORE
3280 void
3281 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx, MonoError *error)
3283 mono_threads_register_app_context (ctx, error);
3285 #endif
3287 void
3288 mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error)
3291 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3292 * cleanup in exceptional circumstances, we don't actually do any
3293 * cleanup work here. We instead do this via a reference queue.
3296 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3298 MONO_PROFILER_RAISE (context_unloaded, (ctx));
3301 #ifndef ENABLE_NETCORE
3302 void
3303 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx, MonoError *error)
3305 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_release_app_context */
3307 #endif
3309 void mono_thread_init (MonoThreadStartCB start_cb,
3310 MonoThreadAttachCB attach_cb)
3312 mono_coop_mutex_init_recursive (&threads_mutex);
3314 #if SIZEOF_VOID_P == 4
3315 mono_os_mutex_init (&interlocked_mutex);
3316 #endif
3317 mono_coop_mutex_init_recursive(&joinable_threads_mutex);
3319 mono_os_event_init (&background_change_event, FALSE);
3321 mono_coop_cond_init (&pending_native_thread_join_calls_event);
3322 mono_coop_cond_init (&zero_pending_joinable_thread_event);
3324 mono_init_static_data_info (&thread_static_info);
3325 mono_init_static_data_info (&context_static_info);
3327 mono_thread_start_cb = start_cb;
3328 mono_thread_attach_cb = attach_cb;
3332 static gpointer
3333 thread_attach (MonoThreadInfo *info)
3335 return mono_gc_thread_attach (info);
3338 static void
3339 thread_detach (MonoThreadInfo *info)
3341 MonoInternalThread *internal;
3342 guint32 gchandle;
3344 /* If a delegate is passed to native code and invoked on a thread we dont
3345 * know about, marshal will register it with mono_threads_attach_coop, but
3346 * we have no way of knowing when that thread goes away. SGen has a TSD
3347 * so we assume that if the domain is still registered, we can detach
3348 * the thread */
3350 g_assert (info);
3351 g_assert (mono_thread_info_is_current (info));
3353 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
3354 return;
3356 internal = (MonoInternalThread*) mono_gchandle_get_target_internal (gchandle);
3357 g_assert (internal);
3359 mono_thread_detach_internal (internal);
3362 static void
3363 thread_detach_with_lock (MonoThreadInfo *info)
3365 mono_gc_thread_detach_with_lock (info);
3368 static gboolean
3369 thread_in_critical_region (MonoThreadInfo *info)
3371 return mono_gc_thread_in_critical_region (info);
3374 static gboolean
3375 ip_in_critical_region (MonoDomain *domain, gpointer ip)
3377 MonoJitInfo *ji;
3378 MonoMethod *method;
3381 * We pass false for 'try_aot' so this becomes async safe.
3382 * It won't find aot methods whose jit info is not yet loaded,
3383 * so we preload their jit info in the JIT.
3385 ji = mono_jit_info_table_find_internal (domain, ip, FALSE, FALSE);
3386 if (!ji)
3387 return FALSE;
3389 method = mono_jit_info_get_method (ji);
3390 g_assert (method);
3392 return mono_gc_is_critical_method (method);
3395 static void
3396 thread_flags_changing (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3398 mono_gc_skip_thread_changing (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3401 static void
3402 thread_flags_changed (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3404 mono_gc_skip_thread_changed (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3407 void
3408 mono_thread_callbacks_init (void)
3410 MonoThreadInfoCallbacks cb;
3412 memset (&cb, 0, sizeof(cb));
3413 cb.thread_attach = thread_attach;
3414 cb.thread_detach = thread_detach;
3415 cb.thread_detach_with_lock = thread_detach_with_lock;
3416 cb.ip_in_critical_region = ip_in_critical_region;
3417 cb.thread_in_critical_region = thread_in_critical_region;
3418 cb.thread_flags_changing = thread_flags_changing;
3419 cb.thread_flags_changed = thread_flags_changed;
3420 mono_thread_info_callbacks_init (&cb);
3424 * mono_thread_cleanup:
3426 void
3427 mono_thread_cleanup (void)
3429 /* Wait for pending threads to park on joinable threads list */
3430 /* NOTE, waiting on this should be extremely rare and will only happen */
3431 /* under certain specific conditions. */
3432 gboolean wait_result = threads_wait_pending_joinable_threads (2000);
3433 if (!wait_result)
3434 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3436 mono_threads_join_threads ();
3438 #if !defined(HOST_WIN32)
3439 /* The main thread must abandon any held mutexes (particularly
3440 * important for named mutexes as they are shared across
3441 * processes, see bug 74680.) This will happen when the
3442 * thread exits, but if it's not running in a subthread it
3443 * won't exit in time.
3445 if (!mono_runtime_get_no_exec ())
3446 mono_w32mutex_abandon (mono_thread_internal_current ());
3447 #endif
3449 #if 0
3450 /* This stuff needs more testing, it seems one of these
3451 * critical sections can be locked when mono_thread_cleanup is
3452 * called.
3454 mono_coop_mutex_destroy (&threads_mutex);
3455 mono_os_mutex_destroy (&interlocked_mutex);
3456 mono_os_mutex_destroy (&delayed_free_table_mutex);
3457 mono_os_mutex_destroy (&small_id_mutex);
3458 mono_coop_cond_destroy (&zero_pending_joinable_thread_event);
3459 mono_coop_cond_destroy (&pending_native_thread_join_calls_event);
3460 mono_os_event_destroy (&background_change_event);
3461 #endif
3464 void
3465 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
3467 mono_thread_cleanup_fn = func;
3471 * mono_thread_set_manage_callback:
3473 void
3474 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
3476 thread->internal_thread->manage_callback = func;
3479 G_GNUC_UNUSED
3480 static void print_tids (gpointer key, gpointer value, gpointer user)
3482 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3483 * sizeof(uint) and a cast to uint would overflow
3485 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3486 * print this as a pointer.
3488 g_message ("Waiting for: %p", key);
3491 struct wait_data
3493 MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3494 MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3495 guint32 num;
3498 static void
3499 wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
3501 guint32 i;
3502 MonoThreadInfoWaitRet ret;
3504 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
3506 /* Add the thread state change event, so it wakes
3507 * up if a thread changes to background mode. */
3509 MONO_ENTER_GC_SAFE;
3510 if (check_state_change)
3511 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, &background_change_event, FALSE, timeout, TRUE);
3512 else
3513 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, NULL, TRUE, timeout, TRUE);
3514 MONO_EXIT_GC_SAFE;
3516 if (ret == MONO_THREAD_INFO_WAIT_RET_FAILED) {
3517 /* See the comment in build_wait_tids() */
3518 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
3519 return;
3522 for( i = 0; i < wait->num; i++)
3523 mono_threads_close_thread_handle (wait->handles [i]);
3525 if (ret >= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 && ret < (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + wait->num)) {
3526 MonoInternalThread *internal;
3528 internal = wait->threads [ret - MONO_THREAD_INFO_WAIT_RET_SUCCESS_0];
3530 mono_threads_lock ();
3531 if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
3532 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
3533 mono_threads_unlock ();
3537 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
3539 struct wait_data *wait=(struct wait_data *)user;
3541 if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
3542 MonoInternalThread *thread=(MonoInternalThread *)value;
3544 /* Ignore background threads, we abort them later */
3545 /* Do not lock here since it is not needed and the caller holds threads_lock */
3546 if (thread->state & ThreadState_Background) {
3547 THREAD_DEBUG (g_message ("%s: ignoring background thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3548 return; /* just leave, ignore */
3551 if (mono_gc_is_finalizer_internal_thread (thread)) {
3552 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3553 return;
3556 if (thread == mono_thread_internal_current ()) {
3557 THREAD_DEBUG (g_message ("%s: ignoring current thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3558 return;
3561 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
3562 THREAD_DEBUG (g_message ("%s: ignoring main thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3563 return;
3566 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
3567 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
3568 return;
3571 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
3572 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
3573 wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
3574 wait->threads[wait->num]=thread;
3575 wait->num++;
3577 THREAD_DEBUG (g_message ("%s: adding thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3578 } else {
3579 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3583 } else {
3584 /* Just ignore the rest, we can't do anything with
3585 * them yet
3590 static void
3591 abort_threads (gpointer key, gpointer value, gpointer user)
3593 struct wait_data *wait=(struct wait_data *)user;
3594 MonoNativeThreadId self = mono_native_thread_id_get ();
3595 MonoInternalThread *thread = (MonoInternalThread *)value;
3597 if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
3598 return;
3600 if (mono_native_thread_id_equals (thread_get_tid (thread), self))
3601 return;
3602 if (mono_gc_is_finalizer_internal_thread (thread))
3603 return;
3605 if ((thread->flags & MONO_THREAD_FLAG_DONT_MANAGE))
3606 return;
3608 wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
3609 wait->threads[wait->num] = thread;
3610 wait->num++;
3612 THREAD_DEBUG (g_print ("%s: Aborting id: %" G_GSIZE_FORMAT "\n", __func__, (gsize)thread->tid));
3613 mono_thread_internal_abort (thread, FALSE);
3616 /**
3617 * mono_threads_set_shutting_down:
3619 * Is called by a thread that wants to shut down Mono. If the runtime is already
3620 * shutting down, the calling thread is suspended/stopped, and this function never
3621 * returns.
3623 void
3624 mono_threads_set_shutting_down (void)
3626 MonoInternalThread *current_thread = mono_thread_internal_current ();
3628 mono_threads_lock ();
3630 if (shutting_down) {
3631 mono_threads_unlock ();
3633 /* Make sure we're properly suspended/stopped */
3635 LOCK_THREAD (current_thread);
3637 if (current_thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
3638 UNLOCK_THREAD (current_thread);
3639 mono_thread_execute_interruption_void ();
3640 } else {
3641 UNLOCK_THREAD (current_thread);
3644 /*since we're killing the thread, detach it.*/
3645 mono_thread_detach_internal (current_thread);
3647 /* Wake up other threads potentially waiting for us */
3648 mono_thread_info_exit (0);
3649 } else {
3650 shutting_down = TRUE;
3652 /* Not really a background state change, but this will
3653 * interrupt the main thread if it is waiting for all
3654 * the other threads.
3656 MONO_ENTER_GC_SAFE;
3657 mono_os_event_set (&background_change_event);
3658 MONO_EXIT_GC_SAFE;
3660 mono_threads_unlock ();
3665 * mono_thread_manage:
3667 void
3668 mono_thread_manage (void)
3670 struct wait_data wait_data;
3671 struct wait_data *wait = &wait_data;
3673 memset (wait, 0, sizeof (struct wait_data));
3674 /* join each thread that's still running */
3675 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3677 mono_threads_lock ();
3678 if(threads==NULL) {
3679 THREAD_DEBUG (g_message("%s: No threads", __func__));
3680 mono_threads_unlock ();
3681 return;
3684 mono_threads_unlock ();
3686 do {
3687 mono_threads_lock ();
3688 if (shutting_down) {
3689 /* somebody else is shutting down */
3690 mono_threads_unlock ();
3691 break;
3693 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3694 mono_g_hash_table_foreach (threads, print_tids, NULL));
3696 MONO_ENTER_GC_SAFE;
3697 mono_os_event_reset (&background_change_event);
3698 MONO_EXIT_GC_SAFE;
3699 wait->num=0;
3700 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3701 memset (wait->threads, 0, sizeof (wait->threads));
3702 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3703 mono_threads_unlock ();
3704 if (wait->num > 0)
3705 /* Something to wait for */
3706 wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3707 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3708 } while(wait->num>0);
3710 /* Mono is shutting down, so just wait for the end */
3711 if (!mono_runtime_try_shutdown ()) {
3712 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3713 mono_thread_suspend (mono_thread_internal_current ());
3714 mono_thread_execute_interruption_void ();
3717 #ifndef ENABLE_NETCORE
3719 * Under netcore, we don't abort any threads, just exit.
3720 * This is not a problem since we don't do runtime cleanup either.
3723 * Remove everything but the finalizer thread and self.
3724 * Also abort all the background threads
3725 * */
3726 do {
3727 mono_threads_lock ();
3729 wait->num = 0;
3730 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3731 memset (wait->threads, 0, sizeof (wait->threads));
3732 mono_g_hash_table_foreach (threads, abort_threads, wait);
3734 mono_threads_unlock ();
3736 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3737 if (wait->num > 0) {
3738 /* Something to wait for */
3739 wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3741 } while (wait->num > 0);
3742 #endif
3745 * give the subthreads a chance to really quit (this is mainly needed
3746 * to get correct user and system times from getrusage/wait/time(1)).
3747 * This could be removed if we avoid pthread_detach() and use pthread_join().
3749 mono_thread_info_yield ();
3752 #ifndef ENABLE_NETCORE
3753 static void
3754 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3756 MonoInternalThread *thread = (MonoInternalThread*)value;
3757 struct wait_data *wait = (struct wait_data*)user_data;
3760 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3761 * limitation.
3762 * This needs no locking.
3764 if ((thread->state & ThreadState_Suspended) != 0 ||
3765 (thread->state & ThreadState_Stopped) != 0)
3766 return;
3768 if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3769 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3770 wait->threads [wait->num] = thread;
3771 wait->num++;
3776 * mono_thread_suspend_all_other_threads:
3778 * Suspend all managed threads except the finalizer thread and this thread. It is
3779 * not possible to resume them later.
3781 void mono_thread_suspend_all_other_threads (void)
3783 struct wait_data wait_data;
3784 struct wait_data *wait = &wait_data;
3785 int i;
3786 MonoNativeThreadId self = mono_native_thread_id_get ();
3787 guint32 eventidx = 0;
3788 gboolean starting, finished;
3790 memset (wait, 0, sizeof (struct wait_data));
3792 * The other threads could be in an arbitrary state at this point, i.e.
3793 * they could be starting up, shutting down etc. This means that there could be
3794 * threads which are not even in the threads hash table yet.
3798 * First we set a barrier which will be checked by all threads before they
3799 * are added to the threads hash table, and they will exit if the flag is set.
3800 * This ensures that no threads could be added to the hash later.
3801 * We will use shutting_down as the barrier for now.
3803 g_assert (shutting_down);
3806 * We make multiple calls to WaitForMultipleObjects since:
3807 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3808 * - some threads could exit without becoming suspended
3810 finished = FALSE;
3811 while (!finished) {
3813 * Make a copy of the hashtable since we can't do anything with
3814 * threads while threads_mutex is held.
3816 wait->num = 0;
3817 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3818 memset (wait->threads, 0, sizeof (wait->threads));
3819 mono_threads_lock ();
3820 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3821 mono_threads_unlock ();
3823 eventidx = 0;
3824 /* Get the suspended events that we'll be waiting for */
3825 for (i = 0; i < wait->num; ++i) {
3826 MonoInternalThread *thread = wait->threads [i];
3828 if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3829 || mono_gc_is_finalizer_internal_thread (thread)
3830 || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3832 mono_threads_close_thread_handle (wait->handles [i]);
3833 wait->threads [i] = NULL;
3834 continue;
3837 LOCK_THREAD (thread);
3839 if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3840 UNLOCK_THREAD (thread);
3841 mono_threads_close_thread_handle (wait->handles [i]);
3842 wait->threads [i] = NULL;
3843 continue;
3846 ++eventidx;
3848 /* Convert abort requests into suspend requests */
3849 if ((thread->state & ThreadState_AbortRequested) != 0)
3850 thread->state &= ~ThreadState_AbortRequested;
3852 thread->state |= ThreadState_SuspendRequested;
3853 MONO_ENTER_GC_SAFE;
3854 mono_os_event_reset (thread->suspended);
3855 MONO_EXIT_GC_SAFE;
3857 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3858 async_suspend_internal (thread, TRUE);
3860 mono_threads_close_thread_handle (wait->handles [i]);
3861 wait->threads [i] = NULL;
3863 if (eventidx <= 0) {
3865 * If there are threads which are starting up, we wait until they
3866 * are suspended when they try to register in the threads hash.
3867 * This is guaranteed to finish, since the threads which can create new
3868 * threads get suspended after a while.
3869 * FIXME: The finalizer thread can still create new threads.
3871 mono_threads_lock ();
3872 if (threads_starting_up)
3873 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3874 else
3875 starting = FALSE;
3876 mono_threads_unlock ();
3877 if (starting)
3878 mono_thread_info_sleep (100, NULL);
3879 else
3880 finished = TRUE;
3884 #endif
3886 typedef struct {
3887 MonoInternalThread *thread;
3888 MonoStackFrameInfo *frames;
3889 int nframes, max_frames;
3890 int nthreads, max_threads;
3891 MonoInternalThread **threads;
3892 } ThreadDumpUserData;
3894 static gboolean thread_dump_requested;
3896 /* This needs to be async safe */
3897 static gboolean
3898 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3900 ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3902 if (ud->nframes < ud->max_frames) {
3903 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3904 ud->nframes ++;
3907 return FALSE;
3910 /* This needs to be async safe */
3911 static SuspendThreadResult
3912 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3914 ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3915 MonoInternalThread *thread = user_data->thread;
3917 #if 0
3918 /* This no longer works with remote unwinding */
3919 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3920 mono_thread_internal_describe (thread, text);
3921 g_string_append (text, "\n");
3922 #endif
3924 if (thread == mono_thread_internal_current ())
3925 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3926 else
3927 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3929 return MonoResumeThread;
3932 typedef struct {
3933 int nthreads, max_threads;
3935 guint32 *threads;
3936 } CollectThreadsUserData;
3938 typedef struct {
3939 int nthreads, max_threads;
3940 MonoNativeThreadId *threads;
3941 } CollectThreadIdsUserData;
3943 static void
3944 collect_thread (gpointer key, gpointer value, gpointer user)
3946 CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3947 MonoInternalThread *thread = (MonoInternalThread *)value;
3949 if (ud->nthreads < ud->max_threads)
3950 ud->threads [ud->nthreads ++] = mono_gchandle_new_internal (&thread->obj, TRUE);
3954 * Collect running threads into the THREADS array.
3955 * THREADS should be an array allocated on the stack.
3957 static int
3958 collect_threads (guint32 *thread_handles, int max_threads)
3960 CollectThreadsUserData ud;
3962 mono_memory_barrier ();
3963 if (!threads)
3964 return 0;
3966 memset (&ud, 0, sizeof (ud));
3967 /* This array contains refs, but its on the stack, so its ok */
3968 ud.threads = thread_handles;
3969 ud.max_threads = max_threads;
3971 mono_threads_lock ();
3972 mono_g_hash_table_foreach (threads, collect_thread, &ud);
3973 mono_threads_unlock ();
3975 return ud.nthreads;
3978 void
3979 mono_gstring_append_thread_name (GString* text, MonoInternalThread* thread)
3981 g_string_append (text, "\n\"");
3982 char const * const name = thread->name.chars;
3983 g_string_append (text, name ? name :
3984 thread->threadpool_thread ? "<threadpool thread>" :
3985 "<unnamed thread>");
3986 g_string_append (text, "\"");
3989 static void
3990 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud, FILE* output_file)
3992 GString* text = g_string_new (0);
3993 int i;
3995 ud->thread = thread;
3996 ud->nframes = 0;
3998 /* Collect frames for the thread */
3999 if (thread == mono_thread_internal_current ()) {
4000 get_thread_dump (mono_thread_info_current (), ud);
4001 } else {
4002 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
4006 * Do all the non async-safe work outside of get_thread_dump.
4008 mono_gstring_append_thread_name (text, thread);
4010 for (i = 0; i < ud->nframes; ++i) {
4011 MonoStackFrameInfo *frame = &ud->frames [i];
4012 MonoMethod *method = NULL;
4014 if (frame->type == FRAME_TYPE_MANAGED)
4015 method = mono_jit_info_get_method (frame->ji);
4017 if (method) {
4018 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
4019 g_string_append_printf (text, " %s\n", location);
4020 g_free (location);
4021 } else {
4022 g_string_append_printf (text, " at <unknown> <0x%05x>\n", frame->native_offset);
4026 g_fprintf (output_file, "%s", text->str);
4028 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
4029 OutputDebugStringA(text->str);
4030 #endif
4032 g_string_free (text, TRUE);
4033 fflush (output_file);
4036 static void
4037 mono_get_time_of_day (struct timeval *tv) {
4038 #ifdef WIN32
4039 struct _timeb time;
4040 _ftime(&time);
4041 tv->tv_sec = time.time;
4042 tv->tv_usec = time.millitm * 1000;
4043 #else
4044 if (gettimeofday (tv, NULL) == -1) {
4045 g_error ("gettimeofday() failed; errno is %d (%s)", errno, strerror (errno));
4047 #endif
4050 static void
4051 mono_local_time (const struct timeval *tv, struct tm *tm) {
4052 #ifdef HAVE_LOCALTIME_R
4053 localtime_r(&tv->tv_sec, tm);
4054 #else
4055 time_t const tv_sec = tv->tv_sec; // Copy due to Win32/Posix contradiction.
4056 *tm = *localtime (&tv_sec);
4057 #endif
4060 void
4061 mono_threads_perform_thread_dump (void)
4063 FILE* output_file = NULL;
4064 ThreadDumpUserData ud;
4065 guint32 thread_array [128];
4066 int tindex, nthreads;
4068 if (!thread_dump_requested)
4069 return;
4071 if (thread_dump_dir != NULL) {
4072 GString* path = g_string_new (0);
4073 char time_str[80];
4074 struct timeval tv;
4075 long ms;
4076 struct tm tod;
4077 mono_get_time_of_day (&tv);
4078 mono_local_time(&tv, &tod);
4079 strftime(time_str, sizeof(time_str), MONO_STRFTIME_F "_" MONO_STRFTIME_T, &tod);
4080 ms = tv.tv_usec / 1000;
4081 g_string_append_printf (path, "%s/%s.%03ld.tdump", thread_dump_dir, time_str, ms);
4082 output_file = fopen (path->str, "w");
4083 g_string_free (path, TRUE);
4085 if (output_file == NULL) {
4086 g_print ("Full thread dump:\n");
4089 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4090 nthreads = collect_threads (thread_array, 128);
4092 memset (&ud, 0, sizeof (ud));
4093 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4094 ud.max_frames = 256;
4096 for (tindex = 0; tindex < nthreads; ++tindex) {
4097 guint32 handle = thread_array [tindex];
4098 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4099 dump_thread (thread, &ud, output_file != NULL ? output_file : stdout);
4100 mono_gchandle_free_internal (handle);
4103 if (output_file != NULL) {
4104 fclose (output_file);
4106 g_free (ud.frames);
4108 thread_dump_requested = FALSE;
4111 #ifndef ENABLE_NETCORE
4112 /* Obtain the thread dump of all threads */
4113 void
4114 ves_icall_System_Threading_Thread_GetStackTraces (MonoArrayHandleOut out_threads_handle, MonoArrayHandleOut out_stack_frames_handle, MonoError *error)
4116 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4117 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4119 guint32 handle = 0;
4121 MonoStackFrameHandle stack_frame_handle = MONO_HANDLE_NEW (MonoStackFrame, NULL);
4122 MonoReflectionMethodHandle reflection_method_handle = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4123 MonoStringHandle filename_handle = MONO_HANDLE_NEW (MonoString, NULL);
4124 MonoArrayHandle thread_frames_handle = MONO_HANDLE_NEW (MonoArray, NULL);
4126 ThreadDumpUserData ud;
4127 guint32 thread_array [128];
4128 MonoDomain *domain = mono_domain_get ();
4129 MonoDebugSourceLocation *location;
4130 int tindex, nthreads;
4132 MonoArray* out_threads = NULL;
4133 MonoArray* out_stack_frames = NULL;
4135 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4136 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4138 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4139 nthreads = collect_threads (thread_array, 128);
4141 memset (&ud, 0, sizeof (ud));
4142 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4143 ud.max_frames = 256;
4145 out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
4146 goto_if_nok (error, leave);
4147 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, out_threads);
4148 out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
4149 goto_if_nok (error, leave);
4150 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, out_stack_frames);
4152 for (tindex = 0; tindex < nthreads; ++tindex) {
4154 mono_gchandle_free_internal (handle);
4155 handle = thread_array [tindex];
4156 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4158 MonoArray *thread_frames;
4159 int i;
4161 ud.thread = thread;
4162 ud.nframes = 0;
4164 /* Collect frames for the thread */
4165 if (thread == mono_thread_internal_current ()) {
4166 get_thread_dump (mono_thread_info_current (), &ud);
4167 } else {
4168 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
4171 mono_array_setref_fast (out_threads, tindex, mono_thread_current_for_thread (thread));
4173 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
4174 MONO_HANDLE_ASSIGN_RAW (thread_frames_handle, thread_frames);
4175 goto_if_nok (error, leave);
4176 mono_array_setref_fast (out_stack_frames, tindex, thread_frames);
4178 for (i = 0; i < ud.nframes; ++i) {
4179 MonoStackFrameInfo *frame = &ud.frames [i];
4180 MonoMethod *method = NULL;
4181 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
4182 MONO_HANDLE_ASSIGN_RAW (stack_frame_handle, sf);
4183 goto_if_nok (error, leave);
4185 sf->native_offset = frame->native_offset;
4187 if (frame->type == FRAME_TYPE_MANAGED)
4188 method = mono_jit_info_get_method (frame->ji);
4190 if (method) {
4191 sf->method_address = (gsize) frame->ji->code_start;
4193 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
4194 MONO_HANDLE_ASSIGN_RAW (reflection_method_handle, rm);
4195 goto_if_nok (error, leave);
4196 MONO_OBJECT_SETREF_INTERNAL (sf, method, rm);
4198 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
4199 if (location) {
4200 sf->il_offset = location->il_offset;
4202 if (location->source_file) {
4203 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
4204 MONO_HANDLE_ASSIGN_RAW (filename_handle, filename);
4205 goto_if_nok (error, leave);
4206 MONO_OBJECT_SETREF_INTERNAL (sf, filename, filename);
4207 sf->line = location->row;
4208 sf->column = location->column;
4210 mono_debug_free_source_location (location);
4211 } else {
4212 sf->il_offset = -1;
4215 mono_array_setref_internal (thread_frames, i, sf);
4218 mono_gchandle_free_internal (handle);
4219 handle = 0;
4222 leave:
4223 mono_gchandle_free_internal (handle);
4224 g_free (ud.frames);
4226 #endif
4229 * mono_threads_request_thread_dump:
4231 * Ask all threads except the current to print their stacktrace to stdout.
4233 void
4234 mono_threads_request_thread_dump (void)
4236 /*The new thread dump code runs out of the finalizer thread. */
4237 thread_dump_requested = TRUE;
4238 mono_gc_finalize_notify ();
4241 struct ref_stack {
4242 gpointer *refs;
4243 gint allocated; /* +1 so that refs [allocated] == NULL */
4244 gint bottom;
4247 typedef struct ref_stack RefStack;
4249 static RefStack *
4250 ref_stack_new (gint initial_size)
4252 RefStack *rs;
4254 initial_size = MAX (initial_size, 16) + 1;
4255 rs = g_new0 (RefStack, 1);
4256 rs->refs = g_new0 (gpointer, initial_size);
4257 rs->allocated = initial_size;
4258 return rs;
4261 static void
4262 ref_stack_destroy (gpointer ptr)
4264 RefStack *rs = (RefStack *)ptr;
4266 if (rs != NULL) {
4267 g_free (rs->refs);
4268 g_free (rs);
4272 static void
4273 ref_stack_push (RefStack *rs, gpointer ptr)
4275 g_assert (rs != NULL);
4277 if (rs->bottom >= rs->allocated) {
4278 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
4279 rs->allocated <<= 1;
4280 rs->refs [rs->allocated] = NULL;
4282 rs->refs [rs->bottom++] = ptr;
4285 static void
4286 ref_stack_pop (RefStack *rs)
4288 if (rs == NULL || rs->bottom == 0)
4289 return;
4291 rs->bottom--;
4292 rs->refs [rs->bottom] = NULL;
4295 static gboolean
4296 ref_stack_find (RefStack *rs, gpointer ptr)
4298 gpointer *refs;
4300 if (rs == NULL)
4301 return FALSE;
4303 for (refs = rs->refs; refs && *refs; refs++) {
4304 if (*refs == ptr)
4305 return TRUE;
4307 return FALSE;
4311 * mono_thread_push_appdomain_ref:
4313 * Register that the current thread may have references to objects in domain
4314 * @domain on its stack. Each call to this function should be paired with a
4315 * call to pop_appdomain_ref.
4317 void
4318 mono_thread_push_appdomain_ref (MonoDomain *domain)
4320 MonoInternalThread *thread = mono_thread_internal_current ();
4322 if (thread) {
4323 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4324 SPIN_LOCK (thread->lock_thread_id);
4325 if (thread->appdomain_refs == NULL)
4326 thread->appdomain_refs = ref_stack_new (16);
4327 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
4328 SPIN_UNLOCK (thread->lock_thread_id);
4332 void
4333 mono_thread_pop_appdomain_ref (void)
4335 MonoInternalThread *thread = mono_thread_internal_current ();
4337 if (thread) {
4338 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4339 SPIN_LOCK (thread->lock_thread_id);
4340 ref_stack_pop ((RefStack *)thread->appdomain_refs);
4341 SPIN_UNLOCK (thread->lock_thread_id);
4345 gboolean
4346 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
4348 gboolean res;
4349 SPIN_LOCK (thread->lock_thread_id);
4350 res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
4351 SPIN_UNLOCK (thread->lock_thread_id);
4352 return res;
4355 gboolean
4356 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
4358 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
4361 typedef struct abort_appdomain_data {
4362 struct wait_data wait;
4363 MonoDomain *domain;
4364 } abort_appdomain_data;
4366 static void
4367 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
4369 MonoInternalThread *thread = (MonoInternalThread*)value;
4370 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
4371 MonoDomain *domain = data->domain;
4373 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
4374 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4376 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
4377 data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
4378 data->wait.threads [data->wait.num] = thread;
4379 data->wait.num++;
4380 } else {
4381 /* Just ignore the rest, we can't do anything with
4382 * them yet
4389 * mono_threads_abort_appdomain_threads:
4391 * Abort threads which has references to the given appdomain.
4393 gboolean
4394 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
4396 abort_appdomain_data user_data;
4397 gint64 start_time;
4398 int orig_timeout = timeout;
4399 int i;
4401 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
4403 start_time = mono_msec_ticks ();
4404 do {
4405 mono_threads_lock ();
4407 user_data.domain = domain;
4408 user_data.wait.num = 0;
4409 /* This shouldn't take any locks */
4410 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
4411 mono_threads_unlock ();
4413 if (user_data.wait.num > 0) {
4414 /* Abort the threads outside the threads lock */
4415 for (i = 0; i < user_data.wait.num; ++i)
4416 mono_thread_internal_abort (user_data.wait.threads [i], TRUE);
4419 * We should wait for the threads either to abort, or to leave the
4420 * domain. We can't do the latter, so we wait with a timeout.
4422 wait_for_tids (&user_data.wait, 100, FALSE);
4425 /* Update remaining time */
4426 timeout -= mono_msec_ticks () - start_time;
4427 start_time = mono_msec_ticks ();
4429 if (orig_timeout != -1 && timeout < 0)
4430 return FALSE;
4432 while (user_data.wait.num > 0);
4434 THREAD_DEBUG (g_message ("%s: abort done", __func__));
4436 return TRUE;
4439 /* This is a JIT icall. This icall is called from a finally block when
4440 * mono_install_handler_block_guard called by another thread has flipped the
4441 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4442 * the finally is in an abort protected block, we must defer the abort
4443 * exception until we leave the abort protected block. Otherwise we proceed
4444 * with a synchronous self-abort.
4446 void
4447 ves_icall_thread_finish_async_abort (void)
4449 /* We were called from the handler block and are about to
4450 * leave it. (If we end up postponing the abort because we're
4451 * in an abort protected block, the unwinder won't run and
4452 * won't clear the handler block itself which will confuse the
4453 * unwinder if we're in a try {} catch {} and we throw again.
4454 * ie, this:
4455 * static Constructor () {
4456 * try {
4457 * try {
4458 * } finally {
4459 * icall (); // Thread.Abort landed here,
4460 * // and caused the handler block to be installed
4461 * if (exvar)
4462 * ves_icall_thread_finish_async_abort (); // we're here
4464 * throw E ();
4465 * } catch (E) {
4466 * // unwinder will get confused here and synthesize a self abort
4470 * More interestingly, this doesn't only happen with icalls - a JIT
4471 * trampoline is native code that will cause a handler to be installed.
4472 * So the above situation can happen with any code in a "finally"
4473 * clause.
4475 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4476 /* Just set the async interruption requested bit. Rely on the icall
4477 * wrapper of this icall to process the thread interruption, respecting
4478 * any abort protection blocks in our call stack.
4480 mono_thread_set_self_interruption_respect_abort_prot ();
4484 * mono_thread_get_undeniable_exception:
4486 * Return an exception which needs to be raised when leaving a catch clause.
4487 * This is used for undeniable exception propagation.
4489 MonoException*
4490 mono_thread_get_undeniable_exception (void)
4492 MonoInternalThread *thread = mono_thread_internal_current ();
4494 if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
4495 return NULL;
4497 // We don't want to have our exception effect calls made by
4498 // the catching block
4500 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4501 return NULL;
4504 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4505 * exception if the thread no longer references a dying appdomain.
4507 thread->abort_exc->trace_ips = NULL;
4508 thread->abort_exc->stack_trace = NULL;
4509 return thread->abort_exc;
4512 #if MONO_SMALL_CONFIG
4513 #define NUM_STATIC_DATA_IDX 4
4514 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4515 64, 256, 1024, 4096
4517 #else
4518 #define NUM_STATIC_DATA_IDX 8
4519 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4520 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4522 #endif
4524 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
4525 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
4527 static void
4528 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
4530 gpointer *static_data = (gpointer *)addr;
4532 for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4533 void **ptr = (void **)static_data [i];
4535 if (!ptr)
4536 continue;
4538 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4539 void **p = ptr + idx;
4541 if (*p)
4542 mark_func ((MonoObject**)p, gc_data);
4547 static void
4548 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4550 mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4553 static void
4554 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4556 mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4560 * mono_alloc_static_data
4562 * Allocate memory blocks for storing threads or context static data
4564 static void
4565 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal)
4567 guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4568 int i;
4570 gpointer* static_data = *static_data_ptr;
4571 if (!static_data) {
4572 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4573 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4575 if (mono_gc_user_markers_supported ()) {
4576 if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4577 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4579 if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4580 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4583 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4584 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4585 alloc_key,
4586 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4587 *static_data_ptr = static_data;
4588 static_data [0] = static_data;
4591 for (i = 1; i <= idx; ++i) {
4592 if (static_data [i])
4593 continue;
4595 if (mono_gc_user_markers_supported ())
4596 static_data [i] = g_malloc0 (static_data_size [i]);
4597 else
4598 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4599 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4600 alloc_key,
4601 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4605 static void
4606 mono_free_static_data (gpointer* static_data)
4608 int i;
4609 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4610 gpointer p = static_data [i];
4611 if (!p)
4612 continue;
4614 * At this point, the static data pointer array is still registered with the
4615 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4616 * data. Freeing the individual arrays without first nulling their slots
4617 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4618 * such an already freed array. See bug #13813.
4620 static_data [i] = NULL;
4621 mono_memory_write_barrier ();
4622 if (mono_gc_user_markers_supported ())
4623 g_free (p);
4624 else
4625 mono_gc_free_fixed (p);
4627 mono_gc_free_fixed (static_data);
4631 * mono_init_static_data_info
4633 * Initializes static data counters
4635 static void mono_init_static_data_info (StaticDataInfo *static_data)
4637 static_data->idx = 0;
4638 static_data->offset = 0;
4639 static_data->freelist = NULL;
4643 * mono_alloc_static_data_slot
4645 * Generates an offset for static data. static_data contains the counters
4646 * used to generate it.
4648 static guint32
4649 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4651 if (!static_data->idx && !static_data->offset) {
4653 * we use the first chunk of the first allocation also as
4654 * an array for the rest of the data
4656 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4658 static_data->offset += align - 1;
4659 static_data->offset &= ~(align - 1);
4660 if (static_data->offset + size >= static_data_size [static_data->idx]) {
4661 static_data->idx ++;
4662 g_assert (size <= static_data_size [static_data->idx]);
4663 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4664 static_data->offset = 0;
4666 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4667 static_data->offset += size;
4668 return offset;
4672 * LOCKING: requires that threads_mutex is held
4674 static void
4675 context_adjust_static_data (MonoAppContextHandle ctx_handle)
4677 MonoAppContext *ctx = MONO_HANDLE_RAW (ctx_handle);
4678 if (context_static_info.offset || context_static_info.idx > 0) {
4679 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4680 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4681 ctx->data->static_data = ctx->static_data;
4686 * LOCKING: requires that threads_mutex is held
4688 static void
4689 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4691 MonoInternalThread *thread = (MonoInternalThread *)value;
4692 guint32 offset = GPOINTER_TO_UINT (user);
4694 mono_alloc_static_data (&(thread->static_data), offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid), TRUE);
4698 * LOCKING: requires that threads_mutex is held
4700 static void
4701 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4703 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4705 if (!ctx)
4706 return;
4708 guint32 offset = GPOINTER_TO_UINT (user);
4709 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4710 ctx->data->static_data = ctx->static_data;
4713 static StaticDataFreeList*
4714 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
4716 StaticDataFreeList* prev = NULL;
4717 StaticDataFreeList* tmp = static_data->freelist;
4718 while (tmp) {
4719 if (tmp->size == size) {
4720 if (prev)
4721 prev->next = tmp->next;
4722 else
4723 static_data->freelist = tmp->next;
4724 return tmp;
4726 prev = tmp;
4727 tmp = tmp->next;
4729 return NULL;
4732 #if SIZEOF_VOID_P == 4
4733 #define ONE_P 1
4734 #else
4735 #define ONE_P 1ll
4736 #endif
4738 static void
4739 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4741 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4742 if (!sets [idx])
4743 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4744 MonoBitSet *rb = sets [idx];
4745 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4746 offset /= sizeof (uintptr_t);
4747 /* offset is now the bitmap offset */
4748 for (int i = 0; i < numbits; ++i) {
4749 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4750 mono_bitset_set_fast (rb, offset + i);
4754 static void
4755 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4757 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4758 MonoBitSet *rb = sets [idx];
4759 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4760 offset /= sizeof (uintptr_t);
4761 /* offset is now the bitmap offset */
4762 for (int i = 0; i < size / sizeof (uintptr_t); i++)
4763 mono_bitset_clear_fast (rb, offset + i);
4766 guint32
4767 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4769 g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4771 StaticDataInfo *info;
4772 MonoBitSet **sets;
4774 if (static_type == SPECIAL_STATIC_THREAD) {
4775 info = &thread_static_info;
4776 sets = thread_reference_bitmaps;
4777 } else {
4778 info = &context_static_info;
4779 sets = context_reference_bitmaps;
4782 mono_threads_lock ();
4784 StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4785 guint32 offset;
4787 if (item) {
4788 offset = item->offset;
4789 g_free (item);
4790 } else {
4791 offset = mono_alloc_static_data_slot (info, size, align);
4794 update_reference_bitmap (sets, offset, bitmap, numbits);
4796 if (static_type == SPECIAL_STATIC_THREAD) {
4797 /* This can be called during startup */
4798 if (threads != NULL)
4799 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4800 } else {
4801 if (contexts != NULL)
4802 g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4804 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4807 mono_threads_unlock ();
4809 return offset;
4812 gpointer
4813 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4815 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4817 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4818 return get_thread_static_data (thread, offset);
4819 } else {
4820 return get_context_static_data (thread->current_appcontext, offset);
4824 gpointer
4825 mono_get_special_static_data (guint32 offset)
4827 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4830 typedef struct {
4831 guint32 offset;
4832 guint32 size;
4833 } OffsetSize;
4836 * LOCKING: requires that threads_mutex is held
4838 static void
4839 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4841 MonoInternalThread *thread = (MonoInternalThread *)value;
4842 OffsetSize *data = (OffsetSize *)user;
4843 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4844 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4845 char *ptr;
4847 if (!thread->static_data || !thread->static_data [idx])
4848 return;
4849 ptr = ((char*) thread->static_data [idx]) + off;
4850 mono_gc_bzero_atomic (ptr, data->size);
4854 * LOCKING: requires that threads_mutex is held
4856 static void
4857 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4859 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4861 if (!ctx)
4862 return;
4864 OffsetSize *data = (OffsetSize *)user;
4865 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4866 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4867 char *ptr;
4869 if (!ctx->static_data || !ctx->static_data [idx])
4870 return;
4872 ptr = ((char*) ctx->static_data [idx]) + off;
4873 mono_gc_bzero_atomic (ptr, data->size);
4876 static void
4877 do_free_special_slot (guint32 offset, guint32 size)
4879 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4880 MonoBitSet **sets;
4881 StaticDataInfo *info;
4883 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4884 info = &thread_static_info;
4885 sets = thread_reference_bitmaps;
4886 } else {
4887 info = &context_static_info;
4888 sets = context_reference_bitmaps;
4891 guint32 data_offset = offset;
4892 ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4893 OffsetSize data = { data_offset, size };
4895 clear_reference_bitmap (sets, data.offset, data.size);
4897 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4898 if (threads != NULL)
4899 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4900 } else {
4901 if (contexts != NULL)
4902 g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4905 if (!mono_runtime_is_shutting_down ()) {
4906 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4908 item->offset = offset;
4909 item->size = size;
4911 item->next = info->freelist;
4912 info->freelist = item;
4916 static void
4917 do_free_special (gpointer key, gpointer value, gpointer data)
4919 MonoClassField *field = (MonoClassField *)key;
4920 guint32 offset = GPOINTER_TO_UINT (value);
4921 gint32 align;
4922 guint32 size;
4923 size = mono_type_size (field->type, &align);
4924 do_free_special_slot (offset, size);
4927 void
4928 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4930 mono_threads_lock ();
4932 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4934 mono_threads_unlock ();
4937 #ifdef HOST_WIN32
4938 static void
4939 flush_thread_interrupt_queue (void)
4941 /* Consume pending APC calls for current thread.*/
4942 /* Since this function get's called from interrupt handler it must use a direct */
4943 /* Win32 API call and can't go through mono_coop_win32_wait_for_single_object_ex */
4944 /* or it will detect a pending interrupt and not entering the wait call needed */
4945 /* to consume pending APC's.*/
4946 MONO_ENTER_GC_SAFE;
4947 WaitForSingleObjectEx (GetCurrentThread (), 0, TRUE);
4948 MONO_EXIT_GC_SAFE;
4950 #else
4951 static void
4952 flush_thread_interrupt_queue (void)
4955 #endif
4958 * mono_thread_execute_interruption
4960 * Performs the operation that the requested thread state requires (abort,
4961 * suspend or stop)
4963 static gboolean
4964 mono_thread_execute_interruption (MonoExceptionHandle *pexc)
4966 gboolean fexc = FALSE;
4968 // Optimize away frame if caller supplied one.
4969 if (!pexc) {
4970 HANDLE_FUNCTION_ENTER ();
4971 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4972 fexc = mono_thread_execute_interruption (&exc);
4973 HANDLE_FUNCTION_RETURN_VAL (fexc);
4976 MONO_REQ_GC_UNSAFE_MODE;
4978 MonoInternalThreadHandle thread = mono_thread_internal_current_handle ();
4979 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4981 lock_thread_handle (thread);
4982 gboolean unlock = TRUE;
4984 /* MonoThread::interruption_requested can only be changed with atomics */
4985 if (!mono_thread_clear_interruption_requested_handle (thread))
4986 goto exit;
4988 MonoThreadObjectHandle sys_thread;
4989 sys_thread = mono_thread_current_handle ();
4991 flush_thread_interrupt_queue ();
4993 /* Clear the interrupted flag of the thread so it can wait again */
4994 mono_thread_info_clear_self_interrupt ();
4996 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4997 MONO_HANDLE_GET (exc, sys_thread, pending_exception);
4998 if (!MONO_HANDLE_IS_NULL (exc)) {
4999 // sys_thread->pending_exception = NULL;
5000 MONO_HANDLE_SETRAW (sys_thread, pending_exception, NULL);
5001 fexc = TRUE;
5002 goto exit;
5003 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_AbortRequested) {
5004 // Does the thread already have an abort exception?
5005 // If not, create a new one and set it on demand.
5006 // exc = thread->abort_exc;
5007 MONO_HANDLE_GET (exc, thread, abort_exc);
5008 if (MONO_HANDLE_IS_NULL (exc)) {
5009 ERROR_DECL (error);
5010 exc = mono_exception_new_thread_abort (error);
5011 mono_error_assert_ok (error); // FIXME
5012 // thread->abort_exc = exc;
5013 MONO_HANDLE_SET (thread, abort_exc, exc);
5015 fexc = TRUE;
5016 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_SuspendRequested) {
5017 /* calls UNLOCK_THREAD (thread) */
5018 self_suspend_internal ();
5019 unlock = FALSE;
5020 } else if (MONO_HANDLE_GETVAL (thread, thread_interrupt_requested)) {
5021 // thread->thread_interrupt_requested = FALSE
5022 MONO_HANDLE_SETVAL (thread, thread_interrupt_requested, MonoBoolean, FALSE);
5023 unlock_thread_handle (thread);
5024 unlock = FALSE;
5025 ERROR_DECL (error);
5026 exc = mono_exception_new_thread_interrupted (error);
5027 mono_error_assert_ok (error); // FIXME
5028 fexc = TRUE;
5030 exit:
5031 if (unlock)
5032 unlock_thread_handle (thread);
5034 if (fexc)
5035 MONO_HANDLE_ASSIGN (*pexc, exc);
5037 return fexc;
5040 static void
5041 mono_thread_execute_interruption_void (void)
5043 (void)mono_thread_execute_interruption (NULL);
5046 static MonoException*
5047 mono_thread_execute_interruption_ptr (void)
5049 HANDLE_FUNCTION_ENTER ();
5050 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5051 MonoException * const exc_raw = mono_thread_execute_interruption (&exc) ? MONO_HANDLE_RAW (exc) : NULL;
5052 HANDLE_FUNCTION_RETURN_VAL (exc_raw);
5056 * mono_thread_request_interruption_internal
5058 * A signal handler can call this method to request the interruption of a
5059 * thread. The result of the interruption will depend on the current state of
5060 * the thread. If the result is an exception that needs to be thrown, it is
5061 * provided as return value.
5063 static gboolean
5064 mono_thread_request_interruption_internal (gboolean running_managed, MonoExceptionHandle *pexc)
5066 MonoInternalThread *thread = mono_thread_internal_current ();
5068 /* The thread may already be stopping */
5069 if (thread == NULL)
5070 return FALSE;
5072 if (!mono_thread_set_interruption_requested (thread))
5073 return FALSE;
5075 if (!running_managed || is_running_protected_wrapper ()) {
5076 /* Can't stop while in unmanaged code. Increase the global interruption
5077 request count. When exiting the unmanaged method the count will be
5078 checked and the thread will be interrupted. */
5080 /* this will awake the thread if it is in WaitForSingleObject
5081 or similar */
5082 #ifdef HOST_WIN32
5083 mono_win32_interrupt_wait (thread->thread_info, thread->native_handle, (DWORD)thread->tid);
5084 #else
5085 mono_thread_info_self_interrupt ();
5086 #endif
5087 return FALSE;
5089 return mono_thread_execute_interruption (pexc);
5092 static void
5093 mono_thread_request_interruption_native (void)
5095 (void)mono_thread_request_interruption_internal (FALSE, NULL);
5098 static gboolean
5099 mono_thread_request_interruption_managed (MonoExceptionHandle *exc)
5101 return mono_thread_request_interruption_internal (TRUE, exc);
5104 /*This function should be called by a thread after it has exited all of
5105 * its handle blocks at interruption time.*/
5106 void
5107 mono_thread_resume_interruption (gboolean exec)
5109 MonoInternalThread *thread = mono_thread_internal_current ();
5110 gboolean still_aborting;
5112 /* The thread may already be stopping */
5113 if (thread == NULL)
5114 return;
5116 LOCK_THREAD (thread);
5117 still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
5118 UNLOCK_THREAD (thread);
5120 /*This can happen if the protected block called Thread::ResetAbort*/
5121 if (!still_aborting)
5122 return;
5124 if (!mono_thread_set_interruption_requested (thread))
5125 return;
5127 mono_thread_info_self_interrupt ();
5129 if (exec) // Ignore the exception here, it will be raised later.
5130 mono_thread_execute_interruption_void ();
5133 gboolean
5134 mono_thread_interruption_requested (void)
5136 if (mono_thread_interruption_request_flag) {
5137 MonoInternalThread *thread = mono_thread_internal_current ();
5138 /* The thread may already be stopping */
5139 if (thread != NULL)
5140 return mono_thread_get_interruption_requested (thread);
5142 return FALSE;
5145 static MonoException*
5146 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
5148 MonoInternalThread *thread = mono_thread_internal_current ();
5150 /* The thread may already be stopping */
5151 if (!thread)
5152 return NULL;
5153 if (!mono_thread_get_interruption_requested (thread))
5154 return NULL;
5155 if (!bypass_abort_protection && !mono_thread_current ()->pending_exception && is_running_protected_wrapper ())
5156 return NULL;
5158 return mono_thread_execute_interruption_ptr ();
5162 * Performs the interruption of the current thread, if one has been requested,
5163 * and the thread is not running a protected wrapper.
5164 * Return the exception which needs to be thrown, if any.
5166 MonoException*
5167 mono_thread_interruption_checkpoint (void)
5169 return mono_thread_interruption_checkpoint_request (FALSE);
5172 gboolean
5173 mono_thread_interruption_checkpoint_bool (void)
5175 return mono_thread_interruption_checkpoint () != NULL;
5178 void
5179 mono_thread_interruption_checkpoint_void (void)
5181 mono_thread_interruption_checkpoint ();
5185 * Performs the interruption of the current thread, if one has been requested.
5186 * Return the exception which needs to be thrown, if any.
5188 MonoException*
5189 mono_thread_force_interruption_checkpoint_noraise (void)
5191 return mono_thread_interruption_checkpoint_request (TRUE);
5195 * mono_set_pending_exception:
5197 * Set the pending exception of the current thread to EXC.
5198 * The exception will be thrown when execution returns to managed code.
5200 void
5201 mono_set_pending_exception (MonoException *exc)
5203 MonoThread *thread = mono_thread_current ();
5205 /* The thread may already be stopping */
5206 if (thread == NULL)
5207 return;
5209 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5211 mono_thread_request_interruption_native ();
5215 * mono_runtime_set_pending_exception:
5217 * Set the pending exception of the current thread to \p exc.
5218 * The exception will be thrown when execution returns to managed code.
5219 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5220 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5221 * in which case the behavior will be undefined).
5222 * Return whether the pending exception was set or not.
5223 * It will not be set if:
5224 * * The thread or runtime is stopping or shutting down
5225 * * There already is a pending exception (and \p overwrite is false)
5227 mono_bool
5228 mono_runtime_set_pending_exception (MonoException *exc, mono_bool overwrite)
5230 MonoThread *thread = mono_thread_current ();
5232 /* The thread may already be stopping */
5233 if (thread == NULL)
5234 return FALSE;
5236 /* Don't overwrite any existing pending exceptions unless asked to */
5237 if (!overwrite && thread->pending_exception)
5238 return FALSE;
5240 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5242 mono_thread_request_interruption_native ();
5244 return TRUE;
5249 * mono_set_pending_exception_handle:
5251 * Set the pending exception of the current thread to EXC.
5252 * The exception will be thrown when execution returns to managed code.
5254 MONO_COLD void
5255 mono_set_pending_exception_handle (MonoExceptionHandle exc)
5257 MonoThread *thread = mono_thread_current ();
5259 /* The thread may already be stopping */
5260 if (thread == NULL)
5261 return;
5263 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, MONO_HANDLE_RAW (exc));
5265 mono_thread_request_interruption_native ();
5268 void
5269 mono_thread_init_apartment_state (void)
5271 #ifdef HOST_WIN32
5272 MonoInternalThread* thread = mono_thread_internal_current ();
5274 /* Positive return value indicates success, either
5275 * S_OK if this is first CoInitialize call, or
5276 * S_FALSE if CoInitialize already called, but with same
5277 * threading model. A negative value indicates failure,
5278 * probably due to trying to change the threading model.
5280 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
5281 ? COINIT_APARTMENTTHREADED
5282 : COINIT_MULTITHREADED) < 0) {
5283 thread->apartment_state = ThreadApartmentState_Unknown;
5285 #endif
5288 void
5289 mono_thread_cleanup_apartment_state (void)
5291 #ifdef HOST_WIN32
5292 MonoInternalThread* thread = mono_thread_internal_current ();
5294 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
5295 CoUninitialize ();
5297 #endif
5300 static void
5301 mono_thread_notify_change_state (MonoThreadState old_state, MonoThreadState new_state)
5303 MonoThreadState diff = old_state ^ new_state;
5304 if (diff & ThreadState_Background) {
5305 /* If the thread changes the background mode, the main thread has to
5306 * be notified, since it has to rebuild the list of threads to
5307 * wait for.
5309 MONO_ENTER_GC_SAFE;
5310 mono_os_event_set (&background_change_event);
5311 MONO_EXIT_GC_SAFE;
5315 void
5316 mono_thread_clear_and_set_state (MonoInternalThread *thread, MonoThreadState clear, MonoThreadState set)
5318 LOCK_THREAD (thread);
5320 MonoThreadState const old_state = (MonoThreadState)thread->state;
5321 MonoThreadState const new_state = (old_state & ~clear) | set;
5322 thread->state = new_state;
5324 UNLOCK_THREAD (thread);
5326 mono_thread_notify_change_state (old_state, new_state);
5329 void
5330 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
5332 mono_thread_clear_and_set_state (thread, (MonoThreadState)0, state);
5336 * mono_thread_test_and_set_state:
5337 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5338 * \returns TRUE if \p set was OR'd in.
5340 gboolean
5341 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
5343 LOCK_THREAD (thread);
5345 MonoThreadState const old_state = (MonoThreadState)thread->state;
5347 if ((old_state & test) != 0) {
5348 UNLOCK_THREAD (thread);
5349 return FALSE;
5352 MonoThreadState const new_state = old_state | set;
5353 thread->state = new_state;
5355 UNLOCK_THREAD (thread);
5357 mono_thread_notify_change_state (old_state, new_state);
5359 return TRUE;
5362 void
5363 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
5365 mono_thread_clear_and_set_state (thread, state, (MonoThreadState)0);
5368 gboolean
5369 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
5371 LOCK_THREAD (thread);
5373 gboolean const ret = ((thread->state & test) != 0);
5375 UNLOCK_THREAD (thread);
5377 return ret;
5380 static void
5381 self_interrupt_thread (void *_unused)
5383 MonoException *exc;
5384 MonoThreadInfo *info;
5385 MonoContext ctx;
5387 exc = mono_thread_execute_interruption_ptr ();
5388 if (!exc) {
5389 if (mono_threads_are_safepoints_enabled ()) {
5390 /* We can return from an async call in coop, as
5391 * it's simply called when exiting the safepoint */
5392 /* If we're using hybrid suspend, we only self
5393 * interrupt if we were running, hence using
5394 * safepoints */
5395 return;
5398 g_error ("%s: we can't resume from an async call", __func__);
5401 info = mono_thread_info_current ();
5403 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5404 ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
5406 mono_raise_exception_with_context (exc, &ctx);
5409 static gboolean
5410 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
5412 if (!ji)
5413 return FALSE;
5414 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
5417 static gboolean
5418 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
5420 MonoJitInfo **dest = (MonoJitInfo **)data;
5421 *dest = frame->ji;
5422 return TRUE;
5425 static MonoJitInfo*
5426 mono_thread_info_get_last_managed (MonoThreadInfo *info)
5428 MonoJitInfo *ji = NULL;
5429 if (!info)
5430 return NULL;
5433 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5434 * any runtime locks while unwinding.
5436 mono_thread_info_set_is_async_context (TRUE);
5437 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
5438 mono_thread_info_set_is_async_context (FALSE);
5439 return ji;
5442 typedef struct {
5443 MonoInternalThread *thread;
5444 gboolean install_async_abort;
5445 MonoThreadInfoInterruptToken *interrupt_token;
5446 } AbortThreadData;
5448 static SuspendThreadResult
5449 async_abort_critical (MonoThreadInfo *info, gpointer ud)
5451 AbortThreadData *data = (AbortThreadData *)ud;
5452 MonoInternalThread *thread = data->thread;
5453 MonoJitInfo *ji = NULL;
5454 gboolean protected_wrapper;
5455 gboolean running_managed;
5457 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
5458 return MonoResumeThread;
5460 /*someone is already interrupting it*/
5461 if (!mono_thread_set_interruption_requested (thread))
5462 return MonoResumeThread;
5464 ji = mono_thread_info_get_last_managed (info);
5465 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5466 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5468 if (!protected_wrapper && running_managed) {
5469 /*We are in managed code*/
5470 /*Set the thread to call */
5471 if (data->install_async_abort)
5472 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5473 return MonoResumeThread;
5474 } else {
5476 * This will cause waits to be broken.
5477 * It will also prevent the thread from entering a wait, so if the thread returns
5478 * from the wait before it receives the abort signal, it will just spin in the wait
5479 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5480 * make it return.
5482 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
5484 return MonoResumeThread;
5488 static void
5489 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
5491 AbortThreadData data;
5493 g_assert (thread != mono_thread_internal_current ());
5495 data.thread = thread;
5496 data.install_async_abort = install_async_abort;
5497 data.interrupt_token = NULL;
5499 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
5500 if (data.interrupt_token)
5501 mono_thread_info_finish_interrupt (data.interrupt_token);
5502 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5505 static void
5506 self_abort_internal (MonoError *error)
5508 HANDLE_FUNCTION_ENTER ();
5510 error_init (error);
5512 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5513 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5516 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.
5518 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5519 if (mono_thread_request_interruption_managed (&exc))
5520 mono_error_set_exception_handle (error, exc);
5521 else
5522 mono_thread_info_self_interrupt ();
5524 HANDLE_FUNCTION_RETURN ();
5527 typedef struct {
5528 MonoInternalThread *thread;
5529 gboolean interrupt;
5530 MonoThreadInfoInterruptToken *interrupt_token;
5531 } SuspendThreadData;
5533 static SuspendThreadResult
5534 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
5536 SuspendThreadData *data = (SuspendThreadData *)ud;
5537 MonoInternalThread *thread = data->thread;
5538 MonoJitInfo *ji = NULL;
5539 gboolean protected_wrapper;
5540 gboolean running_managed;
5542 ji = mono_thread_info_get_last_managed (info);
5543 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5544 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5546 if (running_managed && !protected_wrapper) {
5547 if (mono_threads_are_safepoints_enabled ()) {
5548 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5549 return MonoResumeThread;
5550 } else {
5551 thread->state &= ~ThreadState_SuspendRequested;
5552 thread->state |= ThreadState_Suspended;
5553 return KeepSuspended;
5555 } else {
5556 mono_thread_set_interruption_requested (thread);
5557 if (data->interrupt)
5558 data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
5560 return MonoResumeThread;
5564 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5565 static void
5566 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
5568 SuspendThreadData data;
5570 g_assert (thread != mono_thread_internal_current ());
5572 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5574 thread->self_suspended = FALSE;
5576 data.thread = thread;
5577 data.interrupt = interrupt;
5578 data.interrupt_token = NULL;
5580 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
5581 if (data.interrupt_token)
5582 mono_thread_info_finish_interrupt (data.interrupt_token);
5584 UNLOCK_THREAD (thread);
5587 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5588 static void
5589 self_suspend_internal (void)
5591 MonoInternalThread *thread;
5592 MonoOSEvent *event;
5593 MonoOSEventWaitRet res;
5595 thread = mono_thread_internal_current ();
5597 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5599 thread->self_suspended = TRUE;
5601 thread->state &= ~ThreadState_SuspendRequested;
5602 thread->state |= ThreadState_Suspended;
5604 UNLOCK_THREAD (thread);
5606 event = thread->suspended;
5608 MONO_ENTER_GC_SAFE;
5609 res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
5610 g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
5611 MONO_EXIT_GC_SAFE;
5614 static void
5615 suspend_for_shutdown_async_call (gpointer unused)
5617 for (;;)
5618 mono_thread_info_yield ();
5621 static SuspendThreadResult
5622 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
5624 mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
5625 return MonoResumeThread;
5628 void
5629 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
5631 g_assert (thread != mono_thread_internal_current ());
5633 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
5637 * mono_thread_is_foreign:
5638 * \param thread the thread to query
5640 * This function allows one to determine if a thread was created by the mono runtime and has
5641 * a well defined lifecycle or it's a foreign one, created by the native environment.
5643 * \returns TRUE if \p thread was not created by the runtime.
5645 mono_bool
5646 mono_thread_is_foreign (MonoThread *thread)
5648 mono_bool result;
5649 MONO_ENTER_GC_UNSAFE;
5650 MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
5651 result = (info->runtime_thread == FALSE);
5652 MONO_EXIT_GC_UNSAFE;
5653 return result;
5656 #ifndef HOST_WIN32
5657 static void
5658 threads_native_thread_join_lock (gpointer tid, gpointer value)
5660 pthread_t thread = (pthread_t)tid;
5661 if (thread != pthread_self ()) {
5662 MONO_ENTER_GC_SAFE;
5663 /* This shouldn't block */
5664 mono_threads_join_lock ();
5665 mono_native_thread_join (thread);
5666 mono_threads_join_unlock ();
5667 MONO_EXIT_GC_SAFE;
5670 static void
5671 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5673 pthread_t thread = (pthread_t)tid;
5674 MONO_ENTER_GC_SAFE;
5675 mono_native_thread_join (thread);
5676 MONO_EXIT_GC_SAFE;
5679 static void
5680 threads_add_joinable_thread_nolock (gpointer tid)
5682 g_hash_table_insert (joinable_threads, tid, tid);
5684 #else
5685 static void
5686 threads_native_thread_join_lock (gpointer tid, gpointer value)
5688 MonoNativeThreadId thread_id = (MonoNativeThreadId)(guint64)tid;
5689 HANDLE thread_handle = (HANDLE)value;
5690 if (thread_id != GetCurrentThreadId () && thread_handle != NULL && thread_handle != INVALID_HANDLE_VALUE) {
5691 MONO_ENTER_GC_SAFE;
5692 /* This shouldn't block */
5693 mono_threads_join_lock ();
5694 mono_native_thread_join_handle (thread_handle, TRUE);
5695 mono_threads_join_unlock ();
5696 MONO_EXIT_GC_SAFE;
5700 static void
5701 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5703 HANDLE thread_handle = (HANDLE)value;
5704 MONO_ENTER_GC_SAFE;
5705 mono_native_thread_join_handle (thread_handle, TRUE);
5706 MONO_EXIT_GC_SAFE;
5709 static void
5710 threads_add_joinable_thread_nolock (gpointer tid)
5712 g_hash_table_insert (joinable_threads, tid, (gpointer)OpenThread (SYNCHRONIZE, TRUE, (MonoNativeThreadId)(guint64)tid));
5714 #endif
5716 static void
5717 threads_add_pending_joinable_thread (gpointer tid)
5719 joinable_threads_lock ();
5721 if (!pending_joinable_threads)
5722 pending_joinable_threads = g_hash_table_new (NULL, NULL);
5724 gpointer orig_key;
5725 gpointer value;
5727 if (!g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5728 g_hash_table_insert (pending_joinable_threads, tid, tid);
5729 UnlockedIncrement (&pending_joinable_thread_count);
5732 joinable_threads_unlock ();
5735 static void
5736 threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info)
5738 g_assert (mono_thread_info);
5740 if (mono_thread_info->runtime_thread) {
5741 threads_add_pending_joinable_thread ((gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info))));
5745 static void
5746 threads_remove_pending_joinable_thread_nolock (gpointer tid)
5748 gpointer orig_key;
5749 gpointer value;
5751 if (pending_joinable_threads && g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5752 g_hash_table_remove (pending_joinable_threads, tid);
5753 if (UnlockedDecrement (&pending_joinable_thread_count) == 0)
5754 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event);
5758 static gboolean
5759 threads_wait_pending_joinable_threads (uint32_t timeout)
5761 if (UnlockedRead (&pending_joinable_thread_count) > 0) {
5762 joinable_threads_lock ();
5763 if (timeout == MONO_INFINITE_WAIT) {
5764 while (UnlockedRead (&pending_joinable_thread_count) > 0)
5765 mono_coop_cond_wait (&zero_pending_joinable_thread_event, &joinable_threads_mutex);
5766 } else {
5767 gint64 start = mono_msec_ticks ();
5768 gint64 elapsed = 0;
5769 while (UnlockedRead (&pending_joinable_thread_count) > 0 && elapsed < timeout) {
5770 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event, &joinable_threads_mutex, timeout - (uint32_t)elapsed);
5771 elapsed = mono_msec_ticks () - start;
5774 joinable_threads_unlock ();
5777 return UnlockedRead (&pending_joinable_thread_count) == 0;
5780 static void
5781 threads_add_unique_joinable_thread_nolock (gpointer tid)
5783 if (!joinable_threads)
5784 joinable_threads = g_hash_table_new (NULL, NULL);
5786 gpointer orig_key;
5787 gpointer value;
5789 if (!g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5790 threads_add_joinable_thread_nolock (tid);
5791 UnlockedIncrement (&joinable_thread_count);
5795 void
5796 mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info)
5798 g_assert (thread_info);
5799 MonoThreadInfo *mono_thread_info = thread_info;
5801 if (mono_thread_info->runtime_thread) {
5802 gpointer tid = (gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info)));
5804 joinable_threads_lock ();
5806 // Add to joinable thread list, if not already included.
5807 threads_add_unique_joinable_thread_nolock (tid);
5809 // Remove thread from pending joinable list, if present.
5810 threads_remove_pending_joinable_thread_nolock (tid);
5812 joinable_threads_unlock ();
5814 mono_gc_finalize_notify ();
5818 static void
5819 threads_add_pending_native_thread_join_call_nolock (gpointer tid)
5821 if (!pending_native_thread_join_calls)
5822 pending_native_thread_join_calls = g_hash_table_new (NULL, NULL);
5824 gpointer orig_key;
5825 gpointer value;
5827 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value))
5828 g_hash_table_insert (pending_native_thread_join_calls, tid, tid);
5831 static void
5832 threads_remove_pending_native_thread_join_call_nolock (gpointer tid)
5834 if (pending_native_thread_join_calls)
5835 g_hash_table_remove (pending_native_thread_join_calls, tid);
5837 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event);
5840 static void
5841 threads_wait_pending_native_thread_join_call_nolock (gpointer tid)
5843 gpointer orig_key;
5844 gpointer value;
5846 while (g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value)) {
5847 mono_coop_cond_wait (&pending_native_thread_join_calls_event, &joinable_threads_mutex);
5852 * mono_add_joinable_thread:
5854 * Add TID to the list of joinable threads.
5855 * LOCKING: Acquires the threads lock.
5857 void
5858 mono_threads_add_joinable_thread (gpointer tid)
5861 * We cannot detach from threads because it causes problems like
5862 * 2fd16f60/r114307. So we collect them and join them when
5863 * we have time (in the finalizer thread).
5865 joinable_threads_lock ();
5866 threads_add_unique_joinable_thread_nolock (tid);
5867 joinable_threads_unlock ();
5869 mono_gc_finalize_notify ();
5873 * mono_threads_join_threads:
5875 * Join all joinable threads. This is called from the finalizer thread.
5876 * LOCKING: Acquires the threads lock.
5878 void
5879 mono_threads_join_threads (void)
5881 GHashTableIter iter;
5882 gpointer key = NULL;
5883 gpointer value = NULL;
5884 gboolean found = FALSE;
5886 /* Fastpath */
5887 if (!UnlockedRead (&joinable_thread_count))
5888 return;
5890 while (TRUE) {
5891 joinable_threads_lock ();
5892 if (found) {
5893 // Previous native thread join call completed.
5894 threads_remove_pending_native_thread_join_call_nolock (key);
5896 found = FALSE;
5897 if (g_hash_table_size (joinable_threads)) {
5898 g_hash_table_iter_init (&iter, joinable_threads);
5899 g_hash_table_iter_next (&iter, &key, (void**)&value);
5900 g_hash_table_remove (joinable_threads, key);
5901 UnlockedDecrement (&joinable_thread_count);
5902 found = TRUE;
5904 // Add to table of tid's with pending native thread join call.
5905 threads_add_pending_native_thread_join_call_nolock (key);
5907 joinable_threads_unlock ();
5908 if (found)
5909 threads_native_thread_join_lock (key, value);
5910 else
5911 break;
5916 * mono_thread_join:
5918 * Wait for thread TID to exit.
5919 * LOCKING: Acquires the threads lock.
5921 void
5922 mono_thread_join (gpointer tid)
5924 gboolean found = FALSE;
5925 gpointer orig_key;
5926 gpointer value;
5928 joinable_threads_lock ();
5929 if (!joinable_threads)
5930 joinable_threads = g_hash_table_new (NULL, NULL);
5932 if (g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5933 g_hash_table_remove (joinable_threads, tid);
5934 UnlockedDecrement (&joinable_thread_count);
5935 found = TRUE;
5937 // Add to table of tid's with pending native join call.
5938 threads_add_pending_native_thread_join_call_nolock (tid);
5941 if (!found) {
5942 // Wait for any pending native thread join call not yet completed for this tid.
5943 threads_wait_pending_native_thread_join_call_nolock (tid);
5946 joinable_threads_unlock ();
5948 if (!found)
5949 return;
5951 threads_native_thread_join_nolock (tid, value);
5953 joinable_threads_lock ();
5954 // Native thread join call completed for this tid.
5955 threads_remove_pending_native_thread_join_call_nolock (tid);
5956 joinable_threads_unlock ();
5959 void
5960 mono_thread_internal_unhandled_exception (MonoObject* exc)
5962 MonoClass *klass = exc->vtable->klass;
5963 if (is_threadabort_exception (klass)) {
5964 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5965 } else if (!is_appdomainunloaded_exception (klass)
5966 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
5967 mono_unhandled_exception_internal (exc);
5968 if (mono_environment_exitcode_get () == 1) {
5969 mono_environment_exitcode_set (255);
5970 mono_invoke_unhandled_exception_hook (exc);
5971 g_assert_not_reached ();
5977 * mono_threads_attach_coop_internal: called by native->managed wrappers
5979 * - @cookie:
5980 * - blocking mode: contains gc unsafe transition cookie
5981 * - non-blocking mode: contains random data
5982 * - @stackdata: semi-opaque struct: stackpointer and function_name
5983 * - @return: the original domain which needs to be restored, or NULL.
5985 MonoDomain*
5986 mono_threads_attach_coop_internal (MonoDomain *domain, gpointer *cookie, MonoStackData *stackdata)
5988 MonoDomain *orig;
5989 MonoThreadInfo *info;
5990 gboolean external = FALSE;
5992 orig = mono_domain_get ();
5994 if (!domain) {
5995 /* Happens when called from AOTed code which is only used in the root domain. */
5996 domain = mono_get_root_domain ();
5997 g_assert (domain);
6000 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
6001 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
6002 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
6003 * we're only responsible for making the cookie. */
6004 if (mono_threads_is_blocking_transition_enabled ())
6005 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
6007 if (!mono_thread_internal_current ()) {
6008 mono_thread_attach (domain);
6010 // #678164
6011 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
6014 if (mono_threads_is_blocking_transition_enabled ()) {
6015 if (external) {
6016 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
6017 * return the right cookie. */
6018 *cookie = mono_threads_enter_gc_unsafe_region_cookie ();
6019 } else {
6020 /* thread state (BLOCKING|RUNNING) -> RUNNING */
6021 *cookie = mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata);
6025 if (orig != domain)
6026 mono_domain_set_fast (domain, TRUE);
6028 return orig;
6032 * mono_threads_attach_coop: called by native->managed wrappers
6034 * - @dummy:
6035 * - blocking mode: contains gc unsafe transition cookie
6036 * - non-blocking mode: contains random data
6037 * - a pointer to stack, used for some checks
6038 * - @return: the original domain which needs to be restored, or NULL.
6040 gpointer
6041 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
6043 MONO_STACKDATA (stackdata);
6044 stackdata.stackpointer = dummy;
6045 return mono_threads_attach_coop_internal (domain, dummy, &stackdata);
6049 * mono_threads_detach_coop_internal: called by native->managed wrappers
6051 * - @orig: the original domain which needs to be restored, or NULL.
6052 * - @stackdata: semi-opaque struct: stackpointer and function_name
6053 * - @cookie:
6054 * - blocking mode: contains gc unsafe transition cookie
6055 * - non-blocking mode: contains random data
6057 void
6058 mono_threads_detach_coop_internal (MonoDomain *orig, gpointer cookie, MonoStackData *stackdata)
6060 MonoDomain *domain = mono_domain_get ();
6061 g_assert (domain);
6063 if (orig != domain) {
6064 if (!orig)
6065 mono_domain_unset ();
6066 else
6067 mono_domain_set_fast (orig, TRUE);
6070 if (mono_threads_is_blocking_transition_enabled ()) {
6071 /* it won't do anything if cookie is NULL
6072 * thread state RUNNING -> (RUNNING|BLOCKING) */
6073 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie, stackdata);
6078 * mono_threads_detach_coop: called by native->managed wrappers
6080 * - @orig: the original domain which needs to be restored, or NULL.
6081 * - @dummy:
6082 * - blocking mode: contains gc unsafe transition cookie
6083 * - non-blocking mode: contains random data
6084 * - a pointer to stack, used for some checks
6086 void
6087 mono_threads_detach_coop (gpointer orig, gpointer *dummy)
6089 MONO_STACKDATA (stackdata);
6090 stackdata.stackpointer = dummy;
6091 mono_threads_detach_coop_internal ((MonoDomain*)orig, *dummy, &stackdata);
6094 #if 0
6095 /* Returns TRUE if the current thread is ready to be interrupted. */
6096 gboolean
6097 mono_threads_is_ready_to_be_interrupted (void)
6099 MonoInternalThread *thread;
6101 thread = mono_thread_internal_current ();
6102 LOCK_THREAD (thread);
6103 if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
6104 UNLOCK_THREAD (thread);
6105 return FALSE;
6108 if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6109 UNLOCK_THREAD (thread);
6110 return FALSE;
6113 UNLOCK_THREAD (thread);
6114 return TRUE;
6116 #endif
6118 void
6119 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
6121 g_string_append_printf (text, ", thread handle : %p", internal->handle);
6123 if (internal->thread_info) {
6124 g_string_append (text, ", state : ");
6125 mono_thread_info_describe_interrupt_token (internal->thread_info, text);
6128 if (internal->owned_mutexes) {
6129 int i;
6131 g_string_append (text, ", owns : [");
6132 for (i = 0; i < internal->owned_mutexes->len; i++)
6133 g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
6134 g_string_append (text, "]");
6138 gboolean
6139 mono_thread_internal_is_current (MonoInternalThread *internal)
6141 g_assert (internal);
6142 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
6145 void
6146 mono_set_thread_dump_dir (gchar* dir) {
6147 thread_dump_dir = dir;
6150 #ifdef DISABLE_CRASH_REPORTING
6151 void
6152 mono_threads_summarize_init (void)
6156 gboolean
6157 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6159 return FALSE;
6162 gboolean
6163 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6165 return FALSE;
6168 #else
6170 static gboolean
6171 mono_threads_summarize_native_self (MonoThreadSummary *out, MonoContext *ctx)
6173 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6174 return FALSE;
6176 memset (out, 0, sizeof (MonoThreadSummary));
6177 out->ctx = ctx;
6179 MonoNativeThreadId current = mono_native_thread_id_get();
6180 out->native_thread_id = (intptr_t) current;
6182 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out);
6184 mono_native_thread_get_name (current, out->name, MONO_MAX_SUMMARY_NAME_LEN);
6186 return TRUE;
6189 // Not safe to call from signal handler
6190 gboolean
6191 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6193 gboolean success = mono_threads_summarize_native_self (out, ctx);
6195 // Finish this on the same thread
6197 if (success && mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6198 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out);
6200 return success;
6203 #define MAX_NUM_THREADS 128
6204 typedef struct {
6205 gint32 has_owner; // state of this memory
6207 MonoSemType update; // notify of addition of threads
6209 int nthreads;
6210 MonoNativeThreadId thread_array [MAX_NUM_THREADS]; // ids of threads we're dumping
6212 int nthreads_attached; // Number of threads self-registered
6213 MonoThreadSummary *all_threads [MAX_NUM_THREADS];
6215 gboolean silent; // print to stdout
6216 } SummarizerGlobalState;
6218 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && defined(HAVE_EXECVE) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6219 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6220 #endif
6222 static void
6223 summarizer_supervisor_init (void);
6225 typedef struct {
6226 MonoSemType supervisor;
6227 pid_t pid;
6228 pid_t supervisor_pid;
6229 } SummarizerSupervisorState;
6231 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6233 void
6234 summarizer_supervisor_init (void)
6236 return;
6239 static pid_t
6240 summarizer_supervisor_start (SummarizerSupervisorState *state)
6242 // nonzero, so caller doesn't think it's the supervisor
6243 return (pid_t) 1;
6246 static void
6247 summarizer_supervisor_end (SummarizerSupervisorState *state)
6249 return;
6252 #else
6253 static const char *hang_watchdog_path;
6255 void
6256 summarizer_supervisor_init (void)
6258 hang_watchdog_path = g_build_filename (mono_get_config_dir (), "..", "bin", "mono-hang-watchdog", NULL);
6259 g_assert (hang_watchdog_path);
6262 static pid_t
6263 summarizer_supervisor_start (SummarizerSupervisorState *state)
6265 memset (state, 0, sizeof (*state));
6266 pid_t pid;
6268 state->pid = getpid();
6271 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6272 * it will deadlock. Call the syscall directly instead.
6274 #if defined(HOST_ANDROID)
6275 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6276 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6277 g_assert_not_reached ();
6278 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6279 pid = (pid_t) syscall (SYS_fork);
6280 #elif HAVE_FORK
6281 pid = (pid_t) fork ();
6282 #else
6283 g_assert_not_reached ();
6284 #endif
6286 if (pid != 0)
6287 state->supervisor_pid = pid;
6288 else {
6289 char pid_str[20]; // pid is a uint64_t, 20 digits max in decimal form
6290 sprintf (pid_str, "%llu", (uint64_t)state->pid);
6291 const char *const args[] = { hang_watchdog_path, pid_str, NULL };
6292 execve (args[0], (char * const*)args, NULL); // run 'mono-hang-watchdog [pid]'
6293 g_async_safe_printf ("Could not exec mono-hang-watchdog, expected on path '%s' (errno %d)\n", hang_watchdog_path, errno);
6294 exit (1);
6297 return pid;
6300 static void
6301 summarizer_supervisor_end (SummarizerSupervisorState *state)
6303 #ifdef HAVE_KILL
6304 kill (state->supervisor_pid, SIGKILL);
6305 #endif
6307 #if defined (HAVE_WAITPID)
6308 // Accessed on same thread that sets it.
6309 int status;
6310 waitpid (state->supervisor_pid, &status, 0);
6311 #endif
6313 #endif
6315 static void
6316 collect_thread_id (gpointer key, gpointer value, gpointer user)
6318 CollectThreadIdsUserData *ud = (CollectThreadIdsUserData *)user;
6319 MonoInternalThread *thread = (MonoInternalThread *)value;
6321 if (ud->nthreads < ud->max_threads)
6322 ud->threads [ud->nthreads ++] = thread_get_tid (thread);
6325 static int
6326 collect_thread_ids (MonoNativeThreadId *thread_ids, int max_threads)
6328 CollectThreadIdsUserData ud;
6330 mono_memory_barrier ();
6331 if (!threads)
6332 return 0;
6334 memset (&ud, 0, sizeof (ud));
6335 /* This array contains refs, but its on the stack, so its ok */
6336 ud.threads = thread_ids;
6337 ud.max_threads = max_threads;
6339 mono_threads_lock ();
6340 mono_g_hash_table_foreach (threads, collect_thread_id, &ud);
6341 mono_threads_unlock ();
6343 return ud.nthreads;
6346 static gboolean
6347 summarizer_state_init (SummarizerGlobalState *state, MonoNativeThreadId current, int *my_index)
6349 gint32 started_state = mono_atomic_cas_i32 (&state->has_owner, 1 /* set */, 0 /* compare */);
6350 gboolean not_started = started_state == 0;
6351 if (not_started) {
6352 state->nthreads = collect_thread_ids (state->thread_array, MAX_NUM_THREADS);
6353 mono_os_sem_init (&state->update, 0);
6356 for (int i = 0; i < state->nthreads; i++) {
6357 if (state->thread_array [i] == current) {
6358 *my_index = i;
6359 break;
6363 return not_started;
6366 static void
6367 summarizer_signal_other_threads (SummarizerGlobalState *state, MonoNativeThreadId current, int current_idx)
6369 #ifdef HAVE_SIGNAL_H
6370 sigset_t sigset, old_sigset;
6371 sigemptyset(&sigset);
6372 sigaddset(&sigset, SIGTERM);
6374 for (int i=0; i < state->nthreads; i++) {
6375 sigprocmask (SIG_UNBLOCK, &sigset, &old_sigset);
6377 if (i == current_idx)
6378 continue;
6379 #ifdef HAVE_PTHREAD_KILL
6380 pthread_kill (state->thread_array [i], SIGTERM);
6382 if (!state->silent)
6383 g_async_safe_printf("Pkilling 0x%zx from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (state->thread_array [i]), MONO_NATIVE_THREAD_ID_TO_UINT (current));
6384 #else
6385 g_error ("pthread_kill () is not supported by this platform");
6386 #endif
6388 #endif
6391 // Returns true when there are shared global references to "this_thread"
6392 static gboolean
6393 summarizer_post_dump (SummarizerGlobalState *state, MonoThreadSummary *this_thread, int current_idx)
6395 mono_memory_barrier ();
6397 gpointer old = mono_atomic_cas_ptr ((volatile gpointer *)&state->all_threads [current_idx], this_thread, NULL);
6399 if (old == GINT_TO_POINTER (-1)) {
6400 g_async_safe_printf ("Trying to register response after dumping period ended");
6401 return FALSE;
6402 } else if (old != NULL) {
6403 g_async_safe_printf ("Thread dump raced for thread slot.");
6404 return FALSE;
6407 // We added our pointer
6408 gint32 count = mono_atomic_inc_i32 ((volatile gint32 *) &state->nthreads_attached);
6409 if (count == state->nthreads)
6410 mono_os_sem_post (&state->update);
6412 return TRUE;
6415 // A lockless spinwait with a timeout
6416 // Used in environments where locks are unsafe
6418 // If set_pos is true, we wait until the expected number of threads have
6419 // responded and then count that the expected number are set. If it is not true,
6420 // then we wait for them to be unset.
6421 static void
6422 summary_timedwait (SummarizerGlobalState *state, int timeout_seconds)
6424 const gint64 milliseconds_in_second = 1000;
6425 gint64 timeout_total = milliseconds_in_second * timeout_seconds;
6427 gint64 end = mono_msec_ticks () + timeout_total;
6429 while (TRUE) {
6430 if (mono_atomic_load_i32 ((volatile gint32 *) &state->nthreads_attached) == state->nthreads)
6431 break;
6433 gint64 now = mono_msec_ticks ();
6434 gint64 remaining = end - now;
6435 if (remaining <= 0)
6436 break;
6438 mono_os_sem_timedwait (&state->update, remaining, MONO_SEM_FLAGS_NONE);
6441 return;
6444 static MonoThreadSummary *
6445 summarizer_try_read_thread (SummarizerGlobalState *state, int index)
6447 gpointer old_value = NULL;
6448 gpointer new_value = GINT_TO_POINTER(-1);
6450 do {
6451 old_value = state->all_threads [index];
6452 } while (mono_atomic_cas_ptr ((volatile gpointer *) &state->all_threads [index], new_value, old_value) != old_value);
6454 MonoThreadSummary *thread = (MonoThreadSummary *) old_value;
6455 return thread;
6458 static void
6459 summarizer_state_term (SummarizerGlobalState *state, gchar **out, gchar *mem, size_t provided_size, MonoThreadSummary *controlling)
6461 // See the array writes
6462 mono_memory_barrier ();
6464 MonoThreadSummary *threads [MAX_NUM_THREADS];
6465 memset (threads, 0, sizeof(threads));
6467 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6468 for (int i=0; i < state->nthreads; i++) {
6469 threads [i] = summarizer_try_read_thread (state, i);
6470 if (!threads [i])
6471 continue;
6473 // We are doing this dump on the controlling thread because this isn't
6474 // an async context sometimes. There's still some reliance on malloc here, but it's
6475 // much more stable to do it all from the controlling thread.
6477 // This is non-null, checked in mono_threads_summarize
6478 // with early exit there
6479 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads [i]);
6482 MonoStateWriter writer;
6483 memset (&writer, 0, sizeof (writer));
6485 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6486 mono_summarize_native_state_begin (&writer, mem, provided_size);
6487 for (int i=0; i < state->nthreads; i++) {
6488 MonoThreadSummary *thread = threads [i];
6489 if (!thread)
6490 continue;
6492 mono_summarize_native_state_add_thread (&writer, thread, thread->ctx, thread == controlling);
6493 // Set non-shared state to notify the waiting thread to clean up
6494 // without having to keep our shared state alive
6495 mono_atomic_store_i32 (&thread->done, 0x1);
6496 mono_os_sem_post (&thread->done_wait);
6498 *out = mono_summarize_native_state_end (&writer);
6499 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6501 mono_os_sem_destroy (&state->update);
6503 memset (state, 0, sizeof (*state));
6504 mono_atomic_store_i32 ((volatile gint32 *)&state->has_owner, 0);
6507 static void
6508 summarizer_state_wait (MonoThreadSummary *thread)
6510 gint64 milliseconds_in_second = 1000;
6512 // cond_wait can spuriously wake up, so we need to check
6513 // done
6514 while (!mono_atomic_load_i32 (&thread->done))
6515 mono_os_sem_timedwait (&thread->done_wait, milliseconds_in_second, MONO_SEM_FLAGS_NONE);
6518 static gboolean
6519 mono_threads_summarize_execute_internal (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size, gboolean this_thread_controls)
6521 static SummarizerGlobalState state;
6523 int current_idx;
6524 MonoNativeThreadId current = mono_native_thread_id_get ();
6525 gboolean thread_given_control = summarizer_state_init (&state, current, &current_idx);
6527 g_assert (this_thread_controls == thread_given_control);
6529 if (state.nthreads == 0) {
6530 if (!silent)
6531 g_async_safe_printf("No threads attached to runtime.\n");
6532 memset (&state, 0, sizeof (state));
6533 return FALSE;
6536 if (this_thread_controls) {
6537 g_assert (working_mem);
6539 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6540 state.silent = silent;
6541 summarizer_signal_other_threads (&state, current, current_idx);
6542 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6545 MonoStateMem mem;
6546 gboolean success = mono_state_alloc_mem (&mem, (long) current, sizeof (MonoThreadSummary));
6547 if (!success)
6548 return FALSE;
6550 MonoThreadSummary *this_thread = (MonoThreadSummary *) mem.mem;
6552 if (mono_threads_summarize_native_self (this_thread, ctx)) {
6553 // Init the synchronization between the controlling thread and the
6554 // providing thread
6555 mono_os_sem_init (&this_thread->done_wait, 0);
6557 // Store a reference to our stack memory into global state
6558 gboolean success = summarizer_post_dump (&state, this_thread, current_idx);
6559 if (!success && !state.silent)
6560 g_async_safe_printf("Thread 0x%zx reported itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6561 } else if (!state.silent) {
6562 g_async_safe_printf("Thread 0x%zx couldn't report itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6565 // From summarizer, wait and dump.
6566 if (this_thread_controls) {
6567 if (!state.silent)
6568 g_async_safe_printf("Entering thread summarizer pause from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6570 // Wait up to 2 seconds for all of the other threads to catch up
6571 summary_timedwait (&state, 2);
6573 if (!state.silent)
6574 g_async_safe_printf("Finished thread summarizer pause from 0x%zx.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6576 // Dump and cleanup all the stack memory
6577 summarizer_state_term (&state, out, working_mem, provided_size, this_thread);
6578 } else {
6579 // Wait here, keeping our stack memory alive
6580 // for the dumper
6581 summarizer_state_wait (this_thread);
6584 // FIXME: How many threads should be counted?
6585 if (hashes)
6586 *hashes = this_thread->hashes;
6588 mono_state_free_mem (&mem);
6590 return TRUE;
6593 void
6594 mono_threads_summarize_init (void)
6596 summarizer_supervisor_init ();
6599 gboolean
6600 mono_threads_summarize_execute (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size)
6602 gboolean result;
6603 gboolean already_async = mono_thread_info_is_async_context ();
6604 if (!already_async)
6605 mono_thread_info_set_is_async_context (TRUE);
6606 result = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, working_mem, provided_size, FALSE);
6607 if (!already_async)
6608 mono_thread_info_set_is_async_context (FALSE);
6609 return result;
6612 gboolean
6613 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6615 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6616 return FALSE;
6618 // The staggered values are due to the need to use inc_i64 for the first value
6619 static gint64 next_pending_request_id = 0;
6620 static gint64 request_available_to_run = 1;
6621 gint64 this_request_id = mono_atomic_inc_i64 ((volatile gint64 *) &next_pending_request_id);
6623 // This is a global queue of summary requests.
6624 // It's not safe to signal a thread while they're in the
6625 // middle of a dump. Dladdr is not reentrant. It's the one lock
6626 // we rely on being able to take.
6628 // We don't use it in almost any other place in managed code, so
6629 // our problem is in the stack dumping code racing with the signalling code.
6631 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6632 // If we're running from a crash handler block, we're not in any position to
6633 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6634 // We should simply return so we can die cleanly.
6636 // signal_handler_controller should be set only from a handler that expects itself to be the only
6637 // entry point, where the runtime already being dumping means we should just give up
6639 gboolean success = FALSE;
6641 while (TRUE) {
6642 gint64 next_request_id = mono_atomic_load_i64 ((volatile gint64 *) &request_available_to_run);
6644 if (next_request_id == this_request_id) {
6645 gboolean already_async = mono_thread_info_is_async_context ();
6646 if (!already_async)
6647 mono_thread_info_set_is_async_context (TRUE);
6649 SummarizerSupervisorState synch;
6650 if (summarizer_supervisor_start (&synch)) {
6651 g_assert (mem);
6652 success = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, mem, provided_size, TRUE);
6653 summarizer_supervisor_end (&synch);
6656 if (!already_async)
6657 mono_thread_info_set_is_async_context (FALSE);
6659 // Only the thread that gets the ticket can unblock future dumpers.
6660 mono_atomic_inc_i64 ((volatile gint64 *) &request_available_to_run);
6661 break;
6662 } else if (signal_handler_controller) {
6663 // We're done. We can't do anything.
6664 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6665 mono_summarize_double_fault_log ();
6666 break;
6667 } else {
6668 if (!silent)
6669 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6670 sleep (2);
6674 return success;
6677 #endif
6679 #ifdef ENABLE_NETCORE
6680 void
6681 ves_icall_System_Threading_Thread_StartInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6683 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6684 gboolean res;
6686 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p)", __func__, internal));
6688 LOCK_THREAD (internal);
6690 if ((internal->state & ThreadState_Unstarted) == 0) {
6691 UNLOCK_THREAD (internal);
6692 mono_error_set_exception_thread_state (error, "Thread has already been started.");
6693 return;
6696 if ((internal->state & ThreadState_Aborted) != 0) {
6697 UNLOCK_THREAD (internal);
6698 return;
6701 res = create_thread (internal, internal, NULL, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
6702 if (!res) {
6703 UNLOCK_THREAD (internal);
6704 return;
6707 internal->state &= ~ThreadState_Unstarted;
6709 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, (gsize)internal->tid, internal->handle));
6711 UNLOCK_THREAD (internal);
6714 void
6715 ves_icall_System_Threading_Thread_InitInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6717 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6719 // Need to initialize thread objects created from managed code
6720 init_internal_thread_object (internal);
6721 internal->state = ThreadState_Unstarted;
6722 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
6725 guint64
6726 ves_icall_System_Threading_Thread_GetCurrentOSThreadId (MonoError *error)
6728 return mono_native_thread_os_id_get ();
6731 #endif