3 * Thread support internal calls
6 * Dick Porter (dick@ximian.com)
7 * Paolo Molaro (lupus@ximian.com)
8 * Patrik Torstensson (patrik.torstensson@labs2.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/domain-internals.h>
23 #include <mono/metadata/profiler-private.h>
24 #include <mono/metadata/threads.h>
25 #include <mono/metadata/threads-types.h>
26 #include <mono/metadata/exception.h>
27 #include <mono/metadata/environment.h>
28 #include <mono/metadata/monitor.h>
29 #include <mono/metadata/mono-hash-internals.h>
30 #include <mono/metadata/gc-internals.h>
31 #include <mono/metadata/marshal.h>
32 #include <mono/metadata/runtime.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/debug-internals.h>
35 #include <mono/utils/monobitset.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
40 #include <mono/utils/mono-threads.h>
41 #include <mono/utils/mono-threads-coop.h>
42 #include <mono/utils/mono-tls.h>
43 #include <mono/utils/atomic.h>
44 #include <mono/utils/mono-memory-model.h>
45 #include <mono/utils/mono-error-internals.h>
46 #include <mono/utils/os-event.h>
47 #include <mono/utils/mono-threads-debug.h>
48 #include <mono/utils/unlocked.h>
49 #include <mono/metadata/w32handle.h>
50 #include <mono/metadata/w32event.h>
51 #include <mono/metadata/w32mutex.h>
53 #include <mono/metadata/reflection-internals.h>
54 #include <mono/metadata/abi-details.h>
55 #include <mono/metadata/w32error.h>
56 #include <mono/utils/w32api.h>
57 #include <mono/utils/mono-os-wait.h>
58 #include <mono/metadata/exception-internals.h>
59 #include <mono/utils/mono-state.h>
60 #include <mono/metadata/w32subset.h>
61 #include <mono/metadata/mono-config.h>
63 #ifdef HAVE_SYS_WAIT_H
71 #if defined(HOST_WIN32)
73 #include <sys/timeb.h>
75 mono_native_thread_join_handle (HANDLE thread_handle
, gboolean close_handle
);
78 #if defined(HOST_FUCHSIA)
79 #include <zircon/syscalls.h>
82 #if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
83 #define USE_TKILL_ON_ANDROID 1
89 #ifdef USE_TKILL_ON_ANDROID
90 extern int tkill (pid_t tid
, int signal
);
94 #include "icall-decl.h"
96 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
97 #define THREAD_DEBUG(a)
98 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
99 #define THREAD_WAIT_DEBUG(a)
100 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
101 #define LIBGC_DEBUG(a)
103 #define SPIN_TRYLOCK(i) (mono_atomic_cas_i32 (&(i), 1, 0) == 0)
104 #define SPIN_LOCK(i) do { \
105 if (SPIN_TRYLOCK (i)) \
109 #define SPIN_UNLOCK(i) i = 0
111 #define LOCK_THREAD(thread) lock_thread((thread))
112 #define UNLOCK_THREAD(thread) unlock_thread((thread))
124 typedef struct _StaticDataFreeList StaticDataFreeList
;
125 struct _StaticDataFreeList
{
126 StaticDataFreeList
*next
;
134 StaticDataFreeList
*freelist
;
137 /* Controls access to the 'threads' hash table */
138 static void mono_threads_lock (void);
139 static void mono_threads_unlock (void);
140 static MonoCoopMutex threads_mutex
;
142 /* Controls access to the 'joinable_threads' hash table */
143 #define joinable_threads_lock() mono_coop_mutex_lock (&joinable_threads_mutex)
144 #define joinable_threads_unlock() mono_coop_mutex_unlock (&joinable_threads_mutex)
145 static MonoCoopMutex joinable_threads_mutex
;
147 /* Holds current status of static data heap */
148 static StaticDataInfo thread_static_info
;
149 static StaticDataInfo context_static_info
;
151 /* The hash of existing threads (key is thread ID, value is
152 * MonoInternalThread*) that need joining before exit
154 static MonoGHashTable
*threads
=NULL
;
156 /* List of app context GC handles.
157 * Added to from mono_threads_register_app_context ().
159 static GHashTable
*contexts
= NULL
;
161 /* Cleanup queue for contexts. */
162 static MonoReferenceQueue
*context_queue
;
165 * Threads which are starting up and they are not in the 'threads' hash yet.
166 * When mono_thread_attach_internal is called for a thread, it will be removed from this hash table.
167 * Protected by mono_threads_lock ().
169 static MonoGHashTable
*threads_starting_up
= NULL
;
172 /* Protected by the threads lock */
173 static GHashTable
*joinable_threads
;
174 static gint32 joinable_thread_count
;
176 /* mono_threads_join_threads will take threads from joinable_threads list and wait for them. */
177 /* When this happens, the tid is not on the list anymore so mono_thread_join assumes the thread has complete */
178 /* and will return back to the caller. This could cause a race since caller of join assumes thread has completed */
179 /* and on some OS it could cause errors. Keeping the tid's currently pending a native thread join call */
180 /* in a separate table (only affecting callers interested in this internal join detail) and look at that table in mono_thread_join */
181 /* will close this race. */
182 static GHashTable
*pending_native_thread_join_calls
;
183 static MonoCoopCond pending_native_thread_join_calls_event
;
185 static GHashTable
*pending_joinable_threads
;
186 static gint32 pending_joinable_thread_count
;
188 static MonoCoopCond zero_pending_joinable_thread_event
;
190 static void threads_add_pending_joinable_runtime_thread (MonoThreadInfo
*mono_thread_info
);
191 static gboolean
threads_wait_pending_joinable_threads (uint32_t timeout
);
192 static gchar
* thread_dump_dir
= NULL
;
194 #define SET_CURRENT_OBJECT mono_tls_set_thread
195 #define GET_CURRENT_OBJECT mono_tls_get_thread
197 /* function called at thread start */
198 static MonoThreadStartCB mono_thread_start_cb
= NULL
;
200 /* function called at thread attach */
201 static MonoThreadAttachCB mono_thread_attach_cb
= NULL
;
203 /* function called at thread cleanup */
204 static MonoThreadCleanupFunc mono_thread_cleanup_fn
= NULL
;
206 /* The default stack size for each thread */
207 static guint32 default_stacksize
= 0;
208 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
210 static void context_adjust_static_data (MonoAppContextHandle ctx
);
211 static void mono_free_static_data (gpointer
* static_data
);
212 static void mono_init_static_data_info (StaticDataInfo
*static_data
);
213 static guint32
mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
);
214 static gboolean
mono_thread_resume (MonoInternalThread
* thread
);
215 static void async_abort_internal (MonoInternalThread
*thread
, gboolean install_async_abort
);
216 static void self_abort_internal (MonoError
*error
);
217 static void async_suspend_internal (MonoInternalThread
*thread
, gboolean interrupt
);
218 static void self_suspend_internal (void);
221 mono_thread_set_interruption_requested_flags (MonoInternalThread
*thread
, gboolean sync
);
224 mono_set_pending_exception_handle (MonoExceptionHandle exc
);
226 static MonoException
*
227 mono_thread_execute_interruption_ptr (void);
230 mono_thread_execute_interruption_void (void);
233 mono_thread_execute_interruption (MonoExceptionHandle
*pexc
);
235 static void ref_stack_destroy (gpointer rs
);
237 #if SIZEOF_VOID_P == 4
238 /* Spin lock for unaligned InterlockedXXX 64 bit functions on 32bit platforms. */
239 #define mono_interlocked_lock() mono_os_mutex_lock (&interlocked_mutex)
240 #define mono_interlocked_unlock() mono_os_mutex_unlock (&interlocked_mutex)
241 static mono_mutex_t interlocked_mutex
;
244 /* global count of thread interruptions requested */
245 gint32 mono_thread_interruption_request_flag
;
247 /* Event signaled when a thread changes its background mode */
248 static MonoOSEvent background_change_event
;
250 static gboolean shutting_down
= FALSE
;
252 static gint32 managed_thread_id_counter
= 0;
255 mono_threads_lock (void)
257 mono_locks_coop_acquire (&threads_mutex
, ThreadsLock
);
261 mono_threads_unlock (void)
263 mono_locks_coop_release (&threads_mutex
, ThreadsLock
);
268 get_next_managed_thread_id (void)
270 return mono_atomic_inc_i32 (&managed_thread_id_counter
);
274 * We separate interruptions/exceptions into either sync (they can be processed anytime,
275 * normally as soon as they are set, and are set by the same thread) and async (they can't
276 * be processed inside abort protected blocks and are normally set by other threads). We
277 * can have both a pending sync and async interruption. In this case, the sync exception is
278 * processed first. Since we clean sync flag first, mono_thread_execute_interruption must
279 * also handle all sync type exceptions before the async type exceptions.
282 INTERRUPT_SYNC_REQUESTED_BIT
= 0x1,
283 INTERRUPT_ASYNC_REQUESTED_BIT
= 0x2,
284 INTERRUPT_REQUESTED_MASK
= 0x3,
285 ABORT_PROT_BLOCK_SHIFT
= 2,
286 ABORT_PROT_BLOCK_BITS
= 8,
287 ABORT_PROT_BLOCK_MASK
= (((1 << ABORT_PROT_BLOCK_BITS
) - 1) << ABORT_PROT_BLOCK_SHIFT
)
291 mono_thread_get_abort_prot_block_count (MonoInternalThread
*thread
)
293 gsize state
= thread
->thread_state
;
294 return (state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
;
298 mono_threads_is_current_thread_in_protected_block (void)
300 MonoInternalThread
*thread
= mono_thread_internal_current ();
302 return mono_thread_get_abort_prot_block_count (thread
) > 0;
306 mono_threads_begin_abort_protected_block (void)
308 MonoInternalThread
*thread
= mono_thread_internal_current ();
309 gsize old_state
, new_state
;
312 old_state
= thread
->thread_state
;
314 new_val
= ((old_state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
) + 1;
315 //bounds check abort_prot_count
316 g_assert (new_val
> 0);
317 g_assert (new_val
< (1 << ABORT_PROT_BLOCK_BITS
));
319 new_state
= old_state
+ (1 << ABORT_PROT_BLOCK_SHIFT
);
320 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
322 /* Defer async request since we won't be able to process until exiting the block */
323 if (new_val
== 1 && (new_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)) {
324 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag
);
325 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, defer tir %d\n", thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
326 if (mono_thread_interruption_request_flag
< 0)
327 g_warning ("bad mono_thread_interruption_request_flag state");
329 THREADS_INTERRUPT_DEBUG ("[%d] begin abort protected block old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
334 mono_thread_state_has_interruption (gsize state
)
336 /* pending exception, self abort */
337 if (state
& INTERRUPT_SYNC_REQUESTED_BIT
)
340 /* abort, interruption, suspend */
341 if ((state
& INTERRUPT_ASYNC_REQUESTED_BIT
) && !(state
& ABORT_PROT_BLOCK_MASK
))
348 mono_threads_end_abort_protected_block (void)
350 MonoInternalThread
*thread
= mono_thread_internal_current ();
351 gsize old_state
, new_state
;
354 old_state
= thread
->thread_state
;
356 //bounds check abort_prot_count
357 new_val
= ((old_state
& ABORT_PROT_BLOCK_MASK
) >> ABORT_PROT_BLOCK_SHIFT
) - 1;
358 g_assert (new_val
>= 0);
359 g_assert (new_val
< (1 << ABORT_PROT_BLOCK_BITS
));
361 new_state
= old_state
- (1 << ABORT_PROT_BLOCK_SHIFT
);
362 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
364 if (new_val
== 0 && (new_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)) {
365 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag
);
366 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, restore tir %d\n", thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
368 THREADS_INTERRUPT_DEBUG ("[%d] end abort protected block old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
371 return mono_thread_state_has_interruption (new_state
);
375 mono_thread_get_interruption_requested (MonoInternalThread
*thread
)
377 gsize state
= thread
->thread_state
;
379 return mono_thread_state_has_interruption (state
);
383 * Returns TRUE is there was a state change
384 * We clear a single interruption request, sync has priority.
387 mono_thread_clear_interruption_requested (MonoInternalThread
*thread
)
389 gsize old_state
, new_state
;
391 old_state
= thread
->thread_state
;
393 // no interruption to process
394 if (!(old_state
& INTERRUPT_SYNC_REQUESTED_BIT
) &&
395 (!(old_state
& INTERRUPT_ASYNC_REQUESTED_BIT
) || (old_state
& ABORT_PROT_BLOCK_MASK
)))
398 if (old_state
& INTERRUPT_SYNC_REQUESTED_BIT
)
399 new_state
= old_state
& ~INTERRUPT_SYNC_REQUESTED_BIT
;
401 new_state
= old_state
& ~INTERRUPT_ASYNC_REQUESTED_BIT
;
402 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
404 mono_atomic_dec_i32 (&mono_thread_interruption_request_flag
);
405 THREADS_INTERRUPT_DEBUG ("[%d] clear interruption old_state %ld new_state %ld, tir %d\n", thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
406 if (mono_thread_interruption_request_flag
< 0)
407 g_warning ("bad mono_thread_interruption_request_flag state");
412 mono_thread_clear_interruption_requested_handle (MonoInternalThreadHandle thread
)
414 // Internal threads are pinned so shallow coop/handle.
415 return mono_thread_clear_interruption_requested (mono_internal_thread_handle_ptr (thread
));
418 /* Returns TRUE is there was a state change and the interruption can be processed */
420 mono_thread_set_interruption_requested (MonoInternalThread
*thread
)
422 //always force when the current thread is doing it to itself.
423 gboolean sync
= thread
== mono_thread_internal_current ();
424 /* Normally synchronous interruptions can bypass abort protection. */
425 return mono_thread_set_interruption_requested_flags (thread
, sync
);
428 /* Returns TRUE if there was a state change and the interruption can be
429 * processed. This variant defers a self abort when inside an abort protected
430 * block. Normally this should only be done when a thread has received an
431 * outside indication that it should abort. (For example when the JIT sets a
432 * flag in an finally block.)
436 mono_thread_set_self_interruption_respect_abort_prot (void)
438 MonoInternalThread
*thread
= mono_thread_internal_current ();
439 /* N.B. Sets the ASYNC_REQUESTED_BIT for current this thread,
440 * which is unusual. */
441 return mono_thread_set_interruption_requested_flags (thread
, FALSE
);
444 /* Returns TRUE if there was a state change and the interruption can be processed. */
446 mono_thread_set_interruption_requested_flags (MonoInternalThread
*thread
, gboolean sync
)
448 gsize old_state
, new_state
;
450 old_state
= thread
->thread_state
;
453 if ((sync
&& (old_state
& INTERRUPT_SYNC_REQUESTED_BIT
)) ||
454 (!sync
&& (old_state
& INTERRUPT_ASYNC_REQUESTED_BIT
)))
458 new_state
= old_state
| INTERRUPT_SYNC_REQUESTED_BIT
;
460 new_state
= old_state
| INTERRUPT_ASYNC_REQUESTED_BIT
;
461 } while (mono_atomic_cas_ptr ((volatile gpointer
*)&thread
->thread_state
, (gpointer
)new_state
, (gpointer
)old_state
) != (gpointer
)old_state
);
463 if (sync
|| !(new_state
& ABORT_PROT_BLOCK_MASK
)) {
464 mono_atomic_inc_i32 (&mono_thread_interruption_request_flag
);
465 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir %d\n", mono_thread_internal_current ()->small_id
, thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
467 THREADS_INTERRUPT_DEBUG ("[%d] set interruption on [%d] old_state %ld new_state %ld, tir deferred %d\n", mono_thread_internal_current ()->small_id
, thread
->small_id
, old_state
, new_state
, mono_thread_interruption_request_flag
);
470 return sync
|| !(new_state
& ABORT_PROT_BLOCK_MASK
);
473 static MonoNativeThreadId
474 thread_get_tid (MonoInternalThread
*thread
)
476 /* We store the tid as a guint64 to keep the object layout constant between platforms */
477 return MONO_UINT_TO_NATIVE_THREAD_ID (thread
->tid
);
481 free_synch_cs (MonoCoopMutex
*synch_cs
)
484 mono_coop_mutex_destroy (synch_cs
);
489 free_longlived_thread_data (void *user_data
)
491 MonoLongLivedThreadData
*lltd
= (MonoLongLivedThreadData
*)user_data
;
492 free_synch_cs (lltd
->synch_cs
);
498 init_longlived_thread_data (MonoLongLivedThreadData
*lltd
)
500 mono_refcount_init (lltd
, free_longlived_thread_data
);
501 mono_refcount_inc (lltd
);
502 /* Initial refcount is 2: decremented once by
503 * mono_thread_detach_internal and once by the MonoInternalThread
504 * finalizer - whichever one happens later will deallocate. */
506 lltd
->synch_cs
= g_new0 (MonoCoopMutex
, 1);
507 mono_coop_mutex_init_recursive (lltd
->synch_cs
);
509 mono_memory_barrier ();
513 dec_longlived_thread_data (MonoLongLivedThreadData
*lltd
)
515 mono_refcount_dec (lltd
);
519 lock_thread (MonoInternalThread
*thread
)
521 g_assert (thread
->longlived
);
522 g_assert (thread
->longlived
->synch_cs
);
524 mono_coop_mutex_lock (thread
->longlived
->synch_cs
);
528 unlock_thread (MonoInternalThread
*thread
)
530 mono_coop_mutex_unlock (thread
->longlived
->synch_cs
);
534 lock_thread_handle (MonoInternalThreadHandle thread
)
536 lock_thread (mono_internal_thread_handle_ptr (thread
));
540 unlock_thread_handle (MonoInternalThreadHandle thread
)
542 unlock_thread (mono_internal_thread_handle_ptr (thread
));
546 is_appdomainunloaded_exception (MonoClass
*klass
)
548 #ifdef ENABLE_NETCORE
551 return klass
== mono_class_get_appdomain_unloaded_exception_class ();
556 is_threadabort_exception (MonoClass
*klass
)
558 return klass
== mono_defaults
.threadabortexception_class
;
562 * A special static data offset (guint32) consists of 3 parts:
564 * [0] 6-bit index into the array of chunks.
565 * [6] 25-bit offset into the array.
566 * [31] Bit indicating thread or context static.
571 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
582 } SpecialStaticOffset
;
584 #define SPECIAL_STATIC_OFFSET_TYPE_THREAD 0
585 #define SPECIAL_STATIC_OFFSET_TYPE_CONTEXT 1
588 MAKE_SPECIAL_STATIC_OFFSET (guint32 index
, guint32 offset
, guint32 type
)
590 SpecialStaticOffset special_static_offset
;
591 memset (&special_static_offset
, 0, sizeof (special_static_offset
));
592 special_static_offset
.fields
.index
= index
;
593 special_static_offset
.fields
.offset
= offset
;
594 special_static_offset
.fields
.type
= type
;
595 return special_static_offset
.raw
;
598 #define ACCESS_SPECIAL_STATIC_OFFSET(x,f) \
599 (((SpecialStaticOffset *) &(x))->fields.f)
602 get_thread_static_data (MonoInternalThread
*thread
, guint32 offset
)
604 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) == SPECIAL_STATIC_OFFSET_TYPE_THREAD
);
606 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
607 int off
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
609 return ((char *) thread
->static_data
[idx
]) + off
;
613 get_context_static_data (MonoAppContext
*ctx
, guint32 offset
)
615 g_assert (ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) == SPECIAL_STATIC_OFFSET_TYPE_CONTEXT
);
617 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
618 int off
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
620 return ((char *) ctx
->static_data
[idx
]) + off
;
624 get_current_thread_ptr_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
)
626 static MonoClassField
*current_thread_field
= NULL
;
630 if (!current_thread_field
) {
631 current_thread_field
= mono_class_get_field_from_name_full (mono_defaults
.thread_class
, "current_thread", NULL
);
632 g_assert (current_thread_field
);
635 ERROR_DECL (thread_vt_error
);
636 mono_class_vtable_checked (domain
, mono_defaults
.thread_class
, thread_vt_error
);
637 mono_error_assert_ok (thread_vt_error
);
638 mono_domain_lock (domain
);
639 offset
= GPOINTER_TO_UINT (g_hash_table_lookup (domain
->special_static_fields
, current_thread_field
));
640 mono_domain_unlock (domain
);
643 return (MonoThread
**)get_thread_static_data (thread
, offset
);
647 set_current_thread_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
, MonoThread
*current
)
649 #ifndef ENABLE_NETCORE
650 MonoThread
**current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, thread
);
652 g_assert (current
->obj
.vtable
->domain
== domain
);
654 g_assert (!*current_thread_ptr
);
655 *current_thread_ptr
= current
;
660 create_thread_object (MonoDomain
*domain
, MonoInternalThread
*internal
)
662 #ifdef ENABLE_NETCORE
663 MONO_OBJECT_SETREF_INTERNAL (internal
, internal_thread
, internal
);
670 vtable
= mono_class_vtable_checked (domain
, mono_defaults
.thread_class
, error
);
671 mono_error_assert_ok (error
);
673 thread
= (MonoThread
*)mono_object_new_mature (vtable
, error
);
674 /* only possible failure mode is OOM, from which we don't expect to recover. */
675 mono_error_assert_ok (error
);
677 MONO_OBJECT_SETREF_INTERNAL (thread
, internal_thread
, internal
);
684 init_internal_thread_object (MonoInternalThread
*thread
)
686 thread
->longlived
= g_new0 (MonoLongLivedThreadData
, 1);
687 init_longlived_thread_data (thread
->longlived
);
689 thread
->apartment_state
= ThreadApartmentState_Unknown
;
690 thread
->managed_id
= get_next_managed_thread_id ();
691 if (mono_gc_is_moving ()) {
692 thread
->thread_pinning_ref
= thread
;
693 MONO_GC_REGISTER_ROOT_PINNING (thread
->thread_pinning_ref
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Pinning Reference");
696 thread
->priority
= MONO_THREAD_PRIORITY_NORMAL
;
698 thread
->suspended
= g_new0 (MonoOSEvent
, 1);
699 mono_os_event_init (thread
->suspended
, TRUE
);
702 static MonoInternalThread
*
703 create_internal_thread_object (void)
706 MonoInternalThread
*thread
;
709 vt
= mono_class_vtable_checked (mono_get_root_domain (), mono_defaults
.internal_thread_class
, error
);
710 mono_error_assert_ok (error
);
711 thread
= (MonoInternalThread
*) mono_object_new_mature (vt
, error
);
712 /* only possible failure mode is OOM, from which we don't exect to recover */
713 mono_error_assert_ok (error
);
715 init_internal_thread_object (thread
);
721 mono_thread_internal_set_priority (MonoInternalThread
*internal
, MonoThreadPriority priority
)
725 g_assert (priority
>= MONO_THREAD_PRIORITY_LOWEST
);
726 g_assert (priority
<= MONO_THREAD_PRIORITY_HIGHEST
);
727 g_assert (MONO_THREAD_PRIORITY_LOWEST
< MONO_THREAD_PRIORITY_HIGHEST
);
733 g_assert (internal
->native_handle
);
736 res
= SetThreadPriority (internal
->native_handle
, (int)priority
- 2);
737 last_error
= GetLastError ();
740 g_error ("%s: SetThreadPriority failed, error %d", __func__
, last_error
);
741 #elif defined(HOST_FUCHSIA)
744 if (priority
== MONO_THREAD_PRIORITY_LOWEST
)
745 z_priority
= ZX_PRIORITY_LOWEST
;
746 else if (priority
== MONO_THREAD_PRIORITY_BELOW_NORMAL
)
747 z_priority
= ZX_PRIORITY_LOW
;
748 else if (priority
== MONO_THREAD_PRIORITY_NORMAL
)
749 z_priority
= ZX_PRIORITY_DEFAULT
;
750 else if (priority
== MONO_THREAD_PRIORITY_ABOVE_NORMAL
)
751 z_priority
= ZX_PRIORITY_HIGH
;
752 else if (priority
== MONO_THREAD_PRIORITY_HIGHEST
)
753 z_priority
= ZX_PRIORITY_HIGHEST
;
758 // When this API becomes available on an arbitrary thread, we can use it,
759 // not available on current Zircon
761 #else /* !HOST_WIN32 and not HOST_FUCHSIA */
764 struct sched_param param
;
767 tid
= thread_get_tid (internal
);
770 res
= pthread_getschedparam (tid
, &policy
, ¶m
);
773 g_error ("%s: pthread_getschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
775 #ifdef _POSIX_PRIORITY_SCHEDULING
778 /* Necessary to get valid priority range */
781 #if defined(__PASE__)
782 /* only priorities allowed by IBM i */
786 min
= sched_get_priority_min (policy
);
787 max
= sched_get_priority_max (policy
);
791 /* Not tunable. Bail out */
792 if ((min
== -1) || (max
== -1))
795 if (max
> 0 && min
>= 0 && max
> min
) {
796 double srange
, drange
, sposition
, dposition
;
797 srange
= MONO_THREAD_PRIORITY_HIGHEST
- MONO_THREAD_PRIORITY_LOWEST
;
799 sposition
= priority
- MONO_THREAD_PRIORITY_LOWEST
;
800 dposition
= (sposition
/ srange
) * drange
;
801 param
.sched_priority
= (int)(dposition
+ min
);
808 param
.sched_priority
= 50;
814 param
.sched_priority
= 0;
817 g_warning ("%s: unknown policy %d", __func__
, policy
);
823 #if defined(__PASE__)
824 /* only scheduling param allowed by IBM i */
825 res
= pthread_setschedparam (tid
, SCHED_OTHER
, ¶m
);
827 res
= pthread_setschedparam (tid
, policy
, ¶m
);
833 /* AIX doesn't like doing this and will spam this every time;
834 * weirdly, i doesn't complain
836 g_warning ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
840 g_error ("%s: pthread_setschedparam failed, error: \"%s\" (%d)", __func__
, g_strerror (res
), res
);
842 #endif /* HOST_WIN32 */
846 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, void *alloc_key
, gboolean threadlocal
);
849 mono_thread_attach_internal (MonoThread
*thread
, gboolean force_attach
, gboolean force_domain
)
851 MonoThreadInfo
*info
;
852 MonoInternalThread
*internal
;
853 MonoDomain
*domain
, *root_domain
;
858 info
= mono_thread_info_current ();
861 internal
= thread
->internal_thread
;
864 /* It is needed to store the MonoInternalThread on the MonoThreadInfo, because of the following case:
865 * - the MonoInternalThread TLS key is destroyed: set it to NULL
866 * - the MonoThreadInfo TLS key is destroyed: calls mono_thread_info_detach
867 * - it calls MonoThreadInfoCallbacks.thread_detach
868 * - mono_thread_internal_current returns NULL -> fails to detach the MonoInternalThread. */
869 mono_thread_info_set_internal_thread_gchandle (info
, mono_gchandle_new_internal ((MonoObject
*) internal
, FALSE
));
871 internal
->handle
= mono_threads_open_thread_handle (info
->handle
);
872 internal
->native_handle
= MONO_NATIVE_THREAD_HANDLE_TO_GPOINTER (mono_threads_open_native_thread_handle (info
->native_handle
));
873 internal
->tid
= MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ());
874 internal
->thread_info
= info
;
875 internal
->small_id
= info
->small_id
;
877 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Setting current_object_key to %p", __func__
, mono_native_thread_id_get (), internal
));
879 SET_CURRENT_OBJECT (internal
);
881 domain
= mono_object_domain (thread
);
883 mono_thread_push_appdomain_ref (domain
);
884 if (!mono_domain_set_fast (domain
, force_domain
)) {
885 mono_thread_pop_appdomain_ref ();
889 mono_threads_lock ();
891 if (shutting_down
&& !force_attach
) {
892 mono_threads_unlock ();
893 mono_thread_pop_appdomain_ref ();
897 if (threads_starting_up
)
898 mono_g_hash_table_remove (threads_starting_up
, thread
);
901 threads
= mono_g_hash_table_new_type_internal (NULL
, NULL
, MONO_HASH_VALUE_GC
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Table");
904 /* We don't need to duplicate thread->handle, because it is
905 * only closed when the thread object is finalized by the GC. */
906 mono_g_hash_table_insert_internal (threads
, (gpointer
)(gsize
)(internal
->tid
), internal
);
908 /* We have to do this here because mono_thread_start_cb
909 * requires that root_domain_thread is set up. */
910 if (thread_static_info
.offset
|| thread_static_info
.idx
> 0) {
911 /* get the current allocated size */
912 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (thread_static_info
.idx
, thread_static_info
.offset
, 0);
913 mono_alloc_static_data (&internal
->static_data
, offset
, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
), TRUE
);
916 mono_threads_unlock ();
918 root_domain
= mono_get_root_domain ();
920 g_assert (!internal
->root_domain_thread
);
921 if (domain
!= root_domain
)
922 MONO_OBJECT_SETREF_INTERNAL (internal
, root_domain_thread
, create_thread_object (root_domain
, internal
));
924 MONO_OBJECT_SETREF_INTERNAL (internal
, root_domain_thread
, thread
);
926 if (domain
!= root_domain
)
927 set_current_thread_for_domain (root_domain
, internal
, internal
->root_domain_thread
);
929 set_current_thread_for_domain (domain
, internal
, thread
);
931 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT
" (handle %p)", __func__
, internal
->tid
, internal
->handle
));
936 mono_threads_lock ();
937 if (threads_starting_up
)
938 mono_g_hash_table_remove (threads_starting_up
, thread
);
939 mono_threads_unlock ();
941 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
942 g_error ("%s: failed to get gchandle, info %p", __func__
, info
);
944 mono_gchandle_free_internal (gchandle
);
946 mono_thread_info_unset_internal_thread_gchandle (info
);
948 SET_CURRENT_OBJECT(NULL
);
954 mono_thread_detach_internal (MonoInternalThread
*thread
)
956 MonoThreadInfo
*info
;
957 MonoInternalThread
*value
;
961 g_assert (mono_thread_internal_is_current (thread
));
963 g_assert (thread
!= NULL
);
964 SET_CURRENT_OBJECT (thread
);
966 info
= thread
->thread_info
;
969 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%" G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
971 MONO_PROFILER_RAISE (thread_stopping
, (thread
->tid
));
974 * Prevent race condition between thread shutdown and runtime shutdown.
975 * Including all runtime threads in the pending joinable count will make
976 * sure shutdown will wait for it to get onto the joinable thread list before
977 * critical resources have been cleanup (like GC memory). Threads getting onto
978 * the joinable thread list should just about to exit and not blocking a potential
979 * join call. Owner of threads attached to the runtime but not identified as runtime
980 * threads needs to make sure thread detach calls won't race with runtime shutdown.
982 threads_add_pending_joinable_runtime_thread (info
);
985 mono_w32mutex_abandon (thread
);
988 mono_gchandle_free_internal (thread
->abort_state_handle
);
989 thread
->abort_state_handle
= 0;
991 thread
->abort_exc
= NULL
;
992 thread
->current_appcontext
= NULL
;
994 LOCK_THREAD (thread
);
996 thread
->state
|= ThreadState_Stopped
;
997 thread
->state
&= ~ThreadState_Background
;
999 UNLOCK_THREAD (thread
);
1002 An interruption request has leaked to cleanup. Adjust the global counter.
1004 This can happen is the abort source thread finds the abortee (this) thread
1005 in unmanaged code. If this thread never trips back to managed code or check
1006 the local flag it will be left set and positively unbalance the global counter.
1008 Leaving the counter unbalanced will cause a performance degradation since all threads
1009 will now keep checking their local flags all the time.
1011 mono_thread_clear_interruption_requested (thread
);
1013 mono_threads_lock ();
1017 if (!mono_g_hash_table_lookup_extended (threads
, (gpointer
)thread
->tid
, NULL
, (gpointer
*) &value
)) {
1018 g_error ("%s: thread %p (tid: %p) should not have been removed yet from threads", __func__
, thread
, thread
->tid
);
1019 } else if (thread
!= value
) {
1020 /* We have to check whether the thread object for the tid is still the same in the table because the
1021 * thread might have been destroyed and the tid reused in the meantime, in which case the tid would be in
1022 * the table, but with another thread object. */
1023 g_error ("%s: thread %p (tid: %p) do not match with value %p (tid: %p)", __func__
, thread
, thread
->tid
, value
, value
->tid
);
1026 removed
= mono_g_hash_table_remove (threads
, (gpointer
)thread
->tid
);
1029 mono_threads_unlock ();
1031 /* Don't close the handle here, wait for the object finalizer
1032 * to do it. Otherwise, the following race condition applies:
1034 * 1) Thread exits (and mono_thread_detach_internal() closes the handle)
1036 * 2) Some other handle is reassigned the same slot
1038 * 3) Another thread tries to join the first thread, and
1039 * blocks waiting for the reassigned handle to be signalled
1040 * (which might never happen). This is possible, because the
1041 * thread calling Join() still has a reference to the first
1045 mono_release_type_locks (thread
);
1047 MONO_PROFILER_RAISE (thread_stopped
, (thread
->tid
));
1048 MONO_PROFILER_RAISE (gc_root_unregister
, ((const mono_byte
*)(info
->stack_start_limit
)));
1049 MONO_PROFILER_RAISE (gc_root_unregister
, ((const mono_byte
*)(info
->handle_stack
)));
1052 * This will signal async signal handlers that the thread has exited.
1053 * The profiler callback needs this to be set, so it cannot be done earlier.
1055 mono_domain_unset ();
1056 mono_memory_barrier ();
1058 mono_thread_pop_appdomain_ref ();
1060 mono_free_static_data (thread
->static_data
);
1061 thread
->static_data
= NULL
;
1062 ref_stack_destroy (thread
->appdomain_refs
);
1063 thread
->appdomain_refs
= NULL
;
1065 g_assert (thread
->suspended
);
1066 mono_os_event_destroy (thread
->suspended
);
1067 g_free (thread
->suspended
);
1068 thread
->suspended
= NULL
;
1070 if (mono_thread_cleanup_fn
)
1071 mono_thread_cleanup_fn (thread_get_tid (thread
));
1073 mono_memory_barrier ();
1075 if (mono_gc_is_moving ()) {
1076 MONO_GC_UNREGISTER_ROOT (thread
->thread_pinning_ref
);
1077 thread
->thread_pinning_ref
= NULL
;
1080 /* There is no more any guarantee that `thread` is alive */
1081 mono_memory_barrier ();
1083 SET_CURRENT_OBJECT (NULL
);
1084 mono_domain_unset ();
1086 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
1087 g_error ("%s: failed to get gchandle, info = %p", __func__
, info
);
1089 mono_gchandle_free_internal (gchandle
);
1091 mono_thread_info_unset_internal_thread_gchandle (info
);
1093 /* Possibly free synch_cs, if the finalizer for InternalThread already
1095 dec_longlived_thread_data (thread
->longlived
);
1097 MONO_PROFILER_RAISE (thread_exited
, (thread
->tid
));
1099 /* Don't need to close the handle to this thread, even though we took a
1100 * reference in mono_thread_attach (), because the GC will do it
1101 * when the Thread object is finalised.
1108 MonoObject
*start_delegate
;
1109 MonoObject
*start_delegate_arg
;
1110 MonoThreadStart start_func
;
1111 gpointer start_func_arg
;
1112 gboolean force_attach
;
1114 MonoCoopSem registered
;
1118 fire_attach_profiler_events (MonoNativeThreadId tid
)
1120 MONO_PROFILER_RAISE (thread_started
, ((uintptr_t) tid
));
1122 MonoThreadInfo
*info
= mono_thread_info_current ();
1124 MONO_PROFILER_RAISE (gc_root_register
, (
1125 (const mono_byte
*)(info
->stack_start_limit
),
1126 (char *) info
->stack_end
- (char *) info
->stack_start_limit
,
1127 MONO_ROOT_SOURCE_STACK
,
1131 // The handle stack is a pseudo-root similar to the finalizer queues.
1132 MONO_PROFILER_RAISE (gc_root_register
, (
1133 (const mono_byte
*)info
->handle_stack
,
1135 MONO_ROOT_SOURCE_HANDLE
,
1140 static guint32 WINAPI
1141 start_wrapper_internal (StartInfo
*start_info
, gsize
*stack_ptr
)
1144 MonoThreadStart start_func
;
1145 void *start_func_arg
;
1148 * We don't create a local to hold start_info->thread, so hopefully it won't get pinned during a
1152 MonoInternalThread
*internal
;
1153 MonoObject
*start_delegate
;
1154 MonoObject
*start_delegate_arg
;
1156 thread
= start_info
->thread
;
1157 internal
= thread
->internal_thread
;
1159 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Start wrapper", __func__
, mono_native_thread_id_get ()));
1161 if (!mono_thread_attach_internal (thread
, start_info
->force_attach
, FALSE
)) {
1162 start_info
->failed
= TRUE
;
1164 mono_coop_sem_post (&start_info
->registered
);
1166 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1167 mono_coop_sem_destroy (&start_info
->registered
);
1168 g_free (start_info
);
1174 mono_thread_internal_set_priority (internal
, (MonoThreadPriority
)internal
->priority
);
1176 tid
= internal
->tid
;
1178 start_delegate
= start_info
->start_delegate
;
1179 start_delegate_arg
= start_info
->start_delegate_arg
;
1180 start_func
= start_info
->start_func
;
1181 start_func_arg
= start_info
->start_func_arg
;
1183 /* This MUST be called before any managed code can be
1184 * executed, as it calls the callback function that (for the
1185 * jit) sets the lmf marker.
1188 if (mono_thread_start_cb
)
1189 mono_thread_start_cb (tid
, stack_ptr
, (gpointer
)start_func
);
1191 /* On 2.0 profile (and higher), set explicitly since state might have been
1193 if (internal
->apartment_state
== ThreadApartmentState_Unknown
)
1194 internal
->apartment_state
= ThreadApartmentState_MTA
;
1196 mono_thread_init_apartment_state ();
1198 /* Let the thread that called Start() know we're ready */
1199 mono_coop_sem_post (&start_info
->registered
);
1201 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1202 mono_coop_sem_destroy (&start_info
->registered
);
1203 g_free (start_info
);
1206 /* start_info is not valid anymore */
1210 * Call this after calling start_notify, since the profiler callback might want
1211 * to lock the thread, and the lock is held by thread_start () which waits for
1214 fire_attach_profiler_events ((MonoNativeThreadId
) tid
);
1216 /* if the name was set before starting, we didn't invoke the profiler callback */
1217 // This is a little racy, ok.
1219 if (internal
->name
.chars
) {
1221 LOCK_THREAD (internal
);
1223 if (internal
->name
.chars
) {
1224 MONO_PROFILER_RAISE (thread_name
, (internal
->tid
, internal
->name
.chars
));
1225 mono_native_thread_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
), internal
->name
.chars
);
1228 UNLOCK_THREAD (internal
);
1231 /* start_func is set only for unmanaged start functions */
1233 start_func (start_func_arg
);
1235 #ifdef ENABLE_NETCORE
1236 static MonoMethod
*cb
;
1238 /* Call a callback in the RuntimeThread class */
1239 g_assert (start_delegate
== NULL
);
1241 cb
= mono_class_get_method_from_name_checked (internal
->obj
.vtable
->klass
, "StartCallback", 0, 0, error
);
1243 mono_error_assert_ok (error
);
1245 mono_runtime_invoke_checked (cb
, internal
, NULL
, error
);
1249 g_assert (start_delegate
!= NULL
);
1251 /* we may want to handle the exception here. See comment below on unhandled exceptions */
1252 args
[0] = (gpointer
) start_delegate_arg
;
1253 mono_runtime_delegate_invoke_checked (start_delegate
, args
, error
);
1256 if (!is_ok (error
)) {
1257 MonoException
*ex
= mono_error_convert_to_exception (error
);
1259 g_assert (ex
!= NULL
);
1260 MonoClass
*klass
= mono_object_class (ex
);
1261 if ((mono_runtime_unhandled_exception_policy_get () != MONO_UNHANDLED_POLICY_LEGACY
) &&
1262 !is_threadabort_exception (klass
)) {
1263 mono_unhandled_exception_internal (&ex
->object
);
1264 mono_invoke_unhandled_exception_hook (&ex
->object
);
1265 g_assert_not_reached ();
1268 mono_error_cleanup (error
);
1272 /* If the thread calls ExitThread at all, this remaining code
1273 * will not be executed, but the main thread will eventually
1274 * call mono_thread_detach_internal() on this thread's behalf.
1277 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Start wrapper terminating", __func__
, mono_native_thread_id_get ()));
1279 /* Do any cleanup needed for apartment state. This
1280 * cannot be done in mono_thread_detach_internal since
1281 * mono_thread_detach_internal could be called for a
1282 * thread other than the current thread.
1283 * mono_thread_cleanup_apartment_state cleans up apartment
1284 * for the current thead */
1285 mono_thread_cleanup_apartment_state ();
1287 mono_thread_detach_internal (internal
);
1292 static mono_thread_start_return_t WINAPI
1293 start_wrapper (gpointer data
)
1295 StartInfo
*start_info
;
1296 MonoThreadInfo
*info
;
1299 start_info
= (StartInfo
*) data
;
1300 g_assert (start_info
);
1302 info
= mono_thread_info_attach ();
1303 info
->runtime_thread
= TRUE
;
1305 /* Run the actual main function of the thread */
1306 res
= start_wrapper_internal (start_info
, (gsize
*)info
->stack_end
);
1308 mono_thread_info_exit (res
);
1310 g_assert_not_reached ();
1316 * Common thread creation code.
1317 * LOCKING: Acquires the threads lock.
1320 create_thread (MonoThread
*thread
, MonoInternalThread
*internal
, MonoObject
*start_delegate
, MonoThreadStart start_func
, gpointer start_func_arg
,
1321 MonoThreadCreateFlags flags
, MonoError
*error
)
1323 StartInfo
*start_info
= NULL
;
1324 MonoNativeThreadId tid
;
1326 gsize stack_set_size
;
1329 g_assert (!start_func
&& !start_func_arg
);
1331 g_assert (!start_delegate
);
1333 if (flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
) {
1334 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
));
1335 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
));
1337 if (flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
) {
1338 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
));
1339 g_assert (!(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
));
1343 * Join joinable threads to prevent running out of threads since the finalizer
1344 * thread might be blocked/backlogged.
1346 mono_threads_join_threads ();
1350 mono_threads_lock ();
1351 if (shutting_down
&& !(flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
)) {
1352 mono_threads_unlock ();
1353 mono_error_set_execution_engine (error
, "Couldn't create thread. Runtime is shutting down.");
1356 if (threads_starting_up
== NULL
) {
1357 threads_starting_up
= mono_g_hash_table_new_type_internal (NULL
, NULL
, MONO_HASH_KEY_VALUE_GC
, MONO_ROOT_SOURCE_THREADING
, NULL
, "Thread Starting Table");
1359 mono_g_hash_table_insert_internal (threads_starting_up
, thread
, thread
);
1360 mono_threads_unlock ();
1362 internal
->threadpool_thread
= flags
& MONO_THREAD_CREATE_FLAGS_THREADPOOL
;
1363 if (internal
->threadpool_thread
)
1364 mono_thread_set_state (internal
, ThreadState_Background
);
1366 internal
->debugger_thread
= flags
& MONO_THREAD_CREATE_FLAGS_DEBUGGER
;
1368 start_info
= g_new0 (StartInfo
, 1);
1369 start_info
->ref
= 2;
1370 start_info
->thread
= thread
;
1371 start_info
->start_delegate
= start_delegate
;
1372 start_info
->start_delegate_arg
= thread
->start_obj
;
1373 start_info
->start_func
= start_func
;
1374 start_info
->start_func_arg
= start_func_arg
;
1375 start_info
->force_attach
= flags
& MONO_THREAD_CREATE_FLAGS_FORCE_CREATE
;
1376 start_info
->failed
= FALSE
;
1377 mono_coop_sem_init (&start_info
->registered
, 0);
1379 if (flags
!= MONO_THREAD_CREATE_FLAGS_SMALL_STACK
)
1380 stack_set_size
= default_stacksize_for_thread (internal
);
1384 if (!mono_thread_platform_create_thread (start_wrapper
, start_info
, &stack_set_size
, &tid
)) {
1385 /* The thread couldn't be created, so set an exception */
1386 mono_threads_lock ();
1387 mono_g_hash_table_remove (threads_starting_up
, thread
);
1388 mono_threads_unlock ();
1389 mono_error_set_execution_engine (error
, "Couldn't create thread. Error 0x%x", mono_w32error_get_last());
1390 /* ref is not going to be decremented in start_wrapper_internal */
1391 mono_atomic_dec_i32 (&start_info
->ref
);
1396 internal
->stack_size
= (int) stack_set_size
;
1398 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Launching thread %p (%" G_GSIZE_FORMAT
")", __func__
, mono_native_thread_id_get (), internal
, (gsize
)internal
->tid
));
1401 * Wait for the thread to set up its TLS data etc, so
1402 * theres no potential race condition if someone tries
1403 * to look up the data believing the thread has
1407 mono_coop_sem_wait (&start_info
->registered
, MONO_SEM_FLAGS_NONE
);
1409 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Done launching thread %p (%" G_GSIZE_FORMAT
")", __func__
, mono_native_thread_id_get (), internal
, (gsize
)internal
->tid
));
1411 ret
= !start_info
->failed
;
1414 if (mono_atomic_dec_i32 (&start_info
->ref
) == 0) {
1415 mono_coop_sem_destroy (&start_info
->registered
);
1416 g_free (start_info
);
1423 * mono_thread_new_init:
1426 mono_thread_new_init (intptr_t tid
, gpointer stack_start
, gpointer func
)
1428 if (mono_thread_start_cb
) {
1429 mono_thread_start_cb (tid
, stack_start
, func
);
1434 * mono_threads_set_default_stacksize:
1437 mono_threads_set_default_stacksize (guint32 stacksize
)
1439 default_stacksize
= stacksize
;
1443 * mono_threads_get_default_stacksize:
1446 mono_threads_get_default_stacksize (void)
1448 return default_stacksize
;
1452 * mono_thread_create_internal:
1454 * ARG should not be a GC reference.
1457 mono_thread_create_internal (MonoDomain
*domain
, gpointer func
, gpointer arg
, MonoThreadCreateFlags flags
, MonoError
*error
)
1460 MonoInternalThread
*internal
;
1465 internal
= create_internal_thread_object ();
1467 thread
= create_thread_object (domain
, internal
);
1469 LOCK_THREAD (internal
);
1471 res
= create_thread (thread
, internal
, NULL
, (MonoThreadStart
) func
, arg
, flags
, error
);
1474 UNLOCK_THREAD (internal
);
1476 return_val_if_nok (error
, NULL
);
1480 MonoInternalThreadHandle
1481 mono_thread_create_internal_handle (MonoDomain
*domain
, gpointer func
, gpointer arg
, MonoThreadCreateFlags flags
, MonoError
*error
)
1484 return MONO_HANDLE_NEW (MonoInternalThread
, mono_thread_create_internal (domain
, func
, arg
, flags
, error
));
1488 * mono_thread_create:
1491 mono_thread_create (MonoDomain
*domain
, gpointer func
, gpointer arg
)
1493 MONO_ENTER_GC_UNSAFE
;
1495 if (!mono_thread_create_checked (domain
, func
, arg
, error
))
1496 mono_error_cleanup (error
);
1497 MONO_EXIT_GC_UNSAFE
;
1501 mono_thread_create_checked (MonoDomain
*domain
, gpointer func
, gpointer arg
, MonoError
*error
)
1503 return (NULL
!= mono_thread_create_internal (domain
, func
, arg
, MONO_THREAD_CREATE_FLAGS_NONE
, error
));
1507 * mono_thread_attach:
1510 mono_thread_attach (MonoDomain
*domain
)
1512 MonoInternalThread
*internal
;
1514 MonoThreadInfo
*info
;
1515 MonoNativeThreadId tid
;
1517 if (mono_thread_internal_current_is_attached ()) {
1518 if (domain
!= mono_domain_get ())
1519 mono_domain_set_fast (domain
, TRUE
);
1520 /* Already attached */
1521 return mono_thread_current ();
1524 info
= mono_thread_info_attach ();
1527 tid
=mono_native_thread_id_get ();
1529 if (mono_runtime_get_no_exec ())
1532 internal
= create_internal_thread_object ();
1534 thread
= create_thread_object (domain
, internal
);
1536 if (!mono_thread_attach_internal (thread
, FALSE
, TRUE
)) {
1537 /* Mono is shutting down, so just wait for the end */
1539 mono_thread_info_sleep (10000, NULL
);
1542 THREAD_DEBUG (g_message ("%s: Attached thread ID %" G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, internal
->handle
));
1544 if (mono_thread_attach_cb
)
1545 mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid
), info
->stack_end
);
1547 fire_attach_profiler_events (tid
);
1553 * mono_thread_detach:
1556 mono_thread_detach (MonoThread
*thread
)
1559 mono_thread_detach_internal (thread
->internal_thread
);
1563 * mono_thread_detach_if_exiting:
1565 * Detach the current thread from the runtime if it is exiting, i.e. it is running pthread dtors.
1566 * This should be used at the end of embedding code which calls into managed code, and which
1567 * can be called from pthread dtors, like <code>dealloc:</code> implementations in Objective-C.
1570 mono_thread_detach_if_exiting (void)
1572 if (mono_thread_info_is_exiting ()) {
1573 MonoInternalThread
*thread
;
1575 thread
= mono_thread_internal_current ();
1577 // Switch to GC Unsafe thread state before detaching;
1578 // don't expect to undo this switch, hence unbalanced.
1580 (void) mono_threads_enter_gc_unsafe_region_unbalanced (&dummy
);
1582 mono_thread_detach_internal (thread
);
1583 mono_thread_info_detach ();
1591 mono_thread_internal_current_is_attached (void)
1593 MonoInternalThread
*internal
;
1595 internal
= GET_CURRENT_OBJECT ();
1606 mono_thread_exit (void)
1608 MonoInternalThread
*thread
= mono_thread_internal_current ();
1610 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%" G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
1612 mono_thread_detach_internal (thread
);
1614 /* we could add a callback here for embedders to use. */
1615 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
))
1616 exit (mono_environment_exitcode_get ());
1618 mono_thread_info_exit (0);
1622 mono_thread_construct_internal (MonoThreadObjectHandle this_obj_handle
)
1624 MonoInternalThread
* const internal
= create_internal_thread_object ();
1626 internal
->state
= ThreadState_Unstarted
;
1628 int const thread_gchandle
= mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject
, this_obj_handle
), TRUE
);
1630 MonoThreadObject
*this_obj
= MONO_HANDLE_RAW (this_obj_handle
);
1632 mono_atomic_cas_ptr ((volatile gpointer
*)&this_obj
->internal_thread
, internal
, NULL
);
1634 mono_gchandle_free_internal (thread_gchandle
);
1637 #ifndef ENABLE_NETCORE
1639 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThreadObjectHandle this_obj_handle
, MonoError
*error
)
1641 mono_thread_construct_internal (this_obj_handle
);
1645 MonoThreadObjectHandle
1646 ves_icall_System_Threading_Thread_GetCurrentThread (MonoError
*error
)
1648 return MONO_HANDLE_NEW (MonoThreadObject
, mono_thread_current ());
1651 static MonoInternalThread
*
1652 thread_handle_to_internal_ptr (MonoThreadObjectHandle thread_handle
)
1654 return MONO_HANDLE_GETVAL(thread_handle
, internal_thread
); // InternalThreads are always pinned.
1658 mono_error_set_exception_thread_state (MonoError
*error
, const char *exception_message
)
1660 mono_error_set_generic_error (error
, "System.Threading", "ThreadStateException", "%s", exception_message
);
1664 mono_error_set_exception_thread_not_started_or_dead (MonoError
*error
)
1666 mono_error_set_exception_thread_state (error
, "Thread has not been started, or is dead.");
1669 #ifndef ENABLE_NETCORE
1671 ves_icall_System_Threading_Thread_Thread_internal (MonoThreadObjectHandle thread_handle
, MonoObjectHandle start_handle
, MonoError
*error
)
1673 MonoInternalThread
*internal
;
1675 MonoThread
*this_obj
= MONO_HANDLE_RAW (thread_handle
);
1676 MonoObject
*start
= MONO_HANDLE_RAW (start_handle
);
1678 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__
, this_obj
, start
));
1680 internal
= thread_handle_to_internal_ptr (thread_handle
);
1683 mono_thread_construct_internal (thread_handle
);
1684 internal
= thread_handle_to_internal_ptr (thread_handle
);
1685 g_assert (internal
);
1688 LOCK_THREAD (internal
);
1690 if ((internal
->state
& ThreadState_Unstarted
) == 0) {
1691 UNLOCK_THREAD (internal
);
1692 mono_error_set_exception_thread_state (error
, "Thread has already been started.");
1696 if ((internal
->state
& ThreadState_Aborted
) != 0) {
1697 UNLOCK_THREAD (internal
);
1701 res
= create_thread (this_obj
, internal
, start
, NULL
, NULL
, MONO_THREAD_CREATE_FLAGS_NONE
, error
);
1703 UNLOCK_THREAD (internal
);
1707 internal
->state
&= ~ThreadState_Unstarted
;
1709 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, thread
));
1711 UNLOCK_THREAD (internal
);
1718 mono_thread_name_cleanup (MonoThreadName
* name
)
1720 MonoThreadName
const old_name
= *name
;
1721 // Do not reset generation.
1725 //memset (name, 0, sizeof (*name));
1727 g_free (old_name
.chars
);
1731 * This is called from the finalizer of the internal thread object.
1734 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThreadHandle this_obj_handle
, MonoError
*error
)
1736 MonoInternalThread
*this_obj
= mono_internal_thread_handle_ptr (this_obj_handle
);
1737 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__
, this_obj
, this_obj
->handle
));
1740 * Since threads keep a reference to their thread object while running, by
1741 * the time this function is called, the thread has already exited/detached,
1742 * i.e. mono_thread_detach_internal () has ran. The exception is during
1743 * shutdown, when mono_thread_detach_internal () can be called after this.
1745 if (this_obj
->handle
) {
1746 mono_threads_close_thread_handle (this_obj
->handle
);
1747 this_obj
->handle
= NULL
;
1750 mono_threads_close_native_thread_handle (MONO_GPOINTER_TO_NATIVE_THREAD_HANDLE (this_obj
->native_handle
));
1751 this_obj
->native_handle
= NULL
;
1753 /* Possibly free synch_cs, if the thread already detached also. */
1754 dec_longlived_thread_data (this_obj
->longlived
);
1756 mono_thread_name_cleanup (&this_obj
->name
);
1760 ves_icall_System_Threading_Thread_Sleep_internal (gint32 ms
, MonoError
*error
)
1762 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__
, ms
));
1764 if (mono_thread_current_check_pending_interrupt ())
1767 MonoInternalThread
* const thread
= mono_thread_internal_current ();
1769 HANDLE_LOOP_PREPARE
;
1772 gboolean alerted
= FALSE
;
1774 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1776 (void)mono_thread_info_sleep (ms
, &alerted
);
1778 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1785 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
1787 const gboolean interrupt
= mono_thread_execute_interruption (&exc
);
1790 mono_set_pending_exception_handle (exc
);
1796 if (ms
== MONO_INFINITE_WAIT
) // FIXME: !MONO_INFINITE_WAIT
1803 ves_icall_System_Threading_Thread_SpinWait_nop (MonoError
*error
)
1807 #ifndef ENABLE_NETCORE
1809 ves_icall_System_Threading_Thread_GetDomainID (MonoError
*error
)
1811 return mono_domain_get()->domain_id
;
1816 * mono_thread_get_name_utf8:
1817 * \returns the name of the thread in UTF-8.
1818 * Return NULL if the thread has no name.
1819 * The returned memory is owned by the caller (g_free it).
1822 mono_thread_get_name_utf8 (MonoThread
*thread
)
1827 MonoInternalThread
*internal
= thread
->internal_thread
;
1829 // This is a little racy, ok.
1831 if (internal
== NULL
|| !internal
->name
.chars
)
1834 LOCK_THREAD (internal
);
1836 char *tname
= (char*)g_memdup (internal
->name
.chars
, internal
->name
.length
+ 1);
1838 UNLOCK_THREAD (internal
);
1844 * mono_thread_get_managed_id:
1845 * \returns the \c Thread.ManagedThreadId value of \p thread.
1846 * Returns \c -1 if \p thread is NULL.
1849 mono_thread_get_managed_id (MonoThread
*thread
)
1854 MonoInternalThread
*internal
= thread
->internal_thread
;
1855 if (internal
== NULL
)
1858 int32_t id
= internal
->managed_id
;
1863 #ifndef ENABLE_NETCORE
1865 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThreadHandle thread_handle
, MonoError
*error
)
1867 // InternalThreads are always pinned, so shallowly coop-handleize.
1868 MonoInternalThread
* const this_obj
= mono_internal_thread_handle_ptr (thread_handle
);
1870 MonoStringHandle str
= NULL_HANDLE_STRING
;
1872 // This is a little racy, ok.
1874 if (this_obj
->name
.chars
) {
1875 LOCK_THREAD (this_obj
);
1877 if (this_obj
->name
.chars
)
1878 str
= mono_string_new_utf8_len (mono_domain_get (), this_obj
->name
.chars
, this_obj
->name
.length
, error
);
1880 UNLOCK_THREAD (this_obj
);
1888 // - MonoError is optional -- failure is usually not interesting, except the documented failure mode for managed callers.
1889 // - name16 only used on Windows.
1890 // - name8 is either constant, or g_free'able -- this function always takes ownership and never copies.
1893 mono_thread_set_name (MonoInternalThread
*this_obj
,
1894 const char* name8
, size_t name8_length
, const gunichar2
* name16
,
1895 MonoSetThreadNameFlags flags
, MonoError
*error
)
1897 MonoNativeThreadId tid
= 0;
1899 // A counter to optimize redundant sets.
1900 // It is not exactly thread safe but no use of it could be.
1901 gsize name_generation
;
1903 const gboolean constant
= !!(flags
& MonoSetThreadNameFlag_Constant
);
1905 #if HOST_WIN32 // On Windows, if name8 is supplied, then name16 must be also.
1906 g_assert (!name8
|| name16
);
1909 LOCK_THREAD (this_obj
);
1911 name_generation
= this_obj
->name
.generation
;
1913 if (flags
& MonoSetThreadNameFlag_Reset
) {
1914 this_obj
->flags
&= ~MONO_THREAD_FLAG_NAME_SET
;
1915 } else if (this_obj
->flags
& MONO_THREAD_FLAG_NAME_SET
) {
1916 UNLOCK_THREAD (this_obj
);
1919 mono_error_set_invalid_operation (error
, "%s", "Thread.Name can only be set once.");
1922 g_free ((char*)name8
);
1923 return name_generation
;
1926 name_generation
= ++this_obj
->name
.generation
;
1928 mono_thread_name_cleanup (&this_obj
->name
);
1931 this_obj
->name
.chars
= (char*)name8
;
1932 this_obj
->name
.length
= name8_length
;
1933 this_obj
->name
.free
= !constant
;
1934 if (flags
& MonoSetThreadNameFlag_Permanent
)
1935 this_obj
->flags
|= MONO_THREAD_FLAG_NAME_SET
;
1938 if (!(this_obj
->state
& ThreadState_Stopped
))
1939 tid
= thread_get_tid (this_obj
);
1941 UNLOCK_THREAD (this_obj
);
1944 MONO_PROFILER_RAISE (thread_name
, ((uintptr_t)tid
, name8
));
1945 mono_native_thread_set_name (tid
, name8
);
1948 mono_thread_set_name_windows (this_obj
->native_handle
, name16
);
1950 mono_free (0); // FIXME keep mono-publib.c in use and its functions exported
1952 return name_generation
;
1957 ves_icall_System_Threading_Thread_SetName_icall (MonoInternalThreadHandle thread_handle
, const gunichar2
* name16
, gint32 name16_length
, MonoError
* error
)
1959 long name8_length
= 0;
1961 char* name8
= name16
? g_utf16_to_utf8 (name16
, name16_length
, NULL
, &name8_length
, NULL
) : NULL
;
1963 mono_thread_set_name (mono_internal_thread_handle_ptr (thread_handle
),
1964 name8
, (gint32
)name8_length
, name16
, MonoSetThreadNameFlag_Permanent
, error
);
1967 #ifndef ENABLE_NETCORE
1969 * ves_icall_System_Threading_Thread_GetPriority_internal:
1970 * @param this_obj: The MonoInternalThread on which to operate.
1972 * Gets the priority of the given thread.
1973 * @return: The priority of the given thread.
1976 ves_icall_System_Threading_Thread_GetPriority (MonoThreadObjectHandle this_obj
, MonoError
*error
)
1980 MonoInternalThread
*internal
= thread_handle_to_internal_ptr (this_obj
);
1982 LOCK_THREAD (internal
);
1983 priority
= internal
->priority
;
1984 UNLOCK_THREAD (internal
);
1991 * ves_icall_System_Threading_Thread_SetPriority_internal:
1992 * @param this_obj: The MonoInternalThread on which to operate.
1993 * @param priority: The priority to set.
1995 * Sets the priority of the given thread.
1998 ves_icall_System_Threading_Thread_SetPriority (MonoThreadObjectHandle this_obj
, int priority
, MonoError
*error
)
2000 MonoInternalThread
*internal
= thread_handle_to_internal_ptr (this_obj
);
2002 LOCK_THREAD (internal
);
2003 internal
->priority
= priority
;
2004 if (internal
->thread_info
!= NULL
)
2005 mono_thread_internal_set_priority (internal
, (MonoThreadPriority
)priority
);
2006 UNLOCK_THREAD (internal
);
2009 /* If the array is already in the requested domain, we just return it,
2010 otherwise we return a copy in that domain. */
2011 static MonoArrayHandle
2012 byte_array_to_domain (MonoArrayHandle arr
, MonoDomain
*domain
, MonoError
*error
)
2014 HANDLE_FUNCTION_ENTER ()
2016 if (MONO_HANDLE_IS_NULL (arr
))
2017 return MONO_HANDLE_NEW (MonoArray
, NULL
);
2019 if (MONO_HANDLE_DOMAIN (arr
) == domain
)
2022 size_t const size
= mono_array_handle_length (arr
);
2024 // Capture arrays into common representation for repetitious code.
2025 // These two variables could also be an array of size 2 and
2026 // repitition implemented with a loop.
2028 MonoArrayHandle handle
;
2033 dest
= { mono_array_new_handle (domain
, mono_defaults
.byte_class
, size
, error
) };
2034 goto_if_nok (error
, exit
);
2037 source
.p
= mono_array_handle_pin_with_size (source
.handle
, size
, 0, &source
.gchandle
);
2038 dest
.p
= mono_array_handle_pin_with_size (dest
.handle
, size
, 0, &dest
.gchandle
);
2040 memmove (dest
.p
, source
.p
, size
);
2042 // Unpin both arrays.
2043 mono_gchandle_free_internal (source
.gchandle
);
2044 mono_gchandle_free_internal (dest
.gchandle
);
2046 HANDLE_FUNCTION_RETURN_REF (MonoArray
, dest
.handle
)
2049 #ifndef ENABLE_NETCORE
2051 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArrayHandle arr
, MonoError
*error
)
2053 return byte_array_to_domain (arr
, mono_get_root_domain (), error
);
2057 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArrayHandle arr
, MonoError
*error
)
2059 return byte_array_to_domain (arr
, mono_domain_get (), error
);
2064 * mono_thread_current:
2067 mono_thread_current (void)
2069 #ifdef ENABLE_NETCORE
2070 return mono_thread_internal_current ();
2072 MonoDomain
*domain
= mono_domain_get ();
2073 MonoInternalThread
*internal
= mono_thread_internal_current ();
2074 MonoThread
**current_thread_ptr
;
2076 g_assert (internal
);
2077 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
2079 if (!*current_thread_ptr
) {
2080 g_assert (domain
!= mono_get_root_domain ());
2081 *current_thread_ptr
= create_thread_object (domain
, internal
);
2083 return *current_thread_ptr
;
2087 static MonoThreadObjectHandle
2088 mono_thread_current_handle (void)
2090 return MONO_HANDLE_NEW (MonoThreadObject
, mono_thread_current ());
2093 /* Return the thread object belonging to INTERNAL in the current domain */
2095 mono_thread_current_for_thread (MonoInternalThread
*internal
)
2097 #ifdef ENABLE_NETCORE
2098 return mono_thread_internal_current ();
2100 MonoDomain
*domain
= mono_domain_get ();
2101 MonoThread
**current_thread_ptr
;
2103 g_assert (internal
);
2104 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
2106 if (!*current_thread_ptr
) {
2107 g_assert (domain
!= mono_get_root_domain ());
2108 *current_thread_ptr
= create_thread_object (domain
, internal
);
2110 return *current_thread_ptr
;
2115 mono_thread_internal_current (void)
2117 MonoInternalThread
*res
= GET_CURRENT_OBJECT ();
2118 THREAD_DEBUG (g_message ("%s: returning %p", __func__
, res
));
2122 MonoInternalThreadHandle
2123 mono_thread_internal_current_handle (void)
2125 return MONO_HANDLE_NEW (MonoInternalThread
, mono_thread_internal_current ());
2128 static MonoThreadInfoWaitRet
2129 mono_join_uninterrupted (MonoThreadHandle
* thread_to_join
, gint32 ms
, MonoError
*error
)
2131 MonoThreadInfoWaitRet ret
;
2134 const gint64 start
= (ms
== -1) ? 0 : mono_msec_ticks ();
2137 ret
= mono_thread_info_wait_one_handle (thread_to_join
, wait
, TRUE
);
2140 if (ret
!= MONO_THREAD_INFO_WAIT_RET_ALERTED
)
2143 MonoException
*exc
= mono_thread_execute_interruption_ptr ();
2145 mono_error_set_exception_instance (error
, exc
);
2152 /* Re-calculate ms according to the time passed */
2153 const gint32 diff_ms
= (gint32
)(mono_msec_ticks () - start
);
2154 if (diff_ms
>= ms
) {
2155 ret
= MONO_THREAD_INFO_WAIT_RET_TIMEOUT
;
2158 wait
= ms
- diff_ms
;
2165 ves_icall_System_Threading_Thread_Join_internal (MonoThreadObjectHandle thread_handle
, int ms
, MonoError
*error
)
2167 if (mono_thread_current_check_pending_interrupt ())
2170 // Internal threads are pinned so shallow coop/handle.
2171 MonoInternalThread
* const thread
= thread_handle_to_internal_ptr (thread_handle
);
2172 MonoThreadHandle
*handle
= thread
->handle
;
2173 MonoInternalThread
*cur_thread
= mono_thread_internal_current ();
2174 gboolean ret
= FALSE
;
2176 LOCK_THREAD (thread
);
2178 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
2179 UNLOCK_THREAD (thread
);
2181 mono_error_set_exception_thread_state (error
, "Thread has not been started.");
2185 UNLOCK_THREAD (thread
);
2188 ms
= MONO_INFINITE_WAIT
;
2189 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__
, handle
, ms
));
2191 mono_thread_set_state (cur_thread
, ThreadState_WaitSleepJoin
);
2193 ret
= mono_join_uninterrupted (handle
, ms
, error
);
2195 mono_thread_clr_state (cur_thread
, ThreadState_WaitSleepJoin
);
2197 if (ret
== MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
) {
2198 THREAD_DEBUG (g_message ("%s: join successful", __func__
));
2200 mono_error_assert_ok (error
);
2202 /* Wait for the thread to really exit */
2203 MonoNativeThreadId tid
= thread_get_tid (thread
);
2204 mono_thread_join ((gpointer
)(gsize
)tid
);
2209 THREAD_DEBUG (g_message ("%s: join failed", __func__
));
2214 #define MANAGED_WAIT_FAILED 0x7fffffff
2217 map_native_wait_result_to_managed (MonoW32HandleWaitRet val
, gsize numobjects
)
2219 if (val
>= MONO_W32HANDLE_WAIT_RET_SUCCESS_0
&& val
< MONO_W32HANDLE_WAIT_RET_SUCCESS_0
+ numobjects
) {
2220 return WAIT_OBJECT_0
+ (val
- MONO_W32HANDLE_WAIT_RET_SUCCESS_0
);
2221 } else if (val
>= MONO_W32HANDLE_WAIT_RET_ABANDONED_0
&& val
< MONO_W32HANDLE_WAIT_RET_ABANDONED_0
+ numobjects
) {
2222 return WAIT_ABANDONED_0
+ (val
- MONO_W32HANDLE_WAIT_RET_ABANDONED_0
);
2223 } else if (val
== MONO_W32HANDLE_WAIT_RET_ALERTED
) {
2224 return WAIT_IO_COMPLETION
;
2225 } else if (val
== MONO_W32HANDLE_WAIT_RET_TIMEOUT
) {
2226 return WAIT_TIMEOUT
;
2227 } else if (val
== MONO_W32HANDLE_WAIT_RET_TOO_MANY_POSTS
) {
2228 return WAIT_TOO_MANY_POSTS
;
2229 } else if (val
== MONO_W32HANDLE_WAIT_RET_NOT_OWNED_BY_CALLER
) {
2230 return WAIT_NOT_OWNED_BY_CALLER
;
2231 } else if (val
== MONO_W32HANDLE_WAIT_RET_FAILED
) {
2232 /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
2233 return MANAGED_WAIT_FAILED
;
2235 g_error ("%s: unknown val value %d", __func__
, val
);
2240 ves_icall_System_Threading_WaitHandle_Wait_internal (gpointer
*handles
, gint32 numhandles
, MonoBoolean waitall
, gint32 timeout
, MonoError
*error
)
2242 /* Do this WaitSleepJoin check before creating objects */
2243 if (mono_thread_current_check_pending_interrupt ())
2244 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED
, 0);
2246 MonoInternalThread
* const thread
= mono_thread_internal_current ();
2248 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
2253 timeout
= MONO_INFINITE_WAIT
;
2254 if (timeout
!= MONO_INFINITE_WAIT
)
2255 start
= mono_msec_ticks ();
2257 guint32 timeoutLeft
= timeout
;
2259 MonoW32HandleWaitRet ret
;
2261 HANDLE_LOOP_PREPARE
;
2265 /* mono_w32handle_wait_multiple optimizes the case for numhandles == 1 */
2266 ret
= mono_w32handle_wait_multiple (handles
, numhandles
, waitall
, timeoutLeft
, TRUE
, error
);
2268 if (ret
!= MONO_W32HANDLE_WAIT_RET_ALERTED
)
2273 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
2275 const gboolean interrupt
= mono_thread_execute_interruption (&exc
);
2278 mono_error_set_exception_handle (error
, exc
);
2285 if (timeout
!= MONO_INFINITE_WAIT
) {
2286 gint64
const elapsed
= mono_msec_ticks () - start
;
2287 if (elapsed
>= timeout
) {
2288 ret
= MONO_W32HANDLE_WAIT_RET_TIMEOUT
;
2292 timeoutLeft
= timeout
- elapsed
;
2296 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
2298 return map_native_wait_result_to_managed (ret
, numhandles
);
2301 #if HAVE_API_SUPPORT_WIN32_SIGNAL_OBJECT_AND_WAIT
2303 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (gpointer toSignal
, gpointer toWait
, gint32 ms
, MonoError
*error
)
2305 MonoW32HandleWaitRet ret
;
2306 MonoInternalThread
*thread
= mono_thread_internal_current ();
2309 ms
= MONO_INFINITE_WAIT
;
2311 if (mono_thread_current_check_pending_interrupt ())
2312 return map_native_wait_result_to_managed (MONO_W32HANDLE_WAIT_RET_FAILED
, 0);
2314 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
2316 ret
= mono_w32handle_signal_and_wait (toSignal
, toWait
, ms
, TRUE
);
2318 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
2320 return map_native_wait_result_to_managed (ret
, 1);
2325 gint32
ves_icall_System_Threading_Interlocked_Increment_Int (gint32
*location
)
2327 return mono_atomic_inc_i32 (location
);
2330 gint64
ves_icall_System_Threading_Interlocked_Increment_Long (gint64
*location
)
2332 #if SIZEOF_VOID_P == 4
2333 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2335 mono_interlocked_lock ();
2338 mono_interlocked_unlock ();
2342 return mono_atomic_inc_i64 (location
);
2345 gint32
ves_icall_System_Threading_Interlocked_Decrement_Int (gint32
*location
)
2347 return mono_atomic_dec_i32(location
);
2350 gint64
ves_icall_System_Threading_Interlocked_Decrement_Long (gint64
* location
)
2352 #if SIZEOF_VOID_P == 4
2353 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2355 mono_interlocked_lock ();
2358 mono_interlocked_unlock ();
2362 return mono_atomic_dec_i64 (location
);
2365 gint32
ves_icall_System_Threading_Interlocked_Exchange_Int (gint32
*location
, gint32 value
)
2367 return mono_atomic_xchg_i32(location
, value
);
2371 ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject
*volatile*location
, MonoObject
*volatile*value
, MonoObject
*volatile*res
)
2373 // Coop-equivalency here via pointers to pointers.
2374 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2376 // This also handles generic T case, T constrained to a class.
2378 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2379 // presently breaks identity of location and would therefore never work.
2381 *res
= (MonoObject
*)mono_atomic_xchg_ptr ((volatile gpointer
*)location
, *value
);
2382 mono_gc_wbarrier_generic_nostore_internal ((gpointer
)location
); // FIXME volatile
2385 gpointer
ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer
*location
, gpointer value
)
2387 return mono_atomic_xchg_ptr(location
, value
);
2390 gfloat
ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat
*location
, gfloat value
)
2392 IntFloatUnion val
, ret
;
2395 ret
.ival
= mono_atomic_xchg_i32((gint32
*) location
, val
.ival
);
2401 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64
*location
, gint64 value
)
2403 #if SIZEOF_VOID_P == 4
2404 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2406 mono_interlocked_lock ();
2409 mono_interlocked_unlock ();
2413 return mono_atomic_xchg_i64 (location
, value
);
2417 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble
*location
, gdouble value
)
2419 LongDoubleUnion val
, ret
;
2422 ret
.ival
= (gint64
)mono_atomic_xchg_i64((gint64
*) location
, val
.ival
);
2427 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32
*location
, gint32 value
, gint32 comparand
)
2429 return mono_atomic_cas_i32(location
, value
, comparand
);
2432 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int_Success(gint32
*location
, gint32 value
, gint32 comparand
, MonoBoolean
*success
)
2434 gint32 r
= mono_atomic_cas_i32(location
, value
, comparand
);
2435 *success
= r
== comparand
;
2440 ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject
*volatile*location
, MonoObject
*volatile*value
, MonoObject
*volatile*comparand
, MonoObject
*volatile* res
)
2442 // Coop-equivalency here via pointers to pointers.
2443 // value and comparand and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2445 // This also handles generic T case, T constrained to a class.
2447 // This is not entirely convincing due to lack of volatile in the caller, however coop also
2448 // presently breaks identity of location and would therefore never work.
2450 *res
= (MonoObject
*)mono_atomic_cas_ptr ((volatile gpointer
*)location
, *value
, *comparand
);
2451 mono_gc_wbarrier_generic_nostore_internal ((gpointer
)location
); // FIXME volatile
2455 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject
*volatile*location
, MonoObject
*volatile*value
, MonoObject
*volatile*comparand
, MonoObject
*volatile* res
)
2457 ves_icall_System_Threading_Interlocked_CompareExchange_Object (location
, value
, comparand
, res
);
2460 gpointer
ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer
*location
, gpointer value
, gpointer comparand
)
2462 return mono_atomic_cas_ptr(location
, value
, comparand
);
2465 gfloat
ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat
*location
, gfloat value
, gfloat comparand
)
2467 IntFloatUnion val
, ret
, cmp
;
2470 cmp
.fval
= comparand
;
2471 ret
.ival
= mono_atomic_cas_i32((gint32
*) location
, val
.ival
, cmp
.ival
);
2477 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble
*location
, gdouble value
, gdouble comparand
)
2479 #if SIZEOF_VOID_P == 8
2480 LongDoubleUnion val
, comp
, ret
;
2483 comp
.fval
= comparand
;
2484 ret
.ival
= (gint64
)mono_atomic_cas_ptr((gpointer
*) location
, (gpointer
)val
.ival
, (gpointer
)comp
.ival
);
2490 mono_interlocked_lock ();
2492 if (old
== comparand
)
2494 mono_interlocked_unlock ();
2501 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64
*location
, gint64 value
, gint64 comparand
)
2503 #if SIZEOF_VOID_P == 4
2504 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2506 mono_interlocked_lock ();
2508 if (old
== comparand
)
2510 mono_interlocked_unlock ();
2514 return mono_atomic_cas_i64 (location
, value
, comparand
);
2518 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject
*volatile*location
, MonoObject
*volatile*value
, MonoObject
*volatile*res
)
2520 // Coop-equivalency here via pointers to pointers.
2521 // value and res are to managed frames, location ought to be (or member or global) but it cannot be guaranteed.
2523 // This is not entirely convincing due to lack of volatile in the caller.
2525 MONO_CHECK_NULL (location
, );
2526 ves_icall_System_Threading_Interlocked_Exchange_Object (location
, value
, res
);
2530 ves_icall_System_Threading_Interlocked_Add_Int (gint32
*location
, gint32 value
)
2532 return mono_atomic_add_i32 (location
, value
);
2536 ves_icall_System_Threading_Interlocked_Add_Long (gint64
*location
, gint64 value
)
2538 #if SIZEOF_VOID_P == 4
2539 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2541 mono_interlocked_lock ();
2544 mono_interlocked_unlock ();
2548 return mono_atomic_add_i64 (location
, value
);
2552 ves_icall_System_Threading_Interlocked_Read_Long (gint64
*location
)
2554 #if SIZEOF_VOID_P == 4
2555 if (G_UNLIKELY ((size_t)location
& 0x7)) {
2557 mono_interlocked_lock ();
2559 mono_interlocked_unlock ();
2563 return mono_atomic_load_i64 (location
);
2567 ves_icall_System_Threading_Interlocked_MemoryBarrierProcessWide (void)
2569 mono_memory_barrier_process_wide ();
2573 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2575 mono_memory_barrier ();
2579 ves_icall_System_Threading_Thread_ClrState (MonoInternalThreadHandle this_obj
, guint32 state
, MonoError
*error
)
2581 // InternalThreads are always pinned, so shallowly coop-handleize.
2582 mono_thread_clr_state (mono_internal_thread_handle_ptr (this_obj
), (MonoThreadState
)state
);
2586 ves_icall_System_Threading_Thread_SetState (MonoInternalThreadHandle thread_handle
, guint32 state
, MonoError
*error
)
2588 // InternalThreads are always pinned, so shallowly coop-handleize.
2589 mono_thread_set_state (mono_internal_thread_handle_ptr (thread_handle
), (MonoThreadState
)state
);
2593 ves_icall_System_Threading_Thread_GetState (MonoInternalThreadHandle thread_handle
, MonoError
*error
)
2595 // InternalThreads are always pinned, so shallowly coop-handleize.
2596 MonoInternalThread
*this_obj
= mono_internal_thread_handle_ptr (thread_handle
);
2600 LOCK_THREAD (this_obj
);
2602 state
= this_obj
->state
;
2604 UNLOCK_THREAD (this_obj
);
2610 ves_icall_System_Threading_Thread_Interrupt_internal (MonoThreadObjectHandle thread_handle
, MonoError
*error
)
2612 // Internal threads are pinned so shallow coop/handle.
2613 MonoInternalThread
* const thread
= thread_handle_to_internal_ptr (thread_handle
);
2614 MonoInternalThread
* const current
= mono_thread_internal_current ();
2616 LOCK_THREAD (thread
);
2618 thread
->thread_interrupt_requested
= TRUE
;
2619 gboolean
const throw_
= current
!= thread
&& (thread
->state
& ThreadState_WaitSleepJoin
);
2621 UNLOCK_THREAD (thread
);
2624 async_abort_internal (thread
, FALSE
);
2628 * mono_thread_current_check_pending_interrupt:
2629 * Checks if there's a interruption request and set the pending exception if so.
2630 * \returns true if a pending exception was set
2633 mono_thread_current_check_pending_interrupt (void)
2635 MonoInternalThread
*thread
= mono_thread_internal_current ();
2636 gboolean throw_
= FALSE
;
2638 LOCK_THREAD (thread
);
2640 if (thread
->thread_interrupt_requested
) {
2642 thread
->thread_interrupt_requested
= FALSE
;
2645 UNLOCK_THREAD (thread
);
2649 mono_error_set_thread_interrupted (error
);
2650 mono_error_set_pending_exception (error
);
2656 request_thread_abort (MonoInternalThread
*thread
, MonoObjectHandle
*state
, gboolean appdomain_unload
)
2657 // state is a pointer to a handle in order to be optional,
2658 // and be passed unspecified from functions not using handles.
2659 // When raw pointers is gone, it need not be a pointer,
2660 // though this would still work efficiently.
2662 LOCK_THREAD (thread
);
2664 /* With self abort we always throw a new exception */
2665 if (thread
== mono_thread_internal_current ())
2666 thread
->abort_exc
= NULL
;
2668 if (thread
->state
& (ThreadState_AbortRequested
| ThreadState_Stopped
))
2670 UNLOCK_THREAD (thread
);
2674 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
2675 thread
->state
|= ThreadState_Aborted
;
2676 UNLOCK_THREAD (thread
);
2680 thread
->state
|= ThreadState_AbortRequested
;
2681 if (appdomain_unload
)
2682 thread
->flags
|= MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2684 thread
->flags
&= ~MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2686 mono_gchandle_free_internal (thread
->abort_state_handle
);
2687 thread
->abort_state_handle
= 0;
2690 if (state
&& !MONO_HANDLE_IS_NULL (*state
)) {
2691 thread
->abort_state_handle
= mono_gchandle_from_handle (*state
, FALSE
);
2692 g_assert (thread
->abort_state_handle
);
2695 thread
->abort_exc
= NULL
;
2697 THREAD_DEBUG (g_message ("%s: (%" G_GSIZE_FORMAT
") Abort requested for %p (%" G_GSIZE_FORMAT
")", __func__
, mono_native_thread_id_get (), thread
, (gsize
)thread
->tid
));
2699 /* During shutdown, we can't wait for other threads */
2701 /* Make sure the thread is awake */
2702 mono_thread_resume (thread
);
2704 UNLOCK_THREAD (thread
);
2708 #ifndef ENABLE_NETCORE
2710 ves_icall_System_Threading_Thread_Abort (MonoInternalThreadHandle thread_handle
, MonoObjectHandle state
, MonoError
*error
)
2712 // InternalThreads are always pinned, so shallowly coop-handleize.
2713 MonoInternalThread
* const thread
= mono_internal_thread_handle_ptr (thread_handle
);
2714 gboolean is_self
= thread
== mono_thread_internal_current ();
2716 /* For self aborts we always process the abort */
2717 if (!request_thread_abort (thread
, &state
, FALSE
) && !is_self
)
2721 self_abort_internal (error
);
2723 async_abort_internal (thread
, TRUE
);
2729 * mono_thread_internal_abort:
2730 * Request thread \p thread to be aborted.
2731 * \p thread MUST NOT be the current thread.
2734 mono_thread_internal_abort (MonoInternalThread
*thread
, gboolean appdomain_unload
)
2736 g_assert (thread
!= mono_thread_internal_current ());
2738 if (!request_thread_abort (thread
, NULL
, appdomain_unload
))
2740 async_abort_internal (thread
, TRUE
);
2743 #ifndef ENABLE_NETCORE
2745 ves_icall_System_Threading_Thread_ResetAbort (MonoThreadObjectHandle this_obj
, MonoError
*error
)
2747 MonoInternalThread
*thread
= mono_thread_internal_current ();
2748 gboolean was_aborting
, is_domain_abort
;
2750 LOCK_THREAD (thread
);
2751 was_aborting
= thread
->state
& ThreadState_AbortRequested
;
2752 is_domain_abort
= thread
->flags
& MONO_THREAD_FLAG_APPDOMAIN_ABORT
;
2754 if (was_aborting
&& !is_domain_abort
)
2755 thread
->state
&= ~ThreadState_AbortRequested
;
2756 UNLOCK_THREAD (thread
);
2758 if (!was_aborting
) {
2759 mono_error_set_exception_thread_state (error
, "Unable to reset abort because no abort was requested");
2761 } else if (is_domain_abort
) {
2762 /* Silently ignore abort resets in unloading appdomains */
2766 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2767 thread
->abort_exc
= NULL
;
2768 mono_gchandle_free_internal (thread
->abort_state_handle
);
2769 /* This is actually not necessary - the handle
2770 only counts if the exception is set */
2771 thread
->abort_state_handle
= 0;
2776 mono_thread_internal_reset_abort (MonoInternalThread
*thread
)
2778 LOCK_THREAD (thread
);
2780 thread
->state
&= ~ThreadState_AbortRequested
;
2782 if (thread
->abort_exc
) {
2783 mono_get_eh_callbacks ()->mono_clear_abort_threshold ();
2784 thread
->abort_exc
= NULL
;
2785 mono_gchandle_free_internal (thread
->abort_state_handle
);
2786 /* This is actually not necessary - the handle
2787 only counts if the exception is set */
2788 thread
->abort_state_handle
= 0;
2791 UNLOCK_THREAD (thread
);
2794 #ifndef ENABLE_NETCORE
2796 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThreadObjectHandle this_obj
, MonoError
*error
)
2798 MonoInternalThread
*thread
= thread_handle_to_internal_ptr (this_obj
);
2800 if (!thread
->abort_state_handle
)
2801 return NULL_HANDLE
; // No state. No error.
2803 // Convert gc handle to coop handle.
2804 MonoObjectHandle state
= mono_gchandle_get_target_handle (thread
->abort_state_handle
);
2805 g_assert (MONO_HANDLE_BOOL (state
));
2807 MonoDomain
*domain
= mono_domain_get ();
2808 if (MONO_HANDLE_DOMAIN (state
) == domain
)
2809 return state
; // No need to cross domain, return state directly.
2811 // Attempt move state cross-domain.
2812 MonoObjectHandle deserialized
= mono_object_xdomain_representation (state
, domain
, error
);
2814 // If deserialized is null, there must be an error, and vice versa.
2815 g_assert (is_ok (error
) == MONO_HANDLE_BOOL (deserialized
));
2817 if (MONO_HANDLE_BOOL (deserialized
))
2818 return deserialized
; // Cross-domain serialization succeeded. Return it.
2820 // Wrap error in InvalidOperationException.
2821 ERROR_DECL (error_creating_exception
);
2822 MonoExceptionHandle invalid_op_exc
= mono_exception_new_invalid_operation (
2823 "Thread.ExceptionState cannot access an ExceptionState from a different AppDomain", error_creating_exception
);
2824 mono_error_assert_ok (error_creating_exception
);
2825 g_assert (!is_ok (error
) && 1);
2826 MONO_HANDLE_SET (invalid_op_exc
, inner_ex
, mono_error_convert_to_exception_handle (error
));
2827 error_init_reuse (error
);
2828 mono_error_set_exception_handle (error
, invalid_op_exc
);
2829 g_assert (!is_ok (error
) && 2);
2831 // There is state, but we failed to return it.
2837 mono_thread_suspend (MonoInternalThread
*thread
)
2839 LOCK_THREAD (thread
);
2841 if (thread
->state
& (ThreadState_Unstarted
| ThreadState_Aborted
| ThreadState_Stopped
))
2843 UNLOCK_THREAD (thread
);
2847 if (thread
->state
& (ThreadState_Suspended
| ThreadState_SuspendRequested
| ThreadState_AbortRequested
))
2849 UNLOCK_THREAD (thread
);
2853 thread
->state
|= ThreadState_SuspendRequested
;
2855 mono_os_event_reset (thread
->suspended
);
2858 if (thread
== mono_thread_internal_current ()) {
2859 /* calls UNLOCK_THREAD (thread) */
2860 self_suspend_internal ();
2862 /* calls UNLOCK_THREAD (thread) */
2863 async_suspend_internal (thread
, FALSE
);
2869 #ifndef ENABLE_NETCORE
2871 ves_icall_System_Threading_Thread_Suspend (MonoThreadObjectHandle this_obj
, MonoError
*error
)
2873 if (!mono_thread_suspend (thread_handle_to_internal_ptr (this_obj
)))
2874 mono_error_set_exception_thread_not_started_or_dead (error
);
2879 /* LOCKING: LOCK_THREAD(thread) must be held */
2881 mono_thread_resume (MonoInternalThread
*thread
)
2883 if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
2884 // g_async_safe_printf ("RESUME (1) thread %p\n", thread_get_tid (thread));
2885 thread
->state
&= ~ThreadState_SuspendRequested
;
2887 mono_os_event_set (thread
->suspended
);
2892 if ((thread
->state
& ThreadState_Suspended
) == 0 ||
2893 (thread
->state
& ThreadState_Unstarted
) != 0 ||
2894 (thread
->state
& ThreadState_Aborted
) != 0 ||
2895 (thread
->state
& ThreadState_Stopped
) != 0)
2897 // g_async_safe_printf ("RESUME (2) thread %p\n", thread_get_tid (thread));
2901 // g_async_safe_printf ("RESUME (3) thread %p\n", thread_get_tid (thread));
2904 mono_os_event_set (thread
->suspended
);
2907 if (!thread
->self_suspended
) {
2908 UNLOCK_THREAD (thread
);
2910 /* Awake the thread */
2911 if (!mono_thread_info_resume (thread_get_tid (thread
)))
2914 LOCK_THREAD (thread
);
2917 thread
->state
&= ~ThreadState_Suspended
;
2922 #ifndef ENABLE_NETCORE
2924 ves_icall_System_Threading_Thread_Resume (MonoThreadObjectHandle thread_handle
, MonoError
*error
)
2926 // Internal threads are pinned so shallow coop/handle.
2927 MonoInternalThread
* const internal_thread
= thread_handle_to_internal_ptr (thread_handle
);
2928 gboolean exception
= FALSE
;
2930 if (!internal_thread
) {
2933 LOCK_THREAD (internal_thread
);
2934 if (!mono_thread_resume (internal_thread
))
2936 UNLOCK_THREAD (internal_thread
);
2940 mono_error_set_exception_thread_not_started_or_dead (error
);
2945 mono_threads_is_critical_method (MonoMethod
*method
)
2947 switch (method
->wrapper_type
) {
2948 case MONO_WRAPPER_RUNTIME_INVOKE
:
2949 case MONO_WRAPPER_XDOMAIN_INVOKE
:
2950 case MONO_WRAPPER_XDOMAIN_DISPATCH
:
2957 find_wrapper (MonoMethod
*m
, gint no
, gint ilo
, gboolean managed
, gpointer data
)
2962 if (mono_threads_is_critical_method (m
)) {
2963 *((gboolean
*)data
) = TRUE
;
2970 is_running_protected_wrapper (void)
2972 gboolean found
= FALSE
;
2973 mono_stack_walk (find_wrapper
, &found
);
2981 mono_thread_stop (MonoThread
*thread
)
2983 MonoInternalThread
*internal
= thread
->internal_thread
;
2985 if (!request_thread_abort (internal
, NULL
, FALSE
))
2988 if (internal
== mono_thread_internal_current ()) {
2990 self_abort_internal (error
);
2992 This function is part of the embeding API and has no way to return the exception
2993 to be thrown. So what we do is keep the old behavior and raise the exception.
2995 mono_error_raise_exception_deprecated (error
); /* OK to throw, see note */
2997 async_abort_internal (internal
, TRUE
);
3002 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr
)
3004 gint8 tmp
= *(volatile gint8
*)ptr
;
3005 mono_memory_barrier ();
3010 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr
)
3012 gint16 tmp
= *(volatile gint16
*)ptr
;
3013 mono_memory_barrier ();
3018 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr
)
3020 gint32 tmp
= *(volatile gint32
*)ptr
;
3021 mono_memory_barrier ();
3026 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr
)
3028 gint64 tmp
= *(volatile gint64
*)ptr
;
3029 mono_memory_barrier ();
3034 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr
)
3036 volatile void *tmp
= *(volatile void **)ptr
;
3037 mono_memory_barrier ();
3038 return (void *) tmp
;
3042 ves_icall_System_Threading_Thread_VolatileReadObject (void *ptr
)
3044 volatile MonoObject
*tmp
= *(volatile MonoObject
**)ptr
;
3045 mono_memory_barrier ();
3046 return (MonoObject
*) tmp
;
3050 ves_icall_System_Threading_Thread_VolatileReadDouble (void *ptr
)
3052 double tmp
= *(volatile double *)ptr
;
3053 mono_memory_barrier ();
3058 ves_icall_System_Threading_Thread_VolatileReadFloat (void *ptr
)
3060 float tmp
= *(volatile float *)ptr
;
3061 mono_memory_barrier ();
3066 ves_icall_System_Threading_Volatile_Read8 (void *ptr
)
3068 #if SIZEOF_VOID_P == 4
3069 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3071 mono_interlocked_lock ();
3072 val
= *(gint64
*)ptr
;
3073 mono_interlocked_unlock ();
3077 return mono_atomic_load_i64 ((volatile gint64
*)ptr
);
3081 ves_icall_System_Threading_Volatile_ReadU8 (void *ptr
)
3083 #if SIZEOF_VOID_P == 4
3084 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3086 mono_interlocked_lock ();
3087 val
= *(guint64
*)ptr
;
3088 mono_interlocked_unlock ();
3092 return (guint64
)mono_atomic_load_i64 ((volatile gint64
*)ptr
);
3096 ves_icall_System_Threading_Volatile_ReadDouble (void *ptr
)
3100 #if SIZEOF_VOID_P == 4
3101 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3103 mono_interlocked_lock ();
3104 val
= *(double*)ptr
;
3105 mono_interlocked_unlock ();
3110 u
.ival
= mono_atomic_load_i64 ((volatile gint64
*)ptr
);
3116 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr
, gint8 value
)
3118 mono_memory_barrier ();
3119 *(volatile gint8
*)ptr
= value
;
3123 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr
, gint16 value
)
3125 mono_memory_barrier ();
3126 *(volatile gint16
*)ptr
= value
;
3130 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr
, gint32 value
)
3132 mono_memory_barrier ();
3133 *(volatile gint32
*)ptr
= value
;
3137 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr
, gint64 value
)
3139 mono_memory_barrier ();
3140 *(volatile gint64
*)ptr
= value
;
3144 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr
, void *value
)
3146 mono_memory_barrier ();
3147 *(volatile void **)ptr
= value
;
3151 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr
, MonoObject
*value
)
3153 mono_memory_barrier ();
3154 mono_gc_wbarrier_generic_store_internal (ptr
, value
);
3158 ves_icall_System_Threading_Thread_VolatileWriteDouble (void *ptr
, double value
)
3160 mono_memory_barrier ();
3161 *(volatile double *)ptr
= value
;
3165 ves_icall_System_Threading_Thread_VolatileWriteFloat (void *ptr
, float value
)
3167 mono_memory_barrier ();
3168 *(volatile float *)ptr
= value
;
3172 ves_icall_System_Threading_Volatile_Write8 (void *ptr
, gint64 value
)
3174 #if SIZEOF_VOID_P == 4
3175 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3176 mono_interlocked_lock ();
3177 *(gint64
*)ptr
= value
;
3178 mono_interlocked_unlock ();
3183 mono_atomic_store_i64 ((volatile gint64
*)ptr
, value
);
3187 ves_icall_System_Threading_Volatile_WriteU8 (void *ptr
, guint64 value
)
3189 #if SIZEOF_VOID_P == 4
3190 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3191 mono_interlocked_lock ();
3192 *(guint64
*)ptr
= value
;
3193 mono_interlocked_unlock ();
3198 mono_atomic_store_i64 ((volatile gint64
*)ptr
, (gint64
)value
);
3202 ves_icall_System_Threading_Volatile_WriteDouble (void *ptr
, double value
)
3206 #if SIZEOF_VOID_P == 4
3207 if (G_UNLIKELY ((size_t)ptr
& 0x7)) {
3208 mono_interlocked_lock ();
3209 *(double*)ptr
= value
;
3210 mono_interlocked_unlock ();
3217 mono_atomic_store_i64 ((volatile gint64
*)ptr
, u
.ival
);
3221 free_context (void *user_data
)
3223 ContextStaticData
*data
= (ContextStaticData
*)user_data
;
3225 mono_threads_lock ();
3228 * There is no guarantee that, by the point this reference queue callback
3229 * has been invoked, the GC handle associated with the object will fail to
3230 * resolve as one might expect. So if we don't free and remove the GC
3231 * handle here, free_context_static_data_helper () could end up resolving
3232 * a GC handle to an actually-dead context which would contain a pointer
3233 * to an already-freed static data segment, resulting in a crash when
3236 g_hash_table_remove (contexts
, GUINT_TO_POINTER (data
->gc_handle
));
3238 mono_threads_unlock ();
3240 mono_gchandle_free_internal (data
->gc_handle
);
3241 mono_free_static_data (data
->static_data
);
3246 mono_threads_register_app_context (MonoAppContextHandle ctx
, MonoError
*error
)
3249 mono_threads_lock ();
3251 //g_print ("Registering context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3254 contexts
= g_hash_table_new (NULL
, NULL
);
3257 context_queue
= mono_gc_reference_queue_new_internal (free_context
);
3259 gpointer gch
= GUINT_TO_POINTER (mono_gchandle_new_weakref_from_handle (MONO_HANDLE_CAST (MonoObject
, ctx
)));
3260 g_hash_table_insert (contexts
, gch
, gch
);
3263 * We use this intermediate structure to contain a duplicate pointer to
3264 * the static data because we can't rely on being able to resolve the GC
3265 * handle in the reference queue callback.
3267 ContextStaticData
*data
= g_new0 (ContextStaticData
, 1);
3268 data
->gc_handle
= GPOINTER_TO_UINT (gch
);
3269 MONO_HANDLE_SETVAL (ctx
, data
, ContextStaticData
*, data
);
3271 context_adjust_static_data (ctx
);
3272 mono_gc_reference_queue_add_handle (context_queue
, ctx
, data
);
3274 mono_threads_unlock ();
3276 MONO_PROFILER_RAISE (context_loaded
, (MONO_HANDLE_RAW (ctx
)));
3279 #ifndef ENABLE_NETCORE
3281 ves_icall_System_Runtime_Remoting_Contexts_Context_RegisterContext (MonoAppContextHandle ctx
, MonoError
*error
)
3283 mono_threads_register_app_context (ctx
, error
);
3288 mono_threads_release_app_context (MonoAppContext
* ctx
, MonoError
*error
)
3291 * NOTE: Since finalizers are unreliable for the purposes of ensuring
3292 * cleanup in exceptional circumstances, we don't actually do any
3293 * cleanup work here. We instead do this via a reference queue.
3296 //g_print ("Releasing context %d in domain %d\n", ctx->context_id, ctx->domain_id);
3298 MONO_PROFILER_RAISE (context_unloaded
, (ctx
));
3301 #ifndef ENABLE_NETCORE
3303 ves_icall_System_Runtime_Remoting_Contexts_Context_ReleaseContext (MonoAppContextHandle ctx
, MonoError
*error
)
3305 mono_threads_release_app_context (MONO_HANDLE_RAW (ctx
), error
); /* FIXME use handles in mono_threads_release_app_context */
3309 void mono_thread_init (MonoThreadStartCB start_cb
,
3310 MonoThreadAttachCB attach_cb
)
3312 mono_coop_mutex_init_recursive (&threads_mutex
);
3314 #if SIZEOF_VOID_P == 4
3315 mono_os_mutex_init (&interlocked_mutex
);
3317 mono_coop_mutex_init_recursive(&joinable_threads_mutex
);
3319 mono_os_event_init (&background_change_event
, FALSE
);
3321 mono_coop_cond_init (&pending_native_thread_join_calls_event
);
3322 mono_coop_cond_init (&zero_pending_joinable_thread_event
);
3324 mono_init_static_data_info (&thread_static_info
);
3325 mono_init_static_data_info (&context_static_info
);
3327 mono_thread_start_cb
= start_cb
;
3328 mono_thread_attach_cb
= attach_cb
;
3333 thread_attach (MonoThreadInfo
*info
)
3335 return mono_gc_thread_attach (info
);
3339 thread_detach (MonoThreadInfo
*info
)
3341 MonoInternalThread
*internal
;
3344 /* If a delegate is passed to native code and invoked on a thread we dont
3345 * know about, marshal will register it with mono_threads_attach_coop, but
3346 * we have no way of knowing when that thread goes away. SGen has a TSD
3347 * so we assume that if the domain is still registered, we can detach
3351 g_assert (mono_thread_info_is_current (info
));
3353 if (!mono_thread_info_try_get_internal_thread_gchandle (info
, &gchandle
))
3356 internal
= (MonoInternalThread
*) mono_gchandle_get_target_internal (gchandle
);
3357 g_assert (internal
);
3359 mono_thread_detach_internal (internal
);
3363 thread_detach_with_lock (MonoThreadInfo
*info
)
3365 mono_gc_thread_detach_with_lock (info
);
3369 thread_in_critical_region (MonoThreadInfo
*info
)
3371 return mono_gc_thread_in_critical_region (info
);
3375 ip_in_critical_region (MonoDomain
*domain
, gpointer ip
)
3381 * We pass false for 'try_aot' so this becomes async safe.
3382 * It won't find aot methods whose jit info is not yet loaded,
3383 * so we preload their jit info in the JIT.
3385 ji
= mono_jit_info_table_find_internal (domain
, ip
, FALSE
, FALSE
);
3389 method
= mono_jit_info_get_method (ji
);
3392 return mono_gc_is_critical_method (method
);
3396 thread_flags_changing (MonoThreadInfoFlags old
, MonoThreadInfoFlags new_
)
3398 mono_gc_skip_thread_changing (!!(new_
& MONO_THREAD_INFO_FLAGS_NO_GC
));
3402 thread_flags_changed (MonoThreadInfoFlags old
, MonoThreadInfoFlags new_
)
3404 mono_gc_skip_thread_changed (!!(new_
& MONO_THREAD_INFO_FLAGS_NO_GC
));
3408 mono_thread_callbacks_init (void)
3410 MonoThreadInfoCallbacks cb
;
3412 memset (&cb
, 0, sizeof(cb
));
3413 cb
.thread_attach
= thread_attach
;
3414 cb
.thread_detach
= thread_detach
;
3415 cb
.thread_detach_with_lock
= thread_detach_with_lock
;
3416 cb
.ip_in_critical_region
= ip_in_critical_region
;
3417 cb
.thread_in_critical_region
= thread_in_critical_region
;
3418 cb
.thread_flags_changing
= thread_flags_changing
;
3419 cb
.thread_flags_changed
= thread_flags_changed
;
3420 mono_thread_info_callbacks_init (&cb
);
3424 * mono_thread_cleanup:
3427 mono_thread_cleanup (void)
3429 /* Wait for pending threads to park on joinable threads list */
3430 /* NOTE, waiting on this should be extremely rare and will only happen */
3431 /* under certain specific conditions. */
3432 gboolean wait_result
= threads_wait_pending_joinable_threads (2000);
3434 g_warning ("Waiting on threads to park on joinable thread list timed out.");
3436 mono_threads_join_threads ();
3438 #if !defined(HOST_WIN32)
3439 /* The main thread must abandon any held mutexes (particularly
3440 * important for named mutexes as they are shared across
3441 * processes, see bug 74680.) This will happen when the
3442 * thread exits, but if it's not running in a subthread it
3443 * won't exit in time.
3445 if (!mono_runtime_get_no_exec ())
3446 mono_w32mutex_abandon (mono_thread_internal_current ());
3450 /* This stuff needs more testing, it seems one of these
3451 * critical sections can be locked when mono_thread_cleanup is
3454 mono_coop_mutex_destroy (&threads_mutex
);
3455 mono_os_mutex_destroy (&interlocked_mutex
);
3456 mono_os_mutex_destroy (&delayed_free_table_mutex
);
3457 mono_os_mutex_destroy (&small_id_mutex
);
3458 mono_coop_cond_destroy (&zero_pending_joinable_thread_event
);
3459 mono_coop_cond_destroy (&pending_native_thread_join_calls_event
);
3460 mono_os_event_destroy (&background_change_event
);
3465 mono_threads_install_cleanup (MonoThreadCleanupFunc func
)
3467 mono_thread_cleanup_fn
= func
;
3471 * mono_thread_set_manage_callback:
3474 mono_thread_set_manage_callback (MonoThread
*thread
, MonoThreadManageCallback func
)
3476 thread
->internal_thread
->manage_callback
= func
;
3480 static void print_tids (gpointer key
, gpointer value
, gpointer user
)
3482 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
3483 * sizeof(uint) and a cast to uint would overflow
3485 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
3486 * print this as a pointer.
3488 g_message ("Waiting for: %p", key
);
3493 MonoThreadHandle
*handles
[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
];
3494 MonoInternalThread
*threads
[MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
];
3499 wait_for_tids (struct wait_data
*wait
, guint32 timeout
, gboolean check_state_change
)
3502 MonoThreadInfoWaitRet ret
;
3504 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
3506 /* Add the thread state change event, so it wakes
3507 * up if a thread changes to background mode. */
3510 if (check_state_change
)
3511 ret
= mono_thread_info_wait_multiple_handle (wait
->handles
, wait
->num
, &background_change_event
, FALSE
, timeout
, TRUE
);
3513 ret
= mono_thread_info_wait_multiple_handle (wait
->handles
, wait
->num
, NULL
, TRUE
, timeout
, TRUE
);
3516 if (ret
== MONO_THREAD_INFO_WAIT_RET_FAILED
) {
3517 /* See the comment in build_wait_tids() */
3518 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
3522 for( i
= 0; i
< wait
->num
; i
++)
3523 mono_threads_close_thread_handle (wait
->handles
[i
]);
3525 if (ret
>= MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
&& ret
< (MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
+ wait
->num
)) {
3526 MonoInternalThread
*internal
;
3528 internal
= wait
->threads
[ret
- MONO_THREAD_INFO_WAIT_RET_SUCCESS_0
];
3530 mono_threads_lock ();
3531 if (mono_g_hash_table_lookup (threads
, (gpointer
) internal
->tid
) == internal
)
3532 g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__
, internal
->tid
, internal
);
3533 mono_threads_unlock ();
3537 static void build_wait_tids (gpointer key
, gpointer value
, gpointer user
)
3539 struct wait_data
*wait
=(struct wait_data
*)user
;
3541 if(wait
->num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
- 1) {
3542 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
3544 /* Ignore background threads, we abort them later */
3545 /* Do not lock here since it is not needed and the caller holds threads_lock */
3546 if (thread
->state
& ThreadState_Background
) {
3547 THREAD_DEBUG (g_message ("%s: ignoring background thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3548 return; /* just leave, ignore */
3551 if (mono_gc_is_finalizer_internal_thread (thread
)) {
3552 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3556 if (thread
== mono_thread_internal_current ()) {
3557 THREAD_DEBUG (g_message ("%s: ignoring current thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3561 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
)) {
3562 THREAD_DEBUG (g_message ("%s: ignoring main thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3566 if (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
) {
3567 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT
"with DONT_MANAGE flag set.", __func__
, (gsize
)thread
->tid
));
3571 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__
, thread
));
3572 if ((thread
->manage_callback
== NULL
) || (thread
->manage_callback (thread
->root_domain_thread
) == TRUE
)) {
3573 wait
->handles
[wait
->num
]=mono_threads_open_thread_handle (thread
->handle
);
3574 wait
->threads
[wait
->num
]=thread
;
3577 THREAD_DEBUG (g_message ("%s: adding thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3579 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %" G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
3584 /* Just ignore the rest, we can't do anything with
3591 abort_threads (gpointer key
, gpointer value
, gpointer user
)
3593 struct wait_data
*wait
=(struct wait_data
*)user
;
3594 MonoNativeThreadId self
= mono_native_thread_id_get ();
3595 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3597 if (wait
->num
>= MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
)
3600 if (mono_native_thread_id_equals (thread_get_tid (thread
), self
))
3602 if (mono_gc_is_finalizer_internal_thread (thread
))
3605 if ((thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
))
3608 wait
->handles
[wait
->num
] = mono_threads_open_thread_handle (thread
->handle
);
3609 wait
->threads
[wait
->num
] = thread
;
3612 THREAD_DEBUG (g_print ("%s: Aborting id: %" G_GSIZE_FORMAT
"\n", __func__
, (gsize
)thread
->tid
));
3613 mono_thread_internal_abort (thread
, FALSE
);
3617 * mono_threads_set_shutting_down:
3619 * Is called by a thread that wants to shut down Mono. If the runtime is already
3620 * shutting down, the calling thread is suspended/stopped, and this function never
3624 mono_threads_set_shutting_down (void)
3626 MonoInternalThread
*current_thread
= mono_thread_internal_current ();
3628 mono_threads_lock ();
3630 if (shutting_down
) {
3631 mono_threads_unlock ();
3633 /* Make sure we're properly suspended/stopped */
3635 LOCK_THREAD (current_thread
);
3637 if (current_thread
->state
& (ThreadState_SuspendRequested
| ThreadState_AbortRequested
)) {
3638 UNLOCK_THREAD (current_thread
);
3639 mono_thread_execute_interruption_void ();
3641 UNLOCK_THREAD (current_thread
);
3644 /*since we're killing the thread, detach it.*/
3645 mono_thread_detach_internal (current_thread
);
3647 /* Wake up other threads potentially waiting for us */
3648 mono_thread_info_exit (0);
3650 shutting_down
= TRUE
;
3652 /* Not really a background state change, but this will
3653 * interrupt the main thread if it is waiting for all
3654 * the other threads.
3657 mono_os_event_set (&background_change_event
);
3660 mono_threads_unlock ();
3665 * mono_thread_manage:
3668 mono_thread_manage (void)
3670 struct wait_data wait_data
;
3671 struct wait_data
*wait
= &wait_data
;
3673 memset (wait
, 0, sizeof (struct wait_data
));
3674 /* join each thread that's still running */
3675 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__
));
3677 mono_threads_lock ();
3679 THREAD_DEBUG (g_message("%s: No threads", __func__
));
3680 mono_threads_unlock ();
3684 mono_threads_unlock ();
3687 mono_threads_lock ();
3688 if (shutting_down
) {
3689 /* somebody else is shutting down */
3690 mono_threads_unlock ();
3693 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__
, mono_g_hash_table_size (threads
));
3694 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
3697 mono_os_event_reset (&background_change_event
);
3700 /* We must zero all InternalThread pointers to avoid making the GC unhappy. */
3701 memset (wait
->threads
, 0, sizeof (wait
->threads
));
3702 mono_g_hash_table_foreach (threads
, build_wait_tids
, wait
);
3703 mono_threads_unlock ();
3705 /* Something to wait for */
3706 wait_for_tids (wait
, MONO_INFINITE_WAIT
, TRUE
);
3707 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__
, wait
->num
));
3708 } while(wait
->num
>0);
3710 /* Mono is shutting down, so just wait for the end */
3711 if (!mono_runtime_try_shutdown ()) {
3712 /*FIXME mono_thread_suspend probably should call mono_thread_execute_interruption when self interrupting. */
3713 mono_thread_suspend (mono_thread_internal_current ());
3714 mono_thread_execute_interruption_void ();
3717 #ifndef ENABLE_NETCORE
3719 * Under netcore, we don't abort any threads, just exit.
3720 * This is not a problem since we don't do runtime cleanup either.
3723 * Remove everything but the finalizer thread and self.
3724 * Also abort all the background threads
3727 mono_threads_lock ();
3730 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3731 memset (wait
->threads
, 0, sizeof (wait
->threads
));
3732 mono_g_hash_table_foreach (threads
, abort_threads
, wait
);
3734 mono_threads_unlock ();
3736 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__
, wait
->num
));
3737 if (wait
->num
> 0) {
3738 /* Something to wait for */
3739 wait_for_tids (wait
, MONO_INFINITE_WAIT
, FALSE
);
3741 } while (wait
->num
> 0);
3745 * give the subthreads a chance to really quit (this is mainly needed
3746 * to get correct user and system times from getrusage/wait/time(1)).
3747 * This could be removed if we avoid pthread_detach() and use pthread_join().
3749 mono_thread_info_yield ();
3752 #ifndef ENABLE_NETCORE
3754 collect_threads_for_suspend (gpointer key
, gpointer value
, gpointer user_data
)
3756 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3757 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3760 * We try to exclude threads early, to avoid running into the MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
3762 * This needs no locking.
3764 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3765 (thread
->state
& ThreadState_Stopped
) != 0)
3768 if (wait
->num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
) {
3769 wait
->handles
[wait
->num
] = mono_threads_open_thread_handle (thread
->handle
);
3770 wait
->threads
[wait
->num
] = thread
;
3776 * mono_thread_suspend_all_other_threads:
3778 * Suspend all managed threads except the finalizer thread and this thread. It is
3779 * not possible to resume them later.
3781 void mono_thread_suspend_all_other_threads (void)
3783 struct wait_data wait_data
;
3784 struct wait_data
*wait
= &wait_data
;
3786 MonoNativeThreadId self
= mono_native_thread_id_get ();
3787 guint32 eventidx
= 0;
3788 gboolean starting
, finished
;
3790 memset (wait
, 0, sizeof (struct wait_data
));
3792 * The other threads could be in an arbitrary state at this point, i.e.
3793 * they could be starting up, shutting down etc. This means that there could be
3794 * threads which are not even in the threads hash table yet.
3798 * First we set a barrier which will be checked by all threads before they
3799 * are added to the threads hash table, and they will exit if the flag is set.
3800 * This ensures that no threads could be added to the hash later.
3801 * We will use shutting_down as the barrier for now.
3803 g_assert (shutting_down
);
3806 * We make multiple calls to WaitForMultipleObjects since:
3807 * - we can only wait for MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS threads
3808 * - some threads could exit without becoming suspended
3813 * Make a copy of the hashtable since we can't do anything with
3814 * threads while threads_mutex is held.
3817 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3818 memset (wait
->threads
, 0, sizeof (wait
->threads
));
3819 mono_threads_lock ();
3820 mono_g_hash_table_foreach (threads
, collect_threads_for_suspend
, wait
);
3821 mono_threads_unlock ();
3824 /* Get the suspended events that we'll be waiting for */
3825 for (i
= 0; i
< wait
->num
; ++i
) {
3826 MonoInternalThread
*thread
= wait
->threads
[i
];
3828 if (mono_native_thread_id_equals (thread_get_tid (thread
), self
)
3829 || mono_gc_is_finalizer_internal_thread (thread
)
3830 || (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)
3832 mono_threads_close_thread_handle (wait
->handles
[i
]);
3833 wait
->threads
[i
] = NULL
;
3837 LOCK_THREAD (thread
);
3839 if (thread
->state
& (ThreadState_Suspended
| ThreadState_Stopped
)) {
3840 UNLOCK_THREAD (thread
);
3841 mono_threads_close_thread_handle (wait
->handles
[i
]);
3842 wait
->threads
[i
] = NULL
;
3848 /* Convert abort requests into suspend requests */
3849 if ((thread
->state
& ThreadState_AbortRequested
) != 0)
3850 thread
->state
&= ~ThreadState_AbortRequested
;
3852 thread
->state
|= ThreadState_SuspendRequested
;
3854 mono_os_event_reset (thread
->suspended
);
3857 /* Signal the thread to suspend + calls UNLOCK_THREAD (thread) */
3858 async_suspend_internal (thread
, TRUE
);
3860 mono_threads_close_thread_handle (wait
->handles
[i
]);
3861 wait
->threads
[i
] = NULL
;
3863 if (eventidx
<= 0) {
3865 * If there are threads which are starting up, we wait until they
3866 * are suspended when they try to register in the threads hash.
3867 * This is guaranteed to finish, since the threads which can create new
3868 * threads get suspended after a while.
3869 * FIXME: The finalizer thread can still create new threads.
3871 mono_threads_lock ();
3872 if (threads_starting_up
)
3873 starting
= mono_g_hash_table_size (threads_starting_up
) > 0;
3876 mono_threads_unlock ();
3878 mono_thread_info_sleep (100, NULL
);
3887 MonoInternalThread
*thread
;
3888 MonoStackFrameInfo
*frames
;
3889 int nframes
, max_frames
;
3890 int nthreads
, max_threads
;
3891 MonoInternalThread
**threads
;
3892 } ThreadDumpUserData
;
3894 static gboolean thread_dump_requested
;
3896 /* This needs to be async safe */
3898 collect_frame (MonoStackFrameInfo
*frame
, MonoContext
*ctx
, gpointer data
)
3900 ThreadDumpUserData
*ud
= (ThreadDumpUserData
*)data
;
3902 if (ud
->nframes
< ud
->max_frames
) {
3903 memcpy (&ud
->frames
[ud
->nframes
], frame
, sizeof (MonoStackFrameInfo
));
3910 /* This needs to be async safe */
3911 static SuspendThreadResult
3912 get_thread_dump (MonoThreadInfo
*info
, gpointer ud
)
3914 ThreadDumpUserData
*user_data
= (ThreadDumpUserData
*)ud
;
3915 MonoInternalThread
*thread
= user_data
->thread
;
3918 /* This no longer works with remote unwinding */
3919 g_string_append_printf (text
, " tid=0x%p this=0x%p ", (gpointer
)(gsize
)thread
->tid
, thread
);
3920 mono_thread_internal_describe (thread
, text
);
3921 g_string_append (text
, "\n");
3924 if (thread
== mono_thread_internal_current ())
3925 mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (collect_frame
, NULL
, MONO_UNWIND_SIGNAL_SAFE
, ud
);
3927 mono_get_eh_callbacks ()->mono_walk_stack_with_state (collect_frame
, mono_thread_info_get_suspend_state (info
), MONO_UNWIND_SIGNAL_SAFE
, ud
);
3929 return MonoResumeThread
;
3933 int nthreads
, max_threads
;
3936 } CollectThreadsUserData
;
3939 int nthreads
, max_threads
;
3940 MonoNativeThreadId
*threads
;
3941 } CollectThreadIdsUserData
;
3944 collect_thread (gpointer key
, gpointer value
, gpointer user
)
3946 CollectThreadsUserData
*ud
= (CollectThreadsUserData
*)user
;
3947 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3949 if (ud
->nthreads
< ud
->max_threads
)
3950 ud
->threads
[ud
->nthreads
++] = mono_gchandle_new_internal (&thread
->obj
, TRUE
);
3954 * Collect running threads into the THREADS array.
3955 * THREADS should be an array allocated on the stack.
3958 collect_threads (guint32
*thread_handles
, int max_threads
)
3960 CollectThreadsUserData ud
;
3962 mono_memory_barrier ();
3966 memset (&ud
, 0, sizeof (ud
));
3967 /* This array contains refs, but its on the stack, so its ok */
3968 ud
.threads
= thread_handles
;
3969 ud
.max_threads
= max_threads
;
3971 mono_threads_lock ();
3972 mono_g_hash_table_foreach (threads
, collect_thread
, &ud
);
3973 mono_threads_unlock ();
3979 mono_gstring_append_thread_name (GString
* text
, MonoInternalThread
* thread
)
3981 g_string_append (text
, "\n\"");
3982 char const * const name
= thread
->name
.chars
;
3983 g_string_append (text
, name
? name
:
3984 thread
->threadpool_thread
? "<threadpool thread>" :
3985 "<unnamed thread>");
3986 g_string_append (text
, "\"");
3990 dump_thread (MonoInternalThread
*thread
, ThreadDumpUserData
*ud
, FILE* output_file
)
3992 GString
* text
= g_string_new (0);
3995 ud
->thread
= thread
;
3998 /* Collect frames for the thread */
3999 if (thread
== mono_thread_internal_current ()) {
4000 get_thread_dump (mono_thread_info_current (), ud
);
4002 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, get_thread_dump
, ud
);
4006 * Do all the non async-safe work outside of get_thread_dump.
4008 mono_gstring_append_thread_name (text
, thread
);
4010 for (i
= 0; i
< ud
->nframes
; ++i
) {
4011 MonoStackFrameInfo
*frame
= &ud
->frames
[i
];
4012 MonoMethod
*method
= NULL
;
4014 if (frame
->type
== FRAME_TYPE_MANAGED
)
4015 method
= mono_jit_info_get_method (frame
->ji
);
4018 gchar
*location
= mono_debug_print_stack_frame (method
, frame
->native_offset
, frame
->domain
);
4019 g_string_append_printf (text
, " %s\n", location
);
4022 g_string_append_printf (text
, " at <unknown> <0x%05x>\n", frame
->native_offset
);
4026 g_fprintf (output_file
, "%s", text
->str
);
4028 #if PLATFORM_WIN32 && TARGET_WIN32 && _DEBUG
4029 OutputDebugStringA(text
->str
);
4032 g_string_free (text
, TRUE
);
4033 fflush (output_file
);
4037 mono_get_time_of_day (struct timeval
*tv
) {
4041 tv
->tv_sec
= time
.time
;
4042 tv
->tv_usec
= time
.millitm
* 1000;
4044 if (gettimeofday (tv
, NULL
) == -1) {
4045 g_error ("gettimeofday() failed; errno is %d (%s)", errno
, strerror (errno
));
4051 mono_local_time (const struct timeval
*tv
, struct tm
*tm
) {
4052 #ifdef HAVE_LOCALTIME_R
4053 localtime_r(&tv
->tv_sec
, tm
);
4055 time_t const tv_sec
= tv
->tv_sec
; // Copy due to Win32/Posix contradiction.
4056 *tm
= *localtime (&tv_sec
);
4061 mono_threads_perform_thread_dump (void)
4063 FILE* output_file
= NULL
;
4064 ThreadDumpUserData ud
;
4065 guint32 thread_array
[128];
4066 int tindex
, nthreads
;
4068 if (!thread_dump_requested
)
4071 if (thread_dump_dir
!= NULL
) {
4072 GString
* path
= g_string_new (0);
4077 mono_get_time_of_day (&tv
);
4078 mono_local_time(&tv
, &tod
);
4079 strftime(time_str
, sizeof(time_str
), MONO_STRFTIME_F
"_" MONO_STRFTIME_T
, &tod
);
4080 ms
= tv
.tv_usec
/ 1000;
4081 g_string_append_printf (path
, "%s/%s.%03ld.tdump", thread_dump_dir
, time_str
, ms
);
4082 output_file
= fopen (path
->str
, "w");
4083 g_string_free (path
, TRUE
);
4085 if (output_file
== NULL
) {
4086 g_print ("Full thread dump:\n");
4089 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4090 nthreads
= collect_threads (thread_array
, 128);
4092 memset (&ud
, 0, sizeof (ud
));
4093 ud
.frames
= g_new0 (MonoStackFrameInfo
, 256);
4094 ud
.max_frames
= 256;
4096 for (tindex
= 0; tindex
< nthreads
; ++tindex
) {
4097 guint32 handle
= thread_array
[tindex
];
4098 MonoInternalThread
*thread
= (MonoInternalThread
*) mono_gchandle_get_target_internal (handle
);
4099 dump_thread (thread
, &ud
, output_file
!= NULL
? output_file
: stdout
);
4100 mono_gchandle_free_internal (handle
);
4103 if (output_file
!= NULL
) {
4104 fclose (output_file
);
4108 thread_dump_requested
= FALSE
;
4111 #ifndef ENABLE_NETCORE
4112 /* Obtain the thread dump of all threads */
4114 ves_icall_System_Threading_Thread_GetStackTraces (MonoArrayHandleOut out_threads_handle
, MonoArrayHandleOut out_stack_frames_handle
, MonoError
*error
)
4116 MONO_HANDLE_ASSIGN_RAW (out_threads_handle
, NULL
);
4117 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle
, NULL
);
4121 MonoStackFrameHandle stack_frame_handle
= MONO_HANDLE_NEW (MonoStackFrame
, NULL
);
4122 MonoReflectionMethodHandle reflection_method_handle
= MONO_HANDLE_NEW (MonoReflectionMethod
, NULL
);
4123 MonoStringHandle filename_handle
= MONO_HANDLE_NEW (MonoString
, NULL
);
4124 MonoArrayHandle thread_frames_handle
= MONO_HANDLE_NEW (MonoArray
, NULL
);
4126 ThreadDumpUserData ud
;
4127 guint32 thread_array
[128];
4128 MonoDomain
*domain
= mono_domain_get ();
4129 MonoDebugSourceLocation
*location
;
4130 int tindex
, nthreads
;
4132 MonoArray
* out_threads
= NULL
;
4133 MonoArray
* out_stack_frames
= NULL
;
4135 MONO_HANDLE_ASSIGN_RAW (out_threads_handle
, NULL
);
4136 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle
, NULL
);
4138 /* Make a copy of the threads hash to avoid doing work inside threads_lock () */
4139 nthreads
= collect_threads (thread_array
, 128);
4141 memset (&ud
, 0, sizeof (ud
));
4142 ud
.frames
= g_new0 (MonoStackFrameInfo
, 256);
4143 ud
.max_frames
= 256;
4145 out_threads
= mono_array_new_checked (domain
, mono_defaults
.thread_class
, nthreads
, error
);
4146 goto_if_nok (error
, leave
);
4147 MONO_HANDLE_ASSIGN_RAW (out_threads_handle
, out_threads
);
4148 out_stack_frames
= mono_array_new_checked (domain
, mono_defaults
.array_class
, nthreads
, error
);
4149 goto_if_nok (error
, leave
);
4150 MONO_HANDLE_ASSIGN_RAW (out_stack_frames_handle
, out_stack_frames
);
4152 for (tindex
= 0; tindex
< nthreads
; ++tindex
) {
4154 mono_gchandle_free_internal (handle
);
4155 handle
= thread_array
[tindex
];
4156 MonoInternalThread
*thread
= (MonoInternalThread
*) mono_gchandle_get_target_internal (handle
);
4158 MonoArray
*thread_frames
;
4164 /* Collect frames for the thread */
4165 if (thread
== mono_thread_internal_current ()) {
4166 get_thread_dump (mono_thread_info_current (), &ud
);
4168 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, get_thread_dump
, &ud
);
4171 mono_array_setref_fast (out_threads
, tindex
, mono_thread_current_for_thread (thread
));
4173 thread_frames
= mono_array_new_checked (domain
, mono_defaults
.stack_frame_class
, ud
.nframes
, error
);
4174 MONO_HANDLE_ASSIGN_RAW (thread_frames_handle
, thread_frames
);
4175 goto_if_nok (error
, leave
);
4176 mono_array_setref_fast (out_stack_frames
, tindex
, thread_frames
);
4178 for (i
= 0; i
< ud
.nframes
; ++i
) {
4179 MonoStackFrameInfo
*frame
= &ud
.frames
[i
];
4180 MonoMethod
*method
= NULL
;
4181 MonoStackFrame
*sf
= (MonoStackFrame
*)mono_object_new_checked (domain
, mono_defaults
.stack_frame_class
, error
);
4182 MONO_HANDLE_ASSIGN_RAW (stack_frame_handle
, sf
);
4183 goto_if_nok (error
, leave
);
4185 sf
->native_offset
= frame
->native_offset
;
4187 if (frame
->type
== FRAME_TYPE_MANAGED
)
4188 method
= mono_jit_info_get_method (frame
->ji
);
4191 sf
->method_address
= (gsize
) frame
->ji
->code_start
;
4193 MonoReflectionMethod
*rm
= mono_method_get_object_checked (domain
, method
, NULL
, error
);
4194 MONO_HANDLE_ASSIGN_RAW (reflection_method_handle
, rm
);
4195 goto_if_nok (error
, leave
);
4196 MONO_OBJECT_SETREF_INTERNAL (sf
, method
, rm
);
4198 location
= mono_debug_lookup_source_location (method
, frame
->native_offset
, domain
);
4200 sf
->il_offset
= location
->il_offset
;
4202 if (location
->source_file
) {
4203 MonoString
*filename
= mono_string_new_checked (domain
, location
->source_file
, error
);
4204 MONO_HANDLE_ASSIGN_RAW (filename_handle
, filename
);
4205 goto_if_nok (error
, leave
);
4206 MONO_OBJECT_SETREF_INTERNAL (sf
, filename
, filename
);
4207 sf
->line
= location
->row
;
4208 sf
->column
= location
->column
;
4210 mono_debug_free_source_location (location
);
4215 mono_array_setref_internal (thread_frames
, i
, sf
);
4218 mono_gchandle_free_internal (handle
);
4223 mono_gchandle_free_internal (handle
);
4229 * mono_threads_request_thread_dump:
4231 * Ask all threads except the current to print their stacktrace to stdout.
4234 mono_threads_request_thread_dump (void)
4236 /*The new thread dump code runs out of the finalizer thread. */
4237 thread_dump_requested
= TRUE
;
4238 mono_gc_finalize_notify ();
4243 gint allocated
; /* +1 so that refs [allocated] == NULL */
4247 typedef struct ref_stack RefStack
;
4250 ref_stack_new (gint initial_size
)
4254 initial_size
= MAX (initial_size
, 16) + 1;
4255 rs
= g_new0 (RefStack
, 1);
4256 rs
->refs
= g_new0 (gpointer
, initial_size
);
4257 rs
->allocated
= initial_size
;
4262 ref_stack_destroy (gpointer ptr
)
4264 RefStack
*rs
= (RefStack
*)ptr
;
4273 ref_stack_push (RefStack
*rs
, gpointer ptr
)
4275 g_assert (rs
!= NULL
);
4277 if (rs
->bottom
>= rs
->allocated
) {
4278 rs
->refs
= (void **)g_realloc (rs
->refs
, rs
->allocated
* 2 * sizeof (gpointer
) + 1);
4279 rs
->allocated
<<= 1;
4280 rs
->refs
[rs
->allocated
] = NULL
;
4282 rs
->refs
[rs
->bottom
++] = ptr
;
4286 ref_stack_pop (RefStack
*rs
)
4288 if (rs
== NULL
|| rs
->bottom
== 0)
4292 rs
->refs
[rs
->bottom
] = NULL
;
4296 ref_stack_find (RefStack
*rs
, gpointer ptr
)
4303 for (refs
= rs
->refs
; refs
&& *refs
; refs
++) {
4311 * mono_thread_push_appdomain_ref:
4313 * Register that the current thread may have references to objects in domain
4314 * @domain on its stack. Each call to this function should be paired with a
4315 * call to pop_appdomain_ref.
4318 mono_thread_push_appdomain_ref (MonoDomain
*domain
)
4320 MonoInternalThread
*thread
= mono_thread_internal_current ();
4323 /* printf ("PUSH REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
4324 SPIN_LOCK (thread
->lock_thread_id
);
4325 if (thread
->appdomain_refs
== NULL
)
4326 thread
->appdomain_refs
= ref_stack_new (16);
4327 ref_stack_push ((RefStack
*)thread
->appdomain_refs
, domain
);
4328 SPIN_UNLOCK (thread
->lock_thread_id
);
4333 mono_thread_pop_appdomain_ref (void)
4335 MonoInternalThread
*thread
= mono_thread_internal_current ();
4338 /* printf ("POP REF: %" G_GSIZE_FORMAT " -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
4339 SPIN_LOCK (thread
->lock_thread_id
);
4340 ref_stack_pop ((RefStack
*)thread
->appdomain_refs
);
4341 SPIN_UNLOCK (thread
->lock_thread_id
);
4346 mono_thread_internal_has_appdomain_ref (MonoInternalThread
*thread
, MonoDomain
*domain
)
4349 SPIN_LOCK (thread
->lock_thread_id
);
4350 res
= ref_stack_find ((RefStack
*)thread
->appdomain_refs
, domain
);
4351 SPIN_UNLOCK (thread
->lock_thread_id
);
4356 mono_thread_has_appdomain_ref (MonoThread
*thread
, MonoDomain
*domain
)
4358 return mono_thread_internal_has_appdomain_ref (thread
->internal_thread
, domain
);
4361 typedef struct abort_appdomain_data
{
4362 struct wait_data wait
;
4364 } abort_appdomain_data
;
4367 collect_appdomain_thread (gpointer key
, gpointer value
, gpointer user_data
)
4369 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4370 abort_appdomain_data
*data
= (abort_appdomain_data
*)user_data
;
4371 MonoDomain
*domain
= data
->domain
;
4373 if (mono_thread_internal_has_appdomain_ref (thread
, domain
)) {
4374 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
4376 if(data
->wait
.num
<MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS
) {
4377 data
->wait
.handles
[data
->wait
.num
] = mono_threads_open_thread_handle (thread
->handle
);
4378 data
->wait
.threads
[data
->wait
.num
] = thread
;
4381 /* Just ignore the rest, we can't do anything with
4389 * mono_threads_abort_appdomain_threads:
4391 * Abort threads which has references to the given appdomain.
4394 mono_threads_abort_appdomain_threads (MonoDomain
*domain
, int timeout
)
4396 abort_appdomain_data user_data
;
4398 int orig_timeout
= timeout
;
4401 THREAD_DEBUG (g_message ("%s: starting abort", __func__
));
4403 start_time
= mono_msec_ticks ();
4405 mono_threads_lock ();
4407 user_data
.domain
= domain
;
4408 user_data
.wait
.num
= 0;
4409 /* This shouldn't take any locks */
4410 mono_g_hash_table_foreach (threads
, collect_appdomain_thread
, &user_data
);
4411 mono_threads_unlock ();
4413 if (user_data
.wait
.num
> 0) {
4414 /* Abort the threads outside the threads lock */
4415 for (i
= 0; i
< user_data
.wait
.num
; ++i
)
4416 mono_thread_internal_abort (user_data
.wait
.threads
[i
], TRUE
);
4419 * We should wait for the threads either to abort, or to leave the
4420 * domain. We can't do the latter, so we wait with a timeout.
4422 wait_for_tids (&user_data
.wait
, 100, FALSE
);
4425 /* Update remaining time */
4426 timeout
-= mono_msec_ticks () - start_time
;
4427 start_time
= mono_msec_ticks ();
4429 if (orig_timeout
!= -1 && timeout
< 0)
4432 while (user_data
.wait
.num
> 0);
4434 THREAD_DEBUG (g_message ("%s: abort done", __func__
));
4439 /* This is a JIT icall. This icall is called from a finally block when
4440 * mono_install_handler_block_guard called by another thread has flipped the
4441 * finally block's exvar (see mono_find_exvar_for_offset). In that case, if
4442 * the finally is in an abort protected block, we must defer the abort
4443 * exception until we leave the abort protected block. Otherwise we proceed
4444 * with a synchronous self-abort.
4447 ves_icall_thread_finish_async_abort (void)
4449 /* We were called from the handler block and are about to
4450 * leave it. (If we end up postponing the abort because we're
4451 * in an abort protected block, the unwinder won't run and
4452 * won't clear the handler block itself which will confuse the
4453 * unwinder if we're in a try {} catch {} and we throw again.
4455 * static Constructor () {
4459 * icall (); // Thread.Abort landed here,
4460 * // and caused the handler block to be installed
4462 * ves_icall_thread_finish_async_abort (); // we're here
4466 * // unwinder will get confused here and synthesize a self abort
4470 * More interestingly, this doesn't only happen with icalls - a JIT
4471 * trampoline is native code that will cause a handler to be installed.
4472 * So the above situation can happen with any code in a "finally"
4475 mono_get_eh_callbacks ()->mono_uninstall_current_handler_block_guard ();
4476 /* Just set the async interruption requested bit. Rely on the icall
4477 * wrapper of this icall to process the thread interruption, respecting
4478 * any abort protection blocks in our call stack.
4480 mono_thread_set_self_interruption_respect_abort_prot ();
4484 * mono_thread_get_undeniable_exception:
4486 * Return an exception which needs to be raised when leaving a catch clause.
4487 * This is used for undeniable exception propagation.
4490 mono_thread_get_undeniable_exception (void)
4492 MonoInternalThread
*thread
= mono_thread_internal_current ();
4494 if (!(thread
&& thread
->abort_exc
&& !is_running_protected_wrapper ()))
4497 // We don't want to have our exception effect calls made by
4498 // the catching block
4500 if (!mono_get_eh_callbacks ()->mono_above_abort_threshold ())
4504 * FIXME: Clear the abort exception and return an AppDomainUnloaded
4505 * exception if the thread no longer references a dying appdomain.
4507 thread
->abort_exc
->trace_ips
= NULL
;
4508 thread
->abort_exc
->stack_trace
= NULL
;
4509 return thread
->abort_exc
;
4512 #if MONO_SMALL_CONFIG
4513 #define NUM_STATIC_DATA_IDX 4
4514 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
4518 #define NUM_STATIC_DATA_IDX 8
4519 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
4520 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
4524 static MonoBitSet
*thread_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
4525 static MonoBitSet
*context_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
4528 mark_slots (void *addr
, MonoBitSet
**bitmaps
, MonoGCMarkFunc mark_func
, void *gc_data
)
4530 gpointer
*static_data
= (gpointer
*)addr
;
4532 for (int i
= 0; i
< NUM_STATIC_DATA_IDX
; ++i
) {
4533 void **ptr
= (void **)static_data
[i
];
4538 MONO_BITSET_FOREACH (bitmaps
[i
], idx
, {
4539 void **p
= ptr
+ idx
;
4542 mark_func ((MonoObject
**)p
, gc_data
);
4548 mark_tls_slots (void *addr
, MonoGCMarkFunc mark_func
, void *gc_data
)
4550 mark_slots (addr
, thread_reference_bitmaps
, mark_func
, gc_data
);
4554 mark_ctx_slots (void *addr
, MonoGCMarkFunc mark_func
, void *gc_data
)
4556 mark_slots (addr
, context_reference_bitmaps
, mark_func
, gc_data
);
4560 * mono_alloc_static_data
4562 * Allocate memory blocks for storing threads or context static data
4565 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, void *alloc_key
, gboolean threadlocal
)
4567 guint idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4570 gpointer
* static_data
= *static_data_ptr
;
4572 static MonoGCDescriptor tls_desc
= MONO_GC_DESCRIPTOR_NULL
;
4573 static MonoGCDescriptor ctx_desc
= MONO_GC_DESCRIPTOR_NULL
;
4575 if (mono_gc_user_markers_supported ()) {
4576 if (tls_desc
== MONO_GC_DESCRIPTOR_NULL
)
4577 tls_desc
= mono_gc_make_root_descr_user (mark_tls_slots
);
4579 if (ctx_desc
== MONO_GC_DESCRIPTOR_NULL
)
4580 ctx_desc
= mono_gc_make_root_descr_user (mark_ctx_slots
);
4583 static_data
= (void **)mono_gc_alloc_fixed (static_data_size
[0], threadlocal
? tls_desc
: ctx_desc
,
4584 threadlocal
? MONO_ROOT_SOURCE_THREAD_STATIC
: MONO_ROOT_SOURCE_CONTEXT_STATIC
,
4586 threadlocal
? "ThreadStatic Fields" : "ContextStatic Fields");
4587 *static_data_ptr
= static_data
;
4588 static_data
[0] = static_data
;
4591 for (i
= 1; i
<= idx
; ++i
) {
4592 if (static_data
[i
])
4595 if (mono_gc_user_markers_supported ())
4596 static_data
[i
] = g_malloc0 (static_data_size
[i
]);
4598 static_data
[i
] = mono_gc_alloc_fixed (static_data_size
[i
], MONO_GC_DESCRIPTOR_NULL
,
4599 threadlocal
? MONO_ROOT_SOURCE_THREAD_STATIC
: MONO_ROOT_SOURCE_CONTEXT_STATIC
,
4601 threadlocal
? "ThreadStatic Fields" : "ContextStatic Fields");
4606 mono_free_static_data (gpointer
* static_data
)
4609 for (i
= 1; i
< NUM_STATIC_DATA_IDX
; ++i
) {
4610 gpointer p
= static_data
[i
];
4614 * At this point, the static data pointer array is still registered with the
4615 * GC, so must ensure that mark_tls_slots() will not encounter any invalid
4616 * data. Freeing the individual arrays without first nulling their slots
4617 * would make it possible for mark_tls/ctx_slots() to encounter a pointer to
4618 * such an already freed array. See bug #13813.
4620 static_data
[i
] = NULL
;
4621 mono_memory_write_barrier ();
4622 if (mono_gc_user_markers_supported ())
4625 mono_gc_free_fixed (p
);
4627 mono_gc_free_fixed (static_data
);
4631 * mono_init_static_data_info
4633 * Initializes static data counters
4635 static void mono_init_static_data_info (StaticDataInfo
*static_data
)
4637 static_data
->idx
= 0;
4638 static_data
->offset
= 0;
4639 static_data
->freelist
= NULL
;
4643 * mono_alloc_static_data_slot
4645 * Generates an offset for static data. static_data contains the counters
4646 * used to generate it.
4649 mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
4651 if (!static_data
->idx
&& !static_data
->offset
) {
4653 * we use the first chunk of the first allocation also as
4654 * an array for the rest of the data
4656 static_data
->offset
= sizeof (gpointer
) * NUM_STATIC_DATA_IDX
;
4658 static_data
->offset
+= align
- 1;
4659 static_data
->offset
&= ~(align
- 1);
4660 if (static_data
->offset
+ size
>= static_data_size
[static_data
->idx
]) {
4661 static_data
->idx
++;
4662 g_assert (size
<= static_data_size
[static_data
->idx
]);
4663 g_assert (static_data
->idx
< NUM_STATIC_DATA_IDX
);
4664 static_data
->offset
= 0;
4666 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (static_data
->idx
, static_data
->offset
, 0);
4667 static_data
->offset
+= size
;
4672 * LOCKING: requires that threads_mutex is held
4675 context_adjust_static_data (MonoAppContextHandle ctx_handle
)
4677 MonoAppContext
*ctx
= MONO_HANDLE_RAW (ctx_handle
);
4678 if (context_static_info
.offset
|| context_static_info
.idx
> 0) {
4679 guint32 offset
= MAKE_SPECIAL_STATIC_OFFSET (context_static_info
.idx
, context_static_info
.offset
, 0);
4680 mono_alloc_static_data (&ctx
->static_data
, offset
, ctx
, FALSE
);
4681 ctx
->data
->static_data
= ctx
->static_data
;
4686 * LOCKING: requires that threads_mutex is held
4689 alloc_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4691 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4692 guint32 offset
= GPOINTER_TO_UINT (user
);
4694 mono_alloc_static_data (&(thread
->static_data
), offset
, (void *) MONO_UINT_TO_NATIVE_THREAD_ID (thread
->tid
), TRUE
);
4698 * LOCKING: requires that threads_mutex is held
4701 alloc_context_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4703 MonoAppContext
*ctx
= (MonoAppContext
*) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key
));
4708 guint32 offset
= GPOINTER_TO_UINT (user
);
4709 mono_alloc_static_data (&ctx
->static_data
, offset
, ctx
, FALSE
);
4710 ctx
->data
->static_data
= ctx
->static_data
;
4713 static StaticDataFreeList
*
4714 search_slot_in_freelist (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
4716 StaticDataFreeList
* prev
= NULL
;
4717 StaticDataFreeList
* tmp
= static_data
->freelist
;
4719 if (tmp
->size
== size
) {
4721 prev
->next
= tmp
->next
;
4723 static_data
->freelist
= tmp
->next
;
4732 #if SIZEOF_VOID_P == 4
4739 update_reference_bitmap (MonoBitSet
**sets
, guint32 offset
, uintptr_t *bitmap
, int numbits
)
4741 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4743 sets
[idx
] = mono_bitset_new (static_data_size
[idx
] / sizeof (uintptr_t), 0);
4744 MonoBitSet
*rb
= sets
[idx
];
4745 offset
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
4746 offset
/= sizeof (uintptr_t);
4747 /* offset is now the bitmap offset */
4748 for (int i
= 0; i
< numbits
; ++i
) {
4749 if (bitmap
[i
/ sizeof (uintptr_t)] & (ONE_P
<< (i
& (sizeof (uintptr_t) * 8 -1))))
4750 mono_bitset_set_fast (rb
, offset
+ i
);
4755 clear_reference_bitmap (MonoBitSet
**sets
, guint32 offset
, guint32 size
)
4757 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, index
);
4758 MonoBitSet
*rb
= sets
[idx
];
4759 offset
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, offset
);
4760 offset
/= sizeof (uintptr_t);
4761 /* offset is now the bitmap offset */
4762 for (int i
= 0; i
< size
/ sizeof (uintptr_t); i
++)
4763 mono_bitset_clear_fast (rb
, offset
+ i
);
4767 mono_alloc_special_static_data (guint32 static_type
, guint32 size
, guint32 align
, uintptr_t *bitmap
, int numbits
)
4769 g_assert (static_type
== SPECIAL_STATIC_THREAD
|| static_type
== SPECIAL_STATIC_CONTEXT
);
4771 StaticDataInfo
*info
;
4774 if (static_type
== SPECIAL_STATIC_THREAD
) {
4775 info
= &thread_static_info
;
4776 sets
= thread_reference_bitmaps
;
4778 info
= &context_static_info
;
4779 sets
= context_reference_bitmaps
;
4782 mono_threads_lock ();
4784 StaticDataFreeList
*item
= search_slot_in_freelist (info
, size
, align
);
4788 offset
= item
->offset
;
4791 offset
= mono_alloc_static_data_slot (info
, size
, align
);
4794 update_reference_bitmap (sets
, offset
, bitmap
, numbits
);
4796 if (static_type
== SPECIAL_STATIC_THREAD
) {
4797 /* This can be called during startup */
4798 if (threads
!= NULL
)
4799 mono_g_hash_table_foreach (threads
, alloc_thread_static_data_helper
, GUINT_TO_POINTER (offset
));
4801 if (contexts
!= NULL
)
4802 g_hash_table_foreach (contexts
, alloc_context_static_data_helper
, GUINT_TO_POINTER (offset
));
4804 ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
) = SPECIAL_STATIC_OFFSET_TYPE_CONTEXT
;
4807 mono_threads_unlock ();
4813 mono_get_special_static_data_for_thread (MonoInternalThread
*thread
, guint32 offset
)
4815 guint32 static_type
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
);
4817 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4818 return get_thread_static_data (thread
, offset
);
4820 return get_context_static_data (thread
->current_appcontext
, offset
);
4825 mono_get_special_static_data (guint32 offset
)
4827 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset
);
4836 * LOCKING: requires that threads_mutex is held
4839 free_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4841 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
4842 OffsetSize
*data
= (OffsetSize
*)user
;
4843 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, index
);
4844 int off
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, offset
);
4847 if (!thread
->static_data
|| !thread
->static_data
[idx
])
4849 ptr
= ((char*) thread
->static_data
[idx
]) + off
;
4850 mono_gc_bzero_atomic (ptr
, data
->size
);
4854 * LOCKING: requires that threads_mutex is held
4857 free_context_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
4859 MonoAppContext
*ctx
= (MonoAppContext
*) mono_gchandle_get_target_internal (GPOINTER_TO_INT (key
));
4864 OffsetSize
*data
= (OffsetSize
*)user
;
4865 int idx
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, index
);
4866 int off
= ACCESS_SPECIAL_STATIC_OFFSET (data
->offset
, offset
);
4869 if (!ctx
->static_data
|| !ctx
->static_data
[idx
])
4872 ptr
= ((char*) ctx
->static_data
[idx
]) + off
;
4873 mono_gc_bzero_atomic (ptr
, data
->size
);
4877 do_free_special_slot (guint32 offset
, guint32 size
)
4879 guint32 static_type
= ACCESS_SPECIAL_STATIC_OFFSET (offset
, type
);
4881 StaticDataInfo
*info
;
4883 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4884 info
= &thread_static_info
;
4885 sets
= thread_reference_bitmaps
;
4887 info
= &context_static_info
;
4888 sets
= context_reference_bitmaps
;
4891 guint32 data_offset
= offset
;
4892 ACCESS_SPECIAL_STATIC_OFFSET (data_offset
, type
) = 0;
4893 OffsetSize data
= { data_offset
, size
};
4895 clear_reference_bitmap (sets
, data
.offset
, data
.size
);
4897 if (static_type
== SPECIAL_STATIC_OFFSET_TYPE_THREAD
) {
4898 if (threads
!= NULL
)
4899 mono_g_hash_table_foreach (threads
, free_thread_static_data_helper
, &data
);
4901 if (contexts
!= NULL
)
4902 g_hash_table_foreach (contexts
, free_context_static_data_helper
, &data
);
4905 if (!mono_runtime_is_shutting_down ()) {
4906 StaticDataFreeList
*item
= g_new0 (StaticDataFreeList
, 1);
4908 item
->offset
= offset
;
4911 item
->next
= info
->freelist
;
4912 info
->freelist
= item
;
4917 do_free_special (gpointer key
, gpointer value
, gpointer data
)
4919 MonoClassField
*field
= (MonoClassField
*)key
;
4920 guint32 offset
= GPOINTER_TO_UINT (value
);
4923 size
= mono_type_size (field
->type
, &align
);
4924 do_free_special_slot (offset
, size
);
4928 mono_alloc_special_static_data_free (GHashTable
*special_static_fields
)
4930 mono_threads_lock ();
4932 g_hash_table_foreach (special_static_fields
, do_free_special
, NULL
);
4934 mono_threads_unlock ();
4939 flush_thread_interrupt_queue (void)
4941 /* Consume pending APC calls for current thread.*/
4942 /* Since this function get's called from interrupt handler it must use a direct */
4943 /* Win32 API call and can't go through mono_coop_win32_wait_for_single_object_ex */
4944 /* or it will detect a pending interrupt and not entering the wait call needed */
4945 /* to consume pending APC's.*/
4947 WaitForSingleObjectEx (GetCurrentThread (), 0, TRUE
);
4952 flush_thread_interrupt_queue (void)
4958 * mono_thread_execute_interruption
4960 * Performs the operation that the requested thread state requires (abort,
4964 mono_thread_execute_interruption (MonoExceptionHandle
*pexc
)
4966 gboolean fexc
= FALSE
;
4968 // Optimize away frame if caller supplied one.
4970 HANDLE_FUNCTION_ENTER ();
4971 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
4972 fexc
= mono_thread_execute_interruption (&exc
);
4973 HANDLE_FUNCTION_RETURN_VAL (fexc
);
4976 MONO_REQ_GC_UNSAFE_MODE
;
4978 MonoInternalThreadHandle thread
= mono_thread_internal_current_handle ();
4979 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
4981 lock_thread_handle (thread
);
4982 gboolean unlock
= TRUE
;
4984 /* MonoThread::interruption_requested can only be changed with atomics */
4985 if (!mono_thread_clear_interruption_requested_handle (thread
))
4988 MonoThreadObjectHandle sys_thread
;
4989 sys_thread
= mono_thread_current_handle ();
4991 flush_thread_interrupt_queue ();
4993 /* Clear the interrupted flag of the thread so it can wait again */
4994 mono_thread_info_clear_self_interrupt ();
4996 /* If there's a pending exception and an AbortRequested, the pending exception takes precedence */
4997 MONO_HANDLE_GET (exc
, sys_thread
, pending_exception
);
4998 if (!MONO_HANDLE_IS_NULL (exc
)) {
4999 // sys_thread->pending_exception = NULL;
5000 MONO_HANDLE_SETRAW (sys_thread
, pending_exception
, NULL
);
5003 } else if (MONO_HANDLE_GETVAL (thread
, state
) & ThreadState_AbortRequested
) {
5004 // Does the thread already have an abort exception?
5005 // If not, create a new one and set it on demand.
5006 // exc = thread->abort_exc;
5007 MONO_HANDLE_GET (exc
, thread
, abort_exc
);
5008 if (MONO_HANDLE_IS_NULL (exc
)) {
5010 exc
= mono_exception_new_thread_abort (error
);
5011 mono_error_assert_ok (error
); // FIXME
5012 // thread->abort_exc = exc;
5013 MONO_HANDLE_SET (thread
, abort_exc
, exc
);
5016 } else if (MONO_HANDLE_GETVAL (thread
, state
) & ThreadState_SuspendRequested
) {
5017 /* calls UNLOCK_THREAD (thread) */
5018 self_suspend_internal ();
5020 } else if (MONO_HANDLE_GETVAL (thread
, thread_interrupt_requested
)) {
5021 // thread->thread_interrupt_requested = FALSE
5022 MONO_HANDLE_SETVAL (thread
, thread_interrupt_requested
, MonoBoolean
, FALSE
);
5023 unlock_thread_handle (thread
);
5026 exc
= mono_exception_new_thread_interrupted (error
);
5027 mono_error_assert_ok (error
); // FIXME
5032 unlock_thread_handle (thread
);
5035 MONO_HANDLE_ASSIGN (*pexc
, exc
);
5041 mono_thread_execute_interruption_void (void)
5043 (void)mono_thread_execute_interruption (NULL
);
5046 static MonoException
*
5047 mono_thread_execute_interruption_ptr (void)
5049 HANDLE_FUNCTION_ENTER ();
5050 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
5051 MonoException
* const exc_raw
= mono_thread_execute_interruption (&exc
) ? MONO_HANDLE_RAW (exc
) : NULL
;
5052 HANDLE_FUNCTION_RETURN_VAL (exc_raw
);
5056 * mono_thread_request_interruption_internal
5058 * A signal handler can call this method to request the interruption of a
5059 * thread. The result of the interruption will depend on the current state of
5060 * the thread. If the result is an exception that needs to be thrown, it is
5061 * provided as return value.
5064 mono_thread_request_interruption_internal (gboolean running_managed
, MonoExceptionHandle
*pexc
)
5066 MonoInternalThread
*thread
= mono_thread_internal_current ();
5068 /* The thread may already be stopping */
5072 if (!mono_thread_set_interruption_requested (thread
))
5075 if (!running_managed
|| is_running_protected_wrapper ()) {
5076 /* Can't stop while in unmanaged code. Increase the global interruption
5077 request count. When exiting the unmanaged method the count will be
5078 checked and the thread will be interrupted. */
5080 /* this will awake the thread if it is in WaitForSingleObject
5083 mono_win32_interrupt_wait (thread
->thread_info
, thread
->native_handle
, (DWORD
)thread
->tid
);
5085 mono_thread_info_self_interrupt ();
5089 return mono_thread_execute_interruption (pexc
);
5093 mono_thread_request_interruption_native (void)
5095 (void)mono_thread_request_interruption_internal (FALSE
, NULL
);
5099 mono_thread_request_interruption_managed (MonoExceptionHandle
*exc
)
5101 return mono_thread_request_interruption_internal (TRUE
, exc
);
5104 /*This function should be called by a thread after it has exited all of
5105 * its handle blocks at interruption time.*/
5107 mono_thread_resume_interruption (gboolean exec
)
5109 MonoInternalThread
*thread
= mono_thread_internal_current ();
5110 gboolean still_aborting
;
5112 /* The thread may already be stopping */
5116 LOCK_THREAD (thread
);
5117 still_aborting
= (thread
->state
& (ThreadState_AbortRequested
)) != 0;
5118 UNLOCK_THREAD (thread
);
5120 /*This can happen if the protected block called Thread::ResetAbort*/
5121 if (!still_aborting
)
5124 if (!mono_thread_set_interruption_requested (thread
))
5127 mono_thread_info_self_interrupt ();
5129 if (exec
) // Ignore the exception here, it will be raised later.
5130 mono_thread_execute_interruption_void ();
5134 mono_thread_interruption_requested (void)
5136 if (mono_thread_interruption_request_flag
) {
5137 MonoInternalThread
*thread
= mono_thread_internal_current ();
5138 /* The thread may already be stopping */
5140 return mono_thread_get_interruption_requested (thread
);
5145 static MonoException
*
5146 mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection
)
5148 MonoInternalThread
*thread
= mono_thread_internal_current ();
5150 /* The thread may already be stopping */
5153 if (!mono_thread_get_interruption_requested (thread
))
5155 if (!bypass_abort_protection
&& !mono_thread_current ()->pending_exception
&& is_running_protected_wrapper ())
5158 return mono_thread_execute_interruption_ptr ();
5162 * Performs the interruption of the current thread, if one has been requested,
5163 * and the thread is not running a protected wrapper.
5164 * Return the exception which needs to be thrown, if any.
5167 mono_thread_interruption_checkpoint (void)
5169 return mono_thread_interruption_checkpoint_request (FALSE
);
5173 mono_thread_interruption_checkpoint_bool (void)
5175 return mono_thread_interruption_checkpoint () != NULL
;
5179 mono_thread_interruption_checkpoint_void (void)
5181 mono_thread_interruption_checkpoint ();
5185 * Performs the interruption of the current thread, if one has been requested.
5186 * Return the exception which needs to be thrown, if any.
5189 mono_thread_force_interruption_checkpoint_noraise (void)
5191 return mono_thread_interruption_checkpoint_request (TRUE
);
5195 * mono_set_pending_exception:
5197 * Set the pending exception of the current thread to EXC.
5198 * The exception will be thrown when execution returns to managed code.
5201 mono_set_pending_exception (MonoException
*exc
)
5203 MonoThread
*thread
= mono_thread_current ();
5205 /* The thread may already be stopping */
5209 MONO_OBJECT_SETREF_INTERNAL (thread
, pending_exception
, exc
);
5211 mono_thread_request_interruption_native ();
5215 * mono_runtime_set_pending_exception:
5217 * Set the pending exception of the current thread to \p exc.
5218 * The exception will be thrown when execution returns to managed code.
5219 * Can optionally \p overwrite any existing pending exceptions (it's not supported
5220 * to overwrite any pending exceptions if the runtime is processing a thread abort request,
5221 * in which case the behavior will be undefined).
5222 * Return whether the pending exception was set or not.
5223 * It will not be set if:
5224 * * The thread or runtime is stopping or shutting down
5225 * * There already is a pending exception (and \p overwrite is false)
5228 mono_runtime_set_pending_exception (MonoException
*exc
, mono_bool overwrite
)
5230 MonoThread
*thread
= mono_thread_current ();
5232 /* The thread may already be stopping */
5236 /* Don't overwrite any existing pending exceptions unless asked to */
5237 if (!overwrite
&& thread
->pending_exception
)
5240 MONO_OBJECT_SETREF_INTERNAL (thread
, pending_exception
, exc
);
5242 mono_thread_request_interruption_native ();
5249 * mono_set_pending_exception_handle:
5251 * Set the pending exception of the current thread to EXC.
5252 * The exception will be thrown when execution returns to managed code.
5255 mono_set_pending_exception_handle (MonoExceptionHandle exc
)
5257 MonoThread
*thread
= mono_thread_current ();
5259 /* The thread may already be stopping */
5263 MONO_OBJECT_SETREF_INTERNAL (thread
, pending_exception
, MONO_HANDLE_RAW (exc
));
5265 mono_thread_request_interruption_native ();
5269 mono_thread_init_apartment_state (void)
5272 MonoInternalThread
* thread
= mono_thread_internal_current ();
5274 /* Positive return value indicates success, either
5275 * S_OK if this is first CoInitialize call, or
5276 * S_FALSE if CoInitialize already called, but with same
5277 * threading model. A negative value indicates failure,
5278 * probably due to trying to change the threading model.
5280 if (CoInitializeEx(NULL
, (thread
->apartment_state
== ThreadApartmentState_STA
)
5281 ? COINIT_APARTMENTTHREADED
5282 : COINIT_MULTITHREADED
) < 0) {
5283 thread
->apartment_state
= ThreadApartmentState_Unknown
;
5289 mono_thread_cleanup_apartment_state (void)
5292 MonoInternalThread
* thread
= mono_thread_internal_current ();
5294 if (thread
&& thread
->apartment_state
!= ThreadApartmentState_Unknown
) {
5301 mono_thread_notify_change_state (MonoThreadState old_state
, MonoThreadState new_state
)
5303 MonoThreadState diff
= old_state
^ new_state
;
5304 if (diff
& ThreadState_Background
) {
5305 /* If the thread changes the background mode, the main thread has to
5306 * be notified, since it has to rebuild the list of threads to
5310 mono_os_event_set (&background_change_event
);
5316 mono_thread_clear_and_set_state (MonoInternalThread
*thread
, MonoThreadState clear
, MonoThreadState set
)
5318 LOCK_THREAD (thread
);
5320 MonoThreadState
const old_state
= (MonoThreadState
)thread
->state
;
5321 MonoThreadState
const new_state
= (old_state
& ~clear
) | set
;
5322 thread
->state
= new_state
;
5324 UNLOCK_THREAD (thread
);
5326 mono_thread_notify_change_state (old_state
, new_state
);
5330 mono_thread_set_state (MonoInternalThread
*thread
, MonoThreadState state
)
5332 mono_thread_clear_and_set_state (thread
, (MonoThreadState
)0, state
);
5336 * mono_thread_test_and_set_state:
5337 * Test if current state of \p thread include \p test. If it does not, OR \p set into the state.
5338 * \returns TRUE if \p set was OR'd in.
5341 mono_thread_test_and_set_state (MonoInternalThread
*thread
, MonoThreadState test
, MonoThreadState set
)
5343 LOCK_THREAD (thread
);
5345 MonoThreadState
const old_state
= (MonoThreadState
)thread
->state
;
5347 if ((old_state
& test
) != 0) {
5348 UNLOCK_THREAD (thread
);
5352 MonoThreadState
const new_state
= old_state
| set
;
5353 thread
->state
= new_state
;
5355 UNLOCK_THREAD (thread
);
5357 mono_thread_notify_change_state (old_state
, new_state
);
5363 mono_thread_clr_state (MonoInternalThread
*thread
, MonoThreadState state
)
5365 mono_thread_clear_and_set_state (thread
, state
, (MonoThreadState
)0);
5369 mono_thread_test_state (MonoInternalThread
*thread
, MonoThreadState test
)
5371 LOCK_THREAD (thread
);
5373 gboolean
const ret
= ((thread
->state
& test
) != 0);
5375 UNLOCK_THREAD (thread
);
5381 self_interrupt_thread (void *_unused
)
5384 MonoThreadInfo
*info
;
5387 exc
= mono_thread_execute_interruption_ptr ();
5389 if (mono_threads_are_safepoints_enabled ()) {
5390 /* We can return from an async call in coop, as
5391 * it's simply called when exiting the safepoint */
5392 /* If we're using hybrid suspend, we only self
5393 * interrupt if we were running, hence using
5398 g_error ("%s: we can't resume from an async call", __func__
);
5401 info
= mono_thread_info_current ();
5403 /* FIXME using thread_saved_state [ASYNC_SUSPEND_STATE_INDEX] can race with another suspend coming in. */
5404 ctx
= info
->thread_saved_state
[ASYNC_SUSPEND_STATE_INDEX
].ctx
;
5406 mono_raise_exception_with_context (exc
, &ctx
);
5410 mono_jit_info_match (MonoJitInfo
*ji
, gpointer ip
)
5414 return ji
->code_start
<= ip
&& (char*)ip
< (char*)ji
->code_start
+ ji
->code_size
;
5418 last_managed (MonoStackFrameInfo
*frame
, MonoContext
*ctx
, gpointer data
)
5420 MonoJitInfo
**dest
= (MonoJitInfo
**)data
;
5426 mono_thread_info_get_last_managed (MonoThreadInfo
*info
)
5428 MonoJitInfo
*ji
= NULL
;
5433 * The suspended thread might be holding runtime locks. Make sure we don't try taking
5434 * any runtime locks while unwinding.
5436 mono_thread_info_set_is_async_context (TRUE
);
5437 mono_get_eh_callbacks ()->mono_walk_stack_with_state (last_managed
, mono_thread_info_get_suspend_state (info
), MONO_UNWIND_SIGNAL_SAFE
, &ji
);
5438 mono_thread_info_set_is_async_context (FALSE
);
5443 MonoInternalThread
*thread
;
5444 gboolean install_async_abort
;
5445 MonoThreadInfoInterruptToken
*interrupt_token
;
5448 static SuspendThreadResult
5449 async_abort_critical (MonoThreadInfo
*info
, gpointer ud
)
5451 AbortThreadData
*data
= (AbortThreadData
*)ud
;
5452 MonoInternalThread
*thread
= data
->thread
;
5453 MonoJitInfo
*ji
= NULL
;
5454 gboolean protected_wrapper
;
5455 gboolean running_managed
;
5457 if (mono_get_eh_callbacks ()->mono_install_handler_block_guard (mono_thread_info_get_suspend_state (info
)))
5458 return MonoResumeThread
;
5460 /*someone is already interrupting it*/
5461 if (!mono_thread_set_interruption_requested (thread
))
5462 return MonoResumeThread
;
5464 ji
= mono_thread_info_get_last_managed (info
);
5465 protected_wrapper
= ji
&& !ji
->is_trampoline
&& !ji
->async
&& mono_threads_is_critical_method (mono_jit_info_get_method (ji
));
5466 running_managed
= mono_jit_info_match (ji
, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info
)->ctx
));
5468 if (!protected_wrapper
&& running_managed
) {
5469 /*We are in managed code*/
5470 /*Set the thread to call */
5471 if (data
->install_async_abort
)
5472 mono_thread_info_setup_async_call (info
, self_interrupt_thread
, NULL
);
5473 return MonoResumeThread
;
5476 * This will cause waits to be broken.
5477 * It will also prevent the thread from entering a wait, so if the thread returns
5478 * from the wait before it receives the abort signal, it will just spin in the wait
5479 * functions in the io-layer until the signal handler calls QueueUserAPC which will
5482 data
->interrupt_token
= mono_thread_info_prepare_interrupt (info
);
5484 return MonoResumeThread
;
5489 async_abort_internal (MonoInternalThread
*thread
, gboolean install_async_abort
)
5491 AbortThreadData data
;
5493 g_assert (thread
!= mono_thread_internal_current ());
5495 data
.thread
= thread
;
5496 data
.install_async_abort
= install_async_abort
;
5497 data
.interrupt_token
= NULL
;
5499 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), TRUE
, async_abort_critical
, &data
);
5500 if (data
.interrupt_token
)
5501 mono_thread_info_finish_interrupt (data
.interrupt_token
);
5502 /*FIXME we need to wait for interruption to complete -- figure out how much into interruption we should wait for here*/
5506 self_abort_internal (MonoError
*error
)
5508 HANDLE_FUNCTION_ENTER ();
5512 /* FIXME this is insanely broken, it doesn't cause interruption to happen synchronously
5513 * since passing FALSE to mono_thread_request_interruption makes sure it returns NULL */
5516 Self aborts ignore the protected block logic and raise the TAE regardless. This is verified by one of the tests in mono/tests/abort-cctor.cs.
5518 MonoExceptionHandle exc
= MONO_HANDLE_NEW (MonoException
, NULL
);
5519 if (mono_thread_request_interruption_managed (&exc
))
5520 mono_error_set_exception_handle (error
, exc
);
5522 mono_thread_info_self_interrupt ();
5524 HANDLE_FUNCTION_RETURN ();
5528 MonoInternalThread
*thread
;
5530 MonoThreadInfoInterruptToken
*interrupt_token
;
5531 } SuspendThreadData
;
5533 static SuspendThreadResult
5534 async_suspend_critical (MonoThreadInfo
*info
, gpointer ud
)
5536 SuspendThreadData
*data
= (SuspendThreadData
*)ud
;
5537 MonoInternalThread
*thread
= data
->thread
;
5538 MonoJitInfo
*ji
= NULL
;
5539 gboolean protected_wrapper
;
5540 gboolean running_managed
;
5542 ji
= mono_thread_info_get_last_managed (info
);
5543 protected_wrapper
= ji
&& !ji
->is_trampoline
&& !ji
->async
&& mono_threads_is_critical_method (mono_jit_info_get_method (ji
));
5544 running_managed
= mono_jit_info_match (ji
, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info
)->ctx
));
5546 if (running_managed
&& !protected_wrapper
) {
5547 if (mono_threads_are_safepoints_enabled ()) {
5548 mono_thread_info_setup_async_call (info
, self_interrupt_thread
, NULL
);
5549 return MonoResumeThread
;
5551 thread
->state
&= ~ThreadState_SuspendRequested
;
5552 thread
->state
|= ThreadState_Suspended
;
5553 return KeepSuspended
;
5556 mono_thread_set_interruption_requested (thread
);
5557 if (data
->interrupt
)
5558 data
->interrupt_token
= mono_thread_info_prepare_interrupt ((MonoThreadInfo
*)thread
->thread_info
);
5560 return MonoResumeThread
;
5564 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5566 async_suspend_internal (MonoInternalThread
*thread
, gboolean interrupt
)
5568 SuspendThreadData data
;
5570 g_assert (thread
!= mono_thread_internal_current ());
5572 // g_async_safe_printf ("ASYNC SUSPEND thread %p\n", thread_get_tid (thread));
5574 thread
->self_suspended
= FALSE
;
5576 data
.thread
= thread
;
5577 data
.interrupt
= interrupt
;
5578 data
.interrupt_token
= NULL
;
5580 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), interrupt
, async_suspend_critical
, &data
);
5581 if (data
.interrupt_token
)
5582 mono_thread_info_finish_interrupt (data
.interrupt_token
);
5584 UNLOCK_THREAD (thread
);
5587 /* LOCKING: called with @thread longlived->synch_cs held, and releases it */
5589 self_suspend_internal (void)
5591 MonoInternalThread
*thread
;
5593 MonoOSEventWaitRet res
;
5595 thread
= mono_thread_internal_current ();
5597 // g_async_safe_printf ("SELF SUSPEND thread %p\n", thread_get_tid (thread));
5599 thread
->self_suspended
= TRUE
;
5601 thread
->state
&= ~ThreadState_SuspendRequested
;
5602 thread
->state
|= ThreadState_Suspended
;
5604 UNLOCK_THREAD (thread
);
5606 event
= thread
->suspended
;
5609 res
= mono_os_event_wait_one (event
, MONO_INFINITE_WAIT
, TRUE
);
5610 g_assert (res
== MONO_OS_EVENT_WAIT_RET_SUCCESS_0
|| res
== MONO_OS_EVENT_WAIT_RET_ALERTED
);
5615 suspend_for_shutdown_async_call (gpointer unused
)
5618 mono_thread_info_yield ();
5621 static SuspendThreadResult
5622 suspend_for_shutdown_critical (MonoThreadInfo
*info
, gpointer unused
)
5624 mono_thread_info_setup_async_call (info
, suspend_for_shutdown_async_call
, NULL
);
5625 return MonoResumeThread
;
5629 mono_thread_internal_suspend_for_shutdown (MonoInternalThread
*thread
)
5631 g_assert (thread
!= mono_thread_internal_current ());
5633 mono_thread_info_safe_suspend_and_run (thread_get_tid (thread
), FALSE
, suspend_for_shutdown_critical
, NULL
);
5637 * mono_thread_is_foreign:
5638 * \param thread the thread to query
5640 * This function allows one to determine if a thread was created by the mono runtime and has
5641 * a well defined lifecycle or it's a foreign one, created by the native environment.
5643 * \returns TRUE if \p thread was not created by the runtime.
5646 mono_thread_is_foreign (MonoThread
*thread
)
5649 MONO_ENTER_GC_UNSAFE
;
5650 MonoThreadInfo
*info
= (MonoThreadInfo
*)thread
->internal_thread
->thread_info
;
5651 result
= (info
->runtime_thread
== FALSE
);
5652 MONO_EXIT_GC_UNSAFE
;
5658 threads_native_thread_join_lock (gpointer tid
, gpointer value
)
5660 pthread_t thread
= (pthread_t
)tid
;
5661 if (thread
!= pthread_self ()) {
5663 /* This shouldn't block */
5664 mono_threads_join_lock ();
5665 mono_native_thread_join (thread
);
5666 mono_threads_join_unlock ();
5671 threads_native_thread_join_nolock (gpointer tid
, gpointer value
)
5673 pthread_t thread
= (pthread_t
)tid
;
5675 mono_native_thread_join (thread
);
5680 threads_add_joinable_thread_nolock (gpointer tid
)
5682 g_hash_table_insert (joinable_threads
, tid
, tid
);
5686 threads_native_thread_join_lock (gpointer tid
, gpointer value
)
5688 MonoNativeThreadId thread_id
= (MonoNativeThreadId
)(guint64
)tid
;
5689 HANDLE thread_handle
= (HANDLE
)value
;
5690 if (thread_id
!= GetCurrentThreadId () && thread_handle
!= NULL
&& thread_handle
!= INVALID_HANDLE_VALUE
) {
5692 /* This shouldn't block */
5693 mono_threads_join_lock ();
5694 mono_native_thread_join_handle (thread_handle
, TRUE
);
5695 mono_threads_join_unlock ();
5701 threads_native_thread_join_nolock (gpointer tid
, gpointer value
)
5703 HANDLE thread_handle
= (HANDLE
)value
;
5705 mono_native_thread_join_handle (thread_handle
, TRUE
);
5710 threads_add_joinable_thread_nolock (gpointer tid
)
5712 g_hash_table_insert (joinable_threads
, tid
, (gpointer
)OpenThread (SYNCHRONIZE
, TRUE
, (MonoNativeThreadId
)(guint64
)tid
));
5717 threads_add_pending_joinable_thread (gpointer tid
)
5719 joinable_threads_lock ();
5721 if (!pending_joinable_threads
)
5722 pending_joinable_threads
= g_hash_table_new (NULL
, NULL
);
5727 if (!g_hash_table_lookup_extended (pending_joinable_threads
, tid
, &orig_key
, &value
)) {
5728 g_hash_table_insert (pending_joinable_threads
, tid
, tid
);
5729 UnlockedIncrement (&pending_joinable_thread_count
);
5732 joinable_threads_unlock ();
5736 threads_add_pending_joinable_runtime_thread (MonoThreadInfo
*mono_thread_info
)
5738 g_assert (mono_thread_info
);
5740 if (mono_thread_info
->runtime_thread
) {
5741 threads_add_pending_joinable_thread ((gpointer
)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info
))));
5746 threads_remove_pending_joinable_thread_nolock (gpointer tid
)
5751 if (pending_joinable_threads
&& g_hash_table_lookup_extended (pending_joinable_threads
, tid
, &orig_key
, &value
)) {
5752 g_hash_table_remove (pending_joinable_threads
, tid
);
5753 if (UnlockedDecrement (&pending_joinable_thread_count
) == 0)
5754 mono_coop_cond_broadcast (&zero_pending_joinable_thread_event
);
5759 threads_wait_pending_joinable_threads (uint32_t timeout
)
5761 if (UnlockedRead (&pending_joinable_thread_count
) > 0) {
5762 joinable_threads_lock ();
5763 if (timeout
== MONO_INFINITE_WAIT
) {
5764 while (UnlockedRead (&pending_joinable_thread_count
) > 0)
5765 mono_coop_cond_wait (&zero_pending_joinable_thread_event
, &joinable_threads_mutex
);
5767 gint64 start
= mono_msec_ticks ();
5769 while (UnlockedRead (&pending_joinable_thread_count
) > 0 && elapsed
< timeout
) {
5770 mono_coop_cond_timedwait (&zero_pending_joinable_thread_event
, &joinable_threads_mutex
, timeout
- (uint32_t)elapsed
);
5771 elapsed
= mono_msec_ticks () - start
;
5774 joinable_threads_unlock ();
5777 return UnlockedRead (&pending_joinable_thread_count
) == 0;
5781 threads_add_unique_joinable_thread_nolock (gpointer tid
)
5783 if (!joinable_threads
)
5784 joinable_threads
= g_hash_table_new (NULL
, NULL
);
5789 if (!g_hash_table_lookup_extended (joinable_threads
, tid
, &orig_key
, &value
)) {
5790 threads_add_joinable_thread_nolock (tid
);
5791 UnlockedIncrement (&joinable_thread_count
);
5796 mono_threads_add_joinable_runtime_thread (MonoThreadInfo
*thread_info
)
5798 g_assert (thread_info
);
5799 MonoThreadInfo
*mono_thread_info
= thread_info
;
5801 if (mono_thread_info
->runtime_thread
) {
5802 gpointer tid
= (gpointer
)(MONO_UINT_TO_NATIVE_THREAD_ID (mono_thread_info_get_tid (mono_thread_info
)));
5804 joinable_threads_lock ();
5806 // Add to joinable thread list, if not already included.
5807 threads_add_unique_joinable_thread_nolock (tid
);
5809 // Remove thread from pending joinable list, if present.
5810 threads_remove_pending_joinable_thread_nolock (tid
);
5812 joinable_threads_unlock ();
5814 mono_gc_finalize_notify ();
5819 threads_add_pending_native_thread_join_call_nolock (gpointer tid
)
5821 if (!pending_native_thread_join_calls
)
5822 pending_native_thread_join_calls
= g_hash_table_new (NULL
, NULL
);
5827 if (!g_hash_table_lookup_extended (pending_native_thread_join_calls
, tid
, &orig_key
, &value
))
5828 g_hash_table_insert (pending_native_thread_join_calls
, tid
, tid
);
5832 threads_remove_pending_native_thread_join_call_nolock (gpointer tid
)
5834 if (pending_native_thread_join_calls
)
5835 g_hash_table_remove (pending_native_thread_join_calls
, tid
);
5837 mono_coop_cond_broadcast (&pending_native_thread_join_calls_event
);
5841 threads_wait_pending_native_thread_join_call_nolock (gpointer tid
)
5846 while (g_hash_table_lookup_extended (pending_native_thread_join_calls
, tid
, &orig_key
, &value
)) {
5847 mono_coop_cond_wait (&pending_native_thread_join_calls_event
, &joinable_threads_mutex
);
5852 * mono_add_joinable_thread:
5854 * Add TID to the list of joinable threads.
5855 * LOCKING: Acquires the threads lock.
5858 mono_threads_add_joinable_thread (gpointer tid
)
5861 * We cannot detach from threads because it causes problems like
5862 * 2fd16f60/r114307. So we collect them and join them when
5863 * we have time (in the finalizer thread).
5865 joinable_threads_lock ();
5866 threads_add_unique_joinable_thread_nolock (tid
);
5867 joinable_threads_unlock ();
5869 mono_gc_finalize_notify ();
5873 * mono_threads_join_threads:
5875 * Join all joinable threads. This is called from the finalizer thread.
5876 * LOCKING: Acquires the threads lock.
5879 mono_threads_join_threads (void)
5881 GHashTableIter iter
;
5882 gpointer key
= NULL
;
5883 gpointer value
= NULL
;
5884 gboolean found
= FALSE
;
5887 if (!UnlockedRead (&joinable_thread_count
))
5891 joinable_threads_lock ();
5893 // Previous native thread join call completed.
5894 threads_remove_pending_native_thread_join_call_nolock (key
);
5897 if (g_hash_table_size (joinable_threads
)) {
5898 g_hash_table_iter_init (&iter
, joinable_threads
);
5899 g_hash_table_iter_next (&iter
, &key
, (void**)&value
);
5900 g_hash_table_remove (joinable_threads
, key
);
5901 UnlockedDecrement (&joinable_thread_count
);
5904 // Add to table of tid's with pending native thread join call.
5905 threads_add_pending_native_thread_join_call_nolock (key
);
5907 joinable_threads_unlock ();
5909 threads_native_thread_join_lock (key
, value
);
5918 * Wait for thread TID to exit.
5919 * LOCKING: Acquires the threads lock.
5922 mono_thread_join (gpointer tid
)
5924 gboolean found
= FALSE
;
5928 joinable_threads_lock ();
5929 if (!joinable_threads
)
5930 joinable_threads
= g_hash_table_new (NULL
, NULL
);
5932 if (g_hash_table_lookup_extended (joinable_threads
, tid
, &orig_key
, &value
)) {
5933 g_hash_table_remove (joinable_threads
, tid
);
5934 UnlockedDecrement (&joinable_thread_count
);
5937 // Add to table of tid's with pending native join call.
5938 threads_add_pending_native_thread_join_call_nolock (tid
);
5942 // Wait for any pending native thread join call not yet completed for this tid.
5943 threads_wait_pending_native_thread_join_call_nolock (tid
);
5946 joinable_threads_unlock ();
5951 threads_native_thread_join_nolock (tid
, value
);
5953 joinable_threads_lock ();
5954 // Native thread join call completed for this tid.
5955 threads_remove_pending_native_thread_join_call_nolock (tid
);
5956 joinable_threads_unlock ();
5960 mono_thread_internal_unhandled_exception (MonoObject
* exc
)
5962 MonoClass
*klass
= exc
->vtable
->klass
;
5963 if (is_threadabort_exception (klass
)) {
5964 mono_thread_internal_reset_abort (mono_thread_internal_current ());
5965 } else if (!is_appdomainunloaded_exception (klass
)
5966 && mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_CURRENT
) {
5967 mono_unhandled_exception_internal (exc
);
5968 if (mono_environment_exitcode_get () == 1) {
5969 mono_environment_exitcode_set (255);
5970 mono_invoke_unhandled_exception_hook (exc
);
5971 g_assert_not_reached ();
5977 * mono_threads_attach_coop_internal: called by native->managed wrappers
5980 * - blocking mode: contains gc unsafe transition cookie
5981 * - non-blocking mode: contains random data
5982 * - @stackdata: semi-opaque struct: stackpointer and function_name
5983 * - @return: the original domain which needs to be restored, or NULL.
5986 mono_threads_attach_coop_internal (MonoDomain
*domain
, gpointer
*cookie
, MonoStackData
*stackdata
)
5989 MonoThreadInfo
*info
;
5990 gboolean external
= FALSE
;
5992 orig
= mono_domain_get ();
5995 /* Happens when called from AOTed code which is only used in the root domain. */
5996 domain
= mono_get_root_domain ();
6000 /* On coop, when we detached, we moved the thread from RUNNING->BLOCKING.
6001 * If we try to reattach we do a BLOCKING->RUNNING transition. If the thread
6002 * is fresh, mono_thread_attach() will do a STARTING->RUNNING transition so
6003 * we're only responsible for making the cookie. */
6004 if (mono_threads_is_blocking_transition_enabled ())
6005 external
= !(info
= mono_thread_info_current_unchecked ()) || !mono_thread_info_is_live (info
);
6007 if (!mono_thread_internal_current ()) {
6008 mono_thread_attach (domain
);
6011 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background
);
6014 if (mono_threads_is_blocking_transition_enabled ()) {
6016 /* mono_thread_attach put the thread in RUNNING mode from STARTING, but we need to
6017 * return the right cookie. */
6018 *cookie
= mono_threads_enter_gc_unsafe_region_cookie ();
6020 /* thread state (BLOCKING|RUNNING) -> RUNNING */
6021 *cookie
= mono_threads_enter_gc_unsafe_region_unbalanced_internal (stackdata
);
6026 mono_domain_set_fast (domain
, TRUE
);
6032 * mono_threads_attach_coop: called by native->managed wrappers
6035 * - blocking mode: contains gc unsafe transition cookie
6036 * - non-blocking mode: contains random data
6037 * - a pointer to stack, used for some checks
6038 * - @return: the original domain which needs to be restored, or NULL.
6041 mono_threads_attach_coop (MonoDomain
*domain
, gpointer
*dummy
)
6043 MONO_STACKDATA (stackdata
);
6044 stackdata
.stackpointer
= dummy
;
6045 return mono_threads_attach_coop_internal (domain
, dummy
, &stackdata
);
6049 * mono_threads_detach_coop_internal: called by native->managed wrappers
6051 * - @orig: the original domain which needs to be restored, or NULL.
6052 * - @stackdata: semi-opaque struct: stackpointer and function_name
6054 * - blocking mode: contains gc unsafe transition cookie
6055 * - non-blocking mode: contains random data
6058 mono_threads_detach_coop_internal (MonoDomain
*orig
, gpointer cookie
, MonoStackData
*stackdata
)
6060 MonoDomain
*domain
= mono_domain_get ();
6063 if (orig
!= domain
) {
6065 mono_domain_unset ();
6067 mono_domain_set_fast (orig
, TRUE
);
6070 if (mono_threads_is_blocking_transition_enabled ()) {
6071 /* it won't do anything if cookie is NULL
6072 * thread state RUNNING -> (RUNNING|BLOCKING) */
6073 mono_threads_exit_gc_unsafe_region_unbalanced_internal (cookie
, stackdata
);
6078 * mono_threads_detach_coop: called by native->managed wrappers
6080 * - @orig: the original domain which needs to be restored, or NULL.
6082 * - blocking mode: contains gc unsafe transition cookie
6083 * - non-blocking mode: contains random data
6084 * - a pointer to stack, used for some checks
6087 mono_threads_detach_coop (gpointer orig
, gpointer
*dummy
)
6089 MONO_STACKDATA (stackdata
);
6090 stackdata
.stackpointer
= dummy
;
6091 mono_threads_detach_coop_internal ((MonoDomain
*)orig
, *dummy
, &stackdata
);
6095 /* Returns TRUE if the current thread is ready to be interrupted. */
6097 mono_threads_is_ready_to_be_interrupted (void)
6099 MonoInternalThread
*thread
;
6101 thread
= mono_thread_internal_current ();
6102 LOCK_THREAD (thread
);
6103 if (thread
->state
& (ThreadState_SuspendRequested
| ThreadState_AbortRequested
)) {
6104 UNLOCK_THREAD (thread
);
6108 if (mono_thread_get_abort_prot_block_count (thread
) || mono_get_eh_callbacks ()->mono_current_thread_has_handle_block_guard ()) {
6109 UNLOCK_THREAD (thread
);
6113 UNLOCK_THREAD (thread
);
6119 mono_thread_internal_describe (MonoInternalThread
*internal
, GString
*text
)
6121 g_string_append_printf (text
, ", thread handle : %p", internal
->handle
);
6123 if (internal
->thread_info
) {
6124 g_string_append (text
, ", state : ");
6125 mono_thread_info_describe_interrupt_token (internal
->thread_info
, text
);
6128 if (internal
->owned_mutexes
) {
6131 g_string_append (text
, ", owns : [");
6132 for (i
= 0; i
< internal
->owned_mutexes
->len
; i
++)
6133 g_string_append_printf (text
, i
== 0 ? "%p" : ", %p", g_ptr_array_index (internal
->owned_mutexes
, i
));
6134 g_string_append (text
, "]");
6139 mono_thread_internal_is_current (MonoInternalThread
*internal
)
6141 g_assert (internal
);
6142 return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal
->tid
));
6146 mono_set_thread_dump_dir (gchar
* dir
) {
6147 thread_dump_dir
= dir
;
6150 #ifdef DISABLE_CRASH_REPORTING
6152 mono_threads_summarize_init (void)
6157 mono_threads_summarize (MonoContext
*ctx
, gchar
**out
, MonoStackHash
*hashes
, gboolean silent
, gboolean signal_handler_controller
, gchar
*mem
, size_t provided_size
)
6163 mono_threads_summarize_one (MonoThreadSummary
*out
, MonoContext
*ctx
)
6171 mono_threads_summarize_native_self (MonoThreadSummary
*out
, MonoContext
*ctx
)
6173 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack
)
6176 memset (out
, 0, sizeof (MonoThreadSummary
));
6179 MonoNativeThreadId current
= mono_native_thread_id_get();
6180 out
->native_thread_id
= (intptr_t) current
;
6182 mono_get_eh_callbacks ()->mono_summarize_unmanaged_stack (out
);
6184 mono_native_thread_get_name (current
, out
->name
, MONO_MAX_SUMMARY_NAME_LEN
);
6189 // Not safe to call from signal handler
6191 mono_threads_summarize_one (MonoThreadSummary
*out
, MonoContext
*ctx
)
6193 gboolean success
= mono_threads_summarize_native_self (out
, ctx
);
6195 // Finish this on the same thread
6197 if (success
&& mono_get_eh_callbacks ()->mono_summarize_managed_stack
)
6198 mono_get_eh_callbacks ()->mono_summarize_managed_stack (out
);
6203 #define MAX_NUM_THREADS 128
6205 gint32 has_owner
; // state of this memory
6207 MonoSemType update
; // notify of addition of threads
6210 MonoNativeThreadId thread_array
[MAX_NUM_THREADS
]; // ids of threads we're dumping
6212 int nthreads_attached
; // Number of threads self-registered
6213 MonoThreadSummary
*all_threads
[MAX_NUM_THREADS
];
6215 gboolean silent
; // print to stdout
6216 } SummarizerGlobalState
;
6218 #if defined(HAVE_KILL) && !defined(HOST_ANDROID) && defined(HAVE_WAITPID) && defined(HAVE_EXECVE) && ((!defined(HOST_DARWIN) && defined(SYS_fork)) || HAVE_FORK)
6219 #define HAVE_MONO_SUMMARIZER_SUPERVISOR 1
6223 summarizer_supervisor_init (void);
6226 MonoSemType supervisor
;
6228 pid_t supervisor_pid
;
6229 } SummarizerSupervisorState
;
6231 #ifndef HAVE_MONO_SUMMARIZER_SUPERVISOR
6234 summarizer_supervisor_init (void)
6240 summarizer_supervisor_start (SummarizerSupervisorState
*state
)
6242 // nonzero, so caller doesn't think it's the supervisor
6247 summarizer_supervisor_end (SummarizerSupervisorState
*state
)
6253 static const char *hang_watchdog_path
;
6256 summarizer_supervisor_init (void)
6258 hang_watchdog_path
= g_build_filename (mono_get_config_dir (), "..", "bin", "mono-hang-watchdog", NULL
);
6259 g_assert (hang_watchdog_path
);
6263 summarizer_supervisor_start (SummarizerSupervisorState
*state
)
6265 memset (state
, 0, sizeof (*state
));
6268 state
->pid
= getpid();
6271 * glibc fork acquires some locks, so if the crash happened inside malloc/free,
6272 * it will deadlock. Call the syscall directly instead.
6274 #if defined(HOST_ANDROID)
6275 /* SYS_fork is defined to be __NR_fork which is not defined in some ndk versions */
6276 // We disable this when we set HAVE_MONO_SUMMARIZER_SUPERVISOR above
6277 g_assert_not_reached ();
6278 #elif !defined(HOST_DARWIN) && defined(SYS_fork)
6279 pid
= (pid_t
) syscall (SYS_fork
);
6281 pid
= (pid_t
) fork ();
6283 g_assert_not_reached ();
6287 state
->supervisor_pid
= pid
;
6289 char pid_str
[20]; // pid is a uint64_t, 20 digits max in decimal form
6290 sprintf (pid_str
, "%llu", (uint64_t)state
->pid
);
6291 const char *const args
[] = { hang_watchdog_path
, pid_str
, NULL
};
6292 execve (args
[0], (char * const*)args
, NULL
); // run 'mono-hang-watchdog [pid]'
6293 g_async_safe_printf ("Could not exec mono-hang-watchdog, expected on path '%s' (errno %d)\n", hang_watchdog_path
, errno
);
6301 summarizer_supervisor_end (SummarizerSupervisorState
*state
)
6304 kill (state
->supervisor_pid
, SIGKILL
);
6307 #if defined (HAVE_WAITPID)
6308 // Accessed on same thread that sets it.
6310 waitpid (state
->supervisor_pid
, &status
, 0);
6316 collect_thread_id (gpointer key
, gpointer value
, gpointer user
)
6318 CollectThreadIdsUserData
*ud
= (CollectThreadIdsUserData
*)user
;
6319 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
6321 if (ud
->nthreads
< ud
->max_threads
)
6322 ud
->threads
[ud
->nthreads
++] = thread_get_tid (thread
);
6326 collect_thread_ids (MonoNativeThreadId
*thread_ids
, int max_threads
)
6328 CollectThreadIdsUserData ud
;
6330 mono_memory_barrier ();
6334 memset (&ud
, 0, sizeof (ud
));
6335 /* This array contains refs, but its on the stack, so its ok */
6336 ud
.threads
= thread_ids
;
6337 ud
.max_threads
= max_threads
;
6339 mono_threads_lock ();
6340 mono_g_hash_table_foreach (threads
, collect_thread_id
, &ud
);
6341 mono_threads_unlock ();
6347 summarizer_state_init (SummarizerGlobalState
*state
, MonoNativeThreadId current
, int *my_index
)
6349 gint32 started_state
= mono_atomic_cas_i32 (&state
->has_owner
, 1 /* set */, 0 /* compare */);
6350 gboolean not_started
= started_state
== 0;
6352 state
->nthreads
= collect_thread_ids (state
->thread_array
, MAX_NUM_THREADS
);
6353 mono_os_sem_init (&state
->update
, 0);
6356 for (int i
= 0; i
< state
->nthreads
; i
++) {
6357 if (state
->thread_array
[i
] == current
) {
6367 summarizer_signal_other_threads (SummarizerGlobalState
*state
, MonoNativeThreadId current
, int current_idx
)
6369 #ifdef HAVE_SIGNAL_H
6370 sigset_t sigset
, old_sigset
;
6371 sigemptyset(&sigset
);
6372 sigaddset(&sigset
, SIGTERM
);
6374 for (int i
=0; i
< state
->nthreads
; i
++) {
6375 sigprocmask (SIG_UNBLOCK
, &sigset
, &old_sigset
);
6377 if (i
== current_idx
)
6379 #ifdef HAVE_PTHREAD_KILL
6380 pthread_kill (state
->thread_array
[i
], SIGTERM
);
6383 g_async_safe_printf("Pkilling 0x%zx from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (state
->thread_array
[i
]), MONO_NATIVE_THREAD_ID_TO_UINT (current
));
6385 g_error ("pthread_kill () is not supported by this platform");
6391 // Returns true when there are shared global references to "this_thread"
6393 summarizer_post_dump (SummarizerGlobalState
*state
, MonoThreadSummary
*this_thread
, int current_idx
)
6395 mono_memory_barrier ();
6397 gpointer old
= mono_atomic_cas_ptr ((volatile gpointer
*)&state
->all_threads
[current_idx
], this_thread
, NULL
);
6399 if (old
== GINT_TO_POINTER (-1)) {
6400 g_async_safe_printf ("Trying to register response after dumping period ended");
6402 } else if (old
!= NULL
) {
6403 g_async_safe_printf ("Thread dump raced for thread slot.");
6407 // We added our pointer
6408 gint32 count
= mono_atomic_inc_i32 ((volatile gint32
*) &state
->nthreads_attached
);
6409 if (count
== state
->nthreads
)
6410 mono_os_sem_post (&state
->update
);
6415 // A lockless spinwait with a timeout
6416 // Used in environments where locks are unsafe
6418 // If set_pos is true, we wait until the expected number of threads have
6419 // responded and then count that the expected number are set. If it is not true,
6420 // then we wait for them to be unset.
6422 summary_timedwait (SummarizerGlobalState
*state
, int timeout_seconds
)
6424 const gint64 milliseconds_in_second
= 1000;
6425 gint64 timeout_total
= milliseconds_in_second
* timeout_seconds
;
6427 gint64 end
= mono_msec_ticks () + timeout_total
;
6430 if (mono_atomic_load_i32 ((volatile gint32
*) &state
->nthreads_attached
) == state
->nthreads
)
6433 gint64 now
= mono_msec_ticks ();
6434 gint64 remaining
= end
- now
;
6438 mono_os_sem_timedwait (&state
->update
, remaining
, MONO_SEM_FLAGS_NONE
);
6444 static MonoThreadSummary
*
6445 summarizer_try_read_thread (SummarizerGlobalState
*state
, int index
)
6447 gpointer old_value
= NULL
;
6448 gpointer new_value
= GINT_TO_POINTER(-1);
6451 old_value
= state
->all_threads
[index
];
6452 } while (mono_atomic_cas_ptr ((volatile gpointer
*) &state
->all_threads
[index
], new_value
, old_value
) != old_value
);
6454 MonoThreadSummary
*thread
= (MonoThreadSummary
*) old_value
;
6459 summarizer_state_term (SummarizerGlobalState
*state
, gchar
**out
, gchar
*mem
, size_t provided_size
, MonoThreadSummary
*controlling
)
6461 // See the array writes
6462 mono_memory_barrier ();
6464 MonoThreadSummary
*threads
[MAX_NUM_THREADS
];
6465 memset (threads
, 0, sizeof(threads
));
6467 mono_summarize_timeline_phase_log (MonoSummaryManagedStacks
);
6468 for (int i
=0; i
< state
->nthreads
; i
++) {
6469 threads
[i
] = summarizer_try_read_thread (state
, i
);
6473 // We are doing this dump on the controlling thread because this isn't
6474 // an async context sometimes. There's still some reliance on malloc here, but it's
6475 // much more stable to do it all from the controlling thread.
6477 // This is non-null, checked in mono_threads_summarize
6478 // with early exit there
6479 mono_get_eh_callbacks ()->mono_summarize_managed_stack (threads
[i
]);
6482 MonoStateWriter writer
;
6483 memset (&writer
, 0, sizeof (writer
));
6485 mono_summarize_timeline_phase_log (MonoSummaryStateWriter
);
6486 mono_summarize_native_state_begin (&writer
, mem
, provided_size
);
6487 for (int i
=0; i
< state
->nthreads
; i
++) {
6488 MonoThreadSummary
*thread
= threads
[i
];
6492 mono_summarize_native_state_add_thread (&writer
, thread
, thread
->ctx
, thread
== controlling
);
6493 // Set non-shared state to notify the waiting thread to clean up
6494 // without having to keep our shared state alive
6495 mono_atomic_store_i32 (&thread
->done
, 0x1);
6496 mono_os_sem_post (&thread
->done_wait
);
6498 *out
= mono_summarize_native_state_end (&writer
);
6499 mono_summarize_timeline_phase_log (MonoSummaryStateWriterDone
);
6501 mono_os_sem_destroy (&state
->update
);
6503 memset (state
, 0, sizeof (*state
));
6504 mono_atomic_store_i32 ((volatile gint32
*)&state
->has_owner
, 0);
6508 summarizer_state_wait (MonoThreadSummary
*thread
)
6510 gint64 milliseconds_in_second
= 1000;
6512 // cond_wait can spuriously wake up, so we need to check
6514 while (!mono_atomic_load_i32 (&thread
->done
))
6515 mono_os_sem_timedwait (&thread
->done_wait
, milliseconds_in_second
, MONO_SEM_FLAGS_NONE
);
6519 mono_threads_summarize_execute_internal (MonoContext
*ctx
, gchar
**out
, MonoStackHash
*hashes
, gboolean silent
, gchar
*working_mem
, size_t provided_size
, gboolean this_thread_controls
)
6521 static SummarizerGlobalState state
;
6524 MonoNativeThreadId current
= mono_native_thread_id_get ();
6525 gboolean thread_given_control
= summarizer_state_init (&state
, current
, ¤t_idx
);
6527 g_assert (this_thread_controls
== thread_given_control
);
6529 if (state
.nthreads
== 0) {
6531 g_async_safe_printf("No threads attached to runtime.\n");
6532 memset (&state
, 0, sizeof (state
));
6536 if (this_thread_controls
) {
6537 g_assert (working_mem
);
6539 mono_summarize_timeline_phase_log (MonoSummarySuspendHandshake
);
6540 state
.silent
= silent
;
6541 summarizer_signal_other_threads (&state
, current
, current_idx
);
6542 mono_summarize_timeline_phase_log (MonoSummaryUnmanagedStacks
);
6546 gboolean success
= mono_state_alloc_mem (&mem
, (long) current
, sizeof (MonoThreadSummary
));
6550 MonoThreadSummary
*this_thread
= (MonoThreadSummary
*) mem
.mem
;
6552 if (mono_threads_summarize_native_self (this_thread
, ctx
)) {
6553 // Init the synchronization between the controlling thread and the
6555 mono_os_sem_init (&this_thread
->done_wait
, 0);
6557 // Store a reference to our stack memory into global state
6558 gboolean success
= summarizer_post_dump (&state
, this_thread
, current_idx
);
6559 if (!success
&& !state
.silent
)
6560 g_async_safe_printf("Thread 0x%zx reported itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current
));
6561 } else if (!state
.silent
) {
6562 g_async_safe_printf("Thread 0x%zx couldn't report itself.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current
));
6565 // From summarizer, wait and dump.
6566 if (this_thread_controls
) {
6568 g_async_safe_printf("Entering thread summarizer pause from 0x%zx\n", MONO_NATIVE_THREAD_ID_TO_UINT (current
));
6570 // Wait up to 2 seconds for all of the other threads to catch up
6571 summary_timedwait (&state
, 2);
6574 g_async_safe_printf("Finished thread summarizer pause from 0x%zx.\n", MONO_NATIVE_THREAD_ID_TO_UINT (current
));
6576 // Dump and cleanup all the stack memory
6577 summarizer_state_term (&state
, out
, working_mem
, provided_size
, this_thread
);
6579 // Wait here, keeping our stack memory alive
6581 summarizer_state_wait (this_thread
);
6584 // FIXME: How many threads should be counted?
6586 *hashes
= this_thread
->hashes
;
6588 mono_state_free_mem (&mem
);
6594 mono_threads_summarize_init (void)
6596 summarizer_supervisor_init ();
6600 mono_threads_summarize_execute (MonoContext
*ctx
, gchar
**out
, MonoStackHash
*hashes
, gboolean silent
, gchar
*working_mem
, size_t provided_size
)
6603 gboolean already_async
= mono_thread_info_is_async_context ();
6605 mono_thread_info_set_is_async_context (TRUE
);
6606 result
= mono_threads_summarize_execute_internal (ctx
, out
, hashes
, silent
, working_mem
, provided_size
, FALSE
);
6608 mono_thread_info_set_is_async_context (FALSE
);
6613 mono_threads_summarize (MonoContext
*ctx
, gchar
**out
, MonoStackHash
*hashes
, gboolean silent
, gboolean signal_handler_controller
, gchar
*mem
, size_t provided_size
)
6615 if (!mono_get_eh_callbacks ()->mono_summarize_managed_stack
)
6618 // The staggered values are due to the need to use inc_i64 for the first value
6619 static gint64 next_pending_request_id
= 0;
6620 static gint64 request_available_to_run
= 1;
6621 gint64 this_request_id
= mono_atomic_inc_i64 ((volatile gint64
*) &next_pending_request_id
);
6623 // This is a global queue of summary requests.
6624 // It's not safe to signal a thread while they're in the
6625 // middle of a dump. Dladdr is not reentrant. It's the one lock
6626 // we rely on being able to take.
6628 // We don't use it in almost any other place in managed code, so
6629 // our problem is in the stack dumping code racing with the signalling code.
6631 // A dump is wait-free to the degree that it's not going to loop indefinitely.
6632 // If we're running from a crash handler block, we're not in any position to
6633 // wait for an in-flight dump to finish. If we crashed while dumping, we cannot dump.
6634 // We should simply return so we can die cleanly.
6636 // signal_handler_controller should be set only from a handler that expects itself to be the only
6637 // entry point, where the runtime already being dumping means we should just give up
6639 gboolean success
= FALSE
;
6642 gint64 next_request_id
= mono_atomic_load_i64 ((volatile gint64
*) &request_available_to_run
);
6644 if (next_request_id
== this_request_id
) {
6645 gboolean already_async
= mono_thread_info_is_async_context ();
6647 mono_thread_info_set_is_async_context (TRUE
);
6649 SummarizerSupervisorState synch
;
6650 if (summarizer_supervisor_start (&synch
)) {
6652 success
= mono_threads_summarize_execute_internal (ctx
, out
, hashes
, silent
, mem
, provided_size
, TRUE
);
6653 summarizer_supervisor_end (&synch
);
6657 mono_thread_info_set_is_async_context (FALSE
);
6659 // Only the thread that gets the ticket can unblock future dumpers.
6660 mono_atomic_inc_i64 ((volatile gint64
*) &request_available_to_run
);
6662 } else if (signal_handler_controller
) {
6663 // We're done. We can't do anything.
6664 g_async_safe_printf ("Attempted to dump for critical failure when already in dump. Error reporting crashed?");
6665 mono_summarize_double_fault_log ();
6669 g_async_safe_printf ("Waiting for in-flight dump to complete.");
6679 #ifdef ENABLE_NETCORE
6681 ves_icall_System_Threading_Thread_StartInternal (MonoThreadObjectHandle thread_handle
, MonoError
*error
)
6683 MonoThread
*internal
= MONO_HANDLE_RAW (thread_handle
);
6686 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p)", __func__
, internal
));
6688 LOCK_THREAD (internal
);
6690 if ((internal
->state
& ThreadState_Unstarted
) == 0) {
6691 UNLOCK_THREAD (internal
);
6692 mono_error_set_exception_thread_state (error
, "Thread has already been started.");
6696 if ((internal
->state
& ThreadState_Aborted
) != 0) {
6697 UNLOCK_THREAD (internal
);
6701 res
= create_thread (internal
, internal
, NULL
, NULL
, NULL
, MONO_THREAD_CREATE_FLAGS_NONE
, error
);
6703 UNLOCK_THREAD (internal
);
6707 internal
->state
&= ~ThreadState_Unstarted
;
6709 THREAD_DEBUG (g_message ("%s: Started thread ID %" G_GSIZE_FORMAT
" (handle %p)", __func__
, (gsize
)internal
->tid
, internal
->handle
));
6711 UNLOCK_THREAD (internal
);
6715 ves_icall_System_Threading_Thread_InitInternal (MonoThreadObjectHandle thread_handle
, MonoError
*error
)
6717 MonoThread
*internal
= MONO_HANDLE_RAW (thread_handle
);
6719 // Need to initialize thread objects created from managed code
6720 init_internal_thread_object (internal
);
6721 internal
->state
= ThreadState_Unstarted
;
6722 MONO_OBJECT_SETREF_INTERNAL (internal
, internal_thread
, internal
);
6726 ves_icall_System_Threading_Thread_GetCurrentOSThreadId (MonoError
*error
)
6728 return mono_native_thread_os_id_get ();