Allow runtime to be built with C++ on AIX (#17672)
[mono-project.git] / mono / metadata / threads.c
blob645543125ccde031667ccbd50575da4c3c8a2adc
1 /**
2 * \file
3 * Thread support internal calls
5 * Author:
6 * Dick Porter (dick@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
8 * Patrik Torstensson (patrik.torstensson@labs2.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <config.h>
18 #include <glib.h>
19 #include <string.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/environment.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/mono-hash-internals.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/runtime.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/debug-internals.h>
35 #include <mono/utils/monobitset.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
40 #include <mono/utils/mono-threads.h>
41 #include <mono/utils/mono-threads-coop.h>
42 #include <mono/utils/mono-tls.h>
43 #include <mono/utils/atomic.h>
44 #include <mono/utils/mono-memory-model.h>
45 #include <mono/utils/mono-error-internals.h>
46 #include <mono/utils/os-event.h>
47 #include <mono/utils/mono-threads-debug.h>
48 #include <mono/utils/unlocked.h>
49 #include <mono/metadata/w32handle.h>
50 #include <mono/metadata/w32event.h>
51 #include <mono/metadata/w32mutex.h>
53 #include <mono/metadata/reflection-internals.h>
54 #include <mono/metadata/abi-details.h>
55 #include <mono/metadata/w32error.h>
56 #include <mono/utils/w32api.h>
57 #include <mono/utils/mono-os-wait.h>
58 #include <mono/metadata/exception-internals.h>
59 #include <mono/utils/mono-state.h>
60 #include <mono/metadata/w32subset.h>
61 #include <mono/metadata/mono-config.h>
62 #include "mono/utils/mono-tls-inline.h"
64 #ifdef HAVE_SYS_WAIT_H
65 #include <sys/wait.h>
66 #endif
68 #include <signal.h>
70 #if defined(HOST_WIN32)
71 #include <objbase.h>
72 #include <sys/timeb.h>
73 extern gboolean
74 mono_native_thread_join_handle (HANDLE thread_handle, gboolean close_handle);
75 #endif
77 #if defined(HOST_FUCHSIA)
78 #include <zircon/syscalls.h>
79 #endif
81 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
82 #define USE_TKILL_ON_ANDROID 1
83 #endif
85 #ifdef HOST_ANDROID
86 #include <errno.h>
88 #ifdef USE_TKILL_ON_ANDROID
89 extern int tkill (pid_t tid, int signal);
90 #endif
91 #endif
93 #include "icall-decl.h"
95 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
96 #define THREAD_DEBUG(a)
97 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
98 #define THREAD_WAIT_DEBUG(a)
99 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
100 #define LIBGC_DEBUG(a)
102 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
103 #define SPIN_LOCK(i) do { \
104 if (SPIN_TRYLOCK (i)) \
105 break; \
106 } while (1)
108 #define SPIN_UNLOCK(i) i = 0
110 #define LOCK_THREAD(thread) lock_thread((thread))
111 #define UNLOCK_THREAD(thread) unlock_thread((thread))
113 typedef union {
114 gint32 ival;
115 gfloat fval;
116 } IntFloatUnion;
118 typedef union {
119 gint64 ival;
120 gdouble fval;
121 } LongDoubleUnion;
123 typedef struct _StaticDataFreeList StaticDataFreeList;
124 struct _StaticDataFreeList {
125 StaticDataFreeList *next;
126 guint32 offset;
127 guint32 size;
130 typedef struct {
131 int idx;
132 int offset;
133 StaticDataFreeList *freelist;
134 } StaticDataInfo;
136 /* Controls access to the 'threads' hash table */
137 static void mono_threads_lock (void);
138 static void mono_threads_unlock (void);
139 static MonoCoopMutex threads_mutex;
141 /* Controls access to the 'joinable_threads' hash table */
142 #define joinable_threads_lock() mono_coop_mutex_lock (&joinable_threads_mutex)
143 #define joinable_threads_unlock() mono_coop_mutex_unlock (&joinable_threads_mutex)
144 static MonoCoopMutex joinable_threads_mutex;
146 /* Holds current status of static data heap */
147 static StaticDataInfo thread_static_info;
148 static StaticDataInfo context_static_info;
150 /* The hash of existing threads (key is thread ID, value is
151 * MonoInternalThread*) that need joining before exit
153 static MonoGHashTable *threads=NULL;
155 /* List of app context GC handles.
156 * Added to from mono_threads_register_app_context ().
158 static GHashTable *contexts = NULL;
160 /* Cleanup queue for contexts. */
161 static MonoReferenceQueue *context_queue;
164 * Threads which are starting up and they are not in the 'threads' hash yet.
165 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
166 * Protected by mono_threads_lock ().
168 static MonoGHashTable *threads_starting_up = NULL;
170 /* Contains tids */
171 /* Protected by the threads lock */
172 static GHashTable *joinable_threads;
173 static gint32 joinable_thread_count;
175 /* mono_threads_join_threads will take threads from joinable_threads list and wait for them. */
176 /* When this happens, the tid is not on the list anymore so mono_thread_join assumes the thread has complete */
177 /* and will return back to the caller. This could cause a race since caller of join assumes thread has completed */
178 /* and on some OS it could cause errors. Keeping the tid's currently pending a native thread join call */
179 /* in a separate table (only affecting callers interested in this internal join detail) and look at that table in mono_thread_join */
180 /* will close this race. */
181 static GHashTable *pending_native_thread_join_calls;
182 static MonoCoopCond pending_native_thread_join_calls_event;
184 static GHashTable *pending_joinable_threads;
185 static gint32 pending_joinable_thread_count;
187 static MonoCoopCond zero_pending_joinable_thread_event;
189 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info);
190 static gboolean threads_wait_pending_joinable_threads (uint32_t timeout);
191 static gchar* thread_dump_dir = NULL;
193 #define SET_CURRENT_OBJECT mono_tls_set_thread
194 #define GET_CURRENT_OBJECT mono_tls_get_thread
196 /* function called at thread start */
197 static MonoThreadStartCB mono_thread_start_cb = NULL;
199 /* function called at thread attach */
200 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
202 /* function called at thread cleanup */
203 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
205 /* The default stack size for each thread */
206 static guint32 default_stacksize = 0;
207 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
209 static void context_adjust_static_data (MonoAppContextHandle ctx);
210 static void mono_free_static_data (gpointer* static_data);
211 static void mono_init_static_data_info (StaticDataInfo *static_data);
212 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
213 static gboolean mono_thread_resume (MonoInternalThread* thread);
214 static void async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort);
215 static void self_abort_internal (MonoError *error);
216 static void async_suspend_internal (MonoInternalThread *thread, gboolean interrupt);
217 static void self_suspend_internal (void);
219 static gboolean
220 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync);
222 MONO_COLD void
223 mono_set_pending_exception_handle (MonoExceptionHandle exc);
225 static MonoException*
226 mono_thread_execute_interruption_ptr (void);
228 static void
229 mono_thread_execute_interruption_void (void);
231 static gboolean
232 mono_thread_execute_interruption (MonoExceptionHandle *pexc);
234 static void ref_stack_destroy (gpointer rs);
236 #if SIZEOF_VOID_P == 4
237 /* Spin lock for unaligned InterlockedXXX 64 bit functions on 32bit platforms. */
238 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
239 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
240 static mono_mutex_t interlocked_mutex;
241 #endif
243 /* global count of thread interruptions requested */
244 gint32 mono_thread_interruption_request_flag;
246 /* Event signaled when a thread changes its background mode */
247 static MonoOSEvent background_change_event;
249 static gboolean shutting_down = FALSE;
251 static gint32 managed_thread_id_counter = 0;
253 static void
254 mono_threads_lock (void)
256 mono_locks_coop_acquire (&threads_mutex, ThreadsLock);
259 static void
260 mono_threads_unlock (void)
262 mono_locks_coop_release (&threads_mutex, ThreadsLock);
266 static guint32
267 get_next_managed_thread_id (void)
269 return mono_atomic_inc_i32 (&managed_thread_id_counter);
273 * We separate interruptions/exceptions into either sync (they can be processed anytime,
274 * normally as soon as they are set, and are set by the same thread) and async (they can't
275 * be processed inside abort protected blocks and are normally set by other threads). We
276 * can have both a pending sync and async interruption. In this case, the sync exception is
277 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
278 * also handle all sync type exceptions before the async type exceptions.
280 enum {
281 INTERRUPT_SYNC_REQUESTED_BIT = 0x1,
282 INTERRUPT_ASYNC_REQUESTED_BIT = 0x2,
283 INTERRUPT_REQUESTED_MASK = 0x3,
284 ABORT_PROT_BLOCK_SHIFT = 2,
285 ABORT_PROT_BLOCK_BITS = 8,
286 ABORT_PROT_BLOCK_MASK = (((1 << ABORT_PROT_BLOCK_BITS) - 1) << ABORT_PROT_BLOCK_SHIFT)
289 static int
290 mono_thread_get_abort_prot_block_count (MonoInternalThread *thread)
292 gsize state = thread->thread_state;
293 return (state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT;
296 gboolean
297 mono_threads_is_current_thread_in_protected_block (void)
299 MonoInternalThread *thread = mono_thread_internal_current ();
301 return mono_thread_get_abort_prot_block_count (thread) > 0;
304 void
305 mono_threads_begin_abort_protected_block (void)
307 MonoInternalThread *thread = mono_thread_internal_current ();
308 gsize old_state, new_state;
309 int new_val;
310 do {
311 old_state = thread->thread_state;
313 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) + 1;
314 //bounds check abort_prot_count
315 g_assert (new_val > 0);
316 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
318 new_state = old_state + (1 << ABORT_PROT_BLOCK_SHIFT);
319 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
321 /* Defer async request since we won't be able to process until exiting the block */
322 if (new_val == 1 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
323 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag);
324 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
325 if (mono_thread_interruption_request_flag < 0)
326 g_warning ("bad mono_thread_interruption_request_flag state");
327 } else {
328 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
332 static gboolean
333 mono_thread_state_has_interruption (gsize state)
335 /* pending exception, self abort */
336 if (state & INTERRUPT_SYNC_REQUESTED_BIT)
337 return TRUE;
339 /* abort, interruption, suspend */
340 if ((state & INTERRUPT_ASYNC_REQUESTED_BIT) && !(state & ABORT_PROT_BLOCK_MASK))
341 return TRUE;
343 return FALSE;
346 gboolean
347 mono_threads_end_abort_protected_block (void)
349 MonoInternalThread *thread = mono_thread_internal_current ();
350 gsize old_state, new_state;
351 int new_val;
352 do {
353 old_state = thread->thread_state;
355 //bounds check abort_prot_count
356 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) - 1;
357 g_assert (new_val >= 0);
358 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
360 new_state = old_state - (1 << ABORT_PROT_BLOCK_SHIFT);
361 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
363 if (new_val == 0 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
364 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag);
365 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
366 } else {
367 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
370 return mono_thread_state_has_interruption (new_state);
373 static gboolean
374 mono_thread_get_interruption_requested (MonoInternalThread *thread)
376 gsize state = thread->thread_state;
378 return mono_thread_state_has_interruption (state);
382 * Returns TRUE is there was a state change
383 * We clear a single interruption request, sync has priority.
385 static gboolean
386 mono_thread_clear_interruption_requested (MonoInternalThread *thread)
388 gsize old_state, new_state;
389 do {
390 old_state = thread->thread_state;
392 // no interruption to process
393 if (!(old_state & INTERRUPT_SYNC_REQUESTED_BIT) &&
394 (!(old_state & INTERRUPT_ASYNC_REQUESTED_BIT) || (old_state & ABORT_PROT_BLOCK_MASK)))
395 return FALSE;
397 if (old_state & INTERRUPT_SYNC_REQUESTED_BIT)
398 new_state = old_state & ~INTERRUPT_SYNC_REQUESTED_BIT;
399 else
400 new_state = old_state & ~INTERRUPT_ASYNC_REQUESTED_BIT;
401 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
403 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag);
404 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);
405 if (mono_thread_interruption_request_flag < 0)
406 g_warning ("bad mono_thread_interruption_request_flag state");
407 return TRUE;
410 static gboolean
411 mono_thread_clear_interruption_requested_handle (MonoInternalThreadHandle thread)
413 // Internal threads are pinned so shallow coop/handle.
414 return mono_thread_clear_interruption_requested (mono_internal_thread_handle_ptr (thread));
417 /* Returns TRUE is there was a state change and the interruption can be processed */
418 static gboolean
419 mono_thread_set_interruption_requested (MonoInternalThread *thread)
421 //always force when the current thread is doing it to itself.
422 gboolean sync = thread == mono_thread_internal_current ();
423 /* Normally synchronous interruptions can bypass abort protection. */
424 return mono_thread_set_interruption_requested_flags (thread, sync);
427 /* Returns TRUE if there was a state change and the interruption can be
428 * processed. This variant defers a self abort when inside an abort protected
429 * block. Normally this should only be done when a thread has received an
430 * outside indication that it should abort. (For example when the JIT sets a
431 * flag in an finally block.)
434 static gboolean
435 mono_thread_set_self_interruption_respect_abort_prot (void)
437 MonoInternalThread *thread = mono_thread_internal_current ();
438 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
439 * which is unusual. */
440 return mono_thread_set_interruption_requested_flags (thread, FALSE);
443 /* Returns TRUE if there was a state change and the interruption can be processed. */
444 static gboolean
445 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync)
447 gsize old_state, new_state;
448 do {
449 old_state = thread->thread_state;
451 //Already set
452 if ((sync && (old_state & INTERRUPT_SYNC_REQUESTED_BIT)) ||
453 (!sync && (old_state & INTERRUPT_ASYNC_REQUESTED_BIT)))
454 return FALSE;
456 if (sync)
457 new_state = old_state | INTERRUPT_SYNC_REQUESTED_BIT;
458 else
459 new_state = old_state | INTERRUPT_ASYNC_REQUESTED_BIT;
460 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
462 if (sync || !(new_state & ABORT_PROT_BLOCK_MASK)) {
463 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag);
464 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
465 } else {
466 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, mono_thread_interruption_request_flag);
469 return sync || !(new_state & ABORT_PROT_BLOCK_MASK);
472 static MonoNativeThreadId
473 thread_get_tid (MonoInternalThread *thread)
475 /* We store the tid as a guint64 to keep the object layout constant between platforms */
476 return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
479 static void
480 free_synch_cs (MonoCoopMutex *synch_cs)
482 g_assert (synch_cs);
483 mono_coop_mutex_destroy (synch_cs);
484 g_free (synch_cs);
487 static void
488 free_longlived_thread_data (void *user_data)
490 MonoLongLivedThreadData *lltd = (MonoLongLivedThreadData*)user_data;
491 free_synch_cs (lltd->synch_cs);
493 g_free (lltd);
496 static void
497 init_longlived_thread_data (MonoLongLivedThreadData *lltd)
499 mono_refcount_init (lltd, free_longlived_thread_data);
500 mono_refcount_inc (lltd);
501 /* Initial refcount is 2: decremented once by
502 * mono_thread_detach_internal and once by the MonoInternalThread
503 * finalizer - whichever one happens later will deallocate. */
505 lltd->synch_cs = g_new0 (MonoCoopMutex, 1);
506 mono_coop_mutex_init_recursive (lltd->synch_cs);
508 mono_memory_barrier ();
511 static void
512 dec_longlived_thread_data (MonoLongLivedThreadData *lltd)
514 mono_refcount_dec (lltd);
517 static void
518 lock_thread (MonoInternalThread *thread)
520 g_assert (thread->longlived);
521 g_assert (thread->longlived->synch_cs);
523 mono_coop_mutex_lock (thread->longlived->synch_cs);
526 static void
527 unlock_thread (MonoInternalThread *thread)
529 mono_coop_mutex_unlock (thread->longlived->synch_cs);
532 static void
533 lock_thread_handle (MonoInternalThreadHandle thread)
535 lock_thread (mono_internal_thread_handle_ptr (thread));
538 static void
539 unlock_thread_handle (MonoInternalThreadHandle thread)
541 unlock_thread (mono_internal_thread_handle_ptr (thread));
544 static gboolean
545 is_appdomainunloaded_exception (MonoClass *klass)
547 #ifdef ENABLE_NETCORE
548 return FALSE;
549 #else
550 return klass == mono_class_get_appdomain_unloaded_exception_class ();
551 #endif
554 static gboolean
555 is_threadabort_exception (MonoClass *klass)
557 return klass == mono_defaults.threadabortexception_class;
561 * A special static data offset (guint32) consists of 3 parts:
563 * [0] 6-bit index into the array of chunks.
564 * [6] 25-bit offset into the array.
565 * [31] Bit indicating thread or context static.
568 typedef union {
569 struct {
570 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
571 guint32 type : 1;
572 guint32 offset : 25;
573 guint32 index : 6;
574 #else
575 guint32 index : 6;
576 guint32 offset : 25;
577 guint32 type : 1;
578 #endif
579 } fields;
580 guint32 raw;
581 } SpecialStaticOffset;
583 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
584 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
586 static guint32
587 MAKE_SPECIAL_STATIC_OFFSET (guint32 index, guint32 offset, guint32 type)
589 SpecialStaticOffset special_static_offset;
590 memset (&special_static_offset, 0, sizeof (special_static_offset));
591 special_static_offset.fields.index = index;
592 special_static_offset.fields.offset = offset;
593 special_static_offset.fields.type = type;
594 return special_static_offset.raw;
597 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
598 (((SpecialStaticOffset *) &(x))->fields.f)
600 static gpointer
601 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
603 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_THREAD);
605 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
606 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
608 return ((char *) thread->static_data [idx]) + off;
611 static gpointer
612 get_context_static_data (MonoAppContext *ctx, guint32 offset)
614 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT);
616 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
617 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
619 return ((char *) ctx->static_data [idx]) + off;
622 static MonoThread**
623 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
625 static MonoClassField *current_thread_field = NULL;
627 guint32 offset;
629 if (!current_thread_field) {
630 current_thread_field = mono_class_get_field_from_name_full (mono_defaults.thread_class, "current_thread", NULL);
631 g_assert (current_thread_field);
634 ERROR_DECL (thread_vt_error);
635 mono_class_vtable_checked (domain, mono_defaults.thread_class, thread_vt_error);
636 mono_error_assert_ok (thread_vt_error);
637 mono_domain_lock (domain);
638 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
639 mono_domain_unlock (domain);
640 g_assert (offset);
642 return (MonoThread **)get_thread_static_data (thread, offset);
645 static void
646 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
648 #ifndef ENABLE_NETCORE
649 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
651 g_assert (current->obj.vtable->domain == domain);
653 g_assert (!*current_thread_ptr);
654 *current_thread_ptr = current;
655 #endif
658 static MonoThread*
659 create_thread_object (MonoDomain *domain, MonoInternalThread *internal)
661 #ifdef ENABLE_NETCORE
662 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
663 return internal;
664 #else
665 MonoThread *thread;
666 MonoVTable *vtable;
667 ERROR_DECL (error);
669 vtable = mono_class_vtable_checked (domain, mono_defaults.thread_class, error);
670 mono_error_assert_ok (error);
672 thread = (MonoThread*)mono_object_new_mature (vtable, error);
673 /* only possible failure mode is OOM, from which we don't expect to recover. */
674 mono_error_assert_ok (error);
676 MONO_OBJECT_SETREF_INTERNAL (thread, internal_thread, internal);
678 return thread;
679 #endif
682 static void
683 init_internal_thread_object (MonoInternalThread *thread)
685 thread->longlived = g_new0 (MonoLongLivedThreadData, 1);
686 init_longlived_thread_data (thread->longlived);
688 thread->apartment_state = ThreadApartmentState_Unknown;
689 thread->managed_id = get_next_managed_thread_id ();
690 if (mono_gc_is_moving ()) {
691 thread->thread_pinning_ref = thread;
692 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Pinning Reference");
695 thread->priority = MONO_THREAD_PRIORITY_NORMAL;
697 thread->suspended = g_new0 (MonoOSEvent, 1);
698 mono_os_event_init (thread->suspended, TRUE);
701 static MonoInternalThread*
702 create_internal_thread_object (void)
704 ERROR_DECL (error);
705 MonoInternalThread *thread;
706 MonoVTable *vt;
708 vt = mono_class_vtable_checked (mono_get_root_domain (), mono_defaults.internal_thread_class, error);
709 mono_error_assert_ok (error);
710 thread = (MonoInternalThread*) mono_object_new_mature (vt, error);
711 /* only possible failure mode is OOM, from which we don't exect to recover */
712 mono_error_assert_ok (error);
714 init_internal_thread_object (thread);
716 return thread;
719 static void
720 mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPriority priority)
722 g_assert (internal);
724 g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
725 g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
726 g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
728 #ifdef HOST_WIN32
729 BOOL res;
730 DWORD last_error;
732 g_assert (internal->native_handle);
734 MONO_ENTER_GC_SAFE;
735 res = SetThreadPriority (internal->native_handle, (int)priority - 2);
736 last_error = GetLastError ();
737 MONO_EXIT_GC_SAFE;
738 if (!res)
739 g_error ("%s: SetThreadPriority failed, error %d", __func__, last_error);
740 #elif defined(HOST_FUCHSIA)
741 int z_priority;
743 if (priority == MONO_THREAD_PRIORITY_LOWEST)
744 z_priority = ZX_PRIORITY_LOWEST;
745 else if (priority == MONO_THREAD_PRIORITY_BELOW_NORMAL)
746 z_priority = ZX_PRIORITY_LOW;
747 else if (priority == MONO_THREAD_PRIORITY_NORMAL)
748 z_priority = ZX_PRIORITY_DEFAULT;
749 else if (priority == MONO_THREAD_PRIORITY_ABOVE_NORMAL)
750 z_priority = ZX_PRIORITY_HIGH;
751 else if (priority == MONO_THREAD_PRIORITY_HIGHEST)
752 z_priority = ZX_PRIORITY_HIGHEST;
753 else
754 return;
757 // When this API becomes available on an arbitrary thread, we can use it,
758 // not available on current Zircon
760 #else /* !HOST_WIN32 and not HOST_FUCHSIA */
761 pthread_t tid;
762 int policy;
763 struct sched_param param;
764 gint res;
766 tid = thread_get_tid (internal);
768 MONO_ENTER_GC_SAFE;
769 res = pthread_getschedparam (tid, &policy, &param);
770 MONO_EXIT_GC_SAFE;
771 if (res != 0)
772 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
774 #ifdef _POSIX_PRIORITY_SCHEDULING
775 int max, min;
777 /* Necessary to get valid priority range */
779 MONO_ENTER_GC_SAFE;
780 #if defined(__PASE__)
781 /* only priorities allowed by IBM i */
782 min = PRIORITY_MIN;
783 max = PRIORITY_MAX;
784 #else
785 min = sched_get_priority_min (policy);
786 max = sched_get_priority_max (policy);
787 #endif
788 MONO_EXIT_GC_SAFE;
790 /* Not tunable. Bail out */
791 if ((min == -1) || (max == -1))
792 return;
794 if (max > 0 && min >= 0 && max > min) {
795 double srange, drange, sposition, dposition;
796 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
797 drange = max - min;
798 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
799 dposition = (sposition / srange) * drange;
800 param.sched_priority = (int)(dposition + min);
801 } else
802 #endif
804 switch (policy) {
805 case SCHED_FIFO:
806 case SCHED_RR:
807 param.sched_priority = 50;
808 break;
809 #ifdef SCHED_BATCH
810 case SCHED_BATCH:
811 #endif
812 case SCHED_OTHER:
813 param.sched_priority = 0;
814 break;
815 default:
816 g_warning ("%s: unknown policy %d", __func__, policy);
817 return;
821 MONO_ENTER_GC_SAFE;
822 #if defined(__PASE__)
823 /* only scheduling param allowed by IBM i */
824 res = pthread_setschedparam (tid, SCHED_OTHER, &param);
825 #else
826 res = pthread_setschedparam (tid, policy, &param);
827 #endif
828 MONO_EXIT_GC_SAFE;
829 if (res != 0) {
830 if (res == EPERM) {
831 #if !defined(_AIX)
832 /* AIX doesn't like doing this and will spam this every time;
833 * weirdly, i doesn't complain
835 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
836 #endif
837 return;
839 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
841 #endif /* HOST_WIN32 */
844 static void
845 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal);
847 static gboolean
848 mono_thread_attach_internal (MonoThread *thread, gboolean force_attach, gboolean force_domain)
850 MonoThreadInfo *info;
851 MonoInternalThread *internal;
852 MonoDomain *domain, *root_domain;
853 guint32 gchandle;
855 g_assert (thread);
857 info = mono_thread_info_current ();
858 g_assert (info);
860 internal = thread->internal_thread;
861 g_assert (internal);
863 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
864 * - the MonoInternalThread TLS key is destroyed: set it to NULL
865 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
866 * - it calls MonoThreadInfoCallbacks.thread_detach
867 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
868 mono_thread_info_set_internal_thread_gchandle (info, mono_gchandle_new_internal ((MonoObject*) internal, FALSE));
870 internal->handle = mono_threads_open_thread_handle (info->handle);
871 internal->native_handle = MONO_NATIVE_THREAD_HANDLE_TO_GPOINTER (mono_threads_open_native_thread_handle (info->native_handle));
872 internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
873 internal->thread_info = info;
874 internal->small_id = info->small_id;
876 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Setting current_object_key to %p", __func__, mono_native_thread_id_get (), internal));
878 SET_CURRENT_OBJECT (internal);
880 domain = mono_object_domain (thread);
882 mono_thread_push_appdomain_ref (domain);
883 if (!mono_domain_set_fast (domain, force_domain)) {
884 mono_thread_pop_appdomain_ref ();
885 goto fail;
888 mono_threads_lock ();
890 if (shutting_down && !force_attach) {
891 mono_threads_unlock ();
892 mono_thread_pop_appdomain_ref ();
893 goto fail;
896 if (threads_starting_up)
897 mono_g_hash_table_remove (threads_starting_up, thread);
899 if (!threads) {
900 threads = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Table");
903 /* We don't need to duplicate thread->handle, because it is
904 * only closed when the thread object is finalized by the GC. */
905 mono_g_hash_table_insert_internal (threads, (gpointer)(gsize)(internal->tid), internal);
907 /* We have to do this here because mono_thread_start_cb
908 * requires that root_domain_thread is set up. */
909 if (thread_static_info.offset || thread_static_info.idx > 0) {
910 /* get the current allocated size */
911 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (thread_static_info.idx, thread_static_info.offset, 0);
912 mono_alloc_static_data (&internal->static_data, offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), TRUE);
915 mono_threads_unlock ();
917 root_domain = mono_get_root_domain ();
919 g_assert (!internal->root_domain_thread);
920 if (domain != root_domain)
921 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, create_thread_object (root_domain, internal));
922 else
923 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, thread);
925 if (domain != root_domain)
926 set_current_thread_for_domain (root_domain, internal, internal->root_domain_thread);
928 set_current_thread_for_domain (domain, internal, thread);
930 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, internal->tid, internal->handle));
932 return TRUE;
934 fail:
935 mono_threads_lock ();
936 if (threads_starting_up)
937 mono_g_hash_table_remove (threads_starting_up, thread);
938 mono_threads_unlock ();
940 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
941 g_error ("%s: failed to get gchandle, info %p", __func__, info);
943 mono_gchandle_free_internal (gchandle);
945 mono_thread_info_unset_internal_thread_gchandle (info);
947 SET_CURRENT_OBJECT(NULL);
949 return FALSE;
952 static void
953 mono_thread_detach_internal (MonoInternalThread *thread)
955 MonoThreadInfo *info;
956 MonoInternalThread *value;
957 gboolean removed;
958 guint32 gchandle;
960 g_assert (mono_thread_internal_is_current (thread));
962 g_assert (thread != NULL);
963 SET_CURRENT_OBJECT (thread);
965 info = thread->thread_info;
966 g_assert (info);
968 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
970 MONO_PROFILER_RAISE (thread_stopping, (thread->tid));
973 * Prevent race condition between thread shutdown and runtime shutdown.
974 * Including all runtime threads in the pending joinable count will make
975 * sure shutdown will wait for it to get onto the joinable thread list before
976 * critical resources have been cleanup (like GC memory). Threads getting onto
977 * the joinable thread list should just about to exit and not blocking a potential
978 * join call. Owner of threads attached to the runtime but not identified as runtime
979 * threads needs to make sure thread detach calls won't race with runtime shutdown.
981 threads_add_pending_joinable_runtime_thread (info);
983 #ifndef HOST_WIN32
984 mono_w32mutex_abandon (thread);
985 #endif
987 mono_gchandle_free_internal (thread->abort_state_handle);
988 thread->abort_state_handle = 0;
990 thread->abort_exc = NULL;
991 thread->current_appcontext = NULL;
993 LOCK_THREAD (thread);
995 thread->state |= ThreadState_Stopped;
996 thread->state &= ~ThreadState_Background;
998 UNLOCK_THREAD (thread);
1001 An interruption request has leaked to cleanup. Adjust the global counter.
1003 This can happen is the abort source thread finds the abortee (this) thread
1004 in unmanaged code. If this thread never trips back to managed code or check
1005 the local flag it will be left set and positively unbalance the global counter.
1007 Leaving the counter unbalanced will cause a performance degradation since all threads
1008 will now keep checking their local flags all the time.
1010 mono_thread_clear_interruption_requested (thread);
1012 mono_threads_lock ();
1014 g_assert (threads);
1016 if (!mono_g_hash_table_lookup_extended (threads, (gpointer)thread->tid, NULL, (gpointer*) &value)) {
1017 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__, thread, thread->tid);
1018 } else if (thread != value) {
1019 /* We have to check whether the thread object for the tid is still the same in the table because the
1020 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
1021 * the table, but with another thread object. */
1022 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__, thread, thread->tid, value, value->tid);
1025 removed = mono_g_hash_table_remove (threads, (gpointer)thread->tid);
1026 g_assert (removed);
1028 mono_threads_unlock ();
1030 /* Don't close the handle here, wait for the object finalizer
1031 * to do it. Otherwise, the following race condition applies:
1033 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
1035 * 2) Some other handle is reassigned the same slot
1037 * 3) Another thread tries to join the first thread, and
1038 * blocks waiting for the reassigned handle to be signalled
1039 * (which might never happen). This is possible, because the
1040 * thread calling Join() still has a reference to the first
1041 * thread's object.
1044 mono_release_type_locks (thread);
1046 MONO_PROFILER_RAISE (thread_stopped, (thread->tid));
1047 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->stack_start_limit)));
1048 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->handle_stack)));
1051 * This will signal async signal handlers that the thread has exited.
1052 * The profiler callback needs this to be set, so it cannot be done earlier.
1054 mono_domain_unset ();
1055 mono_memory_barrier ();
1057 mono_thread_pop_appdomain_ref ();
1059 mono_free_static_data (thread->static_data);
1060 thread->static_data = NULL;
1061 ref_stack_destroy (thread->appdomain_refs);
1062 thread->appdomain_refs = NULL;
1064 g_assert (thread->suspended);
1065 mono_os_event_destroy (thread->suspended);
1066 g_free (thread->suspended);
1067 thread->suspended = NULL;
1069 if (mono_thread_cleanup_fn)
1070 mono_thread_cleanup_fn (thread_get_tid (thread));
1072 mono_memory_barrier ();
1074 if (mono_gc_is_moving ()) {
1075 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
1076 thread->thread_pinning_ref = NULL;
1079 /* There is no more any guarantee that `thread` is alive */
1080 mono_memory_barrier ();
1082 SET_CURRENT_OBJECT (NULL);
1083 mono_domain_unset ();
1085 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
1086 g_error ("%s: failed to get gchandle, info = %p", __func__, info);
1088 mono_gchandle_free_internal (gchandle);
1090 mono_thread_info_unset_internal_thread_gchandle (info);
1092 /* Possibly free synch_cs, if the finalizer for InternalThread already
1093 * ran also. */
1094 dec_longlived_thread_data (thread->longlived);
1096 MONO_PROFILER_RAISE (thread_exited, (thread->tid));
1098 /* Don't need to close the handle to this thread, even though we took a
1099 * reference in mono_thread_attach (), because the GC will do it
1100 * when the Thread object is finalised.
1104 typedef struct {
1105 gint32 ref;
1106 MonoThread *thread;
1107 MonoObject *start_delegate;
1108 MonoObject *start_delegate_arg;
1109 MonoThreadStart start_func;
1110 gpointer start_func_arg;
1111 gboolean force_attach;
1112 gboolean failed;
1113 MonoCoopSem registered;
1114 } StartInfo;
1116 static void
1117 fire_attach_profiler_events (MonoNativeThreadId tid)
1119 MONO_PROFILER_RAISE (thread_started, ((uintptr_t) tid));
1121 MonoThreadInfo *info = mono_thread_info_current ();
1123 MONO_PROFILER_RAISE (gc_root_register, (
1124 (const mono_byte*)(info->stack_start_limit),
1125 (char *) info->stack_end - (char *) info->stack_start_limit,
1126 MONO_ROOT_SOURCE_STACK,
1127 (void *) tid,
1128 "Thread Stack"));
1130 // The handle stack is a pseudo-root similar to the finalizer queues.
1131 MONO_PROFILER_RAISE (gc_root_register, (
1132 (const mono_byte*)info->handle_stack,
1134 MONO_ROOT_SOURCE_HANDLE,
1135 (void *) tid,
1136 "Handle Stack"));
1139 static guint32 WINAPI
1140 start_wrapper_internal (StartInfo *start_info, gsize *stack_ptr)
1142 ERROR_DECL (error);
1143 MonoThreadStart start_func;
1144 void *start_func_arg;
1145 gsize tid;
1147 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1148 * GC stack walk.
1150 MonoThread *thread;
1151 MonoInternalThread *internal;
1152 MonoObject *start_delegate;
1153 MonoObject *start_delegate_arg;
1155 thread = start_info->thread;
1156 internal = thread->internal_thread;
1158 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper", __func__, mono_native_thread_id_get ()));
1160 if (!mono_thread_attach_internal (thread, start_info->force_attach, FALSE)) {
1161 start_info->failed = TRUE;
1163 mono_coop_sem_post (&start_info->registered);
1165 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1166 mono_coop_sem_destroy (&start_info->registered);
1167 g_free (start_info);
1170 return 0;
1173 mono_thread_internal_set_priority (internal, (MonoThreadPriority)internal->priority);
1175 tid = internal->tid;
1177 start_delegate = start_info->start_delegate;
1178 start_delegate_arg = start_info->start_delegate_arg;
1179 start_func = start_info->start_func;
1180 start_func_arg = start_info->start_func_arg;
1182 /* This MUST be called before any managed code can be
1183 * executed, as it calls the callback function that (for the
1184 * jit) sets the lmf marker.
1187 if (mono_thread_start_cb)
1188 mono_thread_start_cb (tid, stack_ptr, (gpointer)start_func);
1190 /* On 2.0 profile (and higher), set explicitly since state might have been
1191 Unknown */
1192 if (internal->apartment_state == ThreadApartmentState_Unknown)
1193 internal->apartment_state = ThreadApartmentState_MTA;
1195 mono_thread_init_apartment_state ();
1197 /* Let the thread that called Start() know we're ready */
1198 mono_coop_sem_post (&start_info->registered);
1200 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1201 mono_coop_sem_destroy (&start_info->registered);
1202 g_free (start_info);
1205 /* start_info is not valid anymore */
1206 start_info = NULL;
1209 * Call this after calling start_notify, since the profiler callback might want
1210 * to lock the thread, and the lock is held by thread_start () which waits for
1211 * start_notify.
1213 fire_attach_profiler_events ((MonoNativeThreadId) tid);
1215 /* if the name was set before starting, we didn't invoke the profiler callback */
1216 // This is a little racy, ok.
1218 if (internal->name.chars) {
1220 LOCK_THREAD (internal);
1222 if (internal->name.chars) {
1223 MONO_PROFILER_RAISE (thread_name, (internal->tid, internal->name.chars));
1224 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), internal->name.chars);
1227 UNLOCK_THREAD (internal);
1230 /* start_func is set only for unmanaged start functions */
1231 if (start_func) {
1232 start_func (start_func_arg);
1233 } else {
1234 #ifdef ENABLE_NETCORE
1235 static MonoMethod *cb;
1237 /* Call a callback in the RuntimeThread class */
1238 g_assert (start_delegate == NULL);
1239 if (!cb) {
1240 cb = mono_class_get_method_from_name_checked (internal->obj.vtable->klass, "StartCallback", 0, 0, error);
1241 g_assert (cb);
1242 mono_error_assert_ok (error);
1244 mono_runtime_invoke_checked (cb, internal, NULL, error);
1245 #else
1246 void *args [1];
1248 g_assert (start_delegate != NULL);
1250 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1251 args [0] = (gpointer) start_delegate_arg;
1252 mono_runtime_delegate_invoke_checked (start_delegate, args, error);
1253 #endif
1255 if (!is_ok (error)) {
1256 MonoException *ex = mono_error_convert_to_exception (error);
1258 g_assert (ex != NULL);
1259 MonoClass *klass = mono_object_class (ex);
1260 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
1261 !is_threadabort_exception (klass)) {
1262 mono_unhandled_exception_internal (&ex->object);
1263 mono_invoke_unhandled_exception_hook (&ex->object);
1264 g_assert_not_reached ();
1266 } else {
1267 mono_error_cleanup (error);
1271 /* If the thread calls ExitThread at all, this remaining code
1272 * will not be executed, but the main thread will eventually
1273 * call mono_thread_detach_internal() on this thread's behalf.
1276 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
1278 /* Do any cleanup needed for apartment state. This
1279 * cannot be done in mono_thread_detach_internal since
1280 * mono_thread_detach_internal could be called for a
1281 * thread other than the current thread.
1282 * mono_thread_cleanup_apartment_state cleans up apartment
1283 * for the current thead */
1284 mono_thread_cleanup_apartment_state ();
1286 mono_thread_detach_internal (internal);
1288 return 0;
1291 static mono_thread_start_return_t WINAPI
1292 start_wrapper (gpointer data)
1294 StartInfo *start_info;
1295 MonoThreadInfo *info;
1296 gsize res;
1298 start_info = (StartInfo*) data;
1299 g_assert (start_info);
1301 info = mono_thread_info_attach ();
1302 info->runtime_thread = TRUE;
1304 /* Run the actual main function of the thread */
1305 res = start_wrapper_internal (start_info, (gsize*)info->stack_end);
1307 mono_thread_info_exit (res);
1309 g_assert_not_reached ();
1313 * create_thread:
1315 * Common thread creation code.
1316 * LOCKING: Acquires the threads lock.
1318 static gboolean
1319 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
1320 MonoThreadCreateFlags flags, MonoError *error)
1322 StartInfo *start_info = NULL;
1323 MonoNativeThreadId tid;
1324 gboolean ret;
1325 gsize stack_set_size;
1327 if (start_delegate)
1328 g_assert (!start_func && !start_func_arg);
1329 if (start_func)
1330 g_assert (!start_delegate);
1332 if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
1333 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
1334 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1336 if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
1337 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
1338 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1342 * Join joinable threads to prevent running out of threads since the finalizer
1343 * thread might be blocked/backlogged.
1345 mono_threads_join_threads ();
1347 error_init (error);
1349 mono_threads_lock ();
1350 if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
1351 mono_threads_unlock ();
1352 mono_error_set_execution_engine (error, "Couldn't create thread. Runtime is shutting down.");
1353 return FALSE;
1355 if (threads_starting_up == NULL) {
1356 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");
1358 mono_g_hash_table_insert_internal (threads_starting_up, thread, thread);
1359 mono_threads_unlock ();
1361 #ifndef ENABLE_NETCORE
1362 internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
1363 if (internal->threadpool_thread)
1364 mono_thread_set_state (internal, ThreadState_Background);
1365 #endif
1367 internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
1369 start_info = g_new0 (StartInfo, 1);
1370 start_info->ref = 2;
1371 start_info->thread = thread;
1372 start_info->start_delegate = start_delegate;
1373 start_info->start_delegate_arg = thread->start_obj;
1374 start_info->start_func = start_func;
1375 start_info->start_func_arg = start_func_arg;
1376 start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
1377 start_info->failed = FALSE;
1378 mono_coop_sem_init (&start_info->registered, 0);
1380 if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
1381 stack_set_size = default_stacksize_for_thread (internal);
1382 else
1383 stack_set_size = 0;
1385 if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
1386 /* The thread couldn't be created, so set an exception */
1387 mono_threads_lock ();
1388 mono_g_hash_table_remove (threads_starting_up, thread);
1389 mono_threads_unlock ();
1390 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1391 /* ref is not going to be decremented in start_wrapper_internal */
1392 mono_atomic_dec_i32 (&start_info->ref);
1393 ret = FALSE;
1394 goto done;
1397 internal->stack_size = (int) stack_set_size;
1399 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1402 * Wait for the thread to set up its TLS data etc, so
1403 * theres no potential race condition if someone tries
1404 * to look up the data believing the thread has
1405 * started
1408 mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1410 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));
1412 ret = !start_info->failed;
1414 done:
1415 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1416 mono_coop_sem_destroy (&start_info->registered);
1417 g_free (start_info);
1420 return ret;
1424 * mono_thread_new_init:
1426 void
1427 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1429 if (mono_thread_start_cb) {
1430 mono_thread_start_cb (tid, stack_start, func);
1435 * mono_threads_set_default_stacksize:
1437 void
1438 mono_threads_set_default_stacksize (guint32 stacksize)
1440 default_stacksize = stacksize;
1444 * mono_threads_get_default_stacksize:
1446 guint32
1447 mono_threads_get_default_stacksize (void)
1449 return default_stacksize;
1453 * mono_thread_create_internal:
1455 * ARG should not be a GC reference.
1457 MonoInternalThread*
1458 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1460 MonoThread *thread;
1461 MonoInternalThread *internal;
1462 gboolean res;
1464 error_init (error);
1466 internal = create_internal_thread_object ();
1468 thread = create_thread_object (domain, internal);
1470 LOCK_THREAD (internal);
1472 res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1473 (void)res;
1475 UNLOCK_THREAD (internal);
1477 return_val_if_nok (error, NULL);
1478 return internal;
1481 MonoInternalThreadHandle
1482 mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1484 // FIXME invert
1485 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_create_internal (domain, func, arg, flags, error));
1489 * mono_thread_create:
1491 void
1492 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1494 MONO_ENTER_GC_UNSAFE;
1495 ERROR_DECL (error);
1496 if (!mono_thread_create_checked (domain, func, arg, error))
1497 mono_error_cleanup (error);
1498 MONO_EXIT_GC_UNSAFE;
1501 gboolean
1502 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1504 return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1508 * mono_thread_attach:
1510 MonoThread *
1511 mono_thread_attach (MonoDomain *domain)
1513 MonoInternalThread *internal;
1514 MonoThread *thread;
1515 MonoThreadInfo *info;
1516 MonoNativeThreadId tid;
1518 if (mono_thread_internal_current_is_attached ()) {
1519 if (domain != mono_domain_get ())
1520 mono_domain_set_fast (domain, TRUE);
1521 /* Already attached */
1522 return mono_thread_current ();
1525 info = mono_thread_info_attach ();
1526 g_assert (info);
1528 tid=mono_native_thread_id_get ();
1530 if (mono_runtime_get_no_exec ())
1531 return NULL;
1533 internal = create_internal_thread_object ();
1535 thread = create_thread_object (domain, internal);
1537 if (!mono_thread_attach_internal (thread, FALSE, TRUE)) {
1538 /* Mono is shutting down, so just wait for the end */
1539 for (;;)
1540 mono_thread_info_sleep (10000, NULL);
1543 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, internal->handle));
1545 if (mono_thread_attach_cb)
1546 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1548 fire_attach_profiler_events (tid);
1550 return thread;
1554 * mono_thread_detach:
1556 void
1557 mono_thread_detach (MonoThread *thread)
1559 if (thread)
1560 mono_thread_detach_internal (thread->internal_thread);
1564 * mono_thread_detach_if_exiting:
1566 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1567 * This should be used at the end of embedding code which calls into managed code, and which
1568 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1570 mono_bool
1571 mono_thread_detach_if_exiting (void)
1573 if (mono_thread_info_is_exiting ()) {
1574 MonoInternalThread *thread;
1576 thread = mono_thread_internal_current ();
1577 if (thread) {
1578 // Switch to GC Unsafe thread state before detaching;
1579 // don't expect to undo this switch, hence unbalanced.
1580 gpointer dummy;
1581 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy);
1583 mono_thread_detach_internal (thread);
1584 mono_thread_info_detach ();
1585 return TRUE;
1588 return FALSE;
1591 gboolean
1592 mono_thread_internal_current_is_attached (void)
1594 MonoInternalThread *internal;
1596 internal = GET_CURRENT_OBJECT ();
1597 if (!internal)
1598 return FALSE;
1600 return TRUE;
1604 * mono_thread_exit:
1606 void
1607 mono_thread_exit (void)
1609 MonoInternalThread *thread = mono_thread_internal_current ();
1611 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
1613 mono_thread_detach_internal (thread);
1615 /* we could add a callback here for embedders to use. */
1616 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1617 exit (mono_environment_exitcode_get ());
1619 mono_thread_info_exit (0);
1622 static void
1623 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle)
1625 MonoInternalThread * const internal = create_internal_thread_object ();
1627 internal->state = ThreadState_Unstarted;
1629 int const thread_gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, this_obj_handle), TRUE);
1631 MonoThreadObject *this_obj = MONO_HANDLE_RAW (this_obj_handle);
1633 mono_atomic_cas_ptr ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1635 mono_gchandle_free_internal (thread_gchandle);
1638 #ifndef ENABLE_NETCORE
1639 void
1640 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle, MonoError *error)
1642 mono_thread_construct_internal (this_obj_handle);
1644 #endif
1646 MonoThreadObjectHandle
1647 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError *error)
1649 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
1652 static MonoInternalThread*
1653 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle)
1655 return MONO_HANDLE_GETVAL(thread_handle, internal_thread); // InternalThreads are always pinned.
1658 static void
1659 mono_error_set_exception_thread_state (MonoError *error, const char *exception_message)
1661 mono_error_set_generic_error (error, "System.Threading", "ThreadStateException", "%s", exception_message);
1664 static void
1665 mono_error_set_exception_thread_not_started_or_dead (MonoError *error)
1667 mono_error_set_exception_thread_state (error, "Thread has not been started, or is dead.");
1670 #ifndef ENABLE_NETCORE
1671 MonoBoolean
1672 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle, MonoObjectHandle start_handle, MonoError *error)
1674 MonoInternalThread *internal;
1675 gboolean res;
1676 MonoThread *this_obj = MONO_HANDLE_RAW (thread_handle);
1677 MonoObject *start = MONO_HANDLE_RAW (start_handle);
1679 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1681 internal = thread_handle_to_internal_ptr (thread_handle);
1683 if (!internal) {
1684 mono_thread_construct_internal (thread_handle);
1685 internal = thread_handle_to_internal_ptr (thread_handle);
1686 g_assert (internal);
1689 LOCK_THREAD (internal);
1691 if ((internal->state & ThreadState_Unstarted) == 0) {
1692 UNLOCK_THREAD (internal);
1693 mono_error_set_exception_thread_state (error, "Thread has already been started.");
1694 return FALSE;
1697 if ((internal->state & ThreadState_Aborted) != 0) {
1698 UNLOCK_THREAD (internal);
1699 return TRUE;
1702 res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
1703 if (!res) {
1704 UNLOCK_THREAD (internal);
1705 return FALSE;
1708 internal->state &= ~ThreadState_Unstarted;
1710 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, thread));
1712 UNLOCK_THREAD (internal);
1713 return TRUE;
1715 #endif
1717 static
1718 void
1719 mono_thread_name_cleanup (MonoThreadName* name)
1721 MonoThreadName const old_name = *name;
1722 // Do not reset generation.
1723 name->chars = 0;
1724 name->length = 0;
1725 name->free = 0;
1726 //memset (name, 0, sizeof (*name));
1727 if (old_name.free)
1728 g_free (old_name.chars);
1732 * This is called from the finalizer of the internal thread object.
1734 void
1735 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle, MonoError *error)
1737 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (this_obj_handle);
1738 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this_obj, this_obj->handle));
1741 * Since threads keep a reference to their thread object while running, by
1742 * the time this function is called, the thread has already exited/detached,
1743 * i.e. mono_thread_detach_internal () has ran. The exception is during
1744 * shutdown, when mono_thread_detach_internal () can be called after this.
1746 if (this_obj->handle) {
1747 mono_threads_close_thread_handle (this_obj->handle);
1748 this_obj->handle = NULL;
1751 mono_threads_close_native_thread_handle (MONO_GPOINTER_TO_NATIVE_THREAD_HANDLE (this_obj->native_handle));
1752 this_obj->native_handle = NULL;
1754 /* Possibly free synch_cs, if the thread already detached also. */
1755 dec_longlived_thread_data (this_obj->longlived);
1757 mono_thread_name_cleanup (&this_obj->name);
1760 static void
1761 mono_sleep_internal (gint32 ms, MonoBoolean allow_interruption, MonoError *error)
1763 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1765 if (mono_thread_current_check_pending_interrupt ())
1766 return;
1768 MonoInternalThread * const thread = mono_thread_internal_current ();
1770 HANDLE_LOOP_PREPARE;
1772 while (TRUE) {
1773 gboolean alerted = FALSE;
1775 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1777 (void)mono_thread_info_sleep (ms, &alerted);
1779 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1781 if (!alerted)
1782 return;
1784 if (allow_interruption) {
1785 SETUP_ICALL_FRAME;
1787 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
1789 const gboolean interrupt = mono_thread_execute_interruption (&exc);
1791 if (interrupt)
1792 mono_set_pending_exception_handle (exc);
1794 CLEAR_ICALL_FRAME;
1796 if (interrupt)
1797 return;
1800 if (ms == MONO_INFINITE_WAIT) // FIXME: !MONO_INFINITE_WAIT
1801 continue;
1802 return;
1806 #ifdef ENABLE_NETCORE
1807 void
1808 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoBoolean allow_interruption, MonoError *error)
1810 return mono_sleep_internal (ms, allow_interruption, error);
1812 #else
1813 void
1814 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoError *error)
1816 return mono_sleep_internal (ms, TRUE, error);
1818 #endif
1820 void
1821 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error)
1825 #ifndef ENABLE_NETCORE
1826 gint32
1827 ves_icall_System_Threading_Thread_GetDomainID (MonoError *error)
1829 return mono_domain_get()->domain_id;
1831 #endif
1834 * mono_thread_get_name_utf8:
1835 * \returns the name of the thread in UTF-8.
1836 * Return NULL if the thread has no name.
1837 * The returned memory is owned by the caller (g_free it).
1839 char *
1840 mono_thread_get_name_utf8 (MonoThread *thread)
1842 if (thread == NULL)
1843 return NULL;
1845 MonoInternalThread *internal = thread->internal_thread;
1847 // This is a little racy, ok.
1849 if (internal == NULL || !internal->name.chars)
1850 return NULL;
1852 LOCK_THREAD (internal);
1854 char *tname = (char*)g_memdup (internal->name.chars, internal->name.length + 1);
1856 UNLOCK_THREAD (internal);
1858 return tname;
1862 * mono_thread_get_managed_id:
1863 * \returns the \c Thread.ManagedThreadId value of \p thread.
1864 * Returns \c -1 if \p thread is NULL.
1866 int32_t
1867 mono_thread_get_managed_id (MonoThread *thread)
1869 if (thread == NULL)
1870 return -1;
1872 MonoInternalThread *internal = thread->internal_thread;
1873 if (internal == NULL)
1874 return -1;
1876 int32_t id = internal->managed_id;
1878 return id;
1881 #ifndef ENABLE_NETCORE
1882 MonoStringHandle
1883 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle, MonoError *error)
1885 // InternalThreads are always pinned, so shallowly coop-handleize.
1886 MonoInternalThread * const this_obj = mono_internal_thread_handle_ptr (thread_handle);
1888 MonoStringHandle str = NULL_HANDLE_STRING;
1890 // This is a little racy, ok.
1892 if (this_obj->name.chars) {
1893 LOCK_THREAD (this_obj);
1895 if (this_obj->name.chars)
1896 str = mono_string_new_utf8_len (mono_domain_get (), this_obj->name.chars, this_obj->name.length, error);
1898 UNLOCK_THREAD (this_obj);
1901 return str;
1903 #endif
1905 // Unusal function:
1906 // - MonoError is optional -- failure is usually not interesting, except the documented failure mode for managed callers.
1907 // - name16 only used on Windows.
1908 // - name8 is either constant, or g_free'able -- this function always takes ownership and never copies.
1910 gsize
1911 mono_thread_set_name (MonoInternalThread *this_obj,
1912 const char* name8, size_t name8_length, const gunichar2* name16,
1913 MonoSetThreadNameFlags flags, MonoError *error)
1915 MonoNativeThreadId tid = 0;
1917 // A counter to optimize redundant sets.
1918 // It is not exactly thread safe but no use of it could be.
1919 gsize name_generation;
1921 const gboolean constant = !!(flags & MonoSetThreadNameFlag_Constant);
1923 #if HOST_WIN32 // On Windows, if name8 is supplied, then name16 must be also.
1924 g_assert (!name8 || name16);
1925 #endif
1927 LOCK_THREAD (this_obj);
1929 name_generation = this_obj->name.generation;
1931 if (flags & MonoSetThreadNameFlag_Reset) {
1932 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1933 } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1934 UNLOCK_THREAD (this_obj);
1936 if (error)
1937 mono_error_set_invalid_operation (error, "%s", "Thread.Name can only be set once.");
1939 if (!constant)
1940 g_free ((char*)name8);
1941 return name_generation;
1944 name_generation = ++this_obj->name.generation;
1946 mono_thread_name_cleanup (&this_obj->name);
1948 if (name8) {
1949 this_obj->name.chars = (char*)name8;
1950 this_obj->name.length = name8_length;
1951 this_obj->name.free = !constant;
1952 if (flags & MonoSetThreadNameFlag_Permanent)
1953 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1956 if (!(this_obj->state & ThreadState_Stopped))
1957 tid = thread_get_tid (this_obj);
1959 UNLOCK_THREAD (this_obj);
1961 if (name8 && tid) {
1962 MONO_PROFILER_RAISE (thread_name, ((uintptr_t)tid, name8));
1963 mono_native_thread_set_name (tid, name8);
1966 mono_thread_set_name_windows (this_obj->native_handle, name16);
1968 mono_free (0); // FIXME keep mono-publib.c in use and its functions exported
1970 return name_generation;
1974 void
1975 ves_icall_System_Threading_Thread_SetName_icall (MonoInternalThreadHandle thread_handle, const gunichar2* name16, gint32 name16_length, MonoError* error)
1977 long name8_length = 0;
1979 char* name8 = name16 ? g_utf16_to_utf8 (name16, name16_length, NULL, &name8_length, NULL) : NULL;
1981 mono_thread_set_name (mono_internal_thread_handle_ptr (thread_handle),
1982 name8, (gint32)name8_length, name16, MonoSetThreadNameFlag_Permanent, error);
1985 #ifndef ENABLE_NETCORE
1987 * ves_icall_System_Threading_Thread_GetPriority_internal:
1988 * @param this_obj: The MonoInternalThread on which to operate.
1990 * Gets the priority of the given thread.
1991 * @return: The priority of the given thread.
1994 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj, MonoError *error)
1996 gint32 priority;
1998 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
2000 LOCK_THREAD (internal);
2001 priority = internal->priority;
2002 UNLOCK_THREAD (internal);
2004 return priority;
2006 #endif
2009 * ves_icall_System_Threading_Thread_SetPriority_internal:
2010 * @param this_obj: The MonoInternalThread on which to operate.
2011 * @param priority: The priority to set.
2013 * Sets the priority of the given thread.
2015 void
2016 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj, int priority, MonoError *error)
2018 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
2020 LOCK_THREAD (internal);
2021 internal->priority = priority;
2022 if (internal->thread_info != NULL)
2023 mono_thread_internal_set_priority (internal, (MonoThreadPriority)priority);
2024 UNLOCK_THREAD (internal);
2027 /* If the array is already in the requested domain, we just return it,
2028 otherwise we return a copy in that domain. */
2029 static MonoArrayHandle
2030 byte_array_to_domain (MonoArrayHandle arr, MonoDomain *domain, MonoError *error)
2032 HANDLE_FUNCTION_ENTER ()
2034 if (MONO_HANDLE_IS_NULL (arr))
2035 return MONO_HANDLE_NEW (MonoArray, NULL);
2037 if (MONO_HANDLE_DOMAIN (arr) == domain)
2038 return arr;
2040 size_t const size = mono_array_handle_length (arr);
2042 // Capture arrays into common representation for repetitious code.
2043 // These two variables could also be an array of size 2 and
2044 // repitition implemented with a loop.
2045 struct {
2046 MonoArrayHandle handle;
2047 gpointer p;
2048 guint gchandle;
2050 source = { arr },
2051 dest = { mono_array_new_handle (domain, mono_defaults.byte_class, size, error) };
2052 goto_if_nok (error, exit);
2054 // Pin both arrays.
2055 source.p = mono_array_handle_pin_with_size (source.handle, size, 0, &source.gchandle);
2056 dest.p = mono_array_handle_pin_with_size (dest.handle, size, 0, &dest.gchandle);
2058 memmove (dest.p, source.p, size);
2059 exit:
2060 // Unpin both arrays.
2061 mono_gchandle_free_internal (source.gchandle);
2062 mono_gchandle_free_internal (dest.gchandle);
2064 HANDLE_FUNCTION_RETURN_REF (MonoArray, dest.handle)
2067 #ifndef ENABLE_NETCORE
2068 MonoArrayHandle
2069 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr, MonoError *error)
2071 return byte_array_to_domain (arr, mono_get_root_domain (), error);
2074 MonoArrayHandle
2075 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr, MonoError *error)
2077 return byte_array_to_domain (arr, mono_domain_get (), error);
2079 #endif
2082 * mono_thread_current:
2084 MonoThread *
2085 mono_thread_current (void)
2087 #ifdef ENABLE_NETCORE
2088 return mono_thread_internal_current ();
2089 #else
2090 MonoDomain *domain = mono_domain_get ();
2091 MonoInternalThread *internal = mono_thread_internal_current ();
2092 MonoThread **current_thread_ptr;
2094 g_assert (internal);
2095 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2097 if (!*current_thread_ptr) {
2098 g_assert (domain != mono_get_root_domain ());
2099 *current_thread_ptr = create_thread_object (domain, internal);
2101 return *current_thread_ptr;
2102 #endif
2105 static MonoThreadObjectHandle
2106 mono_thread_current_handle (void)
2108 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
2111 /* Return the thread object belonging to INTERNAL in the current domain */
2112 static MonoThread *
2113 mono_thread_current_for_thread (MonoInternalThread *internal)
2115 #ifdef ENABLE_NETCORE
2116 return mono_thread_internal_current ();
2117 #else
2118 MonoDomain *domain = mono_domain_get ();
2119 MonoThread **current_thread_ptr;
2121 g_assert (internal);
2122 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2124 if (!*current_thread_ptr) {
2125 g_assert (domain != mono_get_root_domain ());
2126 *current_thread_ptr = create_thread_object (domain, internal);
2128 return *current_thread_ptr;
2129 #endif
2132 MonoInternalThread*
2133 mono_thread_internal_current (void)
2135 MonoInternalThread *res = GET_CURRENT_OBJECT ();
2136 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
2137 return res;
2140 MonoInternalThreadHandle
2141 mono_thread_internal_current_handle (void)
2143 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_internal_current ());
2146 static MonoThreadInfoWaitRet
2147 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
2149 MonoThreadInfoWaitRet ret;
2150 gint32 wait = ms;
2152 const gint64 start = (ms == -1) ? 0 : mono_msec_ticks ();
2153 while (TRUE) {
2154 MONO_ENTER_GC_SAFE;
2155 ret = mono_thread_info_wait_one_handle (thread_to_join, wait, TRUE);
2156 MONO_EXIT_GC_SAFE;
2158 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
2159 return ret;
2161 MonoException *exc = mono_thread_execute_interruption_ptr ();
2162 if (exc) {
2163 mono_error_set_exception_instance (error, exc);
2164 return ret;
2167 if (ms == -1)
2168 continue;
2170 /* Re-calculate ms according to the time passed */
2171 const gint32 diff_ms = (gint32)(mono_msec_ticks () - start);
2172 if (diff_ms >= ms) {
2173 ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
2174 return ret;
2176 wait = ms - diff_ms;
2179 return ret;
2182 MonoBoolean
2183 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle, int ms, MonoError *error)
2185 if (mono_thread_current_check_pending_interrupt ())
2186 return FALSE;
2188 // Internal threads are pinned so shallow coop/handle.
2189 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2190 MonoThreadHandle *handle = thread->handle;
2191 MonoInternalThread *cur_thread = mono_thread_internal_current ();
2192 gboolean ret = FALSE;
2194 LOCK_THREAD (thread);
2196 if ((thread->state & ThreadState_Unstarted) != 0) {
2197 UNLOCK_THREAD (thread);
2199 mono_error_set_exception_thread_state (error, "Thread has not been started.");
2200 return FALSE;
2203 UNLOCK_THREAD (thread);
2205 if (ms == -1)
2206 ms = MONO_INFINITE_WAIT;
2207 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
2209 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
2211 ret = mono_join_uninterrupted (handle, ms, error);
2213 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
2215 if (ret == MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
2216 THREAD_DEBUG (g_message ("%s: join successful", __func__));
2218 mono_error_assert_ok (error);
2220 /* Wait for the thread to really exit */
2221 MonoNativeThreadId tid = thread_get_tid (thread);
2222 mono_thread_join ((gpointer)(gsize)tid);
2224 return TRUE;
2227 THREAD_DEBUG (g_message ("%s: join failed", __func__));
2229 return FALSE;
2232 #define MANAGED_WAIT_FAILED 0x7fffffff
2234 static gint32
2235 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
2237 if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
2238 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
2239 } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
2240 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
2241 } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
2242 return WAIT_IO_COMPLETION;
2243 } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
2244 return WAIT_TIMEOUT;
2245 } else if (val == MONO_W32HANDLE_WAIT_RET_TOO_MANY_POSTS) {
2246 return WAIT_TOO_MANY_POSTS;
2247 } else if (val == MONO_W32HANDLE_WAIT_RET_NOT_OWNED_BY_CALLER) {
2248 return WAIT_NOT_OWNED_BY_CALLER;
2249 } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
2250 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2251 return MANAGED_WAIT_FAILED;
2252 } else {
2253 g_error ("%s: unknown val value %d", __func__, val);
2257 gint32
2258 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
2260 /* Do this WaitSleepJoin check before creating objects */
2261 if (mono_thread_current_check_pending_interrupt ())
2262 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2264 MonoInternalThread * const thread = mono_thread_internal_current ();
2266 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2268 gint64 start = 0;
2270 if (timeout == -1)
2271 timeout = MONO_INFINITE_WAIT;
2272 if (timeout != MONO_INFINITE_WAIT)
2273 start = mono_msec_ticks ();
2275 guint32 timeoutLeft = timeout;
2277 MonoW32HandleWaitRet ret;
2279 HANDLE_LOOP_PREPARE;
2281 for (;;) {
2283 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2284 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE, error);
2286 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
2287 break;
2289 SETUP_ICALL_FRAME;
2291 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
2293 const gboolean interrupt = mono_thread_execute_interruption (&exc);
2295 if (interrupt)
2296 mono_error_set_exception_handle (error, exc);
2298 CLEAR_ICALL_FRAME;
2300 if (interrupt)
2301 break;
2303 if (timeout != MONO_INFINITE_WAIT) {
2304 gint64 const elapsed = mono_msec_ticks () - start;
2305 if (elapsed >= timeout) {
2306 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
2307 break;
2310 timeoutLeft = timeout - elapsed;
2314 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2316 return map_native_wait_result_to_managed (ret, numhandles);
2319 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2320 gint32
2321 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
2323 MonoW32HandleWaitRet ret;
2324 MonoInternalThread *thread = mono_thread_internal_current ();
2326 if (ms == -1)
2327 ms = MONO_INFINITE_WAIT;
2329 if (mono_thread_current_check_pending_interrupt ())
2330 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2332 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2334 ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
2336 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2338 return map_native_wait_result_to_managed (ret, 1);
2341 #endif
2343 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
2345 return mono_atomic_inc_i32 (location);
2348 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
2350 #if SIZEOF_VOID_P == 4
2351 if (G_UNLIKELY ((size_t)location & 0x7)) {
2352 gint64 ret;
2353 mono_interlocked_lock ();
2354 (*location)++;
2355 ret = *location;
2356 mono_interlocked_unlock ();
2357 return ret;
2359 #endif
2360 return mono_atomic_inc_i64 (location);
2363 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
2365 return mono_atomic_dec_i32(location);
2368 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
2370 #if SIZEOF_VOID_P == 4
2371 if (G_UNLIKELY ((size_t)location & 0x7)) {
2372 gint64 ret;
2373 mono_interlocked_lock ();
2374 (*location)--;
2375 ret = *location;
2376 mono_interlocked_unlock ();
2377 return ret;
2379 #endif
2380 return mono_atomic_dec_i64 (location);
2383 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2385 return mono_atomic_xchg_i32(location, value);
2388 void
2389 ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*res)
2391 // Coop-equivalency here via pointers to pointers.
2392 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2394 // This also handles generic T case, T constrained to a class.
2396 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2397 // presently breaks identity of location and would therefore never work.
2399 *res = (MonoObject*)mono_atomic_xchg_ptr ((volatile gpointer*)location, *value);
2400 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2403 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2405 return mono_atomic_xchg_ptr(location, value);
2408 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2410 IntFloatUnion val, ret;
2412 val.fval = value;
2413 ret.ival = mono_atomic_xchg_i32((gint32 *) location, val.ival);
2415 return ret.fval;
2418 gint64
2419 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2421 #if SIZEOF_VOID_P == 4
2422 if (G_UNLIKELY ((size_t)location & 0x7)) {
2423 gint64 ret;
2424 mono_interlocked_lock ();
2425 ret = *location;
2426 *location = value;
2427 mono_interlocked_unlock ();
2428 return ret;
2430 #endif
2431 return mono_atomic_xchg_i64 (location, value);
2434 gdouble
2435 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2437 LongDoubleUnion val, ret;
2439 val.fval = value;
2440 ret.ival = (gint64)mono_atomic_xchg_i64((gint64 *) location, val.ival);
2442 return ret.fval;
2445 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2447 return mono_atomic_cas_i32(location, value, comparand);
2450 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2452 gint32 r = mono_atomic_cas_i32(location, value, comparand);
2453 *success = r == comparand;
2454 return r;
2457 void
2458 ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject *volatile*location, MonoObject *volatile*value, MonoObject *volatile*comparand, MonoObject *volatile* res)
2460 // Coop-equivalency here via pointers to pointers.
2461 // value and comparand and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2463 // This also handles generic T case, T constrained to a class.
2465 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2466 // presently breaks identity of location and would therefore never work.
2468 *res = (MonoObject*)mono_atomic_cas_ptr ((volatile gpointer*)location, *value, *comparand);
2469 mono_gc_wbarrier_generic_nostore_internal ((gpointer)location); // FIXME volatile
2472 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2474 return mono_atomic_cas_ptr(location, value, comparand);
2477 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2479 IntFloatUnion val, ret, cmp;
2481 val.fval = value;
2482 cmp.fval = comparand;
2483 ret.ival = mono_atomic_cas_i32((gint32 *) location, val.ival, cmp.ival);
2485 return ret.fval;
2488 gdouble
2489 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2491 #if SIZEOF_VOID_P == 8
2492 LongDoubleUnion val, comp, ret;
2494 val.fval = value;
2495 comp.fval = comparand;
2496 ret.ival = (gint64)mono_atomic_cas_ptr((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2498 return ret.fval;
2499 #else
2500 gdouble old;
2502 mono_interlocked_lock ();
2503 old = *location;
2504 if (old == comparand)
2505 *location = value;
2506 mono_interlocked_unlock ();
2508 return old;
2509 #endif
2512 gint64
2513 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2515 #if SIZEOF_VOID_P == 4
2516 if (G_UNLIKELY ((size_t)location & 0x7)) {
2517 gint64 old;
2518 mono_interlocked_lock ();
2519 old = *location;
2520 if (old == comparand)
2521 *location = value;
2522 mono_interlocked_unlock ();
2523 return old;
2525 #endif
2526 return mono_atomic_cas_i64 (location, value, comparand);
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_internal:
3667 void
3668 mono_thread_manage_internal (void)
3670 MONO_REQ_GC_UNSAFE_MODE;
3672 struct wait_data wait_data;
3673 struct wait_data *wait = &wait_data;
3675 memset (wait, 0, sizeof (struct wait_data));
3676 /* join each thread that's still running */
3677 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3679 mono_threads_lock ();
3680 if(threads==NULL) {
3681 THREAD_DEBUG (g_message("%s: No threads", __func__));
3682 mono_threads_unlock ();
3683 return;
3686 mono_threads_unlock ();
3688 do {
3689 mono_threads_lock ();
3690 if (shutting_down) {
3691 /* somebody else is shutting down */
3692 mono_threads_unlock ();
3693 break;
3695 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3696 mono_g_hash_table_foreach (threads, print_tids, NULL));
3698 MONO_ENTER_GC_SAFE;
3699 mono_os_event_reset (&background_change_event);
3700 MONO_EXIT_GC_SAFE;
3701 wait->num=0;
3702 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3703 memset (wait->threads, 0, sizeof (wait->threads));
3704 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3705 mono_threads_unlock ();
3706 if (wait->num > 0)
3707 /* Something to wait for */
3708 wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3709 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3710 } while(wait->num>0);
3712 /* Mono is shutting down, so just wait for the end */
3713 if (!mono_runtime_try_shutdown ()) {
3714 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3715 mono_thread_suspend (mono_thread_internal_current ());
3716 mono_thread_execute_interruption_void ();
3719 #ifndef ENABLE_NETCORE
3721 * Under netcore, we don't abort any threads, just exit.
3722 * This is not a problem since we don't do runtime cleanup either.
3725 * Remove everything but the finalizer thread and self.
3726 * Also abort all the background threads
3727 * */
3728 do {
3729 mono_threads_lock ();
3731 wait->num = 0;
3732 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3733 memset (wait->threads, 0, sizeof (wait->threads));
3734 mono_g_hash_table_foreach (threads, abort_threads, wait);
3736 mono_threads_unlock ();
3738 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3739 if (wait->num > 0) {
3740 /* Something to wait for */
3741 wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3743 } while (wait->num > 0);
3744 #endif
3747 * give the subthreads a chance to really quit (this is mainly needed
3748 * to get correct user and system times from getrusage/wait/time(1)).
3749 * This could be removed if we avoid pthread_detach() and use pthread_join().
3751 mono_thread_info_yield ();
3754 #ifndef ENABLE_NETCORE
3755 static void
3756 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3758 MonoInternalThread *thread = (MonoInternalThread*)value;
3759 struct wait_data *wait = (struct wait_data*)user_data;
3762 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3763 * limitation.
3764 * This needs no locking.
3766 if ((thread->state & ThreadState_Suspended) != 0 ||
3767 (thread->state & ThreadState_Stopped) != 0)
3768 return;
3770 if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3771 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3772 wait->threads [wait->num] = thread;
3773 wait->num++;
3778 * mono_thread_suspend_all_other_threads:
3780 * Suspend all managed threads except the finalizer thread and this thread. It is
3781 * not possible to resume them later.
3783 void mono_thread_suspend_all_other_threads (void)
3785 struct wait_data wait_data;
3786 struct wait_data *wait = &wait_data;
3787 int i;
3788 MonoNativeThreadId self = mono_native_thread_id_get ();
3789 guint32 eventidx = 0;
3790 gboolean starting, finished;
3792 memset (wait, 0, sizeof (struct wait_data));
3794 * The other threads could be in an arbitrary state at this point, i.e.
3795 * they could be starting up, shutting down etc. This means that there could be
3796 * threads which are not even in the threads hash table yet.
3800 * First we set a barrier which will be checked by all threads before they
3801 * are added to the threads hash table, and they will exit if the flag is set.
3802 * This ensures that no threads could be added to the hash later.
3803 * We will use shutting_down as the barrier for now.
3805 g_assert (shutting_down);
3808 * We make multiple calls to WaitForMultipleObjects since:
3809 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3810 * - some threads could exit without becoming suspended
3812 finished = FALSE;
3813 while (!finished) {
3815 * Make a copy of the hashtable since we can't do anything with
3816 * threads while threads_mutex is held.
3818 wait->num = 0;
3819 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3820 memset (wait->threads, 0, sizeof (wait->threads));
3821 mono_threads_lock ();
3822 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3823 mono_threads_unlock ();
3825 eventidx = 0;
3826 /* Get the suspended events that we'll be waiting for */
3827 for (i = 0; i < wait->num; ++i) {
3828 MonoInternalThread *thread = wait->threads [i];
3830 if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3831 || mono_gc_is_finalizer_internal_thread (thread)
3832 || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3834 mono_threads_close_thread_handle (wait->handles [i]);
3835 wait->threads [i] = NULL;
3836 continue;
3839 LOCK_THREAD (thread);
3841 if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3842 UNLOCK_THREAD (thread);
3843 mono_threads_close_thread_handle (wait->handles [i]);
3844 wait->threads [i] = NULL;
3845 continue;
3848 ++eventidx;
3850 /* Convert abort requests into suspend requests */
3851 if ((thread->state & ThreadState_AbortRequested) != 0)
3852 thread->state &= ~ThreadState_AbortRequested;
3854 thread->state |= ThreadState_SuspendRequested;
3855 MONO_ENTER_GC_SAFE;
3856 mono_os_event_reset (thread->suspended);
3857 MONO_EXIT_GC_SAFE;
3859 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3860 async_suspend_internal (thread, TRUE);
3862 mono_threads_close_thread_handle (wait->handles [i]);
3863 wait->threads [i] = NULL;
3865 if (eventidx <= 0) {
3867 * If there are threads which are starting up, we wait until they
3868 * are suspended when they try to register in the threads hash.
3869 * This is guaranteed to finish, since the threads which can create new
3870 * threads get suspended after a while.
3871 * FIXME: The finalizer thread can still create new threads.
3873 mono_threads_lock ();
3874 if (threads_starting_up)
3875 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3876 else
3877 starting = FALSE;
3878 mono_threads_unlock ();
3879 if (starting)
3880 mono_thread_info_sleep (100, NULL);
3881 else
3882 finished = TRUE;
3886 #endif
3888 typedef struct {
3889 MonoInternalThread *thread;
3890 MonoStackFrameInfo *frames;
3891 int nframes, max_frames;
3892 int nthreads, max_threads;
3893 MonoInternalThread **threads;
3894 } ThreadDumpUserData;
3896 static gboolean thread_dump_requested;
3898 /* This needs to be async safe */
3899 static gboolean
3900 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3902 ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3904 if (ud->nframes < ud->max_frames) {
3905 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3906 ud->nframes ++;
3909 return FALSE;
3912 /* This needs to be async safe */
3913 static SuspendThreadResult
3914 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3916 ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3917 MonoInternalThread *thread = user_data->thread;
3919 #if 0
3920 /* This no longer works with remote unwinding */
3921 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3922 mono_thread_internal_describe (thread, text);
3923 g_string_append (text, "\n");
3924 #endif
3926 if (thread == mono_thread_internal_current ())
3927 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3928 else
3929 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3931 return MonoResumeThread;
3934 typedef struct {
3935 int nthreads, max_threads;
3937 guint32 *threads;
3938 } CollectThreadsUserData;
3940 typedef struct {
3941 int nthreads, max_threads;
3942 MonoNativeThreadId *threads;
3943 } CollectThreadIdsUserData;
3945 static void
3946 collect_thread (gpointer key, gpointer value, gpointer user)
3948 CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3949 MonoInternalThread *thread = (MonoInternalThread *)value;
3951 if (ud->nthreads < ud->max_threads)
3952 ud->threads [ud->nthreads ++] = mono_gchandle_new_internal (&thread->obj, TRUE);
3956 * Collect running threads into the THREADS array.
3957 * THREADS should be an array allocated on the stack.
3959 static int
3960 collect_threads (guint32 *thread_handles, int max_threads)
3962 CollectThreadsUserData ud;
3964 mono_memory_barrier ();
3965 if (!threads)
3966 return 0;
3968 memset (&ud, 0, sizeof (ud));
3969 /* This array contains refs, but its on the stack, so its ok */
3970 ud.threads = thread_handles;
3971 ud.max_threads = max_threads;
3973 mono_threads_lock ();
3974 mono_g_hash_table_foreach (threads, collect_thread, &ud);
3975 mono_threads_unlock ();
3977 return ud.nthreads;
3980 void
3981 mono_gstring_append_thread_name (GString* text, MonoInternalThread* thread)
3983 g_string_append (text, "\n\"");
3984 char const * const name = thread->name.chars;
3985 g_string_append (text, name ? name :
3986 thread->threadpool_thread ? "<threadpool thread>" :
3987 "<unnamed thread>");
3988 g_string_append (text, "\"");
3991 static void
3992 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud, FILE* output_file)
3994 GString* text = g_string_new (0);
3995 int i;
3997 ud->thread = thread;
3998 ud->nframes = 0;
4000 /* Collect frames for the thread */
4001 if (thread == mono_thread_internal_current ()) {
4002 get_thread_dump (mono_thread_info_current (), ud);
4003 } else {
4004 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
4008 * Do all the non async-safe work outside of get_thread_dump.
4010 mono_gstring_append_thread_name (text, thread);
4012 for (i = 0; i < ud->nframes; ++i) {
4013 MonoStackFrameInfo *frame = &ud->frames [i];
4014 MonoMethod *method = NULL;
4016 if (frame->type == FRAME_TYPE_MANAGED)
4017 method = mono_jit_info_get_method (frame->ji);
4019 if (method) {
4020 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
4021 g_string_append_printf (text, " %s\n", location);
4022 g_free (location);
4023 } else {
4024 g_string_append_printf (text, " at <unknown> <0x%05x>\n", frame->native_offset);
4028 g_fprintf (output_file, "%s", text->str);
4030 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
4031 OutputDebugStringA(text->str);
4032 #endif
4034 g_string_free (text, TRUE);
4035 fflush (output_file);
4038 static void
4039 mono_get_time_of_day (struct timeval *tv) {
4040 #ifdef WIN32
4041 struct _timeb time;
4042 _ftime(&time);
4043 tv->tv_sec = time.time;
4044 tv->tv_usec = time.millitm * 1000;
4045 #else
4046 if (gettimeofday (tv, NULL) == -1) {
4047 g_error ("gettimeofday() failed; errno is %d (%s)", errno, strerror (errno));
4049 #endif
4052 static void
4053 mono_local_time (const struct timeval *tv, struct tm *tm) {
4054 #ifdef HAVE_LOCALTIME_R
4055 localtime_r(&tv->tv_sec, tm);
4056 #else
4057 time_t const tv_sec = tv->tv_sec; // Copy due to Win32/Posix contradiction.
4058 *tm = *localtime (&tv_sec);
4059 #endif
4062 void
4063 mono_threads_perform_thread_dump (void)
4065 FILE* output_file = NULL;
4066 ThreadDumpUserData ud;
4067 guint32 thread_array [128];
4068 int tindex, nthreads;
4070 if (!thread_dump_requested)
4071 return;
4073 if (thread_dump_dir != NULL) {
4074 GString* path = g_string_new (0);
4075 char time_str[80];
4076 struct timeval tv;
4077 long ms;
4078 struct tm tod;
4079 mono_get_time_of_day (&tv);
4080 mono_local_time(&tv, &tod);
4081 strftime(time_str, sizeof(time_str), MONO_STRFTIME_F "_" MONO_STRFTIME_T, &tod);
4082 ms = tv.tv_usec / 1000;
4083 g_string_append_printf (path, "%s/%s.%03ld.tdump", thread_dump_dir, time_str, ms);
4084 output_file = fopen (path->str, "w");
4085 g_string_free (path, TRUE);
4087 if (output_file == NULL) {
4088 g_print ("Full thread dump:\n");
4091 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4092 nthreads = collect_threads (thread_array, 128);
4094 memset (&ud, 0, sizeof (ud));
4095 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4096 ud.max_frames = 256;
4098 for (tindex = 0; tindex < nthreads; ++tindex) {
4099 guint32 handle = thread_array [tindex];
4100 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4101 dump_thread (thread, &ud, output_file != NULL ? output_file : stdout);
4102 mono_gchandle_free_internal (handle);
4105 if (output_file != NULL) {
4106 fclose (output_file);
4108 g_free (ud.frames);
4110 thread_dump_requested = FALSE;
4113 #ifndef ENABLE_NETCORE
4114 /* Obtain the thread dump of all threads */
4115 void
4116 ves_icall_System_Threading_Thread_GetStackTraces (MonoArrayHandleOut out_threads_handle, MonoArrayHandleOut out_stack_frames_handle, MonoError *error)
4118 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4119 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4121 guint32 handle = 0;
4123 MonoStackFrameHandle stack_frame_handle = MONO_HANDLE_NEW (MonoStackFrame, NULL);
4124 MonoReflectionMethodHandle reflection_method_handle = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
4125 MonoStringHandle filename_handle = MONO_HANDLE_NEW (MonoString, NULL);
4126 MonoArrayHandle thread_frames_handle = MONO_HANDLE_NEW (MonoArray, NULL);
4128 ThreadDumpUserData ud;
4129 guint32 thread_array [128];
4130 MonoDomain *domain = mono_domain_get ();
4131 MonoDebugSourceLocation *location;
4132 int tindex, nthreads;
4134 MonoArray* out_threads = NULL;
4135 MonoArray* out_stack_frames = NULL;
4137 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, NULL);
4138 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, NULL);
4140 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4141 nthreads = collect_threads (thread_array, 128);
4143 memset (&ud, 0, sizeof (ud));
4144 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4145 ud.max_frames = 256;
4147 out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
4148 goto_if_nok (error, leave);
4149 MONO_HANDLE_ASSIGN_RAW (out_threads_handle, out_threads);
4150 out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
4151 goto_if_nok (error, leave);
4152 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle, out_stack_frames);
4154 for (tindex = 0; tindex < nthreads; ++tindex) {
4156 mono_gchandle_free_internal (handle);
4157 handle = thread_array [tindex];
4158 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4160 MonoArray *thread_frames;
4161 int i;
4163 ud.thread = thread;
4164 ud.nframes = 0;
4166 /* Collect frames for the thread */
4167 if (thread == mono_thread_internal_current ()) {
4168 get_thread_dump (mono_thread_info_current (), &ud);
4169 } else {
4170 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
4173 mono_array_setref_fast (out_threads, tindex, mono_thread_current_for_thread (thread));
4175 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
4176 MONO_HANDLE_ASSIGN_RAW (thread_frames_handle, thread_frames);
4177 goto_if_nok (error, leave);
4178 mono_array_setref_fast (out_stack_frames, tindex, thread_frames);
4180 for (i = 0; i < ud.nframes; ++i) {
4181 MonoStackFrameInfo *frame = &ud.frames [i];
4182 MonoMethod *method = NULL;
4183 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
4184 MONO_HANDLE_ASSIGN_RAW (stack_frame_handle, sf);
4185 goto_if_nok (error, leave);
4187 sf->native_offset = frame->native_offset;
4189 if (frame->type == FRAME_TYPE_MANAGED)
4190 method = mono_jit_info_get_method (frame->ji);
4192 if (method) {
4193 sf->method_address = (gsize) frame->ji->code_start;
4195 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
4196 MONO_HANDLE_ASSIGN_RAW (reflection_method_handle, rm);
4197 goto_if_nok (error, leave);
4198 MONO_OBJECT_SETREF_INTERNAL (sf, method, rm);
4200 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
4201 if (location) {
4202 sf->il_offset = location->il_offset;
4204 if (location->source_file) {
4205 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
4206 MONO_HANDLE_ASSIGN_RAW (filename_handle, filename);
4207 goto_if_nok (error, leave);
4208 MONO_OBJECT_SETREF_INTERNAL (sf, filename, filename);
4209 sf->line = location->row;
4210 sf->column = location->column;
4212 mono_debug_free_source_location (location);
4213 } else {
4214 sf->il_offset = -1;
4217 mono_array_setref_internal (thread_frames, i, sf);
4220 mono_gchandle_free_internal (handle);
4221 handle = 0;
4224 leave:
4225 mono_gchandle_free_internal (handle);
4226 g_free (ud.frames);
4228 #endif
4231 * mono_threads_request_thread_dump:
4233 * Ask all threads except the current to print their stacktrace to stdout.
4235 void
4236 mono_threads_request_thread_dump (void)
4238 /*The new thread dump code runs out of the finalizer thread. */
4239 thread_dump_requested = TRUE;
4240 mono_gc_finalize_notify ();
4243 struct ref_stack {
4244 gpointer *refs;
4245 gint allocated; /* +1 so that refs [allocated] == NULL */
4246 gint bottom;
4249 typedef struct ref_stack RefStack;
4251 static RefStack *
4252 ref_stack_new (gint initial_size)
4254 RefStack *rs;
4256 initial_size = MAX (initial_size, 16) + 1;
4257 rs = g_new0 (RefStack, 1);
4258 rs->refs = g_new0 (gpointer, initial_size);
4259 rs->allocated = initial_size;
4260 return rs;
4263 static void
4264 ref_stack_destroy (gpointer ptr)
4266 RefStack *rs = (RefStack *)ptr;
4268 if (rs != NULL) {
4269 g_free (rs->refs);
4270 g_free (rs);
4274 static void
4275 ref_stack_push (RefStack *rs, gpointer ptr)
4277 g_assert (rs != NULL);
4279 if (rs->bottom >= rs->allocated) {
4280 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
4281 rs->allocated <<= 1;
4282 rs->refs [rs->allocated] = NULL;
4284 rs->refs [rs->bottom++] = ptr;
4287 static void
4288 ref_stack_pop (RefStack *rs)
4290 if (rs == NULL || rs->bottom == 0)
4291 return;
4293 rs->bottom--;
4294 rs->refs [rs->bottom] = NULL;
4297 static gboolean
4298 ref_stack_find (RefStack *rs, gpointer ptr)
4300 gpointer *refs;
4302 if (rs == NULL)
4303 return FALSE;
4305 for (refs = rs->refs; refs && *refs; refs++) {
4306 if (*refs == ptr)
4307 return TRUE;
4309 return FALSE;
4313 * mono_thread_push_appdomain_ref:
4315 * Register that the current thread may have references to objects in domain
4316 * @domain on its stack. Each call to this function should be paired with a
4317 * call to pop_appdomain_ref.
4319 void
4320 mono_thread_push_appdomain_ref (MonoDomain *domain)
4322 MonoInternalThread *thread = mono_thread_internal_current ();
4324 if (thread) {
4325 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4326 SPIN_LOCK (thread->lock_thread_id);
4327 if (thread->appdomain_refs == NULL)
4328 thread->appdomain_refs = ref_stack_new (16);
4329 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
4330 SPIN_UNLOCK (thread->lock_thread_id);
4334 void
4335 mono_thread_pop_appdomain_ref (void)
4337 MonoInternalThread *thread = mono_thread_internal_current ();
4339 if (thread) {
4340 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4341 SPIN_LOCK (thread->lock_thread_id);
4342 ref_stack_pop ((RefStack *)thread->appdomain_refs);
4343 SPIN_UNLOCK (thread->lock_thread_id);
4347 gboolean
4348 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
4350 gboolean res;
4351 SPIN_LOCK (thread->lock_thread_id);
4352 res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
4353 SPIN_UNLOCK (thread->lock_thread_id);
4354 return res;
4357 gboolean
4358 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
4360 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
4363 typedef struct abort_appdomain_data {
4364 struct wait_data wait;
4365 MonoDomain *domain;
4366 } abort_appdomain_data;
4368 static void
4369 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
4371 MonoInternalThread *thread = (MonoInternalThread*)value;
4372 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
4373 MonoDomain *domain = data->domain;
4375 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
4376 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4378 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
4379 data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
4380 data->wait.threads [data->wait.num] = thread;
4381 data->wait.num++;
4382 } else {
4383 /* Just ignore the rest, we can't do anything with
4384 * them yet
4391 * mono_threads_abort_appdomain_threads:
4393 * Abort threads which has references to the given appdomain.
4395 gboolean
4396 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
4398 abort_appdomain_data user_data;
4399 gint64 start_time;
4400 int orig_timeout = timeout;
4401 int i;
4403 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
4405 start_time = mono_msec_ticks ();
4406 do {
4407 mono_threads_lock ();
4409 user_data.domain = domain;
4410 user_data.wait.num = 0;
4411 /* This shouldn't take any locks */
4412 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
4413 mono_threads_unlock ();
4415 if (user_data.wait.num > 0) {
4416 /* Abort the threads outside the threads lock */
4417 for (i = 0; i < user_data.wait.num; ++i)
4418 mono_thread_internal_abort (user_data.wait.threads [i], TRUE);
4421 * We should wait for the threads either to abort, or to leave the
4422 * domain. We can't do the latter, so we wait with a timeout.
4424 wait_for_tids (&user_data.wait, 100, FALSE);
4427 /* Update remaining time */
4428 timeout -= mono_msec_ticks () - start_time;
4429 start_time = mono_msec_ticks ();
4431 if (orig_timeout != -1 && timeout < 0)
4432 return FALSE;
4434 while (user_data.wait.num > 0);
4436 THREAD_DEBUG (g_message ("%s: abort done", __func__));
4438 return TRUE;
4441 /* This is a JIT icall. This icall is called from a finally block when
4442 * mono_install_handler_block_guard called by another thread has flipped the
4443 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4444 * the finally is in an abort protected block, we must defer the abort
4445 * exception until we leave the abort protected block. Otherwise we proceed
4446 * with a synchronous self-abort.
4448 void
4449 ves_icall_thread_finish_async_abort (void)
4451 /* We were called from the handler block and are about to
4452 * leave it. (If we end up postponing the abort because we're
4453 * in an abort protected block, the unwinder won't run and
4454 * won't clear the handler block itself which will confuse the
4455 * unwinder if we're in a try {} catch {} and we throw again.
4456 * ie, this:
4457 * static Constructor () {
4458 * try {
4459 * try {
4460 * } finally {
4461 * icall (); // Thread.Abort landed here,
4462 * // and caused the handler block to be installed
4463 * if (exvar)
4464 * ves_icall_thread_finish_async_abort (); // we're here
4466 * throw E ();
4467 * } catch (E) {
4468 * // unwinder will get confused here and synthesize a self abort
4472 * More interestingly, this doesn't only happen with icalls - a JIT
4473 * trampoline is native code that will cause a handler to be installed.
4474 * So the above situation can happen with any code in a "finally"
4475 * clause.
4477 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4478 /* Just set the async interruption requested bit. Rely on the icall
4479 * wrapper of this icall to process the thread interruption, respecting
4480 * any abort protection blocks in our call stack.
4482 mono_thread_set_self_interruption_respect_abort_prot ();
4486 * mono_thread_get_undeniable_exception:
4488 * Return an exception which needs to be raised when leaving a catch clause.
4489 * This is used for undeniable exception propagation.
4491 MonoException*
4492 mono_thread_get_undeniable_exception (void)
4494 MonoInternalThread *thread = mono_thread_internal_current ();
4496 if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
4497 return NULL;
4499 // We don't want to have our exception effect calls made by
4500 // the catching block
4502 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4503 return NULL;
4506 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4507 * exception if the thread no longer references a dying appdomain.
4509 thread->abort_exc->trace_ips = NULL;
4510 thread->abort_exc->stack_trace = NULL;
4511 return thread->abort_exc;
4514 #if MONO_SMALL_CONFIG
4515 #define NUM_STATIC_DATA_IDX 4
4516 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4517 64, 256, 1024, 4096
4519 #else
4520 #define NUM_STATIC_DATA_IDX 8
4521 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4522 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4524 #endif
4526 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
4527 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
4529 static void
4530 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
4532 gpointer *static_data = (gpointer *)addr;
4534 for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4535 void **ptr = (void **)static_data [i];
4537 if (!ptr)
4538 continue;
4540 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4541 void **p = ptr + idx;
4543 if (*p)
4544 mark_func ((MonoObject**)p, gc_data);
4549 static void
4550 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4552 mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4555 static void
4556 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4558 mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4562 * mono_alloc_static_data
4564 * Allocate memory blocks for storing threads or context static data
4566 static void
4567 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal)
4569 guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4570 int i;
4572 gpointer* static_data = *static_data_ptr;
4573 if (!static_data) {
4574 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4575 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4577 if (mono_gc_user_markers_supported ()) {
4578 if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4579 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4581 if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4582 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4585 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4586 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4587 alloc_key,
4588 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4589 *static_data_ptr = static_data;
4590 static_data [0] = static_data;
4593 for (i = 1; i <= idx; ++i) {
4594 if (static_data [i])
4595 continue;
4597 if (mono_gc_user_markers_supported ())
4598 static_data [i] = g_malloc0 (static_data_size [i]);
4599 else
4600 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4601 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4602 alloc_key,
4603 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4607 static void
4608 mono_free_static_data (gpointer* static_data)
4610 int i;
4611 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4612 gpointer p = static_data [i];
4613 if (!p)
4614 continue;
4616 * At this point, the static data pointer array is still registered with the
4617 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4618 * data. Freeing the individual arrays without first nulling their slots
4619 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4620 * such an already freed array. See bug #13813.
4622 static_data [i] = NULL;
4623 mono_memory_write_barrier ();
4624 if (mono_gc_user_markers_supported ())
4625 g_free (p);
4626 else
4627 mono_gc_free_fixed (p);
4629 mono_gc_free_fixed (static_data);
4633 * mono_init_static_data_info
4635 * Initializes static data counters
4637 static void mono_init_static_data_info (StaticDataInfo *static_data)
4639 static_data->idx = 0;
4640 static_data->offset = 0;
4641 static_data->freelist = NULL;
4645 * mono_alloc_static_data_slot
4647 * Generates an offset for static data. static_data contains the counters
4648 * used to generate it.
4650 static guint32
4651 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4653 if (!static_data->idx && !static_data->offset) {
4655 * we use the first chunk of the first allocation also as
4656 * an array for the rest of the data
4658 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4660 static_data->offset += align - 1;
4661 static_data->offset &= ~(align - 1);
4662 if (static_data->offset + size >= static_data_size [static_data->idx]) {
4663 static_data->idx ++;
4664 g_assert (size <= static_data_size [static_data->idx]);
4665 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4666 static_data->offset = 0;
4668 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4669 static_data->offset += size;
4670 return offset;
4674 * LOCKING: requires that threads_mutex is held
4676 static void
4677 context_adjust_static_data (MonoAppContextHandle ctx_handle)
4679 MonoAppContext *ctx = MONO_HANDLE_RAW (ctx_handle);
4680 if (context_static_info.offset || context_static_info.idx > 0) {
4681 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4682 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4683 ctx->data->static_data = ctx->static_data;
4688 * LOCKING: requires that threads_mutex is held
4690 static void
4691 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4693 MonoInternalThread *thread = (MonoInternalThread *)value;
4694 guint32 offset = GPOINTER_TO_UINT (user);
4696 mono_alloc_static_data (&(thread->static_data), offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid), TRUE);
4700 * LOCKING: requires that threads_mutex is held
4702 static void
4703 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4705 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4707 if (!ctx)
4708 return;
4710 guint32 offset = GPOINTER_TO_UINT (user);
4711 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4712 ctx->data->static_data = ctx->static_data;
4715 static StaticDataFreeList*
4716 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
4718 StaticDataFreeList* prev = NULL;
4719 StaticDataFreeList* tmp = static_data->freelist;
4720 while (tmp) {
4721 if (tmp->size == size) {
4722 if (prev)
4723 prev->next = tmp->next;
4724 else
4725 static_data->freelist = tmp->next;
4726 return tmp;
4728 prev = tmp;
4729 tmp = tmp->next;
4731 return NULL;
4734 #if SIZEOF_VOID_P == 4
4735 #define ONE_P 1
4736 #else
4737 #define ONE_P 1ll
4738 #endif
4740 static void
4741 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4743 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4744 if (!sets [idx])
4745 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4746 MonoBitSet *rb = sets [idx];
4747 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4748 offset /= sizeof (uintptr_t);
4749 /* offset is now the bitmap offset */
4750 for (int i = 0; i < numbits; ++i) {
4751 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4752 mono_bitset_set_fast (rb, offset + i);
4756 static void
4757 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4759 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4760 MonoBitSet *rb = sets [idx];
4761 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4762 offset /= sizeof (uintptr_t);
4763 /* offset is now the bitmap offset */
4764 for (int i = 0; i < size / sizeof (uintptr_t); i++)
4765 mono_bitset_clear_fast (rb, offset + i);
4768 guint32
4769 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4771 g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4773 StaticDataInfo *info;
4774 MonoBitSet **sets;
4776 if (static_type == SPECIAL_STATIC_THREAD) {
4777 info = &thread_static_info;
4778 sets = thread_reference_bitmaps;
4779 } else {
4780 info = &context_static_info;
4781 sets = context_reference_bitmaps;
4784 mono_threads_lock ();
4786 StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4787 guint32 offset;
4789 if (item) {
4790 offset = item->offset;
4791 g_free (item);
4792 } else {
4793 offset = mono_alloc_static_data_slot (info, size, align);
4796 update_reference_bitmap (sets, offset, bitmap, numbits);
4798 if (static_type == SPECIAL_STATIC_THREAD) {
4799 /* This can be called during startup */
4800 if (threads != NULL)
4801 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4802 } else {
4803 if (contexts != NULL)
4804 g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4806 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4809 mono_threads_unlock ();
4811 return offset;
4814 gpointer
4815 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4817 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4819 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4820 return get_thread_static_data (thread, offset);
4821 } else {
4822 return get_context_static_data (thread->current_appcontext, offset);
4826 gpointer
4827 mono_get_special_static_data (guint32 offset)
4829 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4832 typedef struct {
4833 guint32 offset;
4834 guint32 size;
4835 } OffsetSize;
4838 * LOCKING: requires that threads_mutex is held
4840 static void
4841 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4843 MonoInternalThread *thread = (MonoInternalThread *)value;
4844 OffsetSize *data = (OffsetSize *)user;
4845 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4846 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4847 char *ptr;
4849 if (!thread->static_data || !thread->static_data [idx])
4850 return;
4851 ptr = ((char*) thread->static_data [idx]) + off;
4852 mono_gc_bzero_atomic (ptr, data->size);
4856 * LOCKING: requires that threads_mutex is held
4858 static void
4859 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4861 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4863 if (!ctx)
4864 return;
4866 OffsetSize *data = (OffsetSize *)user;
4867 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4868 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4869 char *ptr;
4871 if (!ctx->static_data || !ctx->static_data [idx])
4872 return;
4874 ptr = ((char*) ctx->static_data [idx]) + off;
4875 mono_gc_bzero_atomic (ptr, data->size);
4878 static void
4879 do_free_special_slot (guint32 offset, guint32 size)
4881 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4882 MonoBitSet **sets;
4883 StaticDataInfo *info;
4885 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4886 info = &thread_static_info;
4887 sets = thread_reference_bitmaps;
4888 } else {
4889 info = &context_static_info;
4890 sets = context_reference_bitmaps;
4893 guint32 data_offset = offset;
4894 ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4895 OffsetSize data = { data_offset, size };
4897 clear_reference_bitmap (sets, data.offset, data.size);
4899 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4900 if (threads != NULL)
4901 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4902 } else {
4903 if (contexts != NULL)
4904 g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4907 if (!mono_runtime_is_shutting_down ()) {
4908 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4910 item->offset = offset;
4911 item->size = size;
4913 item->next = info->freelist;
4914 info->freelist = item;
4918 static void
4919 do_free_special (gpointer key, gpointer value, gpointer data)
4921 MonoClassField *field = (MonoClassField *)key;
4922 guint32 offset = GPOINTER_TO_UINT (value);
4923 gint32 align;
4924 guint32 size;
4925 size = mono_type_size (field->type, &align);
4926 do_free_special_slot (offset, size);
4929 void
4930 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4932 mono_threads_lock ();
4934 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4936 mono_threads_unlock ();
4939 #ifdef HOST_WIN32
4940 static void
4941 flush_thread_interrupt_queue (void)
4943 /* Consume pending APC calls for current thread.*/
4944 /* Since this function get's called from interrupt handler it must use a direct */
4945 /* Win32 API call and can't go through mono_coop_win32_wait_for_single_object_ex */
4946 /* or it will detect a pending interrupt and not entering the wait call needed */
4947 /* to consume pending APC's.*/
4948 MONO_ENTER_GC_SAFE;
4949 WaitForSingleObjectEx (GetCurrentThread (), 0, TRUE);
4950 MONO_EXIT_GC_SAFE;
4952 #else
4953 static void
4954 flush_thread_interrupt_queue (void)
4957 #endif
4960 * mono_thread_execute_interruption
4962 * Performs the operation that the requested thread state requires (abort,
4963 * suspend or stop)
4965 static gboolean
4966 mono_thread_execute_interruption (MonoExceptionHandle *pexc)
4968 gboolean fexc = FALSE;
4970 // Optimize away frame if caller supplied one.
4971 if (!pexc) {
4972 HANDLE_FUNCTION_ENTER ();
4973 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4974 fexc = mono_thread_execute_interruption (&exc);
4975 HANDLE_FUNCTION_RETURN_VAL (fexc);
4978 MONO_REQ_GC_UNSAFE_MODE;
4980 MonoInternalThreadHandle thread = mono_thread_internal_current_handle ();
4981 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4983 lock_thread_handle (thread);
4984 gboolean unlock = TRUE;
4986 /* MonoThread::interruption_requested can only be changed with atomics */
4987 if (!mono_thread_clear_interruption_requested_handle (thread))
4988 goto exit;
4990 MonoThreadObjectHandle sys_thread;
4991 sys_thread = mono_thread_current_handle ();
4993 flush_thread_interrupt_queue ();
4995 /* Clear the interrupted flag of the thread so it can wait again */
4996 mono_thread_info_clear_self_interrupt ();
4998 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4999 MONO_HANDLE_GET (exc, sys_thread, pending_exception);
5000 if (!MONO_HANDLE_IS_NULL (exc)) {
5001 // sys_thread->pending_exception = NULL;
5002 MONO_HANDLE_SETRAW (sys_thread, pending_exception, NULL);
5003 fexc = TRUE;
5004 goto exit;
5005 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_AbortRequested) {
5006 // Does the thread already have an abort exception?
5007 // If not, create a new one and set it on demand.
5008 // exc = thread->abort_exc;
5009 MONO_HANDLE_GET (exc, thread, abort_exc);
5010 if (MONO_HANDLE_IS_NULL (exc)) {
5011 ERROR_DECL (error);
5012 exc = mono_exception_new_thread_abort (error);
5013 mono_error_assert_ok (error); // FIXME
5014 // thread->abort_exc = exc;
5015 MONO_HANDLE_SET (thread, abort_exc, exc);
5017 fexc = TRUE;
5018 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_SuspendRequested) {
5019 /* calls UNLOCK_THREAD (thread) */
5020 self_suspend_internal ();
5021 unlock = FALSE;
5022 } else if (MONO_HANDLE_GETVAL (thread, thread_interrupt_requested)) {
5023 // thread->thread_interrupt_requested = FALSE
5024 MONO_HANDLE_SETVAL (thread, thread_interrupt_requested, MonoBoolean, FALSE);
5025 unlock_thread_handle (thread);
5026 unlock = FALSE;
5027 ERROR_DECL (error);
5028 exc = mono_exception_new_thread_interrupted (error);
5029 mono_error_assert_ok (error); // FIXME
5030 fexc = TRUE;
5032 exit:
5033 if (unlock)
5034 unlock_thread_handle (thread);
5036 if (fexc)
5037 MONO_HANDLE_ASSIGN (*pexc, exc);
5039 return fexc;
5042 static void
5043 mono_thread_execute_interruption_void (void)
5045 (void)mono_thread_execute_interruption (NULL);
5048 static MonoException*
5049 mono_thread_execute_interruption_ptr (void)
5051 HANDLE_FUNCTION_ENTER ();
5052 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5053 MonoException * const exc_raw = mono_thread_execute_interruption (&exc) ? MONO_HANDLE_RAW (exc) : NULL;
5054 HANDLE_FUNCTION_RETURN_VAL (exc_raw);
5058 * mono_thread_request_interruption_internal
5060 * A signal handler can call this method to request the interruption of a
5061 * thread. The result of the interruption will depend on the current state of
5062 * the thread. If the result is an exception that needs to be thrown, it is
5063 * provided as return value.
5065 static gboolean
5066 mono_thread_request_interruption_internal (gboolean running_managed, MonoExceptionHandle *pexc)
5068 MonoInternalThread *thread = mono_thread_internal_current ();
5070 /* The thread may already be stopping */
5071 if (thread == NULL)
5072 return FALSE;
5074 if (!mono_thread_set_interruption_requested (thread))
5075 return FALSE;
5077 if (!running_managed || is_running_protected_wrapper ()) {
5078 /* Can't stop while in unmanaged code. Increase the global interruption
5079 request count. When exiting the unmanaged method the count will be
5080 checked and the thread will be interrupted. */
5082 /* this will awake the thread if it is in WaitForSingleObject
5083 or similar */
5084 #ifdef HOST_WIN32
5085 mono_win32_interrupt_wait (thread->thread_info, thread->native_handle, (DWORD)thread->tid);
5086 #else
5087 mono_thread_info_self_interrupt ();
5088 #endif
5089 return FALSE;
5091 return mono_thread_execute_interruption (pexc);
5094 static void
5095 mono_thread_request_interruption_native (void)
5097 (void)mono_thread_request_interruption_internal (FALSE, NULL);
5100 static gboolean
5101 mono_thread_request_interruption_managed (MonoExceptionHandle *exc)
5103 return mono_thread_request_interruption_internal (TRUE, exc);
5106 /*This function should be called by a thread after it has exited all of
5107 * its handle blocks at interruption time.*/
5108 void
5109 mono_thread_resume_interruption (gboolean exec)
5111 MonoInternalThread *thread = mono_thread_internal_current ();
5112 gboolean still_aborting;
5114 /* The thread may already be stopping */
5115 if (thread == NULL)
5116 return;
5118 LOCK_THREAD (thread);
5119 still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
5120 UNLOCK_THREAD (thread);
5122 /*This can happen if the protected block called Thread::ResetAbort*/
5123 if (!still_aborting)
5124 return;
5126 if (!mono_thread_set_interruption_requested (thread))
5127 return;
5129 mono_thread_info_self_interrupt ();
5131 if (exec) // Ignore the exception here, it will be raised later.
5132 mono_thread_execute_interruption_void ();
5135 gboolean
5136 mono_thread_interruption_requested (void)
5138 if (mono_thread_interruption_request_flag) {
5139 MonoInternalThread *thread = mono_thread_internal_current ();
5140 /* The thread may already be stopping */
5141 if (thread != NULL)
5142 return mono_thread_get_interruption_requested (thread);
5144 return FALSE;
5147 static MonoException*
5148 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
5150 MonoInternalThread *thread = mono_thread_internal_current ();
5152 /* The thread may already be stopping */
5153 if (!thread)
5154 return NULL;
5155 if (!mono_thread_get_interruption_requested (thread))
5156 return NULL;
5157 if (!bypass_abort_protection && !mono_thread_current ()->pending_exception && is_running_protected_wrapper ())
5158 return NULL;
5160 return mono_thread_execute_interruption_ptr ();
5164 * Performs the interruption of the current thread, if one has been requested,
5165 * and the thread is not running a protected wrapper.
5166 * Return the exception which needs to be thrown, if any.
5168 MonoException*
5169 mono_thread_interruption_checkpoint (void)
5171 return mono_thread_interruption_checkpoint_request (FALSE);
5174 gboolean
5175 mono_thread_interruption_checkpoint_bool (void)
5177 return mono_thread_interruption_checkpoint () != NULL;
5180 void
5181 mono_thread_interruption_checkpoint_void (void)
5183 mono_thread_interruption_checkpoint ();
5187 * Performs the interruption of the current thread, if one has been requested.
5188 * Return the exception which needs to be thrown, if any.
5190 MonoException*
5191 mono_thread_force_interruption_checkpoint_noraise (void)
5193 return mono_thread_interruption_checkpoint_request (TRUE);
5197 * mono_set_pending_exception:
5199 * Set the pending exception of the current thread to EXC.
5200 * The exception will be thrown when execution returns to managed code.
5202 void
5203 mono_set_pending_exception (MonoException *exc)
5205 MonoThread *thread = mono_thread_current ();
5207 /* The thread may already be stopping */
5208 if (thread == NULL)
5209 return;
5211 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5213 mono_thread_request_interruption_native ();
5217 * mono_runtime_set_pending_exception:
5219 * Set the pending exception of the current thread to \p exc.
5220 * The exception will be thrown when execution returns to managed code.
5221 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5222 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5223 * in which case the behavior will be undefined).
5224 * Return whether the pending exception was set or not.
5225 * It will not be set if:
5226 * * The thread or runtime is stopping or shutting down
5227 * * There already is a pending exception (and \p overwrite is false)
5229 mono_bool
5230 mono_runtime_set_pending_exception (MonoException *exc, mono_bool overwrite)
5232 MonoThread *thread = mono_thread_current ();
5234 /* The thread may already be stopping */
5235 if (thread == NULL)
5236 return FALSE;
5238 /* Don't overwrite any existing pending exceptions unless asked to */
5239 if (!overwrite && thread->pending_exception)
5240 return FALSE;
5242 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5244 mono_thread_request_interruption_native ();
5246 return TRUE;
5251 * mono_set_pending_exception_handle:
5253 * Set the pending exception of the current thread to EXC.
5254 * The exception will be thrown when execution returns to managed code.
5256 MONO_COLD void
5257 mono_set_pending_exception_handle (MonoExceptionHandle exc)
5259 MonoThread *thread = mono_thread_current ();
5261 /* The thread may already be stopping */
5262 if (thread == NULL)
5263 return;
5265 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, MONO_HANDLE_RAW (exc));
5267 mono_thread_request_interruption_native ();
5270 void
5271 mono_thread_init_apartment_state (void)
5273 #ifdef HOST_WIN32
5274 MonoInternalThread* thread = mono_thread_internal_current ();
5276 /* Positive return value indicates success, either
5277 * S_OK if this is first CoInitialize call, or
5278 * S_FALSE if CoInitialize already called, but with same
5279 * threading model. A negative value indicates failure,
5280 * probably due to trying to change the threading model.
5282 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
5283 ? COINIT_APARTMENTTHREADED
5284 : COINIT_MULTITHREADED) < 0) {
5285 thread->apartment_state = ThreadApartmentState_Unknown;
5287 #endif
5290 void
5291 mono_thread_cleanup_apartment_state (void)
5293 #ifdef HOST_WIN32
5294 MonoInternalThread* thread = mono_thread_internal_current ();
5296 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
5297 CoUninitialize ();
5299 #endif
5302 static void
5303 mono_thread_notify_change_state (MonoThreadState old_state, MonoThreadState new_state)
5305 MonoThreadState diff = old_state ^ new_state;
5306 if (diff & ThreadState_Background) {
5307 /* If the thread changes the background mode, the main thread has to
5308 * be notified, since it has to rebuild the list of threads to
5309 * wait for.
5311 MONO_ENTER_GC_SAFE;
5312 mono_os_event_set (&background_change_event);
5313 MONO_EXIT_GC_SAFE;
5317 void
5318 mono_thread_clear_and_set_state (MonoInternalThread *thread, MonoThreadState clear, MonoThreadState set)
5320 LOCK_THREAD (thread);
5322 MonoThreadState const old_state = (MonoThreadState)thread->state;
5323 MonoThreadState const new_state = (old_state & ~clear) | set;
5324 thread->state = new_state;
5326 UNLOCK_THREAD (thread);
5328 mono_thread_notify_change_state (old_state, new_state);
5331 void
5332 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
5334 mono_thread_clear_and_set_state (thread, (MonoThreadState)0, state);
5338 * mono_thread_test_and_set_state:
5339 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5340 * \returns TRUE if \p set was OR'd in.
5342 gboolean
5343 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
5345 LOCK_THREAD (thread);
5347 MonoThreadState const old_state = (MonoThreadState)thread->state;
5349 if ((old_state & test) != 0) {
5350 UNLOCK_THREAD (thread);
5351 return FALSE;
5354 MonoThreadState const new_state = old_state | set;
5355 thread->state = new_state;
5357 UNLOCK_THREAD (thread);
5359 mono_thread_notify_change_state (old_state, new_state);
5361 return TRUE;
5364 void
5365 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
5367 mono_thread_clear_and_set_state (thread, state, (MonoThreadState)0);
5370 gboolean
5371 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
5373 LOCK_THREAD (thread);
5375 gboolean const ret = ((thread->state & test) != 0);
5377 UNLOCK_THREAD (thread);
5379 return ret;
5382 static void
5383 self_interrupt_thread (void *_unused)
5385 MonoException *exc;
5386 MonoThreadInfo *info;
5387 MonoContext ctx;
5389 exc = mono_thread_execute_interruption_ptr ();
5390 if (!exc) {
5391 if (mono_threads_are_safepoints_enabled ()) {
5392 /* We can return from an async call in coop, as
5393 * it's simply called when exiting the safepoint */
5394 /* If we're using hybrid suspend, we only self
5395 * interrupt if we were running, hence using
5396 * safepoints */
5397 return;
5400 g_error ("%s: we can't resume from an async call", __func__);
5403 info = mono_thread_info_current ();
5405 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5406 ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
5408 mono_raise_exception_with_context (exc, &ctx);
5411 static gboolean
5412 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
5414 if (!ji)
5415 return FALSE;
5416 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
5419 static gboolean
5420 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
5422 MonoJitInfo **dest = (MonoJitInfo **)data;
5423 *dest = frame->ji;
5424 return TRUE;
5427 static MonoJitInfo*
5428 mono_thread_info_get_last_managed (MonoThreadInfo *info)
5430 MonoJitInfo *ji = NULL;
5431 if (!info)
5432 return NULL;
5435 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5436 * any runtime locks while unwinding.
5438 mono_thread_info_set_is_async_context (TRUE);
5439 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
5440 mono_thread_info_set_is_async_context (FALSE);
5441 return ji;
5444 typedef struct {
5445 MonoInternalThread *thread;
5446 gboolean install_async_abort;
5447 MonoThreadInfoInterruptToken *interrupt_token;
5448 } AbortThreadData;
5450 static SuspendThreadResult
5451 async_abort_critical (MonoThreadInfo *info, gpointer ud)
5453 AbortThreadData *data = (AbortThreadData *)ud;
5454 MonoInternalThread *thread = data->thread;
5455 MonoJitInfo *ji = NULL;
5456 gboolean protected_wrapper;
5457 gboolean running_managed;
5459 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
5460 return MonoResumeThread;
5462 /*someone is already interrupting it*/
5463 if (!mono_thread_set_interruption_requested (thread))
5464 return MonoResumeThread;
5466 ji = mono_thread_info_get_last_managed (info);
5467 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5468 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5470 if (!protected_wrapper && running_managed) {
5471 /*We are in managed code*/
5472 /*Set the thread to call */
5473 if (data->install_async_abort)
5474 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5475 return MonoResumeThread;
5476 } else {
5478 * This will cause waits to be broken.
5479 * It will also prevent the thread from entering a wait, so if the thread returns
5480 * from the wait before it receives the abort signal, it will just spin in the wait
5481 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5482 * make it return.
5484 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
5486 return MonoResumeThread;
5490 static void
5491 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
5493 AbortThreadData data;
5495 g_assert (thread != mono_thread_internal_current ());
5497 data.thread = thread;
5498 data.install_async_abort = install_async_abort;
5499 data.interrupt_token = NULL;
5501 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
5502 if (data.interrupt_token)
5503 mono_thread_info_finish_interrupt (data.interrupt_token);
5504 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5507 static void
5508 self_abort_internal (MonoError *error)
5510 HANDLE_FUNCTION_ENTER ();
5512 error_init (error);
5514 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5515 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5518 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.
5520 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5521 if (mono_thread_request_interruption_managed (&exc))
5522 mono_error_set_exception_handle (error, exc);
5523 else
5524 mono_thread_info_self_interrupt ();
5526 HANDLE_FUNCTION_RETURN ();
5529 typedef struct {
5530 MonoInternalThread *thread;
5531 gboolean interrupt;
5532 MonoThreadInfoInterruptToken *interrupt_token;
5533 } SuspendThreadData;
5535 static SuspendThreadResult
5536 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
5538 SuspendThreadData *data = (SuspendThreadData *)ud;
5539 MonoInternalThread *thread = data->thread;
5540 MonoJitInfo *ji = NULL;
5541 gboolean protected_wrapper;
5542 gboolean running_managed;
5544 ji = mono_thread_info_get_last_managed (info);
5545 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5546 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5548 if (running_managed && !protected_wrapper) {
5549 if (mono_threads_are_safepoints_enabled ()) {
5550 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5551 return MonoResumeThread;
5552 } else {
5553 thread->state &= ~ThreadState_SuspendRequested;
5554 thread->state |= ThreadState_Suspended;
5555 return KeepSuspended;
5557 } else {
5558 mono_thread_set_interruption_requested (thread);
5559 if (data->interrupt)
5560 data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
5562 return MonoResumeThread;
5566 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5567 static void
5568 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
5570 SuspendThreadData data;
5572 g_assert (thread != mono_thread_internal_current ());
5574 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5576 thread->self_suspended = FALSE;
5578 data.thread = thread;
5579 data.interrupt = interrupt;
5580 data.interrupt_token = NULL;
5582 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
5583 if (data.interrupt_token)
5584 mono_thread_info_finish_interrupt (data.interrupt_token);
5586 UNLOCK_THREAD (thread);
5589 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5590 static void
5591 self_suspend_internal (void)
5593 MonoInternalThread *thread;
5594 MonoOSEvent *event;
5595 MonoOSEventWaitRet res;
5597 thread = mono_thread_internal_current ();
5599 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5601 thread->self_suspended = TRUE;
5603 thread->state &= ~ThreadState_SuspendRequested;
5604 thread->state |= ThreadState_Suspended;
5606 UNLOCK_THREAD (thread);
5608 event = thread->suspended;
5610 MONO_ENTER_GC_SAFE;
5611 res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
5612 g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
5613 MONO_EXIT_GC_SAFE;
5616 static void
5617 suspend_for_shutdown_async_call (gpointer unused)
5619 for (;;)
5620 mono_thread_info_yield ();
5623 static SuspendThreadResult
5624 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
5626 mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
5627 return MonoResumeThread;
5630 void
5631 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
5633 g_assert (thread != mono_thread_internal_current ());
5635 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
5639 * mono_thread_is_foreign:
5640 * \param thread the thread to query
5642 * This function allows one to determine if a thread was created by the mono runtime and has
5643 * a well defined lifecycle or it's a foreign one, created by the native environment.
5645 * \returns TRUE if \p thread was not created by the runtime.
5647 mono_bool
5648 mono_thread_is_foreign (MonoThread *thread)
5650 mono_bool result;
5651 MONO_ENTER_GC_UNSAFE;
5652 MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
5653 result = (info->runtime_thread == FALSE);
5654 MONO_EXIT_GC_UNSAFE;
5655 return result;
5658 #ifndef HOST_WIN32
5659 static void
5660 threads_native_thread_join_lock (gpointer tid, gpointer value)
5663 * Have to cast to a pointer-sized integer first, as we can't narrow
5664 * from a pointer if pthread_t is an integer smaller than a pointer.
5666 pthread_t thread = (pthread_t)(intptr_t)tid;
5667 if (thread != pthread_self ()) {
5668 MONO_ENTER_GC_SAFE;
5669 /* This shouldn't block */
5670 mono_threads_join_lock ();
5671 mono_native_thread_join (thread);
5672 mono_threads_join_unlock ();
5673 MONO_EXIT_GC_SAFE;
5676 static void
5677 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5679 pthread_t thread = (pthread_t)(intptr_t)tid;
5680 MONO_ENTER_GC_SAFE;
5681 mono_native_thread_join (thread);
5682 MONO_EXIT_GC_SAFE;
5685 static void
5686 threads_add_joinable_thread_nolock (gpointer tid)
5688 g_hash_table_insert (joinable_threads, tid, tid);
5690 #else
5691 static void
5692 threads_native_thread_join_lock (gpointer tid, gpointer value)
5694 MonoNativeThreadId thread_id = (MonoNativeThreadId)(guint64)tid;
5695 HANDLE thread_handle = (HANDLE)value;
5696 if (thread_id != GetCurrentThreadId () && thread_handle != NULL && thread_handle != INVALID_HANDLE_VALUE) {
5697 MONO_ENTER_GC_SAFE;
5698 /* This shouldn't block */
5699 mono_threads_join_lock ();
5700 mono_native_thread_join_handle (thread_handle, TRUE);
5701 mono_threads_join_unlock ();
5702 MONO_EXIT_GC_SAFE;
5706 static void
5707 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5709 HANDLE thread_handle = (HANDLE)value;
5710 MONO_ENTER_GC_SAFE;
5711 mono_native_thread_join_handle (thread_handle, TRUE);
5712 MONO_EXIT_GC_SAFE;
5715 static void
5716 threads_add_joinable_thread_nolock (gpointer tid)
5718 g_hash_table_insert (joinable_threads, tid, (gpointer)OpenThread (SYNCHRONIZE, TRUE, (MonoNativeThreadId)(guint64)tid));
5720 #endif
5722 static void
5723 threads_add_pending_joinable_thread (gpointer tid)
5725 joinable_threads_lock ();
5727 if (!pending_joinable_threads)
5728 pending_joinable_threads = g_hash_table_new (NULL, NULL);
5730 gpointer orig_key;
5731 gpointer value;
5733 if (!g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5734 g_hash_table_insert (pending_joinable_threads, tid, tid);
5735 UnlockedIncrement (&pending_joinable_thread_count);
5738 joinable_threads_unlock ();
5741 static void
5742 threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info)
5744 g_assert (mono_thread_info);
5746 if (mono_thread_info->runtime_thread) {
5747 threads_add_pending_joinable_thread ((gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info))));
5751 static void
5752 threads_remove_pending_joinable_thread_nolock (gpointer tid)
5754 gpointer orig_key;
5755 gpointer value;
5757 if (pending_joinable_threads && g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5758 g_hash_table_remove (pending_joinable_threads, tid);
5759 if (UnlockedDecrement (&pending_joinable_thread_count) == 0)
5760 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event);
5764 static gboolean
5765 threads_wait_pending_joinable_threads (uint32_t timeout)
5767 if (UnlockedRead (&pending_joinable_thread_count) > 0) {
5768 joinable_threads_lock ();
5769 if (timeout == MONO_INFINITE_WAIT) {
5770 while (UnlockedRead (&pending_joinable_thread_count) > 0)
5771 mono_coop_cond_wait (&zero_pending_joinable_thread_event, &joinable_threads_mutex);
5772 } else {
5773 gint64 start = mono_msec_ticks ();
5774 gint64 elapsed = 0;
5775 while (UnlockedRead (&pending_joinable_thread_count) > 0 && elapsed < timeout) {
5776 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event, &joinable_threads_mutex, timeout - (uint32_t)elapsed);
5777 elapsed = mono_msec_ticks () - start;
5780 joinable_threads_unlock ();
5783 return UnlockedRead (&pending_joinable_thread_count) == 0;
5786 static void
5787 threads_add_unique_joinable_thread_nolock (gpointer tid)
5789 if (!joinable_threads)
5790 joinable_threads = g_hash_table_new (NULL, NULL);
5792 gpointer orig_key;
5793 gpointer value;
5795 if (!g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5796 threads_add_joinable_thread_nolock (tid);
5797 UnlockedIncrement (&joinable_thread_count);
5801 void
5802 mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info)
5804 g_assert (thread_info);
5805 MonoThreadInfo *mono_thread_info = thread_info;
5807 if (mono_thread_info->runtime_thread) {
5808 gpointer tid = (gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info)));
5810 joinable_threads_lock ();
5812 // Add to joinable thread list, if not already included.
5813 threads_add_unique_joinable_thread_nolock (tid);
5815 // Remove thread from pending joinable list, if present.
5816 threads_remove_pending_joinable_thread_nolock (tid);
5818 joinable_threads_unlock ();
5820 mono_gc_finalize_notify ();
5824 static void
5825 threads_add_pending_native_thread_join_call_nolock (gpointer tid)
5827 if (!pending_native_thread_join_calls)
5828 pending_native_thread_join_calls = g_hash_table_new (NULL, NULL);
5830 gpointer orig_key;
5831 gpointer value;
5833 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value))
5834 g_hash_table_insert (pending_native_thread_join_calls, tid, tid);
5837 static void
5838 threads_remove_pending_native_thread_join_call_nolock (gpointer tid)
5840 if (pending_native_thread_join_calls)
5841 g_hash_table_remove (pending_native_thread_join_calls, tid);
5843 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event);
5846 static void
5847 threads_wait_pending_native_thread_join_call_nolock (gpointer tid)
5849 gpointer orig_key;
5850 gpointer value;
5852 while (g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value)) {
5853 mono_coop_cond_wait (&pending_native_thread_join_calls_event, &joinable_threads_mutex);
5858 * mono_add_joinable_thread:
5860 * Add TID to the list of joinable threads.
5861 * LOCKING: Acquires the threads lock.
5863 void
5864 mono_threads_add_joinable_thread (gpointer tid)
5867 * We cannot detach from threads because it causes problems like
5868 * 2fd16f60/r114307. So we collect them and join them when
5869 * we have time (in the finalizer thread).
5871 joinable_threads_lock ();
5872 threads_add_unique_joinable_thread_nolock (tid);
5873 joinable_threads_unlock ();
5875 mono_gc_finalize_notify ();
5879 * mono_threads_join_threads:
5881 * Join all joinable threads. This is called from the finalizer thread.
5882 * LOCKING: Acquires the threads lock.
5884 void
5885 mono_threads_join_threads (void)
5887 GHashTableIter iter;
5888 gpointer key = NULL;
5889 gpointer value = NULL;
5890 gboolean found = FALSE;
5892 /* Fastpath */
5893 if (!UnlockedRead (&joinable_thread_count))
5894 return;
5896 while (TRUE) {
5897 joinable_threads_lock ();
5898 if (found) {
5899 // Previous native thread join call completed.
5900 threads_remove_pending_native_thread_join_call_nolock (key);
5902 found = FALSE;
5903 if (g_hash_table_size (joinable_threads)) {
5904 g_hash_table_iter_init (&iter, joinable_threads);
5905 g_hash_table_iter_next (&iter, &key, (void**)&value);
5906 g_hash_table_remove (joinable_threads, key);
5907 UnlockedDecrement (&joinable_thread_count);
5908 found = TRUE;
5910 // Add to table of tid's with pending native thread join call.
5911 threads_add_pending_native_thread_join_call_nolock (key);
5913 joinable_threads_unlock ();
5914 if (found)
5915 threads_native_thread_join_lock (key, value);
5916 else
5917 break;
5922 * mono_thread_join:
5924 * Wait for thread TID to exit.
5925 * LOCKING: Acquires the threads lock.
5927 void
5928 mono_thread_join (gpointer tid)
5930 gboolean found = FALSE;
5931 gpointer orig_key;
5932 gpointer value;
5934 joinable_threads_lock ();
5935 if (!joinable_threads)
5936 joinable_threads = g_hash_table_new (NULL, NULL);
5938 if (g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5939 g_hash_table_remove (joinable_threads, tid);
5940 UnlockedDecrement (&joinable_thread_count);
5941 found = TRUE;
5943 // Add to table of tid's with pending native join call.
5944 threads_add_pending_native_thread_join_call_nolock (tid);
5947 if (!found) {
5948 // Wait for any pending native thread join call not yet completed for this tid.
5949 threads_wait_pending_native_thread_join_call_nolock (tid);
5952 joinable_threads_unlock ();
5954 if (!found)
5955 return;
5957 threads_native_thread_join_nolock (tid, value);
5959 joinable_threads_lock ();
5960 // Native thread join call completed for this tid.
5961 threads_remove_pending_native_thread_join_call_nolock (tid);
5962 joinable_threads_unlock ();
5965 void
5966 mono_thread_internal_unhandled_exception (MonoObject* exc)
5968 MonoClass *klass = exc->vtable->klass;
5969 if (is_threadabort_exception (klass)) {
5970 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5971 } else if (!is_appdomainunloaded_exception (klass)
5972 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
5973 mono_unhandled_exception_internal (exc);
5974 if (mono_environment_exitcode_get () == 1) {
5975 mono_environment_exitcode_set (255);
5976 mono_invoke_unhandled_exception_hook (exc);
5977 g_assert_not_reached ();
5983 * mono_threads_attach_coop_internal: called by native->managed wrappers
5985 * - @cookie:
5986 * - blocking mode: contains gc unsafe transition cookie
5987 * - non-blocking mode: contains random data
5988 * - @stackdata: semi-opaque struct: stackpointer and function_name
5989 * - @return: the original domain which needs to be restored, or NULL.
5991 MonoDomain*
5992 mono_threads_attach_coop_internal (MonoDomain *domain, gpointer *cookie, MonoStackData *stackdata)
5994 MonoDomain *orig;
5995 MonoThreadInfo *info;
5996 gboolean external = FALSE;
5998 orig = mono_domain_get ();
6000 if (!domain) {
6001 /* Happens when called from AOTed code which is only used in the root domain. */
6002 domain = mono_get_root_domain ();
6003 g_assert (domain);
6006 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
6007 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
6008 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
6009 * we're only responsible for making the cookie. */
6010 if (mono_threads_is_blocking_transition_enabled ())
6011 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
6013 if (!mono_thread_internal_current ()) {
6014 mono_thread_attach (domain);
6016 // #678164
6017 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
6020 if (mono_threads_is_blocking_transition_enabled ()) {
6021 if (external) {
6022 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
6023 * return the right cookie. */
6024 *cookie = mono_threads_enter_gc_unsafe_region_cookie ();
6025 } else {
6026 /* thread state (BLOCKING|RUNNING) -> RUNNING */
6027 *cookie = mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata);
6031 if (orig != domain)
6032 mono_domain_set_fast (domain, TRUE);
6034 return orig;
6038 * mono_threads_attach_coop: called by native->managed wrappers
6040 * - @dummy:
6041 * - blocking mode: contains gc unsafe transition cookie
6042 * - non-blocking mode: contains random data
6043 * - a pointer to stack, used for some checks
6044 * - @return: the original domain which needs to be restored, or NULL.
6046 gpointer
6047 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
6049 MONO_STACKDATA (stackdata);
6050 stackdata.stackpointer = dummy;
6051 return mono_threads_attach_coop_internal (domain, dummy, &stackdata);
6055 * mono_threads_detach_coop_internal: called by native->managed wrappers
6057 * - @orig: the original domain which needs to be restored, or NULL.
6058 * - @stackdata: semi-opaque struct: stackpointer and function_name
6059 * - @cookie:
6060 * - blocking mode: contains gc unsafe transition cookie
6061 * - non-blocking mode: contains random data
6063 void
6064 mono_threads_detach_coop_internal (MonoDomain *orig, gpointer cookie, MonoStackData *stackdata)
6066 MonoDomain *domain = mono_domain_get ();
6067 g_assert (domain);
6069 if (orig != domain) {
6070 if (!orig)
6071 mono_domain_unset ();
6072 else
6073 mono_domain_set_fast (orig, TRUE);
6076 if (mono_threads_is_blocking_transition_enabled ()) {
6077 /* it won't do anything if cookie is NULL
6078 * thread state RUNNING -> (RUNNING|BLOCKING) */
6079 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie, stackdata);
6084 * mono_threads_detach_coop: called by native->managed wrappers
6086 * - @orig: the original domain which needs to be restored, or NULL.
6087 * - @dummy:
6088 * - blocking mode: contains gc unsafe transition cookie
6089 * - non-blocking mode: contains random data
6090 * - a pointer to stack, used for some checks
6092 void
6093 mono_threads_detach_coop (gpointer orig, gpointer *dummy)
6095 MONO_STACKDATA (stackdata);
6096 stackdata.stackpointer = dummy;
6097 mono_threads_detach_coop_internal ((MonoDomain*)orig, *dummy, &stackdata);
6100 #if 0
6101 /* Returns TRUE if the current thread is ready to be interrupted. */
6102 gboolean
6103 mono_threads_is_ready_to_be_interrupted (void)
6105 MonoInternalThread *thread;
6107 thread = mono_thread_internal_current ();
6108 LOCK_THREAD (thread);
6109 if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
6110 UNLOCK_THREAD (thread);
6111 return FALSE;
6114 if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6115 UNLOCK_THREAD (thread);
6116 return FALSE;
6119 UNLOCK_THREAD (thread);
6120 return TRUE;
6122 #endif
6124 void
6125 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
6127 g_string_append_printf (text, ", thread handle : %p", internal->handle);
6129 if (internal->thread_info) {
6130 g_string_append (text, ", state : ");
6131 mono_thread_info_describe_interrupt_token (internal->thread_info, text);
6134 if (internal->owned_mutexes) {
6135 int i;
6137 g_string_append (text, ", owns : [");
6138 for (i = 0; i < internal->owned_mutexes->len; i++)
6139 g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
6140 g_string_append (text, "]");
6144 gboolean
6145 mono_thread_internal_is_current (MonoInternalThread *internal)
6147 g_assert (internal);
6148 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
6151 void
6152 mono_set_thread_dump_dir (gchar* dir) {
6153 thread_dump_dir = dir;
6156 #ifdef DISABLE_CRASH_REPORTING
6157 void
6158 mono_threads_summarize_init (void)
6162 gboolean
6163 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6165 return FALSE;
6168 gboolean
6169 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6171 return FALSE;
6174 #else
6176 static gboolean
6177 mono_threads_summarize_native_self (MonoThreadSummary *out, MonoContext *ctx)
6179 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6180 return FALSE;
6182 memset (out, 0, sizeof (MonoThreadSummary));
6183 out->ctx = ctx;
6185 MonoNativeThreadId current = mono_native_thread_id_get();
6186 out->native_thread_id = (intptr_t) current;
6188 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out);
6190 mono_native_thread_get_name (current, out->name, MONO_MAX_SUMMARY_NAME_LEN);
6192 return TRUE;
6195 // Not safe to call from signal handler
6196 gboolean
6197 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6199 gboolean success = mono_threads_summarize_native_self (out, ctx);
6201 // Finish this on the same thread
6203 if (success && mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6204 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out);
6206 return success;
6209 #define MAX_NUM_THREADS 128
6210 typedef struct {
6211 gint32 has_owner; // state of this memory
6213 MonoSemType update; // notify of addition of threads
6215 int nthreads;
6216 MonoNativeThreadId thread_array [MAX_NUM_THREADS]; // ids of threads we're dumping
6218 int nthreads_attached; // Number of threads self-registered
6219 MonoThreadSummary *all_threads [MAX_NUM_THREADS];
6221 gboolean silent; // print to stdout
6222 } SummarizerGlobalState;
6224 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && defined(HAVE_EXECVE) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6225 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6226 #endif
6228 static void
6229 summarizer_supervisor_init (void);
6231 typedef struct {
6232 MonoSemType supervisor;
6233 pid_t pid;
6234 pid_t supervisor_pid;
6235 } SummarizerSupervisorState;
6237 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6239 void
6240 summarizer_supervisor_init (void)
6242 return;
6245 static pid_t
6246 summarizer_supervisor_start (SummarizerSupervisorState *state)
6248 // nonzero, so caller doesn't think it's the supervisor
6249 return (pid_t) 1;
6252 static void
6253 summarizer_supervisor_end (SummarizerSupervisorState *state)
6255 return;
6258 #else
6259 static const char *hang_watchdog_path;
6261 void
6262 summarizer_supervisor_init (void)
6264 hang_watchdog_path = g_build_filename (mono_get_config_dir (), "..", "bin", "mono-hang-watchdog", NULL);
6265 g_assert (hang_watchdog_path);
6268 static pid_t
6269 summarizer_supervisor_start (SummarizerSupervisorState *state)
6271 memset (state, 0, sizeof (*state));
6272 pid_t pid;
6274 state->pid = getpid();
6277 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6278 * it will deadlock. Call the syscall directly instead.
6280 #if defined(HOST_ANDROID)
6281 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6282 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6283 g_assert_not_reached ();
6284 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6285 pid = (pid_t) syscall (SYS_fork);
6286 #elif HAVE_FORK
6287 pid = (pid_t) fork ();
6288 #else
6289 g_assert_not_reached ();
6290 #endif
6292 if (pid != 0)
6293 state->supervisor_pid = pid;
6294 else {
6295 char pid_str[20]; // pid is a uint64_t, 20 digits max in decimal form
6296 sprintf (pid_str, "%llu", (uint64_t)state->pid);
6297 const char *const args[] = { hang_watchdog_path, pid_str, NULL };
6298 execve (args[0], (char * const*)args, NULL); // run 'mono-hang-watchdog [pid]'
6299 g_async_safe_printf ("Could not exec mono-hang-watchdog, expected on path '%s' (errno %d)\n", hang_watchdog_path, errno);
6300 exit (1);
6303 return pid;
6306 static void
6307 summarizer_supervisor_end (SummarizerSupervisorState *state)
6309 #ifdef HAVE_KILL
6310 kill (state->supervisor_pid, SIGKILL);
6311 #endif
6313 #if defined (HAVE_WAITPID)
6314 // Accessed on same thread that sets it.
6315 int status;
6316 waitpid (state->supervisor_pid, &status, 0);
6317 #endif
6319 #endif
6321 static void
6322 collect_thread_id (gpointer key, gpointer value, gpointer user)
6324 CollectThreadIdsUserData *ud = (CollectThreadIdsUserData *)user;
6325 MonoInternalThread *thread = (MonoInternalThread *)value;
6327 if (ud->nthreads < ud->max_threads)
6328 ud->threads [ud->nthreads ++] = thread_get_tid (thread);
6331 static int
6332 collect_thread_ids (MonoNativeThreadId *thread_ids, int max_threads)
6334 CollectThreadIdsUserData ud;
6336 mono_memory_barrier ();
6337 if (!threads)
6338 return 0;
6340 memset (&ud, 0, sizeof (ud));
6341 /* This array contains refs, but its on the stack, so its ok */
6342 ud.threads = thread_ids;
6343 ud.max_threads = max_threads;
6345 mono_threads_lock ();
6346 mono_g_hash_table_foreach (threads, collect_thread_id, &ud);
6347 mono_threads_unlock ();
6349 return ud.nthreads;
6352 static gboolean
6353 summarizer_state_init (SummarizerGlobalState *state, MonoNativeThreadId current, int *my_index)
6355 gint32 started_state = mono_atomic_cas_i32 (&state->has_owner, 1 /* set */, 0 /* compare */);
6356 gboolean not_started = started_state == 0;
6357 if (not_started) {
6358 state->nthreads = collect_thread_ids (state->thread_array, MAX_NUM_THREADS);
6359 mono_os_sem_init (&state->update, 0);
6362 for (int i = 0; i < state->nthreads; i++) {
6363 if (state->thread_array [i] == current) {
6364 *my_index = i;
6365 break;
6369 return not_started;
6372 static void
6373 summarizer_signal_other_threads (SummarizerGlobalState *state, MonoNativeThreadId current, int current_idx)
6375 sigset_t sigset, old_sigset;
6376 sigemptyset(&sigset);
6377 sigaddset(&sigset, SIGTERM);
6379 for (int i=0; i < state->nthreads; i++) {
6380 sigprocmask (SIG_UNBLOCK, &sigset, &old_sigset);
6382 if (i == current_idx)
6383 continue;
6384 #ifdef HAVE_PTHREAD_KILL
6385 pthread_kill (state->thread_array [i], SIGTERM);
6387 if (!state->silent)
6388 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));
6389 #else
6390 g_error ("pthread_kill () is not supported by this platform");
6391 #endif
6395 // Returns true when there are shared global references to "this_thread"
6396 static gboolean
6397 summarizer_post_dump (SummarizerGlobalState *state, MonoThreadSummary *this_thread, int current_idx)
6399 mono_memory_barrier ();
6401 gpointer old = mono_atomic_cas_ptr ((volatile gpointer *)&state->all_threads [current_idx], this_thread, NULL);
6403 if (old == GINT_TO_POINTER (-1)) {
6404 g_async_safe_printf ("Trying to register response after dumping period ended");
6405 return FALSE;
6406 } else if (old != NULL) {
6407 g_async_safe_printf ("Thread dump raced for thread slot.");
6408 return FALSE;
6411 // We added our pointer
6412 gint32 count = mono_atomic_inc_i32 ((volatile gint32 *) &state->nthreads_attached);
6413 if (count == state->nthreads)
6414 mono_os_sem_post (&state->update);
6416 return TRUE;
6419 // A lockless spinwait with a timeout
6420 // Used in environments where locks are unsafe
6422 // If set_pos is true, we wait until the expected number of threads have
6423 // responded and then count that the expected number are set. If it is not true,
6424 // then we wait for them to be unset.
6425 static void
6426 summary_timedwait (SummarizerGlobalState *state, int timeout_seconds)
6428 const gint64 milliseconds_in_second = 1000;
6429 gint64 timeout_total = milliseconds_in_second * timeout_seconds;
6431 gint64 end = mono_msec_ticks () + timeout_total;
6433 while (TRUE) {
6434 if (mono_atomic_load_i32 ((volatile gint32 *) &state->nthreads_attached) == state->nthreads)
6435 break;
6437 gint64 now = mono_msec_ticks ();
6438 gint64 remaining = end - now;
6439 if (remaining <= 0)
6440 break;
6442 mono_os_sem_timedwait (&state->update, remaining, MONO_SEM_FLAGS_NONE);
6445 return;
6448 static MonoThreadSummary *
6449 summarizer_try_read_thread (SummarizerGlobalState *state, int index)
6451 gpointer old_value = NULL;
6452 gpointer new_value = GINT_TO_POINTER(-1);
6454 do {
6455 old_value = state->all_threads [index];
6456 } while (mono_atomic_cas_ptr ((volatile gpointer *) &state->all_threads [index], new_value, old_value) != old_value);
6458 MonoThreadSummary *thread = (MonoThreadSummary *) old_value;
6459 return thread;
6462 static void
6463 summarizer_state_term (SummarizerGlobalState *state, gchar **out, gchar *mem, size_t provided_size, MonoThreadSummary *controlling)
6465 // See the array writes
6466 mono_memory_barrier ();
6468 MonoThreadSummary *threads [MAX_NUM_THREADS];
6469 memset (threads, 0, sizeof(threads));
6471 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6472 for (int i=0; i < state->nthreads; i++) {
6473 threads [i] = summarizer_try_read_thread (state, i);
6474 if (!threads [i])
6475 continue;
6477 // We are doing this dump on the controlling thread because this isn't
6478 // an async context sometimes. There's still some reliance on malloc here, but it's
6479 // much more stable to do it all from the controlling thread.
6481 // This is non-null, checked in mono_threads_summarize
6482 // with early exit there
6483 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads [i]);
6486 MonoStateWriter writer;
6487 memset (&writer, 0, sizeof (writer));
6489 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6490 mono_summarize_native_state_begin (&writer, mem, provided_size);
6491 for (int i=0; i < state->nthreads; i++) {
6492 MonoThreadSummary *thread = threads [i];
6493 if (!thread)
6494 continue;
6496 mono_summarize_native_state_add_thread (&writer, thread, thread->ctx, thread == controlling);
6497 // Set non-shared state to notify the waiting thread to clean up
6498 // without having to keep our shared state alive
6499 mono_atomic_store_i32 (&thread->done, 0x1);
6500 mono_os_sem_post (&thread->done_wait);
6502 *out = mono_summarize_native_state_end (&writer);
6503 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6505 mono_os_sem_destroy (&state->update);
6507 memset (state, 0, sizeof (*state));
6508 mono_atomic_store_i32 ((volatile gint32 *)&state->has_owner, 0);
6511 static void
6512 summarizer_state_wait (MonoThreadSummary *thread)
6514 gint64 milliseconds_in_second = 1000;
6516 // cond_wait can spuriously wake up, so we need to check
6517 // done
6518 while (!mono_atomic_load_i32 (&thread->done))
6519 mono_os_sem_timedwait (&thread->done_wait, milliseconds_in_second, MONO_SEM_FLAGS_NONE);
6522 static gboolean
6523 mono_threads_summarize_execute_internal (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size, gboolean this_thread_controls)
6525 static SummarizerGlobalState state;
6527 int current_idx;
6528 MonoNativeThreadId current = mono_native_thread_id_get ();
6529 gboolean thread_given_control = summarizer_state_init (&state, current, &current_idx);
6531 g_assert (this_thread_controls == thread_given_control);
6533 if (state.nthreads == 0) {
6534 if (!silent)
6535 g_async_safe_printf("No threads attached to runtime.\n");
6536 memset (&state, 0, sizeof (state));
6537 return FALSE;
6540 if (this_thread_controls) {
6541 g_assert (working_mem);
6543 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6544 state.silent = silent;
6545 summarizer_signal_other_threads (&state, current, current_idx);
6546 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6549 MonoStateMem mem;
6550 gboolean success = mono_state_alloc_mem (&mem, (long) current, sizeof (MonoThreadSummary));
6551 if (!success)
6552 return FALSE;
6554 MonoThreadSummary *this_thread = (MonoThreadSummary *) mem.mem;
6556 if (mono_threads_summarize_native_self (this_thread, ctx)) {
6557 // Init the synchronization between the controlling thread and the
6558 // providing thread
6559 mono_os_sem_init (&this_thread->done_wait, 0);
6561 // Store a reference to our stack memory into global state
6562 gboolean success = summarizer_post_dump (&state, this_thread, current_idx);
6563 if (!success && !state.silent)
6564 g_async_safe_printf("Thread 0x%zx reported itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6565 } else if (!state.silent) {
6566 g_async_safe_printf("Thread 0x%zx couldn't report itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6569 // From summarizer, wait and dump.
6570 if (this_thread_controls) {
6571 if (!state.silent)
6572 g_async_safe_printf("Entering thread summarizer pause from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6574 // Wait up to 2 seconds for all of the other threads to catch up
6575 summary_timedwait (&state, 2);
6577 if (!state.silent)
6578 g_async_safe_printf("Finished thread summarizer pause from 0x%zx.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6580 // Dump and cleanup all the stack memory
6581 summarizer_state_term (&state, out, working_mem, provided_size, this_thread);
6582 } else {
6583 // Wait here, keeping our stack memory alive
6584 // for the dumper
6585 summarizer_state_wait (this_thread);
6588 // FIXME: How many threads should be counted?
6589 if (hashes)
6590 *hashes = this_thread->hashes;
6592 mono_state_free_mem (&mem);
6594 return TRUE;
6597 void
6598 mono_threads_summarize_init (void)
6600 summarizer_supervisor_init ();
6603 gboolean
6604 mono_threads_summarize_execute (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size)
6606 gboolean result;
6607 gboolean already_async = mono_thread_info_is_async_context ();
6608 if (!already_async)
6609 mono_thread_info_set_is_async_context (TRUE);
6610 result = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, working_mem, provided_size, FALSE);
6611 if (!already_async)
6612 mono_thread_info_set_is_async_context (FALSE);
6613 return result;
6616 gboolean
6617 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6619 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6620 return FALSE;
6622 // The staggered values are due to the need to use inc_i64 for the first value
6623 static gint64 next_pending_request_id = 0;
6624 static gint64 request_available_to_run = 1;
6625 gint64 this_request_id = mono_atomic_inc_i64 ((volatile gint64 *) &next_pending_request_id);
6627 // This is a global queue of summary requests.
6628 // It's not safe to signal a thread while they're in the
6629 // middle of a dump. Dladdr is not reentrant. It's the one lock
6630 // we rely on being able to take.
6632 // We don't use it in almost any other place in managed code, so
6633 // our problem is in the stack dumping code racing with the signalling code.
6635 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6636 // If we're running from a crash handler block, we're not in any position to
6637 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6638 // We should simply return so we can die cleanly.
6640 // signal_handler_controller should be set only from a handler that expects itself to be the only
6641 // entry point, where the runtime already being dumping means we should just give up
6643 gboolean success = FALSE;
6645 while (TRUE) {
6646 gint64 next_request_id = mono_atomic_load_i64 ((volatile gint64 *) &request_available_to_run);
6648 if (next_request_id == this_request_id) {
6649 gboolean already_async = mono_thread_info_is_async_context ();
6650 if (!already_async)
6651 mono_thread_info_set_is_async_context (TRUE);
6653 SummarizerSupervisorState synch;
6654 if (summarizer_supervisor_start (&synch)) {
6655 g_assert (mem);
6656 success = mono_threads_summarize_execute_internal (ctx, out, hashes, silent, mem, provided_size, TRUE);
6657 summarizer_supervisor_end (&synch);
6660 if (!already_async)
6661 mono_thread_info_set_is_async_context (FALSE);
6663 // Only the thread that gets the ticket can unblock future dumpers.
6664 mono_atomic_inc_i64 ((volatile gint64 *) &request_available_to_run);
6665 break;
6666 } else if (signal_handler_controller) {
6667 // We're done. We can't do anything.
6668 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6669 mono_summarize_double_fault_log ();
6670 break;
6671 } else {
6672 if (!silent)
6673 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6674 sleep (2);
6678 return success;
6681 #endif
6683 #ifdef ENABLE_NETCORE
6684 void
6685 ves_icall_System_Threading_Thread_StartInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6687 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6688 gboolean res;
6690 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p)", __func__, internal));
6692 LOCK_THREAD (internal);
6694 if ((internal->state & ThreadState_Unstarted) == 0) {
6695 UNLOCK_THREAD (internal);
6696 mono_error_set_exception_thread_state (error, "Thread has already been started.");
6697 return;
6700 if ((internal->state & ThreadState_Aborted) != 0) {
6701 UNLOCK_THREAD (internal);
6702 return;
6705 res = create_thread (internal, internal, NULL, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
6706 if (!res) {
6707 UNLOCK_THREAD (internal);
6708 return;
6711 internal->state &= ~ThreadState_Unstarted;
6713 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, (gsize)internal->tid, internal->handle));
6715 UNLOCK_THREAD (internal);
6718 void
6719 ves_icall_System_Threading_Thread_InitInternal (MonoThreadObjectHandle thread_handle, MonoError *error)
6721 MonoThread *internal = MONO_HANDLE_RAW (thread_handle);
6723 // Need to initialize thread objects created from managed code
6724 init_internal_thread_object (internal);
6725 internal->state = ThreadState_Unstarted;
6726 MONO_OBJECT_SETREF_INTERNAL (internal, internal_thread, internal);
6729 guint64
6730 ves_icall_System_Threading_Thread_GetCurrentOSThreadId (MonoError *error)
6732 return mono_native_thread_os_id_get ();
6735 #endif