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