[Mono.Runtime.Tests] Exclude simd tests
[mono-project.git] / mono / metadata / threads.c
blob3f0dd8c6528dfba64860b6d65f9f51d5fd45df22
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/gc-internals.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/runtime.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/debug-internals.h>
34 #include <mono/utils/monobitset.h>
35 #include <mono/utils/mono-compiler.h>
36 #include <mono/utils/mono-mmap.h>
37 #include <mono/utils/mono-membar.h>
38 #include <mono/utils/mono-time.h>
39 #include <mono/utils/mono-threads.h>
40 #include <mono/utils/mono-threads-coop.h>
41 #include <mono/utils/mono-tls.h>
42 #include <mono/utils/atomic.h>
43 #include <mono/utils/mono-memory-model.h>
44 #include <mono/utils/mono-error-internals.h>
45 #include <mono/utils/os-event.h>
46 #include <mono/utils/mono-threads-debug.h>
47 #include <mono/utils/unlocked.h>
48 #include <mono/metadata/w32handle.h>
49 #include <mono/metadata/w32event.h>
50 #include <mono/metadata/w32mutex.h>
52 #include <mono/metadata/reflection-internals.h>
53 #include <mono/metadata/abi-details.h>
54 #include <mono/metadata/w32error.h>
55 #include <mono/utils/w32api.h>
56 #include <mono/utils/mono-os-wait.h>
57 #include <mono/metadata/exception-internals.h>
58 #include <mono/utils/mono-state.h>
59 #include <mono/metadata/w32subset.h>
61 #ifdef HAVE_SYS_WAIT_H
62 #include <sys/wait.h>
63 #endif
65 #ifdef HAVE_SIGNAL_H
66 #include <signal.h>
67 #endif
69 #if defined(HOST_WIN32)
70 #include <objbase.h>
71 #include <sys/timeb.h>
72 extern gboolean
73 mono_native_thread_join_handle (HANDLE thread_handle, gboolean close_handle);
74 #endif
76 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
77 #define USE_TKILL_ON_ANDROID 1
78 #endif
80 #ifdef HOST_ANDROID
81 #include <errno.h>
83 #ifdef USE_TKILL_ON_ANDROID
84 extern int tkill (pid_t tid, int signal);
85 #endif
86 #endif
88 #include "icall-decl.h"
90 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
91 #define THREAD_DEBUG(a)
92 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
93 #define THREAD_WAIT_DEBUG(a)
94 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
95 #define LIBGC_DEBUG(a)
97 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
98 #define SPIN_LOCK(i) do { \
99 if (SPIN_TRYLOCK (i)) \
100 break; \
101 } while (1)
103 #define SPIN_UNLOCK(i) i = 0
105 #define LOCK_THREAD(thread) lock_thread((thread))
106 #define UNLOCK_THREAD(thread) unlock_thread((thread))
108 typedef union {
109 gint32 ival;
110 gfloat fval;
111 } IntFloatUnion;
113 typedef union {
114 gint64 ival;
115 gdouble fval;
116 } LongDoubleUnion;
118 typedef struct _StaticDataFreeList StaticDataFreeList;
119 struct _StaticDataFreeList {
120 StaticDataFreeList *next;
121 guint32 offset;
122 guint32 size;
125 typedef struct {
126 int idx;
127 int offset;
128 StaticDataFreeList *freelist;
129 } StaticDataInfo;
131 /* Controls access to the 'threads' hash table */
132 static void mono_threads_lock (void);
133 static void mono_threads_unlock (void);
134 static MonoCoopMutex threads_mutex;
136 /* Controls access to the 'joinable_threads' hash table */
137 #define joinable_threads_lock() mono_coop_mutex_lock (&joinable_threads_mutex)
138 #define joinable_threads_unlock() mono_coop_mutex_unlock (&joinable_threads_mutex)
139 static MonoCoopMutex joinable_threads_mutex;
141 /* Holds current status of static data heap */
142 static StaticDataInfo thread_static_info;
143 static StaticDataInfo context_static_info;
145 /* The hash of existing threads (key is thread ID, value is
146 * MonoInternalThread*) that need joining before exit
148 static MonoGHashTable *threads=NULL;
150 /* List of app context GC handles.
151 * Added to from mono_threads_register_app_context ().
153 static GHashTable *contexts = NULL;
155 /* Cleanup queue for contexts. */
156 static MonoReferenceQueue *context_queue;
159 * Threads which are starting up and they are not in the 'threads' hash yet.
160 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
161 * Protected by mono_threads_lock ().
163 static MonoGHashTable *threads_starting_up = NULL;
165 /* Contains tids */
166 /* Protected by the threads lock */
167 static GHashTable *joinable_threads;
168 static gint32 joinable_thread_count;
170 /* mono_threads_join_threads will take threads from joinable_threads list and wait for them. */
171 /* When this happens, the tid is not on the list anymore so mono_thread_join assumes the thread has complete */
172 /* and will return back to the caller. This could cause a race since caller of join assumes thread has completed */
173 /* and on some OS it could cause errors. Keeping the tid's currently pending a native thread join call */
174 /* in a separate table (only affecting callers interested in this internal join detail) and look at that table in mono_thread_join */
175 /* will close this race. */
176 static GHashTable *pending_native_thread_join_calls;
177 static MonoCoopCond pending_native_thread_join_calls_event;
179 static GHashTable *pending_joinable_threads;
180 static gint32 pending_joinable_thread_count;
182 static MonoCoopCond zero_pending_joinable_thread_event;
184 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info);
185 static gboolean threads_wait_pending_joinable_threads (uint32_t timeout);
186 static gchar* thread_dump_dir = NULL;
188 #define SET_CURRENT_OBJECT mono_tls_set_thread
189 #define GET_CURRENT_OBJECT mono_tls_get_thread
191 /* function called at thread start */
192 static MonoThreadStartCB mono_thread_start_cb = NULL;
194 /* function called at thread attach */
195 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
197 /* function called at thread cleanup */
198 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
200 /* The default stack size for each thread */
201 static guint32 default_stacksize = 0;
202 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
204 static void context_adjust_static_data (MonoAppContextHandle ctx);
205 static void mono_free_static_data (gpointer* static_data);
206 static void mono_init_static_data_info (StaticDataInfo *static_data);
207 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
208 static gboolean mono_thread_resume (MonoInternalThread* thread);
209 static void async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort);
210 static void self_abort_internal (MonoError *error);
211 static void async_suspend_internal (MonoInternalThread *thread, gboolean interrupt);
212 static void self_suspend_internal (void);
214 static gboolean
215 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync);
217 MONO_COLD void
218 mono_set_pending_exception_handle (MonoExceptionHandle exc);
220 static MonoException*
221 mono_thread_execute_interruption_ptr (void);
223 static void
224 mono_thread_execute_interruption_void (void);
226 static gboolean
227 mono_thread_execute_interruption (MonoExceptionHandle *pexc);
229 static void ref_stack_destroy (gpointer rs);
231 /* Spin lock for InterlockedXXX 64 bit functions */
232 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
233 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
234 static mono_mutex_t interlocked_mutex;
236 /* global count of thread interruptions requested */
237 static gint32 thread_interruption_requested = 0;
239 /* Event signaled when a thread changes its background mode */
240 static MonoOSEvent background_change_event;
242 static gboolean shutting_down = FALSE;
244 static gint32 managed_thread_id_counter = 0;
246 static void
247 mono_threads_lock (void)
249 mono_locks_coop_acquire (&threads_mutex, ThreadsLock);
252 static void
253 mono_threads_unlock (void)
255 mono_locks_coop_release (&threads_mutex, ThreadsLock);
259 static guint32
260 get_next_managed_thread_id (void)
262 return mono_atomic_inc_i32 (&managed_thread_id_counter);
266 * We separate interruptions/exceptions into either sync (they can be processed anytime,
267 * normally as soon as they are set, and are set by the same thread) and async (they can't
268 * be processed inside abort protected blocks and are normally set by other threads). We
269 * can have both a pending sync and async interruption. In this case, the sync exception is
270 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
271 * also handle all sync type exceptions before the async type exceptions.
273 enum {
274 INTERRUPT_SYNC_REQUESTED_BIT = 0x1,
275 INTERRUPT_ASYNC_REQUESTED_BIT = 0x2,
276 INTERRUPT_REQUESTED_MASK = 0x3,
277 ABORT_PROT_BLOCK_SHIFT = 2,
278 ABORT_PROT_BLOCK_BITS = 8,
279 ABORT_PROT_BLOCK_MASK = (((1 << ABORT_PROT_BLOCK_BITS) - 1) << ABORT_PROT_BLOCK_SHIFT)
282 static int
283 mono_thread_get_abort_prot_block_count (MonoInternalThread *thread)
285 gsize state = thread->thread_state;
286 return (state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT;
289 gboolean
290 mono_threads_is_current_thread_in_protected_block (void)
292 MonoInternalThread *thread = mono_thread_internal_current ();
294 return mono_thread_get_abort_prot_block_count (thread) > 0;
297 void
298 mono_threads_begin_abort_protected_block (void)
300 MonoInternalThread *thread = mono_thread_internal_current ();
301 gsize old_state, new_state;
302 int new_val;
303 do {
304 old_state = thread->thread_state;
306 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) + 1;
307 //bounds check abort_prot_count
308 g_assert (new_val > 0);
309 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
311 new_state = old_state + (1 << ABORT_PROT_BLOCK_SHIFT);
312 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
314 /* Defer async request since we won't be able to process until exiting the block */
315 if (new_val == 1 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
316 mono_atomic_dec_i32 (&thread_interruption_requested);
317 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
318 if (thread_interruption_requested < 0)
319 g_warning ("bad thread_interruption_requested state");
320 } else {
321 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
325 static gboolean
326 mono_thread_state_has_interruption (gsize state)
328 /* pending exception, self abort */
329 if (state & INTERRUPT_SYNC_REQUESTED_BIT)
330 return TRUE;
332 /* abort, interruption, suspend */
333 if ((state & INTERRUPT_ASYNC_REQUESTED_BIT) && !(state & ABORT_PROT_BLOCK_MASK))
334 return TRUE;
336 return FALSE;
339 gboolean
340 mono_threads_end_abort_protected_block (void)
342 MonoInternalThread *thread = mono_thread_internal_current ();
343 gsize old_state, new_state;
344 int new_val;
345 do {
346 old_state = thread->thread_state;
348 //bounds check abort_prot_count
349 new_val = ((old_state & ABORT_PROT_BLOCK_MASK) >> ABORT_PROT_BLOCK_SHIFT) - 1;
350 g_assert (new_val >= 0);
351 g_assert (new_val < (1 << ABORT_PROT_BLOCK_BITS));
353 new_state = old_state - (1 << ABORT_PROT_BLOCK_SHIFT);
354 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
356 if (new_val == 0 && (new_state & INTERRUPT_ASYNC_REQUESTED_BIT)) {
357 mono_atomic_inc_i32 (&thread_interruption_requested);
358 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
359 } else {
360 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
363 return mono_thread_state_has_interruption (new_state);
366 static gboolean
367 mono_thread_get_interruption_requested (MonoInternalThread *thread)
369 gsize state = thread->thread_state;
371 return mono_thread_state_has_interruption (state);
375 * Returns TRUE is there was a state change
376 * We clear a single interruption request, sync has priority.
378 static gboolean
379 mono_thread_clear_interruption_requested (MonoInternalThread *thread)
381 gsize old_state, new_state;
382 do {
383 old_state = thread->thread_state;
385 // no interruption to process
386 if (!(old_state & INTERRUPT_SYNC_REQUESTED_BIT) &&
387 (!(old_state & INTERRUPT_ASYNC_REQUESTED_BIT) || (old_state & ABORT_PROT_BLOCK_MASK)))
388 return FALSE;
390 if (old_state & INTERRUPT_SYNC_REQUESTED_BIT)
391 new_state = old_state & ~INTERRUPT_SYNC_REQUESTED_BIT;
392 else
393 new_state = old_state & ~INTERRUPT_ASYNC_REQUESTED_BIT;
394 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
396 mono_atomic_dec_i32 (&thread_interruption_requested);
397 THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread->small_id, old_state, new_state, thread_interruption_requested);
398 if (thread_interruption_requested < 0)
399 g_warning ("bad thread_interruption_requested state");
400 return TRUE;
403 static gboolean
404 mono_thread_clear_interruption_requested_handle (MonoInternalThreadHandle thread)
406 // Internal threads are pinned so shallow coop/handle.
407 return mono_thread_clear_interruption_requested (mono_internal_thread_handle_ptr (thread));
410 /* Returns TRUE is there was a state change and the interruption can be processed */
411 static gboolean
412 mono_thread_set_interruption_requested (MonoInternalThread *thread)
414 //always force when the current thread is doing it to itself.
415 gboolean sync = thread == mono_thread_internal_current ();
416 /* Normally synchronous interruptions can bypass abort protection. */
417 return mono_thread_set_interruption_requested_flags (thread, sync);
420 /* Returns TRUE if there was a state change and the interruption can be
421 * processed. This variant defers a self abort when inside an abort protected
422 * block. Normally this should only be done when a thread has received an
423 * outside indication that it should abort. (For example when the JIT sets a
424 * flag in an finally block.)
427 static gboolean
428 mono_thread_set_self_interruption_respect_abort_prot (void)
430 MonoInternalThread *thread = mono_thread_internal_current ();
431 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
432 * which is unusual. */
433 return mono_thread_set_interruption_requested_flags (thread, FALSE);
436 /* Returns TRUE if there was a state change and the interruption can be processed. */
437 static gboolean
438 mono_thread_set_interruption_requested_flags (MonoInternalThread *thread, gboolean sync)
440 gsize old_state, new_state;
441 do {
442 old_state = thread->thread_state;
444 //Already set
445 if ((sync && (old_state & INTERRUPT_SYNC_REQUESTED_BIT)) ||
446 (!sync && (old_state & INTERRUPT_ASYNC_REQUESTED_BIT)))
447 return FALSE;
449 if (sync)
450 new_state = old_state | INTERRUPT_SYNC_REQUESTED_BIT;
451 else
452 new_state = old_state | INTERRUPT_ASYNC_REQUESTED_BIT;
453 } while (mono_atomic_cas_ptr ((volatile gpointer *)&thread->thread_state, (gpointer)new_state, (gpointer)old_state) != (gpointer)old_state);
455 if (sync || !(new_state & ABORT_PROT_BLOCK_MASK)) {
456 mono_atomic_inc_i32 (&thread_interruption_requested);
457 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
458 } else {
459 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id, thread->small_id, old_state, new_state, thread_interruption_requested);
462 return sync || !(new_state & ABORT_PROT_BLOCK_MASK);
465 static inline MonoNativeThreadId
466 thread_get_tid (MonoInternalThread *thread)
468 /* We store the tid as a guint64 to keep the object layout constant between platforms */
469 return MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
472 static void
473 free_synch_cs (MonoCoopMutex *synch_cs)
475 g_assert (synch_cs);
476 mono_coop_mutex_destroy (synch_cs);
477 g_free (synch_cs);
480 static void
481 free_longlived_thread_data (void *user_data)
483 MonoLongLivedThreadData *lltd = (MonoLongLivedThreadData*)user_data;
484 free_synch_cs (lltd->synch_cs);
486 g_free (lltd);
489 static void
490 init_longlived_thread_data (MonoLongLivedThreadData *lltd)
492 mono_refcount_init (lltd, free_longlived_thread_data);
493 mono_refcount_inc (lltd);
494 /* Initial refcount is 2: decremented once by
495 * mono_thread_detach_internal and once by the MonoInternalThread
496 * finalizer - whichever one happens later will deallocate. */
498 lltd->synch_cs = g_new0 (MonoCoopMutex, 1);
499 mono_coop_mutex_init_recursive (lltd->synch_cs);
501 mono_memory_barrier ();
504 static void
505 dec_longlived_thread_data (MonoLongLivedThreadData *lltd)
507 mono_refcount_dec (lltd);
510 static inline void
511 lock_thread (MonoInternalThread *thread)
513 g_assert (thread->longlived);
514 g_assert (thread->longlived->synch_cs);
516 mono_coop_mutex_lock (thread->longlived->synch_cs);
519 static inline void
520 unlock_thread (MonoInternalThread *thread)
522 mono_coop_mutex_unlock (thread->longlived->synch_cs);
525 static void
526 lock_thread_handle (MonoInternalThreadHandle thread)
528 lock_thread (mono_internal_thread_handle_ptr (thread));
531 static void
532 unlock_thread_handle (MonoInternalThreadHandle thread)
534 unlock_thread (mono_internal_thread_handle_ptr (thread));
537 static inline gboolean
538 is_appdomainunloaded_exception (MonoClass *klass)
540 return klass == mono_class_get_appdomain_unloaded_exception_class ();
543 static inline gboolean
544 is_threadabort_exception (MonoClass *klass)
546 return klass == mono_defaults.threadabortexception_class;
550 * A special static data offset (guint32) consists of 3 parts:
552 * [0] 6-bit index into the array of chunks.
553 * [6] 25-bit offset into the array.
554 * [31] Bit indicating thread or context static.
557 typedef union {
558 struct {
559 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
560 guint32 type : 1;
561 guint32 offset : 25;
562 guint32 index : 6;
563 #else
564 guint32 index : 6;
565 guint32 offset : 25;
566 guint32 type : 1;
567 #endif
568 } fields;
569 guint32 raw;
570 } SpecialStaticOffset;
572 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
573 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
575 static guint32
576 MAKE_SPECIAL_STATIC_OFFSET (guint32 index, guint32 offset, guint32 type)
578 SpecialStaticOffset special_static_offset;
579 memset (&special_static_offset, 0, sizeof (special_static_offset));
580 special_static_offset.fields.index = index;
581 special_static_offset.fields.offset = offset;
582 special_static_offset.fields.type = type;
583 return special_static_offset.raw;
586 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
587 (((SpecialStaticOffset *) &(x))->fields.f)
589 static gpointer
590 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
592 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_THREAD);
594 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
595 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
597 return ((char *) thread->static_data [idx]) + off;
600 static gpointer
601 get_context_static_data (MonoAppContext *ctx, guint32 offset)
603 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset, type) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT);
605 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
606 int off = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
608 return ((char *) ctx->static_data [idx]) + off;
611 static MonoThread**
612 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
614 static MonoClassField *current_thread_field = NULL;
616 guint32 offset;
618 if (!current_thread_field) {
619 current_thread_field = mono_class_get_field_from_name_full (mono_defaults.thread_class, "current_thread", NULL);
620 g_assert (current_thread_field);
623 ERROR_DECL (thread_vt_error);
624 mono_class_vtable_checked (domain, mono_defaults.thread_class, thread_vt_error);
625 mono_error_assert_ok (thread_vt_error);
626 mono_domain_lock (domain);
627 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
628 mono_domain_unlock (domain);
629 g_assert (offset);
631 return (MonoThread **)get_thread_static_data (thread, offset);
634 static void
635 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
637 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
639 g_assert (current->obj.vtable->domain == domain);
641 g_assert (!*current_thread_ptr);
642 *current_thread_ptr = current;
645 static MonoThread*
646 create_thread_object (MonoDomain *domain, MonoInternalThread *internal)
648 MonoThread *thread;
649 MonoVTable *vtable;
650 ERROR_DECL (error);
652 vtable = mono_class_vtable_checked (domain, mono_defaults.thread_class, error);
653 mono_error_assert_ok (error);
655 thread = (MonoThread*)mono_object_new_mature (vtable, error);
656 /* only possible failure mode is OOM, from which we don't expect to recover. */
657 mono_error_assert_ok (error);
659 MONO_OBJECT_SETREF_INTERNAL (thread, internal_thread, internal);
661 return thread;
664 static MonoInternalThread*
665 create_internal_thread_object (void)
667 ERROR_DECL (error);
668 MonoInternalThread *thread;
669 MonoVTable *vt;
671 vt = mono_class_vtable_checked (mono_get_root_domain (), mono_defaults.internal_thread_class, error);
672 mono_error_assert_ok (error);
673 thread = (MonoInternalThread*) mono_object_new_mature (vt, error);
674 /* only possible failure mode is OOM, from which we don't exect to recover */
675 mono_error_assert_ok (error);
677 thread->longlived = g_new0 (MonoLongLivedThreadData, 1);
678 init_longlived_thread_data (thread->longlived);
680 thread->apartment_state = ThreadApartmentState_Unknown;
681 thread->managed_id = get_next_managed_thread_id ();
682 if (mono_gc_is_moving ()) {
683 thread->thread_pinning_ref = thread;
684 MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Pinning Reference");
687 thread->priority = MONO_THREAD_PRIORITY_NORMAL;
689 thread->suspended = g_new0 (MonoOSEvent, 1);
690 mono_os_event_init (thread->suspended, TRUE);
692 return thread;
695 static void
696 mono_thread_internal_set_priority (MonoInternalThread *internal, MonoThreadPriority priority)
698 g_assert (internal);
700 g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
701 g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
702 g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
704 #ifdef HOST_WIN32
705 BOOL res;
706 DWORD last_error;
708 g_assert (internal->native_handle);
710 MONO_ENTER_GC_SAFE;
711 res = SetThreadPriority (internal->native_handle, (int)priority - 2);
712 last_error = GetLastError ();
713 MONO_EXIT_GC_SAFE;
714 if (!res)
715 g_error ("%s: SetThreadPriority failed, error %d", __func__, last_error);
716 #else /* HOST_WIN32 */
717 pthread_t tid;
718 int policy;
719 struct sched_param param;
720 gint res;
722 tid = thread_get_tid (internal);
724 MONO_ENTER_GC_SAFE;
725 res = pthread_getschedparam (tid, &policy, &param);
726 MONO_EXIT_GC_SAFE;
727 if (res != 0)
728 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
730 #ifdef _POSIX_PRIORITY_SCHEDULING
731 int max, min;
733 /* Necessary to get valid priority range */
735 MONO_ENTER_GC_SAFE;
736 #if defined(__PASE__)
737 /* only priorities allowed by IBM i */
738 min = PRIORITY_MIN;
739 max = PRIORITY_MAX;
740 #else
741 min = sched_get_priority_min (policy);
742 max = sched_get_priority_max (policy);
743 #endif
744 MONO_EXIT_GC_SAFE;
746 if (max > 0 && min >= 0 && max > min) {
747 double srange, drange, sposition, dposition;
748 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
749 drange = max - min;
750 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
751 dposition = (sposition / srange) * drange;
752 param.sched_priority = (int)(dposition + min);
753 } else
754 #endif
756 switch (policy) {
757 case SCHED_FIFO:
758 case SCHED_RR:
759 param.sched_priority = 50;
760 break;
761 #ifdef SCHED_BATCH
762 case SCHED_BATCH:
763 #endif
764 case SCHED_OTHER:
765 param.sched_priority = 0;
766 break;
767 default:
768 g_warning ("%s: unknown policy %d", __func__, policy);
769 return;
773 MONO_ENTER_GC_SAFE;
774 #if defined(__PASE__)
775 /* only scheduling param allowed by IBM i */
776 res = pthread_setschedparam (tid, SCHED_OTHER, &param);
777 #else
778 res = pthread_setschedparam (tid, policy, &param);
779 #endif
780 MONO_EXIT_GC_SAFE;
781 if (res != 0) {
782 if (res == EPERM) {
783 #if !defined(_AIX)
784 /* AIX doesn't like doing this and will spam this every time;
785 * weirdly, i doesn't complain
787 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
788 #endif
789 return;
791 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
793 #endif /* HOST_WIN32 */
796 static void
797 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal);
799 static gboolean
800 mono_thread_attach_internal (MonoThread *thread, gboolean force_attach, gboolean force_domain)
802 MonoThreadInfo *info;
803 MonoInternalThread *internal;
804 MonoDomain *domain, *root_domain;
805 guint32 gchandle;
807 g_assert (thread);
809 info = mono_thread_info_current ();
810 g_assert (info);
812 internal = thread->internal_thread;
813 g_assert (internal);
815 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
816 * - the MonoInternalThread TLS key is destroyed: set it to NULL
817 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
818 * - it calls MonoThreadInfoCallbacks.thread_detach
819 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
820 mono_thread_info_set_internal_thread_gchandle (info, mono_gchandle_new_internal ((MonoObject*) internal, FALSE));
822 internal->handle = mono_threads_open_thread_handle (info->handle);
823 #ifdef HOST_WIN32
824 internal->native_handle = OpenThread (THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId ());
825 #endif
826 internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
827 internal->thread_info = info;
828 internal->small_id = info->small_id;
830 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Setting current_object_key to %p", __func__, mono_native_thread_id_get (), internal));
832 SET_CURRENT_OBJECT (internal);
834 domain = mono_object_domain (thread);
836 mono_thread_push_appdomain_ref (domain);
837 if (!mono_domain_set (domain, force_domain)) {
838 mono_thread_pop_appdomain_ref ();
839 goto fail;
842 mono_threads_lock ();
844 if (shutting_down && !force_attach) {
845 mono_threads_unlock ();
846 mono_thread_pop_appdomain_ref ();
847 goto fail;
850 if (threads_starting_up)
851 mono_g_hash_table_remove (threads_starting_up, thread);
853 if (!threads) {
854 threads = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Table");
857 /* We don't need to duplicate thread->handle, because it is
858 * only closed when the thread object is finalized by the GC. */
859 mono_g_hash_table_insert (threads, (gpointer)(gsize)(internal->tid), internal);
861 /* We have to do this here because mono_thread_start_cb
862 * requires that root_domain_thread is set up. */
863 if (thread_static_info.offset || thread_static_info.idx > 0) {
864 /* get the current allocated size */
865 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (thread_static_info.idx, thread_static_info.offset, 0);
866 mono_alloc_static_data (&internal->static_data, offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), TRUE);
869 mono_threads_unlock ();
871 root_domain = mono_get_root_domain ();
873 g_assert (!internal->root_domain_thread);
874 if (domain != root_domain)
875 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, create_thread_object (root_domain, internal));
876 else
877 MONO_OBJECT_SETREF_INTERNAL (internal, root_domain_thread, thread);
879 if (domain != root_domain)
880 set_current_thread_for_domain (root_domain, internal, internal->root_domain_thread);
882 set_current_thread_for_domain (domain, internal, thread);
884 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, internal->tid, internal->handle));
886 return TRUE;
888 fail:
889 mono_threads_lock ();
890 if (threads_starting_up)
891 mono_g_hash_table_remove (threads_starting_up, thread);
892 mono_threads_unlock ();
894 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
895 g_error ("%s: failed to get gchandle, info %p", __func__, info);
897 mono_gchandle_free_internal (gchandle);
899 mono_thread_info_unset_internal_thread_gchandle (info);
901 SET_CURRENT_OBJECT(NULL);
903 return FALSE;
906 static void
907 mono_thread_detach_internal (MonoInternalThread *thread)
909 MonoThreadInfo *info;
910 MonoInternalThread *value;
911 gboolean removed;
912 guint32 gchandle;
914 g_assert (mono_thread_internal_is_current (thread));
916 g_assert (thread != NULL);
917 SET_CURRENT_OBJECT (thread);
919 info = thread->thread_info;
920 g_assert (info);
922 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
924 MONO_PROFILER_RAISE (thread_stopping, (thread->tid));
927 * Prevent race condition between thread shutdown and runtime shutdown.
928 * Including all runtime threads in the pending joinable count will make
929 * sure shutdown will wait for it to get onto the joinable thread list before
930 * critical resources have been cleanup (like GC memory). Threads getting onto
931 * the joinable thread list should just about to exit and not blocking a potential
932 * join call. Owner of threads attached to the runtime but not identified as runtime
933 * threads needs to make sure thread detach calls won't race with runtime shutdown.
935 threads_add_pending_joinable_runtime_thread (info);
937 #ifndef HOST_WIN32
938 mono_w32mutex_abandon (thread);
939 #endif
941 mono_gchandle_free_internal (thread->abort_state_handle);
942 thread->abort_state_handle = 0;
944 thread->abort_exc = NULL;
945 thread->current_appcontext = NULL;
947 LOCK_THREAD (thread);
949 thread->state |= ThreadState_Stopped;
950 thread->state &= ~ThreadState_Background;
952 UNLOCK_THREAD (thread);
955 An interruption request has leaked to cleanup. Adjust the global counter.
957 This can happen is the abort source thread finds the abortee (this) thread
958 in unmanaged code. If this thread never trips back to managed code or check
959 the local flag it will be left set and positively unbalance the global counter.
961 Leaving the counter unbalanced will cause a performance degradation since all threads
962 will now keep checking their local flags all the time.
964 mono_thread_clear_interruption_requested (thread);
966 mono_threads_lock ();
968 g_assert (threads);
970 if (!mono_g_hash_table_lookup_extended (threads, (gpointer)thread->tid, NULL, (gpointer*) &value)) {
971 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__, thread, thread->tid);
972 } else if (thread != value) {
973 /* We have to check whether the thread object for the tid is still the same in the table because the
974 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
975 * the table, but with another thread object. */
976 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__, thread, thread->tid, value, value->tid);
979 removed = mono_g_hash_table_remove (threads, (gpointer)thread->tid);
980 g_assert (removed);
982 mono_threads_unlock ();
984 /* Don't close the handle here, wait for the object finalizer
985 * to do it. Otherwise, the following race condition applies:
987 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
989 * 2) Some other handle is reassigned the same slot
991 * 3) Another thread tries to join the first thread, and
992 * blocks waiting for the reassigned handle to be signalled
993 * (which might never happen). This is possible, because the
994 * thread calling Join() still has a reference to the first
995 * thread's object.
998 mono_release_type_locks (thread);
1000 MONO_PROFILER_RAISE (thread_stopped, (thread->tid));
1001 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->stack_start_limit)));
1002 MONO_PROFILER_RAISE (gc_root_unregister, ((const mono_byte*)(info->handle_stack)));
1005 * This will signal async signal handlers that the thread has exited.
1006 * The profiler callback needs this to be set, so it cannot be done earlier.
1008 mono_domain_unset ();
1009 mono_memory_barrier ();
1011 mono_thread_pop_appdomain_ref ();
1013 mono_free_static_data (thread->static_data);
1014 thread->static_data = NULL;
1015 ref_stack_destroy (thread->appdomain_refs);
1016 thread->appdomain_refs = NULL;
1018 g_assert (thread->suspended);
1019 mono_os_event_destroy (thread->suspended);
1020 g_free (thread->suspended);
1021 thread->suspended = NULL;
1023 if (mono_thread_cleanup_fn)
1024 mono_thread_cleanup_fn (thread_get_tid (thread));
1026 mono_memory_barrier ();
1028 if (mono_gc_is_moving ()) {
1029 MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
1030 thread->thread_pinning_ref = NULL;
1033 /* There is no more any guarantee that `thread` is alive */
1034 mono_memory_barrier ();
1036 SET_CURRENT_OBJECT (NULL);
1037 mono_domain_unset ();
1039 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
1040 g_error ("%s: failed to get gchandle, info = %p", __func__, info);
1042 mono_gchandle_free_internal (gchandle);
1044 mono_thread_info_unset_internal_thread_gchandle (info);
1046 /* Possibly free synch_cs, if the finalizer for InternalThread already
1047 * ran also. */
1048 dec_longlived_thread_data (thread->longlived);
1050 MONO_PROFILER_RAISE (thread_exited, (thread->tid));
1052 /* Don't need to close the handle to this thread, even though we took a
1053 * reference in mono_thread_attach (), because the GC will do it
1054 * when the Thread object is finalised.
1058 typedef struct {
1059 gint32 ref;
1060 MonoThread *thread;
1061 MonoObject *start_delegate;
1062 MonoObject *start_delegate_arg;
1063 MonoThreadStart start_func;
1064 gpointer start_func_arg;
1065 gboolean force_attach;
1066 gboolean failed;
1067 MonoCoopSem registered;
1068 } StartInfo;
1070 static void
1071 fire_attach_profiler_events (MonoNativeThreadId tid)
1073 MONO_PROFILER_RAISE (thread_started, ((uintptr_t) tid));
1075 MonoThreadInfo *info = mono_thread_info_current ();
1077 MONO_PROFILER_RAISE (gc_root_register, (
1078 (const mono_byte*)(info->stack_start_limit),
1079 (char *) info->stack_end - (char *) info->stack_start_limit,
1080 MONO_ROOT_SOURCE_STACK,
1081 (void *) tid,
1082 "Thread Stack"));
1084 // The handle stack is a pseudo-root similar to the finalizer queues.
1085 MONO_PROFILER_RAISE (gc_root_register, (
1086 (const mono_byte*)info->handle_stack,
1088 MONO_ROOT_SOURCE_HANDLE,
1089 (void *) tid,
1090 "Handle Stack"));
1093 static guint32 WINAPI start_wrapper_internal(StartInfo *start_info, gsize *stack_ptr)
1095 ERROR_DECL (error);
1096 MonoThreadStart start_func;
1097 void *start_func_arg;
1098 gsize tid;
1100 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1101 * GC stack walk.
1103 MonoThread *thread;
1104 MonoInternalThread *internal;
1105 MonoObject *start_delegate;
1106 MonoObject *start_delegate_arg;
1108 thread = start_info->thread;
1109 internal = thread->internal_thread;
1111 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper", __func__, mono_native_thread_id_get ()));
1113 if (!mono_thread_attach_internal (thread, start_info->force_attach, FALSE)) {
1114 start_info->failed = TRUE;
1116 mono_coop_sem_post (&start_info->registered);
1118 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1119 mono_coop_sem_destroy (&start_info->registered);
1120 g_free (start_info);
1123 return 0;
1126 mono_thread_internal_set_priority (internal, (MonoThreadPriority)internal->priority);
1128 tid = internal->tid;
1130 start_delegate = start_info->start_delegate;
1131 start_delegate_arg = start_info->start_delegate_arg;
1132 start_func = start_info->start_func;
1133 start_func_arg = start_info->start_func_arg;
1135 /* This MUST be called before any managed code can be
1136 * executed, as it calls the callback function that (for the
1137 * jit) sets the lmf marker.
1140 if (mono_thread_start_cb)
1141 mono_thread_start_cb (tid, stack_ptr, (gpointer)start_func);
1143 /* On 2.0 profile (and higher), set explicitly since state might have been
1144 Unknown */
1145 if (internal->apartment_state == ThreadApartmentState_Unknown)
1146 internal->apartment_state = ThreadApartmentState_MTA;
1148 mono_thread_init_apartment_state ();
1150 /* Let the thread that called Start() know we're ready */
1151 mono_coop_sem_post (&start_info->registered);
1153 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1154 mono_coop_sem_destroy (&start_info->registered);
1155 g_free (start_info);
1158 /* start_info is not valid anymore */
1159 start_info = NULL;
1162 * Call this after calling start_notify, since the profiler callback might want
1163 * to lock the thread, and the lock is held by thread_start () which waits for
1164 * start_notify.
1166 fire_attach_profiler_events ((MonoNativeThreadId) tid);
1168 /* if the name was set before starting, we didn't invoke the profiler callback */
1169 if (internal->name) {
1170 char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
1171 MONO_PROFILER_RAISE (thread_name, (internal->tid, tname));
1172 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), tname);
1173 g_free (tname);
1176 /* start_func is set only for unmanaged start functions */
1177 if (start_func) {
1178 start_func (start_func_arg);
1179 } else {
1180 void *args [1];
1182 g_assert (start_delegate != NULL);
1184 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1185 args [0] = (gpointer) start_delegate_arg;
1186 mono_runtime_delegate_invoke_checked (start_delegate, args, error);
1188 if (!mono_error_ok (error)) {
1189 MonoException *ex = mono_error_convert_to_exception (error);
1191 g_assert (ex != NULL);
1192 MonoClass *klass = mono_object_class (ex);
1193 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY) &&
1194 !is_threadabort_exception (klass)) {
1195 mono_unhandled_exception_internal (&ex->object);
1196 mono_invoke_unhandled_exception_hook (&ex->object);
1197 g_assert_not_reached ();
1199 } else {
1200 mono_error_cleanup (error);
1204 /* If the thread calls ExitThread at all, this remaining code
1205 * will not be executed, but the main thread will eventually
1206 * call mono_thread_detach_internal() on this thread's behalf.
1209 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Start wrapper terminating", __func__, mono_native_thread_id_get ()));
1211 /* Do any cleanup needed for apartment state. This
1212 * cannot be done in mono_thread_detach_internal since
1213 * mono_thread_detach_internal could be called for a
1214 * thread other than the current thread.
1215 * mono_thread_cleanup_apartment_state cleans up apartment
1216 * for the current thead */
1217 mono_thread_cleanup_apartment_state ();
1219 mono_thread_detach_internal (internal);
1221 return 0;
1224 static mono_thread_start_return_t WINAPI
1225 start_wrapper (gpointer data)
1227 StartInfo *start_info;
1228 MonoThreadInfo *info;
1229 gsize res;
1231 start_info = (StartInfo*) data;
1232 g_assert (start_info);
1234 info = mono_thread_info_attach ();
1235 info->runtime_thread = TRUE;
1237 /* Run the actual main function of the thread */
1238 res = start_wrapper_internal (start_info, (gsize*)info->stack_end);
1240 mono_thread_info_exit (res);
1242 g_assert_not_reached ();
1246 * create_thread:
1248 * Common thread creation code.
1249 * LOCKING: Acquires the threads lock.
1251 static gboolean
1252 create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *start_delegate, MonoThreadStart start_func, gpointer start_func_arg,
1253 MonoThreadCreateFlags flags, MonoError *error)
1255 StartInfo *start_info = NULL;
1256 MonoNativeThreadId tid;
1257 gboolean ret;
1258 gsize stack_set_size;
1260 if (start_delegate)
1261 g_assert (!start_func && !start_func_arg);
1262 if (start_func)
1263 g_assert (!start_delegate);
1265 if (flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL) {
1266 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER));
1267 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1269 if (flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER) {
1270 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL));
1271 g_assert (!(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE));
1275 * Join joinable threads to prevent running out of threads since the finalizer
1276 * thread might be blocked/backlogged.
1278 mono_threads_join_threads ();
1280 error_init (error);
1282 mono_threads_lock ();
1283 if (shutting_down && !(flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE)) {
1284 mono_threads_unlock ();
1285 mono_error_set_execution_engine (error, "Couldn't create thread. Runtime is shutting down.");
1286 return FALSE;
1288 if (threads_starting_up == NULL) {
1289 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_THREADING, NULL, "Thread Starting Table");
1291 mono_g_hash_table_insert (threads_starting_up, thread, thread);
1292 mono_threads_unlock ();
1294 internal->threadpool_thread = flags & MONO_THREAD_CREATE_FLAGS_THREADPOOL;
1295 if (internal->threadpool_thread)
1296 mono_thread_set_state (internal, ThreadState_Background);
1298 internal->debugger_thread = flags & MONO_THREAD_CREATE_FLAGS_DEBUGGER;
1300 start_info = g_new0 (StartInfo, 1);
1301 start_info->ref = 2;
1302 start_info->thread = thread;
1303 start_info->start_delegate = start_delegate;
1304 start_info->start_delegate_arg = thread->start_obj;
1305 start_info->start_func = start_func;
1306 start_info->start_func_arg = start_func_arg;
1307 start_info->force_attach = flags & MONO_THREAD_CREATE_FLAGS_FORCE_CREATE;
1308 start_info->failed = FALSE;
1309 mono_coop_sem_init (&start_info->registered, 0);
1311 if (flags != MONO_THREAD_CREATE_FLAGS_SMALL_STACK)
1312 stack_set_size = default_stacksize_for_thread (internal);
1313 else
1314 stack_set_size = 0;
1316 if (!mono_thread_platform_create_thread (start_wrapper, start_info, &stack_set_size, &tid)) {
1317 /* The thread couldn't be created, so set an exception */
1318 mono_threads_lock ();
1319 mono_g_hash_table_remove (threads_starting_up, thread);
1320 mono_threads_unlock ();
1321 mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1322 /* ref is not going to be decremented in start_wrapper_internal */
1323 mono_atomic_dec_i32 (&start_info->ref);
1324 ret = FALSE;
1325 goto done;
1328 internal->stack_size = (int) stack_set_size;
1330 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT ") Launching thread %p (%" G_GSIZE_FORMAT ")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
1333 * Wait for the thread to set up its TLS data etc, so
1334 * theres no potential race condition if someone tries
1335 * to look up the data believing the thread has
1336 * started
1339 mono_coop_sem_wait (&start_info->registered, MONO_SEM_FLAGS_NONE);
1341 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));
1343 ret = !start_info->failed;
1345 done:
1346 if (mono_atomic_dec_i32 (&start_info->ref) == 0) {
1347 mono_coop_sem_destroy (&start_info->registered);
1348 g_free (start_info);
1351 return ret;
1355 * mono_thread_new_init:
1357 void
1358 mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
1360 if (mono_thread_start_cb) {
1361 mono_thread_start_cb (tid, stack_start, func);
1366 * mono_threads_set_default_stacksize:
1368 void
1369 mono_threads_set_default_stacksize (guint32 stacksize)
1371 default_stacksize = stacksize;
1375 * mono_threads_get_default_stacksize:
1377 guint32
1378 mono_threads_get_default_stacksize (void)
1380 return default_stacksize;
1384 * mono_thread_create_internal:
1386 * ARG should not be a GC reference.
1388 MonoInternalThread*
1389 mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1391 MonoThread *thread;
1392 MonoInternalThread *internal;
1393 gboolean res;
1395 error_init (error);
1397 internal = create_internal_thread_object ();
1399 thread = create_thread_object (domain, internal);
1401 LOCK_THREAD (internal);
1403 res = create_thread (thread, internal, NULL, (MonoThreadStart) func, arg, flags, error);
1405 UNLOCK_THREAD (internal);
1407 return_val_if_nok (error, NULL);
1408 return internal;
1411 MonoInternalThreadHandle
1412 mono_thread_create_internal_handle (MonoDomain *domain, gpointer func, gpointer arg, MonoThreadCreateFlags flags, MonoError *error)
1414 // FIXME invert
1415 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_create_internal (domain, func, arg, flags, error));
1419 * mono_thread_create:
1421 void
1422 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
1424 MONO_ENTER_GC_UNSAFE;
1425 ERROR_DECL (error);
1426 if (!mono_thread_create_checked (domain, func, arg, error))
1427 mono_error_cleanup (error);
1428 MONO_EXIT_GC_UNSAFE;
1431 gboolean
1432 mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
1434 return (NULL != mono_thread_create_internal (domain, func, arg, MONO_THREAD_CREATE_FLAGS_NONE, error));
1438 * mono_thread_attach:
1440 MonoThread *
1441 mono_thread_attach (MonoDomain *domain)
1443 MonoInternalThread *internal;
1444 MonoThread *thread;
1445 MonoThreadInfo *info;
1446 MonoNativeThreadId tid;
1448 if (mono_thread_internal_current_is_attached ()) {
1449 if (domain != mono_domain_get ())
1450 mono_domain_set (domain, TRUE);
1451 /* Already attached */
1452 return mono_thread_current ();
1455 info = mono_thread_info_attach ();
1456 g_assert (info);
1458 tid=mono_native_thread_id_get ();
1460 if (mono_runtime_get_no_exec ())
1461 return NULL;
1463 internal = create_internal_thread_object ();
1465 thread = create_thread_object (domain, internal);
1467 if (!mono_thread_attach_internal (thread, FALSE, TRUE)) {
1468 /* Mono is shutting down, so just wait for the end */
1469 for (;;)
1470 mono_thread_info_sleep (10000, NULL);
1473 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, internal->handle));
1475 if (mono_thread_attach_cb)
1476 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), info->stack_end);
1478 fire_attach_profiler_events (tid);
1480 return thread;
1484 * mono_thread_detach:
1486 void
1487 mono_thread_detach (MonoThread *thread)
1489 if (thread)
1490 mono_thread_detach_internal (thread->internal_thread);
1494 * mono_thread_detach_if_exiting:
1496 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1497 * This should be used at the end of embedding code which calls into managed code, and which
1498 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1500 mono_bool
1501 mono_thread_detach_if_exiting (void)
1503 if (mono_thread_info_is_exiting ()) {
1504 MonoInternalThread *thread;
1506 thread = mono_thread_internal_current ();
1507 if (thread) {
1508 // Switch to GC Unsafe thread state before detaching;
1509 // don't expect to undo this switch, hence unbalanced.
1510 gpointer dummy;
1511 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy);
1513 mono_thread_detach_internal (thread);
1514 mono_thread_info_detach ();
1515 return TRUE;
1518 return FALSE;
1521 gboolean
1522 mono_thread_internal_current_is_attached (void)
1524 MonoInternalThread *internal;
1526 internal = GET_CURRENT_OBJECT ();
1527 if (!internal)
1528 return FALSE;
1530 return TRUE;
1534 * mono_thread_exit:
1536 void
1537 mono_thread_exit (void)
1539 MonoInternalThread *thread = mono_thread_internal_current ();
1541 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT ")", __func__, thread, (gsize)thread->tid));
1543 mono_thread_detach_internal (thread);
1545 /* we could add a callback here for embedders to use. */
1546 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1547 exit (mono_environment_exitcode_get ());
1549 mono_thread_info_exit (0);
1552 static void
1553 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle)
1555 MonoInternalThread * const internal = create_internal_thread_object ();
1557 internal->state = ThreadState_Unstarted;
1559 int const thread_gchandle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, this_obj_handle), TRUE);
1561 MonoThreadObject *this_obj = MONO_HANDLE_RAW (this_obj_handle);
1563 mono_atomic_cas_ptr ((volatile gpointer *)&this_obj->internal_thread, internal, NULL);
1565 mono_gchandle_free_internal (thread_gchandle);
1568 void
1569 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle, MonoError *error)
1571 mono_thread_construct_internal (this_obj_handle);
1574 MonoThreadObjectHandle
1575 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError *error)
1577 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
1580 static MonoInternalThread*
1581 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle)
1583 return MONO_HANDLE_GETVAL(thread_handle, internal_thread); // InternalThreads are always pinned.
1586 static void
1587 mono_error_set_exception_thread_state (MonoError *error, const char *exception_message)
1589 mono_error_set_generic_error (error, "System.Threading", "ThreadStateException", "%s", exception_message);
1592 static void
1593 mono_error_set_exception_thread_not_started_or_dead (MonoError *error)
1595 mono_error_set_exception_thread_state (error, "Thread has not been started, or is dead.");
1598 MonoBoolean
1599 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle, MonoObjectHandle start_handle, MonoError *error)
1601 MonoInternalThread *internal;
1602 gboolean res;
1603 MonoThread *this_obj = MONO_HANDLE_RAW (thread_handle);
1604 MonoObject *start = MONO_HANDLE_RAW (start_handle);
1606 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this_obj, start));
1608 internal = thread_handle_to_internal_ptr (thread_handle);
1610 if (!internal) {
1611 mono_thread_construct_internal (thread_handle);
1612 internal = thread_handle_to_internal_ptr (thread_handle);
1613 g_assert (internal);
1616 LOCK_THREAD (internal);
1618 if ((internal->state & ThreadState_Unstarted) == 0) {
1619 UNLOCK_THREAD (internal);
1620 mono_error_set_exception_thread_state (error, "Thread has already been started.");
1621 return FALSE;
1624 if ((internal->state & ThreadState_Aborted) != 0) {
1625 UNLOCK_THREAD (internal);
1626 return TRUE;
1629 res = create_thread (this_obj, internal, start, NULL, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
1630 if (!res) {
1631 UNLOCK_THREAD (internal);
1632 return FALSE;
1635 internal->state &= ~ThreadState_Unstarted;
1637 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT " (handle %p)", __func__, tid, thread));
1639 UNLOCK_THREAD (internal);
1640 return TRUE;
1644 * This is called from the finalizer of the internal thread object.
1646 void
1647 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle, MonoError *error)
1649 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (this_obj_handle);
1650 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, this_obj->handle));
1653 * Since threads keep a reference to their thread object while running, by
1654 * the time this function is called, the thread has already exited/detached,
1655 * i.e. mono_thread_detach_internal () has ran. The exception is during
1656 * shutdown, when mono_thread_detach_internal () can be called after this.
1658 if (this_obj->handle) {
1659 mono_threads_close_thread_handle (this_obj->handle);
1660 this_obj->handle = NULL;
1663 #if HOST_WIN32
1664 CloseHandle (this_obj->native_handle);
1665 #endif
1667 /* Possibly free synch_cs, if the thread already detached also. */
1668 dec_longlived_thread_data (this_obj->longlived);
1671 if (this_obj->name) {
1672 void *name = this_obj->name;
1673 this_obj->name = NULL;
1674 g_free (name);
1678 void
1679 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms, MonoError *error)
1681 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1683 if (mono_thread_current_check_pending_interrupt ())
1684 return;
1686 MonoInternalThread * const thread = mono_thread_internal_current ();
1688 HANDLE_LOOP_PREPARE;
1690 while (TRUE) {
1691 gboolean alerted = FALSE;
1693 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1695 (void)mono_thread_info_sleep (ms, &alerted);
1697 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1699 if (!alerted)
1700 return;
1702 SETUP_ICALL_FRAME;
1704 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
1706 const gboolean interrupt = mono_thread_execute_interruption (&exc);
1708 if (interrupt)
1709 mono_set_pending_exception_handle (exc);
1711 CLEAR_ICALL_FRAME;
1713 if (interrupt)
1714 return;
1715 if (ms == MONO_INFINITE_WAIT) // FIXME: !MONO_INFINITE_WAIT
1716 continue;
1717 return;
1721 void
1722 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError *error)
1726 gint32
1727 ves_icall_System_Threading_Thread_GetDomainID (MonoError *error)
1729 return mono_domain_get()->domain_id;
1733 * mono_thread_get_name:
1735 * Return the name of the thread. NAME_LEN is set to the length of the name.
1736 * Return NULL if the thread has no name. The returned memory is owned by the
1737 * caller.
1739 gunichar2*
1740 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1742 gunichar2 *res;
1744 LOCK_THREAD (this_obj);
1746 if (!this_obj->name) {
1747 *name_len = 0;
1748 res = NULL;
1749 } else {
1750 *name_len = this_obj->name_len;
1751 res = g_new (gunichar2, this_obj->name_len);
1752 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1755 UNLOCK_THREAD (this_obj);
1757 return res;
1761 * mono_thread_get_name_utf8:
1762 * \returns the name of the thread in UTF-8.
1763 * Return NULL if the thread has no name.
1764 * The returned memory is owned by the caller.
1766 char *
1767 mono_thread_get_name_utf8 (MonoThread *thread)
1769 if (thread == NULL)
1770 return NULL;
1772 MonoInternalThread *internal = thread->internal_thread;
1773 if (internal == NULL)
1774 return NULL;
1776 LOCK_THREAD (internal);
1778 char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
1780 UNLOCK_THREAD (internal);
1782 return tname;
1786 * mono_thread_get_managed_id:
1787 * \returns the \c Thread.ManagedThreadId value of \p thread.
1788 * Returns \c -1 if \p thread is NULL.
1790 int32_t
1791 mono_thread_get_managed_id (MonoThread *thread)
1793 if (thread == NULL)
1794 return -1;
1796 MonoInternalThread *internal = thread->internal_thread;
1797 if (internal == NULL)
1798 return -1;
1800 int32_t id = internal->managed_id;
1802 return id;
1805 MonoStringHandle
1806 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle, MonoError *error)
1808 // InternalThreads are always pinned, so shallowly coop-handleize.
1809 MonoInternalThread * const this_obj = mono_internal_thread_handle_ptr (thread_handle);
1811 MonoStringHandle str = MONO_HANDLE_NEW (MonoString, NULL);
1813 LOCK_THREAD (this_obj);
1815 if (this_obj->name)
1816 MONO_HANDLE_ASSIGN (str, mono_string_new_utf16_handle (mono_domain_get (), this_obj->name, this_obj->name_len, error));
1818 UNLOCK_THREAD (this_obj);
1820 return str;
1823 void
1824 mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean permanent, gboolean reset, MonoError *error)
1826 MonoNativeThreadId tid = 0;
1828 LOCK_THREAD (this_obj);
1830 error_init (error);
1832 if (reset) {
1833 this_obj->flags &= ~MONO_THREAD_FLAG_NAME_SET;
1834 } else if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
1835 UNLOCK_THREAD (this_obj);
1837 mono_error_set_invalid_operation (error, "%s", "Thread.Name can only be set once.");
1838 return;
1840 if (this_obj->name) {
1841 g_free (this_obj->name);
1842 this_obj->name_len = 0;
1844 if (name) {
1845 this_obj->name = g_memdup (mono_string_chars_internal (name), mono_string_length_internal (name) * sizeof (gunichar2));
1846 this_obj->name_len = mono_string_length_internal (name);
1848 if (permanent)
1849 this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
1851 else
1852 this_obj->name = NULL;
1854 if (!(this_obj->state & ThreadState_Stopped))
1855 tid = thread_get_tid (this_obj);
1857 UNLOCK_THREAD (this_obj);
1859 if (this_obj->name && tid) {
1860 char *tname = mono_string_to_utf8_checked_internal (name, error);
1861 return_if_nok (error);
1862 MONO_PROFILER_RAISE (thread_name, ((uintptr_t)tid, tname));
1863 mono_native_thread_set_name (tid, tname);
1864 mono_free (tname);
1868 void
1869 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1871 ERROR_DECL (error);
1872 mono_thread_set_name_internal (this_obj, name, TRUE, FALSE, error);
1873 mono_error_set_pending_exception (error);
1877 * ves_icall_System_Threading_Thread_GetPriority_internal:
1878 * @param this_obj: The MonoInternalThread on which to operate.
1880 * Gets the priority of the given thread.
1881 * @return: The priority of the given thread.
1884 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj, MonoError *error)
1886 gint32 priority;
1888 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
1890 LOCK_THREAD (internal);
1891 priority = internal->priority;
1892 UNLOCK_THREAD (internal);
1894 return priority;
1898 * ves_icall_System_Threading_Thread_SetPriority_internal:
1899 * @param this_obj: The MonoInternalThread on which to operate.
1900 * @param priority: The priority to set.
1902 * Sets the priority of the given thread.
1904 void
1905 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj, int priority, MonoError *error)
1907 MonoInternalThread *internal = thread_handle_to_internal_ptr (this_obj);
1909 LOCK_THREAD (internal);
1910 internal->priority = priority;
1911 if (internal->thread_info != NULL)
1912 mono_thread_internal_set_priority (internal, (MonoThreadPriority)priority);
1913 UNLOCK_THREAD (internal);
1916 /* If the array is already in the requested domain, we just return it,
1917 otherwise we return a copy in that domain. */
1918 static MonoArrayHandle
1919 byte_array_to_domain (MonoArrayHandle arr, MonoDomain *domain, MonoError *error)
1921 HANDLE_FUNCTION_ENTER ()
1923 if (MONO_HANDLE_IS_NULL (arr))
1924 return MONO_HANDLE_NEW (MonoArray, NULL);
1926 if (MONO_HANDLE_DOMAIN (arr) == domain)
1927 return arr;
1929 size_t const size = mono_array_handle_length (arr);
1931 // Capture arrays into common representation for repetitious code.
1932 // These two variables could also be an array of size 2 and
1933 // repitition implemented with a loop.
1934 struct {
1935 MonoArrayHandle handle;
1936 gpointer p;
1937 guint gchandle;
1939 source = { arr },
1940 dest = { mono_array_new_handle (domain, mono_defaults.byte_class, size, error) };
1941 goto_if_nok (error, exit);
1943 // Pin both arrays.
1944 source.p = mono_array_handle_pin_with_size (source.handle, size, 0, &source.gchandle);
1945 dest.p = mono_array_handle_pin_with_size (dest.handle, size, 0, &dest.gchandle);
1947 memmove (dest.p, source.p, size);
1948 exit:
1949 // Unpin both arrays.
1950 mono_gchandle_free_internal (source.gchandle);
1951 mono_gchandle_free_internal (dest.gchandle);
1953 HANDLE_FUNCTION_RETURN_REF (MonoArray, dest.handle)
1956 MonoArrayHandle
1957 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr, MonoError *error)
1959 return byte_array_to_domain (arr, mono_get_root_domain (), error);
1962 MonoArrayHandle
1963 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr, MonoError *error)
1965 return byte_array_to_domain (arr, mono_domain_get (), error);
1969 * mono_thread_current:
1971 MonoThread *
1972 mono_thread_current (void)
1974 MonoDomain *domain = mono_domain_get ();
1975 MonoInternalThread *internal = mono_thread_internal_current ();
1976 MonoThread **current_thread_ptr;
1978 g_assert (internal);
1979 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1981 if (!*current_thread_ptr) {
1982 g_assert (domain != mono_get_root_domain ());
1983 *current_thread_ptr = create_thread_object (domain, internal);
1985 return *current_thread_ptr;
1988 static MonoThreadObjectHandle
1989 mono_thread_current_handle (void)
1991 return MONO_HANDLE_NEW (MonoThreadObject, mono_thread_current ());
1994 /* Return the thread object belonging to INTERNAL in the current domain */
1995 static MonoThread *
1996 mono_thread_current_for_thread (MonoInternalThread *internal)
1998 MonoDomain *domain = mono_domain_get ();
1999 MonoThread **current_thread_ptr;
2001 g_assert (internal);
2002 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
2004 if (!*current_thread_ptr) {
2005 g_assert (domain != mono_get_root_domain ());
2006 *current_thread_ptr = create_thread_object (domain, internal);
2008 return *current_thread_ptr;
2011 MonoInternalThread*
2012 mono_thread_internal_current (void)
2014 MonoInternalThread *res = GET_CURRENT_OBJECT ();
2015 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
2016 return res;
2019 MonoInternalThreadHandle
2020 mono_thread_internal_current_handle (void)
2022 return MONO_HANDLE_NEW (MonoInternalThread, mono_thread_internal_current ());
2025 static MonoThreadInfoWaitRet
2026 mono_join_uninterrupted (MonoThreadHandle* thread_to_join, gint32 ms, MonoError *error)
2028 MonoThreadInfoWaitRet ret;
2029 gint32 wait = ms;
2031 const gint64 start = (ms == -1) ? 0 : mono_msec_ticks ();
2032 while (TRUE) {
2033 MONO_ENTER_GC_SAFE;
2034 ret = mono_thread_info_wait_one_handle (thread_to_join, wait, TRUE);
2035 MONO_EXIT_GC_SAFE;
2037 if (ret != MONO_THREAD_INFO_WAIT_RET_ALERTED)
2038 return ret;
2040 MonoException *exc = mono_thread_execute_interruption_ptr ();
2041 if (exc) {
2042 mono_error_set_exception_instance (error, exc);
2043 return ret;
2046 if (ms == -1)
2047 continue;
2049 /* Re-calculate ms according to the time passed */
2050 const gint32 diff_ms = (gint32)(mono_msec_ticks () - start);
2051 if (diff_ms >= ms) {
2052 ret = MONO_THREAD_INFO_WAIT_RET_TIMEOUT;
2053 return ret;
2055 wait = ms - diff_ms;
2058 return ret;
2061 MonoBoolean
2062 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle, int ms, MonoError *error)
2064 if (mono_thread_current_check_pending_interrupt ())
2065 return FALSE;
2067 // Internal threads are pinned so shallow coop/handle.
2068 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2069 MonoThreadHandle *handle = thread->handle;
2070 MonoInternalThread *cur_thread = mono_thread_internal_current ();
2071 gboolean ret = FALSE;
2073 LOCK_THREAD (thread);
2075 if ((thread->state & ThreadState_Unstarted) != 0) {
2076 UNLOCK_THREAD (thread);
2078 mono_error_set_exception_thread_state (error, "Thread has not been started.");
2079 return FALSE;
2082 UNLOCK_THREAD (thread);
2084 if (ms == -1)
2085 ms = MONO_INFINITE_WAIT;
2086 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, handle, ms));
2088 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
2090 ret = mono_join_uninterrupted (handle, ms, error);
2092 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
2094 if (ret == MONO_THREAD_INFO_WAIT_RET_SUCCESS_0) {
2095 THREAD_DEBUG (g_message ("%s: join successful", __func__));
2097 mono_error_assert_ok (error);
2099 /* Wait for the thread to really exit */
2100 MonoNativeThreadId tid = thread_get_tid (thread);
2101 mono_thread_join ((gpointer)(gsize)tid);
2103 return TRUE;
2106 THREAD_DEBUG (g_message ("%s: join failed", __func__));
2108 return FALSE;
2111 #define MANAGED_WAIT_FAILED 0x7fffffff
2113 static gint32
2114 map_native_wait_result_to_managed (MonoW32HandleWaitRet val, gsize numobjects)
2116 if (val >= MONO_W32HANDLE_WAIT_RET_SUCCESS_0 && val < MONO_W32HANDLE_WAIT_RET_SUCCESS_0 + numobjects) {
2117 return WAIT_OBJECT_0 + (val - MONO_W32HANDLE_WAIT_RET_SUCCESS_0);
2118 } else if (val >= MONO_W32HANDLE_WAIT_RET_ABANDONED_0 && val < MONO_W32HANDLE_WAIT_RET_ABANDONED_0 + numobjects) {
2119 return WAIT_ABANDONED_0 + (val - MONO_W32HANDLE_WAIT_RET_ABANDONED_0);
2120 } else if (val == MONO_W32HANDLE_WAIT_RET_ALERTED) {
2121 return WAIT_IO_COMPLETION;
2122 } else if (val == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
2123 return WAIT_TIMEOUT;
2124 } else if (val == MONO_W32HANDLE_WAIT_RET_FAILED) {
2125 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2126 return MANAGED_WAIT_FAILED;
2127 } else {
2128 g_error ("%s: unknown val value %d", __func__, val);
2132 gint32
2133 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer *handles, gint32 numhandles, MonoBoolean waitall, gint32 timeout, MonoError *error)
2135 /* Do this WaitSleepJoin check before creating objects */
2136 if (mono_thread_current_check_pending_interrupt ())
2137 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2139 MonoInternalThread * const thread = mono_thread_internal_current ();
2141 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2143 gint64 start = 0;
2145 if (timeout == -1)
2146 timeout = MONO_INFINITE_WAIT;
2147 if (timeout != MONO_INFINITE_WAIT)
2148 start = mono_msec_ticks ();
2150 guint32 timeoutLeft = timeout;
2152 MonoW32HandleWaitRet ret;
2154 HANDLE_LOOP_PREPARE;
2156 for (;;) {
2158 #ifdef HOST_WIN32
2159 MONO_ENTER_GC_SAFE;
2160 DWORD const wait_result = (numhandles != 1)
2161 ? mono_win32_wait_for_multiple_objects_ex (numhandles, handles, waitall, timeoutLeft, TRUE, error)
2162 : mono_win32_wait_for_single_object_ex (handles [0], timeoutLeft, TRUE);
2163 ret = mono_w32handle_convert_wait_ret (wait_result, numhandles);
2164 MONO_EXIT_GC_SAFE;
2165 #else
2166 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2167 ret = mono_w32handle_wait_multiple (handles, numhandles, waitall, timeoutLeft, TRUE, error);
2168 #endif /* HOST_WIN32 */
2170 if (ret != MONO_W32HANDLE_WAIT_RET_ALERTED)
2171 break;
2173 SETUP_ICALL_FRAME;
2175 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
2177 const gboolean interrupt = mono_thread_execute_interruption (&exc);
2179 if (interrupt)
2180 mono_error_set_exception_handle (error, exc);
2182 CLEAR_ICALL_FRAME;
2184 if (interrupt)
2185 break;
2187 if (timeout != MONO_INFINITE_WAIT) {
2188 gint64 const elapsed = mono_msec_ticks () - start;
2189 if (elapsed >= timeout) {
2190 ret = MONO_W32HANDLE_WAIT_RET_TIMEOUT;
2191 break;
2194 timeoutLeft = timeout - elapsed;
2198 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2200 return map_native_wait_result_to_managed (ret, numhandles);
2203 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2204 gint32
2205 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal, gpointer toWait, gint32 ms, MonoError *error)
2207 MonoW32HandleWaitRet ret;
2208 MonoInternalThread *thread = mono_thread_internal_current ();
2210 if (ms == -1)
2211 ms = MONO_INFINITE_WAIT;
2213 if (mono_thread_current_check_pending_interrupt ())
2214 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED, 0);
2216 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
2218 #ifdef HOST_WIN32
2219 MONO_ENTER_GC_SAFE;
2220 ret = mono_w32handle_convert_wait_ret (mono_win32_signal_object_and_wait (toSignal, toWait, ms, TRUE), 1);
2221 MONO_EXIT_GC_SAFE;
2222 #else
2223 ret = mono_w32handle_signal_and_wait (toSignal, toWait, ms, TRUE);
2224 #endif
2226 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
2228 return map_native_wait_result_to_managed (ret, 1);
2231 #endif
2233 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
2235 return mono_atomic_inc_i32 (location);
2238 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
2240 #if SIZEOF_VOID_P == 4
2241 if (G_UNLIKELY ((size_t)location & 0x7)) {
2242 gint64 ret;
2243 mono_interlocked_lock ();
2244 (*location)++;
2245 ret = *location;
2246 mono_interlocked_unlock ();
2247 return ret;
2249 #endif
2250 return mono_atomic_inc_i64 (location);
2253 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
2255 return mono_atomic_dec_i32(location);
2258 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
2260 #if SIZEOF_VOID_P == 4
2261 if (G_UNLIKELY ((size_t)location & 0x7)) {
2262 gint64 ret;
2263 mono_interlocked_lock ();
2264 (*location)--;
2265 ret = *location;
2266 mono_interlocked_unlock ();
2267 return ret;
2269 #endif
2270 return mono_atomic_dec_i64 (location);
2273 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
2275 return mono_atomic_xchg_i32(location, value);
2278 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
2280 MonoObject *res;
2281 res = (MonoObject *) mono_atomic_xchg_ptr((gpointer *) location, value);
2282 mono_gc_wbarrier_generic_nostore_internal (location);
2283 return res;
2286 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
2288 return mono_atomic_xchg_ptr(location, value);
2291 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
2293 IntFloatUnion val, ret;
2295 val.fval = value;
2296 ret.ival = mono_atomic_xchg_i32((gint32 *) location, val.ival);
2298 return ret.fval;
2301 gint64
2302 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
2304 #if SIZEOF_VOID_P == 4
2305 if (G_UNLIKELY ((size_t)location & 0x7)) {
2306 gint64 ret;
2307 mono_interlocked_lock ();
2308 ret = *location;
2309 *location = value;
2310 mono_interlocked_unlock ();
2311 return ret;
2313 #endif
2314 return mono_atomic_xchg_i64 (location, value);
2317 gdouble
2318 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
2320 LongDoubleUnion val, ret;
2322 val.fval = value;
2323 ret.ival = (gint64)mono_atomic_xchg_i64((gint64 *) location, val.ival);
2325 return ret.fval;
2328 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
2330 return mono_atomic_cas_i32(location, value, comparand);
2333 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32 *location, gint32 value, gint32 comparand, MonoBoolean *success)
2335 gint32 r = mono_atomic_cas_i32(location, value, comparand);
2336 *success = r == comparand;
2337 return r;
2340 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
2342 MonoObject *res;
2343 res = (MonoObject *) mono_atomic_cas_ptr((gpointer *) location, value, comparand);
2344 mono_gc_wbarrier_generic_nostore_internal (location);
2345 return res;
2348 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
2350 return mono_atomic_cas_ptr(location, value, comparand);
2353 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
2355 IntFloatUnion val, ret, cmp;
2357 val.fval = value;
2358 cmp.fval = comparand;
2359 ret.ival = mono_atomic_cas_i32((gint32 *) location, val.ival, cmp.ival);
2361 return ret.fval;
2364 gdouble
2365 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
2367 #if SIZEOF_VOID_P == 8
2368 LongDoubleUnion val, comp, ret;
2370 val.fval = value;
2371 comp.fval = comparand;
2372 ret.ival = (gint64)mono_atomic_cas_ptr((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2374 return ret.fval;
2375 #else
2376 gdouble old;
2378 mono_interlocked_lock ();
2379 old = *location;
2380 if (old == comparand)
2381 *location = value;
2382 mono_interlocked_unlock ();
2384 return old;
2385 #endif
2388 gint64
2389 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2391 #if SIZEOF_VOID_P == 4
2392 if (G_UNLIKELY ((size_t)location & 0x7)) {
2393 gint64 old;
2394 mono_interlocked_lock ();
2395 old = *location;
2396 if (old == comparand)
2397 *location = value;
2398 mono_interlocked_unlock ();
2399 return old;
2401 #endif
2402 return mono_atomic_cas_i64 (location, value, comparand);
2405 MonoObject*
2406 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2408 MonoObject *res;
2409 res = (MonoObject *)mono_atomic_cas_ptr ((volatile gpointer *)location, value, comparand);
2410 mono_gc_wbarrier_generic_nostore_internal (location);
2411 return res;
2414 MonoObject*
2415 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2417 MonoObject *res;
2418 MONO_CHECK_NULL (location, NULL);
2419 res = (MonoObject *)mono_atomic_xchg_ptr ((volatile gpointer *)location, value);
2420 mono_gc_wbarrier_generic_nostore_internal (location);
2421 return res;
2424 gint32
2425 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2427 return mono_atomic_add_i32 (location, value);
2430 gint64
2431 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2433 #if SIZEOF_VOID_P == 4
2434 if (G_UNLIKELY ((size_t)location & 0x7)) {
2435 gint64 ret;
2436 mono_interlocked_lock ();
2437 *location += value;
2438 ret = *location;
2439 mono_interlocked_unlock ();
2440 return ret;
2442 #endif
2443 return mono_atomic_add_i64 (location, value);
2446 gint64
2447 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2449 #if SIZEOF_VOID_P == 4
2450 if (G_UNLIKELY ((size_t)location & 0x7)) {
2451 gint64 ret;
2452 mono_interlocked_lock ();
2453 ret = *location;
2454 mono_interlocked_unlock ();
2455 return ret;
2457 #endif
2458 return mono_atomic_load_i64 (location);
2461 void
2462 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2464 mono_memory_barrier ();
2467 void
2468 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj, guint32 state, MonoError *error)
2470 // InternalThreads are always pinned, so shallowly coop-handleize.
2471 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj), (MonoThreadState)state);
2474 void
2475 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle, guint32 state, MonoError *error)
2477 // InternalThreads are always pinned, so shallowly coop-handleize.
2478 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle), (MonoThreadState)state);
2481 guint32
2482 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle, MonoError *error)
2484 // InternalThreads are always pinned, so shallowly coop-handleize.
2485 MonoInternalThread *this_obj = mono_internal_thread_handle_ptr (thread_handle);
2487 guint32 state;
2489 LOCK_THREAD (this_obj);
2491 state = this_obj->state;
2493 UNLOCK_THREAD (this_obj);
2495 return state;
2498 void
2499 ves_icall_System_Threading_Thread_Interrupt_internal (MonoThreadObjectHandle thread_handle, MonoError *error)
2501 // Internal threads are pinned so shallow coop/handle.
2502 MonoInternalThread * const thread = thread_handle_to_internal_ptr (thread_handle);
2503 MonoInternalThread * const current = mono_thread_internal_current ();
2505 LOCK_THREAD (thread);
2507 thread->thread_interrupt_requested = TRUE;
2508 gboolean const throw_ = current != thread && (thread->state & ThreadState_WaitSleepJoin);
2510 UNLOCK_THREAD (thread);
2512 if (throw_)
2513 async_abort_internal (thread, FALSE);
2517 * mono_thread_current_check_pending_interrupt:
2518 * Checks if there's a interruption request and set the pending exception if so.
2519 * \returns true if a pending exception was set
2521 gboolean
2522 mono_thread_current_check_pending_interrupt (void)
2524 MonoInternalThread *thread = mono_thread_internal_current ();
2525 gboolean throw_ = FALSE;
2527 LOCK_THREAD (thread);
2529 if (thread->thread_interrupt_requested) {
2530 throw_ = TRUE;
2531 thread->thread_interrupt_requested = FALSE;
2534 UNLOCK_THREAD (thread);
2536 if (throw_) {
2537 ERROR_DECL (error);
2538 mono_error_set_thread_interrupted (error);
2539 mono_error_set_pending_exception (error);
2541 return throw_;
2544 static gboolean
2545 request_thread_abort (MonoInternalThread *thread, MonoObjectHandle *state, gboolean appdomain_unload)
2546 // state is a pointer to a handle in order to be optional,
2547 // and be passed unspecified from functions not using handles.
2548 // When raw pointers is gone, it need not be a pointer,
2549 // though this would still work efficiently.
2551 LOCK_THREAD (thread);
2553 /* With self abort we always throw a new exception */
2554 if (thread == mono_thread_internal_current ())
2555 thread->abort_exc = NULL;
2557 if (thread->state & (ThreadState_AbortRequested | ThreadState_Stopped))
2559 UNLOCK_THREAD (thread);
2560 return FALSE;
2563 if ((thread->state & ThreadState_Unstarted) != 0) {
2564 thread->state |= ThreadState_Aborted;
2565 UNLOCK_THREAD (thread);
2566 return FALSE;
2569 thread->state |= ThreadState_AbortRequested;
2570 if (appdomain_unload)
2571 thread->flags |= MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2572 else
2573 thread->flags &= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2575 mono_gchandle_free_internal (thread->abort_state_handle);
2576 thread->abort_state_handle = 0;
2579 if (state && !MONO_HANDLE_IS_NULL (*state)) {
2580 thread->abort_state_handle = mono_gchandle_from_handle (*state, FALSE);
2581 g_assert (thread->abort_state_handle);
2584 thread->abort_exc = NULL;
2586 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));
2588 /* During shutdown, we can't wait for other threads */
2589 if (!shutting_down)
2590 /* Make sure the thread is awake */
2591 mono_thread_resume (thread);
2593 UNLOCK_THREAD (thread);
2594 return TRUE;
2597 void
2598 ves_icall_System_Threading_Thread_Abort (MonoInternalThreadHandle thread_handle, MonoObjectHandle state, MonoError *error)
2600 // InternalThreads are always pinned, so shallowly coop-handleize.
2601 MonoInternalThread * const thread = mono_internal_thread_handle_ptr (thread_handle);
2602 gboolean is_self = thread == mono_thread_internal_current ();
2604 /* For self aborts we always process the abort */
2605 if (!request_thread_abort (thread, &state, FALSE) && !is_self)
2606 return;
2608 if (is_self) {
2609 self_abort_internal (error);
2610 } else {
2611 async_abort_internal (thread, TRUE);
2616 * mono_thread_internal_abort:
2617 * Request thread \p thread to be aborted.
2618 * \p thread MUST NOT be the current thread.
2620 void
2621 mono_thread_internal_abort (MonoInternalThread *thread, gboolean appdomain_unload)
2623 g_assert (thread != mono_thread_internal_current ());
2625 if (!request_thread_abort (thread, NULL, appdomain_unload))
2626 return;
2627 async_abort_internal (thread, TRUE);
2630 void
2631 ves_icall_System_Threading_Thread_ResetAbort (MonoThreadObjectHandle this_obj, MonoError *error)
2633 MonoInternalThread *thread = mono_thread_internal_current ();
2634 gboolean was_aborting, is_domain_abort;
2636 LOCK_THREAD (thread);
2637 was_aborting = thread->state & ThreadState_AbortRequested;
2638 is_domain_abort = thread->flags & MONO_THREAD_FLAG_APPDOMAIN_ABORT;
2640 if (was_aborting && !is_domain_abort)
2641 thread->state &= ~ThreadState_AbortRequested;
2642 UNLOCK_THREAD (thread);
2644 if (!was_aborting) {
2645 mono_error_set_exception_thread_state (error, "Unable to reset abort because no abort was requested");
2646 return;
2647 } else if (is_domain_abort) {
2648 /* Silently ignore abort resets in unloading appdomains */
2649 return;
2652 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2653 thread->abort_exc = NULL;
2654 mono_gchandle_free_internal (thread->abort_state_handle);
2655 /* This is actually not necessary - the handle
2656 only counts if the exception is set */
2657 thread->abort_state_handle = 0;
2660 void
2661 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2663 LOCK_THREAD (thread);
2665 thread->state &= ~ThreadState_AbortRequested;
2667 if (thread->abort_exc) {
2668 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2669 thread->abort_exc = NULL;
2670 mono_gchandle_free_internal (thread->abort_state_handle);
2671 /* This is actually not necessary - the handle
2672 only counts if the exception is set */
2673 thread->abort_state_handle = 0;
2676 UNLOCK_THREAD (thread);
2679 MonoObjectHandle
2680 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThreadObjectHandle this_obj, MonoError *error)
2682 MonoInternalThread *thread = thread_handle_to_internal_ptr (this_obj);
2684 if (!thread->abort_state_handle)
2685 return NULL_HANDLE; // No state. No error.
2687 // Convert gc handle to coop handle.
2688 MonoObjectHandle state = mono_gchandle_get_target_handle (thread->abort_state_handle);
2689 g_assert (MONO_HANDLE_BOOL (state));
2691 MonoDomain *domain = mono_domain_get ();
2692 if (MONO_HANDLE_DOMAIN (state) == domain)
2693 return state; // No need to cross domain, return state directly.
2695 // Attempt move state cross-domain.
2696 MonoObjectHandle deserialized = mono_object_xdomain_representation (state, domain, error);
2698 // If deserialized is null, there must be an error, and vice versa.
2699 g_assert (is_ok (error) == MONO_HANDLE_BOOL (deserialized));
2701 if (MONO_HANDLE_BOOL (deserialized))
2702 return deserialized; // Cross-domain serialization succeeded. Return it.
2704 // Wrap error in InvalidOperationException.
2705 ERROR_DECL (error_creating_exception);
2706 MonoExceptionHandle invalid_op_exc = mono_exception_new_invalid_operation (
2707 "Thread.ExceptionState cannot access an ExceptionState from a different AppDomain", error_creating_exception);
2708 mono_error_assert_ok (error_creating_exception);
2709 g_assert (!is_ok (error) && 1);
2710 MONO_HANDLE_SET (invalid_op_exc, inner_ex, mono_error_convert_to_exception_handle (error));
2711 error_init_reuse (error);
2712 mono_error_set_exception_handle (error, invalid_op_exc);
2713 g_assert (!is_ok (error) && 2);
2715 // There is state, but we failed to return it.
2716 return NULL_HANDLE;
2719 static gboolean
2720 mono_thread_suspend (MonoInternalThread *thread)
2722 LOCK_THREAD (thread);
2724 if (thread->state & (ThreadState_Unstarted | ThreadState_Aborted | ThreadState_Stopped))
2726 UNLOCK_THREAD (thread);
2727 return FALSE;
2730 if (thread->state & (ThreadState_Suspended | ThreadState_SuspendRequested | ThreadState_AbortRequested))
2732 UNLOCK_THREAD (thread);
2733 return TRUE;
2736 thread->state |= ThreadState_SuspendRequested;
2737 MONO_ENTER_GC_SAFE;
2738 mono_os_event_reset (thread->suspended);
2739 MONO_EXIT_GC_SAFE;
2741 if (thread == mono_thread_internal_current ()) {
2742 /* calls UNLOCK_THREAD (thread) */
2743 self_suspend_internal ();
2744 } else {
2745 /* calls UNLOCK_THREAD (thread) */
2746 async_suspend_internal (thread, FALSE);
2749 return TRUE;
2752 void
2753 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj, MonoError *error)
2755 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj)))
2756 mono_error_set_exception_thread_not_started_or_dead (error);
2760 /* LOCKING: LOCK_THREAD(thread) must be held */
2761 static gboolean
2762 mono_thread_resume (MonoInternalThread *thread)
2764 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2765 // g_async_safe_printf ("RESUME (1) thread %p\n", thread_get_tid (thread));
2766 thread->state &= ~ThreadState_SuspendRequested;
2767 MONO_ENTER_GC_SAFE;
2768 mono_os_event_set (thread->suspended);
2769 MONO_EXIT_GC_SAFE;
2770 return TRUE;
2773 if ((thread->state & ThreadState_Suspended) == 0 ||
2774 (thread->state & ThreadState_Unstarted) != 0 ||
2775 (thread->state & ThreadState_Aborted) != 0 ||
2776 (thread->state & ThreadState_Stopped) != 0)
2778 // g_async_safe_printf ("RESUME (2) thread %p\n", thread_get_tid (thread));
2779 return FALSE;
2782 // g_async_safe_printf ("RESUME (3) thread %p\n", thread_get_tid (thread));
2784 MONO_ENTER_GC_SAFE;
2785 mono_os_event_set (thread->suspended);
2786 MONO_EXIT_GC_SAFE;
2788 if (!thread->self_suspended) {
2789 UNLOCK_THREAD (thread);
2791 /* Awake the thread */
2792 if (!mono_thread_info_resume (thread_get_tid (thread)))
2793 return FALSE;
2795 LOCK_THREAD (thread);
2798 thread->state &= ~ThreadState_Suspended;
2800 return TRUE;
2803 void
2804 ves_icall_System_Threading_Thread_Resume (MonoThreadObjectHandle thread_handle, MonoError *error)
2806 // Internal threads are pinned so shallow coop/handle.
2807 MonoInternalThread * const internal_thread = thread_handle_to_internal_ptr (thread_handle);
2808 gboolean exception = FALSE;
2810 if (!internal_thread) {
2811 exception = TRUE;
2812 } else {
2813 LOCK_THREAD (internal_thread);
2814 if (!mono_thread_resume (internal_thread))
2815 exception = TRUE;
2816 UNLOCK_THREAD (internal_thread);
2819 if (exception)
2820 mono_error_set_exception_thread_not_started_or_dead (error);
2823 gboolean
2824 mono_threads_is_critical_method (MonoMethod *method)
2826 switch (method->wrapper_type) {
2827 case MONO_WRAPPER_RUNTIME_INVOKE:
2828 case MONO_WRAPPER_XDOMAIN_INVOKE:
2829 case MONO_WRAPPER_XDOMAIN_DISPATCH:
2830 return TRUE;
2832 return FALSE;
2835 static gboolean
2836 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2838 if (managed)
2839 return TRUE;
2841 if (mono_threads_is_critical_method (m)) {
2842 *((gboolean*)data) = TRUE;
2843 return TRUE;
2845 return FALSE;
2848 static gboolean
2849 is_running_protected_wrapper (void)
2851 gboolean found = FALSE;
2852 mono_stack_walk (find_wrapper, &found);
2853 return found;
2857 * mono_thread_stop:
2859 void
2860 mono_thread_stop (MonoThread *thread)
2862 MonoInternalThread *internal = thread->internal_thread;
2864 if (!request_thread_abort (internal, NULL, FALSE))
2865 return;
2867 if (internal == mono_thread_internal_current ()) {
2868 ERROR_DECL (error);
2869 self_abort_internal (error);
2871 This function is part of the embeding API and has no way to return the exception
2872 to be thrown. So what we do is keep the old behavior and raise the exception.
2874 mono_error_raise_exception_deprecated (error); /* OK to throw, see note */
2875 } else {
2876 async_abort_internal (internal, TRUE);
2880 gint8
2881 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2883 gint8 tmp = *(volatile gint8 *)ptr;
2884 mono_memory_barrier ();
2885 return tmp;
2888 gint16
2889 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2891 gint16 tmp = *(volatile gint16 *)ptr;
2892 mono_memory_barrier ();
2893 return tmp;
2896 gint32
2897 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2899 gint32 tmp = *(volatile gint32 *)ptr;
2900 mono_memory_barrier ();
2901 return tmp;
2904 gint64
2905 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2907 gint64 tmp = *(volatile gint64 *)ptr;
2908 mono_memory_barrier ();
2909 return tmp;
2912 void *
2913 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2915 volatile void *tmp = *(volatile void **)ptr;
2916 mono_memory_barrier ();
2917 return (void *) tmp;
2920 void *
2921 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr)
2923 volatile MonoObject *tmp = *(volatile MonoObject **)ptr;
2924 mono_memory_barrier ();
2925 return (MonoObject *) tmp;
2928 double
2929 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr)
2931 double tmp = *(volatile double *)ptr;
2932 mono_memory_barrier ();
2933 return tmp;
2936 float
2937 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr)
2939 float tmp = *(volatile float *)ptr;
2940 mono_memory_barrier ();
2941 return tmp;
2944 gint8
2945 ves_icall_System_Threading_Volatile_Read1 (void *ptr)
2947 return mono_atomic_load_i8 ((volatile gint8 *)ptr);
2950 gint16
2951 ves_icall_System_Threading_Volatile_Read2 (void *ptr)
2953 return mono_atomic_load_i16 ((volatile gint16 *)ptr);
2956 gint32
2957 ves_icall_System_Threading_Volatile_Read4 (void *ptr)
2959 return mono_atomic_load_i32 ((volatile gint32 *)ptr);
2962 gint64
2963 ves_icall_System_Threading_Volatile_Read8 (void *ptr)
2965 #if SIZEOF_VOID_P == 4
2966 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2967 gint64 val;
2968 mono_interlocked_lock ();
2969 val = *(gint64*)ptr;
2970 mono_interlocked_unlock ();
2971 return val;
2973 #endif
2974 return mono_atomic_load_i64 ((volatile gint64 *)ptr);
2977 void *
2978 ves_icall_System_Threading_Volatile_ReadIntPtr (void *ptr)
2980 return mono_atomic_load_ptr ((volatile gpointer *)ptr);
2983 double
2984 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr)
2986 LongDoubleUnion u;
2988 #if SIZEOF_VOID_P == 4
2989 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
2990 double val;
2991 mono_interlocked_lock ();
2992 val = *(double*)ptr;
2993 mono_interlocked_unlock ();
2994 return val;
2996 #endif
2998 u.ival = mono_atomic_load_i64 ((volatile gint64 *)ptr);
3000 return u.fval;
3003 float
3004 ves_icall_System_Threading_Volatile_ReadFloat (void *ptr)
3006 IntFloatUnion u;
3008 u.ival = mono_atomic_load_i32 ((volatile gint32 *)ptr);
3010 return u.fval;
3013 MonoObject*
3014 ves_icall_System_Threading_Volatile_Read_T (void *ptr)
3016 return (MonoObject *)mono_atomic_load_ptr ((volatile gpointer *)ptr);
3019 void
3020 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
3022 mono_memory_barrier ();
3023 *(volatile gint8 *)ptr = value;
3026 void
3027 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
3029 mono_memory_barrier ();
3030 *(volatile gint16 *)ptr = value;
3033 void
3034 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
3036 mono_memory_barrier ();
3037 *(volatile gint32 *)ptr = value;
3040 void
3041 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
3043 mono_memory_barrier ();
3044 *(volatile gint64 *)ptr = value;
3047 void
3048 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
3050 mono_memory_barrier ();
3051 *(volatile void **)ptr = value;
3054 void
3055 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, MonoObject *value)
3057 mono_memory_barrier ();
3058 mono_gc_wbarrier_generic_store_internal (ptr, value);
3061 void
3062 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr, double value)
3064 mono_memory_barrier ();
3065 *(volatile double *)ptr = value;
3068 void
3069 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr, float value)
3071 mono_memory_barrier ();
3072 *(volatile float *)ptr = value;
3075 void
3076 ves_icall_System_Threading_Volatile_Write1 (void *ptr, gint8 value)
3078 mono_atomic_store_i8 ((volatile gint8 *)ptr, value);
3081 void
3082 ves_icall_System_Threading_Volatile_Write2 (void *ptr, gint16 value)
3084 mono_atomic_store_i16 ((volatile gint16 *)ptr, value);
3087 void
3088 ves_icall_System_Threading_Volatile_Write4 (void *ptr, gint32 value)
3090 mono_atomic_store_i32 ((volatile gint32 *)ptr, value);
3093 void
3094 ves_icall_System_Threading_Volatile_Write8 (void *ptr, gint64 value)
3096 #if SIZEOF_VOID_P == 4
3097 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3098 mono_interlocked_lock ();
3099 *(gint64*)ptr = value;
3100 mono_interlocked_unlock ();
3101 return;
3103 #endif
3105 mono_atomic_store_i64 ((volatile gint64 *)ptr, value);
3108 void
3109 ves_icall_System_Threading_Volatile_WriteIntPtr (void *ptr, void *value)
3111 mono_atomic_store_ptr ((volatile gpointer *)ptr, value);
3114 void
3115 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr, double value)
3117 LongDoubleUnion u;
3119 #if SIZEOF_VOID_P == 4
3120 if (G_UNLIKELY ((size_t)ptr & 0x7)) {
3121 mono_interlocked_lock ();
3122 *(double*)ptr = value;
3123 mono_interlocked_unlock ();
3124 return;
3126 #endif
3128 u.fval = value;
3130 mono_atomic_store_i64 ((volatile gint64 *)ptr, u.ival);
3133 void
3134 ves_icall_System_Threading_Volatile_WriteFloat (void *ptr, float value)
3136 IntFloatUnion u;
3138 u.fval = value;
3140 mono_atomic_store_i32 ((volatile gint32 *)ptr, u.ival);
3143 void
3144 ves_icall_System_Threading_Volatile_Write_T (void *ptr, MonoObject *value)
3146 mono_gc_wbarrier_generic_store_atomic_internal (ptr, value);
3149 static void
3150 free_context (void *user_data)
3152 ContextStaticData *data = (ContextStaticData*)user_data;
3154 mono_threads_lock ();
3157 * There is no guarantee that, by the point this reference queue callback
3158 * has been invoked, the GC handle associated with the object will fail to
3159 * resolve as one might expect. So if we don't free and remove the GC
3160 * handle here, free_context_static_data_helper () could end up resolving
3161 * a GC handle to an actually-dead context which would contain a pointer
3162 * to an already-freed static data segment, resulting in a crash when
3163 * accessing it.
3165 g_hash_table_remove (contexts, GUINT_TO_POINTER (data->gc_handle));
3167 mono_threads_unlock ();
3169 mono_gchandle_free_internal (data->gc_handle);
3170 mono_free_static_data (data->static_data);
3171 g_free (data);
3174 void
3175 mono_threads_register_app_context (MonoAppContextHandle ctx, MonoError *error)
3177 error_init (error);
3178 mono_threads_lock ();
3180 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3182 if (!contexts)
3183 contexts = g_hash_table_new (NULL, NULL);
3185 if (!context_queue)
3186 context_queue = mono_gc_reference_queue_new_internal (free_context);
3188 gpointer gch = GUINT_TO_POINTER (mono_gchandle_new_weakref_from_handle (MONO_HANDLE_CAST (MonoObject, ctx)));
3189 g_hash_table_insert (contexts, gch, gch);
3192 * We use this intermediate structure to contain a duplicate pointer to
3193 * the static data because we can't rely on being able to resolve the GC
3194 * handle in the reference queue callback.
3196 ContextStaticData *data = g_new0 (ContextStaticData, 1);
3197 data->gc_handle = GPOINTER_TO_UINT (gch);
3198 MONO_HANDLE_SETVAL (ctx, data, ContextStaticData*, data);
3200 context_adjust_static_data (ctx);
3201 mono_gc_reference_queue_add_handle (context_queue, ctx, data);
3203 mono_threads_unlock ();
3205 MONO_PROFILER_RAISE (context_loaded, (MONO_HANDLE_RAW (ctx)));
3208 void
3209 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx, MonoError *error)
3211 mono_threads_register_app_context (ctx, error);
3214 void
3215 mono_threads_release_app_context (MonoAppContext* ctx, MonoError *error)
3218 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3219 * cleanup in exceptional circumstances, we don't actually do any
3220 * cleanup work here. We instead do this via a reference queue.
3223 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3225 MONO_PROFILER_RAISE (context_unloaded, (ctx));
3228 void
3229 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx, MonoError *error)
3231 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx), error); /* FIXME use handles in mono_threads_release_app_context */
3234 void mono_thread_init (MonoThreadStartCB start_cb,
3235 MonoThreadAttachCB attach_cb)
3237 mono_coop_mutex_init_recursive (&threads_mutex);
3239 mono_os_mutex_init_recursive(&interlocked_mutex);
3240 mono_coop_mutex_init_recursive(&joinable_threads_mutex);
3242 mono_os_event_init (&background_change_event, FALSE);
3244 mono_coop_cond_init (&pending_native_thread_join_calls_event);
3245 mono_coop_cond_init (&zero_pending_joinable_thread_event);
3247 mono_init_static_data_info (&thread_static_info);
3248 mono_init_static_data_info (&context_static_info);
3250 mono_thread_start_cb = start_cb;
3251 mono_thread_attach_cb = attach_cb;
3255 static gpointer
3256 thread_attach (MonoThreadInfo *info)
3258 return mono_gc_thread_attach (info);
3261 static void
3262 thread_detach (MonoThreadInfo *info)
3264 MonoInternalThread *internal;
3265 guint32 gchandle;
3267 /* If a delegate is passed to native code and invoked on a thread we dont
3268 * know about, marshal will register it with mono_threads_attach_coop, but
3269 * we have no way of knowing when that thread goes away. SGen has a TSD
3270 * so we assume that if the domain is still registered, we can detach
3271 * the thread */
3273 g_assert (info);
3274 g_assert (mono_thread_info_is_current (info));
3276 if (!mono_thread_info_try_get_internal_thread_gchandle (info, &gchandle))
3277 return;
3279 internal = (MonoInternalThread*) mono_gchandle_get_target_internal (gchandle);
3280 g_assert (internal);
3282 mono_thread_detach_internal (internal);
3285 static void
3286 thread_detach_with_lock (MonoThreadInfo *info)
3288 mono_gc_thread_detach_with_lock (info);
3291 static gboolean
3292 thread_in_critical_region (MonoThreadInfo *info)
3294 return mono_gc_thread_in_critical_region (info);
3297 static gboolean
3298 ip_in_critical_region (MonoDomain *domain, gpointer ip)
3300 MonoJitInfo *ji;
3301 MonoMethod *method;
3304 * We pass false for 'try_aot' so this becomes async safe.
3305 * It won't find aot methods whose jit info is not yet loaded,
3306 * so we preload their jit info in the JIT.
3308 ji = mono_jit_info_table_find_internal (domain, ip, FALSE, FALSE);
3309 if (!ji)
3310 return FALSE;
3312 method = mono_jit_info_get_method (ji);
3313 g_assert (method);
3315 return mono_gc_is_critical_method (method);
3318 static void
3319 thread_flags_changing (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3321 mono_gc_skip_thread_changing (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3324 static void
3325 thread_flags_changed (MonoThreadInfoFlags old, MonoThreadInfoFlags new_)
3327 mono_gc_skip_thread_changed (!!(new_ & MONO_THREAD_INFO_FLAGS_NO_GC));
3330 void
3331 mono_thread_callbacks_init (void)
3333 MonoThreadInfoCallbacks cb;
3335 memset (&cb, 0, sizeof(cb));
3336 cb.thread_attach = thread_attach;
3337 cb.thread_detach = thread_detach;
3338 cb.thread_detach_with_lock = thread_detach_with_lock;
3339 cb.ip_in_critical_region = ip_in_critical_region;
3340 cb.thread_in_critical_region = thread_in_critical_region;
3341 cb.thread_flags_changing = thread_flags_changing;
3342 cb.thread_flags_changed = thread_flags_changed;
3343 mono_thread_info_callbacks_init (&cb);
3347 * mono_thread_cleanup:
3349 void
3350 mono_thread_cleanup (void)
3352 /* Wait for pending threads to park on joinable threads list */
3353 /* NOTE, waiting on this should be extremely rare and will only happen */
3354 /* under certain specific conditions. */
3355 gboolean wait_result = threads_wait_pending_joinable_threads (2000);
3356 if (!wait_result)
3357 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3359 mono_threads_join_threads ();
3361 #if !defined(HOST_WIN32)
3362 /* The main thread must abandon any held mutexes (particularly
3363 * important for named mutexes as they are shared across
3364 * processes, see bug 74680.) This will happen when the
3365 * thread exits, but if it's not running in a subthread it
3366 * won't exit in time.
3368 if (!mono_runtime_get_no_exec ())
3369 mono_w32mutex_abandon (mono_thread_internal_current ());
3370 #endif
3372 #if 0
3373 /* This stuff needs more testing, it seems one of these
3374 * critical sections can be locked when mono_thread_cleanup is
3375 * called.
3377 mono_coop_mutex_destroy (&threads_mutex);
3378 mono_os_mutex_destroy (&interlocked_mutex);
3379 mono_os_mutex_destroy (&delayed_free_table_mutex);
3380 mono_os_mutex_destroy (&small_id_mutex);
3381 mono_coop_cond_destroy (&zero_pending_joinable_thread_event);
3382 mono_coop_cond_destroy (&pending_native_thread_join_calls_event);
3383 mono_os_event_destroy (&background_change_event);
3384 #endif
3387 void
3388 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
3390 mono_thread_cleanup_fn = func;
3394 * mono_thread_set_manage_callback:
3396 void
3397 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
3399 thread->internal_thread->manage_callback = func;
3402 G_GNUC_UNUSED
3403 static void print_tids (gpointer key, gpointer value, gpointer user)
3405 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3406 * sizeof(uint) and a cast to uint would overflow
3408 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3409 * print this as a pointer.
3411 g_message ("Waiting for: %p", key);
3414 struct wait_data
3416 MonoThreadHandle *handles[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3417 MonoInternalThread *threads[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS];
3418 guint32 num;
3421 static void
3422 wait_for_tids (struct wait_data *wait, guint32 timeout, gboolean check_state_change)
3424 guint32 i;
3425 MonoThreadInfoWaitRet ret;
3427 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
3429 /* Add the thread state change event, so it wakes
3430 * up if a thread changes to background mode. */
3432 MONO_ENTER_GC_SAFE;
3433 if (check_state_change)
3434 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, &background_change_event, FALSE, timeout, TRUE);
3435 else
3436 ret = mono_thread_info_wait_multiple_handle (wait->handles, wait->num, NULL, TRUE, timeout, TRUE);
3437 MONO_EXIT_GC_SAFE;
3439 if (ret == MONO_THREAD_INFO_WAIT_RET_FAILED) {
3440 /* See the comment in build_wait_tids() */
3441 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
3442 return;
3445 for( i = 0; i < wait->num; i++)
3446 mono_threads_close_thread_handle (wait->handles [i]);
3448 if (ret >= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 && ret < (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0 + wait->num)) {
3449 MonoInternalThread *internal;
3451 internal = wait->threads [ret - MONO_THREAD_INFO_WAIT_RET_SUCCESS_0];
3453 mono_threads_lock ();
3454 if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
3455 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
3456 mono_threads_unlock ();
3460 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
3462 struct wait_data *wait=(struct wait_data *)user;
3464 if(wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS - 1) {
3465 MonoInternalThread *thread=(MonoInternalThread *)value;
3467 /* Ignore background threads, we abort them later */
3468 /* Do not lock here since it is not needed and the caller holds threads_lock */
3469 if (thread->state & ThreadState_Background) {
3470 THREAD_DEBUG (g_message ("%s: ignoring background thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3471 return; /* just leave, ignore */
3474 if (mono_gc_is_finalizer_internal_thread (thread)) {
3475 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3476 return;
3479 if (thread == mono_thread_internal_current ()) {
3480 THREAD_DEBUG (g_message ("%s: ignoring current thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3481 return;
3484 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
3485 THREAD_DEBUG (g_message ("%s: ignoring main thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3486 return;
3489 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
3490 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
3491 return;
3494 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
3495 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
3496 wait->handles[wait->num]=mono_threads_open_thread_handle (thread->handle);
3497 wait->threads[wait->num]=thread;
3498 wait->num++;
3500 THREAD_DEBUG (g_message ("%s: adding thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3501 } else {
3502 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %" G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
3506 } else {
3507 /* Just ignore the rest, we can't do anything with
3508 * them yet
3513 static void
3514 abort_threads (gpointer key, gpointer value, gpointer user)
3516 struct wait_data *wait=(struct wait_data *)user;
3517 MonoNativeThreadId self = mono_native_thread_id_get ();
3518 MonoInternalThread *thread = (MonoInternalThread *)value;
3520 if (wait->num >= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS)
3521 return;
3523 if (mono_native_thread_id_equals (thread_get_tid (thread), self))
3524 return;
3525 if (mono_gc_is_finalizer_internal_thread (thread))
3526 return;
3528 if ((thread->flags & MONO_THREAD_FLAG_DONT_MANAGE))
3529 return;
3531 wait->handles[wait->num] = mono_threads_open_thread_handle (thread->handle);
3532 wait->threads[wait->num] = thread;
3533 wait->num++;
3535 THREAD_DEBUG (g_print ("%s: Aborting id: %" G_GSIZE_FORMAT "\n", __func__, (gsize)thread->tid));
3536 mono_thread_internal_abort (thread, FALSE);
3539 /**
3540 * mono_threads_set_shutting_down:
3542 * Is called by a thread that wants to shut down Mono. If the runtime is already
3543 * shutting down, the calling thread is suspended/stopped, and this function never
3544 * returns.
3546 void
3547 mono_threads_set_shutting_down (void)
3549 MonoInternalThread *current_thread = mono_thread_internal_current ();
3551 mono_threads_lock ();
3553 if (shutting_down) {
3554 mono_threads_unlock ();
3556 /* Make sure we're properly suspended/stopped */
3558 LOCK_THREAD (current_thread);
3560 if (current_thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
3561 UNLOCK_THREAD (current_thread);
3562 mono_thread_execute_interruption_void ();
3563 } else {
3564 UNLOCK_THREAD (current_thread);
3567 /*since we're killing the thread, detach it.*/
3568 mono_thread_detach_internal (current_thread);
3570 /* Wake up other threads potentially waiting for us */
3571 mono_thread_info_exit (0);
3572 } else {
3573 shutting_down = TRUE;
3575 /* Not really a background state change, but this will
3576 * interrupt the main thread if it is waiting for all
3577 * the other threads.
3579 MONO_ENTER_GC_SAFE;
3580 mono_os_event_set (&background_change_event);
3581 MONO_EXIT_GC_SAFE;
3583 mono_threads_unlock ();
3588 * mono_thread_manage:
3590 void
3591 mono_thread_manage (void)
3593 struct wait_data wait_data;
3594 struct wait_data *wait = &wait_data;
3596 memset (wait, 0, sizeof (struct wait_data));
3597 /* join each thread that's still running */
3598 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
3600 mono_threads_lock ();
3601 if(threads==NULL) {
3602 THREAD_DEBUG (g_message("%s: No threads", __func__));
3603 mono_threads_unlock ();
3604 return;
3607 mono_threads_unlock ();
3609 do {
3610 mono_threads_lock ();
3611 if (shutting_down) {
3612 /* somebody else is shutting down */
3613 mono_threads_unlock ();
3614 break;
3616 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
3617 mono_g_hash_table_foreach (threads, print_tids, NULL));
3619 MONO_ENTER_GC_SAFE;
3620 mono_os_event_reset (&background_change_event);
3621 MONO_EXIT_GC_SAFE;
3622 wait->num=0;
3623 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3624 memset (wait->threads, 0, sizeof (wait->threads));
3625 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
3626 mono_threads_unlock ();
3627 if (wait->num > 0)
3628 /* Something to wait for */
3629 wait_for_tids (wait, MONO_INFINITE_WAIT, TRUE);
3630 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
3631 } while(wait->num>0);
3633 /* Mono is shutting down, so just wait for the end */
3634 if (!mono_runtime_try_shutdown ()) {
3635 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3636 mono_thread_suspend (mono_thread_internal_current ());
3637 mono_thread_execute_interruption_void ();
3641 * Remove everything but the finalizer thread and self.
3642 * Also abort all the background threads
3643 * */
3644 do {
3645 mono_threads_lock ();
3647 wait->num = 0;
3648 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3649 memset (wait->threads, 0, sizeof (wait->threads));
3650 mono_g_hash_table_foreach (threads, abort_threads, wait);
3652 mono_threads_unlock ();
3654 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3655 if (wait->num > 0) {
3656 /* Something to wait for */
3657 wait_for_tids (wait, MONO_INFINITE_WAIT, FALSE);
3659 } while (wait->num > 0);
3662 * give the subthreads a chance to really quit (this is mainly needed
3663 * to get correct user and system times from getrusage/wait/time(1)).
3664 * This could be removed if we avoid pthread_detach() and use pthread_join().
3666 mono_thread_info_yield ();
3669 static void
3670 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3672 MonoInternalThread *thread = (MonoInternalThread*)value;
3673 struct wait_data *wait = (struct wait_data*)user_data;
3676 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3677 * limitation.
3678 * This needs no locking.
3680 if ((thread->state & ThreadState_Suspended) != 0 ||
3681 (thread->state & ThreadState_Stopped) != 0)
3682 return;
3684 if (wait->num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
3685 wait->handles [wait->num] = mono_threads_open_thread_handle (thread->handle);
3686 wait->threads [wait->num] = thread;
3687 wait->num++;
3692 * mono_thread_suspend_all_other_threads:
3694 * Suspend all managed threads except the finalizer thread and this thread. It is
3695 * not possible to resume them later.
3697 void mono_thread_suspend_all_other_threads (void)
3699 struct wait_data wait_data;
3700 struct wait_data *wait = &wait_data;
3701 int i;
3702 MonoNativeThreadId self = mono_native_thread_id_get ();
3703 guint32 eventidx = 0;
3704 gboolean starting, finished;
3706 memset (wait, 0, sizeof (struct wait_data));
3708 * The other threads could be in an arbitrary state at this point, i.e.
3709 * they could be starting up, shutting down etc. This means that there could be
3710 * threads which are not even in the threads hash table yet.
3714 * First we set a barrier which will be checked by all threads before they
3715 * are added to the threads hash table, and they will exit if the flag is set.
3716 * This ensures that no threads could be added to the hash later.
3717 * We will use shutting_down as the barrier for now.
3719 g_assert (shutting_down);
3722 * We make multiple calls to WaitForMultipleObjects since:
3723 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3724 * - some threads could exit without becoming suspended
3726 finished = FALSE;
3727 while (!finished) {
3729 * Make a copy of the hashtable since we can't do anything with
3730 * threads while threads_mutex is held.
3732 wait->num = 0;
3733 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3734 memset (wait->threads, 0, sizeof (wait->threads));
3735 mono_threads_lock ();
3736 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3737 mono_threads_unlock ();
3739 eventidx = 0;
3740 /* Get the suspended events that we'll be waiting for */
3741 for (i = 0; i < wait->num; ++i) {
3742 MonoInternalThread *thread = wait->threads [i];
3744 if (mono_native_thread_id_equals (thread_get_tid (thread), self)
3745 || mono_gc_is_finalizer_internal_thread (thread)
3746 || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)
3748 mono_threads_close_thread_handle (wait->handles [i]);
3749 wait->threads [i] = NULL;
3750 continue;
3753 LOCK_THREAD (thread);
3755 if (thread->state & (ThreadState_Suspended | ThreadState_Stopped)) {
3756 UNLOCK_THREAD (thread);
3757 mono_threads_close_thread_handle (wait->handles [i]);
3758 wait->threads [i] = NULL;
3759 continue;
3762 ++eventidx;
3764 /* Convert abort requests into suspend requests */
3765 if ((thread->state & ThreadState_AbortRequested) != 0)
3766 thread->state &= ~ThreadState_AbortRequested;
3768 thread->state |= ThreadState_SuspendRequested;
3769 MONO_ENTER_GC_SAFE;
3770 mono_os_event_reset (thread->suspended);
3771 MONO_EXIT_GC_SAFE;
3773 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3774 async_suspend_internal (thread, TRUE);
3776 mono_threads_close_thread_handle (wait->handles [i]);
3777 wait->threads [i] = NULL;
3779 if (eventidx <= 0) {
3781 * If there are threads which are starting up, we wait until they
3782 * are suspended when they try to register in the threads hash.
3783 * This is guaranteed to finish, since the threads which can create new
3784 * threads get suspended after a while.
3785 * FIXME: The finalizer thread can still create new threads.
3787 mono_threads_lock ();
3788 if (threads_starting_up)
3789 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3790 else
3791 starting = FALSE;
3792 mono_threads_unlock ();
3793 if (starting)
3794 mono_thread_info_sleep (100, NULL);
3795 else
3796 finished = TRUE;
3801 typedef struct {
3802 MonoInternalThread *thread;
3803 MonoStackFrameInfo *frames;
3804 int nframes, max_frames;
3805 int nthreads, max_threads;
3806 MonoInternalThread **threads;
3807 } ThreadDumpUserData;
3809 static gboolean thread_dump_requested;
3811 /* This needs to be async safe */
3812 static gboolean
3813 collect_frame (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
3815 ThreadDumpUserData *ud = (ThreadDumpUserData *)data;
3817 if (ud->nframes < ud->max_frames) {
3818 memcpy (&ud->frames [ud->nframes], frame, sizeof (MonoStackFrameInfo));
3819 ud->nframes ++;
3822 return FALSE;
3825 /* This needs to be async safe */
3826 static SuspendThreadResult
3827 get_thread_dump (MonoThreadInfo *info, gpointer ud)
3829 ThreadDumpUserData *user_data = (ThreadDumpUserData *)ud;
3830 MonoInternalThread *thread = user_data->thread;
3832 #if 0
3833 /* This no longer works with remote unwinding */
3834 g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
3835 mono_thread_internal_describe (thread, text);
3836 g_string_append (text, "\n");
3837 #endif
3839 if (thread == mono_thread_internal_current ())
3840 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame, NULL, MONO_UNWIND_SIGNAL_SAFE, ud);
3841 else
3842 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, ud);
3844 return MonoResumeThread;
3847 typedef struct {
3848 int nthreads, max_threads;
3850 guint32 *threads;
3851 } CollectThreadsUserData;
3853 typedef struct {
3854 int nthreads, max_threads;
3855 MonoNativeThreadId *threads;
3856 } CollectThreadIdsUserData;
3858 static void
3859 collect_thread (gpointer key, gpointer value, gpointer user)
3861 CollectThreadsUserData *ud = (CollectThreadsUserData *)user;
3862 MonoInternalThread *thread = (MonoInternalThread *)value;
3864 if (ud->nthreads < ud->max_threads)
3865 ud->threads [ud->nthreads ++] = mono_gchandle_new_internal (&thread->obj, TRUE);
3868 static void
3869 collect_thread_id (gpointer key, gpointer value, gpointer user)
3871 CollectThreadIdsUserData *ud = (CollectThreadIdsUserData *)user;
3872 MonoInternalThread *thread = (MonoInternalThread *)value;
3874 if (ud->nthreads < ud->max_threads)
3875 ud->threads [ud->nthreads ++] = thread_get_tid (thread);
3879 * Collect running threads into the THREADS array.
3880 * THREADS should be an array allocated on the stack.
3882 static int
3883 collect_threads (guint32 *thread_handles, int max_threads)
3885 CollectThreadsUserData ud;
3887 mono_memory_barrier ();
3888 if (!threads)
3889 return 0;
3891 memset (&ud, 0, sizeof (ud));
3892 /* This array contains refs, but its on the stack, so its ok */
3893 ud.threads = thread_handles;
3894 ud.max_threads = max_threads;
3896 mono_threads_lock ();
3897 mono_g_hash_table_foreach (threads, collect_thread, &ud);
3898 mono_threads_unlock ();
3900 return ud.nthreads;
3903 static int
3904 collect_thread_ids (MonoNativeThreadId *thread_ids, int max_threads)
3906 CollectThreadIdsUserData ud;
3908 mono_memory_barrier ();
3909 if (!threads)
3910 return 0;
3912 memset (&ud, 0, sizeof (ud));
3913 /* This array contains refs, but its on the stack, so its ok */
3914 ud.threads = thread_ids;
3915 ud.max_threads = max_threads;
3917 mono_threads_lock ();
3918 mono_g_hash_table_foreach (threads, collect_thread_id, &ud);
3919 mono_threads_unlock ();
3921 return ud.nthreads;
3924 static void
3925 dump_thread (MonoInternalThread *thread, ThreadDumpUserData *ud, FILE* output_file)
3927 GString* text = g_string_new (0);
3928 char *name;
3929 GError *gerror = NULL;
3930 int i;
3932 ud->thread = thread;
3933 ud->nframes = 0;
3935 /* Collect frames for the thread */
3936 if (thread == mono_thread_internal_current ()) {
3937 get_thread_dump (mono_thread_info_current (), ud);
3938 } else {
3939 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, ud);
3943 * Do all the non async-safe work outside of get_thread_dump.
3945 if (thread->name) {
3946 name = g_utf16_to_utf8 (thread->name, thread->name_len, NULL, NULL, &gerror);
3947 g_assert (!gerror);
3948 g_string_append_printf (text, "\n\"%s\"", name);
3949 g_free (name);
3951 else if (thread->threadpool_thread) {
3952 g_string_append (text, "\n\"<threadpool thread>\"");
3953 } else {
3954 g_string_append (text, "\n\"<unnamed thread>\"");
3957 for (i = 0; i < ud->nframes; ++i) {
3958 MonoStackFrameInfo *frame = &ud->frames [i];
3959 MonoMethod *method = NULL;
3961 if (frame->type == FRAME_TYPE_MANAGED)
3962 method = mono_jit_info_get_method (frame->ji);
3964 if (method) {
3965 gchar *location = mono_debug_print_stack_frame (method, frame->native_offset, frame->domain);
3966 g_string_append_printf (text, " %s\n", location);
3967 g_free (location);
3968 } else {
3969 g_string_append_printf (text, " at <unknown> <0x%05x>\n", frame->native_offset);
3973 g_fprintf (output_file, "%s", text->str);
3975 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
3976 OutputDebugStringA(text->str);
3977 #endif
3979 g_string_free (text, TRUE);
3980 fflush (output_file);
3983 static void
3984 mono_get_time_of_day (struct timeval *tv) {
3985 #ifdef WIN32
3986 struct _timeb time;
3987 _ftime(&time);
3988 tv->tv_sec = time.time;
3989 tv->tv_usec = time.millitm * 1000;
3990 #else
3991 if (gettimeofday (tv, NULL) == -1) {
3992 g_error ("gettimeofday() failed; errno is %d (%s)", errno, strerror (errno));
3994 #endif
3997 static void
3998 mono_local_time (const struct timeval *tv, struct tm *tm) {
3999 #ifdef HAVE_LOCALTIME_R
4000 localtime_r(&tv->tv_sec, tm);
4001 #else
4002 time_t const tv_sec = tv->tv_sec; // Copy due to Win32/Posix contradiction.
4003 *tm = *localtime (&tv_sec);
4004 #endif
4007 void
4008 mono_threads_perform_thread_dump (void)
4010 FILE* output_file = NULL;
4011 ThreadDumpUserData ud;
4012 guint32 thread_array [128];
4013 int tindex, nthreads;
4015 if (!thread_dump_requested)
4016 return;
4018 if (thread_dump_dir != NULL) {
4019 GString* path = g_string_new (0);
4020 char time_str[80];
4021 struct timeval tv;
4022 long ms;
4023 struct tm tod;
4024 mono_get_time_of_day (&tv);
4025 mono_local_time(&tv, &tod);
4026 strftime(time_str, sizeof(time_str), MONO_STRFTIME_F "_" MONO_STRFTIME_T, &tod);
4027 ms = tv.tv_usec / 1000;
4028 g_string_append_printf (path, "%s/%s.%03ld.tdump", thread_dump_dir, time_str, ms);
4029 output_file = fopen (path->str, "w");
4030 g_string_free (path, TRUE);
4032 if (output_file == NULL) {
4033 g_print ("Full thread dump:\n");
4036 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4037 nthreads = collect_threads (thread_array, 128);
4039 memset (&ud, 0, sizeof (ud));
4040 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4041 ud.max_frames = 256;
4043 for (tindex = 0; tindex < nthreads; ++tindex) {
4044 guint32 handle = thread_array [tindex];
4045 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4046 dump_thread (thread, &ud, output_file != NULL ? output_file : stdout);
4047 mono_gchandle_free_internal (handle);
4050 if (output_file != NULL) {
4051 fclose (output_file);
4053 g_free (ud.frames);
4055 thread_dump_requested = FALSE;
4058 /* Obtain the thread dump of all threads */
4059 static gboolean
4060 mono_threads_get_thread_dump (MonoArray **out_threads, MonoArray **out_stack_frames, MonoError *error)
4063 ThreadDumpUserData ud;
4064 guint32 thread_array [128];
4065 MonoDomain *domain = mono_domain_get ();
4066 MonoDebugSourceLocation *location;
4067 int tindex, nthreads;
4069 error_init (error);
4071 *out_threads = NULL;
4072 *out_stack_frames = NULL;
4074 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4075 nthreads = collect_threads (thread_array, 128);
4077 memset (&ud, 0, sizeof (ud));
4078 ud.frames = g_new0 (MonoStackFrameInfo, 256);
4079 ud.max_frames = 256;
4081 *out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, error);
4082 goto_if_nok (error, leave);
4083 *out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, error);
4084 goto_if_nok (error, leave);
4086 for (tindex = 0; tindex < nthreads; ++tindex) {
4087 guint32 handle = thread_array [tindex];
4088 MonoInternalThread *thread = (MonoInternalThread *) mono_gchandle_get_target_internal (handle);
4090 MonoArray *thread_frames;
4091 int i;
4093 ud.thread = thread;
4094 ud.nframes = 0;
4096 /* Collect frames for the thread */
4097 if (thread == mono_thread_internal_current ()) {
4098 get_thread_dump (mono_thread_info_current (), &ud);
4099 } else {
4100 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, get_thread_dump, &ud);
4103 mono_array_setref_fast (*out_threads, tindex, mono_thread_current_for_thread (thread));
4105 thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, error);
4106 goto_if_nok (error, leave);
4107 mono_array_setref_fast (*out_stack_frames, tindex, thread_frames);
4109 for (i = 0; i < ud.nframes; ++i) {
4110 MonoStackFrameInfo *frame = &ud.frames [i];
4111 MonoMethod *method = NULL;
4112 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new_checked (domain, mono_defaults.stack_frame_class, error);
4113 goto_if_nok (error, leave);
4115 sf->native_offset = frame->native_offset;
4117 if (frame->type == FRAME_TYPE_MANAGED)
4118 method = mono_jit_info_get_method (frame->ji);
4120 if (method) {
4121 sf->method_address = (gsize) frame->ji->code_start;
4123 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, method, NULL, error);
4124 goto_if_nok (error, leave);
4125 MONO_OBJECT_SETREF_INTERNAL (sf, method, rm);
4127 location = mono_debug_lookup_source_location (method, frame->native_offset, domain);
4128 if (location) {
4129 sf->il_offset = location->il_offset;
4131 if (location->source_file) {
4132 MonoString *filename = mono_string_new_checked (domain, location->source_file, error);
4133 goto_if_nok (error, leave);
4134 MONO_OBJECT_SETREF_INTERNAL (sf, filename, filename);
4135 sf->line = location->row;
4136 sf->column = location->column;
4138 mono_debug_free_source_location (location);
4139 } else {
4140 sf->il_offset = -1;
4143 mono_array_setref_internal (thread_frames, i, sf);
4146 mono_gchandle_free_internal (handle);
4149 leave:
4150 g_free (ud.frames);
4151 return is_ok (error);
4155 * mono_threads_request_thread_dump:
4157 * Ask all threads except the current to print their stacktrace to stdout.
4159 void
4160 mono_threads_request_thread_dump (void)
4162 /*The new thread dump code runs out of the finalizer thread. */
4163 thread_dump_requested = TRUE;
4164 mono_gc_finalize_notify ();
4167 struct ref_stack {
4168 gpointer *refs;
4169 gint allocated; /* +1 so that refs [allocated] == NULL */
4170 gint bottom;
4173 typedef struct ref_stack RefStack;
4175 static RefStack *
4176 ref_stack_new (gint initial_size)
4178 RefStack *rs;
4180 initial_size = MAX (initial_size, 16) + 1;
4181 rs = g_new0 (RefStack, 1);
4182 rs->refs = g_new0 (gpointer, initial_size);
4183 rs->allocated = initial_size;
4184 return rs;
4187 static void
4188 ref_stack_destroy (gpointer ptr)
4190 RefStack *rs = (RefStack *)ptr;
4192 if (rs != NULL) {
4193 g_free (rs->refs);
4194 g_free (rs);
4198 static void
4199 ref_stack_push (RefStack *rs, gpointer ptr)
4201 g_assert (rs != NULL);
4203 if (rs->bottom >= rs->allocated) {
4204 rs->refs = (void **)g_realloc (rs->refs, rs->allocated * 2 * sizeof (gpointer) + 1);
4205 rs->allocated <<= 1;
4206 rs->refs [rs->allocated] = NULL;
4208 rs->refs [rs->bottom++] = ptr;
4211 static void
4212 ref_stack_pop (RefStack *rs)
4214 if (rs == NULL || rs->bottom == 0)
4215 return;
4217 rs->bottom--;
4218 rs->refs [rs->bottom] = NULL;
4221 static gboolean
4222 ref_stack_find (RefStack *rs, gpointer ptr)
4224 gpointer *refs;
4226 if (rs == NULL)
4227 return FALSE;
4229 for (refs = rs->refs; refs && *refs; refs++) {
4230 if (*refs == ptr)
4231 return TRUE;
4233 return FALSE;
4237 * mono_thread_push_appdomain_ref:
4239 * Register that the current thread may have references to objects in domain
4240 * @domain on its stack. Each call to this function should be paired with a
4241 * call to pop_appdomain_ref.
4243 void
4244 mono_thread_push_appdomain_ref (MonoDomain *domain)
4246 MonoInternalThread *thread = mono_thread_internal_current ();
4248 if (thread) {
4249 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4250 SPIN_LOCK (thread->lock_thread_id);
4251 if (thread->appdomain_refs == NULL)
4252 thread->appdomain_refs = ref_stack_new (16);
4253 ref_stack_push ((RefStack *)thread->appdomain_refs, domain);
4254 SPIN_UNLOCK (thread->lock_thread_id);
4258 void
4259 mono_thread_pop_appdomain_ref (void)
4261 MonoInternalThread *thread = mono_thread_internal_current ();
4263 if (thread) {
4264 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4265 SPIN_LOCK (thread->lock_thread_id);
4266 ref_stack_pop ((RefStack *)thread->appdomain_refs);
4267 SPIN_UNLOCK (thread->lock_thread_id);
4271 gboolean
4272 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
4274 gboolean res;
4275 SPIN_LOCK (thread->lock_thread_id);
4276 res = ref_stack_find ((RefStack *)thread->appdomain_refs, domain);
4277 SPIN_UNLOCK (thread->lock_thread_id);
4278 return res;
4281 gboolean
4282 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
4284 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
4287 typedef struct abort_appdomain_data {
4288 struct wait_data wait;
4289 MonoDomain *domain;
4290 } abort_appdomain_data;
4292 static void
4293 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
4295 MonoInternalThread *thread = (MonoInternalThread*)value;
4296 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
4297 MonoDomain *domain = data->domain;
4299 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
4300 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4302 if(data->wait.num<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
4303 data->wait.handles [data->wait.num] = mono_threads_open_thread_handle (thread->handle);
4304 data->wait.threads [data->wait.num] = thread;
4305 data->wait.num++;
4306 } else {
4307 /* Just ignore the rest, we can't do anything with
4308 * them yet
4315 * mono_threads_abort_appdomain_threads:
4317 * Abort threads which has references to the given appdomain.
4319 gboolean
4320 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
4322 abort_appdomain_data user_data;
4323 gint64 start_time;
4324 int orig_timeout = timeout;
4325 int i;
4327 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
4329 start_time = mono_msec_ticks ();
4330 do {
4331 mono_threads_lock ();
4333 user_data.domain = domain;
4334 user_data.wait.num = 0;
4335 /* This shouldn't take any locks */
4336 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
4337 mono_threads_unlock ();
4339 if (user_data.wait.num > 0) {
4340 /* Abort the threads outside the threads lock */
4341 for (i = 0; i < user_data.wait.num; ++i)
4342 mono_thread_internal_abort (user_data.wait.threads [i], TRUE);
4345 * We should wait for the threads either to abort, or to leave the
4346 * domain. We can't do the latter, so we wait with a timeout.
4348 wait_for_tids (&user_data.wait, 100, FALSE);
4351 /* Update remaining time */
4352 timeout -= mono_msec_ticks () - start_time;
4353 start_time = mono_msec_ticks ();
4355 if (orig_timeout != -1 && timeout < 0)
4356 return FALSE;
4358 while (user_data.wait.num > 0);
4360 THREAD_DEBUG (g_message ("%s: abort done", __func__));
4362 return TRUE;
4365 /* This is a JIT icall. This icall is called from a finally block when
4366 * mono_install_handler_block_guard called by another thread has flipped the
4367 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4368 * the finally is in an abort protected block, we must defer the abort
4369 * exception until we leave the abort protected block. Otherwise we proceed
4370 * with a synchronous self-abort.
4372 void
4373 ves_icall_thread_finish_async_abort (void)
4375 /* We were called from the handler block and are about to
4376 * leave it. (If we end up postponing the abort because we're
4377 * in an abort protected block, the unwinder won't run and
4378 * won't clear the handler block itself which will confuse the
4379 * unwinder if we're in a try {} catch {} and we throw again.
4380 * ie, this:
4381 * static Constructor () {
4382 * try {
4383 * try {
4384 * } finally {
4385 * icall (); // Thread.Abort landed here,
4386 * // and caused the handler block to be installed
4387 * if (exvar)
4388 * ves_icall_thread_finish_async_abort (); // we're here
4390 * throw E ();
4391 * } catch (E) {
4392 * // unwinder will get confused here and synthesize a self abort
4396 * More interestingly, this doesn't only happen with icalls - a JIT
4397 * trampoline is native code that will cause a handler to be installed.
4398 * So the above situation can happen with any code in a "finally"
4399 * clause.
4401 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4402 /* Just set the async interruption requested bit. Rely on the icall
4403 * wrapper of this icall to process the thread interruption, respecting
4404 * any abort protection blocks in our call stack.
4406 mono_thread_set_self_interruption_respect_abort_prot ();
4410 * mono_thread_get_undeniable_exception:
4412 * Return an exception which needs to be raised when leaving a catch clause.
4413 * This is used for undeniable exception propagation.
4415 MonoException*
4416 mono_thread_get_undeniable_exception (void)
4418 MonoInternalThread *thread = mono_thread_internal_current ();
4420 if (!(thread && thread->abort_exc && !is_running_protected_wrapper ()))
4421 return NULL;
4423 // We don't want to have our exception effect calls made by
4424 // the catching block
4426 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4427 return NULL;
4430 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4431 * exception if the thread no longer references a dying appdomain.
4433 thread->abort_exc->trace_ips = NULL;
4434 thread->abort_exc->stack_trace = NULL;
4435 return thread->abort_exc;
4438 #if MONO_SMALL_CONFIG
4439 #define NUM_STATIC_DATA_IDX 4
4440 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4441 64, 256, 1024, 4096
4443 #else
4444 #define NUM_STATIC_DATA_IDX 8
4445 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
4446 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4448 #endif
4450 static MonoBitSet *thread_reference_bitmaps [NUM_STATIC_DATA_IDX];
4451 static MonoBitSet *context_reference_bitmaps [NUM_STATIC_DATA_IDX];
4453 static void
4454 mark_slots (void *addr, MonoBitSet **bitmaps, MonoGCMarkFunc mark_func, void *gc_data)
4456 gpointer *static_data = (gpointer *)addr;
4458 for (int i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
4459 void **ptr = (void **)static_data [i];
4461 if (!ptr)
4462 continue;
4464 MONO_BITSET_FOREACH (bitmaps [i], idx, {
4465 void **p = ptr + idx;
4467 if (*p)
4468 mark_func ((MonoObject**)p, gc_data);
4473 static void
4474 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4476 mark_slots (addr, thread_reference_bitmaps, mark_func, gc_data);
4479 static void
4480 mark_ctx_slots (void *addr, MonoGCMarkFunc mark_func, void *gc_data)
4482 mark_slots (addr, context_reference_bitmaps, mark_func, gc_data);
4486 * mono_alloc_static_data
4488 * Allocate memory blocks for storing threads or context static data
4490 static void
4491 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, void *alloc_key, gboolean threadlocal)
4493 guint idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4494 int i;
4496 gpointer* static_data = *static_data_ptr;
4497 if (!static_data) {
4498 static MonoGCDescriptor tls_desc = MONO_GC_DESCRIPTOR_NULL;
4499 static MonoGCDescriptor ctx_desc = MONO_GC_DESCRIPTOR_NULL;
4501 if (mono_gc_user_markers_supported ()) {
4502 if (tls_desc == MONO_GC_DESCRIPTOR_NULL)
4503 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
4505 if (ctx_desc == MONO_GC_DESCRIPTOR_NULL)
4506 ctx_desc = mono_gc_make_root_descr_user (mark_ctx_slots);
4509 static_data = (void **)mono_gc_alloc_fixed (static_data_size [0], threadlocal ? tls_desc : ctx_desc,
4510 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4511 alloc_key,
4512 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4513 *static_data_ptr = static_data;
4514 static_data [0] = static_data;
4517 for (i = 1; i <= idx; ++i) {
4518 if (static_data [i])
4519 continue;
4521 if (mono_gc_user_markers_supported ())
4522 static_data [i] = g_malloc0 (static_data_size [i]);
4523 else
4524 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], MONO_GC_DESCRIPTOR_NULL,
4525 threadlocal ? MONO_ROOT_SOURCE_THREAD_STATIC : MONO_ROOT_SOURCE_CONTEXT_STATIC,
4526 alloc_key,
4527 threadlocal ? "ThreadStatic Fields" : "ContextStatic Fields");
4531 static void
4532 mono_free_static_data (gpointer* static_data)
4534 int i;
4535 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
4536 gpointer p = static_data [i];
4537 if (!p)
4538 continue;
4540 * At this point, the static data pointer array is still registered with the
4541 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4542 * data. Freeing the individual arrays without first nulling their slots
4543 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4544 * such an already freed array. See bug #13813.
4546 static_data [i] = NULL;
4547 mono_memory_write_barrier ();
4548 if (mono_gc_user_markers_supported ())
4549 g_free (p);
4550 else
4551 mono_gc_free_fixed (p);
4553 mono_gc_free_fixed (static_data);
4557 * mono_init_static_data_info
4559 * Initializes static data counters
4561 static void mono_init_static_data_info (StaticDataInfo *static_data)
4563 static_data->idx = 0;
4564 static_data->offset = 0;
4565 static_data->freelist = NULL;
4569 * mono_alloc_static_data_slot
4571 * Generates an offset for static data. static_data contains the counters
4572 * used to generate it.
4574 static guint32
4575 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
4577 if (!static_data->idx && !static_data->offset) {
4579 * we use the first chunk of the first allocation also as
4580 * an array for the rest of the data
4582 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
4584 static_data->offset += align - 1;
4585 static_data->offset &= ~(align - 1);
4586 if (static_data->offset + size >= static_data_size [static_data->idx]) {
4587 static_data->idx ++;
4588 g_assert (size <= static_data_size [static_data->idx]);
4589 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
4590 static_data->offset = 0;
4592 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (static_data->idx, static_data->offset, 0);
4593 static_data->offset += size;
4594 return offset;
4598 * LOCKING: requires that threads_mutex is held
4600 static void
4601 context_adjust_static_data (MonoAppContextHandle ctx_handle)
4603 MonoAppContext *ctx = MONO_HANDLE_RAW (ctx_handle);
4604 if (context_static_info.offset || context_static_info.idx > 0) {
4605 guint32 offset = MAKE_SPECIAL_STATIC_OFFSET (context_static_info.idx, context_static_info.offset, 0);
4606 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4607 ctx->data->static_data = ctx->static_data;
4612 * LOCKING: requires that threads_mutex is held
4614 static void
4615 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4617 MonoInternalThread *thread = (MonoInternalThread *)value;
4618 guint32 offset = GPOINTER_TO_UINT (user);
4620 mono_alloc_static_data (&(thread->static_data), offset, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid), TRUE);
4624 * LOCKING: requires that threads_mutex is held
4626 static void
4627 alloc_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4629 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4631 if (!ctx)
4632 return;
4634 guint32 offset = GPOINTER_TO_UINT (user);
4635 mono_alloc_static_data (&ctx->static_data, offset, ctx, FALSE);
4636 ctx->data->static_data = ctx->static_data;
4639 static StaticDataFreeList*
4640 search_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
4642 StaticDataFreeList* prev = NULL;
4643 StaticDataFreeList* tmp = static_data->freelist;
4644 while (tmp) {
4645 if (tmp->size == size) {
4646 if (prev)
4647 prev->next = tmp->next;
4648 else
4649 static_data->freelist = tmp->next;
4650 return tmp;
4652 prev = tmp;
4653 tmp = tmp->next;
4655 return NULL;
4658 #if SIZEOF_VOID_P == 4
4659 #define ONE_P 1
4660 #else
4661 #define ONE_P 1ll
4662 #endif
4664 static void
4665 update_reference_bitmap (MonoBitSet **sets, guint32 offset, uintptr_t *bitmap, int numbits)
4667 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4668 if (!sets [idx])
4669 sets [idx] = mono_bitset_new (static_data_size [idx] / sizeof (uintptr_t), 0);
4670 MonoBitSet *rb = sets [idx];
4671 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4672 offset /= sizeof (uintptr_t);
4673 /* offset is now the bitmap offset */
4674 for (int i = 0; i < numbits; ++i) {
4675 if (bitmap [i / sizeof (uintptr_t)] & (ONE_P << (i & (sizeof (uintptr_t) * 8 -1))))
4676 mono_bitset_set_fast (rb, offset + i);
4680 static void
4681 clear_reference_bitmap (MonoBitSet **sets, guint32 offset, guint32 size)
4683 int idx = ACCESS_SPECIAL_STATIC_OFFSET (offset, index);
4684 MonoBitSet *rb = sets [idx];
4685 offset = ACCESS_SPECIAL_STATIC_OFFSET (offset, offset);
4686 offset /= sizeof (uintptr_t);
4687 /* offset is now the bitmap offset */
4688 for (int i = 0; i < size / sizeof (uintptr_t); i++)
4689 mono_bitset_clear_fast (rb, offset + i);
4692 guint32
4693 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int numbits)
4695 g_assert (static_type == SPECIAL_STATIC_THREAD || static_type == SPECIAL_STATIC_CONTEXT);
4697 StaticDataInfo *info;
4698 MonoBitSet **sets;
4700 if (static_type == SPECIAL_STATIC_THREAD) {
4701 info = &thread_static_info;
4702 sets = thread_reference_bitmaps;
4703 } else {
4704 info = &context_static_info;
4705 sets = context_reference_bitmaps;
4708 mono_threads_lock ();
4710 StaticDataFreeList *item = search_slot_in_freelist (info, size, align);
4711 guint32 offset;
4713 if (item) {
4714 offset = item->offset;
4715 g_free (item);
4716 } else {
4717 offset = mono_alloc_static_data_slot (info, size, align);
4720 update_reference_bitmap (sets, offset, bitmap, numbits);
4722 if (static_type == SPECIAL_STATIC_THREAD) {
4723 /* This can be called during startup */
4724 if (threads != NULL)
4725 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
4726 } else {
4727 if (contexts != NULL)
4728 g_hash_table_foreach (contexts, alloc_context_static_data_helper, GUINT_TO_POINTER (offset));
4730 ACCESS_SPECIAL_STATIC_OFFSET (offset, type) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT;
4733 mono_threads_unlock ();
4735 return offset;
4738 gpointer
4739 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
4741 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4743 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4744 return get_thread_static_data (thread, offset);
4745 } else {
4746 return get_context_static_data (thread->current_appcontext, offset);
4750 gpointer
4751 mono_get_special_static_data (guint32 offset)
4753 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
4756 typedef struct {
4757 guint32 offset;
4758 guint32 size;
4759 } OffsetSize;
4762 * LOCKING: requires that threads_mutex is held
4764 static void
4765 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
4767 MonoInternalThread *thread = (MonoInternalThread *)value;
4768 OffsetSize *data = (OffsetSize *)user;
4769 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4770 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4771 char *ptr;
4773 if (!thread->static_data || !thread->static_data [idx])
4774 return;
4775 ptr = ((char*) thread->static_data [idx]) + off;
4776 mono_gc_bzero_atomic (ptr, data->size);
4780 * LOCKING: requires that threads_mutex is held
4782 static void
4783 free_context_static_data_helper (gpointer key, gpointer value, gpointer user)
4785 MonoAppContext *ctx = (MonoAppContext *) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key));
4787 if (!ctx)
4788 return;
4790 OffsetSize *data = (OffsetSize *)user;
4791 int idx = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, index);
4792 int off = ACCESS_SPECIAL_STATIC_OFFSET (data->offset, offset);
4793 char *ptr;
4795 if (!ctx->static_data || !ctx->static_data [idx])
4796 return;
4798 ptr = ((char*) ctx->static_data [idx]) + off;
4799 mono_gc_bzero_atomic (ptr, data->size);
4802 static void
4803 do_free_special_slot (guint32 offset, guint32 size)
4805 guint32 static_type = ACCESS_SPECIAL_STATIC_OFFSET (offset, type);
4806 MonoBitSet **sets;
4807 StaticDataInfo *info;
4809 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4810 info = &thread_static_info;
4811 sets = thread_reference_bitmaps;
4812 } else {
4813 info = &context_static_info;
4814 sets = context_reference_bitmaps;
4817 guint32 data_offset = offset;
4818 ACCESS_SPECIAL_STATIC_OFFSET (data_offset, type) = 0;
4819 OffsetSize data = { data_offset, size };
4821 clear_reference_bitmap (sets, data.offset, data.size);
4823 if (static_type == SPECIAL_STATIC_OFFSET_TYPE_THREAD) {
4824 if (threads != NULL)
4825 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
4826 } else {
4827 if (contexts != NULL)
4828 g_hash_table_foreach (contexts, free_context_static_data_helper, &data);
4831 if (!mono_runtime_is_shutting_down ()) {
4832 StaticDataFreeList *item = g_new0 (StaticDataFreeList, 1);
4834 item->offset = offset;
4835 item->size = size;
4837 item->next = info->freelist;
4838 info->freelist = item;
4842 static void
4843 do_free_special (gpointer key, gpointer value, gpointer data)
4845 MonoClassField *field = (MonoClassField *)key;
4846 guint32 offset = GPOINTER_TO_UINT (value);
4847 gint32 align;
4848 guint32 size;
4849 size = mono_type_size (field->type, &align);
4850 do_free_special_slot (offset, size);
4853 void
4854 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
4856 mono_threads_lock ();
4858 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
4860 mono_threads_unlock ();
4863 #ifdef HOST_WIN32
4864 static void CALLBACK dummy_apc (ULONG_PTR param)
4867 #endif
4870 * mono_thread_execute_interruption
4872 * Performs the operation that the requested thread state requires (abort,
4873 * suspend or stop)
4875 static gboolean
4876 mono_thread_execute_interruption (MonoExceptionHandle *pexc)
4878 gboolean fexc = FALSE;
4880 // Optimize away frame if caller supplied one.
4881 if (!pexc) {
4882 HANDLE_FUNCTION_ENTER ();
4883 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4884 fexc = mono_thread_execute_interruption (&exc);
4885 HANDLE_FUNCTION_RETURN_VAL (fexc);
4888 MONO_REQ_GC_UNSAFE_MODE;
4890 MonoInternalThreadHandle thread = mono_thread_internal_current_handle ();
4891 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4893 lock_thread_handle (thread);
4894 gboolean unlock = TRUE;
4896 /* MonoThread::interruption_requested can only be changed with atomics */
4897 if (!mono_thread_clear_interruption_requested_handle (thread))
4898 goto exit;
4900 MonoThreadObjectHandle sys_thread;
4901 sys_thread = mono_thread_current_handle ();
4903 /* this will consume pending APC calls */
4904 #ifdef HOST_WIN32
4905 MONO_ENTER_GC_SAFE;
4906 mono_win32_wait_for_single_object_ex (GetCurrentThread (), 0, TRUE);
4907 MONO_EXIT_GC_SAFE;
4908 #endif
4910 /* Clear the interrupted flag of the thread so it can wait again */
4911 mono_thread_info_clear_self_interrupt ();
4913 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4914 MONO_HANDLE_GET (exc, sys_thread, pending_exception);
4915 if (!MONO_HANDLE_IS_NULL (exc)) {
4916 // sys_thread->pending_exception = NULL;
4917 MONO_HANDLE_SETRAW (sys_thread, pending_exception, NULL);
4918 fexc = TRUE;
4919 goto exit;
4920 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_AbortRequested) {
4921 // Does the thread already have an abort exception?
4922 // If not, create a new one and set it on demand.
4923 // exc = thread->abort_exc;
4924 MONO_HANDLE_GET (exc, thread, abort_exc);
4925 if (MONO_HANDLE_IS_NULL (exc)) {
4926 ERROR_DECL (error);
4927 exc = mono_exception_new_thread_abort (error);
4928 mono_error_assert_ok (error); // FIXME
4929 // thread->abort_exc = exc;
4930 MONO_HANDLE_SET (thread, abort_exc, exc);
4932 fexc = TRUE;
4933 } else if (MONO_HANDLE_GETVAL (thread, state) & ThreadState_SuspendRequested) {
4934 /* calls UNLOCK_THREAD (thread) */
4935 self_suspend_internal ();
4936 unlock = FALSE;
4937 } else if (MONO_HANDLE_GETVAL (thread, thread_interrupt_requested)) {
4938 // thread->thread_interrupt_requested = FALSE
4939 MONO_HANDLE_SETVAL (thread, thread_interrupt_requested, MonoBoolean, FALSE);
4940 unlock_thread_handle (thread);
4941 unlock = FALSE;
4942 ERROR_DECL (error);
4943 exc = mono_exception_new_thread_interrupted (error);
4944 mono_error_assert_ok (error); // FIXME
4945 fexc = TRUE;
4947 exit:
4948 if (unlock)
4949 unlock_thread_handle (thread);
4951 if (fexc)
4952 MONO_HANDLE_ASSIGN (*pexc, exc);
4954 return fexc;
4957 static void
4958 mono_thread_execute_interruption_void (void)
4960 (void)mono_thread_execute_interruption (NULL);
4963 static MonoException*
4964 mono_thread_execute_interruption_ptr (void)
4966 HANDLE_FUNCTION_ENTER ();
4967 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
4968 MonoException *exc_raw = mono_thread_execute_interruption (&exc) ? MONO_HANDLE_RAW (exc) : NULL;
4969 HANDLE_FUNCTION_RETURN_VAL (exc_raw);
4973 * mono_thread_request_interruption_internal
4975 * A signal handler can call this method to request the interruption of a
4976 * thread. The result of the interruption will depend on the current state of
4977 * the thread. If the result is an exception that needs to be thrown, it is
4978 * provided as return value.
4980 static gboolean
4981 mono_thread_request_interruption_internal (gboolean running_managed, MonoExceptionHandle *pexc)
4983 MonoInternalThread *thread = mono_thread_internal_current ();
4985 /* The thread may already be stopping */
4986 if (thread == NULL)
4987 return FALSE;
4989 if (!mono_thread_set_interruption_requested (thread))
4990 return FALSE;
4992 if (!running_managed || is_running_protected_wrapper ()) {
4993 /* Can't stop while in unmanaged code. Increase the global interruption
4994 request count. When exiting the unmanaged method the count will be
4995 checked and the thread will be interrupted. */
4997 /* this will awake the thread if it is in WaitForSingleObject
4998 or similar */
4999 #ifdef HOST_WIN32
5000 mono_win32_interrupt_wait (thread->thread_info, thread->native_handle, (DWORD)thread->tid);
5001 #else
5002 mono_thread_info_self_interrupt ();
5003 #endif
5004 return FALSE;
5006 return mono_thread_execute_interruption (pexc);
5009 static void
5010 mono_thread_request_interruption_native (void)
5012 (void)mono_thread_request_interruption_internal (FALSE, NULL);
5015 static gboolean
5016 mono_thread_request_interruption_managed (MonoExceptionHandle *exc)
5018 return mono_thread_request_interruption_internal (TRUE, exc);
5021 /*This function should be called by a thread after it has exited all of
5022 * its handle blocks at interruption time.*/
5023 void
5024 mono_thread_resume_interruption (gboolean exec)
5026 MonoInternalThread *thread = mono_thread_internal_current ();
5027 gboolean still_aborting;
5029 /* The thread may already be stopping */
5030 if (thread == NULL)
5031 return;
5033 LOCK_THREAD (thread);
5034 still_aborting = (thread->state & (ThreadState_AbortRequested)) != 0;
5035 UNLOCK_THREAD (thread);
5037 /*This can happen if the protected block called Thread::ResetAbort*/
5038 if (!still_aborting)
5039 return;
5041 if (!mono_thread_set_interruption_requested (thread))
5042 return;
5044 mono_thread_info_self_interrupt ();
5046 if (exec) // Ignore the exception here, it will be raised later.
5047 mono_thread_execute_interruption_void ();
5050 gboolean
5051 mono_thread_interruption_requested (void)
5053 if (thread_interruption_requested) {
5054 MonoInternalThread *thread = mono_thread_internal_current ();
5055 /* The thread may already be stopping */
5056 if (thread != NULL)
5057 return mono_thread_get_interruption_requested (thread);
5059 return FALSE;
5062 static MonoException*
5063 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
5065 MonoInternalThread *thread = mono_thread_internal_current ();
5067 /* The thread may already be stopping */
5068 if (!thread)
5069 return NULL;
5070 if (!mono_thread_get_interruption_requested (thread))
5071 return NULL;
5072 if (!bypass_abort_protection && !mono_thread_current ()->pending_exception && is_running_protected_wrapper ())
5073 return NULL;
5075 return mono_thread_execute_interruption_ptr ();
5079 * Performs the interruption of the current thread, if one has been requested,
5080 * and the thread is not running a protected wrapper.
5081 * Return the exception which needs to be thrown, if any.
5083 MonoException*
5084 mono_thread_interruption_checkpoint (void)
5086 return mono_thread_interruption_checkpoint_request (FALSE);
5089 gboolean
5090 mono_thread_interruption_checkpoint_bool (void)
5092 return mono_thread_interruption_checkpoint () != NULL;
5095 void
5096 mono_thread_interruption_checkpoint_void (void)
5098 mono_thread_interruption_checkpoint ();
5102 * Performs the interruption of the current thread, if one has been requested.
5103 * Return the exception which needs to be thrown, if any.
5105 MonoException*
5106 mono_thread_force_interruption_checkpoint_noraise (void)
5108 return mono_thread_interruption_checkpoint_request (TRUE);
5112 * mono_set_pending_exception:
5114 * Set the pending exception of the current thread to EXC.
5115 * The exception will be thrown when execution returns to managed code.
5117 void
5118 mono_set_pending_exception (MonoException *exc)
5120 MonoThread *thread = mono_thread_current ();
5122 /* The thread may already be stopping */
5123 if (thread == NULL)
5124 return;
5126 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5128 mono_thread_request_interruption_native ();
5132 * mono_runtime_set_pending_exception:
5134 * Set the pending exception of the current thread to \p exc.
5135 * The exception will be thrown when execution returns to managed code.
5136 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5137 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5138 * in which case the behavior will be undefined).
5139 * Return whether the pending exception was set or not.
5140 * It will not be set if:
5141 * * The thread or runtime is stopping or shutting down
5142 * * There already is a pending exception (and \p overwrite is false)
5144 mono_bool
5145 mono_runtime_set_pending_exception (MonoException *exc, mono_bool overwrite)
5147 MonoThread *thread = mono_thread_current ();
5149 /* The thread may already be stopping */
5150 if (thread == NULL)
5151 return FALSE;
5153 /* Don't overwrite any existing pending exceptions unless asked to */
5154 if (!overwrite && thread->pending_exception)
5155 return FALSE;
5157 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, exc);
5159 mono_thread_request_interruption_native ();
5161 return TRUE;
5166 * mono_set_pending_exception_handle:
5168 * Set the pending exception of the current thread to EXC.
5169 * The exception will be thrown when execution returns to managed code.
5171 MONO_COLD void
5172 mono_set_pending_exception_handle (MonoExceptionHandle exc)
5174 MonoThread *thread = mono_thread_current ();
5176 /* The thread may already be stopping */
5177 if (thread == NULL)
5178 return;
5180 MONO_OBJECT_SETREF_INTERNAL (thread, pending_exception, MONO_HANDLE_RAW (exc));
5182 mono_thread_request_interruption_native ();
5186 * mono_thread_interruption_request_flag:
5188 * Returns the address of a flag that will be non-zero if an interruption has
5189 * been requested for a thread. The thread to interrupt may not be the current
5190 * thread, so an additional call to mono_thread_interruption_requested() or
5191 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
5192 * zero.
5194 gint32*
5195 mono_thread_interruption_request_flag (void)
5197 return &thread_interruption_requested;
5200 void
5201 mono_thread_init_apartment_state (void)
5203 #ifdef HOST_WIN32
5204 MonoInternalThread* thread = mono_thread_internal_current ();
5206 /* Positive return value indicates success, either
5207 * S_OK if this is first CoInitialize call, or
5208 * S_FALSE if CoInitialize already called, but with same
5209 * threading model. A negative value indicates failure,
5210 * probably due to trying to change the threading model.
5212 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
5213 ? COINIT_APARTMENTTHREADED
5214 : COINIT_MULTITHREADED) < 0) {
5215 thread->apartment_state = ThreadApartmentState_Unknown;
5217 #endif
5220 void
5221 mono_thread_cleanup_apartment_state (void)
5223 #ifdef HOST_WIN32
5224 MonoInternalThread* thread = mono_thread_internal_current ();
5226 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
5227 CoUninitialize ();
5229 #endif
5232 static void
5233 mono_thread_notify_change_state (MonoThreadState old_state, MonoThreadState new_state)
5235 MonoThreadState diff = old_state ^ new_state;
5236 if (diff & ThreadState_Background) {
5237 /* If the thread changes the background mode, the main thread has to
5238 * be notified, since it has to rebuild the list of threads to
5239 * wait for.
5241 MONO_ENTER_GC_SAFE;
5242 mono_os_event_set (&background_change_event);
5243 MONO_EXIT_GC_SAFE;
5247 void
5248 mono_thread_clear_and_set_state (MonoInternalThread *thread, MonoThreadState clear, MonoThreadState set)
5250 LOCK_THREAD (thread);
5252 MonoThreadState const old_state = (MonoThreadState)thread->state;
5253 MonoThreadState const new_state = (old_state & ~clear) | set;
5254 thread->state = new_state;
5256 UNLOCK_THREAD (thread);
5258 mono_thread_notify_change_state (old_state, new_state);
5261 void
5262 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
5264 mono_thread_clear_and_set_state (thread, (MonoThreadState)0, state);
5268 * mono_thread_test_and_set_state:
5269 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5270 * \returns TRUE if \p set was OR'd in.
5272 gboolean
5273 mono_thread_test_and_set_state (MonoInternalThread *thread, MonoThreadState test, MonoThreadState set)
5275 LOCK_THREAD (thread);
5277 MonoThreadState const old_state = (MonoThreadState)thread->state;
5279 if ((old_state & test) != 0) {
5280 UNLOCK_THREAD (thread);
5281 return FALSE;
5284 MonoThreadState const new_state = old_state | set;
5285 thread->state = new_state;
5287 UNLOCK_THREAD (thread);
5289 mono_thread_notify_change_state (old_state, new_state);
5291 return TRUE;
5294 void
5295 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
5297 mono_thread_clear_and_set_state (thread, state, (MonoThreadState)0);
5300 gboolean
5301 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
5303 LOCK_THREAD (thread);
5305 gboolean const ret = ((thread->state & test) != 0);
5307 UNLOCK_THREAD (thread);
5309 return ret;
5312 static void
5313 self_interrupt_thread (void *_unused)
5315 MonoException *exc;
5316 MonoThreadInfo *info;
5317 MonoContext ctx;
5319 exc = mono_thread_execute_interruption_ptr ();
5320 if (!exc) {
5321 if (mono_threads_are_safepoints_enabled ()) {
5322 /* We can return from an async call in coop, as
5323 * it's simply called when exiting the safepoint */
5324 /* If we're using hybrid suspend, we only self
5325 * interrupt if we were running, hence using
5326 * safepoints */
5327 return;
5330 g_error ("%s: we can't resume from an async call", __func__);
5333 info = mono_thread_info_current ();
5335 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5336 ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
5338 mono_raise_exception_with_context (exc, &ctx);
5341 static gboolean
5342 mono_jit_info_match (MonoJitInfo *ji, gpointer ip)
5344 if (!ji)
5345 return FALSE;
5346 return ji->code_start <= ip && (char*)ip < (char*)ji->code_start + ji->code_size;
5349 static gboolean
5350 last_managed (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
5352 MonoJitInfo **dest = (MonoJitInfo **)data;
5353 *dest = frame->ji;
5354 return TRUE;
5357 static MonoJitInfo*
5358 mono_thread_info_get_last_managed (MonoThreadInfo *info)
5360 MonoJitInfo *ji = NULL;
5361 if (!info)
5362 return NULL;
5365 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5366 * any runtime locks while unwinding.
5368 mono_thread_info_set_is_async_context (TRUE);
5369 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &ji);
5370 mono_thread_info_set_is_async_context (FALSE);
5371 return ji;
5374 typedef struct {
5375 MonoInternalThread *thread;
5376 gboolean install_async_abort;
5377 MonoThreadInfoInterruptToken *interrupt_token;
5378 } AbortThreadData;
5380 static SuspendThreadResult
5381 async_abort_critical (MonoThreadInfo *info, gpointer ud)
5383 AbortThreadData *data = (AbortThreadData *)ud;
5384 MonoInternalThread *thread = data->thread;
5385 MonoJitInfo *ji = NULL;
5386 gboolean protected_wrapper;
5387 gboolean running_managed;
5389 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info)))
5390 return MonoResumeThread;
5392 /*someone is already interrupting it*/
5393 if (!mono_thread_set_interruption_requested (thread))
5394 return MonoResumeThread;
5396 ji = mono_thread_info_get_last_managed (info);
5397 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5398 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5400 if (!protected_wrapper && running_managed) {
5401 /*We are in managed code*/
5402 /*Set the thread to call */
5403 if (data->install_async_abort)
5404 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5405 return MonoResumeThread;
5406 } else {
5408 * This will cause waits to be broken.
5409 * It will also prevent the thread from entering a wait, so if the thread returns
5410 * from the wait before it receives the abort signal, it will just spin in the wait
5411 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5412 * make it return.
5414 data->interrupt_token = mono_thread_info_prepare_interrupt (info);
5416 return MonoResumeThread;
5420 static void
5421 async_abort_internal (MonoInternalThread *thread, gboolean install_async_abort)
5423 AbortThreadData data;
5425 g_assert (thread != mono_thread_internal_current ());
5427 data.thread = thread;
5428 data.install_async_abort = install_async_abort;
5429 data.interrupt_token = NULL;
5431 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), TRUE, async_abort_critical, &data);
5432 if (data.interrupt_token)
5433 mono_thread_info_finish_interrupt (data.interrupt_token);
5434 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5437 static void
5438 self_abort_internal (MonoError *error)
5440 HANDLE_FUNCTION_ENTER ();
5442 error_init (error);
5444 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5445 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5448 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.
5450 MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL);
5451 if (mono_thread_request_interruption_managed (&exc))
5452 mono_error_set_exception_handle (error, exc);
5453 else
5454 mono_thread_info_self_interrupt ();
5456 HANDLE_FUNCTION_RETURN ();
5459 typedef struct {
5460 MonoInternalThread *thread;
5461 gboolean interrupt;
5462 MonoThreadInfoInterruptToken *interrupt_token;
5463 } SuspendThreadData;
5465 static SuspendThreadResult
5466 async_suspend_critical (MonoThreadInfo *info, gpointer ud)
5468 SuspendThreadData *data = (SuspendThreadData *)ud;
5469 MonoInternalThread *thread = data->thread;
5470 MonoJitInfo *ji = NULL;
5471 gboolean protected_wrapper;
5472 gboolean running_managed;
5474 ji = mono_thread_info_get_last_managed (info);
5475 protected_wrapper = ji && !ji->is_trampoline && !ji->async && mono_threads_is_critical_method (mono_jit_info_get_method (ji));
5476 running_managed = mono_jit_info_match (ji, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
5478 if (running_managed && !protected_wrapper) {
5479 if (mono_threads_are_safepoints_enabled ()) {
5480 mono_thread_info_setup_async_call (info, self_interrupt_thread, NULL);
5481 return MonoResumeThread;
5482 } else {
5483 thread->state &= ~ThreadState_SuspendRequested;
5484 thread->state |= ThreadState_Suspended;
5485 return KeepSuspended;
5487 } else {
5488 mono_thread_set_interruption_requested (thread);
5489 if (data->interrupt)
5490 data->interrupt_token = mono_thread_info_prepare_interrupt ((MonoThreadInfo *)thread->thread_info);
5492 return MonoResumeThread;
5496 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5497 static void
5498 async_suspend_internal (MonoInternalThread *thread, gboolean interrupt)
5500 SuspendThreadData data;
5502 g_assert (thread != mono_thread_internal_current ());
5504 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5506 thread->self_suspended = FALSE;
5508 data.thread = thread;
5509 data.interrupt = interrupt;
5510 data.interrupt_token = NULL;
5512 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), interrupt, async_suspend_critical, &data);
5513 if (data.interrupt_token)
5514 mono_thread_info_finish_interrupt (data.interrupt_token);
5516 UNLOCK_THREAD (thread);
5519 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5520 static void
5521 self_suspend_internal (void)
5523 MonoInternalThread *thread;
5524 MonoOSEvent *event;
5525 MonoOSEventWaitRet res;
5527 thread = mono_thread_internal_current ();
5529 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5531 thread->self_suspended = TRUE;
5533 thread->state &= ~ThreadState_SuspendRequested;
5534 thread->state |= ThreadState_Suspended;
5536 UNLOCK_THREAD (thread);
5538 event = thread->suspended;
5540 MONO_ENTER_GC_SAFE;
5541 res = mono_os_event_wait_one (event, MONO_INFINITE_WAIT, TRUE);
5542 g_assert (res == MONO_OS_EVENT_WAIT_RET_SUCCESS_0 || res == MONO_OS_EVENT_WAIT_RET_ALERTED);
5543 MONO_EXIT_GC_SAFE;
5546 static void
5547 suspend_for_shutdown_async_call (gpointer unused)
5549 for (;;)
5550 mono_thread_info_yield ();
5553 static SuspendThreadResult
5554 suspend_for_shutdown_critical (MonoThreadInfo *info, gpointer unused)
5556 mono_thread_info_setup_async_call (info, suspend_for_shutdown_async_call, NULL);
5557 return MonoResumeThread;
5560 void
5561 mono_thread_internal_suspend_for_shutdown (MonoInternalThread *thread)
5563 g_assert (thread != mono_thread_internal_current ());
5565 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread), FALSE, suspend_for_shutdown_critical, NULL);
5569 * mono_thread_is_foreign:
5570 * \param thread the thread to query
5572 * This function allows one to determine if a thread was created by the mono runtime and has
5573 * a well defined lifecycle or it's a foreign one, created by the native environment.
5575 * \returns TRUE if \p thread was not created by the runtime.
5577 mono_bool
5578 mono_thread_is_foreign (MonoThread *thread)
5580 mono_bool result;
5581 MONO_ENTER_GC_UNSAFE;
5582 MonoThreadInfo *info = (MonoThreadInfo *)thread->internal_thread->thread_info;
5583 result = (info->runtime_thread == FALSE);
5584 MONO_EXIT_GC_UNSAFE;
5585 return result;
5588 #ifndef HOST_WIN32
5589 static void
5590 threads_native_thread_join_lock (gpointer tid, gpointer value)
5592 pthread_t thread = (pthread_t)tid;
5593 if (thread != pthread_self ()) {
5594 MONO_ENTER_GC_SAFE;
5595 /* This shouldn't block */
5596 mono_threads_join_lock ();
5597 mono_native_thread_join (thread);
5598 mono_threads_join_unlock ();
5599 MONO_EXIT_GC_SAFE;
5602 static void
5603 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5605 pthread_t thread = (pthread_t)tid;
5606 MONO_ENTER_GC_SAFE;
5607 mono_native_thread_join (thread);
5608 MONO_EXIT_GC_SAFE;
5611 static void
5612 threads_add_joinable_thread_nolock (gpointer tid)
5614 g_hash_table_insert (joinable_threads, tid, tid);
5616 #else
5617 static void
5618 threads_native_thread_join_lock (gpointer tid, gpointer value)
5620 MonoNativeThreadId thread_id = (MonoNativeThreadId)(guint64)tid;
5621 HANDLE thread_handle = (HANDLE)value;
5622 if (thread_id != GetCurrentThreadId () && thread_handle != NULL && thread_handle != INVALID_HANDLE_VALUE) {
5623 MONO_ENTER_GC_SAFE;
5624 /* This shouldn't block */
5625 mono_threads_join_lock ();
5626 mono_native_thread_join_handle (thread_handle, TRUE);
5627 mono_threads_join_unlock ();
5628 MONO_EXIT_GC_SAFE;
5632 static void
5633 threads_native_thread_join_nolock (gpointer tid, gpointer value)
5635 HANDLE thread_handle = (HANDLE)value;
5636 MONO_ENTER_GC_SAFE;
5637 mono_native_thread_join_handle (thread_handle, TRUE);
5638 MONO_EXIT_GC_SAFE;
5641 static void
5642 threads_add_joinable_thread_nolock (gpointer tid)
5644 g_hash_table_insert (joinable_threads, tid, (gpointer)OpenThread (SYNCHRONIZE, TRUE, (MonoNativeThreadId)(guint64)tid));
5646 #endif
5648 static void
5649 threads_add_pending_joinable_thread (gpointer tid)
5651 joinable_threads_lock ();
5653 if (!pending_joinable_threads)
5654 pending_joinable_threads = g_hash_table_new (NULL, NULL);
5656 gpointer orig_key;
5657 gpointer value;
5659 if (!g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5660 g_hash_table_insert (pending_joinable_threads, tid, tid);
5661 UnlockedIncrement (&pending_joinable_thread_count);
5664 joinable_threads_unlock ();
5667 static void
5668 threads_add_pending_joinable_runtime_thread (MonoThreadInfo *mono_thread_info)
5670 g_assert (mono_thread_info);
5672 if (mono_thread_info->runtime_thread) {
5673 threads_add_pending_joinable_thread ((gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info))));
5677 static void
5678 threads_remove_pending_joinable_thread_nolock (gpointer tid)
5680 gpointer orig_key;
5681 gpointer value;
5683 if (pending_joinable_threads && g_hash_table_lookup_extended (pending_joinable_threads, tid, &orig_key, &value)) {
5684 g_hash_table_remove (pending_joinable_threads, tid);
5685 if (UnlockedDecrement (&pending_joinable_thread_count) == 0)
5686 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event);
5690 static gboolean
5691 threads_wait_pending_joinable_threads (uint32_t timeout)
5693 if (UnlockedRead (&pending_joinable_thread_count) > 0) {
5694 joinable_threads_lock ();
5695 if (timeout == MONO_INFINITE_WAIT) {
5696 while (UnlockedRead (&pending_joinable_thread_count) > 0)
5697 mono_coop_cond_wait (&zero_pending_joinable_thread_event, &joinable_threads_mutex);
5698 } else {
5699 gint64 start = mono_msec_ticks ();
5700 gint64 elapsed = 0;
5701 while (UnlockedRead (&pending_joinable_thread_count) > 0 && elapsed < timeout) {
5702 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event, &joinable_threads_mutex, timeout - (uint32_t)elapsed);
5703 elapsed = mono_msec_ticks () - start;
5706 joinable_threads_unlock ();
5709 return UnlockedRead (&pending_joinable_thread_count) == 0;
5712 static void
5713 threads_add_unique_joinable_thread_nolock (gpointer tid)
5715 if (!joinable_threads)
5716 joinable_threads = g_hash_table_new (NULL, NULL);
5718 gpointer orig_key;
5719 gpointer value;
5721 if (!g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5722 threads_add_joinable_thread_nolock (tid);
5723 UnlockedIncrement (&joinable_thread_count);
5727 void
5728 mono_threads_add_joinable_runtime_thread (MonoThreadInfo *thread_info)
5730 g_assert (thread_info);
5731 MonoThreadInfo *mono_thread_info = thread_info;
5733 if (mono_thread_info->runtime_thread) {
5734 gpointer tid = (gpointer)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info)));
5736 joinable_threads_lock ();
5738 // Add to joinable thread list, if not already included.
5739 threads_add_unique_joinable_thread_nolock (tid);
5741 // Remove thread from pending joinable list, if present.
5742 threads_remove_pending_joinable_thread_nolock (tid);
5744 joinable_threads_unlock ();
5746 mono_gc_finalize_notify ();
5750 static void
5751 threads_add_pending_native_thread_join_call_nolock (gpointer tid)
5753 if (!pending_native_thread_join_calls)
5754 pending_native_thread_join_calls = g_hash_table_new (NULL, NULL);
5756 gpointer orig_key;
5757 gpointer value;
5759 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value))
5760 g_hash_table_insert (pending_native_thread_join_calls, tid, tid);
5763 static void
5764 threads_remove_pending_native_thread_join_call_nolock (gpointer tid)
5766 if (pending_native_thread_join_calls)
5767 g_hash_table_remove (pending_native_thread_join_calls, tid);
5769 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event);
5772 static void
5773 threads_wait_pending_native_thread_join_call_nolock (gpointer tid)
5775 gpointer orig_key;
5776 gpointer value;
5778 while (g_hash_table_lookup_extended (pending_native_thread_join_calls, tid, &orig_key, &value)) {
5779 mono_coop_cond_wait (&pending_native_thread_join_calls_event, &joinable_threads_mutex);
5784 * mono_add_joinable_thread:
5786 * Add TID to the list of joinable threads.
5787 * LOCKING: Acquires the threads lock.
5789 void
5790 mono_threads_add_joinable_thread (gpointer tid)
5793 * We cannot detach from threads because it causes problems like
5794 * 2fd16f60/r114307. So we collect them and join them when
5795 * we have time (in the finalizer thread).
5797 joinable_threads_lock ();
5798 threads_add_unique_joinable_thread_nolock (tid);
5799 joinable_threads_unlock ();
5801 mono_gc_finalize_notify ();
5805 * mono_threads_join_threads:
5807 * Join all joinable threads. This is called from the finalizer thread.
5808 * LOCKING: Acquires the threads lock.
5810 void
5811 mono_threads_join_threads (void)
5813 GHashTableIter iter;
5814 gpointer key = NULL;
5815 gpointer value = NULL;
5816 gboolean found = FALSE;
5818 /* Fastpath */
5819 if (!UnlockedRead (&joinable_thread_count))
5820 return;
5822 while (TRUE) {
5823 joinable_threads_lock ();
5824 if (found) {
5825 // Previous native thread join call completed.
5826 threads_remove_pending_native_thread_join_call_nolock (key);
5828 found = FALSE;
5829 if (g_hash_table_size (joinable_threads)) {
5830 g_hash_table_iter_init (&iter, joinable_threads);
5831 g_hash_table_iter_next (&iter, &key, (void**)&value);
5832 g_hash_table_remove (joinable_threads, key);
5833 UnlockedDecrement (&joinable_thread_count);
5834 found = TRUE;
5836 // Add to table of tid's with pending native thread join call.
5837 threads_add_pending_native_thread_join_call_nolock (key);
5839 joinable_threads_unlock ();
5840 if (found)
5841 threads_native_thread_join_lock (key, value);
5842 else
5843 break;
5848 * mono_thread_join:
5850 * Wait for thread TID to exit.
5851 * LOCKING: Acquires the threads lock.
5853 void
5854 mono_thread_join (gpointer tid)
5856 gboolean found = FALSE;
5857 gpointer orig_key;
5858 gpointer value;
5860 joinable_threads_lock ();
5861 if (!joinable_threads)
5862 joinable_threads = g_hash_table_new (NULL, NULL);
5864 if (g_hash_table_lookup_extended (joinable_threads, tid, &orig_key, &value)) {
5865 g_hash_table_remove (joinable_threads, tid);
5866 UnlockedDecrement (&joinable_thread_count);
5867 found = TRUE;
5869 // Add to table of tid's with pending native join call.
5870 threads_add_pending_native_thread_join_call_nolock (tid);
5873 if (!found) {
5874 // Wait for any pending native thread join call not yet completed for this tid.
5875 threads_wait_pending_native_thread_join_call_nolock (tid);
5878 joinable_threads_unlock ();
5880 if (!found)
5881 return;
5883 threads_native_thread_join_nolock (tid, value);
5885 joinable_threads_lock ();
5886 // Native thread join call completed for this tid.
5887 threads_remove_pending_native_thread_join_call_nolock (tid);
5888 joinable_threads_unlock ();
5891 void
5892 mono_thread_internal_unhandled_exception (MonoObject* exc)
5894 MonoClass *klass = exc->vtable->klass;
5895 if (is_threadabort_exception (klass)) {
5896 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5897 } else if (!is_appdomainunloaded_exception (klass)
5898 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT) {
5899 mono_unhandled_exception_internal (exc);
5900 if (mono_environment_exitcode_get () == 1) {
5901 mono_environment_exitcode_set (255);
5902 mono_invoke_unhandled_exception_hook (exc);
5903 g_assert_not_reached ();
5908 void
5909 ves_icall_System_Threading_Thread_GetStackTraces (MonoArray **out_threads, MonoArray **out_stack_traces)
5911 ERROR_DECL (error);
5912 mono_threads_get_thread_dump (out_threads, out_stack_traces, error);
5913 mono_error_set_pending_exception (error);
5917 * mono_threads_attach_coop_internal: called by native->managed wrappers
5919 * - @cookie:
5920 * - blocking mode: contains gc unsafe transition cookie
5921 * - non-blocking mode: contains random data
5922 * - @stackdata: semi-opaque struct: stackpointer and function_name
5923 * - @return: the original domain which needs to be restored, or NULL.
5925 MonoDomain*
5926 mono_threads_attach_coop_internal (MonoDomain *domain, gpointer *cookie, MonoStackData *stackdata)
5928 MonoDomain *orig;
5929 MonoThreadInfo *info;
5930 gboolean external = FALSE;
5932 orig = mono_domain_get ();
5934 if (!domain) {
5935 /* Happens when called from AOTed code which is only used in the root domain. */
5936 domain = mono_get_root_domain ();
5937 g_assert (domain);
5940 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
5941 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
5942 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
5943 * we're only responsible for making the cookie. */
5944 if (mono_threads_is_blocking_transition_enabled ())
5945 external = !(info = mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info);
5947 if (!mono_thread_internal_current ()) {
5948 mono_thread_attach (domain);
5950 // #678164
5951 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
5954 if (orig != domain)
5955 mono_domain_set (domain, TRUE);
5957 if (mono_threads_is_blocking_transition_enabled ()) {
5958 if (external) {
5959 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
5960 * return the right cookie. */
5961 *cookie = mono_threads_enter_gc_unsafe_region_cookie ();
5962 } else {
5963 /* thread state (BLOCKING|RUNNING) -> RUNNING */
5964 *cookie = mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata);
5968 return orig;
5972 * mono_threads_attach_coop: called by native->managed wrappers
5974 * - @dummy:
5975 * - blocking mode: contains gc unsafe transition cookie
5976 * - non-blocking mode: contains random data
5977 * - a pointer to stack, used for some checks
5978 * - @return: the original domain which needs to be restored, or NULL.
5980 gpointer
5981 mono_threads_attach_coop (MonoDomain *domain, gpointer *dummy)
5983 MONO_STACKDATA (stackdata);
5984 stackdata.stackpointer = dummy;
5985 return mono_threads_attach_coop_internal (domain, dummy, &stackdata);
5989 * mono_threads_detach_coop_internal: called by native->managed wrappers
5991 * - @orig: the original domain which needs to be restored, or NULL.
5992 * - @stackdata: semi-opaque struct: stackpointer and function_name
5993 * - @cookie:
5994 * - blocking mode: contains gc unsafe transition cookie
5995 * - non-blocking mode: contains random data
5997 void
5998 mono_threads_detach_coop_internal (MonoDomain *orig, gpointer cookie, MonoStackData *stackdata)
6000 MonoDomain *domain = mono_domain_get ();
6001 g_assert (domain);
6003 if (mono_threads_is_blocking_transition_enabled ()) {
6004 /* it won't do anything if cookie is NULL
6005 * thread state RUNNING -> (RUNNING|BLOCKING) */
6006 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie, stackdata);
6009 if (orig != domain) {
6010 if (!orig)
6011 mono_domain_unset ();
6012 else
6013 mono_domain_set (orig, TRUE);
6018 * mono_threads_detach_coop: called by native->managed wrappers
6020 * - @orig: the original domain which needs to be restored, or NULL.
6021 * - @dummy:
6022 * - blocking mode: contains gc unsafe transition cookie
6023 * - non-blocking mode: contains random data
6024 * - a pointer to stack, used for some checks
6026 void
6027 mono_threads_detach_coop (gpointer orig, gpointer *dummy)
6029 MONO_STACKDATA (stackdata);
6030 stackdata.stackpointer = dummy;
6031 mono_threads_detach_coop_internal ((MonoDomain*)orig, *dummy, &stackdata);
6034 #if 0
6035 /* Returns TRUE if the current thread is ready to be interrupted. */
6036 gboolean
6037 mono_threads_is_ready_to_be_interrupted (void)
6039 MonoInternalThread *thread;
6041 thread = mono_thread_internal_current ();
6042 LOCK_THREAD (thread);
6043 if (thread->state & (ThreadState_SuspendRequested | ThreadState_AbortRequested)) {
6044 UNLOCK_THREAD (thread);
6045 return FALSE;
6048 if (mono_thread_get_abort_prot_block_count (thread) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6049 UNLOCK_THREAD (thread);
6050 return FALSE;
6053 UNLOCK_THREAD (thread);
6054 return TRUE;
6056 #endif
6058 void
6059 mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
6061 g_string_append_printf (text, ", thread handle : %p", internal->handle);
6063 if (internal->thread_info) {
6064 g_string_append (text, ", state : ");
6065 mono_thread_info_describe_interrupt_token (internal->thread_info, text);
6068 if (internal->owned_mutexes) {
6069 int i;
6071 g_string_append (text, ", owns : [");
6072 for (i = 0; i < internal->owned_mutexes->len; i++)
6073 g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
6074 g_string_append (text, "]");
6078 gboolean
6079 mono_thread_internal_is_current (MonoInternalThread *internal)
6081 g_assert (internal);
6082 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
6085 gboolean
6086 mono_thread_internal_is_current_handle (MonoInternalThreadHandle internal)
6088 return mono_thread_internal_is_current (MONO_HANDLE_RAW (internal));
6091 void
6092 mono_set_thread_dump_dir (gchar* dir) {
6093 thread_dump_dir = dir;
6096 #ifdef DISABLE_CRASH_REPORTING
6097 gboolean
6098 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6100 return FALSE;
6103 gboolean
6104 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6106 return FALSE;
6109 #else
6111 static gboolean
6112 mono_threads_summarize_native_self (MonoThreadSummary *out, MonoContext *ctx)
6114 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6115 return FALSE;
6117 memset (out, 0, sizeof (MonoThreadSummary));
6118 out->ctx = ctx;
6120 MonoNativeThreadId current = mono_native_thread_id_get();
6121 out->native_thread_id = (intptr_t) current;
6123 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out);
6125 mono_native_thread_get_name (current, out->name, MONO_MAX_SUMMARY_NAME_LEN);
6127 return TRUE;
6130 // Not safe to call from signal handler
6131 gboolean
6132 mono_threads_summarize_one (MonoThreadSummary *out, MonoContext *ctx)
6134 gboolean success = mono_threads_summarize_native_self (out, ctx);
6136 // Finish this on the same thread
6138 if (success && mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6139 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out);
6141 return success;
6144 #define TIMEOUT_CRASH_REPORTER_FATAL 30
6145 #define MAX_NUM_THREADS 128
6146 typedef struct {
6147 gint32 has_owner; // state of this memory
6149 MonoSemType update; // notify of addition of threads
6151 int nthreads;
6152 MonoNativeThreadId thread_array [MAX_NUM_THREADS]; // ids of threads we're dumping
6154 int nthreads_attached; // Number of threads self-registered
6155 MonoThreadSummary *all_threads [MAX_NUM_THREADS];
6157 gboolean silent; // print to stdout
6158 } SummarizerGlobalState;
6160 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6161 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6162 #endif
6164 typedef struct {
6165 MonoSemType supervisor;
6166 pid_t pid;
6167 pid_t supervisor_pid;
6168 } SummarizerSupervisorState;
6170 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6171 static void
6172 summarizer_supervisor_wait (SummarizerSupervisorState *state)
6174 return;
6177 static pid_t
6178 summarizer_supervisor_start (SummarizerSupervisorState *state)
6180 // nonzero, so caller doesn't think it's the supervisor
6181 return (pid_t) 1;
6184 static void
6185 summarizer_supervisor_end (SummarizerSupervisorState *state)
6187 return;
6190 #else
6191 static void
6192 summarizer_supervisor_wait (SummarizerSupervisorState *state)
6194 sleep (TIMEOUT_CRASH_REPORTER_FATAL);
6196 // If we haven't been SIGKILL'ed yet, we signal our parent
6197 // and then exit
6198 #ifdef HAVE_KILL
6199 g_async_safe_printf("Crash Reporter has timed out, sending SIGSEGV\n");
6200 kill (state->pid, SIGSEGV);
6201 #else
6202 g_error ("kill () is not supported by this platform");
6203 #endif
6205 exit (1);
6208 static pid_t
6209 summarizer_supervisor_start (SummarizerSupervisorState *state)
6211 memset (state, 0, sizeof (*state));
6212 pid_t pid;
6214 state->pid = getpid();
6217 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6218 * it will deadlock. Call the syscall directly instead.
6220 #if defined(HOST_ANDROID)
6221 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6222 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6223 g_assert_not_reached ();
6224 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6225 pid = (pid_t) syscall (SYS_fork);
6226 #elif HAVE_FORK
6227 pid = (pid_t) fork ();
6228 #else
6229 g_assert_not_reached ();
6230 #endif
6232 if (pid != 0)
6233 state->supervisor_pid = pid;
6235 return pid;
6238 static void
6239 summarizer_supervisor_end (SummarizerSupervisorState *state)
6241 #ifdef HAVE_KILL
6242 kill (state->supervisor_pid, SIGKILL);
6243 #endif
6245 #if defined (HAVE_WAITPID)
6246 // Accessed on same thread that sets it.
6247 int status;
6248 waitpid (state->supervisor_pid, &status, 0);
6249 #endif
6251 #endif
6253 static gboolean
6254 summarizer_state_init (SummarizerGlobalState *state, MonoNativeThreadId current, int *my_index)
6256 gint32 started_state = mono_atomic_cas_i32 (&state->has_owner, 1 /* set */, 0 /* compare */);
6257 gboolean not_started = started_state == 0;
6258 if (not_started) {
6259 state->nthreads = collect_thread_ids (state->thread_array, MAX_NUM_THREADS);
6260 mono_os_sem_init (&state->update, 0);
6263 for (int i = 0; i < state->nthreads; i++) {
6264 if (state->thread_array [i] == current) {
6265 *my_index = i;
6266 break;
6270 return not_started;
6273 static void
6274 summarizer_signal_other_threads (SummarizerGlobalState *state, MonoNativeThreadId current, int current_idx)
6276 sigset_t sigset, old_sigset;
6277 sigemptyset(&sigset);
6278 sigaddset(&sigset, SIGTERM);
6280 for (int i=0; i < state->nthreads; i++) {
6281 sigprocmask (SIG_UNBLOCK, &sigset, &old_sigset);
6283 if (i == current_idx)
6284 continue;
6286 #ifdef HAVE_PTHREAD_KILL
6287 pthread_kill (state->thread_array [i], SIGTERM);
6289 if (!state->silent)
6290 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));
6291 #else
6292 g_error ("pthread_kill () is not supported by this platform");
6293 #endif
6297 // Returns true when there are shared global references to "this_thread"
6298 static gboolean
6299 summarizer_post_dump (SummarizerGlobalState *state, MonoThreadSummary *this_thread, int current_idx)
6301 mono_memory_barrier ();
6303 gpointer old = mono_atomic_cas_ptr ((volatile gpointer *)&state->all_threads [current_idx], this_thread, NULL);
6305 if (old == GINT_TO_POINTER (-1)) {
6306 g_async_safe_printf ("Trying to register response after dumping period ended");
6307 return FALSE;
6308 } else if (old != NULL) {
6309 g_async_safe_printf ("Thread dump raced for thread slot.");
6310 return FALSE;
6313 // We added our pointer
6314 gint32 count = mono_atomic_inc_i32 ((volatile gint32 *) &state->nthreads_attached);
6315 if (count == state->nthreads)
6316 mono_os_sem_post (&state->update);
6318 return TRUE;
6321 // A lockless spinwait with a timeout
6322 // Used in environments where locks are unsafe
6324 // If set_pos is true, we wait until the expected number of threads have
6325 // responded and then count that the expected number are set. If it is not true,
6326 // then we wait for them to be unset.
6327 static void
6328 summary_timedwait (SummarizerGlobalState *state, int timeout_seconds)
6330 const gint64 milliseconds_in_second = 1000;
6331 gint64 timeout_total = milliseconds_in_second * timeout_seconds;
6333 gint64 end = mono_msec_ticks () + timeout_total;
6335 while (TRUE) {
6336 if (mono_atomic_load_i32 ((volatile gint32 *) &state->nthreads_attached) == state->nthreads)
6337 break;
6339 gint64 now = mono_msec_ticks ();
6340 gint64 remaining = end - now;
6341 if (remaining <= 0)
6342 break;
6344 mono_os_sem_timedwait (&state->update, remaining, MONO_SEM_FLAGS_NONE);
6347 return;
6350 static MonoThreadSummary *
6351 summarizer_try_read_thread (SummarizerGlobalState *state, int index)
6353 gpointer old_value = NULL;
6354 gpointer new_value = GINT_TO_POINTER(-1);
6356 do {
6357 old_value = state->all_threads [index];
6358 } while (mono_atomic_cas_ptr ((volatile gpointer *) &state->all_threads [index], new_value, old_value) != old_value);
6360 MonoThreadSummary *thread = (MonoThreadSummary *) old_value;
6361 return thread;
6364 static void
6365 summarizer_state_term (SummarizerGlobalState *state, gchar **out, gchar *mem, size_t provided_size, MonoThreadSummary *controlling)
6367 // See the array writes
6368 mono_memory_barrier ();
6370 MonoThreadSummary *threads [MAX_NUM_THREADS];
6371 memset (threads, 0, sizeof(threads));
6373 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks);
6374 for (int i=0; i < state->nthreads; i++) {
6375 threads [i] = summarizer_try_read_thread (state, i);
6376 if (!threads [i])
6377 continue;
6379 // We are doing this dump on the controlling thread because this isn't
6380 // an async context sometimes. There's still some reliance on malloc here, but it's
6381 // much more stable to do it all from the controlling thread.
6383 // This is non-null, checked in mono_threads_summarize
6384 // with early exit there
6385 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads [i]);
6388 MonoStateWriter writer;
6389 memset (&writer, 0, sizeof (writer));
6391 mono_summarize_timeline_phase_log (MonoSummaryStateWriter);
6392 mono_summarize_native_state_begin (&writer, mem, provided_size);
6393 for (int i=0; i < state->nthreads; i++) {
6394 MonoThreadSummary *thread = threads [i];
6395 if (!thread)
6396 continue;
6398 mono_summarize_native_state_add_thread (&writer, thread, thread->ctx, thread == controlling);
6399 // Set non-shared state to notify the waiting thread to clean up
6400 // without having to keep our shared state alive
6401 mono_atomic_store_i32 (&thread->done, 0x1);
6402 mono_os_sem_post (&thread->done_wait);
6404 *out = mono_summarize_native_state_end (&writer);
6405 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone);
6407 mono_os_sem_destroy (&state->update);
6409 memset (state, 0, sizeof (*state));
6410 mono_atomic_store_i32 ((volatile gint32 *)&state->has_owner, 0);
6413 static void
6414 summarizer_state_wait (MonoThreadSummary *thread)
6416 gint64 milliseconds_in_second = 1000;
6418 // cond_wait can spuriously wake up, so we need to check
6419 // done
6420 while (!mono_atomic_load_i32 (&thread->done))
6421 mono_os_sem_timedwait (&thread->done_wait, milliseconds_in_second, MONO_SEM_FLAGS_NONE);
6424 gboolean
6425 mono_threads_summarize_execute (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gchar *working_mem, size_t provided_size)
6427 static SummarizerGlobalState state;
6429 int current_idx;
6430 MonoNativeThreadId current = mono_native_thread_id_get ();
6431 gboolean this_thread_controls = summarizer_state_init (&state, current, &current_idx);
6433 if (state.nthreads == 0) {
6434 if (!silent)
6435 g_async_safe_printf("No threads attached to runtime.\n");
6436 memset (&state, 0, sizeof (state));
6437 return FALSE;
6440 if (this_thread_controls) {
6441 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake);
6442 state.silent = silent;
6443 summarizer_signal_other_threads (&state, current, current_idx);
6444 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks);
6447 MonoStateMem mem;
6448 gboolean success = mono_state_alloc_mem (&mem, (long) current, sizeof (MonoThreadSummary));
6449 if (!success)
6450 return FALSE;
6452 MonoThreadSummary *this_thread = (MonoThreadSummary *) mem.mem;
6454 if (mono_threads_summarize_native_self (this_thread, ctx)) {
6455 // Init the synchronization between the controlling thread and the
6456 // providing thread
6457 mono_os_sem_init (&this_thread->done_wait, 0);
6459 // Store a reference to our stack memory into global state
6460 gboolean success = summarizer_post_dump (&state, this_thread, current_idx);
6461 if (!success && !state.silent)
6462 g_async_safe_printf("Thread 0x%zx reported itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6463 } else if (!state.silent) {
6464 g_async_safe_printf("Thread 0x%zx couldn't report itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6467 // From summarizer, wait and dump.
6468 if (this_thread_controls) {
6469 if (!state.silent)
6470 g_async_safe_printf("Entering thread summarizer pause from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6472 // Wait up to 2 seconds for all of the other threads to catch up
6473 summary_timedwait (&state, 2);
6475 if (!state.silent)
6476 g_async_safe_printf("Finished thread summarizer pause from 0x%zx.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current));
6478 // Dump and cleanup all the stack memory
6479 summarizer_state_term (&state, out, working_mem, provided_size, this_thread);
6480 } else {
6481 // Wait here, keeping our stack memory alive
6482 // for the dumper
6483 summarizer_state_wait (this_thread);
6486 // FIXME: How many threads should be counted?
6487 if (hashes)
6488 *hashes = this_thread->hashes;
6490 mono_state_free_mem (&mem);
6492 return TRUE;
6495 gboolean
6496 mono_threads_summarize (MonoContext *ctx, gchar **out, MonoStackHash *hashes, gboolean silent, gboolean signal_handler_controller, gchar *mem, size_t provided_size)
6498 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack)
6499 return FALSE;
6501 // The staggered values are due to the need to use inc_i64 for the first value
6502 static gint64 next_pending_request_id = 0;
6503 static gint64 request_available_to_run = 1;
6504 gint64 this_request_id = mono_atomic_inc_i64 ((volatile gint64 *) &next_pending_request_id);
6506 // This is a global queue of summary requests.
6507 // It's not safe to signal a thread while they're in the
6508 // middle of a dump. Dladdr is not reentrant. It's the one lock
6509 // we rely on being able to take.
6511 // We don't use it in almost any other place in managed code, so
6512 // our problem is in the stack dumping code racing with the signalling code.
6514 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6515 // If we're running from a crash handler block, we're not in any position to
6516 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6517 // We should simply return so we can die cleanly.
6519 // signal_handler_controller should be set only from a handler that expects itself to be the only
6520 // entry point, where the runtime already being dumping means we should just give up
6522 gboolean success = FALSE;
6524 while (TRUE) {
6525 gint64 next_request_id = mono_atomic_load_i64 ((volatile gint64 *) &request_available_to_run);
6527 if (next_request_id == this_request_id) {
6528 gboolean already_async = mono_thread_info_is_async_context ();
6529 if (!already_async)
6530 mono_thread_info_set_is_async_context (TRUE);
6532 SummarizerSupervisorState synch;
6533 if (summarizer_supervisor_start (&synch)) {
6534 success = mono_threads_summarize_execute (ctx, out, hashes, silent, mem, provided_size);
6535 summarizer_supervisor_end (&synch);
6536 } else {
6537 summarizer_supervisor_wait (&synch);
6540 if (!already_async)
6541 mono_thread_info_set_is_async_context (FALSE);
6543 // Only the thread that gets the ticket can unblock future dumpers.
6544 mono_atomic_inc_i64 ((volatile gint64 *) &request_available_to_run);
6545 break;
6546 } else if (signal_handler_controller) {
6547 // We're done. We can't do anything.
6548 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6549 mono_summarize_double_fault_log ();
6550 break;
6551 } else {
6552 if (!silent)
6553 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6554 sleep (2);
6558 return success;
6561 #endif