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/gc-internals.h>
30 #include <mono/metadata/marshal.h>
31 #include <mono/metadata/runtime.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/debug-internals.h>
34 #include <mono/utils/monobitset.h>
35 #include <mono/utils/mono-compiler.h>
36 #include <mono/utils/mono-mmap.h>
37 #include <mono/utils/mono-membar.h>
38 #include <mono/utils/mono-time.h>
39 #include <mono/utils/mono-threads.h>
40 #include <mono/utils/mono-threads-coop.h>
41 #include <mono/utils/mono-tls.h>
42 #include <mono/utils/atomic.h>
43 #include <mono/utils/mono-memory-model.h>
44 #include <mono/utils/mono-error-internals.h>
45 #include <mono/utils/os-event.h>
46 #include <mono/utils/mono-threads-debug.h>
47 #include <mono/utils/unlocked.h>
48 #include <mono/metadata/w32handle.h>
49 #include <mono/metadata/w32event.h>
50 #include <mono/metadata/w32mutex.h>
52 #include <mono/metadata/reflection-internals.h>
53 #include <mono/metadata/abi-details.h>
54 #include <mono/metadata/w32error.h>
55 #include <mono/utils/w32api.h>
56 #include <mono/utils/mono-os-wait.h>
57 #include <mono/metadata/exception-internals.h>
63 #if defined(HOST_WIN32)
67 mono_native_thread_join_handle (HANDLE thread_handle
, gboolean close_handle
);
70 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
71 #define USE_TKILL_ON_ANDROID 1
77 #ifdef USE_TKILL_ON_ANDROID
78 extern int tkill (pid_t tid
, int signal
);
82 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
83 #define THREAD_DEBUG(a)
84 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
85 #define THREAD_WAIT_DEBUG(a)
86 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
87 #define LIBGC_DEBUG(a)
89 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
90 #define SPIN_LOCK(i) do { \
91 if (SPIN_TRYLOCK (i)) \
95 #define SPIN_UNLOCK(i) i = 0
97 #define LOCK_THREAD(thread) lock_thread((thread))
98 #define UNLOCK_THREAD(thread) unlock_thread((thread))
110 typedef struct _StaticDataFreeList StaticDataFreeList
;
111 struct _StaticDataFreeList
{
112 StaticDataFreeList
*next
;
120 StaticDataFreeList
*freelist
;
123 /* Controls access to the 'threads' hash table */
124 static void mono_threads_lock (void);
125 static void mono_threads_unlock (void);
126 static MonoCoopMutex threads_mutex
;
128 /* Controls access to the 'joinable_threads' hash table */
129 #define joinable_threads_lock() mono_os_mutex_lock (&joinable_threads_mutex)
130 #define joinable_threads_unlock() mono_os_mutex_unlock (&joinable_threads_mutex)
131 static mono_mutex_t joinable_threads_mutex
;
133 /* Holds current status of static data heap */
134 static StaticDataInfo thread_static_info
;
135 static StaticDataInfo context_static_info
;
137 /* The hash of existing threads (key is thread ID, value is
138 * MonoInternalThread*) that need joining before exit
140 static MonoGHashTable
*threads
=NULL
;
142 /* List of app context GC handles.
143 * Added to from mono_threads_register_app_context ().
145 static GHashTable
*contexts
= NULL
;
147 /* Cleanup queue for contexts. */
148 static MonoReferenceQueue
*context_queue
;
151 * Threads which are starting up and they are not in the 'threads' hash yet.
152 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
153 * Protected by mono_threads_lock ().
155 static MonoGHashTable
*threads_starting_up
= NULL
;
158 /* Protected by the threads lock */
159 static GHashTable
*joinable_threads
;
160 static gint32 joinable_thread_count
;
162 static GHashTable
*pending_joinable_threads
;
163 static gint32 pending_joinable_thread_count
;
165 static mono_cond_t zero_pending_joinable_thread_event
;
167 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo
*mono_thread_info
);
168 static gboolean
threads_wait_pending_joinable_threads (uint32_t timeout
);
170 #define SET_CURRENT_OBJECT(x) (mono_tls_set_thread (x))
171 #define GET_CURRENT_OBJECT() ((MonoInternalThread*) mono_tls_get_thread ())
173 /* function called at thread start */
174 static MonoThreadStartCB mono_thread_start_cb
= NULL
;
176 /* function called at thread attach */
177 static MonoThreadAttachCB mono_thread_attach_cb
= NULL
;
179 /* function called at thread cleanup */
180 static MonoThreadCleanupFunc mono_thread_cleanup_fn
= NULL
;
182 /* The default stack size for each thread */
183 static guint32 default_stacksize
= 0;
184 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
186 static void context_adjust_static_data (MonoAppContext
*ctx
);
187 static void mono_free_static_data (gpointer
* static_data
);
188 static void mono_init_static_data_info (StaticDataInfo
*static_data
);
189 static guint32
mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
);
190 static gboolean
mono_thread_resume (MonoInternalThread
* thread
);
191 static void async_abort_internal (MonoInternalThread
*thread
, gboolean install_async_abort
);
192 static void self_abort_internal (MonoError
*error
);
193 static void async_suspend_internal (MonoInternalThread
*thread
, gboolean interrupt
);
194 static void self_suspend_internal (void);
197 mono_thread_set_interruption_requested_flags (MonoInternalThread
*thread
, gboolean sync
);
199 static MonoException
*
200 mono_thread_execute_interruption (void);
203 mono_thread_execute_interruption_void (void);
205 static void ref_stack_destroy (gpointer rs
);
207 /* Spin lock for InterlockedXXX 64 bit functions */
208 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
209 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
210 static mono_mutex_t interlocked_mutex
;
212 /* global count of thread interruptions requested */
213 static gint32 thread_interruption_requested
= 0;
215 /* Event signaled when a thread changes its background mode */
216 static MonoOSEvent background_change_event
;
218 static gboolean shutting_down
= FALSE
;
220 static gint32 managed_thread_id_counter
= 0;
223 mono_threads_lock (void)
225 mono_locks_coop_acquire (&threads_mutex
, ThreadsLock
);
229 mono_threads_unlock (void)
231 mono_locks_coop_release (&threads_mutex
, ThreadsLock
);
236 get_next_managed_thread_id (void)
238 return mono_atomic_inc_i32 (&managed_thread_id_counter
);
242 * We separate interruptions/exceptions into either sync (they can be processed anytime,
243 * normally as soon as they are set, and are set by the same thread) and async (they can't
244 * be processed inside abort protected blocks and are normally set by other threads). We
245 * can have both a pending sync and async interruption. In this case, the sync exception is
246 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
247 * also handle all sync type exceptions before the async type exceptions.
250 INTERRUPT_SYNC_REQUESTED_BIT
= 0x1,
251 INTERRUPT_ASYNC_REQUESTED_BIT
= 0x2,
252 INTERRUPT_REQUESTED_MASK
= 0x3,
253 ABORT_PROT_BLOCK_SHIFT
= 2,
254 ABORT_PROT_BLOCK_BITS
= 8,
255 ABORT_PROT_BLOCK_MASK
= (((1 << ABORT_PROT_BLOCK_BITS
) - 1) << ABORT_PROT_BLOCK_SHIFT
)
259 mono_thread_get_abort_prot_block_count (MonoInternalThread
*thread
)
261 gsize state
= thread
->thread_state
;
262 return (state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
;
266 mono_threads_is_current_thread_in_protected_block (void)
268 MonoInternalThread
*thread
= mono_thread_internal_current ();
270 return mono_thread_get_abort_prot_block_count (thread
) > 0;
274 mono_threads_begin_abort_protected_block (void)
276 MonoInternalThread
*thread
= mono_thread_internal_current ();
277 gsize old_state
, new_state
;
280 old_state
= thread
->thread_state
;
282 new_val
= ((old_state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
) + 1;
283 //bounds check abort_prot_count
284 g_assert (new_val
> 0);
285 g_assert (new_val
< (1 << ABORT_PROT_BLOCK_BITS
));
287 new_state
= old_state
+ (1 << ABORT_PROT_BLOCK_SHIFT
);
288 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
290 /* Defer async request since we won't be able to process until exiting the block */
291 if (new_val
== 1 && (new_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)) {
292 mono_atomic_dec_i32 (&thread_interruption_requested
);
293 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
294 if (thread_interruption_requested
< 0)
295 g_warning ("bad thread_interruption_requested state");
297 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
302 mono_thread_state_has_interruption (gsize state
)
304 /* pending exception, self abort */
305 if (state
& INTERRUPT_SYNC_REQUESTED_BIT
)
308 /* abort, interruption, suspend */
309 if ((state
& INTERRUPT_ASYNC_REQUESTED_BIT
) && !(state
& ABORT_PROT_BLOCK_MASK
))
316 mono_threads_end_abort_protected_block (void)
318 MonoInternalThread
*thread
= mono_thread_internal_current ();
319 gsize old_state
, new_state
;
322 old_state
= thread
->thread_state
;
324 //bounds check abort_prot_count
325 new_val
= ((old_state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
) - 1;
326 g_assert (new_val
>= 0);
327 g_assert (new_val
< (1 << ABORT_PROT_BLOCK_BITS
));
329 new_state
= old_state
- (1 << ABORT_PROT_BLOCK_SHIFT
);
330 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
332 if (new_val
== 0 && (new_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)) {
333 mono_atomic_inc_i32 (&thread_interruption_requested
);
334 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
336 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
339 return mono_thread_state_has_interruption (new_state
);
343 mono_thread_get_interruption_requested (MonoInternalThread
*thread
)
345 gsize state
= thread
->thread_state
;
347 return mono_thread_state_has_interruption (state
);
351 * Returns TRUE is there was a state change
352 * We clear a single interruption request, sync has priority.
355 mono_thread_clear_interruption_requested (MonoInternalThread
*thread
)
357 gsize old_state
, new_state
;
359 old_state
= thread
->thread_state
;
361 // no interruption to process
362 if (!(old_state
& INTERRUPT_SYNC_REQUESTED_BIT
) &&
363 (!(old_state
& INTERRUPT_ASYNC_REQUESTED_BIT
) || (old_state
& ABORT_PROT_BLOCK_MASK
)))
366 if (old_state
& INTERRUPT_SYNC_REQUESTED_BIT
)
367 new_state
= old_state
& ~INTERRUPT_SYNC_REQUESTED_BIT
;
369 new_state
= old_state
& ~INTERRUPT_ASYNC_REQUESTED_BIT
;
370 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
372 mono_atomic_dec_i32 (&thread_interruption_requested
);
373 THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
374 if (thread_interruption_requested
< 0)
375 g_warning ("bad thread_interruption_requested state");
379 /* Returns TRUE is there was a state change and the interruption can be processed */
381 mono_thread_set_interruption_requested (MonoInternalThread
*thread
)
383 //always force when the current thread is doing it to itself.
384 gboolean sync
= thread
== mono_thread_internal_current ();
385 /* Normally synchronous interruptions can bypass abort protection. */
386 return mono_thread_set_interruption_requested_flags (thread
, sync
);
389 /* Returns TRUE if there was a state change and the interruption can be
390 * processed. This variant defers a self abort when inside an abort protected
391 * block. Normally this should only be done when a thread has received an
392 * outside indication that it should abort. (For example when the JIT sets a
393 * flag in an finally block.)
397 mono_thread_set_self_interruption_respect_abort_prot (void)
399 MonoInternalThread
*thread
= mono_thread_internal_current ();
400 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
401 * which is unusual. */
402 return mono_thread_set_interruption_requested_flags (thread
, FALSE
);
405 /* Returns TRUE if there was a state change and the interruption can be processed. */
407 mono_thread_set_interruption_requested_flags (MonoInternalThread
*thread
, gboolean sync
)
409 gsize old_state
, new_state
;
411 old_state
= thread
->thread_state
;
414 if ((sync
&& (old_state
& INTERRUPT_SYNC_REQUESTED_BIT
)) ||
415 (!sync
&& (old_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)))
419 new_state
= old_state
| INTERRUPT_SYNC_REQUESTED_BIT
;
421 new_state
= old_state
| INTERRUPT_ASYNC_REQUESTED_BIT
;
422 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
424 if (sync
|| !(new_state
& ABORT_PROT_BLOCK_MASK
)) {
425 mono_atomic_inc_i32 (&thread_interruption_requested
);
426 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id
, thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
428 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id
, thread
->small_id
, old_state
, new_state
, thread_interruption_requested
);
431 return sync
|| !(new_state
& ABORT_PROT_BLOCK_MASK
);
434 static inline MonoNativeThreadId
435 thread_get_tid (MonoInternalThread
*thread
)
437 /* We store the tid as a guint64 to keep the object layout constant between platforms */
438 return MONO_UINT_TO_NATIVE_THREAD_ID (thread
->tid
);
441 static void ensure_synch_cs_set (MonoInternalThread
*thread
)
443 MonoCoopMutex
*synch_cs
;
445 if (thread
->synch_cs
!= NULL
) {
449 synch_cs
= g_new0 (MonoCoopMutex
, 1);
450 mono_coop_mutex_init_recursive (synch_cs
);
452 if (mono_atomic_cas_ptr ((gpointer
*)&thread
->synch_cs
,
453 synch_cs
, NULL
) != NULL
) {
454 /* Another thread must have installed this CS */
455 mono_coop_mutex_destroy (synch_cs
);
461 lock_thread (MonoInternalThread
*thread
)
463 if (!thread
->synch_cs
)
464 ensure_synch_cs_set (thread
);
466 g_assert (thread
->synch_cs
);
468 mono_coop_mutex_lock (thread
->synch_cs
);
472 unlock_thread (MonoInternalThread
*thread
)
474 mono_coop_mutex_unlock (thread
->synch_cs
);
477 static inline gboolean
478 is_appdomainunloaded_exception (MonoClass
*klass
)
480 return klass
== mono_class_get_appdomain_unloaded_exception_class ();
483 static inline gboolean
484 is_threadabort_exception (MonoClass
*klass
)
486 return klass
== mono_defaults
.threadabortexception_class
;
490 * A special static data offset (guint32) consists of 3 parts:
492 * [0] 6-bit index into the array of chunks.
493 * [6] 25-bit offset into the array.
494 * [31] Bit indicating thread or context static.
499 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
510 } SpecialStaticOffset
;
512 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
513 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
515 #define MAKE_SPECIAL_STATIC_OFFSET(idx, off, ty) \
516 ((SpecialStaticOffset) { .fields = { .index = (idx), .offset = (off), .type = (ty) } }.raw)
517 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
518 (((SpecialStaticOffset *) &(x))->fields.f)
521 get_thread_static_data (MonoInternalThread
*thread
, guint32 offset
)
523 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) == SPECIAL_STATIC_OFFSET_TYPE_THREAD
);
525 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
526 int off
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
528 return ((char *) thread
->static_data
[idx
]) + off
;
532 get_context_static_data (MonoAppContext
*ctx
, guint32 offset
)
534 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT
);
536 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
537 int off
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
539 return ((char *) ctx
->static_data
[idx
]) + off
;
543 get_current_thread_ptr_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
)
545 static MonoClassField
*current_thread_field
= NULL
;
549 if (!current_thread_field
) {
550 current_thread_field
= mono_class_get_field_from_name (mono_defaults
.thread_class
, "current_thread");
551 g_assert (current_thread_field
);
554 ERROR_DECL_VALUE (thread_vt_error
);
555 mono_class_vtable_checked (domain
, mono_defaults
.thread_class
, &thread_vt_error
);
556 mono_error_assert_ok (&thread_vt_error
);
557 mono_domain_lock (domain
);
558 offset
= GPOINTER_TO_UINT (g_hash_table_lookup (domain
->special_static_fields
, current_thread_field
));
559 mono_domain_unlock (domain
);
562 return (MonoThread
**)get_thread_static_data (thread
, offset
);
566 set_current_thread_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
, MonoThread
*current
)
568 MonoThread
**current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, thread
);
570 g_assert (current
->obj
.vtable
->domain
== domain
);
572 g_assert (!*current_thread_ptr
);
573 *current_thread_ptr
= current
;
577 create_thread_object (MonoDomain
*domain
, MonoInternalThread
*internal
)
583 vtable
= mono_class_vtable_checked (domain
, mono_defaults
.thread_class
, error
);
584 mono_error_assert_ok (error
);
586 thread
= (MonoThread
*)mono_object_new_mature (vtable
, error
);
587 /* only possible failure mode is OOM, from which we don't expect to recover. */
588 mono_error_assert_ok (error
);
590 MONO_OBJECT_SETREF (thread
, internal_thread
, internal
);
595 static MonoInternalThread
*
596 create_internal_thread_object (void)
599 MonoInternalThread
*thread
;
602 vt
= mono_class_vtable_checked (mono_get_root_domain (), mono_defaults
.internal_thread_class
, error
);
603 mono_error_assert_ok (error
);
604 thread
= (MonoInternalThread
*) mono_object_new_mature (vt
, error
);
605 /* only possible failure mode is OOM, from which we don't exect to recover */
606 mono_error_assert_ok (error
);
608 thread
->synch_cs
= g_new0 (MonoCoopMutex
, 1);
609 mono_coop_mutex_init_recursive (thread
->synch_cs
);
611 thread
->apartment_state
= ThreadApartmentState_Unknown
;
612 thread
->managed_id
= get_next_managed_thread_id ();
613 if (mono_gc_is_moving ()) {
614 thread
->thread_pinning_ref
= thread
;
615 MONO_GC_REGISTER_ROOT_PINNING (thread
->thread_pinning_ref
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Pinning Reference");
618 thread
->priority
= MONO_THREAD_PRIORITY_NORMAL
;
620 thread
->suspended
= g_new0 (MonoOSEvent
, 1);
621 mono_os_event_init (thread
->suspended
, TRUE
);
627 mono_thread_internal_set_priority (MonoInternalThread
*internal
, MonoThreadPriority priority
)
631 g_assert (priority
>= MONO_THREAD_PRIORITY_LOWEST
);
632 g_assert (priority
<= MONO_THREAD_PRIORITY_HIGHEST
);
633 g_assert (MONO_THREAD_PRIORITY_LOWEST
< MONO_THREAD_PRIORITY_HIGHEST
);
638 g_assert (internal
->native_handle
);
640 res
= SetThreadPriority (internal
->native_handle
, priority
- 2);
642 g_error ("%s: SetThreadPriority failed, error %d", __func__
, GetLastError ());
643 #else /* HOST_WIN32 */
646 struct sched_param param
;
649 tid
= thread_get_tid (internal
);
651 res
= pthread_getschedparam (tid
, &policy
, ¶m
);
653 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
655 #ifdef _POSIX_PRIORITY_SCHEDULING
658 /* Necessary to get valid priority range */
660 #if defined(__PASE__)
661 /* only priorities allowed by IBM i */
665 min
= sched_get_priority_min (policy
);
666 max
= sched_get_priority_max (policy
);
669 if (max
> 0 && min
>= 0 && max
> min
) {
670 double srange
, drange
, sposition
, dposition
;
671 srange
= MONO_THREAD_PRIORITY_HIGHEST
- MONO_THREAD_PRIORITY_LOWEST
;
673 sposition
= priority
- MONO_THREAD_PRIORITY_LOWEST
;
674 dposition
= (sposition
/ srange
) * drange
;
675 param
.sched_priority
= (int)(dposition
+ min
);
682 param
.sched_priority
= 50;
688 param
.sched_priority
= 0;
691 g_warning ("%s: unknown policy %d", __func__
, policy
);
696 #if defined(__PASE__)
697 /* only scheduling param allowed by IBM i */
698 res
= pthread_setschedparam (tid
, SCHED_OTHER
, ¶m
);
700 res
= pthread_setschedparam (tid
, policy
, ¶m
);
704 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
707 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
709 #endif /* HOST_WIN32 */
713 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, void *alloc_key
, gboolean threadlocal
);
716 mono_thread_attach_internal (MonoThread
*thread
, gboolean force_attach
, gboolean force_domain
)
718 MonoThreadInfo
*info
;
719 MonoInternalThread
*internal
;
720 MonoDomain
*domain
, *root_domain
;
725 info
= mono_thread_info_current ();
728 internal
= thread
->internal_thread
;
731 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
732 * - the MonoInternalThread TLS key is destroyed: set it to NULL
733 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
734 * - it calls MonoThreadInfoCallbacks.thread_detach
735 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
736 mono_thread_info_set_internal_thread_gchandle (info
, mono_gchandle_new ((MonoObject
*) internal
, FALSE
));
738 internal
->handle
= mono_threads_open_thread_handle (info
->handle
);
740 internal
->native_handle
= OpenThread (THREAD_ALL_ACCESS
, FALSE
, GetCurrentThreadId ());
742 internal
->tid
= MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
743 internal
->thread_info
= info
;
744 internal
->small_id
= info
->small_id
;
746 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Setting current_object_key to %p", __func__
, mono_native_thread_id_get (), internal
));
748 SET_CURRENT_OBJECT (internal
);
750 domain
= mono_object_domain (thread
);
752 mono_thread_push_appdomain_ref (domain
);
753 if (!mono_domain_set (domain
, force_domain
)) {
754 mono_thread_pop_appdomain_ref ();
758 mono_threads_lock ();
760 if (shutting_down
&& !force_attach
) {
761 mono_threads_unlock ();
762 mono_thread_pop_appdomain_ref ();
766 if (threads_starting_up
)
767 mono_g_hash_table_remove (threads_starting_up
, thread
);
770 threads
= mono_g_hash_table_new_type (NULL
, NULL
, MONO_HASH_VALUE_GC
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Table");
773 /* We don't need to duplicate thread->handle, because it is
774 * only closed when the thread object is finalized by the GC. */
775 mono_g_hash_table_insert (threads
, (gpointer
)(gsize
)(internal
->tid
), internal
);
777 /* We have to do this here because mono_thread_start_cb
778 * requires that root_domain_thread is set up. */
779 if (thread_static_info
.offset
|| thread_static_info
.idx
> 0) {
780 /* get the current allocated size */
781 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (thread_static_info
.idx
, thread_static_info
.offset
, 0);
782 mono_alloc_static_data (&internal
->static_data
, offset
, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
), TRUE
);
785 mono_threads_unlock ();
787 root_domain
= mono_get_root_domain ();
789 g_assert (!internal
->root_domain_thread
);
790 if (domain
!= root_domain
)
791 MONO_OBJECT_SETREF (internal
, root_domain_thread
, create_thread_object (root_domain
, internal
));
793 MONO_OBJECT_SETREF (internal
, root_domain_thread
, thread
);
795 if (domain
!= root_domain
)
796 set_current_thread_for_domain (root_domain
, internal
, internal
->root_domain_thread
);
798 set_current_thread_for_domain (domain
, internal
, thread
);
800 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, internal
->tid
, internal
->handle
));
805 mono_threads_lock ();
806 if (threads_starting_up
)
807 mono_g_hash_table_remove (threads_starting_up
, thread
);
808 mono_threads_unlock ();
810 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
811 g_error ("%s: failed to get gchandle, info %p", __func__
, info
);
813 mono_gchandle_free (gchandle
);
815 mono_thread_info_unset_internal_thread_gchandle (info
);
817 SET_CURRENT_OBJECT(NULL
);
823 mono_thread_detach_internal (MonoInternalThread
*thread
)
825 MonoThreadInfo
*info
;
826 MonoInternalThread
*value
;
830 g_assert (mono_thread_internal_is_current (thread
));
832 g_assert (thread
!= NULL
);
833 SET_CURRENT_OBJECT (thread
);
835 info
= (MonoThreadInfo
*) thread
->thread_info
;
838 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
840 MONO_PROFILER_RAISE (thread_stopping
, (thread
->tid
));
843 * Prevent race condition between thread shutdown and runtime shutdown.
844 * Including all runtime threads in the pending joinable count will make
845 * sure shutdown will wait for it to get onto the joinable thread list before
846 * critical resources have been cleanup (like GC memory). Threads getting onto
847 * the joinable thread list should just about to exit and not blocking a potential
848 * join call. Owner of threads attached to the runtime but not identified as runtime
849 * threads needs to make sure thread detach calls won't race with runtime shutdown.
851 threads_add_pending_joinable_runtime_thread (info
);
854 mono_w32mutex_abandon (thread
);
857 mono_gchandle_free (thread
->abort_state_handle
);
858 thread
->abort_state_handle
= 0;
860 thread
->abort_exc
= NULL
;
861 thread
->current_appcontext
= NULL
;
864 * thread->synch_cs can be NULL if this was called after
865 * ves_icall_System_Threading_InternalThread_Thread_free_internal.
866 * This can happen only during shutdown.
867 * The shutting_down flag is not always set, so we can't assert on it.
869 if (thread
->synch_cs
)
870 LOCK_THREAD (thread
);
872 thread
->state
|= ThreadState_Stopped
;
873 thread
->state
&= ~ThreadState_Background
;
875 if (thread
->synch_cs
)
876 UNLOCK_THREAD (thread
);
879 An interruption request has leaked to cleanup. Adjust the global counter.
881 This can happen is the abort source thread finds the abortee (this) thread
882 in unmanaged code. If this thread never trips back to managed code or check
883 the local flag it will be left set and positively unbalance the global counter.
885 Leaving the counter unbalanced will cause a performance degradation since all threads
886 will now keep checking their local flags all the time.
888 mono_thread_clear_interruption_requested (thread
);
890 mono_threads_lock ();
894 if (!mono_g_hash_table_lookup_extended (threads
, (gpointer
)thread
->tid
, NULL
, (gpointer
*) &value
)) {
895 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__
, thread
, thread
->tid
);
896 } else if (thread
!= value
) {
897 /* We have to check whether the thread object for the tid is still the same in the table because the
898 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
899 * the table, but with another thread object. */
900 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__
, thread
, thread
->tid
, value
, value
->tid
);
903 removed
= mono_g_hash_table_remove (threads
, (gpointer
)thread
->tid
);
906 mono_threads_unlock ();
908 /* Don't close the handle here, wait for the object finalizer
909 * to do it. Otherwise, the following race condition applies:
911 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
913 * 2) Some other handle is reassigned the same slot
915 * 3) Another thread tries to join the first thread, and
916 * blocks waiting for the reassigned handle to be signalled
917 * (which might never happen). This is possible, because the
918 * thread calling Join() still has a reference to the first
922 mono_release_type_locks (thread
);
924 MONO_PROFILER_RAISE (thread_stopped
, (thread
->tid
));
925 MONO_PROFILER_RAISE (gc_root_unregister
, (info
->stack_start_limit
));
926 MONO_PROFILER_RAISE (gc_root_unregister
, (info
->handle_stack
));
929 * This will signal async signal handlers that the thread has exited.
930 * The profiler callback needs this to be set, so it cannot be done earlier.
932 mono_domain_unset ();
933 mono_memory_barrier ();
935 mono_thread_pop_appdomain_ref ();
937 mono_free_static_data (thread
->static_data
);
938 thread
->static_data
= NULL
;
939 ref_stack_destroy (thread
->appdomain_refs
);
940 thread
->appdomain_refs
= NULL
;
942 g_assert (thread
->suspended
);
943 mono_os_event_destroy (thread
->suspended
);
944 g_free (thread
->suspended
);
945 thread
->suspended
= NULL
;
947 if (mono_thread_cleanup_fn
)
948 mono_thread_cleanup_fn (thread_get_tid (thread
));
950 mono_memory_barrier ();
952 if (mono_gc_is_moving ()) {
953 MONO_GC_UNREGISTER_ROOT (thread
->thread_pinning_ref
);
954 thread
->thread_pinning_ref
= NULL
;
957 /* There is no more any guarantee that `thread` is alive */
958 mono_memory_barrier ();
960 SET_CURRENT_OBJECT (NULL
);
961 mono_domain_unset ();
963 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
964 g_error ("%s: failed to get gchandle, info = %p", __func__
, info
);
966 mono_gchandle_free (gchandle
);
968 mono_thread_info_unset_internal_thread_gchandle (info
);
970 MONO_PROFILER_RAISE (thread_exited
, (thread
->tid
));
972 /* Don't need to close the handle to this thread, even though we took a
973 * reference in mono_thread_attach (), because the GC will do it
974 * when the Thread object is finalised.
981 MonoObject
*start_delegate
;
982 MonoObject
*start_delegate_arg
;
983 MonoThreadStart start_func
;
984 gpointer start_func_arg
;
985 gboolean force_attach
;
987 MonoCoopSem registered
;
991 fire_attach_profiler_events (MonoNativeThreadId tid
)
993 MONO_PROFILER_RAISE (thread_started
, ((uintptr_t) tid
));
995 MonoThreadInfo
*info
= mono_thread_info_current ();
997 MONO_PROFILER_RAISE (gc_root_register
, (
998 info
->stack_start_limit
,
999 (char *) info
->stack_end
- (char *) info
->stack_start_limit
,
1000 MONO_ROOT_SOURCE_STACK
,
1004 // The handle stack is a pseudo-root similar to the finalizer queues.
1005 MONO_PROFILER_RAISE (gc_root_register
, (
1008 MONO_ROOT_SOURCE_HANDLE
,
1013 static guint32 WINAPI
start_wrapper_internal(StartInfo
*start_info
, gsize
*stack_ptr
)
1016 MonoThreadStart start_func
;
1017 void *start_func_arg
;
1020 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1024 MonoInternalThread
*internal
;
1025 MonoObject
*start_delegate
;
1026 MonoObject
*start_delegate_arg
;
1029 thread
= start_info
->thread
;
1030 internal
= thread
->internal_thread
;
1031 domain
= mono_object_domain (start_info
->thread
);
1033 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Start wrapper", __func__
, mono_native_thread_id_get ()));
1035 if (!mono_thread_attach_internal (thread
, start_info
->force_attach
, FALSE
)) {
1036 start_info
->failed
= TRUE
;
1038 mono_coop_sem_post (&start_info
->registered
);
1040 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1041 mono_coop_sem_destroy (&start_info
->registered
);
1042 g_free (start_info
);
1048 mono_thread_internal_set_priority (internal
, internal
->priority
);
1050 tid
= internal
->tid
;
1052 start_delegate
= start_info
->start_delegate
;
1053 start_delegate_arg
= start_info
->start_delegate_arg
;
1054 start_func
= start_info
->start_func
;
1055 start_func_arg
= start_info
->start_func_arg
;
1057 /* This MUST be called before any managed code can be
1058 * executed, as it calls the callback function that (for the
1059 * jit) sets the lmf marker.
1062 if (mono_thread_start_cb
)
1063 mono_thread_start_cb (tid
, stack_ptr
, start_func
);
1065 /* On 2.0 profile (and higher), set explicitly since state might have been
1067 if (internal
->apartment_state
== ThreadApartmentState_Unknown
)
1068 internal
->apartment_state
= ThreadApartmentState_MTA
;
1070 mono_thread_init_apartment_state ();
1072 /* Let the thread that called Start() know we're ready */
1073 mono_coop_sem_post (&start_info
->registered
);
1075 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1076 mono_coop_sem_destroy (&start_info
->registered
);
1077 g_free (start_info
);
1080 /* start_info is not valid anymore */
1084 * Call this after calling start_notify, since the profiler callback might want
1085 * to lock the thread, and the lock is held by thread_start () which waits for
1088 fire_attach_profiler_events ((MonoNativeThreadId
) tid
);
1090 /* if the name was set before starting, we didn't invoke the profiler callback */
1091 if (internal
->name
) {
1092 char *tname
= g_utf16_to_utf8 (internal
->name
, internal
->name_len
, NULL
, NULL
, NULL
);
1093 MONO_PROFILER_RAISE (thread_name
, (internal
->tid
, tname
));
1094 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
), tname
);
1098 /* start_func is set only for unmanaged start functions */
1100 start_func (start_func_arg
);
1104 g_assert (start_delegate
!= NULL
);
1106 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1107 args
[0] = (gpointer
) start_delegate_arg
;
1108 mono_runtime_delegate_invoke_checked (start_delegate
, args
, error
);
1110 if (!mono_error_ok (error
)) {
1111 MonoException
*ex
= mono_error_convert_to_exception (error
);
1113 g_assert (ex
!= NULL
);
1114 MonoClass
*klass
= mono_object_get_class (&ex
->object
);
1115 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY
) &&
1116 !is_threadabort_exception (klass
)) {
1117 mono_unhandled_exception (&ex
->object
);
1118 mono_invoke_unhandled_exception_hook (&ex
->object
);
1119 g_assert_not_reached ();
1122 mono_error_cleanup (error
);
1126 /* If the thread calls ExitThread at all, this remaining code
1127 * will not be executed, but the main thread will eventually
1128 * call mono_thread_detach_internal() on this thread's behalf.
1131 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Start wrapper terminating", __func__
, mono_native_thread_id_get ()));
1133 /* Do any cleanup needed for apartment state. This
1134 * cannot be done in mono_thread_detach_internal since
1135 * mono_thread_detach_internal could be called for a
1136 * thread other than the current thread.
1137 * mono_thread_cleanup_apartment_state cleans up apartment
1138 * for the current thead */
1139 mono_thread_cleanup_apartment_state ();
1141 mono_thread_detach_internal (internal
);
1147 start_wrapper (gpointer data
)
1149 StartInfo
*start_info
;
1150 MonoThreadInfo
*info
;
1153 start_info
= (StartInfo
*) data
;
1154 g_assert (start_info
);
1156 info
= mono_thread_info_attach ();
1157 info
->runtime_thread
= TRUE
;
1159 /* Run the actual main function of the thread */
1160 res
= start_wrapper_internal (start_info
, info
->stack_end
);
1162 mono_thread_info_exit (res
);
1164 g_assert_not_reached ();
1170 * Common thread creation code.
1171 * LOCKING: Acquires the threads lock.
1174 create_thread (MonoThread
*thread
, MonoInternalThread
*internal
, MonoObject
*start_delegate
, MonoThreadStart start_func
, gpointer start_func_arg
,
1175 MonoThreadCreateFlags flags
, MonoError
*error
)
1177 StartInfo
*start_info
= NULL
;
1178 MonoNativeThreadId tid
;
1180 gsize stack_set_size
;
1183 g_assert (!start_func
&& !start_func_arg
);
1185 g_assert (!start_delegate
);
1187 if (flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
) {
1188 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
));
1189 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
));
1191 if (flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
) {
1192 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
));
1193 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
));
1197 * Join joinable threads to prevent running out of threads since the finalizer
1198 * thread might be blocked/backlogged.
1200 mono_threads_join_threads ();
1204 mono_threads_lock ();
1205 if (shutting_down
&& !(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
)) {
1206 mono_threads_unlock ();
1209 if (threads_starting_up
== NULL
) {
1210 threads_starting_up
= mono_g_hash_table_new_type (NULL
, NULL
, MONO_HASH_KEY_VALUE_GC
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Starting Table");
1212 mono_g_hash_table_insert (threads_starting_up
, thread
, thread
);
1213 mono_threads_unlock ();
1215 internal
->threadpool_thread
= flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
;
1216 if (internal
->threadpool_thread
)
1217 mono_thread_set_state (internal
, ThreadState_Background
);
1219 internal
->debugger_thread
= flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
;
1221 start_info
= g_new0 (StartInfo
, 1);
1222 start_info
->ref
= 2;
1223 start_info
->thread
= thread
;
1224 start_info
->start_delegate
= start_delegate
;
1225 start_info
->start_delegate_arg
= thread
->start_obj
;
1226 start_info
->start_func
= start_func
;
1227 start_info
->start_func_arg
= start_func_arg
;
1228 start_info
->force_attach
= flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
;
1229 start_info
->failed
= FALSE
;
1230 mono_coop_sem_init (&start_info
->registered
, 0);
1232 if (flags
!= MONO_THREAD_CREATE_FLAGS_SMALL_STACK
)
1233 stack_set_size
= default_stacksize_for_thread (internal
);
1237 if (!mono_thread_platform_create_thread ((MonoThreadStart
)start_wrapper
, start_info
, &stack_set_size
, &tid
)) {
1238 /* The thread couldn't be created, so set an exception */
1239 mono_threads_lock ();
1240 mono_g_hash_table_remove (threads_starting_up
, thread
);
1241 mono_threads_unlock ();
1242 mono_error_set_execution_engine (error
, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1243 /* ref is not going to be decremented in start_wrapper_internal */
1244 mono_atomic_dec_i32 (&start_info
->ref
);
1249 internal
->stack_size
= (int) stack_set_size
;
1251 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Launching thread %p (%"G_GSIZE_FORMAT
")", __func__
, mono_native_thread_id_get (), internal
, (gsize
)internal
->tid
));
1254 * Wait for the thread to set up its TLS data etc, so
1255 * theres no potential race condition if someone tries
1256 * to look up the data believing the thread has
1260 mono_coop_sem_wait (&start_info
->registered
, MONO_SEM_FLAGS_NONE
);
1262 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
));
1264 ret
= !start_info
->failed
;
1267 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1268 mono_coop_sem_destroy (&start_info
->registered
);
1269 g_free (start_info
);
1276 * mono_thread_new_init:
1279 mono_thread_new_init (intptr_t tid
, gpointer stack_start
, gpointer func
)
1281 if (mono_thread_start_cb
) {
1282 mono_thread_start_cb (tid
, stack_start
, func
);
1287 * mono_threads_set_default_stacksize:
1290 mono_threads_set_default_stacksize (guint32 stacksize
)
1292 default_stacksize
= stacksize
;
1296 * mono_threads_get_default_stacksize:
1299 mono_threads_get_default_stacksize (void)
1301 return default_stacksize
;
1305 * mono_thread_create_internal:
1307 * ARG should not be a GC reference.
1310 mono_thread_create_internal (MonoDomain
*domain
, gpointer func
, gpointer arg
, MonoThreadCreateFlags flags
, MonoError
*error
)
1313 MonoInternalThread
*internal
;
1318 internal
= create_internal_thread_object ();
1320 thread
= create_thread_object (domain
, internal
);
1322 LOCK_THREAD (internal
);
1324 res
= create_thread (thread
, internal
, NULL
, (MonoThreadStart
) func
, arg
, flags
, error
);
1326 UNLOCK_THREAD (internal
);
1328 return_val_if_nok (error
, NULL
);
1333 * mono_thread_create:
1336 mono_thread_create (MonoDomain
*domain
, gpointer func
, gpointer arg
)
1339 if (!mono_thread_create_checked (domain
, func
, arg
, error
))
1340 mono_error_cleanup (error
);
1344 mono_thread_create_checked (MonoDomain
*domain
, gpointer func
, gpointer arg
, MonoError
*error
)
1346 return (NULL
!= mono_thread_create_internal (domain
, func
, arg
, MONO_THREAD_CREATE_FLAGS_NONE
, error
));
1350 * mono_thread_attach:
1353 mono_thread_attach (MonoDomain
*domain
)
1355 MonoInternalThread
*internal
;
1357 MonoThreadInfo
*info
;
1358 MonoNativeThreadId tid
;
1360 if (mono_thread_internal_current_is_attached ()) {
1361 if (domain
!= mono_domain_get ())
1362 mono_domain_set (domain
, TRUE
);
1363 /* Already attached */
1364 return mono_thread_current ();
1367 info
= mono_thread_info_attach ();
1370 tid
=mono_native_thread_id_get ();
1372 internal
= create_internal_thread_object ();
1374 thread
= create_thread_object (domain
, internal
);
1376 if (!mono_thread_attach_internal (thread
, FALSE
, TRUE
)) {
1377 /* Mono is shutting down, so just wait for the end */
1379 mono_thread_info_sleep (10000, NULL
);
1382 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, internal
->handle
));
1384 if (mono_thread_attach_cb
)
1385 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid
), info
->stack_end
);
1387 fire_attach_profiler_events (tid
);
1393 * mono_thread_detach:
1396 mono_thread_detach (MonoThread
*thread
)
1399 mono_thread_detach_internal (thread
->internal_thread
);
1403 * mono_thread_detach_if_exiting:
1405 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1406 * This should be used at the end of embedding code which calls into managed code, and which
1407 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1410 mono_thread_detach_if_exiting (void)
1412 if (mono_thread_info_is_exiting ()) {
1413 MonoInternalThread
*thread
;
1415 thread
= mono_thread_internal_current ();
1417 mono_thread_detach_internal (thread
);
1418 mono_thread_info_detach ();
1426 mono_thread_internal_current_is_attached (void)
1428 MonoInternalThread
*internal
;
1430 internal
= GET_CURRENT_OBJECT ();
1441 mono_thread_exit (void)
1443 MonoInternalThread
*thread
= mono_thread_internal_current ();
1445 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
1447 mono_thread_detach_internal (thread
);
1449 /* we could add a callback here for embedders to use. */
1450 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
))
1451 exit (mono_environment_exitcode_get ());
1453 mono_thread_info_exit (0);
1457 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle
)
1459 MonoInternalThread
*internal
;
1461 internal
= create_internal_thread_object ();
1463 internal
->state
= ThreadState_Unstarted
;
1465 int thread_gchandle
= mono_gchandle_from_handle ((MonoObjectHandle
)this_obj_handle
, TRUE
);
1467 MonoThreadObject
*this_obj
= MONO_HANDLE_RAW (this_obj_handle
);
1469 mono_atomic_cas_ptr ((volatile gpointer
*)&this_obj
->internal_thread
, internal
, NULL
);
1471 mono_gchandle_free (thread_gchandle
);
1475 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle
, MonoError
*error
)
1477 mono_thread_construct_internal (this_obj_handle
);
1480 MonoThreadObjectHandle
1481 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError
*error
)
1483 return MONO_HANDLE_NEW (MonoThreadObject
, mono_thread_current ());
1486 static MonoInternalThread
*
1487 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle
)
1489 return MONO_HANDLE_GETVAL(thread_handle
, internal_thread
); // InternalThreads are always pinned.
1493 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle
, MonoObjectHandle start_handle
, MonoError
*error
)
1495 MonoInternalThread
*internal
;
1497 MonoThread
*this_obj
= MONO_HANDLE_RAW (thread_handle
);
1498 MonoObject
*start
= MONO_HANDLE_RAW (start_handle
);
1500 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__
, this_obj
, start
));
1502 internal
= thread_handle_to_internal_ptr (thread_handle
);
1505 mono_thread_construct_internal (thread_handle
);
1506 internal
= thread_handle_to_internal_ptr (thread_handle
);
1507 g_assert (internal
);
1510 LOCK_THREAD (internal
);
1512 if ((internal
->state
& ThreadState_Unstarted
) == 0) {
1513 UNLOCK_THREAD (internal
);
1514 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has already been started."));
1518 if ((internal
->state
& ThreadState_Aborted
) != 0) {
1519 UNLOCK_THREAD (internal
);
1523 res
= create_thread (this_obj
, internal
, start
, NULL
, NULL
, MONO_THREAD_CREATE_FLAGS_NONE
, error
);
1525 mono_error_cleanup (error
);
1526 UNLOCK_THREAD (internal
);
1530 internal
->state
&= ~ThreadState_Unstarted
;
1532 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, thread
));
1534 UNLOCK_THREAD (internal
);
1539 * This is called from the finalizer of the internal thread object.
1542 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle
, MonoError
*error
)
1544 MonoInternalThread
*this_obj
= mono_internal_thread_handle_ptr (this_obj_handle
);
1545 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__
, this, this_obj
->handle
));
1548 * Since threads keep a reference to their thread object while running, by
1549 * the time this function is called, the thread has already exited/detached,
1550 * i.e. mono_thread_detach_internal () has ran. The exception is during
1551 * shutdown, when mono_thread_detach_internal () can be called after this.
1553 if (this_obj
->handle
) {
1554 mono_threads_close_thread_handle (this_obj
->handle
);
1555 this_obj
->handle
= NULL
;
1559 CloseHandle (this_obj
->native_handle
);
1562 if (this_obj
->synch_cs
) {
1563 MonoCoopMutex
*synch_cs
= this_obj
->synch_cs
;
1564 this_obj
->synch_cs
= NULL
;
1565 mono_coop_mutex_destroy (synch_cs
);
1569 if (this_obj
->name
) {
1570 void *name
= this_obj
->name
;
1571 this_obj
->name
= NULL
;
1577 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms
)
1580 MonoInternalThread
*thread
= mono_thread_internal_current ();
1582 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__
, ms
));
1584 if (mono_thread_current_check_pending_interrupt ())
1588 gboolean alerted
= FALSE
;
1590 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1592 res
= mono_thread_info_sleep (ms
, &alerted
);
1594 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1597 MonoException
* exc
= mono_thread_execute_interruption ();
1599 mono_set_pending_exception (exc
);
1602 // FIXME: !MONO_INFINITE_WAIT
1603 if (ms
!= MONO_INFINITE_WAIT
)
1613 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError
*error
)
1618 ves_icall_System_Threading_Thread_GetDomainID (MonoError
*error
)
1620 return mono_domain_get()->domain_id
;
1624 ves_icall_System_Threading_Thread_Yield (MonoError
*error
)
1626 return mono_thread_info_yield ();
1630 * mono_thread_get_name:
1632 * Return the name of the thread. NAME_LEN is set to the length of the name.
1633 * Return NULL if the thread has no name. The returned memory is owned by the
1637 mono_thread_get_name (MonoInternalThread
*this_obj
, guint32
*name_len
)
1641 LOCK_THREAD (this_obj
);
1643 if (!this_obj
->name
) {
1647 *name_len
= this_obj
->name_len
;
1648 res
= g_new (gunichar2
, this_obj
->name_len
);
1649 memcpy (res
, this_obj
->name
, sizeof (gunichar2
) * this_obj
->name_len
);
1652 UNLOCK_THREAD (this_obj
);
1658 * mono_thread_get_name_utf8:
1659 * \returns the name of the thread in UTF-8.
1660 * Return NULL if the thread has no name.
1661 * The returned memory is owned by the caller.
1664 mono_thread_get_name_utf8 (MonoThread
*thread
)
1669 MonoInternalThread
*internal
= thread
->internal_thread
;
1670 if (internal
== NULL
)
1673 LOCK_THREAD (internal
);
1675 char *tname
= g_utf16_to_utf8 (internal
->name
, internal
->name_len
, NULL
, NULL
, NULL
);
1677 UNLOCK_THREAD (internal
);
1683 * mono_thread_get_managed_id:
1684 * \returns the \c Thread.ManagedThreadId value of \p thread.
1685 * Returns \c -1 if \p thread is NULL.
1688 mono_thread_get_managed_id (MonoThread
*thread
)
1693 MonoInternalThread
*internal
= thread
->internal_thread
;
1694 if (internal
== NULL
)
1697 int32_t id
= internal
->managed_id
;
1703 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle
, MonoError
*error
)
1705 // InternalThreads are always pinned, so shallowly coop-handleize.
1706 MonoInternalThread
* const this_obj
= MONO_HANDLE_RAW (thread_handle
);
1708 MonoStringHandle str
= MONO_HANDLE_NEW (MonoString
, NULL
);
1710 LOCK_THREAD (this_obj
);
1713 MONO_HANDLE_ASSIGN (str
, mono_string_new_utf16_handle (mono_domain_get (), this_obj
->name
, this_obj
->name_len
, error
));
1715 UNLOCK_THREAD (this_obj
);
1721 mono_thread_set_name_internal (MonoInternalThread
*this_obj
, MonoString
*name
, gboolean permanent
, gboolean reset
, MonoError
*error
)
1723 MonoNativeThreadId tid
= 0;
1725 LOCK_THREAD (this_obj
);
1730 this_obj
->flags
&= ~MONO_THREAD_FLAG_NAME_SET
;
1731 } else if (this_obj
->flags
& MONO_THREAD_FLAG_NAME_SET
) {
1732 UNLOCK_THREAD (this_obj
);
1734 mono_error_set_invalid_operation (error
, "Thread.Name can only be set once.");
1737 if (this_obj
->name
) {
1738 g_free (this_obj
->name
);
1739 this_obj
->name_len
= 0;
1742 this_obj
->name
= g_memdup (mono_string_chars (name
), mono_string_length (name
) * sizeof (gunichar2
));
1743 this_obj
->name_len
= mono_string_length (name
);
1746 this_obj
->flags
|= MONO_THREAD_FLAG_NAME_SET
;
1749 this_obj
->name
= NULL
;
1751 if (!(this_obj
->state
& ThreadState_Stopped
))
1752 tid
= thread_get_tid (this_obj
);
1754 UNLOCK_THREAD (this_obj
);
1756 if (this_obj
->name
&& tid
) {
1757 char *tname
= mono_string_to_utf8_checked (name
, error
);
1758 return_if_nok (error
);
1759 MONO_PROFILER_RAISE (thread_name
, ((uintptr_t)tid
, tname
));
1760 mono_native_thread_set_name (tid
, tname
);
1766 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread
*this_obj
, MonoString
*name
)
1769 mono_thread_set_name_internal (this_obj
, name
, TRUE
, FALSE
, error
);
1770 mono_error_set_pending_exception (error
);
1774 * ves_icall_System_Threading_Thread_GetPriority_internal:
1775 * @param this_obj: The MonoInternalThread on which to operate.
1777 * Gets the priority of the given thread.
1778 * @return: The priority of the given thread.
1781 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj
, MonoError
*error
)
1785 MonoInternalThread
*internal
= thread_handle_to_internal_ptr (this_obj
);
1787 LOCK_THREAD (internal
);
1788 priority
= internal
->priority
;
1789 UNLOCK_THREAD (internal
);
1795 * ves_icall_System_Threading_Thread_SetPriority_internal:
1796 * @param this_obj: The MonoInternalThread on which to operate.
1797 * @param priority: The priority to set.
1799 * Sets the priority of the given thread.
1802 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj
, int priority
, MonoError
*error
)
1804 MonoInternalThread
*internal
= thread_handle_to_internal_ptr (this_obj
);
1806 LOCK_THREAD (internal
);
1807 internal
->priority
= priority
;
1808 if (internal
->thread_info
!= NULL
)
1809 mono_thread_internal_set_priority (internal
, priority
);
1810 UNLOCK_THREAD (internal
);
1813 /* If the array is already in the requested domain, we just return it,
1814 otherwise we return a copy in that domain. */
1815 static MonoArrayHandle
1816 byte_array_to_domain (MonoArrayHandle arr
, MonoDomain
*domain
, MonoError
*error
)
1818 HANDLE_FUNCTION_ENTER ()
1820 if (!arr
|| MONO_HANDLE_IS_NULL (arr
))
1821 return MONO_HANDLE_NEW (MonoArray
, NULL
);
1823 if (MONO_HANDLE_DOMAIN (arr
) == domain
)
1826 size_t const size
= mono_array_handle_length (arr
);
1828 // Capture arrays into common representation for repetitious code.
1829 // These two variables could also be an array of size 2 and
1830 // repitition implemented with a loop.
1832 MonoArrayHandle handle
;
1837 dest
= { mono_array_new_handle (domain
, mono_defaults
.byte_class
, size
, error
) };
1838 goto_if_nok (error
, exit
);
1841 source
.p
= mono_array_handle_pin_with_size (source
.handle
, size
, 0, &source
.gchandle
);
1842 dest
.p
= mono_array_handle_pin_with_size (dest
.handle
, size
, 0, &dest
.gchandle
);
1844 memmove (dest
.p
, source
.p
, size
);
1846 // Unpin both arrays.
1847 mono_gchandle_free (source
.gchandle
);
1848 mono_gchandle_free (dest
.gchandle
);
1850 HANDLE_FUNCTION_RETURN_REF (MonoArray
, dest
.handle
)
1854 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr
, MonoError
*error
)
1856 return byte_array_to_domain (arr
, mono_get_root_domain (), error
);
1860 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr
, MonoError
*error
)
1862 return byte_array_to_domain (arr
, mono_domain_get (), error
);
1866 * mono_thread_current:
1869 mono_thread_current (void)
1871 MonoDomain
*domain
= mono_domain_get ();
1872 MonoInternalThread
*internal
= mono_thread_internal_current ();
1873 MonoThread
**current_thread_ptr
;
1875 g_assert (internal
);
1876 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
1878 if (!*current_thread_ptr
) {
1879 g_assert (domain
!= mono_get_root_domain ());
1880 *current_thread_ptr
= create_thread_object (domain
, internal
);
1882 return *current_thread_ptr
;
1885 /* Return the thread object belonging to INTERNAL in the current domain */
1887 mono_thread_current_for_thread (MonoInternalThread
*internal
)
1889 MonoDomain
*domain
= mono_domain_get ();
1890 MonoThread
**current_thread_ptr
;
1892 g_assert (internal
);
1893 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
1895 if (!*current_thread_ptr
) {
1896 g_assert (domain
!= mono_get_root_domain ());
1897 *current_thread_ptr
= create_thread_object (domain
, internal
);
1899 return *current_thread_ptr
;
1903 mono_thread_internal_current (void)
1905 MonoInternalThread
*res
= GET_CURRENT_OBJECT ();
1906 THREAD_DEBUG (g_message ("%s: returning %p", __func__
, res
));
1910 static MonoThreadInfoWaitRet
1911 mono_join_uninterrupted (MonoThreadHandle
* thread_to_join
, gint32 ms
, MonoError
*error
)
1914 MonoThreadInfoWaitRet ret
;
1921 start
= (ms
== -1) ? 0 : mono_msec_ticks ();
1924 ret
= mono_thread_info_wait_one_handle (thread_to_join
, wait
, TRUE
);
1927 if (ret
!= MONO_THREAD_INFO_WAIT_RET_ALERTED
)
1930 exc
= mono_thread_execute_interruption ();
1932 mono_error_set_exception_instance (error
, exc
);
1939 /* Re-calculate ms according to the time passed */
1940 diff_ms
= (gint32
)(mono_msec_ticks () - start
);
1941 if (diff_ms
>= ms
) {
1942 ret
= MONO_THREAD_INFO_WAIT_RET_TIMEOUT
;
1945 wait
= ms
- diff_ms
;
1952 ves_icall_System_Threading_Thread_Join_internal (MonoThread
*this_obj
, int ms
)
1954 MonoInternalThread
*thread
= this_obj
->internal_thread
;
1955 MonoThreadHandle
*handle
= thread
->handle
;
1956 MonoInternalThread
*cur_thread
= mono_thread_internal_current ();
1960 if (mono_thread_current_check_pending_interrupt ())
1963 LOCK_THREAD (thread
);
1965 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
1966 UNLOCK_THREAD (thread
);
1968 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started."));
1972 UNLOCK_THREAD (thread
);
1975 ms
= MONO_INFINITE_WAIT
;
1976 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__
, handle
, ms
));
1978 mono_thread_set_state (cur_thread
, ThreadState_WaitSleepJoin
);
1980 ret
= mono_join_uninterrupted (handle
, ms
, error
);
1982 mono_thread_clr_state (cur_thread
, ThreadState_WaitSleepJoin
);
1984 mono_error_set_pending_exception (error
);
1986 if (ret
== MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
) {
1987 THREAD_DEBUG (g_message ("%s: join successful", __func__
));
1989 /* Wait for the thread to really exit */
1990 MonoNativeThreadId tid
= thread_get_tid (thread
);
1991 mono_thread_join (tid
);
1996 THREAD_DEBUG (g_message ("%s: join failed", __func__
));
2001 #define MANAGED_WAIT_FAILED 0x7fffffff
2004 map_native_wait_result_to_managed (MonoW32HandleWaitRet val
, gsize numobjects
)
2006 if (val
>= MONO_W32HANDLE_WAIT_RET_SUCCESS_0
&& val
< MONO_W32HANDLE_WAIT_RET_SUCCESS_0
+ numobjects
) {
2007 return WAIT_OBJECT_0
+ (val
- MONO_W32HANDLE_WAIT_RET_SUCCESS_0
);
2008 } else if (val
>= MONO_W32HANDLE_WAIT_RET_ABANDONED_0
&& val
< MONO_W32HANDLE_WAIT_RET_ABANDONED_0
+ numobjects
) {
2009 return WAIT_ABANDONED_0
+ (val
- MONO_W32HANDLE_WAIT_RET_ABANDONED_0
);
2010 } else if (val
== MONO_W32HANDLE_WAIT_RET_ALERTED
) {
2011 return WAIT_IO_COMPLETION
;
2012 } else if (val
== MONO_W32HANDLE_WAIT_RET_TIMEOUT
) {
2013 return WAIT_TIMEOUT
;
2014 } else if (val
== MONO_W32HANDLE_WAIT_RET_FAILED
) {
2015 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2016 return MANAGED_WAIT_FAILED
;
2018 g_error ("%s: unknown val value %d", __func__
, val
);
2023 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer
*handles
, gint32 numhandles
, MonoBoolean waitall
, gint32 timeout
, MonoError
*error
)
2025 MonoW32HandleWaitRet ret
;
2026 MonoInternalThread
*thread
;
2029 guint32 timeoutLeft
;
2031 /* Do this WaitSleepJoin check before creating objects */
2032 if (mono_thread_current_check_pending_interrupt ())
2033 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED
, 0);
2035 thread
= mono_thread_internal_current ();
2037 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
2040 timeout
= MONO_INFINITE_WAIT
;
2041 if (timeout
!= MONO_INFINITE_WAIT
)
2042 start
= mono_msec_ticks ();
2044 timeoutLeft
= timeout
;
2049 if (numhandles
!= 1)
2050 ret
= mono_w32handle_convert_wait_ret (mono_win32_wait_for_multiple_objects_ex(numhandles
, handles
, waitall
, timeoutLeft
, TRUE
), numhandles
);
2052 ret
= mono_w32handle_convert_wait_ret (mono_win32_wait_for_single_object_ex (handles
[0], timeoutLeft
, TRUE
), 1);
2055 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2056 ret
= mono_w32handle_wait_multiple (handles
, numhandles
, waitall
, timeoutLeft
, TRUE
);
2057 #endif /* HOST_WIN32 */
2059 if (ret
!= MONO_W32HANDLE_WAIT_RET_ALERTED
)
2062 exc
= mono_thread_execute_interruption ();
2064 mono_error_set_exception_instance (error
, exc
);
2068 if (timeout
!= MONO_INFINITE_WAIT
) {
2071 elapsed
= mono_msec_ticks () - start
;
2072 if (elapsed
>= timeout
) {
2073 ret
= MONO_W32HANDLE_WAIT_RET_TIMEOUT
;
2077 timeoutLeft
= timeout
- elapsed
;
2081 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
2083 return map_native_wait_result_to_managed (ret
, numhandles
);
2086 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
2089 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal
, gpointer toWait
, gint32 ms
, MonoError
*error
)
2091 MonoW32HandleWaitRet ret
;
2092 MonoInternalThread
*thread
= mono_thread_internal_current ();
2095 ms
= MONO_INFINITE_WAIT
;
2097 if (mono_thread_current_check_pending_interrupt ())
2098 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED
, 0);
2100 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
2104 ret
= mono_w32handle_convert_wait_ret (mono_win32_signal_object_and_wait (toSignal
, toWait
, ms
, TRUE
), 1);
2106 ret
= mono_w32handle_signal_and_wait (toSignal
, toWait
, ms
, TRUE
);
2110 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
2112 return map_native_wait_result_to_managed (ret
, 1);
2117 gint32
ves_icall_System_Threading_Interlocked_Increment_Int (gint32
*location
)
2119 return mono_atomic_inc_i32 (location
);
2122 gint64
ves_icall_System_Threading_Interlocked_Increment_Long (gint64
*location
)
2124 #if SIZEOF_VOID_P == 4
2125 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2127 mono_interlocked_lock ();
2130 mono_interlocked_unlock ();
2134 return mono_atomic_inc_i64 (location
);
2137 gint32
ves_icall_System_Threading_Interlocked_Decrement_Int (gint32
*location
)
2139 return mono_atomic_dec_i32(location
);
2142 gint64
ves_icall_System_Threading_Interlocked_Decrement_Long (gint64
* location
)
2144 #if SIZEOF_VOID_P == 4
2145 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2147 mono_interlocked_lock ();
2150 mono_interlocked_unlock ();
2154 return mono_atomic_dec_i64 (location
);
2157 gint32
ves_icall_System_Threading_Interlocked_Exchange_Int (gint32
*location
, gint32 value
)
2159 return mono_atomic_xchg_i32(location
, value
);
2162 MonoObject
* ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject
**location
, MonoObject
*value
)
2165 res
= (MonoObject
*) mono_atomic_xchg_ptr((gpointer
*) location
, value
);
2166 mono_gc_wbarrier_generic_nostore (location
);
2170 gpointer
ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer
*location
, gpointer value
)
2172 return mono_atomic_xchg_ptr(location
, value
);
2175 gfloat
ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat
*location
, gfloat value
)
2177 IntFloatUnion val
, ret
;
2180 ret
.ival
= mono_atomic_xchg_i32((gint32
*) location
, val
.ival
);
2186 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64
*location
, gint64 value
)
2188 #if SIZEOF_VOID_P == 4
2189 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2191 mono_interlocked_lock ();
2194 mono_interlocked_unlock ();
2198 return mono_atomic_xchg_i64 (location
, value
);
2202 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble
*location
, gdouble value
)
2204 LongDoubleUnion val
, ret
;
2207 ret
.ival
= (gint64
)mono_atomic_xchg_i64((gint64
*) location
, val
.ival
);
2212 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32
*location
, gint32 value
, gint32 comparand
)
2214 return mono_atomic_cas_i32(location
, value
, comparand
);
2217 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32
*location
, gint32 value
, gint32 comparand
, MonoBoolean
*success
)
2219 gint32 r
= mono_atomic_cas_i32(location
, value
, comparand
);
2220 *success
= r
== comparand
;
2224 MonoObject
* ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
2227 res
= (MonoObject
*) mono_atomic_cas_ptr((gpointer
*) location
, value
, comparand
);
2228 mono_gc_wbarrier_generic_nostore (location
);
2232 gpointer
ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer
*location
, gpointer value
, gpointer comparand
)
2234 return mono_atomic_cas_ptr(location
, value
, comparand
);
2237 gfloat
ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat
*location
, gfloat value
, gfloat comparand
)
2239 IntFloatUnion val
, ret
, cmp
;
2242 cmp
.fval
= comparand
;
2243 ret
.ival
= mono_atomic_cas_i32((gint32
*) location
, val
.ival
, cmp
.ival
);
2249 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble
*location
, gdouble value
, gdouble comparand
)
2251 #if SIZEOF_VOID_P == 8
2252 LongDoubleUnion val
, comp
, ret
;
2255 comp
.fval
= comparand
;
2256 ret
.ival
= (gint64
)mono_atomic_cas_ptr((gpointer
*) location
, (gpointer
)val
.ival
, (gpointer
)comp
.ival
);
2262 mono_interlocked_lock ();
2264 if (old
== comparand
)
2266 mono_interlocked_unlock ();
2273 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64
*location
, gint64 value
, gint64 comparand
)
2275 #if SIZEOF_VOID_P == 4
2276 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2278 mono_interlocked_lock ();
2280 if (old
== comparand
)
2282 mono_interlocked_unlock ();
2286 return mono_atomic_cas_i64 (location
, value
, comparand
);
2290 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
2293 res
= (MonoObject
*)mono_atomic_cas_ptr ((volatile gpointer
*)location
, value
, comparand
);
2294 mono_gc_wbarrier_generic_nostore (location
);
2299 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject
**location
, MonoObject
*value
)
2302 MONO_CHECK_NULL (location
, NULL
);
2303 res
= (MonoObject
*)mono_atomic_xchg_ptr ((volatile gpointer
*)location
, value
);
2304 mono_gc_wbarrier_generic_nostore (location
);
2309 ves_icall_System_Threading_Interlocked_Add_Int (gint32
*location
, gint32 value
)
2311 return mono_atomic_add_i32 (location
, value
);
2315 ves_icall_System_Threading_Interlocked_Add_Long (gint64
*location
, gint64 value
)
2317 #if SIZEOF_VOID_P == 4
2318 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2320 mono_interlocked_lock ();
2323 mono_interlocked_unlock ();
2327 return mono_atomic_add_i64 (location
, value
);
2331 ves_icall_System_Threading_Interlocked_Read_Long (gint64
*location
)
2333 #if SIZEOF_VOID_P == 4
2334 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2336 mono_interlocked_lock ();
2338 mono_interlocked_unlock ();
2342 return mono_atomic_load_i64 (location
);
2346 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2348 mono_memory_barrier ();
2352 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj
, guint32 state
, MonoError
*error
)
2354 // InternalThreads are always pinned, so shallowly coop-handleize.
2355 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj
), state
);
2359 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle
, guint32 state
, MonoError
*error
)
2361 // InternalThreads are always pinned, so shallowly coop-handleize.
2362 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle
), state
);
2366 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle
, MonoError
*error
)
2368 // InternalThreads are always pinned, so shallowly coop-handleize.
2369 MonoInternalThread
*this_obj
= mono_internal_thread_handle_ptr (thread_handle
);
2373 LOCK_THREAD (this_obj
);
2375 state
= this_obj
->state
;
2377 UNLOCK_THREAD (this_obj
);
2382 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread
*this_obj
)
2384 MonoInternalThread
*current
;
2386 MonoInternalThread
*thread
= this_obj
->internal_thread
;
2388 LOCK_THREAD (thread
);
2390 current
= mono_thread_internal_current ();
2392 thread
->thread_interrupt_requested
= TRUE
;
2393 throw_
= current
!= thread
&& (thread
->state
& ThreadState_WaitSleepJoin
);
2395 UNLOCK_THREAD (thread
);
2398 async_abort_internal (thread
, FALSE
);
2403 * mono_thread_current_check_pending_interrupt:
2404 * Checks if there's a interruption request and set the pending exception if so.
2405 * \returns true if a pending exception was set
2408 mono_thread_current_check_pending_interrupt (void)
2410 MonoInternalThread
*thread
= mono_thread_internal_current ();
2411 gboolean throw_
= FALSE
;
2413 LOCK_THREAD (thread
);
2415 if (thread
->thread_interrupt_requested
) {
2417 thread
->thread_interrupt_requested
= FALSE
;
2420 UNLOCK_THREAD (thread
);
2423 mono_set_pending_exception (mono_get_exception_thread_interrupted ());
2428 request_thread_abort (MonoInternalThread
*thread
, MonoObject
*state
, gboolean appdomain_unload
)
2430 LOCK_THREAD (thread
);
2432 if (thread
->state
& (ThreadState_AbortRequested
| ThreadState_Stopped
))
2434 UNLOCK_THREAD (thread
);
2438 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
2439 thread
->state
|= ThreadState_Aborted
;
2440 UNLOCK_THREAD (thread
);
2444 thread
->state
|= ThreadState_AbortRequested
;
2445 if (appdomain_unload
)
2446 thread
->flags
|= MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2448 thread
->flags
&= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2450 mono_gchandle_free (thread
->abort_state_handle
);
2451 thread
->abort_state_handle
= 0;
2454 thread
->abort_state_handle
= mono_gchandle_new (state
, FALSE
);
2455 g_assert (thread
->abort_state_handle
);
2458 thread
->abort_exc
= NULL
;
2460 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
));
2462 /* During shutdown, we can't wait for other threads */
2464 /* Make sure the thread is awake */
2465 mono_thread_resume (thread
);
2467 UNLOCK_THREAD (thread
);
2472 ves_icall_System_Threading_Thread_Abort (MonoInternalThread
*thread
, MonoObject
*state
)
2474 if (!request_thread_abort (thread
, state
, FALSE
))
2477 if (thread
== mono_thread_internal_current ()) {
2479 self_abort_internal (error
);
2480 mono_error_set_pending_exception (error
);
2482 async_abort_internal (thread
, TRUE
);
2487 * mono_thread_internal_abort:
2488 * Request thread \p thread to be aborted.
2489 * \p thread MUST NOT be the current thread.
2492 mono_thread_internal_abort (MonoInternalThread
*thread
, gboolean appdomain_unload
)
2494 g_assert (thread
!= mono_thread_internal_current ());
2496 if (!request_thread_abort (thread
, NULL
, appdomain_unload
))
2498 async_abort_internal (thread
, TRUE
);
2502 ves_icall_System_Threading_Thread_ResetAbort (MonoThread
*this_obj
)
2504 MonoInternalThread
*thread
= mono_thread_internal_current ();
2505 gboolean was_aborting
, is_domain_abort
;
2507 LOCK_THREAD (thread
);
2508 was_aborting
= thread
->state
& ThreadState_AbortRequested
;
2509 is_domain_abort
= thread
->flags
& MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2511 if (was_aborting
&& !is_domain_abort
)
2512 thread
->state
&= ~ThreadState_AbortRequested
;
2513 UNLOCK_THREAD (thread
);
2515 if (!was_aborting
) {
2516 const char *msg
= "Unable to reset abort because no abort was requested";
2517 mono_set_pending_exception (mono_get_exception_thread_state (msg
));
2519 } else if (is_domain_abort
) {
2520 /* Silently ignore abort resets in unloading appdomains */
2524 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2525 thread
->abort_exc
= NULL
;
2526 mono_gchandle_free (thread
->abort_state_handle
);
2527 /* This is actually not necessary - the handle
2528 only counts if the exception is set */
2529 thread
->abort_state_handle
= 0;
2533 mono_thread_internal_reset_abort (MonoInternalThread
*thread
)
2535 LOCK_THREAD (thread
);
2537 thread
->state
&= ~ThreadState_AbortRequested
;
2539 if (thread
->abort_exc
) {
2540 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2541 thread
->abort_exc
= NULL
;
2542 mono_gchandle_free (thread
->abort_state_handle
);
2543 /* This is actually not necessary - the handle
2544 only counts if the exception is set */
2545 thread
->abort_state_handle
= 0;
2548 UNLOCK_THREAD (thread
);
2552 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread
*this_obj
)
2555 MonoInternalThread
*thread
= this_obj
->internal_thread
;
2556 MonoObject
*state
, *deserialized
= NULL
;
2559 if (!thread
->abort_state_handle
)
2562 state
= mono_gchandle_get_target (thread
->abort_state_handle
);
2565 domain
= mono_domain_get ();
2566 if (mono_object_domain (state
) == domain
)
2569 deserialized
= mono_object_xdomain_representation (state
, domain
, error
);
2571 if (!deserialized
) {
2572 MonoException
*invalid_op_exc
= mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2573 if (!is_ok (error
)) {
2574 MonoObject
*exc
= (MonoObject
*)mono_error_convert_to_exception (error
);
2575 MONO_OBJECT_SETREF (invalid_op_exc
, inner_ex
, exc
);
2577 mono_set_pending_exception (invalid_op_exc
);
2581 return deserialized
;
2585 mono_thread_suspend (MonoInternalThread
*thread
)
2587 LOCK_THREAD (thread
);
2589 if (thread
->state
& (ThreadState_Unstarted
| ThreadState_Aborted
| ThreadState_Stopped
))
2591 UNLOCK_THREAD (thread
);
2595 if (thread
->state
& (ThreadState_Suspended
| ThreadState_SuspendRequested
| ThreadState_AbortRequested
))
2597 UNLOCK_THREAD (thread
);
2601 thread
->state
|= ThreadState_SuspendRequested
;
2603 mono_os_event_reset (thread
->suspended
);
2606 if (thread
== mono_thread_internal_current ()) {
2607 /* calls UNLOCK_THREAD (thread) */
2608 self_suspend_internal ();
2610 /* calls UNLOCK_THREAD (thread) */
2611 async_suspend_internal (thread
, FALSE
);
2618 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj
, MonoError
*error
)
2620 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj
)))
2621 mono_error_set_generic_error (error
, "System.Threading", "ThreadStateException", "Thread has not been started, or is dead.");
2625 /* LOCKING: LOCK_THREAD(thread) must be held */
2627 mono_thread_resume (MonoInternalThread
*thread
)
2629 if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
2630 // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (1) thread %p\n", thread_get_tid (thread));
2631 thread
->state
&= ~ThreadState_SuspendRequested
;
2633 mono_os_event_set (thread
->suspended
);
2638 if ((thread
->state
& ThreadState_Suspended
) == 0 ||
2639 (thread
->state
& ThreadState_Unstarted
) != 0 ||
2640 (thread
->state
& ThreadState_Aborted
) != 0 ||
2641 (thread
->state
& ThreadState_Stopped
) != 0)
2643 // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (2) thread %p\n", thread_get_tid (thread));
2647 // MOSTLY_ASYNC_SAFE_PRINTF ("RESUME (3) thread %p\n", thread_get_tid (thread));
2650 mono_os_event_set (thread
->suspended
);
2653 if (!thread
->self_suspended
) {
2654 UNLOCK_THREAD (thread
);
2656 /* Awake the thread */
2657 if (!mono_thread_info_resume (thread_get_tid (thread
)))
2660 LOCK_THREAD (thread
);
2663 thread
->state
&= ~ThreadState_Suspended
;
2669 ves_icall_System_Threading_Thread_Resume (MonoThread
*thread
)
2671 if (!thread
->internal_thread
) {
2672 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2674 LOCK_THREAD (thread
->internal_thread
);
2675 if (!mono_thread_resume (thread
->internal_thread
))
2676 mono_set_pending_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2677 UNLOCK_THREAD (thread
->internal_thread
);
2682 mono_threads_is_critical_method (MonoMethod
*method
)
2684 switch (method
->wrapper_type
) {
2685 case MONO_WRAPPER_RUNTIME_INVOKE
:
2686 case MONO_WRAPPER_XDOMAIN_INVOKE
:
2687 case MONO_WRAPPER_XDOMAIN_DISPATCH
:
2694 find_wrapper (MonoMethod
*m
, gint no
, gint ilo
, gboolean managed
, gpointer data
)
2699 if (mono_threads_is_critical_method (m
)) {
2700 *((gboolean
*)data
) = TRUE
;
2707 is_running_protected_wrapper (void)
2709 gboolean found
= FALSE
;
2710 mono_stack_walk (find_wrapper
, &found
);
2718 mono_thread_stop (MonoThread
*thread
)
2720 MonoInternalThread
*internal
= thread
->internal_thread
;
2722 if (!request_thread_abort (internal
, NULL
, FALSE
))
2725 if (internal
== mono_thread_internal_current ()) {
2727 self_abort_internal (error
);
2729 This function is part of the embeding API and has no way to return the exception
2730 to be thrown. So what we do is keep the old behavior and raise the exception.
2732 mono_error_raise_exception_deprecated (error
); /* OK to throw, see note */
2734 async_abort_internal (internal
, TRUE
);
2739 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr
)
2741 gint8 tmp
= *(volatile gint8
*)ptr
;
2742 mono_memory_barrier ();
2747 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr
)
2749 gint16 tmp
= *(volatile gint16
*)ptr
;
2750 mono_memory_barrier ();
2755 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr
)
2757 gint32 tmp
= *(volatile gint32
*)ptr
;
2758 mono_memory_barrier ();
2763 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr
)
2765 gint64 tmp
= *(volatile gint64
*)ptr
;
2766 mono_memory_barrier ();
2771 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr
)
2773 volatile void *tmp
= *(volatile void **)ptr
;
2774 mono_memory_barrier ();
2775 return (void *) tmp
;
2779 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr
)
2781 volatile MonoObject
*tmp
= *(volatile MonoObject
**)ptr
;
2782 mono_memory_barrier ();
2783 return (MonoObject
*) tmp
;
2787 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr
)
2789 double tmp
= *(volatile double *)ptr
;
2790 mono_memory_barrier ();
2795 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr
)
2797 float tmp
= *(volatile float *)ptr
;
2798 mono_memory_barrier ();
2803 ves_icall_System_Threading_Volatile_Read1 (void *ptr
)
2805 return mono_atomic_load_i8 ((volatile gint8
*)ptr
);
2809 ves_icall_System_Threading_Volatile_Read2 (void *ptr
)
2811 return mono_atomic_load_i16 ((volatile gint16
*)ptr
);
2815 ves_icall_System_Threading_Volatile_Read4 (void *ptr
)
2817 return mono_atomic_load_i32 ((volatile gint32
*)ptr
);
2821 ves_icall_System_Threading_Volatile_Read8 (void *ptr
)
2823 #if SIZEOF_VOID_P == 4
2824 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
2826 mono_interlocked_lock ();
2827 val
= *(gint64
*)ptr
;
2828 mono_interlocked_unlock ();
2832 return mono_atomic_load_i64 ((volatile gint64
*)ptr
);
2836 ves_icall_System_Threading_Volatile_ReadIntPtr (void *ptr
)
2838 return mono_atomic_load_ptr ((volatile gpointer
*)ptr
);
2842 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr
)
2846 #if SIZEOF_VOID_P == 4
2847 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
2849 mono_interlocked_lock ();
2850 val
= *(double*)ptr
;
2851 mono_interlocked_unlock ();
2856 u
.ival
= mono_atomic_load_i64 ((volatile gint64
*)ptr
);
2862 ves_icall_System_Threading_Volatile_ReadFloat (void *ptr
)
2866 u
.ival
= mono_atomic_load_i32 ((volatile gint32
*)ptr
);
2872 ves_icall_System_Threading_Volatile_Read_T (void *ptr
)
2874 return (MonoObject
*)mono_atomic_load_ptr ((volatile gpointer
*)ptr
);
2878 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr
, gint8 value
)
2880 mono_memory_barrier ();
2881 *(volatile gint8
*)ptr
= value
;
2885 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr
, gint16 value
)
2887 mono_memory_barrier ();
2888 *(volatile gint16
*)ptr
= value
;
2892 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr
, gint32 value
)
2894 mono_memory_barrier ();
2895 *(volatile gint32
*)ptr
= value
;
2899 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr
, gint64 value
)
2901 mono_memory_barrier ();
2902 *(volatile gint64
*)ptr
= value
;
2906 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr
, void *value
)
2908 mono_memory_barrier ();
2909 *(volatile void **)ptr
= value
;
2913 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr
, MonoObject
*value
)
2915 mono_memory_barrier ();
2916 mono_gc_wbarrier_generic_store (ptr
, value
);
2920 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr
, double value
)
2922 mono_memory_barrier ();
2923 *(volatile double *)ptr
= value
;
2927 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr
, float value
)
2929 mono_memory_barrier ();
2930 *(volatile float *)ptr
= value
;
2934 ves_icall_System_Threading_Volatile_Write1 (void *ptr
, gint8 value
)
2936 mono_atomic_store_i8 ((volatile gint8
*)ptr
, value
);
2940 ves_icall_System_Threading_Volatile_Write2 (void *ptr
, gint16 value
)
2942 mono_atomic_store_i16 ((volatile gint16
*)ptr
, value
);
2946 ves_icall_System_Threading_Volatile_Write4 (void *ptr
, gint32 value
)
2948 mono_atomic_store_i32 ((volatile gint32
*)ptr
, value
);
2952 ves_icall_System_Threading_Volatile_Write8 (void *ptr
, gint64 value
)
2954 #if SIZEOF_VOID_P == 4
2955 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
2956 mono_interlocked_lock ();
2957 *(gint64
*)ptr
= value
;
2958 mono_interlocked_unlock ();
2963 mono_atomic_store_i64 ((volatile gint64
*)ptr
, value
);
2967 ves_icall_System_Threading_Volatile_WriteIntPtr (void *ptr
, void *value
)
2969 mono_atomic_store_ptr ((volatile gpointer
*)ptr
, value
);
2973 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr
, double value
)
2977 #if SIZEOF_VOID_P == 4
2978 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
2979 mono_interlocked_lock ();
2980 *(double*)ptr
= value
;
2981 mono_interlocked_unlock ();
2988 mono_atomic_store_i64 ((volatile gint64
*)ptr
, u
.ival
);
2992 ves_icall_System_Threading_Volatile_WriteFloat (void *ptr
, float value
)
2998 mono_atomic_store_i32 ((volatile gint32
*)ptr
, u
.ival
);
3002 ves_icall_System_Threading_Volatile_Write_T (void *ptr
, MonoObject
*value
)
3004 mono_gc_wbarrier_generic_store_atomic (ptr
, value
);
3008 free_context (void *user_data
)
3010 ContextStaticData
*data
= user_data
;
3012 mono_threads_lock ();
3015 * There is no guarantee that, by the point this reference queue callback
3016 * has been invoked, the GC handle associated with the object will fail to
3017 * resolve as one might expect. So if we don't free and remove the GC
3018 * handle here, free_context_static_data_helper () could end up resolving
3019 * a GC handle to an actually-dead context which would contain a pointer
3020 * to an already-freed static data segment, resulting in a crash when
3023 g_hash_table_remove (contexts
, GUINT_TO_POINTER (data
->gc_handle
));
3025 mono_threads_unlock ();
3027 mono_gchandle_free (data
->gc_handle
);
3028 mono_free_static_data (data
->static_data
);
3033 mono_threads_register_app_context (MonoAppContext
*ctx
, MonoError
*error
)
3036 mono_threads_lock ();
3038 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3041 contexts
= g_hash_table_new (NULL
, NULL
);
3044 context_queue
= mono_gc_reference_queue_new (free_context
);
3046 gpointer gch
= GUINT_TO_POINTER (mono_gchandle_new_weakref (&ctx
->obj
, FALSE
));
3047 g_hash_table_insert (contexts
, gch
, gch
);
3050 * We use this intermediate structure to contain a duplicate pointer to
3051 * the static data because we can't rely on being able to resolve the GC
3052 * handle in the reference queue callback.
3054 ContextStaticData
*data
= g_new0 (ContextStaticData
, 1);
3055 data
->gc_handle
= GPOINTER_TO_UINT (gch
);
3058 context_adjust_static_data (ctx
);
3059 mono_gc_reference_queue_add (context_queue
, &ctx
->obj
, data
);
3061 mono_threads_unlock ();
3063 MONO_PROFILER_RAISE (context_loaded
, (ctx
));
3067 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx
, MonoError
*error
)
3070 mono_threads_register_app_context (MONO_HANDLE_RAW (ctx
), error
); /* FIXME use handles in mono_threads_register_app_context */
3074 mono_threads_release_app_context (MonoAppContext
* ctx
, MonoError
*error
)
3077 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3078 * cleanup in exceptional circumstances, we don't actually do any
3079 * cleanup work here. We instead do this via a reference queue.
3082 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3084 MONO_PROFILER_RAISE (context_unloaded
, (ctx
));
3088 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx
, MonoError
*error
)
3091 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx
), error
); /* FIXME use handles in mono_threads_release_app_context */
3094 void mono_thread_init (MonoThreadStartCB start_cb
,
3095 MonoThreadAttachCB attach_cb
)
3097 mono_coop_mutex_init_recursive (&threads_mutex
);
3099 mono_os_mutex_init_recursive(&interlocked_mutex
);
3100 mono_os_mutex_init_recursive(&joinable_threads_mutex
);
3102 mono_os_event_init (&background_change_event
, FALSE
);
3104 mono_os_cond_init (&zero_pending_joinable_thread_event
);
3106 mono_init_static_data_info (&thread_static_info
);
3107 mono_init_static_data_info (&context_static_info
);
3109 mono_thread_start_cb
= start_cb
;
3110 mono_thread_attach_cb
= attach_cb
;
3114 thread_attach (MonoThreadInfo
*info
)
3116 return mono_gc_thread_attach (info
);
3120 thread_detach (MonoThreadInfo
*info
)
3122 MonoInternalThread
*internal
;
3125 /* If a delegate is passed to native code and invoked on a thread we dont
3126 * know about, marshal will register it with mono_threads_attach_coop, but
3127 * we have no way of knowing when that thread goes away. SGen has a TSD
3128 * so we assume that if the domain is still registered, we can detach
3132 g_assert (mono_thread_info_is_current (info
));
3134 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
3137 internal
= (MonoInternalThread
*) mono_gchandle_get_target (gchandle
);
3138 g_assert (internal
);
3140 mono_thread_detach_internal (internal
);
3144 thread_detach_with_lock (MonoThreadInfo
*info
)
3146 mono_gc_thread_detach_with_lock (info
);
3150 thread_in_critical_region (MonoThreadInfo
*info
)
3152 return mono_gc_thread_in_critical_region (info
);
3156 ip_in_critical_region (MonoDomain
*domain
, gpointer ip
)
3162 * We pass false for 'try_aot' so this becomes async safe.
3163 * It won't find aot methods whose jit info is not yet loaded,
3164 * so we preload their jit info in the JIT.
3166 ji
= mono_jit_info_table_find_internal (domain
, ip
, FALSE
, FALSE
);
3170 method
= mono_jit_info_get_method (ji
);
3173 return mono_gc_is_critical_method (method
);
3177 thread_flags_changing (MonoThreadInfoFlags old
, MonoThreadInfoFlags new_
)
3179 mono_gc_skip_thread_changing (!!(new_
& MONO_THREAD_INFO_FLAGS_NO_GC
));
3183 thread_flags_changed (MonoThreadInfoFlags old
, MonoThreadInfoFlags new_
)
3185 mono_gc_skip_thread_changed (!!(new_
& MONO_THREAD_INFO_FLAGS_NO_GC
));
3189 mono_thread_callbacks_init (void)
3191 MonoThreadInfoCallbacks cb
;
3193 memset (&cb
, 0, sizeof(cb
));
3194 cb
.thread_attach
= thread_attach
;
3195 cb
.thread_detach
= thread_detach
;
3196 cb
.thread_detach_with_lock
= thread_detach_with_lock
;
3197 cb
.ip_in_critical_region
= ip_in_critical_region
;
3198 cb
.thread_in_critical_region
= thread_in_critical_region
;
3199 cb
.thread_flags_changing
= thread_flags_changing
;
3200 cb
.thread_flags_changed
= thread_flags_changed
;
3201 mono_thread_info_callbacks_init (&cb
);
3205 * mono_thread_cleanup:
3208 mono_thread_cleanup (void)
3210 /* Wait for pending threads to park on joinable threads list */
3211 /* NOTE, waiting on this should be extremely rare and will only happen */
3212 /* under certain specific conditions. */
3213 gboolean wait_result
= threads_wait_pending_joinable_threads (2000);
3215 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3217 mono_threads_join_threads ();
3219 #if !defined(RUN_IN_SUBTHREAD) && !defined(HOST_WIN32)
3220 /* The main thread must abandon any held mutexes (particularly
3221 * important for named mutexes as they are shared across
3222 * processes, see bug 74680.) This will happen when the
3223 * thread exits, but if it's not running in a subthread it
3224 * won't exit in time.
3226 mono_w32mutex_abandon (mono_thread_internal_current ());
3230 /* This stuff needs more testing, it seems one of these
3231 * critical sections can be locked when mono_thread_cleanup is
3234 mono_coop_mutex_destroy (&threads_mutex
);
3235 mono_os_mutex_destroy (&interlocked_mutex
);
3236 mono_os_mutex_destroy (&delayed_free_table_mutex
);
3237 mono_os_mutex_destroy (&small_id_mutex
);
3238 mono_os_cond_destroy (&zero_pending_joinable_runtime_thread_event
);
3239 mono_os_event_destroy (&background_change_event
);
3244 mono_threads_install_cleanup (MonoThreadCleanupFunc func
)
3246 mono_thread_cleanup_fn
= func
;
3250 * mono_thread_set_manage_callback:
3253 mono_thread_set_manage_callback (MonoThread
*thread
, MonoThreadManageCallback func
)
3255 thread
->internal_thread
->manage_callback
= func
;
3259 static void print_tids (gpointer key
, gpointer value
, gpointer user
)
3261 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3262 * sizeof(uint) and a cast to uint would overflow
3264 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3265 * print this as a pointer.
3267 g_message ("Waiting for: %p", key
);
3272 MonoThreadHandle
*handles
[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
];
3273 MonoInternalThread
*threads
[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
];
3278 wait_for_tids (struct wait_data
*wait
, guint32 timeout
, gboolean check_state_change
)
3281 MonoThreadInfoWaitRet ret
;
3283 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
3285 /* Add the thread state change event, so it wakes
3286 * up if a thread changes to background mode. */
3289 if (check_state_change
)
3290 ret
= mono_thread_info_wait_multiple_handle (wait
->handles
, wait
->num
, &background_change_event
, FALSE
, timeout
, TRUE
);
3292 ret
= mono_thread_info_wait_multiple_handle (wait
->handles
, wait
->num
, NULL
, TRUE
, timeout
, TRUE
);
3295 if (ret
== MONO_THREAD_INFO_WAIT_RET_FAILED
) {
3296 /* See the comment in build_wait_tids() */
3297 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
3301 for( i
= 0; i
< wait
->num
; i
++)
3302 mono_threads_close_thread_handle (wait
->handles
[i
]);
3304 if (ret
>= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
&& ret
< (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
+ wait
->num
)) {
3305 MonoInternalThread
*internal
;
3307 internal
= wait
->threads
[ret
- MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
];
3309 mono_threads_lock ();
3310 if (mono_g_hash_table_lookup (threads
, (gpointer
) internal
->tid
) == internal
)
3311 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__
, internal
->tid
, internal
);
3312 mono_threads_unlock ();
3316 static void build_wait_tids (gpointer key
, gpointer value
, gpointer user
)
3318 struct wait_data
*wait
=(struct wait_data
*)user
;
3320 if(wait
->num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
- 1) {
3321 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
3323 /* Ignore background threads, we abort them later */
3324 /* Do not lock here since it is not needed and the caller holds threads_lock */
3325 if (thread
->state
& ThreadState_Background
) {
3326 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3327 return; /* just leave, ignore */
3330 if (mono_gc_is_finalizer_internal_thread (thread
)) {
3331 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3335 if (thread
== mono_thread_internal_current ()) {
3336 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3340 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
)) {
3341 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3345 if (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
) {
3346 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT
"with DONT_MANAGE flag set.", __func__
, (gsize
)thread
->tid
));
3350 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__
, thread
));
3351 if ((thread
->manage_callback
== NULL
) || (thread
->manage_callback (thread
->root_domain_thread
) == TRUE
)) {
3352 wait
->handles
[wait
->num
]=mono_threads_open_thread_handle (thread
->handle
);
3353 wait
->threads
[wait
->num
]=thread
;
3356 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3358 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3363 /* Just ignore the rest, we can't do anything with
3370 abort_threads (gpointer key
, gpointer value
, gpointer user
)
3372 struct wait_data
*wait
=(struct wait_data
*)user
;
3373 MonoNativeThreadId self
= mono_native_thread_id_get ();
3374 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3376 if (wait
->num
>= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
)
3379 if (mono_native_thread_id_equals (thread_get_tid (thread
), self
))
3381 if (mono_gc_is_finalizer_internal_thread (thread
))
3384 if ((thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
))
3387 wait
->handles
[wait
->num
] = mono_threads_open_thread_handle (thread
->handle
);
3388 wait
->threads
[wait
->num
] = thread
;
3391 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT
"\n", __func__
, (gsize
)thread
->tid
));
3392 mono_thread_internal_abort (thread
, FALSE
);
3396 * mono_threads_set_shutting_down:
3398 * Is called by a thread that wants to shut down Mono. If the runtime is already
3399 * shutting down, the calling thread is suspended/stopped, and this function never
3403 mono_threads_set_shutting_down (void)
3405 MonoInternalThread
*current_thread
= mono_thread_internal_current ();
3407 mono_threads_lock ();
3409 if (shutting_down
) {
3410 mono_threads_unlock ();
3412 /* Make sure we're properly suspended/stopped */
3414 LOCK_THREAD (current_thread
);
3416 if (current_thread
->state
& (ThreadState_SuspendRequested
| ThreadState_AbortRequested
)) {
3417 UNLOCK_THREAD (current_thread
);
3418 mono_thread_execute_interruption_void ();
3420 UNLOCK_THREAD (current_thread
);
3423 /*since we're killing the thread, detach it.*/
3424 mono_thread_detach_internal (current_thread
);
3426 /* Wake up other threads potentially waiting for us */
3427 mono_thread_info_exit (0);
3429 shutting_down
= TRUE
;
3431 /* Not really a background state change, but this will
3432 * interrupt the main thread if it is waiting for all
3433 * the other threads.
3436 mono_os_event_set (&background_change_event
);
3439 mono_threads_unlock ();
3444 * mono_thread_manage:
3447 mono_thread_manage (void)
3449 struct wait_data wait_data
;
3450 struct wait_data
*wait
= &wait_data
;
3452 memset (wait
, 0, sizeof (struct wait_data
));
3453 /* join each thread that's still running */
3454 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__
));
3456 mono_threads_lock ();
3458 THREAD_DEBUG (g_message("%s: No threads", __func__
));
3459 mono_threads_unlock ();
3463 mono_threads_unlock ();
3466 mono_threads_lock ();
3467 if (shutting_down
) {
3468 /* somebody else is shutting down */
3469 mono_threads_unlock ();
3472 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__
, mono_g_hash_table_size (threads
));
3473 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
3476 mono_os_event_reset (&background_change_event
);
3479 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3480 memset (wait
->threads
, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
* SIZEOF_VOID_P
);
3481 mono_g_hash_table_foreach (threads
, build_wait_tids
, wait
);
3482 mono_threads_unlock ();
3484 /* Something to wait for */
3485 wait_for_tids (wait
, MONO_INFINITE_WAIT
, TRUE
);
3486 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__
, wait
->num
));
3487 } while(wait
->num
>0);
3489 /* Mono is shutting down, so just wait for the end */
3490 if (!mono_runtime_try_shutdown ()) {
3491 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3492 mono_thread_suspend (mono_thread_internal_current ());
3493 mono_thread_execute_interruption_void ();
3497 * Remove everything but the finalizer thread and self.
3498 * Also abort all the background threads
3501 mono_threads_lock ();
3504 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3505 memset (wait
->threads
, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
* SIZEOF_VOID_P
);
3506 mono_g_hash_table_foreach (threads
, abort_threads
, wait
);
3508 mono_threads_unlock ();
3510 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__
, wait
->num
));
3511 if (wait
->num
> 0) {
3512 /* Something to wait for */
3513 wait_for_tids (wait
, MONO_INFINITE_WAIT
, FALSE
);
3515 } while (wait
->num
> 0);
3518 * give the subthreads a chance to really quit (this is mainly needed
3519 * to get correct user and system times from getrusage/wait/time(1)).
3520 * This could be removed if we avoid pthread_detach() and use pthread_join().
3522 mono_thread_info_yield ();
3526 collect_threads_for_suspend (gpointer key
, gpointer value
, gpointer user_data
)
3528 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3529 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3532 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3534 * This needs no locking.
3536 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3537 (thread
->state
& ThreadState_Stopped
) != 0)
3540 if (wait
->num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
) {
3541 wait
->handles
[wait
->num
] = mono_threads_open_thread_handle (thread
->handle
);
3542 wait
->threads
[wait
->num
] = thread
;
3548 * mono_thread_suspend_all_other_threads:
3550 * Suspend all managed threads except the finalizer thread and this thread. It is
3551 * not possible to resume them later.
3553 void mono_thread_suspend_all_other_threads (void)
3555 struct wait_data wait_data
;
3556 struct wait_data
*wait
= &wait_data
;
3558 MonoNativeThreadId self
= mono_native_thread_id_get ();
3559 guint32 eventidx
= 0;
3560 gboolean starting
, finished
;
3562 memset (wait
, 0, sizeof (struct wait_data
));
3564 * The other threads could be in an arbitrary state at this point, i.e.
3565 * they could be starting up, shutting down etc. This means that there could be
3566 * threads which are not even in the threads hash table yet.
3570 * First we set a barrier which will be checked by all threads before they
3571 * are added to the threads hash table, and they will exit if the flag is set.
3572 * This ensures that no threads could be added to the hash later.
3573 * We will use shutting_down as the barrier for now.
3575 g_assert (shutting_down
);
3578 * We make multiple calls to WaitForMultipleObjects since:
3579 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3580 * - some threads could exit without becoming suspended
3585 * Make a copy of the hashtable since we can't do anything with
3586 * threads while threads_mutex is held.
3589 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3590 memset (wait
->threads
, 0, MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
* SIZEOF_VOID_P
);
3591 mono_threads_lock ();
3592 mono_g_hash_table_foreach (threads
, collect_threads_for_suspend
, wait
);
3593 mono_threads_unlock ();
3596 /* Get the suspended events that we'll be waiting for */
3597 for (i
= 0; i
< wait
->num
; ++i
) {
3598 MonoInternalThread
*thread
= wait
->threads
[i
];
3600 if (mono_native_thread_id_equals (thread_get_tid (thread
), self
)
3601 || mono_gc_is_finalizer_internal_thread (thread
)
3602 || (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)
3604 mono_threads_close_thread_handle (wait
->handles
[i
]);
3605 wait
->threads
[i
] = NULL
;
3609 LOCK_THREAD (thread
);
3611 if (thread
->state
& (ThreadState_Suspended
| ThreadState_Stopped
)) {
3612 UNLOCK_THREAD (thread
);
3613 mono_threads_close_thread_handle (wait
->handles
[i
]);
3614 wait
->threads
[i
] = NULL
;
3620 /* Convert abort requests into suspend requests */
3621 if ((thread
->state
& ThreadState_AbortRequested
) != 0)
3622 thread
->state
&= ~ThreadState_AbortRequested
;
3624 thread
->state
|= ThreadState_SuspendRequested
;
3626 mono_os_event_reset (thread
->suspended
);
3629 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3630 async_suspend_internal (thread
, TRUE
);
3632 mono_threads_close_thread_handle (wait
->handles
[i
]);
3633 wait
->threads
[i
] = NULL
;
3635 if (eventidx
<= 0) {
3637 * If there are threads which are starting up, we wait until they
3638 * are suspended when they try to register in the threads hash.
3639 * This is guaranteed to finish, since the threads which can create new
3640 * threads get suspended after a while.
3641 * FIXME: The finalizer thread can still create new threads.
3643 mono_threads_lock ();
3644 if (threads_starting_up
)
3645 starting
= mono_g_hash_table_size (threads_starting_up
) > 0;
3648 mono_threads_unlock ();
3650 mono_thread_info_sleep (100, NULL
);
3658 MonoInternalThread
*thread
;
3659 MonoStackFrameInfo
*frames
;
3660 int nframes
, max_frames
;
3661 int nthreads
, max_threads
;
3662 MonoInternalThread
**threads
;
3663 } ThreadDumpUserData
;
3665 static gboolean thread_dump_requested
;
3667 /* This needs to be async safe */
3669 collect_frame (MonoStackFrameInfo
*frame
, MonoContext
*ctx
, gpointer data
)
3671 ThreadDumpUserData
*ud
= (ThreadDumpUserData
*)data
;
3673 if (ud
->nframes
< ud
->max_frames
) {
3674 memcpy (&ud
->frames
[ud
->nframes
], frame
, sizeof (MonoStackFrameInfo
));
3681 /* This needs to be async safe */
3682 static SuspendThreadResult
3683 get_thread_dump (MonoThreadInfo
*info
, gpointer ud
)
3685 ThreadDumpUserData
*user_data
= (ThreadDumpUserData
*)ud
;
3686 MonoInternalThread
*thread
= user_data
->thread
;
3689 /* This no longer works with remote unwinding */
3690 g_string_append_printf (text
, " tid=0x%p this=0x%p ", (gpointer
)(gsize
)thread
->tid
, thread
);
3691 mono_thread_internal_describe (thread
, text
);
3692 g_string_append (text
, "\n");
3695 if (thread
== mono_thread_internal_current ())
3696 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame
, NULL
, MONO_UNWIND_SIGNAL_SAFE
, ud
);
3698 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame
, mono_thread_info_get_suspend_state (info
), MONO_UNWIND_SIGNAL_SAFE
, ud
);
3700 return MonoResumeThread
;
3704 int nthreads
, max_threads
;
3705 MonoInternalThread
**threads
;
3706 } CollectThreadsUserData
;
3709 collect_thread (gpointer key
, gpointer value
, gpointer user
)
3711 CollectThreadsUserData
*ud
= (CollectThreadsUserData
*)user
;
3712 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3714 if (ud
->nthreads
< ud
->max_threads
)
3715 ud
->threads
[ud
->nthreads
++] = thread
;
3719 * Collect running threads into the THREADS array.
3720 * THREADS should be an array allocated on the stack.
3723 collect_threads (MonoInternalThread
**thread_array
, int max_threads
)
3725 CollectThreadsUserData ud
;
3727 memset (&ud
, 0, sizeof (ud
));
3728 /* This array contains refs, but its on the stack, so its ok */
3729 ud
.threads
= thread_array
;
3730 ud
.max_threads
= max_threads
;
3732 mono_threads_lock ();
3733 mono_g_hash_table_foreach (threads
, collect_thread
, &ud
);
3734 mono_threads_unlock ();
3740 dump_thread (MonoInternalThread
*thread
, ThreadDumpUserData
*ud
)
3742 GString
* text
= g_string_new (0);
3744 GError
*gerror
= NULL
;
3747 ud
->thread
= thread
;
3750 /* Collect frames for the thread */
3751 if (thread
== mono_thread_internal_current ()) {
3752 get_thread_dump (mono_thread_info_current (), ud
);
3754 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, get_thread_dump
, ud
);
3758 * Do all the non async-safe work outside of get_thread_dump.
3761 name
= g_utf16_to_utf8 (thread
->name
, thread
->name_len
, NULL
, NULL
, &gerror
);
3763 g_string_append_printf (text
, "\n\"%s\"", name
);
3766 else if (thread
->threadpool_thread
) {
3767 g_string_append (text
, "\n\"<threadpool thread>\"");
3769 g_string_append (text
, "\n\"<unnamed thread>\"");
3772 for (i
= 0; i
< ud
->nframes
; ++i
) {
3773 MonoStackFrameInfo
*frame
= &ud
->frames
[i
];
3774 MonoMethod
*method
= NULL
;
3776 if (frame
->type
== FRAME_TYPE_MANAGED
)
3777 method
= mono_jit_info_get_method (frame
->ji
);
3780 gchar
*location
= mono_debug_print_stack_frame (method
, frame
->native_offset
, frame
->domain
);
3781 g_string_append_printf (text
, " %s\n", location
);
3784 g_string_append_printf (text
, " at <unknown> <0x%05x>\n", frame
->native_offset
);
3788 fprintf (stdout
, "%s", text
->str
);
3790 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
3791 OutputDebugStringA(text
->str
);
3794 g_string_free (text
, TRUE
);
3799 mono_threads_perform_thread_dump (void)
3801 ThreadDumpUserData ud
;
3802 MonoInternalThread
*thread_array
[128];
3803 int tindex
, nthreads
;
3805 if (!thread_dump_requested
)
3808 printf ("Full thread dump:\n");
3810 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
3811 nthreads
= collect_threads (thread_array
, 128);
3813 memset (&ud
, 0, sizeof (ud
));
3814 ud
.frames
= g_new0 (MonoStackFrameInfo
, 256);
3815 ud
.max_frames
= 256;
3817 for (tindex
= 0; tindex
< nthreads
; ++tindex
)
3818 dump_thread (thread_array
[tindex
], &ud
);
3822 thread_dump_requested
= FALSE
;
3825 /* Obtain the thread dump of all threads */
3827 mono_threads_get_thread_dump (MonoArray
**out_threads
, MonoArray
**out_stack_frames
, MonoError
*error
)
3830 ThreadDumpUserData ud
;
3831 MonoInternalThread
*thread_array
[128];
3832 MonoDomain
*domain
= mono_domain_get ();
3833 MonoDebugSourceLocation
*location
;
3834 int tindex
, nthreads
;
3838 *out_threads
= NULL
;
3839 *out_stack_frames
= NULL
;
3841 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
3842 nthreads
= collect_threads (thread_array
, 128);
3844 memset (&ud
, 0, sizeof (ud
));
3845 ud
.frames
= g_new0 (MonoStackFrameInfo
, 256);
3846 ud
.max_frames
= 256;
3848 *out_threads
= mono_array_new_checked (domain
, mono_defaults
.thread_class
, nthreads
, error
);
3849 goto_if_nok (error
, leave
);
3850 *out_stack_frames
= mono_array_new_checked (domain
, mono_defaults
.array_class
, nthreads
, error
);
3851 goto_if_nok (error
, leave
);
3853 for (tindex
= 0; tindex
< nthreads
; ++tindex
) {
3854 MonoInternalThread
*thread
= thread_array
[tindex
];
3855 MonoArray
*thread_frames
;
3861 /* Collect frames for the thread */
3862 if (thread
== mono_thread_internal_current ()) {
3863 get_thread_dump (mono_thread_info_current (), &ud
);
3865 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, get_thread_dump
, &ud
);
3868 mono_array_setref_fast (*out_threads
, tindex
, mono_thread_current_for_thread (thread
));
3870 thread_frames
= mono_array_new_checked (domain
, mono_defaults
.stack_frame_class
, ud
.nframes
, error
);
3871 goto_if_nok (error
, leave
);
3872 mono_array_setref_fast (*out_stack_frames
, tindex
, thread_frames
);
3874 for (i
= 0; i
< ud
.nframes
; ++i
) {
3875 MonoStackFrameInfo
*frame
= &ud
.frames
[i
];
3876 MonoMethod
*method
= NULL
;
3877 MonoStackFrame
*sf
= (MonoStackFrame
*)mono_object_new_checked (domain
, mono_defaults
.stack_frame_class
, error
);
3878 goto_if_nok (error
, leave
);
3880 sf
->native_offset
= frame
->native_offset
;
3882 if (frame
->type
== FRAME_TYPE_MANAGED
)
3883 method
= mono_jit_info_get_method (frame
->ji
);
3886 sf
->method_address
= (gsize
) frame
->ji
->code_start
;
3888 MonoReflectionMethod
*rm
= mono_method_get_object_checked (domain
, method
, NULL
, error
);
3889 goto_if_nok (error
, leave
);
3890 MONO_OBJECT_SETREF (sf
, method
, rm
);
3892 location
= mono_debug_lookup_source_location (method
, frame
->native_offset
, domain
);
3894 sf
->il_offset
= location
->il_offset
;
3896 if (location
&& location
->source_file
) {
3897 MonoString
*filename
= mono_string_new_checked (domain
, location
->source_file
, error
);
3898 goto_if_nok (error
, leave
);
3899 MONO_OBJECT_SETREF (sf
, filename
, filename
);
3900 sf
->line
= location
->row
;
3901 sf
->column
= location
->column
;
3903 mono_debug_free_source_location (location
);
3908 mono_array_setref (thread_frames
, i
, sf
);
3914 return is_ok (error
);
3918 * mono_threads_request_thread_dump:
3920 * Ask all threads except the current to print their stacktrace to stdout.
3923 mono_threads_request_thread_dump (void)
3925 /*The new thread dump code runs out of the finalizer thread. */
3926 thread_dump_requested
= TRUE
;
3927 mono_gc_finalize_notify ();
3932 gint allocated
; /* +1 so that refs [allocated] == NULL */
3936 typedef struct ref_stack RefStack
;
3939 ref_stack_new (gint initial_size
)
3943 initial_size
= MAX (initial_size
, 16) + 1;
3944 rs
= g_new0 (RefStack
, 1);
3945 rs
->refs
= g_new0 (gpointer
, initial_size
);
3946 rs
->allocated
= initial_size
;
3951 ref_stack_destroy (gpointer ptr
)
3953 RefStack
*rs
= (RefStack
*)ptr
;
3962 ref_stack_push (RefStack
*rs
, gpointer ptr
)
3964 g_assert (rs
!= NULL
);
3966 if (rs
->bottom
>= rs
->allocated
) {
3967 rs
->refs
= (void **)g_realloc (rs
->refs
, rs
->allocated
* 2 * sizeof (gpointer
) + 1);
3968 rs
->allocated
<<= 1;
3969 rs
->refs
[rs
->allocated
] = NULL
;
3971 rs
->refs
[rs
->bottom
++] = ptr
;
3975 ref_stack_pop (RefStack
*rs
)
3977 if (rs
== NULL
|| rs
->bottom
== 0)
3981 rs
->refs
[rs
->bottom
] = NULL
;
3985 ref_stack_find (RefStack
*rs
, gpointer ptr
)
3992 for (refs
= rs
->refs
; refs
&& *refs
; refs
++) {
4000 * mono_thread_push_appdomain_ref:
4002 * Register that the current thread may have references to objects in domain
4003 * @domain on its stack. Each call to this function should be paired with a
4004 * call to pop_appdomain_ref.
4007 mono_thread_push_appdomain_ref (MonoDomain
*domain
)
4009 MonoInternalThread
*thread
= mono_thread_internal_current ();
4012 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4013 SPIN_LOCK (thread
->lock_thread_id
);
4014 if (thread
->appdomain_refs
== NULL
)
4015 thread
->appdomain_refs
= ref_stack_new (16);
4016 ref_stack_push ((RefStack
*)thread
->appdomain_refs
, domain
);
4017 SPIN_UNLOCK (thread
->lock_thread_id
);
4022 mono_thread_pop_appdomain_ref (void)
4024 MonoInternalThread
*thread
= mono_thread_internal_current ();
4027 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4028 SPIN_LOCK (thread
->lock_thread_id
);
4029 ref_stack_pop ((RefStack
*)thread
->appdomain_refs
);
4030 SPIN_UNLOCK (thread
->lock_thread_id
);
4035 mono_thread_internal_has_appdomain_ref (MonoInternalThread
*thread
, MonoDomain
*domain
)
4038 SPIN_LOCK (thread
->lock_thread_id
);
4039 res
= ref_stack_find ((RefStack
*)thread
->appdomain_refs
, domain
);
4040 SPIN_UNLOCK (thread
->lock_thread_id
);
4045 mono_thread_has_appdomain_ref (MonoThread
*thread
, MonoDomain
*domain
)
4047 return mono_thread_internal_has_appdomain_ref (thread
->internal_thread
, domain
);
4050 typedef struct abort_appdomain_data
{
4051 struct wait_data wait
;
4053 } abort_appdomain_data
;
4056 collect_appdomain_thread (gpointer key
, gpointer value
, gpointer user_data
)
4058 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4059 abort_appdomain_data
*data
= (abort_appdomain_data
*)user_data
;
4060 MonoDomain
*domain
= data
->domain
;
4062 if (mono_thread_internal_has_appdomain_ref (thread
, domain
)) {
4063 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4065 if(data
->wait
.num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
) {
4066 data
->wait
.handles
[data
->wait
.num
] = mono_threads_open_thread_handle (thread
->handle
);
4067 data
->wait
.threads
[data
->wait
.num
] = thread
;
4070 /* Just ignore the rest, we can't do anything with
4078 * mono_threads_abort_appdomain_threads:
4080 * Abort threads which has references to the given appdomain.
4083 mono_threads_abort_appdomain_threads (MonoDomain
*domain
, int timeout
)
4085 abort_appdomain_data user_data
;
4087 int orig_timeout
= timeout
;
4090 THREAD_DEBUG (g_message ("%s: starting abort", __func__
));
4092 start_time
= mono_msec_ticks ();
4094 mono_threads_lock ();
4096 user_data
.domain
= domain
;
4097 user_data
.wait
.num
= 0;
4098 /* This shouldn't take any locks */
4099 mono_g_hash_table_foreach (threads
, collect_appdomain_thread
, &user_data
);
4100 mono_threads_unlock ();
4102 if (user_data
.wait
.num
> 0) {
4103 /* Abort the threads outside the threads lock */
4104 for (i
= 0; i
< user_data
.wait
.num
; ++i
)
4105 mono_thread_internal_abort (user_data
.wait
.threads
[i
], TRUE
);
4108 * We should wait for the threads either to abort, or to leave the
4109 * domain. We can't do the latter, so we wait with a timeout.
4111 wait_for_tids (&user_data
.wait
, 100, FALSE
);
4114 /* Update remaining time */
4115 timeout
-= mono_msec_ticks () - start_time
;
4116 start_time
= mono_msec_ticks ();
4118 if (orig_timeout
!= -1 && timeout
< 0)
4121 while (user_data
.wait
.num
> 0);
4123 THREAD_DEBUG (g_message ("%s: abort done", __func__
));
4128 /* This is a JIT icall. This icall is called from a finally block when
4129 * mono_install_handler_block_guard called by another thread has flipped the
4130 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4131 * the finally is in an abort protected block, we must defer the abort
4132 * exception until we leave the abort protected block. Otherwise we proceed
4133 * with a synchronous self-abort.
4136 ves_icall_thread_finish_async_abort (void)
4138 /* We were called from the handler block and are about to
4139 * leave it. (If we end up postponing the abort because we're
4140 * in an abort protected block, the unwinder won't run and
4141 * won't clear the handler block itself which will confuse the
4142 * unwinder if we're in a try {} catch {} and we throw again.
4144 * static Constructor () {
4148 * icall (); // Thread.Abort landed here,
4149 * // and caused the handler block to be installed
4151 * ves_icall_thread_finish_async_abort (); // we're here
4155 * // unwinder will get confused here and synthesize a self abort
4159 * More interestingly, this doesn't only happen with icalls - a JIT
4160 * trampoline is native code that will cause a handler to be installed.
4161 * So the above situation can happen with any code in a "finally"
4164 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4165 /* Just set the async interruption requested bit. Rely on the icall
4166 * wrapper of this icall to process the thread interruption, respecting
4167 * any abort protection blocks in our call stack.
4169 mono_thread_set_self_interruption_respect_abort_prot ();
4173 * mono_thread_get_undeniable_exception:
4175 * Return an exception which needs to be raised when leaving a catch clause.
4176 * This is used for undeniable exception propagation.
4179 mono_thread_get_undeniable_exception (void)
4181 MonoInternalThread
*thread
= mono_thread_internal_current ();
4183 if (!(thread
&& thread
->abort_exc
&& !is_running_protected_wrapper ()))
4186 // We don't want to have our exception effect calls made by
4187 // the catching block
4189 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4193 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4194 * exception if the thread no longer references a dying appdomain.
4196 thread
->abort_exc
->trace_ips
= NULL
;
4197 thread
->abort_exc
->stack_trace
= NULL
;
4198 return thread
->abort_exc
;
4201 #if MONO_SMALL_CONFIG
4202 #define NUM_STATIC_DATA_IDX 4
4203 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
4207 #define NUM_STATIC_DATA_IDX 8
4208 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
4209 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4213 static MonoBitSet
*thread_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
4214 static MonoBitSet
*context_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
4217 mark_slots (void *addr
, MonoBitSet
**bitmaps
, MonoGCMarkFunc mark_func
, void *gc_data
)
4219 gpointer
*static_data
= (gpointer
*)addr
;
4221 for (int i
= 0; i
< NUM_STATIC_DATA_IDX
; ++i
) {
4222 void **ptr
= (void **)static_data
[i
];
4227 MONO_BITSET_FOREACH (bitmaps
[i
], idx
, {
4228 void **p
= ptr
+ idx
;
4231 mark_func ((MonoObject
**)p
, gc_data
);
4237 mark_tls_slots (void *addr
, MonoGCMarkFunc mark_func
, void *gc_data
)
4239 mark_slots (addr
, thread_reference_bitmaps
, mark_func
, gc_data
);
4243 mark_ctx_slots (void *addr
, MonoGCMarkFunc mark_func
, void *gc_data
)
4245 mark_slots (addr
, context_reference_bitmaps
, mark_func
, gc_data
);
4249 * mono_alloc_static_data
4251 * Allocate memory blocks for storing threads or context static data
4254 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, void *alloc_key
, gboolean threadlocal
)
4256 guint idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4259 gpointer
* static_data
= *static_data_ptr
;
4261 static MonoGCDescriptor tls_desc
= MONO_GC_DESCRIPTOR_NULL
;
4262 static MonoGCDescriptor ctx_desc
= MONO_GC_DESCRIPTOR_NULL
;
4264 if (mono_gc_user_markers_supported ()) {
4265 if (tls_desc
== MONO_GC_DESCRIPTOR_NULL
)
4266 tls_desc
= mono_gc_make_root_descr_user (mark_tls_slots
);
4268 if (ctx_desc
== MONO_GC_DESCRIPTOR_NULL
)
4269 ctx_desc
= mono_gc_make_root_descr_user (mark_ctx_slots
);
4272 static_data
= (void **)mono_gc_alloc_fixed (static_data_size
[0], threadlocal
? tls_desc
: ctx_desc
,
4273 threadlocal
? MONO_ROOT_SOURCE_THREAD_STATIC
: MONO_ROOT_SOURCE_CONTEXT_STATIC
,
4275 threadlocal
? "ThreadStatic Fields" : "ContextStatic Fields");
4276 *static_data_ptr
= static_data
;
4277 static_data
[0] = static_data
;
4280 for (i
= 1; i
<= idx
; ++i
) {
4281 if (static_data
[i
])
4284 if (mono_gc_user_markers_supported ())
4285 static_data
[i
] = g_malloc0 (static_data_size
[i
]);
4287 static_data
[i
] = mono_gc_alloc_fixed (static_data_size
[i
], MONO_GC_DESCRIPTOR_NULL
,
4288 threadlocal
? MONO_ROOT_SOURCE_THREAD_STATIC
: MONO_ROOT_SOURCE_CONTEXT_STATIC
,
4290 threadlocal
? "ThreadStatic Fields" : "ContextStatic Fields");
4295 mono_free_static_data (gpointer
* static_data
)
4298 for (i
= 1; i
< NUM_STATIC_DATA_IDX
; ++i
) {
4299 gpointer p
= static_data
[i
];
4303 * At this point, the static data pointer array is still registered with the
4304 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4305 * data. Freeing the individual arrays without first nulling their slots
4306 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4307 * such an already freed array. See bug #13813.
4309 static_data
[i
] = NULL
;
4310 mono_memory_write_barrier ();
4311 if (mono_gc_user_markers_supported ())
4314 mono_gc_free_fixed (p
);
4316 mono_gc_free_fixed (static_data
);
4320 * mono_init_static_data_info
4322 * Initializes static data counters
4324 static void mono_init_static_data_info (StaticDataInfo
*static_data
)
4326 static_data
->idx
= 0;
4327 static_data
->offset
= 0;
4328 static_data
->freelist
= NULL
;
4332 * mono_alloc_static_data_slot
4334 * Generates an offset for static data. static_data contains the counters
4335 * used to generate it.
4338 mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
4340 if (!static_data
->idx
&& !static_data
->offset
) {
4342 * we use the first chunk of the first allocation also as
4343 * an array for the rest of the data
4345 static_data
->offset
= sizeof (gpointer
) * NUM_STATIC_DATA_IDX
;
4347 static_data
->offset
+= align
- 1;
4348 static_data
->offset
&= ~(align
- 1);
4349 if (static_data
->offset
+ size
>= static_data_size
[static_data
->idx
]) {
4350 static_data
->idx
++;
4351 g_assert (size
<= static_data_size
[static_data
->idx
]);
4352 g_assert (static_data
->idx
< NUM_STATIC_DATA_IDX
);
4353 static_data
->offset
= 0;
4355 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (static_data
->idx
, static_data
->offset
, 0);
4356 static_data
->offset
+= size
;
4361 * LOCKING: requires that threads_mutex is held
4364 context_adjust_static_data (MonoAppContext
*ctx
)
4366 if (context_static_info
.offset
|| context_static_info
.idx
> 0) {
4367 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (context_static_info
.idx
, context_static_info
.offset
, 0);
4368 mono_alloc_static_data (&ctx
->static_data
, offset
, ctx
, FALSE
);
4369 ctx
->data
->static_data
= ctx
->static_data
;
4374 * LOCKING: requires that threads_mutex is held
4377 alloc_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4379 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4380 guint32 offset
= GPOINTER_TO_UINT (user
);
4382 mono_alloc_static_data (&(thread
->static_data
), offset
, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread
->tid
), TRUE
);
4386 * LOCKING: requires that threads_mutex is held
4389 alloc_context_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4391 MonoAppContext
*ctx
= (MonoAppContext
*) mono_gchandle_get_target (GPOINTER_TO_INT (key
));
4396 guint32 offset
= GPOINTER_TO_UINT (user
);
4397 mono_alloc_static_data (&ctx
->static_data
, offset
, ctx
, FALSE
);
4398 ctx
->data
->static_data
= ctx
->static_data
;
4401 static StaticDataFreeList
*
4402 search_slot_in_freelist (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
4404 StaticDataFreeList
* prev
= NULL
;
4405 StaticDataFreeList
* tmp
= static_data
->freelist
;
4407 if (tmp
->size
== size
) {
4409 prev
->next
= tmp
->next
;
4411 static_data
->freelist
= tmp
->next
;
4420 #if SIZEOF_VOID_P == 4
4427 update_reference_bitmap (MonoBitSet
**sets
, guint32 offset
, uintptr_t *bitmap
, int numbits
)
4429 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4431 sets
[idx
] = mono_bitset_new (static_data_size
[idx
] / sizeof (uintptr_t), 0);
4432 MonoBitSet
*rb
= sets
[idx
];
4433 offset
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
4434 offset
/= sizeof (uintptr_t);
4435 /* offset is now the bitmap offset */
4436 for (int i
= 0; i
< numbits
; ++i
) {
4437 if (bitmap
[i
/ sizeof (uintptr_t)] & (ONE_P
<< (i
& (sizeof (uintptr_t) * 8 -1))))
4438 mono_bitset_set_fast (rb
, offset
+ i
);
4443 clear_reference_bitmap (MonoBitSet
**sets
, guint32 offset
, guint32 size
)
4445 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4446 MonoBitSet
*rb
= sets
[idx
];
4447 offset
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
4448 offset
/= sizeof (uintptr_t);
4449 /* offset is now the bitmap offset */
4450 for (int i
= 0; i
< size
/ sizeof (uintptr_t); i
++)
4451 mono_bitset_clear_fast (rb
, offset
+ i
);
4455 mono_alloc_special_static_data (guint32 static_type
, guint32 size
, guint32 align
, uintptr_t *bitmap
, int numbits
)
4457 g_assert (static_type
== SPECIAL_STATIC_THREAD
|| static_type
== SPECIAL_STATIC_CONTEXT
);
4459 StaticDataInfo
*info
;
4462 if (static_type
== SPECIAL_STATIC_THREAD
) {
4463 info
= &thread_static_info
;
4464 sets
= thread_reference_bitmaps
;
4466 info
= &context_static_info
;
4467 sets
= context_reference_bitmaps
;
4470 mono_threads_lock ();
4472 StaticDataFreeList
*item
= search_slot_in_freelist (info
, size
, align
);
4476 offset
= item
->offset
;
4479 offset
= mono_alloc_static_data_slot (info
, size
, align
);
4482 update_reference_bitmap (sets
, offset
, bitmap
, numbits
);
4484 if (static_type
== SPECIAL_STATIC_THREAD
) {
4485 /* This can be called during startup */
4486 if (threads
!= NULL
)
4487 mono_g_hash_table_foreach (threads
, alloc_thread_static_data_helper
, GUINT_TO_POINTER (offset
));
4489 if (contexts
!= NULL
)
4490 g_hash_table_foreach (contexts
, alloc_context_static_data_helper
, GUINT_TO_POINTER (offset
));
4492 ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT
;
4495 mono_threads_unlock ();
4501 mono_get_special_static_data_for_thread (MonoInternalThread
*thread
, guint32 offset
)
4503 guint32 static_type
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
);
4505 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4506 return get_thread_static_data (thread
, offset
);
4508 return get_context_static_data (thread
->current_appcontext
, offset
);
4513 mono_get_special_static_data (guint32 offset
)
4515 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset
);
4524 * LOCKING: requires that threads_mutex is held
4527 free_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4529 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4530 OffsetSize
*data
= (OffsetSize
*)user
;
4531 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, index
);
4532 int off
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, offset
);
4535 if (!thread
->static_data
|| !thread
->static_data
[idx
])
4537 ptr
= ((char*) thread
->static_data
[idx
]) + off
;
4538 mono_gc_bzero_atomic (ptr
, data
->size
);
4542 * LOCKING: requires that threads_mutex is held
4545 free_context_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4547 MonoAppContext
*ctx
= (MonoAppContext
*) mono_gchandle_get_target (GPOINTER_TO_INT (key
));
4552 OffsetSize
*data
= (OffsetSize
*)user
;
4553 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, index
);
4554 int off
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, offset
);
4557 if (!ctx
->static_data
|| !ctx
->static_data
[idx
])
4560 ptr
= ((char*) ctx
->static_data
[idx
]) + off
;
4561 mono_gc_bzero_atomic (ptr
, data
->size
);
4565 do_free_special_slot (guint32 offset
, guint32 size
)
4567 guint32 static_type
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
);
4569 StaticDataInfo
*info
;
4571 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4572 info
= &thread_static_info
;
4573 sets
= thread_reference_bitmaps
;
4575 info
= &context_static_info
;
4576 sets
= context_reference_bitmaps
;
4579 guint32 data_offset
= offset
;
4580 ACCESS_SPECIAL_STATIC_OFFSET (data_offset
, type
) = 0;
4581 OffsetSize data
= { data_offset
, size
};
4583 clear_reference_bitmap (sets
, data
.offset
, data
.size
);
4585 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4586 if (threads
!= NULL
)
4587 mono_g_hash_table_foreach (threads
, free_thread_static_data_helper
, &data
);
4589 if (contexts
!= NULL
)
4590 g_hash_table_foreach (contexts
, free_context_static_data_helper
, &data
);
4593 if (!mono_runtime_is_shutting_down ()) {
4594 StaticDataFreeList
*item
= g_new0 (StaticDataFreeList
, 1);
4596 item
->offset
= offset
;
4599 item
->next
= info
->freelist
;
4600 info
->freelist
= item
;
4605 do_free_special (gpointer key
, gpointer value
, gpointer data
)
4607 MonoClassField
*field
= (MonoClassField
*)key
;
4608 guint32 offset
= GPOINTER_TO_UINT (value
);
4611 size
= mono_type_size (field
->type
, &align
);
4612 do_free_special_slot (offset
, size
);
4616 mono_alloc_special_static_data_free (GHashTable
*special_static_fields
)
4618 mono_threads_lock ();
4620 g_hash_table_foreach (special_static_fields
, do_free_special
, NULL
);
4622 mono_threads_unlock ();
4626 static void CALLBACK
dummy_apc (ULONG_PTR param
)
4632 * mono_thread_execute_interruption
4634 * Performs the operation that the requested thread state requires (abort,
4637 static MonoException
*
4638 mono_thread_execute_interruption (void)
4640 MONO_REQ_GC_UNSAFE_MODE
;
4642 MonoException
*exc
= NULL
;
4643 MonoInternalThread
*thread
= mono_thread_internal_current ();
4644 MonoThread
*sys_thread
= mono_thread_current ();
4646 LOCK_THREAD (thread
);
4647 gboolean unlock
= TRUE
;
4649 /* MonoThread::interruption_requested can only be changed with atomics */
4650 if (!mono_thread_clear_interruption_requested (thread
))
4653 /* this will consume pending APC calls */
4656 mono_win32_wait_for_single_object_ex (GetCurrentThread (), 0, TRUE
);
4660 /* Clear the interrupted flag of the thread so it can wait again */
4661 mono_thread_info_clear_self_interrupt ();
4663 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4664 exc
= sys_thread
->pending_exception
;
4666 sys_thread
->pending_exception
= NULL
;
4667 } else if (thread
->state
& ThreadState_AbortRequested
) {
4668 exc
= thread
->abort_exc
;
4670 exc
= mono_get_exception_thread_abort ();
4671 MONO_OBJECT_SETREF (thread
, abort_exc
, exc
);
4673 } else if (thread
->state
& ThreadState_SuspendRequested
) {
4674 /* calls UNLOCK_THREAD (thread) */
4675 self_suspend_internal ();
4677 } else if (thread
->thread_interrupt_requested
) {
4678 thread
->thread_interrupt_requested
= FALSE
;
4679 UNLOCK_THREAD (thread
);
4681 exc
= mono_get_exception_thread_interrupted ();
4686 UNLOCK_THREAD (thread
);
4692 mono_thread_execute_interruption_void (void)
4694 mono_thread_execute_interruption ();
4698 * mono_thread_request_interruption
4700 * A signal handler can call this method to request the interruption of a
4701 * thread. The result of the interruption will depend on the current state of
4702 * the thread. If the result is an exception that needs to be throw, it is
4703 * provided as return value.
4705 static MonoException
*
4706 mono_thread_request_interruption (gboolean running_managed
)
4708 MonoInternalThread
*thread
= mono_thread_internal_current ();
4710 /* The thread may already be stopping */
4714 if (!mono_thread_set_interruption_requested (thread
))
4717 if (!running_managed
|| is_running_protected_wrapper ()) {
4718 /* Can't stop while in unmanaged code. Increase the global interruption
4719 request count. When exiting the unmanaged method the count will be
4720 checked and the thread will be interrupted. */
4722 /* this will awake the thread if it is in WaitForSingleObject
4725 mono_win32_interrupt_wait (thread
->thread_info
, thread
->native_handle
, (DWORD
)thread
->tid
);
4727 mono_thread_info_self_interrupt ();
4732 return mono_thread_execute_interruption ();
4737 mono_thread_request_interruption_void (gboolean running_managed
)
4739 mono_thread_request_interruption (running_managed
);
4742 /*This function should be called by a thread after it has exited all of
4743 * its handle blocks at interruption time.*/
4745 mono_thread_resume_interruption (gboolean exec
)
4747 MonoInternalThread
*thread
= mono_thread_internal_current ();
4748 gboolean still_aborting
;
4750 /* The thread may already be stopping */
4754 LOCK_THREAD (thread
);
4755 still_aborting
= (thread
->state
& (ThreadState_AbortRequested
)) != 0;
4756 UNLOCK_THREAD (thread
);
4758 /*This can happen if the protected block called Thread::ResetAbort*/
4759 if (!still_aborting
)
4762 if (!mono_thread_set_interruption_requested (thread
))
4765 mono_thread_info_self_interrupt ();
4767 if (exec
) // Ignore the exception here, it will be raised later.
4768 mono_thread_execute_interruption_void ();
4771 gboolean
mono_thread_interruption_requested ()
4773 if (thread_interruption_requested
) {
4774 MonoInternalThread
*thread
= mono_thread_internal_current ();
4775 /* The thread may already be stopping */
4777 return mono_thread_get_interruption_requested (thread
);
4782 static MonoException
*
4783 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection
)
4785 MonoInternalThread
*thread
= mono_thread_internal_current ();
4787 /* The thread may already be stopping */
4790 if (!mono_thread_get_interruption_requested (thread
))
4792 if (!bypass_abort_protection
&& !mono_thread_current ()->pending_exception
&& is_running_protected_wrapper ())
4795 return mono_thread_execute_interruption ();
4799 * Performs the interruption of the current thread, if one has been requested,
4800 * and the thread is not running a protected wrapper.
4801 * Return the exception which needs to be thrown, if any.
4804 mono_thread_interruption_checkpoint (void)
4806 return mono_thread_interruption_checkpoint_request (FALSE
);
4810 mono_thread_interruption_checkpoint_bool (void)
4812 return mono_thread_interruption_checkpoint () != NULL
;
4816 mono_thread_interruption_checkpoint_void (void)
4818 mono_thread_interruption_checkpoint ();
4822 * Performs the interruption of the current thread, if one has been requested.
4823 * Return the exception which needs to be thrown, if any.
4826 mono_thread_force_interruption_checkpoint_noraise (void)
4828 return mono_thread_interruption_checkpoint_request (TRUE
);
4832 * mono_set_pending_exception:
4834 * Set the pending exception of the current thread to EXC.
4835 * The exception will be thrown when execution returns to managed code.
4838 mono_set_pending_exception (MonoException
*exc
)
4840 MonoThread
*thread
= mono_thread_current ();
4842 /* The thread may already be stopping */
4846 MONO_OBJECT_SETREF (thread
, pending_exception
, exc
);
4848 mono_thread_request_interruption_void (FALSE
);
4852 * mono_runtime_set_pending_exception:
4854 * Set the pending exception of the current thread to \p exc.
4855 * The exception will be thrown when execution returns to managed code.
4856 * Can optionally \p overwrite any existing pending exceptions (it's not supported
4857 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
4858 * in which case the behavior will be undefined).
4859 * Return whether the pending exception was set or not.
4860 * It will not be set if:
4861 * * The thread or runtime is stopping or shutting down
4862 * * There already is a pending exception (and \p overwrite is false)
4865 mono_runtime_set_pending_exception (MonoException
*exc
, mono_bool overwrite
)
4867 MonoThread
*thread
= mono_thread_current ();
4869 /* The thread may already be stopping */
4873 /* Don't overwrite any existing pending exceptions unless asked to */
4874 if (!overwrite
&& thread
->pending_exception
)
4877 MONO_OBJECT_SETREF (thread
, pending_exception
, exc
);
4879 mono_thread_request_interruption (FALSE
);
4886 * mono_set_pending_exception_handle:
4888 * Set the pending exception of the current thread to EXC.
4889 * The exception will be thrown when execution returns to managed code.
4892 mono_set_pending_exception_handle (MonoExceptionHandle exc
)
4894 MonoThread
*thread
= mono_thread_current ();
4896 /* The thread may already be stopping */
4900 MONO_OBJECT_SETREF (thread
, pending_exception
, MONO_HANDLE_RAW (exc
));
4902 mono_thread_request_interruption_void (FALSE
);
4906 * mono_thread_interruption_request_flag:
4908 * Returns the address of a flag that will be non-zero if an interruption has
4909 * been requested for a thread. The thread to interrupt may not be the current
4910 * thread, so an additional call to mono_thread_interruption_requested() or
4911 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4914 gint32
* mono_thread_interruption_request_flag ()
4916 return &thread_interruption_requested
;
4920 mono_thread_init_apartment_state (void)
4923 MonoInternalThread
* thread
= mono_thread_internal_current ();
4925 /* Positive return value indicates success, either
4926 * S_OK if this is first CoInitialize call, or
4927 * S_FALSE if CoInitialize already called, but with same
4928 * threading model. A negative value indicates failure,
4929 * probably due to trying to change the threading model.
4931 if (CoInitializeEx(NULL
, (thread
->apartment_state
== ThreadApartmentState_STA
)
4932 ? COINIT_APARTMENTTHREADED
4933 : COINIT_MULTITHREADED
) < 0) {
4934 thread
->apartment_state
= ThreadApartmentState_Unknown
;
4940 mono_thread_cleanup_apartment_state (void)
4943 MonoInternalThread
* thread
= mono_thread_internal_current ();
4945 if (thread
&& thread
->apartment_state
!= ThreadApartmentState_Unknown
) {
4952 mono_thread_notify_change_state (MonoThreadState old_state
, MonoThreadState new_state
)
4954 MonoThreadState diff
= old_state
^ new_state
;
4955 if (diff
& ThreadState_Background
) {
4956 /* If the thread changes the background mode, the main thread has to
4957 * be notified, since it has to rebuild the list of threads to
4961 mono_os_event_set (&background_change_event
);
4967 mono_thread_clear_and_set_state (MonoInternalThread
*thread
, MonoThreadState clear
, MonoThreadState set
)
4969 LOCK_THREAD (thread
);
4971 MonoThreadState
const old_state
= thread
->state
;
4972 MonoThreadState
const new_state
= (old_state
& ~clear
) | set
;
4973 thread
->state
= new_state
;
4975 UNLOCK_THREAD (thread
);
4977 mono_thread_notify_change_state (old_state
, new_state
);
4981 mono_thread_set_state (MonoInternalThread
*thread
, MonoThreadState state
)
4983 mono_thread_clear_and_set_state (thread
, 0, state
);
4987 * mono_thread_test_and_set_state:
4988 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
4989 * \returns TRUE if \p set was OR'd in.
4992 mono_thread_test_and_set_state (MonoInternalThread
*thread
, MonoThreadState test
, MonoThreadState set
)
4994 LOCK_THREAD (thread
);
4996 MonoThreadState
const old_state
= thread
->state
;
4998 if ((old_state
& test
) != 0) {
4999 UNLOCK_THREAD (thread
);
5003 MonoThreadState
const new_state
= old_state
| set
;
5004 thread
->state
= new_state
;
5006 UNLOCK_THREAD (thread
);
5008 mono_thread_notify_change_state (old_state
, new_state
);
5014 mono_thread_clr_state (MonoInternalThread
*thread
, MonoThreadState state
)
5016 mono_thread_clear_and_set_state (thread
, state
, 0);
5020 mono_thread_test_state (MonoInternalThread
*thread
, MonoThreadState test
)
5022 LOCK_THREAD (thread
);
5024 gboolean
const ret
= ((thread
->state
& test
) != 0);
5026 UNLOCK_THREAD (thread
);
5032 self_interrupt_thread (void *_unused
)
5035 MonoThreadInfo
*info
;
5038 exc
= mono_thread_execute_interruption ();
5040 if (mono_threads_are_safepoints_enabled ()) {
5041 /* We can return from an async call in coop, as
5042 * it's simply called when exiting the safepoint */
5043 /* If we're using hybrid suspend, we only self
5044 * interrupt if we were running, hence using
5049 g_error ("%s: we can't resume from an async call", __func__
);
5052 info
= mono_thread_info_current ();
5054 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5055 ctx
= info
->thread_saved_state
[ASYNC_SUSPEND_STATE_INDEX
].ctx
;
5057 mono_raise_exception_with_context (exc
, &ctx
);
5061 mono_jit_info_match (MonoJitInfo
*ji
, gpointer ip
)
5065 return ji
->code_start
<= ip
&& (char*)ip
< (char*)ji
->code_start
+ ji
->code_size
;
5069 last_managed (MonoStackFrameInfo
*frame
, MonoContext
*ctx
, gpointer data
)
5071 MonoJitInfo
**dest
= (MonoJitInfo
**)data
;
5077 mono_thread_info_get_last_managed (MonoThreadInfo
*info
)
5079 MonoJitInfo
*ji
= NULL
;
5084 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5085 * any runtime locks while unwinding. In coop case we shouldn't safepoint in regions
5086 * where we hold runtime locks.
5088 if (!mono_threads_are_safepoints_enabled ())
5089 mono_thread_info_set_is_async_context (TRUE
);
5090 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed
, mono_thread_info_get_suspend_state (info
), MONO_UNWIND_SIGNAL_SAFE
, &ji
);
5091 if (!mono_threads_are_safepoints_enabled ())
5092 mono_thread_info_set_is_async_context (FALSE
);
5097 MonoInternalThread
*thread
;
5098 gboolean install_async_abort
;
5099 MonoThreadInfoInterruptToken
*interrupt_token
;
5102 static SuspendThreadResult
5103 async_abort_critical (MonoThreadInfo
*info
, gpointer ud
)
5105 AbortThreadData
*data
= (AbortThreadData
*)ud
;
5106 MonoInternalThread
*thread
= data
->thread
;
5107 MonoJitInfo
*ji
= NULL
;
5108 gboolean protected_wrapper
;
5109 gboolean running_managed
;
5111 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info
)))
5112 return MonoResumeThread
;
5114 /*someone is already interrupting it*/
5115 if (!mono_thread_set_interruption_requested (thread
))
5116 return MonoResumeThread
;
5118 ji
= mono_thread_info_get_last_managed (info
);
5119 protected_wrapper
= ji
&& !ji
->is_trampoline
&& !ji
->async
&& mono_threads_is_critical_method (mono_jit_info_get_method (ji
));
5120 running_managed
= mono_jit_info_match (ji
, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info
)->ctx
));
5122 if (!protected_wrapper
&& running_managed
) {
5123 /*We are in managed code*/
5124 /*Set the thread to call */
5125 if (data
->install_async_abort
)
5126 mono_thread_info_setup_async_call (info
, self_interrupt_thread
, NULL
);
5127 return MonoResumeThread
;
5130 * This will cause waits to be broken.
5131 * It will also prevent the thread from entering a wait, so if the thread returns
5132 * from the wait before it receives the abort signal, it will just spin in the wait
5133 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5136 data
->interrupt_token
= mono_thread_info_prepare_interrupt (info
);
5138 return MonoResumeThread
;
5143 async_abort_internal (MonoInternalThread
*thread
, gboolean install_async_abort
)
5145 AbortThreadData data
;
5147 g_assert (thread
!= mono_thread_internal_current ());
5149 data
.thread
= thread
;
5150 data
.install_async_abort
= install_async_abort
;
5151 data
.interrupt_token
= NULL
;
5153 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), TRUE
, async_abort_critical
, &data
);
5154 if (data
.interrupt_token
)
5155 mono_thread_info_finish_interrupt (data
.interrupt_token
);
5156 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5160 self_abort_internal (MonoError
*error
)
5166 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5167 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5170 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.
5172 exc
= mono_thread_request_interruption (TRUE
);
5174 mono_error_set_exception_instance (error
, exc
);
5176 mono_thread_info_self_interrupt ();
5180 MonoInternalThread
*thread
;
5182 MonoThreadInfoInterruptToken
*interrupt_token
;
5183 } SuspendThreadData
;
5185 static SuspendThreadResult
5186 async_suspend_critical (MonoThreadInfo
*info
, gpointer ud
)
5188 SuspendThreadData
*data
= (SuspendThreadData
*)ud
;
5189 MonoInternalThread
*thread
= data
->thread
;
5190 MonoJitInfo
*ji
= NULL
;
5191 gboolean protected_wrapper
;
5192 gboolean running_managed
;
5194 ji
= mono_thread_info_get_last_managed (info
);
5195 protected_wrapper
= ji
&& !ji
->is_trampoline
&& !ji
->async
&& mono_threads_is_critical_method (mono_jit_info_get_method (ji
));
5196 running_managed
= mono_jit_info_match (ji
, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info
)->ctx
));
5198 if (running_managed
&& !protected_wrapper
) {
5199 if (mono_threads_are_safepoints_enabled ()) {
5200 mono_thread_info_setup_async_call (info
, self_interrupt_thread
, NULL
);
5201 return MonoResumeThread
;
5203 thread
->state
&= ~ThreadState_SuspendRequested
;
5204 thread
->state
|= ThreadState_Suspended
;
5205 return KeepSuspended
;
5208 mono_thread_set_interruption_requested (thread
);
5209 if (data
->interrupt
)
5210 data
->interrupt_token
= mono_thread_info_prepare_interrupt ((MonoThreadInfo
*)thread
->thread_info
);
5212 return MonoResumeThread
;
5216 /* LOCKING: called with @thread synch_cs held, and releases it */
5218 async_suspend_internal (MonoInternalThread
*thread
, gboolean interrupt
)
5220 SuspendThreadData data
;
5222 g_assert (thread
!= mono_thread_internal_current ());
5224 // MOSTLY_ASYNC_SAFE_PRINTF ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5226 thread
->self_suspended
= FALSE
;
5228 data
.thread
= thread
;
5229 data
.interrupt
= interrupt
;
5230 data
.interrupt_token
= NULL
;
5232 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), interrupt
, async_suspend_critical
, &data
);
5233 if (data
.interrupt_token
)
5234 mono_thread_info_finish_interrupt (data
.interrupt_token
);
5236 UNLOCK_THREAD (thread
);
5239 /* LOCKING: called with @thread synch_cs held, and releases it */
5241 self_suspend_internal (void)
5243 MonoInternalThread
*thread
;
5245 MonoOSEventWaitRet res
;
5247 thread
= mono_thread_internal_current ();
5249 // MOSTLY_ASYNC_SAFE_PRINTF ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5251 thread
->self_suspended
= TRUE
;
5253 thread
->state
&= ~ThreadState_SuspendRequested
;
5254 thread
->state
|= ThreadState_Suspended
;
5256 UNLOCK_THREAD (thread
);
5258 event
= thread
->suspended
;
5261 res
= mono_os_event_wait_one (event
, MONO_INFINITE_WAIT
, TRUE
);
5262 g_assert (res
== MONO_OS_EVENT_WAIT_RET_SUCCESS_0
|| res
== MONO_OS_EVENT_WAIT_RET_ALERTED
);
5267 suspend_for_shutdown_async_call (gpointer unused
)
5270 mono_thread_info_yield ();
5273 static SuspendThreadResult
5274 suspend_for_shutdown_critical (MonoThreadInfo
*info
, gpointer unused
)
5276 mono_thread_info_setup_async_call (info
, suspend_for_shutdown_async_call
, NULL
);
5277 return MonoResumeThread
;
5281 mono_thread_internal_suspend_for_shutdown (MonoInternalThread
*thread
)
5283 g_assert (thread
!= mono_thread_internal_current ());
5285 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, suspend_for_shutdown_critical
, NULL
);
5289 * mono_thread_is_foreign:
5290 * \param thread the thread to query
5292 * This function allows one to determine if a thread was created by the mono runtime and has
5293 * a well defined lifecycle or it's a foreign one, created by the native environment.
5295 * \returns TRUE if \p thread was not created by the runtime.
5298 mono_thread_is_foreign (MonoThread
*thread
)
5300 MonoThreadInfo
*info
= (MonoThreadInfo
*)thread
->internal_thread
->thread_info
;
5301 return info
->runtime_thread
== FALSE
;
5306 threads_native_thread_join_lock (gpointer tid
, gpointer value
)
5308 pthread_t thread
= (pthread_t
)tid
;
5309 if (thread
!= pthread_self ()) {
5311 /* This shouldn't block */
5312 mono_threads_join_lock ();
5313 mono_native_thread_join (thread
);
5314 mono_threads_join_unlock ();
5319 threads_native_thread_join_nolock (gpointer tid
, gpointer value
)
5321 pthread_t thread
= (pthread_t
)tid
;
5323 mono_native_thread_join (thread
);
5328 threads_add_joinable_thread_nolock (gpointer tid
)
5330 g_hash_table_insert (joinable_threads
, tid
, tid
);
5334 threads_native_thread_join_lock (gpointer tid
, gpointer value
)
5336 MonoNativeThreadId thread_id
= (MonoNativeThreadId
)(guint64
)tid
;
5337 HANDLE thread_handle
= (HANDLE
)value
;
5338 if (thread_id
!= GetCurrentThreadId () && thread_handle
!= NULL
&& thread_handle
!= INVALID_HANDLE_VALUE
) {
5340 /* This shouldn't block */
5341 mono_threads_join_lock ();
5342 mono_native_thread_join_handle (thread_handle
, TRUE
);
5343 mono_threads_join_unlock ();
5349 threads_native_thread_join_nolock (gpointer tid
, gpointer value
)
5351 HANDLE thread_handle
= (HANDLE
)value
;
5353 mono_native_thread_join_handle (thread_handle
, TRUE
);
5358 threads_add_joinable_thread_nolock (gpointer tid
)
5360 g_hash_table_insert (joinable_threads
, tid
, (gpointer
)OpenThread (SYNCHRONIZE
, TRUE
, (MonoNativeThreadId
)(guint64
)tid
));
5365 threads_add_pending_joinable_thread (gpointer tid
)
5367 joinable_threads_lock ();
5369 if (!pending_joinable_threads
)
5370 pending_joinable_threads
= g_hash_table_new (NULL
, NULL
);
5375 if (!g_hash_table_lookup_extended (pending_joinable_threads
, tid
, &orig_key
, &value
)) {
5376 g_hash_table_insert (pending_joinable_threads
, tid
, tid
);
5377 UnlockedIncrement (&pending_joinable_thread_count
);
5380 joinable_threads_unlock ();
5384 threads_add_pending_joinable_runtime_thread (MonoThreadInfo
*mono_thread_info
)
5386 g_assert (mono_thread_info
);
5388 if (mono_thread_info
->runtime_thread
) {
5389 threads_add_pending_joinable_thread ((gpointer
)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info
))));
5394 threads_remove_pending_joinable_thread_nolock (gpointer tid
)
5399 if (pending_joinable_threads
&& g_hash_table_lookup_extended (pending_joinable_threads
, tid
, &orig_key
, &value
)) {
5400 g_hash_table_remove (pending_joinable_threads
, tid
);
5401 if (UnlockedDecrement (&pending_joinable_thread_count
) == 0)
5402 mono_os_cond_broadcast (&zero_pending_joinable_thread_event
);
5407 threads_wait_pending_joinable_threads (uint32_t timeout
)
5409 if (UnlockedRead (&pending_joinable_thread_count
) > 0) {
5410 joinable_threads_lock ();
5411 if (timeout
== MONO_INFINITE_WAIT
) {
5412 while (UnlockedRead (&pending_joinable_thread_count
) > 0)
5413 mono_os_cond_wait (&zero_pending_joinable_thread_event
, &joinable_threads_mutex
);
5415 gint64 start
= mono_msec_ticks ();
5417 while (UnlockedRead (&pending_joinable_thread_count
) > 0 && elapsed
< timeout
) {
5418 mono_os_cond_timedwait (&zero_pending_joinable_thread_event
, &joinable_threads_mutex
, timeout
- (uint32_t)elapsed
);
5419 elapsed
= mono_msec_ticks () - start
;
5422 joinable_threads_unlock ();
5425 return UnlockedRead (&pending_joinable_thread_count
) == 0;
5429 threads_add_unique_joinable_thread_nolock (gpointer tid
)
5431 if (!joinable_threads
)
5432 joinable_threads
= g_hash_table_new (NULL
, NULL
);
5437 if (!g_hash_table_lookup_extended (joinable_threads
, tid
, &orig_key
, &value
)) {
5438 threads_add_joinable_thread_nolock (tid
);
5439 UnlockedIncrement (&joinable_thread_count
);
5444 mono_threads_add_joinable_runtime_thread (gpointer thread_info
)
5446 g_assert (thread_info
);
5447 MonoThreadInfo
*mono_thread_info
= (MonoThreadInfo
*)thread_info
;
5449 if (mono_thread_info
->runtime_thread
) {
5450 gpointer tid
= (gpointer
)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info
)));
5452 joinable_threads_lock ();
5454 // Add to joinable thread list, if not already included.
5455 threads_add_unique_joinable_thread_nolock (tid
);
5457 // Remove thread from pending joinable list, if present.
5458 threads_remove_pending_joinable_thread_nolock (tid
);
5460 joinable_threads_unlock ();
5462 mono_gc_finalize_notify ();
5467 * mono_add_joinable_thread:
5469 * Add TID to the list of joinable threads.
5470 * LOCKING: Acquires the threads lock.
5473 mono_threads_add_joinable_thread (gpointer tid
)
5476 * We cannot detach from threads because it causes problems like
5477 * 2fd16f60/r114307. So we collect them and join them when
5478 * we have time (in the finalizer thread).
5480 joinable_threads_lock ();
5481 threads_add_unique_joinable_thread_nolock (tid
);
5482 joinable_threads_unlock ();
5484 mono_gc_finalize_notify ();
5488 * mono_threads_join_threads:
5490 * Join all joinable threads. This is called from the finalizer thread.
5491 * LOCKING: Acquires the threads lock.
5494 mono_threads_join_threads (void)
5496 GHashTableIter iter
;
5502 if (!UnlockedRead (&joinable_thread_count
))
5506 joinable_threads_lock ();
5508 if (g_hash_table_size (joinable_threads
)) {
5509 g_hash_table_iter_init (&iter
, joinable_threads
);
5510 g_hash_table_iter_next (&iter
, &key
, (void**)&value
);
5511 g_hash_table_remove (joinable_threads
, key
);
5512 UnlockedDecrement (&joinable_thread_count
);
5515 joinable_threads_unlock ();
5517 threads_native_thread_join_lock (key
, value
);
5526 * Wait for thread TID to exit.
5527 * LOCKING: Acquires the threads lock.
5530 mono_thread_join (gpointer tid
)
5532 gboolean found
= FALSE
;
5536 joinable_threads_lock ();
5537 if (!joinable_threads
)
5538 joinable_threads
= g_hash_table_new (NULL
, NULL
);
5540 if (g_hash_table_lookup_extended (joinable_threads
, tid
, &orig_key
, &value
)) {
5541 g_hash_table_remove (joinable_threads
, tid
);
5542 UnlockedDecrement (&joinable_thread_count
);
5545 joinable_threads_unlock ();
5550 threads_native_thread_join_nolock (tid
, value
);
5554 mono_thread_internal_unhandled_exception (MonoObject
* exc
)
5556 MonoClass
*klass
= exc
->vtable
->klass
;
5557 if (is_threadabort_exception (klass
)) {
5558 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5559 } else if (!is_appdomainunloaded_exception (klass
)
5560 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT
) {
5561 mono_unhandled_exception (exc
);
5562 if (mono_environment_exitcode_get () == 1) {
5563 mono_environment_exitcode_set (255);
5564 mono_invoke_unhandled_exception_hook (exc
);
5565 g_assert_not_reached ();
5571 ves_icall_System_Threading_Thread_GetStackTraces (MonoArray
**out_threads
, MonoArray
**out_stack_traces
)
5574 mono_threads_get_thread_dump (out_threads
, out_stack_traces
, error
);
5575 mono_error_set_pending_exception (error
);
5579 * mono_threads_attach_coop_internal: called by native->managed wrappers
5582 * - blocking mode: contains gc unsafe transition cookie
5583 * - non-blocking mode: contains random data
5584 * - @stackdata: semi-opaque struct: stackpointer and function_name
5585 * - @return: the original domain which needs to be restored, or NULL.
5588 mono_threads_attach_coop_internal (MonoDomain
*domain
, gpointer
*cookie
, MonoStackData
*stackdata
)
5591 MonoThreadInfo
*info
;
5594 orig
= mono_domain_get ();
5597 /* Happens when called from AOTed code which is only used in the root domain. */
5598 domain
= mono_get_root_domain ();
5602 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
5603 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
5604 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
5605 * we're only responsible for making the cookie. */
5606 if (mono_threads_is_blocking_transition_enabled ())
5607 external
= !(info
= mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info
);
5609 if (!mono_thread_internal_current ()) {
5610 mono_thread_attach (domain
);
5613 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background
);
5617 mono_domain_set (domain
, TRUE
);
5619 if (mono_threads_is_blocking_transition_enabled ()) {
5621 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
5622 * return the right cookie. */
5623 *cookie
= mono_threads_enter_gc_unsafe_region_cookie ();
5625 /* thread state (BLOCKING|RUNNING) -> RUNNING */
5626 *cookie
= mono_threads_enter_gc_unsafe_region_internal (stackdata
);
5634 * mono_threads_attach_coop: called by native->managed wrappers
5637 * - blocking mode: contains gc unsafe transition cookie
5638 * - non-blocking mode: contains random data
5639 * - a pointer to stack, used for some checks
5640 * - @return: the original domain which needs to be restored, or NULL.
5643 mono_threads_attach_coop (MonoDomain
*domain
, gpointer
*dummy
)
5645 MONO_STACKDATA (stackdata
);
5646 stackdata
.stackpointer
= dummy
;
5647 return mono_threads_attach_coop_internal (domain
, dummy
, &stackdata
);
5651 * mono_threads_detach_coop_internal: called by native->managed wrappers
5653 * - @orig: the original domain which needs to be restored, or NULL.
5654 * - @stackdata: semi-opaque struct: stackpointer and function_name
5656 * - blocking mode: contains gc unsafe transition cookie
5657 * - non-blocking mode: contains random data
5660 mono_threads_detach_coop_internal (MonoDomain
*orig
, gpointer cookie
, MonoStackData
*stackdata
)
5662 MonoDomain
*domain
= mono_domain_get ();
5665 if (mono_threads_is_blocking_transition_enabled ()) {
5666 /* it won't do anything if cookie is NULL
5667 * thread state RUNNING -> (RUNNING|BLOCKING) */
5668 mono_threads_exit_gc_unsafe_region_internal (cookie
, stackdata
);
5671 if (orig
!= domain
) {
5673 mono_domain_unset ();
5675 mono_domain_set (orig
, TRUE
);
5680 * mono_threads_detach_coop: called by native->managed wrappers
5682 * - @orig: the original domain which needs to be restored, or NULL.
5684 * - blocking mode: contains gc unsafe transition cookie
5685 * - non-blocking mode: contains random data
5686 * - a pointer to stack, used for some checks
5689 mono_threads_detach_coop (gpointer orig
, gpointer
*dummy
)
5691 MONO_STACKDATA (stackdata
);
5692 stackdata
.stackpointer
= dummy
;
5693 mono_threads_detach_coop_internal ((MonoDomain
*)orig
, *dummy
, &stackdata
);
5697 /* Returns TRUE if the current thread is ready to be interrupted. */
5699 mono_threads_is_ready_to_be_interrupted (void)
5701 MonoInternalThread
*thread
;
5703 thread
= mono_thread_internal_current ();
5704 LOCK_THREAD (thread
);
5705 if (thread
->state
& (ThreadState_SuspendRequested
| ThreadState_AbortRequested
)) {
5706 UNLOCK_THREAD (thread
);
5710 if (mono_thread_get_abort_prot_block_count (thread
) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
5711 UNLOCK_THREAD (thread
);
5715 UNLOCK_THREAD (thread
);
5721 mono_thread_internal_describe (MonoInternalThread
*internal
, GString
*text
)
5723 g_string_append_printf (text
, ", thread handle : %p", internal
->handle
);
5725 if (internal
->thread_info
) {
5726 g_string_append (text
, ", state : ");
5727 mono_thread_info_describe_interrupt_token ((MonoThreadInfo
*) internal
->thread_info
, text
);
5730 if (internal
->owned_mutexes
) {
5733 g_string_append (text
, ", owns : [");
5734 for (i
= 0; i
< internal
->owned_mutexes
->len
; i
++)
5735 g_string_append_printf (text
, i
== 0 ? "%p" : ", %p", g_ptr_array_index (internal
->owned_mutexes
, i
));
5736 g_string_append (text
, "]");
5741 mono_thread_internal_is_current (MonoInternalThread
*internal
)
5743 g_assert (internal
);
5744 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
));