2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
19 #if defined(__OpenBSD__)
21 #include <pthread_np.h>
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/domain-internals.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/threadpool.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/environment.h>
32 #include <mono/metadata/monitor.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/marshal.h>
35 #include <mono/io-layer/io-layer.h>
37 #include <mono/io-layer/threads.h>
39 #include <mono/metadata/object-internals.h>
40 #include <mono/metadata/mono-debug-debugger.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-mmap.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-time.h>
46 #include <mono/metadata/gc-internal.h>
48 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
49 #define THREAD_DEBUG(a)
50 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
51 #define THREAD_WAIT_DEBUG(a)
52 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
53 #define LIBGC_DEBUG(a)
55 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
56 #define SPIN_LOCK(i) do { \
57 if (SPIN_TRYLOCK (i)) \
61 #define SPIN_UNLOCK(i) i = 0
63 /* Provide this for systems with glib < 2.6 */
64 #ifndef G_GSIZE_FORMAT
65 # if GLIB_SIZEOF_LONG == 8
66 # define G_GSIZE_FORMAT "lu"
68 # define G_GSIZE_FORMAT "u"
74 guint32 (*func
)(void *);
90 typedef struct _MonoThreadDomainTls MonoThreadDomainTls
;
91 struct _MonoThreadDomainTls
{
92 MonoThreadDomainTls
*next
;
100 MonoThreadDomainTls
*freelist
;
105 MonoHazardousFreeFunc free_func
;
108 /* Number of cached culture objects in the MonoThread->cached_culture_info array
109 * (per-type): we use the first NUM entries for CultureInfo and the last for
110 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
112 #define NUM_CACHED_CULTURES 4
113 #define CULTURES_START_IDX 0
114 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
116 /* Controls access to the 'threads' hash table */
117 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
118 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
119 static CRITICAL_SECTION threads_mutex
;
121 /* Controls access to context static data */
122 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
123 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
124 static CRITICAL_SECTION contexts_mutex
;
126 /* Holds current status of static data heap */
127 static StaticDataInfo thread_static_info
;
128 static StaticDataInfo context_static_info
;
130 /* The hash of existing threads (key is thread ID, value is
131 * MonoInternalThread*) that need joining before exit
133 static MonoGHashTable
*threads
=NULL
;
136 * Threads which are starting up and they are not in the 'threads' hash yet.
137 * When handle_store is called for a thread, it will be removed from this hash table.
138 * Protected by mono_threads_lock ().
140 static MonoGHashTable
*threads_starting_up
= NULL
;
142 /* Maps a MonoThread to its start argument */
143 /* Protected by mono_threads_lock () */
144 static MonoGHashTable
*thread_start_args
= NULL
;
146 /* The TLS key that holds the MonoObject assigned to each thread */
147 static guint32 current_object_key
= -1;
149 #ifdef HAVE_KW_THREAD
150 /* we need to use both the Tls* functions and __thread because
151 * the gc needs to see all the threads
153 static __thread MonoInternalThread
* tls_current_object MONO_TLS_FAST
;
154 #define SET_CURRENT_OBJECT(x) do { \
155 tls_current_object = x; \
156 TlsSetValue (current_object_key, x); \
158 #define GET_CURRENT_OBJECT() tls_current_object
160 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
161 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
164 /* function called at thread start */
165 static MonoThreadStartCB mono_thread_start_cb
= NULL
;
167 /* function called at thread attach */
168 static MonoThreadAttachCB mono_thread_attach_cb
= NULL
;
170 /* function called at thread cleanup */
171 static MonoThreadCleanupFunc mono_thread_cleanup_fn
= NULL
;
173 /* function called to notify the runtime about a pending exception on the current thread */
174 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn
= NULL
;
176 /* The default stack size for each thread */
177 static guint32 default_stacksize
= 0;
178 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
180 static void thread_adjust_static_data (MonoInternalThread
*thread
);
181 static void mono_free_static_data (gpointer
* static_data
, gboolean threadlocal
);
182 static void mono_init_static_data_info (StaticDataInfo
*static_data
);
183 static guint32
mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
);
184 static gboolean
mono_thread_resume (MonoInternalThread
* thread
);
185 static void mono_thread_start (MonoThread
*thread
);
186 static void signal_thread_state_change (MonoInternalThread
*thread
);
188 static MonoException
* mono_thread_execute_interruption (MonoInternalThread
*thread
);
190 /* Spin lock for InterlockedXXX 64 bit functions */
191 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
192 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
193 static CRITICAL_SECTION interlocked_mutex
;
195 /* global count of thread interruptions requested */
196 static gint32 thread_interruption_requested
= 0;
198 /* Event signaled when a thread changes its background mode */
199 static HANDLE background_change_event
;
201 /* The table for small ID assignment */
202 static CRITICAL_SECTION small_id_mutex
;
203 static int small_id_table_size
= 0;
204 static int small_id_next
= 0;
205 static int highest_small_id
= -1;
206 static MonoInternalThread
**small_id_table
= NULL
;
208 /* The hazard table */
209 #if MONO_SMALL_CONFIG
210 #define HAZARD_TABLE_MAX_SIZE 256
212 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
214 static volatile int hazard_table_size
= 0;
215 static MonoThreadHazardPointers
* volatile hazard_table
= NULL
;
217 /* The table where we keep pointers to blocks to be freed but that
218 have to wait because they're guarded by a hazard pointer. */
219 static CRITICAL_SECTION delayed_free_table_mutex
;
220 static GArray
*delayed_free_table
= NULL
;
222 static gboolean shutting_down
= FALSE
;
225 mono_thread_get_tls_key (void)
227 return current_object_key
;
231 mono_thread_get_tls_offset (void)
234 MONO_THREAD_VAR_OFFSET (tls_current_object
,offset
);
238 /* handle_store() and handle_remove() manage the array of threads that
239 * still need to be waited for when the main thread exits.
241 * If handle_store() returns FALSE the thread must not be started
242 * because Mono is shutting down.
244 static gboolean
handle_store(MonoThread
*thread
)
246 mono_threads_lock ();
248 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT
, __func__
, thread
, (gsize
)thread
->tid
));
250 if (threads_starting_up
)
251 mono_g_hash_table_remove (threads_starting_up
, thread
);
254 mono_threads_unlock ();
259 MONO_GC_REGISTER_ROOT (threads
);
260 threads
=mono_g_hash_table_new_type (NULL
, NULL
, MONO_HASH_VALUE_GC
);
263 /* We don't need to duplicate thread->handle, because it is
264 * only closed when the thread object is finalized by the GC.
266 g_assert (thread
->internal_thread
);
267 mono_g_hash_table_insert(threads
, (gpointer
)(gsize
)(thread
->internal_thread
->tid
),
268 thread
->internal_thread
);
270 mono_threads_unlock ();
275 static gboolean
handle_remove(MonoInternalThread
*thread
)
278 gsize tid
= thread
->tid
;
280 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT
, __func__
, tid
));
282 mono_threads_lock ();
285 /* We have to check whether the thread object for the
286 * tid is still the same in the table because the
287 * thread might have been destroyed and the tid reused
288 * in the meantime, in which case the tid would be in
289 * the table, but with another thread object.
291 if (mono_g_hash_table_lookup (threads
, (gpointer
)tid
) == thread
) {
292 mono_g_hash_table_remove (threads
, (gpointer
)tid
);
301 mono_threads_unlock ();
303 /* Don't close the handle here, wait for the object finalizer
304 * to do it. Otherwise, the following race condition applies:
306 * 1) Thread exits (and handle_remove() closes the handle)
308 * 2) Some other handle is reassigned the same slot
310 * 3) Another thread tries to join the first thread, and
311 * blocks waiting for the reassigned handle to be signalled
312 * (which might never happen). This is possible, because the
313 * thread calling Join() still has a reference to the first
320 * Allocate a small thread id.
322 * FIXME: The biggest part of this function is very similar to
323 * domain_id_alloc() in domain.c and should be merged.
326 small_id_alloc (MonoInternalThread
*thread
)
330 EnterCriticalSection (&small_id_mutex
);
332 if (!small_id_table
) {
333 small_id_table_size
= 2;
334 small_id_table
= mono_gc_alloc_fixed (small_id_table_size
* sizeof (MonoInternalThread
*), NULL
);
336 for (i
= small_id_next
; i
< small_id_table_size
; ++i
) {
337 if (!small_id_table
[i
]) {
343 for (i
= 0; i
< small_id_next
; ++i
) {
344 if (!small_id_table
[i
]) {
351 MonoInternalThread
**new_table
;
352 int new_size
= small_id_table_size
* 2;
353 if (new_size
>= (1 << 16))
354 g_assert_not_reached ();
355 id
= small_id_table_size
;
356 new_table
= mono_gc_alloc_fixed (new_size
* sizeof (MonoInternalThread
*), NULL
);
357 memcpy (new_table
, small_id_table
, small_id_table_size
* sizeof (void*));
358 mono_gc_free_fixed (small_id_table
);
359 small_id_table
= new_table
;
360 small_id_table_size
= new_size
;
362 thread
->small_id
= id
;
363 g_assert (small_id_table
[id
] == NULL
);
364 small_id_table
[id
] = thread
;
366 if (small_id_next
> small_id_table_size
)
369 g_assert (id
< HAZARD_TABLE_MAX_SIZE
);
370 if (id
>= hazard_table_size
) {
371 #if MONO_SMALL_CONFIG
372 hazard_table
= g_malloc0 (sizeof (MonoThreadHazardPointers
) * HAZARD_TABLE_MAX_SIZE
);
373 hazard_table_size
= HAZARD_TABLE_MAX_SIZE
;
376 int pagesize
= mono_pagesize ();
377 int num_pages
= (hazard_table_size
* sizeof (MonoThreadHazardPointers
) + pagesize
- 1) / pagesize
;
379 if (hazard_table
== NULL
) {
380 hazard_table
= mono_valloc (NULL
,
381 sizeof (MonoThreadHazardPointers
) * HAZARD_TABLE_MAX_SIZE
,
385 g_assert (hazard_table
!= NULL
);
386 page_addr
= (guint8
*)hazard_table
+ num_pages
* pagesize
;
388 mono_mprotect (page_addr
, pagesize
, MONO_MMAP_READ
| MONO_MMAP_WRITE
);
391 hazard_table_size
= num_pages
* pagesize
/ sizeof (MonoThreadHazardPointers
);
394 g_assert (id
< hazard_table_size
);
395 hazard_table
[id
].hazard_pointers
[0] = NULL
;
396 hazard_table
[id
].hazard_pointers
[1] = NULL
;
399 if (id
> highest_small_id
) {
400 highest_small_id
= id
;
401 mono_memory_write_barrier ();
404 LeaveCriticalSection (&small_id_mutex
);
410 small_id_free (int id
)
412 g_assert (id
>= 0 && id
< small_id_table_size
);
413 g_assert (small_id_table
[id
] != NULL
);
415 small_id_table
[id
] = NULL
;
419 is_pointer_hazardous (gpointer p
)
422 int highest
= highest_small_id
;
424 g_assert (highest
< hazard_table_size
);
426 for (i
= 0; i
<= highest
; ++i
) {
427 if (hazard_table
[i
].hazard_pointers
[0] == p
428 || hazard_table
[i
].hazard_pointers
[1] == p
)
435 MonoThreadHazardPointers
*
436 mono_hazard_pointer_get (void)
438 MonoInternalThread
*current_thread
= mono_thread_internal_current ();
440 if (!(current_thread
&& current_thread
->small_id
>= 0)) {
441 static MonoThreadHazardPointers emerg_hazard_table
;
442 g_warning ("Thread %p may have been prematurely finalized", current_thread
);
443 return &emerg_hazard_table
;
446 return &hazard_table
[current_thread
->small_id
];
450 try_free_delayed_free_item (int index
)
452 if (delayed_free_table
->len
> index
) {
453 DelayedFreeItem item
= { NULL
, NULL
};
455 EnterCriticalSection (&delayed_free_table_mutex
);
456 /* We have to check the length again because another
457 thread might have freed an item before we acquired
459 if (delayed_free_table
->len
> index
) {
460 item
= g_array_index (delayed_free_table
, DelayedFreeItem
, index
);
462 if (!is_pointer_hazardous (item
.p
))
463 g_array_remove_index_fast (delayed_free_table
, index
);
467 LeaveCriticalSection (&delayed_free_table_mutex
);
470 item
.free_func (item
.p
);
475 mono_thread_hazardous_free_or_queue (gpointer p
, MonoHazardousFreeFunc free_func
)
479 /* First try to free a few entries in the delayed free
481 for (i
= 2; i
>= 0; --i
)
482 try_free_delayed_free_item (i
);
484 /* Now see if the pointer we're freeing is hazardous. If it
485 isn't, free it. Otherwise put it in the delay list. */
486 if (is_pointer_hazardous (p
)) {
487 DelayedFreeItem item
= { p
, free_func
};
489 ++mono_stats
.hazardous_pointer_count
;
491 EnterCriticalSection (&delayed_free_table_mutex
);
492 g_array_append_val (delayed_free_table
, item
);
493 LeaveCriticalSection (&delayed_free_table_mutex
);
499 mono_thread_hazardous_try_free_all (void)
504 if (!delayed_free_table
)
507 len
= delayed_free_table
->len
;
509 for (i
= len
- 1; i
>= 0; --i
)
510 try_free_delayed_free_item (i
);
513 static void ensure_synch_cs_set (MonoInternalThread
*thread
)
515 CRITICAL_SECTION
*synch_cs
;
517 if (thread
->synch_cs
!= NULL
) {
521 synch_cs
= g_new0 (CRITICAL_SECTION
, 1);
522 InitializeCriticalSection (synch_cs
);
524 if (InterlockedCompareExchangePointer ((gpointer
*)&thread
->synch_cs
,
525 synch_cs
, NULL
) != NULL
) {
526 /* Another thread must have installed this CS */
527 DeleteCriticalSection (synch_cs
);
533 * NOTE: this function can be called also for threads different from the current one:
534 * make sure no code called from it will ever assume it is run on the thread that is
535 * getting cleaned up.
537 static void thread_cleanup (MonoInternalThread
*thread
)
539 g_assert (thread
!= NULL
);
541 if (thread
->abort_state_handle
) {
542 mono_gchandle_free (thread
->abort_state_handle
);
543 thread
->abort_state_handle
= 0;
545 thread
->abort_exc
= NULL
;
546 thread
->current_appcontext
= NULL
;
549 * This is necessary because otherwise we might have
550 * cross-domain references which will not get cleaned up when
551 * the target domain is unloaded.
553 if (thread
->cached_culture_info
) {
555 for (i
= 0; i
< NUM_CACHED_CULTURES
* 2; ++i
)
556 mono_array_set (thread
->cached_culture_info
, MonoObject
*, i
, NULL
);
559 /* if the thread is not in the hash it has been removed already */
560 if (!handle_remove (thread
))
562 mono_release_type_locks (thread
);
564 EnterCriticalSection (thread
->synch_cs
);
566 thread
->state
|= ThreadState_Stopped
;
567 thread
->state
&= ~ThreadState_Background
;
569 LeaveCriticalSection (thread
->synch_cs
);
571 mono_profiler_thread_end (thread
->tid
);
573 if (thread
== mono_thread_internal_current ())
574 mono_thread_pop_appdomain_ref ();
576 thread
->cached_culture_info
= NULL
;
578 mono_free_static_data (thread
->static_data
, TRUE
);
579 thread
->static_data
= NULL
;
582 * FIXME: The check for shutting_down here is a kludge and
583 * should be removed. The reason we need it here is because
584 * mono_thread_manage() does not wait for finalizer threads,
585 * so we might still be at this point in a finalizer thread
586 * after the main thread has cleared the root domain, so
587 * thread could have been zeroed out.
589 if (mono_thread_cleanup_fn
&& !shutting_down
)
590 mono_thread_cleanup_fn (thread
->root_domain_thread
);
592 small_id_free (thread
->small_id
);
593 thread
->small_id
= -2;
597 get_thread_static_data (MonoInternalThread
*thread
, guint32 offset
)
600 g_assert ((offset
& 0x80000000) == 0);
601 offset
&= 0x7fffffff;
602 idx
= (offset
>> 24) - 1;
603 return ((char*) thread
->static_data
[idx
]) + (offset
& 0xffffff);
607 get_current_thread_ptr_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
)
609 static MonoClassField
*current_thread_field
= NULL
;
613 if (!current_thread_field
) {
614 current_thread_field
= mono_class_get_field_from_name (mono_defaults
.thread_class
, "current_thread");
615 g_assert (current_thread_field
);
618 mono_class_vtable (domain
, mono_defaults
.thread_class
);
619 mono_domain_lock (domain
);
620 offset
= GPOINTER_TO_UINT (g_hash_table_lookup (domain
->special_static_fields
, current_thread_field
));
621 mono_domain_unlock (domain
);
624 return get_thread_static_data (thread
, offset
);
628 set_current_thread_for_domain (MonoDomain
*domain
, MonoInternalThread
*thread
, MonoThread
*current
)
630 MonoThread
**current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, thread
);
632 g_assert (current
->obj
.vtable
->domain
== domain
);
634 g_assert (!*current_thread_ptr
);
635 *current_thread_ptr
= current
;
639 new_thread_with_internal (MonoDomain
*domain
, MonoInternalThread
*internal
)
641 MonoThread
*thread
= (MonoThread
*) mono_object_new (domain
, mono_defaults
.thread_class
);
642 MONO_OBJECT_SETREF (thread
, internal_thread
, internal
);
647 init_root_domain_thread (MonoInternalThread
*thread
, MonoThread
*candidate
)
649 MonoDomain
*domain
= mono_get_root_domain ();
651 if (!candidate
|| candidate
->obj
.vtable
->domain
!= domain
)
652 candidate
= new_thread_with_internal (domain
, thread
);
653 set_current_thread_for_domain (domain
, thread
, candidate
);
654 g_assert (!thread
->root_domain_thread
);
655 MONO_OBJECT_SETREF (thread
, root_domain_thread
, candidate
);
658 static guint32 WINAPI
start_wrapper(void *data
)
660 struct StartInfo
*start_info
=(struct StartInfo
*)data
;
661 guint32 (*start_func
)(void *);
664 MonoThread
*thread
=start_info
->obj
;
665 MonoInternalThread
*internal
= thread
->internal_thread
;
666 MonoObject
*start_delegate
= start_info
->delegate
;
668 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Start wrapper", __func__
, GetCurrentThreadId ()));
670 /* We can be sure start_info->obj->tid and
671 * start_info->obj->handle have been set, because the thread
672 * was created suspended, and these values were set before the
678 SET_CURRENT_OBJECT (internal
);
680 mono_monitor_init_tls ();
682 /* Every thread references the appdomain which created it */
683 mono_thread_push_appdomain_ref (thread
->obj
.vtable
->domain
);
685 if (!mono_domain_set (thread
->obj
.vtable
->domain
, FALSE
)) {
686 /* No point in raising an appdomain_unloaded exception here */
687 /* FIXME: Cleanup here */
688 mono_thread_pop_appdomain_ref ();
692 start_func
= start_info
->func
;
693 start_arg
= start_info
->start_arg
;
695 /* We have to do this here because mono_thread_new_init()
696 requires that root_domain_thread is set up. */
697 thread_adjust_static_data (internal
);
698 init_root_domain_thread (internal
, thread
);
700 /* This MUST be called before any managed code can be
701 * executed, as it calls the callback function that (for the
702 * jit) sets the lmf marker.
704 mono_thread_new_init (tid
, &tid
, start_func
);
705 internal
->stack_ptr
= &tid
;
707 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
",%d) Setting thread stack to %p", __func__
, GetCurrentThreadId (), getpid (), thread
->stack_ptr
));
709 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Setting current_object_key to %p", __func__
, GetCurrentThreadId (), thread
));
711 /* On 2.0 profile (and higher), set explicitly since state might have been
713 if (internal
->apartment_state
== ThreadApartmentState_Unknown
)
714 internal
->apartment_state
= ThreadApartmentState_MTA
;
716 mono_thread_init_apartment_state ();
718 if(internal
->start_notify
!=NULL
) {
719 /* Let the thread that called Start() know we're
722 ReleaseSemaphore (internal
->start_notify
, 1, NULL
);
725 mono_threads_lock ();
726 mono_g_hash_table_remove (thread_start_args
, thread
);
727 mono_threads_unlock ();
731 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT
, __func__
,
735 mono_thread_set_execution_context (thread
->ec_to_set
);
736 thread
->ec_to_set
= NULL
;
739 * Call this after calling start_notify, since the profiler callback might want
740 * to lock the thread, and the lock is held by thread_start () which waits for
743 mono_profiler_thread_start (tid
);
745 /* start_func is set only for unmanaged start functions */
747 start_func (start_arg
);
750 g_assert (start_delegate
!= NULL
);
751 args
[0] = start_arg
;
752 /* we may want to handle the exception here. See comment below on unhandled exceptions */
753 mono_runtime_delegate_invoke (start_delegate
, args
, NULL
);
756 /* If the thread calls ExitThread at all, this remaining code
757 * will not be executed, but the main thread will eventually
758 * call thread_cleanup() on this thread's behalf.
761 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Start wrapper terminating", __func__
, GetCurrentThreadId ()));
763 thread_cleanup (internal
);
765 /* Do any cleanup needed for apartment state. This
766 * cannot be done in thread_cleanup since thread_cleanup could be
767 * called for a thread other than the current thread.
768 * mono_thread_cleanup_apartment_state cleans up apartment
769 * for the current thead */
770 mono_thread_cleanup_apartment_state ();
772 /* Remove the reference to the thread object in the TLS data,
773 * so the thread object can be finalized. This won't be
774 * reached if the thread threw an uncaught exception, so those
775 * thread handles will stay referenced :-( (This is due to
776 * missing support for scanning thread-specific data in the
777 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
780 SET_CURRENT_OBJECT (NULL
);
781 mono_domain_unset ();
786 void mono_thread_new_init (intptr_t tid
, gpointer stack_start
, gpointer func
)
788 if (mono_thread_start_cb
) {
789 mono_thread_start_cb (tid
, stack_start
, func
);
793 void mono_threads_set_default_stacksize (guint32 stacksize
)
795 default_stacksize
= stacksize
;
798 guint32
mono_threads_get_default_stacksize (void)
800 return default_stacksize
;
804 * mono_create_thread:
806 * This is a wrapper around CreateThread which handles differences in the type of
807 * the the 'tid' argument.
809 gpointer
mono_create_thread (WapiSecurityAttributes
*security
,
810 guint32 stacksize
, WapiThreadStart start
,
811 gpointer param
, guint32 create
, gsize
*tid
)
818 res
= CreateThread (security
, stacksize
, start
, param
, create
, &real_tid
);
822 res
= CreateThread (security
, stacksize
, start
, param
, create
, tid
);
829 * The thread start argument may be an object reference, and there is
830 * no ref to keep it alive when the new thread is started but not yet
831 * registered with the collector. So we store it in a GC tracked hash
834 * LOCKING: Assumes the threads lock is held.
837 register_thread_start_argument (MonoThread
*thread
, struct StartInfo
*start_info
)
839 if (thread_start_args
== NULL
) {
840 MONO_GC_REGISTER_ROOT (thread_start_args
);
841 thread_start_args
= mono_g_hash_table_new (NULL
, NULL
);
843 mono_g_hash_table_insert (thread_start_args
, thread
, start_info
->start_arg
);
846 MonoInternalThread
* mono_thread_create_internal (MonoDomain
*domain
, gpointer func
, gpointer arg
, gboolean threadpool_thread
)
849 MonoInternalThread
*internal
;
850 HANDLE thread_handle
;
851 struct StartInfo
*start_info
;
854 thread
=(MonoThread
*)mono_object_new (domain
,
855 mono_defaults
.thread_class
);
856 internal
= (MonoInternalThread
*)mono_object_new (mono_get_root_domain (),
857 mono_defaults
.internal_thread_class
);
858 MONO_OBJECT_SETREF (thread
, internal_thread
, internal
);
860 start_info
=g_new0 (struct StartInfo
, 1);
861 start_info
->func
= func
;
862 start_info
->obj
= thread
;
863 start_info
->start_arg
= arg
;
865 mono_threads_lock ();
867 mono_threads_unlock ();
871 if (threads_starting_up
== NULL
) {
872 MONO_GC_REGISTER_ROOT (threads_starting_up
);
873 threads_starting_up
= mono_g_hash_table_new_type (NULL
, NULL
, MONO_HASH_KEY_VALUE_GC
);
876 register_thread_start_argument (thread
, start_info
);
877 mono_g_hash_table_insert (threads_starting_up
, thread
, thread
);
878 mono_threads_unlock ();
880 /* Create suspended, so we can do some housekeeping before the thread
883 thread_handle
= mono_create_thread (NULL
, default_stacksize_for_thread (internal
), (LPTHREAD_START_ROUTINE
)start_wrapper
, start_info
,
884 CREATE_SUSPENDED
, &tid
);
885 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, thread_handle
));
886 if (thread_handle
== NULL
) {
887 /* The thread couldn't be created, so throw an exception */
888 mono_threads_lock ();
889 mono_g_hash_table_remove (threads_starting_up
, thread
);
890 mono_threads_unlock ();
892 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
896 internal
->handle
=thread_handle
;
898 internal
->apartment_state
=ThreadApartmentState_Unknown
;
899 small_id_alloc (internal
);
901 internal
->synch_cs
= g_new0 (CRITICAL_SECTION
, 1);
902 InitializeCriticalSection (internal
->synch_cs
);
904 internal
->threadpool_thread
= threadpool_thread
;
905 if (threadpool_thread
)
906 mono_thread_set_state (internal
, ThreadState_Background
);
908 if (handle_store (thread
))
909 ResumeThread (thread_handle
);
915 mono_thread_create (MonoDomain
*domain
, gpointer func
, gpointer arg
)
917 mono_thread_create_internal (domain
, func
, arg
, FALSE
);
921 * mono_thread_get_stack_bounds:
923 * Return the address and size of the current threads stack. Return NULL as the
924 * stack address if the stack address cannot be determined.
927 mono_thread_get_stack_bounds (guint8
**staddr
, size_t *stsize
)
929 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
930 *staddr
= (guint8
*)pthread_get_stackaddr_np (pthread_self ());
931 *stsize
= pthread_get_stacksize_np (pthread_self ());
932 *staddr
= (guint8
*)((gssize
)*staddr
& ~(mono_pagesize () - 1));
934 /* FIXME: simplify the mess below */
935 #elif !defined(HOST_WIN32)
937 guint8
*current
= (guint8
*)&attr
;
939 pthread_attr_init (&attr
);
940 # ifdef HAVE_PTHREAD_GETATTR_NP
941 pthread_getattr_np (pthread_self(), &attr
);
943 # ifdef HAVE_PTHREAD_ATTR_GET_NP
944 pthread_attr_get_np (pthread_self(), &attr
);
947 pthread_attr_getstacksize (&attr
, &stsize
);
948 # elif defined(__OpenBSD__)
952 rslt
= pthread_stackseg_np(pthread_self(), &ss
);
953 g_assert (rslt
== 0);
955 *staddr
= (guint8
*)((size_t)ss
.ss_sp
- ss
.ss_size
);
956 *stsize
= ss
.ss_size
;
965 # if !defined(__OpenBSD__)
966 pthread_attr_getstack (&attr
, (void**)staddr
, stsize
);
969 g_assert ((current
> *staddr
) && (current
< *staddr
+ *stsize
));
972 pthread_attr_destroy (&attr
);
975 /* When running under emacs, sometimes staddr is not aligned to a page size */
976 *staddr
= (guint8
*)((gssize
)*staddr
& ~(mono_pagesize () - 1));
980 mono_thread_attach (MonoDomain
*domain
)
982 MonoInternalThread
*thread
;
983 MonoThread
*current_thread
;
984 HANDLE thread_handle
;
987 if ((thread
= mono_thread_internal_current ())) {
988 if (domain
!= mono_domain_get ())
989 mono_domain_set (domain
, TRUE
);
990 /* Already attached */
991 return mono_thread_current ();
994 if (!mono_gc_register_thread (&domain
)) {
995 g_error ("Thread %"G_GSIZE_FORMAT
" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
998 thread
= (MonoInternalThread
*)mono_object_new (domain
, mono_defaults
.internal_thread_class
);
1000 thread_handle
= GetCurrentThread ();
1001 g_assert (thread_handle
);
1003 tid
=GetCurrentThreadId ();
1006 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
1007 * refer to the thread from other threads for things like aborting.
1009 DuplicateHandle (GetCurrentProcess (), thread_handle
, GetCurrentProcess (), &thread_handle
,
1010 THREAD_ALL_ACCESS
, TRUE
, 0);
1012 thread
->handle
=thread_handle
;
1014 thread
->apartment_state
=ThreadApartmentState_Unknown
;
1015 small_id_alloc (thread
);
1016 thread
->stack_ptr
= &tid
;
1018 thread
->synch_cs
= g_new0 (CRITICAL_SECTION
, 1);
1019 InitializeCriticalSection (thread
->synch_cs
);
1021 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, thread_handle
));
1023 current_thread
= new_thread_with_internal (domain
, thread
);
1025 if (!handle_store (current_thread
)) {
1026 /* Mono is shutting down, so just wait for the end */
1031 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Setting current_object_key to %p", __func__
, GetCurrentThreadId (), thread
));
1033 SET_CURRENT_OBJECT (thread
);
1034 mono_domain_set (domain
, TRUE
);
1036 mono_monitor_init_tls ();
1038 thread_adjust_static_data (thread
);
1040 init_root_domain_thread (thread
, current_thread
);
1041 if (domain
!= mono_get_root_domain ())
1042 set_current_thread_for_domain (domain
, thread
, current_thread
);
1045 if (mono_thread_attach_cb
) {
1049 mono_thread_get_stack_bounds (&staddr
, &stsize
);
1052 mono_thread_attach_cb (tid
, &tid
);
1054 mono_thread_attach_cb (tid
, staddr
+ stsize
);
1057 // FIXME: Need a separate callback
1058 mono_profiler_thread_start (tid
);
1060 return current_thread
;
1064 mono_thread_detach (MonoThread
*thread
)
1066 g_return_if_fail (thread
!= NULL
);
1068 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
1070 thread_cleanup (thread
->internal_thread
);
1072 SET_CURRENT_OBJECT (NULL
);
1073 mono_domain_unset ();
1075 /* Don't need to CloseHandle this thread, even though we took a
1076 * reference in mono_thread_attach (), because the GC will do it
1077 * when the Thread object is finalised.
1084 MonoInternalThread
*thread
= mono_thread_internal_current ();
1086 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT
")", __func__
, thread
, (gsize
)thread
->tid
));
1088 thread_cleanup (thread
);
1089 SET_CURRENT_OBJECT (NULL
);
1090 mono_domain_unset ();
1092 /* we could add a callback here for embedders to use. */
1093 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
))
1094 exit (mono_environment_exitcode_get ());
1099 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread
*this)
1101 MonoInternalThread
*internal
= (MonoInternalThread
*)mono_object_new (mono_get_root_domain (), mono_defaults
.internal_thread_class
);
1102 internal
->state
= ThreadState_Unstarted
;
1103 internal
->apartment_state
= ThreadApartmentState_Unknown
;
1105 InterlockedCompareExchangePointer ((gpointer
)&this->internal_thread
, internal
, NULL
);
1108 HANDLE
ves_icall_System_Threading_Thread_Thread_internal(MonoThread
*this,
1111 guint32 (*start_func
)(void *);
1112 struct StartInfo
*start_info
;
1115 MonoInternalThread
*internal
;
1117 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__
, this, start
));
1119 if (!this->internal_thread
)
1120 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1121 internal
= this->internal_thread
;
1123 ensure_synch_cs_set (internal
);
1125 EnterCriticalSection (internal
->synch_cs
);
1127 if ((internal
->state
& ThreadState_Unstarted
) == 0) {
1128 LeaveCriticalSection (internal
->synch_cs
);
1129 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1133 internal
->small_id
= -1;
1135 if ((internal
->state
& ThreadState_Aborted
) != 0) {
1136 LeaveCriticalSection (internal
->synch_cs
);
1141 /* This is freed in start_wrapper */
1142 start_info
= g_new0 (struct StartInfo
, 1);
1143 start_info
->func
= start_func
;
1144 start_info
->start_arg
= this->start_obj
; /* FIXME: GC object stored in unmanaged memory */
1145 start_info
->delegate
= start
;
1146 start_info
->obj
= this;
1147 g_assert (this->obj
.vtable
->domain
== mono_domain_get ());
1149 internal
->start_notify
=CreateSemaphore (NULL
, 0, 0x7fffffff, NULL
);
1150 if (internal
->start_notify
==NULL
) {
1151 LeaveCriticalSection (internal
->synch_cs
);
1152 g_warning ("%s: CreateSemaphore error 0x%x", __func__
, GetLastError ());
1153 g_free (start_info
);
1157 mono_threads_lock ();
1158 register_thread_start_argument (this, start_info
);
1159 if (threads_starting_up
== NULL
) {
1160 MONO_GC_REGISTER_ROOT (threads_starting_up
);
1161 threads_starting_up
= mono_g_hash_table_new_type (NULL
, NULL
, MONO_HASH_KEY_VALUE_GC
);
1163 mono_g_hash_table_insert (threads_starting_up
, this, this);
1164 mono_threads_unlock ();
1166 thread
=mono_create_thread(NULL
, default_stacksize_for_thread (internal
), (LPTHREAD_START_ROUTINE
)start_wrapper
, start_info
,
1167 CREATE_SUSPENDED
, &tid
);
1169 LeaveCriticalSection (internal
->synch_cs
);
1170 mono_threads_lock ();
1171 mono_g_hash_table_remove (threads_starting_up
, this);
1172 mono_threads_unlock ();
1173 g_warning("%s: CreateThread error 0x%x", __func__
, GetLastError());
1177 internal
->handle
=thread
;
1179 small_id_alloc (internal
);
1181 /* Don't call handle_store() here, delay it to Start.
1182 * We can't join a thread (trying to will just block
1183 * forever) until it actually starts running, so don't
1184 * store the handle till then.
1187 mono_thread_start (this);
1189 internal
->state
&= ~ThreadState_Unstarted
;
1191 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT
" (handle %p)", __func__
, tid
, thread
));
1193 LeaveCriticalSection (internal
->synch_cs
);
1198 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread
*this, HANDLE thread
)
1200 MONO_ARCH_SAVE_REGS
;
1202 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__
, this, thread
));
1205 CloseHandle (thread
);
1207 if (this->synch_cs
) {
1208 DeleteCriticalSection (this->synch_cs
);
1209 g_free (this->synch_cs
);
1210 this->synch_cs
= NULL
;
1213 g_free (this->name
);
1216 static void mono_thread_start (MonoThread
*thread
)
1218 MonoInternalThread
*internal
= thread
->internal_thread
;
1220 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Launching thread %p (%"G_GSIZE_FORMAT
")", __func__
, GetCurrentThreadId (), thread
, (gsize
)thread
->tid
));
1222 /* Only store the handle when the thread is about to be
1223 * launched, to avoid the main thread deadlocking while trying
1224 * to clean up a thread that will never be signalled.
1226 if (!handle_store (thread
))
1229 ResumeThread (internal
->handle
);
1231 if(internal
->start_notify
!=NULL
) {
1232 /* Wait for the thread to set up its TLS data etc, so
1233 * theres no potential race condition if someone tries
1234 * to look up the data believing the thread has
1238 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") waiting for thread %p (%"G_GSIZE_FORMAT
") to start", __func__
, GetCurrentThreadId (), thread
, (gsize
)thread
->tid
));
1240 WaitForSingleObjectEx (internal
->start_notify
, INFINITE
, FALSE
);
1241 CloseHandle (internal
->start_notify
);
1242 internal
->start_notify
= NULL
;
1245 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Done launching thread %p (%"G_GSIZE_FORMAT
")", __func__
, GetCurrentThreadId (), thread
, (gsize
)thread
->tid
));
1248 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms
)
1251 MonoInternalThread
*thread
= mono_thread_internal_current ();
1253 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__
, ms
));
1255 mono_thread_current_check_pending_interrupt ();
1257 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1259 res
= SleepEx(ms
,TRUE
);
1261 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1263 if (res
== WAIT_IO_COMPLETION
) { /* we might have been interrupted */
1264 MonoException
* exc
= mono_thread_execute_interruption (thread
);
1265 if (exc
) mono_raise_exception (exc
);
1269 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1274 ves_icall_System_Threading_Thread_GetDomainID (void)
1276 MONO_ARCH_SAVE_REGS
;
1278 return mono_domain_get()->domain_id
;
1282 ves_icall_System_Threading_Thread_Yield (void)
1285 return SwitchToThread ();
1287 return sched_yield () == 0;
1292 * mono_thread_get_name:
1294 * Return the name of the thread. NAME_LEN is set to the length of the name.
1295 * Return NULL if the thread has no name. The returned memory is owned by the
1299 mono_thread_get_name (MonoInternalThread
*this_obj
, guint32
*name_len
)
1303 ensure_synch_cs_set (this_obj
);
1305 EnterCriticalSection (this_obj
->synch_cs
);
1307 if (!this_obj
->name
) {
1311 *name_len
= this_obj
->name_len
;
1312 res
= g_new (gunichar2
, this_obj
->name_len
);
1313 memcpy (res
, this_obj
->name
, sizeof (gunichar2
) * this_obj
->name_len
);
1316 LeaveCriticalSection (this_obj
->synch_cs
);
1322 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread
*this_obj
)
1326 ensure_synch_cs_set (this_obj
);
1328 EnterCriticalSection (this_obj
->synch_cs
);
1330 if (!this_obj
->name
)
1333 str
= mono_string_new_utf16 (mono_domain_get (), this_obj
->name
, this_obj
->name_len
);
1335 LeaveCriticalSection (this_obj
->synch_cs
);
1341 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread
*this_obj
, MonoString
*name
)
1343 ensure_synch_cs_set (this_obj
);
1345 EnterCriticalSection (this_obj
->synch_cs
);
1347 if (this_obj
->name
) {
1348 LeaveCriticalSection (this_obj
->synch_cs
);
1350 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1354 this_obj
->name
= g_new (gunichar2
, mono_string_length (name
));
1355 memcpy (this_obj
->name
, mono_string_chars (name
), mono_string_length (name
) * 2);
1356 this_obj
->name_len
= mono_string_length (name
);
1359 this_obj
->name
= NULL
;
1361 LeaveCriticalSection (this_obj
->synch_cs
);
1365 lookup_cached_culture (MonoInternalThread
*this, MonoDomain
*domain
, int start_idx
)
1370 if (this->cached_culture_info
) {
1371 domain
= mono_domain_get ();
1372 for (i
= start_idx
; i
< start_idx
+ NUM_CACHED_CULTURES
; ++i
) {
1373 res
= mono_array_get (this->cached_culture_info
, MonoObject
*, i
);
1374 if (res
&& res
->vtable
->domain
== domain
)
1382 /* If the array is already in the requested domain, we just return it,
1383 otherwise we return a copy in that domain. */
1385 byte_array_to_domain (MonoArray
*arr
, MonoDomain
*domain
)
1392 if (mono_object_domain (arr
) == domain
)
1395 copy
= mono_array_new (domain
, mono_defaults
.byte_class
, arr
->max_length
);
1396 memcpy (mono_array_addr (copy
, guint8
, 0), mono_array_addr (arr
, guint8
, 0), arr
->max_length
);
1401 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray
*arr
)
1403 return byte_array_to_domain (arr
, mono_get_root_domain ());
1407 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray
*arr
)
1409 return byte_array_to_domain (arr
, mono_domain_get ());
1413 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread
*this)
1415 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX
);
1419 cache_culture (MonoInternalThread
*this, MonoObject
*culture
, int start_idx
)
1422 MonoDomain
*domain
= mono_domain_get ();
1425 int same_domain_slot
= -1;
1427 ensure_synch_cs_set (this);
1429 EnterCriticalSection (this->synch_cs
);
1431 if (!this->cached_culture_info
)
1432 MONO_OBJECT_SETREF (this, cached_culture_info
, mono_array_new_cached (mono_get_root_domain (), mono_defaults
.object_class
, NUM_CACHED_CULTURES
* 2));
1434 for (i
= start_idx
; i
< start_idx
+ NUM_CACHED_CULTURES
; ++i
) {
1435 obj
= mono_array_get (this->cached_culture_info
, MonoObject
*, i
);
1439 /* we continue, because there may be a slot used with the same domain */
1443 if (obj
->vtable
->domain
== domain
) {
1444 same_domain_slot
= i
;
1448 if (same_domain_slot
>= 0)
1449 mono_array_setref (this->cached_culture_info
, same_domain_slot
, culture
);
1450 else if (free_slot
>= 0)
1451 mono_array_setref (this->cached_culture_info
, free_slot
, culture
);
1452 /* we may want to replace an existing entry here, even when no suitable slot is found */
1454 LeaveCriticalSection (this->synch_cs
);
1458 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread
*this, MonoObject
*culture
)
1460 MonoDomain
*domain
= mono_object_get_domain (&this->obj
);
1461 g_assert (domain
== mono_domain_get ());
1462 cache_culture (this->internal_thread
, culture
, CULTURES_START_IDX
);
1466 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread
*this)
1468 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX
);
1472 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread
*this, MonoObject
*culture
)
1474 MonoDomain
*domain
= mono_object_get_domain (&this->obj
);
1475 g_assert (domain
== mono_domain_get ());
1476 cache_culture (this->internal_thread
, culture
, UICULTURES_START_IDX
);
1480 mono_thread_current (void)
1482 MonoDomain
*domain
= mono_domain_get ();
1483 MonoInternalThread
*internal
= mono_thread_internal_current ();
1484 MonoThread
**current_thread_ptr
;
1486 g_assert (internal
);
1487 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
1489 if (!*current_thread_ptr
) {
1490 g_assert (domain
!= mono_get_root_domain ());
1491 *current_thread_ptr
= new_thread_with_internal (domain
, internal
);
1493 return *current_thread_ptr
;
1497 mono_thread_internal_current (void)
1499 MonoInternalThread
*res
= GET_CURRENT_OBJECT ();
1500 THREAD_DEBUG (g_message ("%s: returning %p", __func__
, res
));
1504 gboolean
ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread
*this,
1505 int ms
, HANDLE thread
)
1507 MonoInternalThread
*cur_thread
= mono_thread_internal_current ();
1510 mono_thread_current_check_pending_interrupt ();
1512 ensure_synch_cs_set (this);
1514 EnterCriticalSection (this->synch_cs
);
1516 if ((this->state
& ThreadState_Unstarted
) != 0) {
1517 LeaveCriticalSection (this->synch_cs
);
1519 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1523 LeaveCriticalSection (this->synch_cs
);
1528 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__
, thread
, ms
));
1530 mono_thread_set_state (cur_thread
, ThreadState_WaitSleepJoin
);
1532 ret
=WaitForSingleObjectEx (thread
, ms
, TRUE
);
1534 mono_thread_clr_state (cur_thread
, ThreadState_WaitSleepJoin
);
1536 if(ret
==WAIT_OBJECT_0
) {
1537 THREAD_DEBUG (g_message ("%s: join successful", __func__
));
1542 THREAD_DEBUG (g_message ("%s: join failed", __func__
));
1547 /* FIXME: exitContext isnt documented */
1548 gboolean
ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray
*mono_handles
, gint32 ms
, gboolean exitContext
)
1554 MonoObject
*waitHandle
;
1555 MonoInternalThread
*thread
= mono_thread_internal_current ();
1557 /* Do this WaitSleepJoin check before creating objects */
1558 mono_thread_current_check_pending_interrupt ();
1560 numhandles
= mono_array_length(mono_handles
);
1561 handles
= g_new0(HANDLE
, numhandles
);
1563 for(i
= 0; i
< numhandles
; i
++) {
1564 waitHandle
= mono_array_get(mono_handles
, MonoObject
*, i
);
1565 handles
[i
] = mono_wait_handle_get_handle ((MonoWaitHandle
*) waitHandle
);
1572 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1574 ret
=WaitForMultipleObjectsEx(numhandles
, handles
, TRUE
, ms
, TRUE
);
1576 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1580 if(ret
==WAIT_FAILED
) {
1581 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait failed", __func__
, GetCurrentThreadId ()));
1583 } else if(ret
==WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
) {
1584 /* Do we want to try again if we get
1585 * WAIT_IO_COMPLETION? The documentation for
1586 * WaitHandle doesn't give any clues. (We'd have to
1587 * fiddle with the timeout if we retry.)
1589 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait timed out", __func__
, GetCurrentThreadId ()));
1596 /* FIXME: exitContext isnt documented */
1597 gint32
ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray
*mono_handles
, gint32 ms
, gboolean exitContext
)
1603 MonoObject
*waitHandle
;
1604 MonoInternalThread
*thread
= mono_thread_internal_current ();
1606 /* Do this WaitSleepJoin check before creating objects */
1607 mono_thread_current_check_pending_interrupt ();
1609 numhandles
= mono_array_length(mono_handles
);
1610 handles
= g_new0(HANDLE
, numhandles
);
1612 for(i
= 0; i
< numhandles
; i
++) {
1613 waitHandle
= mono_array_get(mono_handles
, MonoObject
*, i
);
1614 handles
[i
] = mono_wait_handle_get_handle ((MonoWaitHandle
*) waitHandle
);
1621 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1623 ret
=WaitForMultipleObjectsEx(numhandles
, handles
, FALSE
, ms
, TRUE
);
1625 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1629 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") returning %d", __func__
, GetCurrentThreadId (), ret
));
1632 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1634 if (ret
>= WAIT_OBJECT_0
&& ret
<= WAIT_OBJECT_0
+ numhandles
- 1) {
1635 return ret
- WAIT_OBJECT_0
;
1637 else if (ret
>= WAIT_ABANDONED_0
&& ret
<= WAIT_ABANDONED_0
+ numhandles
- 1) {
1638 return ret
- WAIT_ABANDONED_0
;
1645 /* FIXME: exitContext isnt documented */
1646 gboolean
ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject
*this, HANDLE handle
, gint32 ms
, gboolean exitContext
)
1649 MonoInternalThread
*thread
= mono_thread_internal_current ();
1651 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") waiting for %p, %d ms", __func__
, GetCurrentThreadId (), handle
, ms
));
1657 mono_thread_current_check_pending_interrupt ();
1659 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1661 ret
=WaitForSingleObjectEx (handle
, ms
, TRUE
);
1663 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1665 if(ret
==WAIT_FAILED
) {
1666 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait failed", __func__
, GetCurrentThreadId ()));
1668 } else if(ret
==WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
) {
1669 /* Do we want to try again if we get
1670 * WAIT_IO_COMPLETION? The documentation for
1671 * WaitHandle doesn't give any clues. (We'd have to
1672 * fiddle with the timeout if we retry.)
1674 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait timed out", __func__
, GetCurrentThreadId ()));
1682 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal
, HANDLE toWait
, gint32 ms
, gboolean exitContext
)
1685 MonoInternalThread
*thread
= mono_thread_internal_current ();
1687 MONO_ARCH_SAVE_REGS
;
1692 mono_thread_current_check_pending_interrupt ();
1694 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1696 ret
= SignalObjectAndWait (toSignal
, toWait
, ms
, TRUE
);
1698 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1700 return (!(ret
== WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
|| ret
== WAIT_FAILED
));
1703 HANDLE
ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned
, MonoString
*name
, MonoBoolean
*created
)
1707 MONO_ARCH_SAVE_REGS
;
1712 mutex
= CreateMutex (NULL
, owned
, NULL
);
1714 mutex
= CreateMutex (NULL
, owned
, mono_string_chars (name
));
1716 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1724 MonoBoolean
ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle
) {
1725 MONO_ARCH_SAVE_REGS
;
1727 return(ReleaseMutex (handle
));
1730 HANDLE
ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString
*name
,
1736 MONO_ARCH_SAVE_REGS
;
1738 *error
= ERROR_SUCCESS
;
1740 ret
= OpenMutex (rights
, FALSE
, mono_string_chars (name
));
1742 *error
= GetLastError ();
1749 HANDLE
ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount
, gint32 maximumCount
, MonoString
*name
, MonoBoolean
*created
)
1753 MONO_ARCH_SAVE_REGS
;
1758 sem
= CreateSemaphore (NULL
, initialCount
, maximumCount
, NULL
);
1760 sem
= CreateSemaphore (NULL
, initialCount
, maximumCount
,
1761 mono_string_chars (name
));
1763 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1771 gint32
ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle
, gint32 releaseCount
, MonoBoolean
*fail
)
1775 MONO_ARCH_SAVE_REGS
;
1777 *fail
= !ReleaseSemaphore (handle
, releaseCount
, &prevcount
);
1782 HANDLE
ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString
*name
, gint32 rights
, gint32
*error
)
1786 MONO_ARCH_SAVE_REGS
;
1788 *error
= ERROR_SUCCESS
;
1790 ret
= OpenSemaphore (rights
, FALSE
, mono_string_chars (name
));
1792 *error
= GetLastError ();
1798 HANDLE
ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual
, MonoBoolean initial
, MonoString
*name
, MonoBoolean
*created
)
1802 MONO_ARCH_SAVE_REGS
;
1807 event
= CreateEvent (NULL
, manual
, initial
, NULL
);
1809 event
= CreateEvent (NULL
, manual
, initial
,
1810 mono_string_chars (name
));
1812 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1820 gboolean
ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle
) {
1821 MONO_ARCH_SAVE_REGS
;
1823 return (SetEvent(handle
));
1826 gboolean
ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle
) {
1827 MONO_ARCH_SAVE_REGS
;
1829 return (ResetEvent(handle
));
1833 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle
) {
1834 MONO_ARCH_SAVE_REGS
;
1836 CloseHandle (handle
);
1839 HANDLE
ves_icall_System_Threading_Events_OpenEvent_internal (MonoString
*name
,
1845 MONO_ARCH_SAVE_REGS
;
1847 *error
= ERROR_SUCCESS
;
1849 ret
= OpenEvent (rights
, FALSE
, mono_string_chars (name
));
1851 *error
= GetLastError ();
1857 gint32
ves_icall_System_Threading_Interlocked_Increment_Int (gint32
*location
)
1859 MONO_ARCH_SAVE_REGS
;
1861 return InterlockedIncrement (location
);
1864 gint64
ves_icall_System_Threading_Interlocked_Increment_Long (gint64
*location
)
1868 MONO_ARCH_SAVE_REGS
;
1870 mono_interlocked_lock ();
1874 mono_interlocked_unlock ();
1880 gint32
ves_icall_System_Threading_Interlocked_Decrement_Int (gint32
*location
)
1882 MONO_ARCH_SAVE_REGS
;
1884 return InterlockedDecrement(location
);
1887 gint64
ves_icall_System_Threading_Interlocked_Decrement_Long (gint64
* location
)
1891 MONO_ARCH_SAVE_REGS
;
1893 mono_interlocked_lock ();
1897 mono_interlocked_unlock ();
1902 gint32
ves_icall_System_Threading_Interlocked_Exchange_Int (gint32
*location
, gint32 value
)
1904 MONO_ARCH_SAVE_REGS
;
1906 return InterlockedExchange(location
, value
);
1909 MonoObject
* ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject
**location
, MonoObject
*value
)
1912 res
= (MonoObject
*) InterlockedExchangePointer((gpointer
*) location
, value
);
1913 mono_gc_wbarrier_generic_nostore (location
);
1917 gpointer
ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer
*location
, gpointer value
)
1919 return InterlockedExchangePointer(location
, value
);
1922 gfloat
ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat
*location
, gfloat value
)
1924 IntFloatUnion val
, ret
;
1926 MONO_ARCH_SAVE_REGS
;
1929 ret
.ival
= InterlockedExchange((gint32
*) location
, val
.ival
);
1935 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64
*location
, gint64 value
)
1937 #if SIZEOF_VOID_P == 8
1938 return (gint64
) InterlockedExchangePointer((gpointer
*) location
, (gpointer
)value
);
1943 * According to MSDN, this function is only atomic with regards to the
1944 * other Interlocked functions on 32 bit platforms.
1946 mono_interlocked_lock ();
1949 mono_interlocked_unlock ();
1956 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble
*location
, gdouble value
)
1958 #if SIZEOF_VOID_P == 8
1959 LongDoubleUnion val
, ret
;
1962 ret
.ival
= (gint64
)InterlockedExchangePointer((gpointer
*) location
, (gpointer
)val
.ival
);
1969 * According to MSDN, this function is only atomic with regards to the
1970 * other Interlocked functions on 32 bit platforms.
1972 mono_interlocked_lock ();
1975 mono_interlocked_unlock ();
1981 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32
*location
, gint32 value
, gint32 comparand
)
1983 MONO_ARCH_SAVE_REGS
;
1985 return InterlockedCompareExchange(location
, value
, comparand
);
1988 MonoObject
* ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
1991 res
= (MonoObject
*) InterlockedCompareExchangePointer((gpointer
*) location
, value
, comparand
);
1992 mono_gc_wbarrier_generic_nostore (location
);
1996 gpointer
ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer
*location
, gpointer value
, gpointer comparand
)
1998 return InterlockedCompareExchangePointer(location
, value
, comparand
);
2001 gfloat
ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat
*location
, gfloat value
, gfloat comparand
)
2003 IntFloatUnion val
, ret
, cmp
;
2005 MONO_ARCH_SAVE_REGS
;
2008 cmp
.fval
= comparand
;
2009 ret
.ival
= InterlockedCompareExchange((gint32
*) location
, val
.ival
, cmp
.ival
);
2015 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble
*location
, gdouble value
, gdouble comparand
)
2017 #if SIZEOF_VOID_P == 8
2018 LongDoubleUnion val
, comp
, ret
;
2021 comp
.fval
= comparand
;
2022 ret
.ival
= (gint64
)InterlockedCompareExchangePointer((gpointer
*) location
, (gpointer
)val
.ival
, (gpointer
)comp
.ival
);
2028 mono_interlocked_lock ();
2030 if (old
== comparand
)
2032 mono_interlocked_unlock ();
2039 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64
*location
, gint64 value
, gint64 comparand
)
2041 #if SIZEOF_VOID_P == 8
2042 return (gint64
)InterlockedCompareExchangePointer((gpointer
*) location
, (gpointer
)value
, (gpointer
)comparand
);
2046 mono_interlocked_lock ();
2048 if (old
== comparand
)
2050 mono_interlocked_unlock ();
2057 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
2060 res
= InterlockedCompareExchangePointer ((gpointer
*)location
, value
, comparand
);
2061 mono_gc_wbarrier_generic_nostore (location
);
2066 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject
**location
, MonoObject
*value
)
2069 res
= InterlockedExchangePointer ((gpointer
*)location
, value
);
2070 mono_gc_wbarrier_generic_nostore (location
);
2075 ves_icall_System_Threading_Interlocked_Add_Int (gint32
*location
, gint32 value
)
2077 #if SIZEOF_VOID_P == 8
2078 /* Should be implemented as a JIT intrinsic */
2079 mono_raise_exception (mono_get_exception_not_implemented (NULL
));
2084 mono_interlocked_lock ();
2086 *location
= orig
+ value
;
2087 mono_interlocked_unlock ();
2089 return orig
+ value
;
2094 ves_icall_System_Threading_Interlocked_Add_Long (gint64
*location
, gint64 value
)
2096 #if SIZEOF_VOID_P == 8
2097 /* Should be implemented as a JIT intrinsic */
2098 mono_raise_exception (mono_get_exception_not_implemented (NULL
));
2103 mono_interlocked_lock ();
2105 *location
= orig
+ value
;
2106 mono_interlocked_unlock ();
2108 return orig
+ value
;
2113 ves_icall_System_Threading_Interlocked_Read_Long (gint64
*location
)
2115 #if SIZEOF_VOID_P == 8
2116 /* 64 bit reads are already atomic */
2121 mono_interlocked_lock ();
2123 mono_interlocked_unlock ();
2130 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2132 mono_threads_lock ();
2133 mono_threads_unlock ();
2137 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread
* this, guint32 state
)
2139 mono_thread_clr_state (this, state
);
2141 if (state
& ThreadState_Background
) {
2142 /* If the thread changes the background mode, the main thread has to
2143 * be notified, since it has to rebuild the list of threads to
2146 SetEvent (background_change_event
);
2151 ves_icall_System_Threading_Thread_SetState (MonoInternalThread
* this, guint32 state
)
2153 mono_thread_set_state (this, state
);
2155 if (state
& ThreadState_Background
) {
2156 /* If the thread changes the background mode, the main thread has to
2157 * be notified, since it has to rebuild the list of threads to
2160 SetEvent (background_change_event
);
2165 ves_icall_System_Threading_Thread_GetState (MonoInternalThread
* this)
2169 ensure_synch_cs_set (this);
2171 EnterCriticalSection (this->synch_cs
);
2173 state
= this->state
;
2175 LeaveCriticalSection (this->synch_cs
);
2180 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread
*this)
2182 gboolean
throw = FALSE
;
2184 ensure_synch_cs_set (this);
2186 if (this == mono_thread_internal_current ())
2189 EnterCriticalSection (this->synch_cs
);
2191 this->thread_interrupt_requested
= TRUE
;
2193 if (this->state
& ThreadState_WaitSleepJoin
) {
2197 LeaveCriticalSection (this->synch_cs
);
2200 signal_thread_state_change (this);
2204 void mono_thread_current_check_pending_interrupt ()
2206 MonoInternalThread
*thread
= mono_thread_internal_current ();
2207 gboolean
throw = FALSE
;
2209 mono_debugger_check_interruption ();
2211 ensure_synch_cs_set (thread
);
2213 EnterCriticalSection (thread
->synch_cs
);
2215 if (thread
->thread_interrupt_requested
) {
2217 thread
->thread_interrupt_requested
= FALSE
;
2220 LeaveCriticalSection (thread
->synch_cs
);
2223 mono_raise_exception (mono_get_exception_thread_interrupted ());
2228 mono_thread_get_abort_signal (void)
2240 static int abort_signum
= -1;
2242 if (abort_signum
!= -1)
2243 return abort_signum
;
2244 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2245 for (i
= SIGRTMIN
+ 1; i
< SIGRTMAX
; ++i
) {
2246 struct sigaction sinfo
;
2247 sigaction (i
, NULL
, &sinfo
);
2248 if (sinfo
.sa_handler
== SIG_DFL
&& (void*)sinfo
.sa_sigaction
== (void*)SIG_DFL
) {
2253 /* fallback to the old way */
2256 #endif /* HOST_WIN32 */
2260 static void CALLBACK
interruption_request_apc (ULONG_PTR param
)
2262 MonoException
* exc
= mono_thread_request_interruption (FALSE
);
2263 if (exc
) mono_raise_exception (exc
);
2265 #endif /* HOST_WIN32 */
2268 * signal_thread_state_change
2270 * Tells the thread that his state has changed and it has to enter the new
2271 * state as soon as possible.
2273 static void signal_thread_state_change (MonoInternalThread
*thread
)
2275 if (thread
== mono_thread_internal_current ()) {
2276 /* Do it synchronously */
2277 MonoException
*exc
= mono_thread_request_interruption (FALSE
);
2279 mono_raise_exception (exc
);
2283 QueueUserAPC ((PAPCFUNC
)interruption_request_apc
, thread
->handle
, NULL
);
2285 /* fixme: store the state somewhere */
2286 #ifdef PTHREAD_POINTER_ID
2287 pthread_kill ((gpointer
)(gsize
)(thread
->tid
), mono_thread_get_abort_signal ());
2289 pthread_kill (thread
->tid
, mono_thread_get_abort_signal ());
2293 * This will cause waits to be broken.
2294 * It will also prevent the thread from entering a wait, so if the thread returns
2295 * from the wait before it receives the abort signal, it will just spin in the wait
2296 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2299 wapi_interrupt_thread (thread
->handle
);
2300 #endif /* HOST_WIN32 */
2304 ves_icall_System_Threading_Thread_Abort (MonoInternalThread
*thread
, MonoObject
*state
)
2306 ensure_synch_cs_set (thread
);
2308 EnterCriticalSection (thread
->synch_cs
);
2310 if ((thread
->state
& ThreadState_AbortRequested
) != 0 ||
2311 (thread
->state
& ThreadState_StopRequested
) != 0 ||
2312 (thread
->state
& ThreadState_Stopped
) != 0)
2314 LeaveCriticalSection (thread
->synch_cs
);
2318 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
2319 thread
->state
|= ThreadState_Aborted
;
2320 LeaveCriticalSection (thread
->synch_cs
);
2324 thread
->state
|= ThreadState_AbortRequested
;
2325 if (thread
->abort_state_handle
)
2326 mono_gchandle_free (thread
->abort_state_handle
);
2328 thread
->abort_state_handle
= mono_gchandle_new (state
, FALSE
);
2329 g_assert (thread
->abort_state_handle
);
2331 thread
->abort_state_handle
= 0;
2333 thread
->abort_exc
= NULL
;
2336 * abort_exc is set in mono_thread_execute_interruption(),
2337 * triggered by the call to signal_thread_state_change(),
2338 * below. There's a point between where we have
2339 * abort_state_handle set, but abort_exc NULL, but that's not
2343 LeaveCriticalSection (thread
->synch_cs
);
2345 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Abort requested for %p (%"G_GSIZE_FORMAT
")", __func__
, GetCurrentThreadId (), thread
, (gsize
)thread
->tid
));
2347 /* During shutdown, we can't wait for other threads */
2349 /* Make sure the thread is awake */
2350 mono_thread_resume (thread
);
2352 signal_thread_state_change (thread
);
2356 ves_icall_System_Threading_Thread_ResetAbort (void)
2358 MonoInternalThread
*thread
= mono_thread_internal_current ();
2359 gboolean was_aborting
;
2361 ensure_synch_cs_set (thread
);
2363 EnterCriticalSection (thread
->synch_cs
);
2364 was_aborting
= thread
->state
& ThreadState_AbortRequested
;
2365 thread
->state
&= ~ThreadState_AbortRequested
;
2366 LeaveCriticalSection (thread
->synch_cs
);
2368 if (!was_aborting
) {
2369 const char *msg
= "Unable to reset abort because no abort was requested";
2370 mono_raise_exception (mono_get_exception_thread_state (msg
));
2372 thread
->abort_exc
= NULL
;
2373 if (thread
->abort_state_handle
) {
2374 mono_gchandle_free (thread
->abort_state_handle
);
2375 /* This is actually not necessary - the handle
2376 only counts if the exception is set */
2377 thread
->abort_state_handle
= 0;
2382 mono_thread_internal_reset_abort (MonoInternalThread
*thread
)
2384 ensure_synch_cs_set (thread
);
2386 EnterCriticalSection (thread
->synch_cs
);
2388 thread
->state
&= ~ThreadState_AbortRequested
;
2390 if (thread
->abort_exc
) {
2391 thread
->abort_exc
= NULL
;
2392 if (thread
->abort_state_handle
) {
2393 mono_gchandle_free (thread
->abort_state_handle
);
2394 /* This is actually not necessary - the handle
2395 only counts if the exception is set */
2396 thread
->abort_state_handle
= 0;
2400 LeaveCriticalSection (thread
->synch_cs
);
2404 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread
*this)
2406 MonoInternalThread
*thread
= this->internal_thread
;
2407 MonoObject
*state
, *deserialized
= NULL
, *exc
;
2410 if (!thread
->abort_state_handle
)
2413 state
= mono_gchandle_get_target (thread
->abort_state_handle
);
2416 domain
= mono_domain_get ();
2417 if (mono_object_domain (state
) == domain
)
2420 deserialized
= mono_object_xdomain_representation (state
, domain
, &exc
);
2422 if (!deserialized
) {
2423 MonoException
*invalid_op_exc
= mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2425 MONO_OBJECT_SETREF (invalid_op_exc
, inner_ex
, exc
);
2426 mono_raise_exception (invalid_op_exc
);
2429 return deserialized
;
2433 mono_thread_suspend (MonoInternalThread
*thread
)
2435 ensure_synch_cs_set (thread
);
2437 EnterCriticalSection (thread
->synch_cs
);
2439 if ((thread
->state
& ThreadState_Unstarted
) != 0 ||
2440 (thread
->state
& ThreadState_Aborted
) != 0 ||
2441 (thread
->state
& ThreadState_Stopped
) != 0)
2443 LeaveCriticalSection (thread
->synch_cs
);
2447 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
2448 (thread
->state
& ThreadState_SuspendRequested
) != 0 ||
2449 (thread
->state
& ThreadState_StopRequested
) != 0)
2451 LeaveCriticalSection (thread
->synch_cs
);
2455 thread
->state
|= ThreadState_SuspendRequested
;
2457 LeaveCriticalSection (thread
->synch_cs
);
2459 signal_thread_state_change (thread
);
2464 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread
*thread
)
2466 if (!mono_thread_suspend (thread
))
2467 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2471 mono_thread_resume (MonoInternalThread
*thread
)
2473 ensure_synch_cs_set (thread
);
2475 EnterCriticalSection (thread
->synch_cs
);
2477 if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
2478 thread
->state
&= ~ThreadState_SuspendRequested
;
2479 LeaveCriticalSection (thread
->synch_cs
);
2483 if ((thread
->state
& ThreadState_Suspended
) == 0 ||
2484 (thread
->state
& ThreadState_Unstarted
) != 0 ||
2485 (thread
->state
& ThreadState_Aborted
) != 0 ||
2486 (thread
->state
& ThreadState_Stopped
) != 0)
2488 LeaveCriticalSection (thread
->synch_cs
);
2492 thread
->resume_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
2493 if (thread
->resume_event
== NULL
) {
2494 LeaveCriticalSection (thread
->synch_cs
);
2498 /* Awake the thread */
2499 SetEvent (thread
->suspend_event
);
2501 LeaveCriticalSection (thread
->synch_cs
);
2503 /* Wait for the thread to awake */
2504 WaitForSingleObject (thread
->resume_event
, INFINITE
);
2505 CloseHandle (thread
->resume_event
);
2506 thread
->resume_event
= NULL
;
2512 ves_icall_System_Threading_Thread_Resume (MonoThread
*thread
)
2514 if (!thread
->internal_thread
|| !mono_thread_resume (thread
->internal_thread
))
2515 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2519 find_wrapper (MonoMethod
*m
, gint no
, gint ilo
, gboolean managed
, gpointer data
)
2524 if (m
->wrapper_type
== MONO_WRAPPER_RUNTIME_INVOKE
||
2525 m
->wrapper_type
== MONO_WRAPPER_XDOMAIN_INVOKE
||
2526 m
->wrapper_type
== MONO_WRAPPER_XDOMAIN_DISPATCH
)
2528 *((gboolean
*)data
) = TRUE
;
2535 is_running_protected_wrapper (void)
2537 gboolean found
= FALSE
;
2538 mono_stack_walk (find_wrapper
, &found
);
2542 void mono_thread_internal_stop (MonoInternalThread
*thread
)
2544 ensure_synch_cs_set (thread
);
2546 EnterCriticalSection (thread
->synch_cs
);
2548 if ((thread
->state
& ThreadState_StopRequested
) != 0 ||
2549 (thread
->state
& ThreadState_Stopped
) != 0)
2551 LeaveCriticalSection (thread
->synch_cs
);
2555 /* Make sure the thread is awake */
2556 mono_thread_resume (thread
);
2558 thread
->state
|= ThreadState_StopRequested
;
2559 thread
->state
&= ~ThreadState_AbortRequested
;
2561 LeaveCriticalSection (thread
->synch_cs
);
2563 signal_thread_state_change (thread
);
2566 void mono_thread_stop (MonoThread
*thread
)
2568 mono_thread_internal_stop (thread
->internal_thread
);
2572 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr
)
2574 return *((volatile gint8
*) (ptr
));
2578 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr
)
2580 return *((volatile gint16
*) (ptr
));
2584 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr
)
2586 return *((volatile gint32
*) (ptr
));
2590 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr
)
2592 return *((volatile gint64
*) (ptr
));
2596 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr
)
2598 return (void *) *((volatile void **) ptr
);
2602 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr
, gint8 value
)
2604 *((volatile gint8
*) ptr
) = value
;
2608 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr
, gint16 value
)
2610 *((volatile gint16
*) ptr
) = value
;
2614 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr
, gint32 value
)
2616 *((volatile gint32
*) ptr
) = value
;
2620 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr
, gint64 value
)
2622 *((volatile gint64
*) ptr
) = value
;
2626 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr
, void *value
)
2628 *((volatile void **) ptr
) = value
;
2632 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr
, void *value
)
2634 mono_gc_wbarrier_generic_store (ptr
, value
);
2637 void mono_thread_init (MonoThreadStartCB start_cb
,
2638 MonoThreadAttachCB attach_cb
)
2640 MONO_GC_REGISTER_ROOT (small_id_table
);
2641 InitializeCriticalSection(&threads_mutex
);
2642 InitializeCriticalSection(&interlocked_mutex
);
2643 InitializeCriticalSection(&contexts_mutex
);
2644 InitializeCriticalSection(&delayed_free_table_mutex
);
2645 InitializeCriticalSection(&small_id_mutex
);
2647 background_change_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
2648 g_assert(background_change_event
!= NULL
);
2650 mono_init_static_data_info (&thread_static_info
);
2651 mono_init_static_data_info (&context_static_info
);
2653 current_object_key
=TlsAlloc();
2654 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__
, current_object_key
));
2656 mono_thread_start_cb
= start_cb
;
2657 mono_thread_attach_cb
= attach_cb
;
2659 delayed_free_table
= g_array_new (FALSE
, FALSE
, sizeof (DelayedFreeItem
));
2661 /* Get a pseudo handle to the current process. This is just a
2662 * kludge so that wapi can build a process handle if needed.
2663 * As a pseudo handle is returned, we don't need to clean
2666 GetCurrentProcess ();
2669 void mono_thread_cleanup (void)
2671 mono_thread_hazardous_try_free_all ();
2673 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2674 /* The main thread must abandon any held mutexes (particularly
2675 * important for named mutexes as they are shared across
2676 * processes, see bug 74680.) This will happen when the
2677 * thread exits, but if it's not running in a subthread it
2678 * won't exit in time.
2680 /* Using non-w32 API is a nasty kludge, but I couldn't find
2681 * anything in the documentation that would let me do this
2682 * here yet still be safe to call on windows.
2684 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2688 /* This stuff needs more testing, it seems one of these
2689 * critical sections can be locked when mono_thread_cleanup is
2692 DeleteCriticalSection (&threads_mutex
);
2693 DeleteCriticalSection (&interlocked_mutex
);
2694 DeleteCriticalSection (&contexts_mutex
);
2695 DeleteCriticalSection (&delayed_free_table_mutex
);
2696 DeleteCriticalSection (&small_id_mutex
);
2697 CloseHandle (background_change_event
);
2700 g_array_free (delayed_free_table
, TRUE
);
2701 delayed_free_table
= NULL
;
2703 TlsFree (current_object_key
);
2707 mono_threads_install_cleanup (MonoThreadCleanupFunc func
)
2709 mono_thread_cleanup_fn
= func
;
2713 mono_thread_set_manage_callback (MonoThread
*thread
, MonoThreadManageCallback func
)
2715 thread
->internal_thread
->manage_callback
= func
;
2718 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func
)
2720 mono_thread_notify_pending_exc_fn
= func
;
2724 static void print_tids (gpointer key
, gpointer value
, gpointer user
)
2726 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2727 * sizeof(uint) and a cast to uint would overflow
2729 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2730 * print this as a pointer.
2732 g_message ("Waiting for: %p", key
);
2737 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
2738 MonoInternalThread
*threads
[MAXIMUM_WAIT_OBJECTS
];
2742 static void wait_for_tids (struct wait_data
*wait
, guint32 timeout
)
2746 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
2748 ret
=WaitForMultipleObjectsEx(wait
->num
, wait
->handles
, TRUE
, timeout
, TRUE
);
2750 if(ret
==WAIT_FAILED
) {
2751 /* See the comment in build_wait_tids() */
2752 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
2756 for(i
=0; i
<wait
->num
; i
++)
2757 CloseHandle (wait
->handles
[i
]);
2759 if (ret
== WAIT_TIMEOUT
)
2762 for(i
=0; i
<wait
->num
; i
++) {
2763 gsize tid
= wait
->threads
[i
]->tid
;
2765 mono_threads_lock ();
2766 if(mono_g_hash_table_lookup (threads
, (gpointer
)tid
)!=NULL
) {
2767 /* This thread must have been killed, because
2768 * it hasn't cleaned itself up. (It's just
2769 * possible that the thread exited before the
2770 * parent thread had a chance to store the
2771 * handle, and now there is another pointer to
2772 * the already-exited thread stored. In this
2773 * case, we'll just get two
2774 * mono_profiler_thread_end() calls for the
2778 mono_threads_unlock ();
2779 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT
")", __func__
, wait
->threads
[i
], tid
));
2780 thread_cleanup (wait
->threads
[i
]);
2782 mono_threads_unlock ();
2787 static void wait_for_tids_or_state_change (struct wait_data
*wait
, guint32 timeout
)
2789 guint32 i
, ret
, count
;
2791 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
2793 /* Add the thread state change event, so it wakes up if a thread changes
2794 * to background mode.
2797 if (count
< MAXIMUM_WAIT_OBJECTS
) {
2798 wait
->handles
[count
] = background_change_event
;
2802 ret
=WaitForMultipleObjectsEx (count
, wait
->handles
, FALSE
, timeout
, TRUE
);
2804 if(ret
==WAIT_FAILED
) {
2805 /* See the comment in build_wait_tids() */
2806 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
2810 for(i
=0; i
<wait
->num
; i
++)
2811 CloseHandle (wait
->handles
[i
]);
2813 if (ret
== WAIT_TIMEOUT
)
2816 if (ret
< wait
->num
) {
2817 gsize tid
= wait
->threads
[ret
]->tid
;
2818 mono_threads_lock ();
2819 if (mono_g_hash_table_lookup (threads
, (gpointer
)tid
)!=NULL
) {
2820 /* See comment in wait_for_tids about thread cleanup */
2821 mono_threads_unlock ();
2822 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT
, __func__
, tid
));
2823 thread_cleanup (wait
->threads
[ret
]);
2825 mono_threads_unlock ();
2829 static void build_wait_tids (gpointer key
, gpointer value
, gpointer user
)
2831 struct wait_data
*wait
=(struct wait_data
*)user
;
2833 if(wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
2835 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
2837 /* Ignore background threads, we abort them later */
2838 /* Do not lock here since it is not needed and the caller holds threads_lock */
2839 if (thread
->state
& ThreadState_Background
) {
2840 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2841 return; /* just leave, ignore */
2844 if (mono_gc_is_finalizer_internal_thread (thread
)) {
2845 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2849 if (thread
== mono_thread_internal_current ()) {
2850 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2854 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
)) {
2855 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2859 if (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
) {
2860 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT
"with DONT_MANAGE flag set.", __func__
, (gsize
)thread
->tid
));
2864 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
2865 if (handle
== NULL
) {
2866 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2870 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__
, thread
));
2871 if ((thread
->manage_callback
== NULL
) || (thread
->manage_callback (thread
->root_domain_thread
) == TRUE
)) {
2872 wait
->handles
[wait
->num
]=handle
;
2873 wait
->threads
[wait
->num
]=thread
;
2876 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2878 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2883 /* Just ignore the rest, we can't do anything with
2890 remove_and_abort_threads (gpointer key
, gpointer value
, gpointer user
)
2892 struct wait_data
*wait
=(struct wait_data
*)user
;
2893 gsize self
= GetCurrentThreadId ();
2894 MonoInternalThread
*thread
= value
;
2897 if (wait
->num
>= MAXIMUM_WAIT_OBJECTS
)
2900 /* The finalizer thread is not a background thread */
2901 if (thread
->tid
!= self
&& (thread
->state
& ThreadState_Background
) != 0 &&
2902 !(thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)) {
2904 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
2908 /* printf ("A: %d\n", wait->num); */
2909 wait
->handles
[wait
->num
]=thread
->handle
;
2910 wait
->threads
[wait
->num
]=thread
;
2913 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT
"\n", __func__
, (gsize
)thread
->tid
));
2914 mono_thread_internal_stop (thread
);
2918 return (thread
->tid
!= self
&& !mono_gc_is_finalizer_internal_thread (thread
));
2922 * mono_threads_set_shutting_down:
2924 * Is called by a thread that wants to shut down Mono. If the runtime is already
2925 * shutting down, the calling thread is suspended/stopped, and this function never
2929 mono_threads_set_shutting_down (void)
2931 MonoInternalThread
*current_thread
= mono_thread_internal_current ();
2933 mono_threads_lock ();
2935 if (shutting_down
) {
2936 mono_threads_unlock ();
2938 /* Make sure we're properly suspended/stopped */
2940 EnterCriticalSection (current_thread
->synch_cs
);
2942 if ((current_thread
->state
& ThreadState_SuspendRequested
) ||
2943 (current_thread
->state
& ThreadState_AbortRequested
) ||
2944 (current_thread
->state
& ThreadState_StopRequested
)) {
2945 LeaveCriticalSection (current_thread
->synch_cs
);
2946 mono_thread_execute_interruption (current_thread
);
2948 current_thread
->state
|= ThreadState_Stopped
;
2949 LeaveCriticalSection (current_thread
->synch_cs
);
2952 /* Wake up other threads potentially waiting for us */
2955 shutting_down
= TRUE
;
2957 /* Not really a background state change, but this will
2958 * interrupt the main thread if it is waiting for all
2959 * the other threads.
2961 SetEvent (background_change_event
);
2963 mono_threads_unlock ();
2968 * mono_threads_is_shutting_down:
2970 * Returns whether a thread has commenced shutdown of Mono. Note that
2971 * if the function returns FALSE the caller must not assume that
2972 * shutdown is not in progress, because the situation might have
2973 * changed since the function returned. For that reason this function
2974 * is of very limited utility.
2977 mono_threads_is_shutting_down (void)
2979 return shutting_down
;
2982 void mono_thread_manage (void)
2984 struct wait_data
*wait
=g_new0 (struct wait_data
, 1);
2986 /* join each thread that's still running */
2987 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__
));
2989 mono_threads_lock ();
2991 THREAD_DEBUG (g_message("%s: No threads", __func__
));
2992 mono_threads_unlock ();
2996 mono_threads_unlock ();
2999 mono_threads_lock ();
3000 if (shutting_down
) {
3001 /* somebody else is shutting down */
3002 mono_threads_unlock ();
3005 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__
, mono_g_hash_table_size (threads
));
3006 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
3008 ResetEvent (background_change_event
);
3010 mono_g_hash_table_foreach (threads
, build_wait_tids
, wait
);
3011 mono_threads_unlock ();
3013 /* Something to wait for */
3014 wait_for_tids_or_state_change (wait
, INFINITE
);
3016 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__
, wait
->num
));
3017 } while(wait
->num
>0);
3019 mono_threads_set_shutting_down ();
3021 /* No new threads will be created after this point */
3023 mono_runtime_set_shutting_down ();
3025 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__
));
3026 mono_thread_pool_cleanup ();
3029 * Remove everything but the finalizer thread and self.
3030 * Also abort all the background threads
3033 mono_threads_lock ();
3036 mono_g_hash_table_foreach_remove (threads
, remove_and_abort_threads
, wait
);
3038 mono_threads_unlock ();
3040 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__
, wait
->num
));
3042 /* Something to wait for */
3043 wait_for_tids (wait
, INFINITE
);
3045 } while (wait
->num
> 0);
3048 * give the subthreads a chance to really quit (this is mainly needed
3049 * to get correct user and system times from getrusage/wait/time(1)).
3050 * This could be removed if we avoid pthread_detach() and use pthread_join().
3059 static void terminate_thread (gpointer key
, gpointer value
, gpointer user
)
3061 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
3063 if(thread
->tid
!= (gsize
)user
) {
3064 /*TerminateThread (thread->handle, -1);*/
3068 void mono_thread_abort_all_other_threads (void)
3070 gsize self
= GetCurrentThreadId ();
3072 mono_threads_lock ();
3073 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__
,
3074 mono_g_hash_table_size (threads
));
3075 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
3077 mono_g_hash_table_foreach (threads
, terminate_thread
, (gpointer
)self
);
3079 mono_threads_unlock ();
3083 collect_threads_for_suspend (gpointer key
, gpointer value
, gpointer user_data
)
3085 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3086 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3090 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3092 * This needs no locking.
3094 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3095 (thread
->state
& ThreadState_Stopped
) != 0)
3098 if (wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
3099 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3103 wait
->handles
[wait
->num
] = handle
;
3104 wait
->threads
[wait
->num
] = thread
;
3110 * mono_thread_suspend_all_other_threads:
3112 * Suspend all managed threads except the finalizer thread and this thread. It is
3113 * not possible to resume them later.
3115 void mono_thread_suspend_all_other_threads (void)
3117 struct wait_data
*wait
= g_new0 (struct wait_data
, 1);
3119 gsize self
= GetCurrentThreadId ();
3121 guint32 eventidx
= 0;
3122 gboolean starting
, finished
;
3125 * The other threads could be in an arbitrary state at this point, i.e.
3126 * they could be starting up, shutting down etc. This means that there could be
3127 * threads which are not even in the threads hash table yet.
3131 * First we set a barrier which will be checked by all threads before they
3132 * are added to the threads hash table, and they will exit if the flag is set.
3133 * This ensures that no threads could be added to the hash later.
3134 * We will use shutting_down as the barrier for now.
3136 g_assert (shutting_down
);
3139 * We make multiple calls to WaitForMultipleObjects since:
3140 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3141 * - some threads could exit without becoming suspended
3146 * Make a copy of the hashtable since we can't do anything with
3147 * threads while threads_mutex is held.
3150 mono_threads_lock ();
3151 mono_g_hash_table_foreach (threads
, collect_threads_for_suspend
, wait
);
3152 mono_threads_unlock ();
3154 events
= g_new0 (gpointer
, wait
->num
);
3156 /* Get the suspended events that we'll be waiting for */
3157 for (i
= 0; i
< wait
->num
; ++i
) {
3158 MonoInternalThread
*thread
= wait
->threads
[i
];
3159 gboolean signal_suspend
= FALSE
;
3161 if ((thread
->tid
== self
) || mono_gc_is_finalizer_internal_thread (thread
) || (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)) {
3162 //CloseHandle (wait->handles [i]);
3163 wait
->threads
[i
] = NULL
; /* ignore this thread in next loop */
3167 ensure_synch_cs_set (thread
);
3169 EnterCriticalSection (thread
->synch_cs
);
3171 if (thread
->suspended_event
== NULL
) {
3172 thread
->suspended_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
3173 if (thread
->suspended_event
== NULL
) {
3174 /* Forget this one and go on to the next */
3175 LeaveCriticalSection (thread
->synch_cs
);
3180 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3181 (thread
->state
& ThreadState_StopRequested
) != 0 ||
3182 (thread
->state
& ThreadState_Stopped
) != 0) {
3183 LeaveCriticalSection (thread
->synch_cs
);
3184 CloseHandle (wait
->handles
[i
]);
3185 wait
->threads
[i
] = NULL
; /* ignore this thread in next loop */
3189 if ((thread
->state
& ThreadState_SuspendRequested
) == 0)
3190 signal_suspend
= TRUE
;
3192 events
[eventidx
++] = thread
->suspended_event
;
3194 /* Convert abort requests into suspend requests */
3195 if ((thread
->state
& ThreadState_AbortRequested
) != 0)
3196 thread
->state
&= ~ThreadState_AbortRequested
;
3198 thread
->state
|= ThreadState_SuspendRequested
;
3200 LeaveCriticalSection (thread
->synch_cs
);
3202 /* Signal the thread to suspend */
3204 signal_thread_state_change (thread
);
3208 WaitForMultipleObjectsEx (eventidx
, events
, TRUE
, 100, FALSE
);
3209 for (i
= 0; i
< wait
->num
; ++i
) {
3210 MonoInternalThread
*thread
= wait
->threads
[i
];
3215 ensure_synch_cs_set (thread
);
3217 EnterCriticalSection (thread
->synch_cs
);
3218 if ((thread
->state
& ThreadState_Suspended
) != 0) {
3219 CloseHandle (thread
->suspended_event
);
3220 thread
->suspended_event
= NULL
;
3222 LeaveCriticalSection (thread
->synch_cs
);
3226 * If there are threads which are starting up, we wait until they
3227 * are suspended when they try to register in the threads hash.
3228 * This is guaranteed to finish, since the threads which can create new
3229 * threads get suspended after a while.
3230 * FIXME: The finalizer thread can still create new threads.
3232 mono_threads_lock ();
3233 if (threads_starting_up
)
3234 starting
= mono_g_hash_table_size (threads_starting_up
) > 0;
3237 mono_threads_unlock ();
3251 collect_threads (gpointer key
, gpointer value
, gpointer user_data
)
3253 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3254 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3257 if (wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
3258 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3262 wait
->handles
[wait
->num
] = handle
;
3263 wait
->threads
[wait
->num
] = thread
;
3269 * mono_threads_request_thread_dump:
3271 * Ask all threads except the current to print their stacktrace to stdout.
3274 mono_threads_request_thread_dump (void)
3276 struct wait_data
*wait
= g_new0 (struct wait_data
, 1);
3280 * Make a copy of the hashtable since we can't do anything with
3281 * threads while threads_mutex is held.
3283 mono_threads_lock ();
3284 mono_g_hash_table_foreach (threads
, collect_threads
, wait
);
3285 mono_threads_unlock ();
3287 for (i
= 0; i
< wait
->num
; ++i
) {
3288 MonoInternalThread
*thread
= wait
->threads
[i
];
3290 if (!mono_gc_is_finalizer_internal_thread (thread
) &&
3291 (thread
!= mono_thread_internal_current ()) &&
3292 !thread
->thread_dump_requested
) {
3293 thread
->thread_dump_requested
= TRUE
;
3295 signal_thread_state_change (thread
);
3298 CloseHandle (wait
->handles
[i
]);
3303 * mono_thread_push_appdomain_ref:
3305 * Register that the current thread may have references to objects in domain
3306 * @domain on its stack. Each call to this function should be paired with a
3307 * call to pop_appdomain_ref.
3310 mono_thread_push_appdomain_ref (MonoDomain
*domain
)
3312 MonoInternalThread
*thread
= mono_thread_internal_current ();
3315 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3316 SPIN_LOCK (thread
->lock_thread_id
);
3317 thread
->appdomain_refs
= g_slist_prepend (thread
->appdomain_refs
, domain
);
3318 SPIN_UNLOCK (thread
->lock_thread_id
);
3323 mono_thread_pop_appdomain_ref (void)
3325 MonoInternalThread
*thread
= mono_thread_internal_current ();
3328 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3329 /* FIXME: How can the list be empty ? */
3330 SPIN_LOCK (thread
->lock_thread_id
);
3331 if (thread
->appdomain_refs
)
3332 thread
->appdomain_refs
= g_slist_remove (thread
->appdomain_refs
, thread
->appdomain_refs
->data
);
3333 SPIN_UNLOCK (thread
->lock_thread_id
);
3338 mono_thread_internal_has_appdomain_ref (MonoInternalThread
*thread
, MonoDomain
*domain
)
3341 SPIN_LOCK (thread
->lock_thread_id
);
3342 res
= g_slist_find (thread
->appdomain_refs
, domain
) != NULL
;
3343 SPIN_UNLOCK (thread
->lock_thread_id
);
3348 mono_thread_has_appdomain_ref (MonoThread
*thread
, MonoDomain
*domain
)
3350 return mono_thread_internal_has_appdomain_ref (thread
->internal_thread
, domain
);
3353 typedef struct abort_appdomain_data
{
3354 struct wait_data wait
;
3356 } abort_appdomain_data
;
3359 collect_appdomain_thread (gpointer key
, gpointer value
, gpointer user_data
)
3361 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3362 abort_appdomain_data
*data
= (abort_appdomain_data
*)user_data
;
3363 MonoDomain
*domain
= data
->domain
;
3365 if (mono_thread_internal_has_appdomain_ref (thread
, domain
)) {
3366 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3368 if(data
->wait
.num
<MAXIMUM_WAIT_OBJECTS
) {
3369 HANDLE handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3372 data
->wait
.handles
[data
->wait
.num
] = handle
;
3373 data
->wait
.threads
[data
->wait
.num
] = thread
;
3376 /* Just ignore the rest, we can't do anything with
3384 * mono_threads_abort_appdomain_threads:
3386 * Abort threads which has references to the given appdomain.
3389 mono_threads_abort_appdomain_threads (MonoDomain
*domain
, int timeout
)
3391 abort_appdomain_data user_data
;
3393 int orig_timeout
= timeout
;
3396 THREAD_DEBUG (g_message ("%s: starting abort", __func__
));
3398 start_time
= mono_msec_ticks ();
3400 mono_threads_lock ();
3402 user_data
.domain
= domain
;
3403 user_data
.wait
.num
= 0;
3404 /* This shouldn't take any locks */
3405 mono_g_hash_table_foreach (threads
, collect_appdomain_thread
, &user_data
);
3406 mono_threads_unlock ();
3408 if (user_data
.wait
.num
> 0) {
3409 /* Abort the threads outside the threads lock */
3410 for (i
= 0; i
< user_data
.wait
.num
; ++i
)
3411 ves_icall_System_Threading_Thread_Abort (user_data
.wait
.threads
[i
], NULL
);
3414 * We should wait for the threads either to abort, or to leave the
3415 * domain. We can't do the latter, so we wait with a timeout.
3417 wait_for_tids (&user_data
.wait
, 100);
3420 /* Update remaining time */
3421 timeout
-= mono_msec_ticks () - start_time
;
3422 start_time
= mono_msec_ticks ();
3424 if (orig_timeout
!= -1 && timeout
< 0)
3427 while (user_data
.wait
.num
> 0);
3429 THREAD_DEBUG (g_message ("%s: abort done", __func__
));
3435 clear_cached_culture (gpointer key
, gpointer value
, gpointer user_data
)
3437 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3438 MonoDomain
*domain
= (MonoDomain
*)user_data
;
3441 /* No locking needed here */
3442 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3444 if (thread
->cached_culture_info
) {
3445 for (i
= 0; i
< NUM_CACHED_CULTURES
* 2; ++i
) {
3446 MonoObject
*obj
= mono_array_get (thread
->cached_culture_info
, MonoObject
*, i
);
3447 if (obj
&& obj
->vtable
->domain
== domain
)
3448 mono_array_set (thread
->cached_culture_info
, MonoObject
*, i
, NULL
);
3454 * mono_threads_clear_cached_culture:
3456 * Clear the cached_current_culture from all threads if it is in the
3460 mono_threads_clear_cached_culture (MonoDomain
*domain
)
3462 mono_threads_lock ();
3463 mono_g_hash_table_foreach (threads
, clear_cached_culture
, domain
);
3464 mono_threads_unlock ();
3468 * mono_thread_get_undeniable_exception:
3470 * Return an exception which needs to be raised when leaving a catch clause.
3471 * This is used for undeniable exception propagation.
3474 mono_thread_get_undeniable_exception (void)
3476 MonoInternalThread
*thread
= mono_thread_internal_current ();
3478 if (thread
&& thread
->abort_exc
&& !is_running_protected_wrapper ()) {
3480 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3481 * exception if the thread no longer references a dying appdomain.
3483 thread
->abort_exc
->trace_ips
= NULL
;
3484 thread
->abort_exc
->stack_trace
= NULL
;
3485 return thread
->abort_exc
;
3491 #if MONO_SMALL_CONFIG
3492 #define NUM_STATIC_DATA_IDX 4
3493 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
3497 #define NUM_STATIC_DATA_IDX 8
3498 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
3499 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3503 static uintptr_t* static_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
3507 mark_tls_slots (void *addr
, MonoGCMarkFunc mark_func
)
3510 gpointer
*static_data
= addr
;
3511 for (i
= 0; i
< NUM_STATIC_DATA_IDX
; ++i
) {
3514 if (!static_data
[i
])
3516 numwords
= 1 + static_data_size
[i
] / sizeof (gpointer
) / (sizeof(uintptr_t) * 8);
3517 ptr
= static_data
[i
];
3518 for (j
= 0; j
< numwords
; ++j
, ptr
+= sizeof (uintptr_t) * 8) {
3519 uintptr_t bmap
= static_reference_bitmaps
[i
][j
];
3522 if ((bmap
& 1) && *p
) {
3534 * mono_alloc_static_data
3536 * Allocate memory blocks for storing threads or context static data
3539 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, gboolean threadlocal
)
3541 guint idx
= (offset
>> 24) - 1;
3544 gpointer
* static_data
= *static_data_ptr
;
3546 static void* tls_desc
= NULL
;
3549 tls_desc
= mono_gc_make_root_descr_user (mark_tls_slots
);
3551 static_data
= mono_gc_alloc_fixed (static_data_size
[0], threadlocal
?tls_desc
:NULL
);
3552 *static_data_ptr
= static_data
;
3553 static_data
[0] = static_data
;
3556 for (i
= 1; i
<= idx
; ++i
) {
3557 if (static_data
[i
])
3560 static_data
[i
] = threadlocal
?g_malloc0 (static_data_size
[i
]):mono_gc_alloc_fixed (static_data_size
[i
], NULL
);
3562 static_data
[i
] = mono_gc_alloc_fixed (static_data_size
[i
], NULL
);
3568 mono_free_static_data (gpointer
* static_data
, gboolean threadlocal
)
3571 for (i
= 1; i
< NUM_STATIC_DATA_IDX
; ++i
) {
3572 if (!static_data
[i
])
3576 g_free (static_data
[i
]);
3578 mono_gc_free_fixed (static_data
[i
]);
3580 mono_gc_free_fixed (static_data
[i
]);
3583 mono_gc_free_fixed (static_data
);
3587 * mono_init_static_data_info
3589 * Initializes static data counters
3591 static void mono_init_static_data_info (StaticDataInfo
*static_data
)
3593 static_data
->idx
= 0;
3594 static_data
->offset
= 0;
3595 static_data
->freelist
= NULL
;
3599 * mono_alloc_static_data_slot
3601 * Generates an offset for static data. static_data contains the counters
3602 * used to generate it.
3605 mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
3609 if (!static_data
->idx
&& !static_data
->offset
) {
3611 * we use the first chunk of the first allocation also as
3612 * an array for the rest of the data
3614 static_data
->offset
= sizeof (gpointer
) * NUM_STATIC_DATA_IDX
;
3616 static_data
->offset
+= align
- 1;
3617 static_data
->offset
&= ~(align
- 1);
3618 if (static_data
->offset
+ size
>= static_data_size
[static_data
->idx
]) {
3619 static_data
->idx
++;
3620 g_assert (size
<= static_data_size
[static_data
->idx
]);
3621 g_assert (static_data
->idx
< NUM_STATIC_DATA_IDX
);
3622 static_data
->offset
= 0;
3624 offset
= static_data
->offset
| ((static_data
->idx
+ 1) << 24);
3625 static_data
->offset
+= size
;
3630 * ensure thread static fields already allocated are valid for thread
3631 * This function is called when a thread is created or on thread attach.
3634 thread_adjust_static_data (MonoInternalThread
*thread
)
3638 mono_threads_lock ();
3639 if (thread_static_info
.offset
|| thread_static_info
.idx
> 0) {
3640 /* get the current allocated size */
3641 offset
= thread_static_info
.offset
| ((thread_static_info
.idx
+ 1) << 24);
3642 mono_alloc_static_data (&(thread
->static_data
), offset
, TRUE
);
3644 mono_threads_unlock ();
3648 alloc_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
3650 MonoInternalThread
*thread
= value
;
3651 guint32 offset
= GPOINTER_TO_UINT (user
);
3653 mono_alloc_static_data (&(thread
->static_data
), offset
, TRUE
);
3656 static MonoThreadDomainTls
*
3657 search_tls_slot_in_freelist (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
3659 MonoThreadDomainTls
* prev
= NULL
;
3660 MonoThreadDomainTls
* tmp
= static_data
->freelist
;
3662 if (tmp
->size
== size
) {
3664 prev
->next
= tmp
->next
;
3666 static_data
->freelist
= tmp
->next
;
3675 update_tls_reference_bitmap (guint32 offset
, uintptr_t *bitmap
, int max_set
)
3678 int idx
= (offset
>> 24) - 1;
3680 if (!static_reference_bitmaps
[idx
])
3681 static_reference_bitmaps
[idx
] = g_new0 (uintptr_t, 1 + static_data_size
[idx
] / sizeof(gpointer
) / (sizeof(uintptr_t) * 8));
3682 rb
= static_reference_bitmaps
[idx
];
3684 offset
/= sizeof (gpointer
);
3685 /* offset is now the bitmap offset */
3686 for (i
= 0; i
< max_set
; ++i
) {
3687 if (bitmap
[i
/ sizeof (uintptr_t)] & (1L << (i
& (sizeof (uintptr_t) * 8 -1))))
3688 rb
[(offset
+ i
) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset
+ i
) & (sizeof (uintptr_t) * 8 -1)));
3693 clear_reference_bitmap (guint32 offset
, guint32 size
)
3695 int idx
= (offset
>> 24) - 1;
3697 rb
= static_reference_bitmaps
[idx
];
3699 offset
/= sizeof (gpointer
);
3700 size
/= sizeof (gpointer
);
3702 /* offset is now the bitmap offset */
3703 for (; offset
< size
; ++offset
)
3704 rb
[offset
/ (sizeof (uintptr_t) * 8)] &= ~(1L << (offset
& (sizeof (uintptr_t) * 8 -1)));
3708 * The offset for a special static variable is composed of three parts:
3709 * a bit that indicates the type of static data (0:thread, 1:context),
3710 * an index in the array of chunks of memory for the thread (thread->static_data)
3711 * and an offset in that chunk of mem. This allows allocating less memory in the
3716 mono_alloc_special_static_data (guint32 static_type
, guint32 size
, guint32 align
, uintptr_t *bitmap
, int max_set
)
3719 if (static_type
== SPECIAL_STATIC_THREAD
) {
3720 MonoThreadDomainTls
*item
;
3721 mono_threads_lock ();
3722 item
= search_tls_slot_in_freelist (&thread_static_info
, size
, align
);
3723 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3725 offset
= item
->offset
;
3728 offset
= mono_alloc_static_data_slot (&thread_static_info
, size
, align
);
3730 update_tls_reference_bitmap (offset
, bitmap
, max_set
);
3731 /* This can be called during startup */
3732 if (threads
!= NULL
)
3733 mono_g_hash_table_foreach (threads
, alloc_thread_static_data_helper
, GUINT_TO_POINTER (offset
));
3734 mono_threads_unlock ();
3736 g_assert (static_type
== SPECIAL_STATIC_CONTEXT
);
3737 mono_contexts_lock ();
3738 offset
= mono_alloc_static_data_slot (&context_static_info
, size
, align
);
3739 mono_contexts_unlock ();
3740 offset
|= 0x80000000; /* Set the high bit to indicate context static data */
3746 mono_get_special_static_data (guint32 offset
)
3748 /* The high bit means either thread (0) or static (1) data. */
3750 guint32 static_type
= (offset
& 0x80000000);
3753 offset
&= 0x7fffffff;
3754 idx
= (offset
>> 24) - 1;
3756 if (static_type
== 0) {
3757 return get_thread_static_data (mono_thread_internal_current (), offset
);
3759 /* Allocate static data block under demand, since we don't have a list
3762 MonoAppContext
*context
= mono_context_get ();
3763 if (!context
->static_data
|| !context
->static_data
[idx
]) {
3764 mono_contexts_lock ();
3765 mono_alloc_static_data (&(context
->static_data
), offset
, FALSE
);
3766 mono_contexts_unlock ();
3768 return ((char*) context
->static_data
[idx
]) + (offset
& 0xffffff);
3778 free_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
3780 MonoInternalThread
*thread
= value
;
3781 TlsOffsetSize
*data
= user
;
3782 int idx
= (data
->offset
>> 24) - 1;
3785 if (!thread
->static_data
|| !thread
->static_data
[idx
])
3787 ptr
= ((char*) thread
->static_data
[idx
]) + (data
->offset
& 0xffffff);
3788 memset (ptr
, 0, data
->size
);
3792 do_free_special (gpointer key
, gpointer value
, gpointer data
)
3794 MonoClassField
*field
= key
;
3795 guint32 offset
= GPOINTER_TO_UINT (value
);
3796 guint32 static_type
= (offset
& 0x80000000);
3799 size
= mono_type_size (field
->type
, &align
);
3800 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3801 if (static_type
== 0) {
3803 MonoThreadDomainTls
*item
= g_new0 (MonoThreadDomainTls
, 1);
3804 data
.offset
= offset
& 0x7fffffff;
3806 clear_reference_bitmap (data
.offset
, data
.size
);
3807 if (threads
!= NULL
)
3808 mono_g_hash_table_foreach (threads
, free_thread_static_data_helper
, &data
);
3809 item
->offset
= offset
;
3811 item
->next
= thread_static_info
.freelist
;
3812 thread_static_info
.freelist
= item
;
3814 /* FIXME: free context static data as well */
3819 mono_alloc_special_static_data_free (GHashTable
*special_static_fields
)
3821 mono_threads_lock ();
3822 g_hash_table_foreach (special_static_fields
, do_free_special
, NULL
);
3823 mono_threads_unlock ();
3826 static MonoClassField
*local_slots
= NULL
;
3829 /* local tls data to get locals_slot from a thread */
3832 /* index in the locals_slot array */
3837 clear_local_slot (gpointer key
, gpointer value
, gpointer user_data
)
3839 LocalSlotID
*sid
= user_data
;
3840 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3841 MonoArray
*slots_array
;
3843 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3844 * it is for the right domain, so we need to check if it is allocated an initialized
3845 * for the current thread.
3847 /*g_print ("handling thread %p\n", thread);*/
3848 if (!thread
->static_data
|| !thread
->static_data
[sid
->idx
])
3850 slots_array
= *(MonoArray
**)(((char*) thread
->static_data
[sid
->idx
]) + (sid
->offset
& 0xffffff));
3851 if (!slots_array
|| sid
->slot
>= mono_array_length (slots_array
))
3853 mono_array_set (slots_array
, MonoObject
*, sid
->slot
, NULL
);
3857 mono_thread_free_local_slot_values (int slot
, MonoBoolean thread_local
)
3865 local_slots
= mono_class_get_field_from_name (mono_defaults
.thread_class
, "local_slots");
3867 g_warning ("local_slots field not found in Thread class");
3871 domain
= mono_domain_get ();
3872 mono_domain_lock (domain
);
3873 if (domain
->special_static_fields
)
3874 addr
= g_hash_table_lookup (domain
->special_static_fields
, local_slots
);
3875 mono_domain_unlock (domain
);
3878 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3879 sid
.offset
= GPOINTER_TO_UINT (addr
);
3880 sid
.offset
&= 0x7fffffff;
3881 sid
.idx
= (sid
.offset
>> 24) - 1;
3882 mono_threads_lock ();
3883 mono_g_hash_table_foreach (threads
, clear_local_slot
, &sid
);
3884 mono_threads_unlock ();
3886 /* FIXME: clear the slot for MonoAppContexts, too */
3891 static void CALLBACK
dummy_apc (ULONG_PTR param
)
3895 static guint32
dummy_apc (gpointer param
)
3902 * mono_thread_execute_interruption
3904 * Performs the operation that the requested thread state requires (abort,
3907 static MonoException
* mono_thread_execute_interruption (MonoInternalThread
*thread
)
3909 ensure_synch_cs_set (thread
);
3911 EnterCriticalSection (thread
->synch_cs
);
3913 /* MonoThread::interruption_requested can only be changed with atomics */
3914 if (InterlockedCompareExchange (&thread
->interruption_requested
, FALSE
, TRUE
)) {
3915 /* this will consume pending APC calls */
3916 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE
);
3917 InterlockedDecrement (&thread_interruption_requested
);
3919 /* Clear the interrupted flag of the thread so it can wait again */
3920 wapi_clear_interruption ();
3924 if ((thread
->state
& ThreadState_AbortRequested
) != 0) {
3925 LeaveCriticalSection (thread
->synch_cs
);
3926 if (thread
->abort_exc
== NULL
) {
3928 * This might be racy, but it has to be called outside the lock
3929 * since it calls managed code.
3931 MONO_OBJECT_SETREF (thread
, abort_exc
, mono_get_exception_thread_abort ());
3933 return thread
->abort_exc
;
3935 else if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
3936 thread
->state
&= ~ThreadState_SuspendRequested
;
3937 thread
->state
|= ThreadState_Suspended
;
3938 thread
->suspend_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
3939 if (thread
->suspend_event
== NULL
) {
3940 LeaveCriticalSection (thread
->synch_cs
);
3943 if (thread
->suspended_event
)
3944 SetEvent (thread
->suspended_event
);
3946 LeaveCriticalSection (thread
->synch_cs
);
3948 if (shutting_down
) {
3949 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3954 WaitForSingleObject (thread
->suspend_event
, INFINITE
);
3956 EnterCriticalSection (thread
->synch_cs
);
3958 CloseHandle (thread
->suspend_event
);
3959 thread
->suspend_event
= NULL
;
3960 thread
->state
&= ~ThreadState_Suspended
;
3962 /* The thread that requested the resume will have replaced this event
3963 * and will be waiting for it
3965 SetEvent (thread
->resume_event
);
3967 LeaveCriticalSection (thread
->synch_cs
);
3971 else if ((thread
->state
& ThreadState_StopRequested
) != 0) {
3972 /* FIXME: do this through the JIT? */
3974 LeaveCriticalSection (thread
->synch_cs
);
3976 mono_thread_exit ();
3978 } else if (thread
->thread_interrupt_requested
) {
3980 thread
->thread_interrupt_requested
= FALSE
;
3981 LeaveCriticalSection (thread
->synch_cs
);
3983 return(mono_get_exception_thread_interrupted ());
3986 LeaveCriticalSection (thread
->synch_cs
);
3992 * mono_thread_request_interruption
3994 * A signal handler can call this method to request the interruption of a
3995 * thread. The result of the interruption will depend on the current state of
3996 * the thread. If the result is an exception that needs to be throw, it is
3997 * provided as return value.
4000 mono_thread_request_interruption (gboolean running_managed
)
4002 MonoInternalThread
*thread
= mono_thread_internal_current ();
4004 /* The thread may already be stopping */
4009 if (thread
->interrupt_on_stop
&&
4010 thread
->state
& ThreadState_StopRequested
&&
4011 thread
->state
& ThreadState_Background
)
4015 if (InterlockedCompareExchange (&thread
->interruption_requested
, 1, 0) == 1)
4018 if (!running_managed
|| is_running_protected_wrapper ()) {
4019 /* Can't stop while in unmanaged code. Increase the global interruption
4020 request count. When exiting the unmanaged method the count will be
4021 checked and the thread will be interrupted. */
4023 InterlockedIncrement (&thread_interruption_requested
);
4025 if (mono_thread_notify_pending_exc_fn
&& !running_managed
)
4026 /* The JIT will notify the thread about the interruption */
4027 /* This shouldn't take any locks */
4028 mono_thread_notify_pending_exc_fn ();
4030 /* this will awake the thread if it is in WaitForSingleObject
4032 /* Our implementation of this function ignores the func argument */
4033 QueueUserAPC ((PAPCFUNC
)dummy_apc
, thread
->handle
, NULL
);
4037 return mono_thread_execute_interruption (thread
);
4041 /*This function should be called by a thread after it has exited all of
4042 * its handle blocks at interruption time.*/
4044 mono_thread_resume_interruption (void)
4046 MonoInternalThread
*thread
= mono_thread_internal_current ();
4047 gboolean still_aborting
;
4049 /* The thread may already be stopping */
4053 ensure_synch_cs_set (thread
);
4054 EnterCriticalSection (thread
->synch_cs
);
4055 still_aborting
= (thread
->state
& ThreadState_AbortRequested
) != 0;
4056 LeaveCriticalSection (thread
->synch_cs
);
4058 /*This can happen if the protected block called Thread::ResetAbort*/
4059 if (!still_aborting
)
4062 if (InterlockedCompareExchange (&thread
->interruption_requested
, 1, 0) == 1)
4064 InterlockedIncrement (&thread_interruption_requested
);
4067 wapi_self_interrupt ();
4069 return mono_thread_execute_interruption (thread
);
4072 gboolean
mono_thread_interruption_requested ()
4074 if (thread_interruption_requested
) {
4075 MonoInternalThread
*thread
= mono_thread_internal_current ();
4076 /* The thread may already be stopping */
4078 return (thread
->interruption_requested
);
4083 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection
)
4085 MonoInternalThread
*thread
= mono_thread_internal_current ();
4087 /* The thread may already be stopping */
4091 mono_debugger_check_interruption ();
4093 if (thread
->interruption_requested
&& (bypass_abort_protection
|| !is_running_protected_wrapper ())) {
4094 MonoException
* exc
= mono_thread_execute_interruption (thread
);
4095 if (exc
) mono_raise_exception (exc
);
4100 * Performs the interruption of the current thread, if one has been requested,
4101 * and the thread is not running a protected wrapper.
4103 void mono_thread_interruption_checkpoint ()
4105 mono_thread_interruption_checkpoint_request (FALSE
);
4109 * Performs the interruption of the current thread, if one has been requested.
4111 void mono_thread_force_interruption_checkpoint ()
4113 mono_thread_interruption_checkpoint_request (TRUE
);
4117 * mono_thread_get_and_clear_pending_exception:
4119 * Return any pending exceptions for the current thread and clear it as a side effect.
4122 mono_thread_get_and_clear_pending_exception (void)
4124 MonoInternalThread
*thread
= mono_thread_internal_current ();
4126 /* The thread may already be stopping */
4130 if (thread
->interruption_requested
&& !is_running_protected_wrapper ()) {
4131 return mono_thread_execute_interruption (thread
);
4134 if (thread
->pending_exception
) {
4135 MonoException
*exc
= thread
->pending_exception
;
4137 thread
->pending_exception
= NULL
;
4145 * mono_set_pending_exception:
4147 * Set the pending exception of the current thread to EXC. On platforms which
4148 * support it, the exception will be thrown when execution returns to managed code.
4149 * On other platforms, this function is equivalent to mono_raise_exception ().
4150 * Internal calls which report exceptions using this function instead of
4151 * raise_exception () might be called by JITted code using a more efficient calling
4155 mono_set_pending_exception (MonoException
*exc
)
4157 MonoInternalThread
*thread
= mono_thread_internal_current ();
4159 /* The thread may already be stopping */
4163 if (mono_thread_notify_pending_exc_fn
) {
4164 MONO_OBJECT_SETREF (thread
, pending_exception
, exc
);
4166 mono_thread_notify_pending_exc_fn ();
4168 /* No way to notify the JIT about the exception, have to throw it now */
4169 mono_raise_exception (exc
);
4174 * mono_thread_interruption_request_flag:
4176 * Returns the address of a flag that will be non-zero if an interruption has
4177 * been requested for a thread. The thread to interrupt may not be the current
4178 * thread, so an additional call to mono_thread_interruption_requested() or
4179 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4182 gint32
* mono_thread_interruption_request_flag ()
4184 return &thread_interruption_requested
;
4188 mono_thread_init_apartment_state (void)
4191 MonoInternalThread
* thread
= mono_thread_internal_current ();
4193 /* Positive return value indicates success, either
4194 * S_OK if this is first CoInitialize call, or
4195 * S_FALSE if CoInitialize already called, but with same
4196 * threading model. A negative value indicates failure,
4197 * probably due to trying to change the threading model.
4199 if (CoInitializeEx(NULL
, (thread
->apartment_state
== ThreadApartmentState_STA
)
4200 ? COINIT_APARTMENTTHREADED
4201 : COINIT_MULTITHREADED
) < 0) {
4202 thread
->apartment_state
= ThreadApartmentState_Unknown
;
4208 mono_thread_cleanup_apartment_state (void)
4211 MonoInternalThread
* thread
= mono_thread_internal_current ();
4213 if (thread
&& thread
->apartment_state
!= ThreadApartmentState_Unknown
) {
4220 mono_thread_set_state (MonoInternalThread
*thread
, MonoThreadState state
)
4222 ensure_synch_cs_set (thread
);
4224 EnterCriticalSection (thread
->synch_cs
);
4225 thread
->state
|= state
;
4226 LeaveCriticalSection (thread
->synch_cs
);
4230 mono_thread_clr_state (MonoInternalThread
*thread
, MonoThreadState state
)
4232 ensure_synch_cs_set (thread
);
4234 EnterCriticalSection (thread
->synch_cs
);
4235 thread
->state
&= ~state
;
4236 LeaveCriticalSection (thread
->synch_cs
);
4240 mono_thread_test_state (MonoInternalThread
*thread
, MonoThreadState test
)
4242 gboolean ret
= FALSE
;
4244 ensure_synch_cs_set (thread
);
4246 EnterCriticalSection (thread
->synch_cs
);
4248 if ((thread
->state
& test
) != 0) {
4252 LeaveCriticalSection (thread
->synch_cs
);
4257 static MonoClassField
*execution_context_field
;
4260 get_execution_context_addr (void)
4262 MonoDomain
*domain
= mono_domain_get ();
4265 if (!execution_context_field
) {
4266 execution_context_field
= mono_class_get_field_from_name (mono_defaults
.thread_class
,
4268 g_assert (execution_context_field
);
4271 g_assert (mono_class_try_get_vtable (domain
, mono_defaults
.appdomain_class
));
4273 mono_domain_lock (domain
);
4274 offset
= GPOINTER_TO_UINT (g_hash_table_lookup (domain
->special_static_fields
, execution_context_field
));
4275 mono_domain_unlock (domain
);
4278 return (MonoObject
**) mono_get_special_static_data (offset
);
4282 mono_thread_get_execution_context (void)
4284 return *get_execution_context_addr ();
4288 mono_thread_set_execution_context (MonoObject
*ec
)
4290 *get_execution_context_addr () = ec
;
4293 static gboolean has_tls_get
= FALSE
;
4296 mono_runtime_set_has_tls_get (gboolean val
)
4302 mono_runtime_has_tls_get (void)