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 * mono_thread_get_name:
1284 * Return the name of the thread. NAME_LEN is set to the length of the name.
1285 * Return NULL if the thread has no name. The returned memory is owned by the
1289 mono_thread_get_name (MonoInternalThread
*this_obj
, guint32
*name_len
)
1293 ensure_synch_cs_set (this_obj
);
1295 EnterCriticalSection (this_obj
->synch_cs
);
1297 if (!this_obj
->name
) {
1301 *name_len
= this_obj
->name_len
;
1302 res
= g_new (gunichar2
, this_obj
->name_len
);
1303 memcpy (res
, this_obj
->name
, sizeof (gunichar2
) * this_obj
->name_len
);
1306 LeaveCriticalSection (this_obj
->synch_cs
);
1312 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread
*this_obj
)
1316 ensure_synch_cs_set (this_obj
);
1318 EnterCriticalSection (this_obj
->synch_cs
);
1320 if (!this_obj
->name
)
1323 str
= mono_string_new_utf16 (mono_domain_get (), this_obj
->name
, this_obj
->name_len
);
1325 LeaveCriticalSection (this_obj
->synch_cs
);
1331 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread
*this_obj
, MonoString
*name
)
1333 ensure_synch_cs_set (this_obj
);
1335 EnterCriticalSection (this_obj
->synch_cs
);
1337 if (this_obj
->name
) {
1338 LeaveCriticalSection (this_obj
->synch_cs
);
1340 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1344 this_obj
->name
= g_new (gunichar2
, mono_string_length (name
));
1345 memcpy (this_obj
->name
, mono_string_chars (name
), mono_string_length (name
) * 2);
1346 this_obj
->name_len
= mono_string_length (name
);
1349 this_obj
->name
= NULL
;
1351 LeaveCriticalSection (this_obj
->synch_cs
);
1355 lookup_cached_culture (MonoInternalThread
*this, MonoDomain
*domain
, int start_idx
)
1360 if (this->cached_culture_info
) {
1361 domain
= mono_domain_get ();
1362 for (i
= start_idx
; i
< start_idx
+ NUM_CACHED_CULTURES
; ++i
) {
1363 res
= mono_array_get (this->cached_culture_info
, MonoObject
*, i
);
1364 if (res
&& res
->vtable
->domain
== domain
)
1372 /* If the array is already in the requested domain, we just return it,
1373 otherwise we return a copy in that domain. */
1375 byte_array_to_domain (MonoArray
*arr
, MonoDomain
*domain
)
1382 if (mono_object_domain (arr
) == domain
)
1385 copy
= mono_array_new (domain
, mono_defaults
.byte_class
, arr
->max_length
);
1386 memcpy (mono_array_addr (copy
, guint8
, 0), mono_array_addr (arr
, guint8
, 0), arr
->max_length
);
1391 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray
*arr
)
1393 return byte_array_to_domain (arr
, mono_get_root_domain ());
1397 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray
*arr
)
1399 return byte_array_to_domain (arr
, mono_domain_get ());
1403 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread
*this)
1405 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX
);
1409 cache_culture (MonoInternalThread
*this, MonoObject
*culture
, int start_idx
)
1412 MonoDomain
*domain
= mono_domain_get ();
1415 int same_domain_slot
= -1;
1417 ensure_synch_cs_set (this);
1419 EnterCriticalSection (this->synch_cs
);
1421 if (!this->cached_culture_info
)
1422 MONO_OBJECT_SETREF (this, cached_culture_info
, mono_array_new_cached (mono_get_root_domain (), mono_defaults
.object_class
, NUM_CACHED_CULTURES
* 2));
1424 for (i
= start_idx
; i
< start_idx
+ NUM_CACHED_CULTURES
; ++i
) {
1425 obj
= mono_array_get (this->cached_culture_info
, MonoObject
*, i
);
1429 /* we continue, because there may be a slot used with the same domain */
1433 if (obj
->vtable
->domain
== domain
) {
1434 same_domain_slot
= i
;
1438 if (same_domain_slot
>= 0)
1439 mono_array_setref (this->cached_culture_info
, same_domain_slot
, culture
);
1440 else if (free_slot
>= 0)
1441 mono_array_setref (this->cached_culture_info
, free_slot
, culture
);
1442 /* we may want to replace an existing entry here, even when no suitable slot is found */
1444 LeaveCriticalSection (this->synch_cs
);
1448 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread
*this, MonoObject
*culture
)
1450 MonoDomain
*domain
= mono_object_get_domain (&this->obj
);
1451 g_assert (domain
== mono_domain_get ());
1452 cache_culture (this->internal_thread
, culture
, CULTURES_START_IDX
);
1456 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread
*this)
1458 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX
);
1462 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread
*this, MonoObject
*culture
)
1464 MonoDomain
*domain
= mono_object_get_domain (&this->obj
);
1465 g_assert (domain
== mono_domain_get ());
1466 cache_culture (this->internal_thread
, culture
, UICULTURES_START_IDX
);
1470 mono_thread_current (void)
1472 MonoDomain
*domain
= mono_domain_get ();
1473 MonoInternalThread
*internal
= mono_thread_internal_current ();
1474 MonoThread
**current_thread_ptr
;
1476 g_assert (internal
);
1477 current_thread_ptr
= get_current_thread_ptr_for_domain (domain
, internal
);
1479 if (!*current_thread_ptr
) {
1480 g_assert (domain
!= mono_get_root_domain ());
1481 *current_thread_ptr
= new_thread_with_internal (domain
, internal
);
1483 return *current_thread_ptr
;
1487 mono_thread_internal_current (void)
1489 MonoInternalThread
*res
= GET_CURRENT_OBJECT ();
1490 THREAD_DEBUG (g_message ("%s: returning %p", __func__
, res
));
1494 gboolean
ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread
*this,
1495 int ms
, HANDLE thread
)
1497 MonoInternalThread
*cur_thread
= mono_thread_internal_current ();
1500 mono_thread_current_check_pending_interrupt ();
1502 ensure_synch_cs_set (this);
1504 EnterCriticalSection (this->synch_cs
);
1506 if ((this->state
& ThreadState_Unstarted
) != 0) {
1507 LeaveCriticalSection (this->synch_cs
);
1509 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1513 LeaveCriticalSection (this->synch_cs
);
1518 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__
, thread
, ms
));
1520 mono_thread_set_state (cur_thread
, ThreadState_WaitSleepJoin
);
1522 ret
=WaitForSingleObjectEx (thread
, ms
, TRUE
);
1524 mono_thread_clr_state (cur_thread
, ThreadState_WaitSleepJoin
);
1526 if(ret
==WAIT_OBJECT_0
) {
1527 THREAD_DEBUG (g_message ("%s: join successful", __func__
));
1532 THREAD_DEBUG (g_message ("%s: join failed", __func__
));
1537 /* FIXME: exitContext isnt documented */
1538 gboolean
ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray
*mono_handles
, gint32 ms
, gboolean exitContext
)
1544 MonoObject
*waitHandle
;
1545 MonoInternalThread
*thread
= mono_thread_internal_current ();
1547 /* Do this WaitSleepJoin check before creating objects */
1548 mono_thread_current_check_pending_interrupt ();
1550 numhandles
= mono_array_length(mono_handles
);
1551 handles
= g_new0(HANDLE
, numhandles
);
1553 for(i
= 0; i
< numhandles
; i
++) {
1554 waitHandle
= mono_array_get(mono_handles
, MonoObject
*, i
);
1555 handles
[i
] = mono_wait_handle_get_handle ((MonoWaitHandle
*) waitHandle
);
1562 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1564 ret
=WaitForMultipleObjectsEx(numhandles
, handles
, TRUE
, ms
, TRUE
);
1566 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1570 if(ret
==WAIT_FAILED
) {
1571 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait failed", __func__
, GetCurrentThreadId ()));
1573 } else if(ret
==WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
) {
1574 /* Do we want to try again if we get
1575 * WAIT_IO_COMPLETION? The documentation for
1576 * WaitHandle doesn't give any clues. (We'd have to
1577 * fiddle with the timeout if we retry.)
1579 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait timed out", __func__
, GetCurrentThreadId ()));
1586 /* FIXME: exitContext isnt documented */
1587 gint32
ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray
*mono_handles
, gint32 ms
, gboolean exitContext
)
1593 MonoObject
*waitHandle
;
1594 MonoInternalThread
*thread
= mono_thread_internal_current ();
1596 /* Do this WaitSleepJoin check before creating objects */
1597 mono_thread_current_check_pending_interrupt ();
1599 numhandles
= mono_array_length(mono_handles
);
1600 handles
= g_new0(HANDLE
, numhandles
);
1602 for(i
= 0; i
< numhandles
; i
++) {
1603 waitHandle
= mono_array_get(mono_handles
, MonoObject
*, i
);
1604 handles
[i
] = mono_wait_handle_get_handle ((MonoWaitHandle
*) waitHandle
);
1611 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1613 ret
=WaitForMultipleObjectsEx(numhandles
, handles
, FALSE
, ms
, TRUE
);
1615 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1619 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") returning %d", __func__
, GetCurrentThreadId (), ret
));
1622 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1624 if (ret
>= WAIT_OBJECT_0
&& ret
<= WAIT_OBJECT_0
+ numhandles
- 1) {
1625 return ret
- WAIT_OBJECT_0
;
1627 else if (ret
>= WAIT_ABANDONED_0
&& ret
<= WAIT_ABANDONED_0
+ numhandles
- 1) {
1628 return ret
- WAIT_ABANDONED_0
;
1635 /* FIXME: exitContext isnt documented */
1636 gboolean
ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject
*this, HANDLE handle
, gint32 ms
, gboolean exitContext
)
1639 MonoInternalThread
*thread
= mono_thread_internal_current ();
1641 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") waiting for %p, %d ms", __func__
, GetCurrentThreadId (), handle
, ms
));
1647 mono_thread_current_check_pending_interrupt ();
1649 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1651 ret
=WaitForSingleObjectEx (handle
, ms
, TRUE
);
1653 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1655 if(ret
==WAIT_FAILED
) {
1656 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait failed", __func__
, GetCurrentThreadId ()));
1658 } else if(ret
==WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
) {
1659 /* Do we want to try again if we get
1660 * WAIT_IO_COMPLETION? The documentation for
1661 * WaitHandle doesn't give any clues. (We'd have to
1662 * fiddle with the timeout if we retry.)
1664 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Wait timed out", __func__
, GetCurrentThreadId ()));
1672 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal
, HANDLE toWait
, gint32 ms
, gboolean exitContext
)
1675 MonoInternalThread
*thread
= mono_thread_internal_current ();
1677 MONO_ARCH_SAVE_REGS
;
1682 mono_thread_current_check_pending_interrupt ();
1684 mono_thread_set_state (thread
, ThreadState_WaitSleepJoin
);
1686 ret
= SignalObjectAndWait (toSignal
, toWait
, ms
, TRUE
);
1688 mono_thread_clr_state (thread
, ThreadState_WaitSleepJoin
);
1690 return (!(ret
== WAIT_TIMEOUT
|| ret
== WAIT_IO_COMPLETION
|| ret
== WAIT_FAILED
));
1693 HANDLE
ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned
, MonoString
*name
, MonoBoolean
*created
)
1697 MONO_ARCH_SAVE_REGS
;
1702 mutex
= CreateMutex (NULL
, owned
, NULL
);
1704 mutex
= CreateMutex (NULL
, owned
, mono_string_chars (name
));
1706 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1714 MonoBoolean
ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle
) {
1715 MONO_ARCH_SAVE_REGS
;
1717 return(ReleaseMutex (handle
));
1720 HANDLE
ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString
*name
,
1726 MONO_ARCH_SAVE_REGS
;
1728 *error
= ERROR_SUCCESS
;
1730 ret
= OpenMutex (rights
, FALSE
, mono_string_chars (name
));
1732 *error
= GetLastError ();
1739 HANDLE
ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount
, gint32 maximumCount
, MonoString
*name
, MonoBoolean
*created
)
1743 MONO_ARCH_SAVE_REGS
;
1748 sem
= CreateSemaphore (NULL
, initialCount
, maximumCount
, NULL
);
1750 sem
= CreateSemaphore (NULL
, initialCount
, maximumCount
,
1751 mono_string_chars (name
));
1753 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1761 gint32
ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle
, gint32 releaseCount
, MonoBoolean
*fail
)
1765 MONO_ARCH_SAVE_REGS
;
1767 *fail
= !ReleaseSemaphore (handle
, releaseCount
, &prevcount
);
1772 HANDLE
ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString
*name
, gint32 rights
, gint32
*error
)
1776 MONO_ARCH_SAVE_REGS
;
1778 *error
= ERROR_SUCCESS
;
1780 ret
= OpenSemaphore (rights
, FALSE
, mono_string_chars (name
));
1782 *error
= GetLastError ();
1788 HANDLE
ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual
, MonoBoolean initial
, MonoString
*name
, MonoBoolean
*created
)
1792 MONO_ARCH_SAVE_REGS
;
1797 event
= CreateEvent (NULL
, manual
, initial
, NULL
);
1799 event
= CreateEvent (NULL
, manual
, initial
,
1800 mono_string_chars (name
));
1802 if (GetLastError () == ERROR_ALREADY_EXISTS
) {
1810 gboolean
ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle
) {
1811 MONO_ARCH_SAVE_REGS
;
1813 return (SetEvent(handle
));
1816 gboolean
ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle
) {
1817 MONO_ARCH_SAVE_REGS
;
1819 return (ResetEvent(handle
));
1823 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle
) {
1824 MONO_ARCH_SAVE_REGS
;
1826 CloseHandle (handle
);
1829 HANDLE
ves_icall_System_Threading_Events_OpenEvent_internal (MonoString
*name
,
1835 MONO_ARCH_SAVE_REGS
;
1837 *error
= ERROR_SUCCESS
;
1839 ret
= OpenEvent (rights
, FALSE
, mono_string_chars (name
));
1841 *error
= GetLastError ();
1847 gint32
ves_icall_System_Threading_Interlocked_Increment_Int (gint32
*location
)
1849 MONO_ARCH_SAVE_REGS
;
1851 return InterlockedIncrement (location
);
1854 gint64
ves_icall_System_Threading_Interlocked_Increment_Long (gint64
*location
)
1858 MONO_ARCH_SAVE_REGS
;
1860 mono_interlocked_lock ();
1864 mono_interlocked_unlock ();
1870 gint32
ves_icall_System_Threading_Interlocked_Decrement_Int (gint32
*location
)
1872 MONO_ARCH_SAVE_REGS
;
1874 return InterlockedDecrement(location
);
1877 gint64
ves_icall_System_Threading_Interlocked_Decrement_Long (gint64
* location
)
1881 MONO_ARCH_SAVE_REGS
;
1883 mono_interlocked_lock ();
1887 mono_interlocked_unlock ();
1892 gint32
ves_icall_System_Threading_Interlocked_Exchange_Int (gint32
*location
, gint32 value
)
1894 MONO_ARCH_SAVE_REGS
;
1896 return InterlockedExchange(location
, value
);
1899 MonoObject
* ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject
**location
, MonoObject
*value
)
1902 res
= (MonoObject
*) InterlockedExchangePointer((gpointer
*) location
, value
);
1903 mono_gc_wbarrier_generic_nostore (location
);
1907 gpointer
ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer
*location
, gpointer value
)
1909 return InterlockedExchangePointer(location
, value
);
1912 gfloat
ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat
*location
, gfloat value
)
1914 IntFloatUnion val
, ret
;
1916 MONO_ARCH_SAVE_REGS
;
1919 ret
.ival
= InterlockedExchange((gint32
*) location
, val
.ival
);
1925 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64
*location
, gint64 value
)
1927 #if SIZEOF_VOID_P == 8
1928 return (gint64
) InterlockedExchangePointer((gpointer
*) location
, (gpointer
)value
);
1933 * According to MSDN, this function is only atomic with regards to the
1934 * other Interlocked functions on 32 bit platforms.
1936 mono_interlocked_lock ();
1939 mono_interlocked_unlock ();
1946 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble
*location
, gdouble value
)
1948 #if SIZEOF_VOID_P == 8
1949 LongDoubleUnion val
, ret
;
1952 ret
.ival
= (gint64
)InterlockedExchangePointer((gpointer
*) location
, (gpointer
)val
.ival
);
1959 * According to MSDN, this function is only atomic with regards to the
1960 * other Interlocked functions on 32 bit platforms.
1962 mono_interlocked_lock ();
1965 mono_interlocked_unlock ();
1971 gint32
ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32
*location
, gint32 value
, gint32 comparand
)
1973 MONO_ARCH_SAVE_REGS
;
1975 return InterlockedCompareExchange(location
, value
, comparand
);
1978 MonoObject
* ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
1981 res
= (MonoObject
*) InterlockedCompareExchangePointer((gpointer
*) location
, value
, comparand
);
1982 mono_gc_wbarrier_generic_nostore (location
);
1986 gpointer
ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer
*location
, gpointer value
, gpointer comparand
)
1988 return InterlockedCompareExchangePointer(location
, value
, comparand
);
1991 gfloat
ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat
*location
, gfloat value
, gfloat comparand
)
1993 IntFloatUnion val
, ret
, cmp
;
1995 MONO_ARCH_SAVE_REGS
;
1998 cmp
.fval
= comparand
;
1999 ret
.ival
= InterlockedCompareExchange((gint32
*) location
, val
.ival
, cmp
.ival
);
2005 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble
*location
, gdouble value
, gdouble comparand
)
2007 #if SIZEOF_VOID_P == 8
2008 LongDoubleUnion val
, comp
, ret
;
2011 comp
.fval
= comparand
;
2012 ret
.ival
= (gint64
)InterlockedCompareExchangePointer((gpointer
*) location
, (gpointer
)val
.ival
, (gpointer
)comp
.ival
);
2018 mono_interlocked_lock ();
2020 if (old
== comparand
)
2022 mono_interlocked_unlock ();
2029 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64
*location
, gint64 value
, gint64 comparand
)
2031 #if SIZEOF_VOID_P == 8
2032 return (gint64
)InterlockedCompareExchangePointer((gpointer
*) location
, (gpointer
)value
, (gpointer
)comparand
);
2036 mono_interlocked_lock ();
2038 if (old
== comparand
)
2040 mono_interlocked_unlock ();
2047 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject
**location
, MonoObject
*value
, MonoObject
*comparand
)
2050 res
= InterlockedCompareExchangePointer ((gpointer
*)location
, value
, comparand
);
2051 mono_gc_wbarrier_generic_nostore (location
);
2056 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject
**location
, MonoObject
*value
)
2059 res
= InterlockedExchangePointer ((gpointer
*)location
, value
);
2060 mono_gc_wbarrier_generic_nostore (location
);
2065 ves_icall_System_Threading_Interlocked_Add_Int (gint32
*location
, gint32 value
)
2067 #if SIZEOF_VOID_P == 8
2068 /* Should be implemented as a JIT intrinsic */
2069 mono_raise_exception (mono_get_exception_not_implemented (NULL
));
2074 mono_interlocked_lock ();
2076 *location
= orig
+ value
;
2077 mono_interlocked_unlock ();
2079 return orig
+ value
;
2084 ves_icall_System_Threading_Interlocked_Add_Long (gint64
*location
, gint64 value
)
2086 #if SIZEOF_VOID_P == 8
2087 /* Should be implemented as a JIT intrinsic */
2088 mono_raise_exception (mono_get_exception_not_implemented (NULL
));
2093 mono_interlocked_lock ();
2095 *location
= orig
+ value
;
2096 mono_interlocked_unlock ();
2098 return orig
+ value
;
2103 ves_icall_System_Threading_Interlocked_Read_Long (gint64
*location
)
2105 #if SIZEOF_VOID_P == 8
2106 /* 64 bit reads are already atomic */
2111 mono_interlocked_lock ();
2113 mono_interlocked_unlock ();
2120 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2122 mono_threads_lock ();
2123 mono_threads_unlock ();
2127 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread
* this, guint32 state
)
2129 mono_thread_clr_state (this, state
);
2131 if (state
& ThreadState_Background
) {
2132 /* If the thread changes the background mode, the main thread has to
2133 * be notified, since it has to rebuild the list of threads to
2136 SetEvent (background_change_event
);
2141 ves_icall_System_Threading_Thread_SetState (MonoInternalThread
* this, guint32 state
)
2143 mono_thread_set_state (this, state
);
2145 if (state
& ThreadState_Background
) {
2146 /* If the thread changes the background mode, the main thread has to
2147 * be notified, since it has to rebuild the list of threads to
2150 SetEvent (background_change_event
);
2155 ves_icall_System_Threading_Thread_GetState (MonoInternalThread
* this)
2159 ensure_synch_cs_set (this);
2161 EnterCriticalSection (this->synch_cs
);
2163 state
= this->state
;
2165 LeaveCriticalSection (this->synch_cs
);
2170 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread
*this)
2172 gboolean
throw = FALSE
;
2174 ensure_synch_cs_set (this);
2176 if (this == mono_thread_internal_current ())
2179 EnterCriticalSection (this->synch_cs
);
2181 this->thread_interrupt_requested
= TRUE
;
2183 if (this->state
& ThreadState_WaitSleepJoin
) {
2187 LeaveCriticalSection (this->synch_cs
);
2190 signal_thread_state_change (this);
2194 void mono_thread_current_check_pending_interrupt ()
2196 MonoInternalThread
*thread
= mono_thread_internal_current ();
2197 gboolean
throw = FALSE
;
2199 mono_debugger_check_interruption ();
2201 ensure_synch_cs_set (thread
);
2203 EnterCriticalSection (thread
->synch_cs
);
2205 if (thread
->thread_interrupt_requested
) {
2207 thread
->thread_interrupt_requested
= FALSE
;
2210 LeaveCriticalSection (thread
->synch_cs
);
2213 mono_raise_exception (mono_get_exception_thread_interrupted ());
2218 mono_thread_get_abort_signal (void)
2230 static int abort_signum
= -1;
2232 if (abort_signum
!= -1)
2233 return abort_signum
;
2234 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2235 for (i
= SIGRTMIN
+ 1; i
< SIGRTMAX
; ++i
) {
2236 struct sigaction sinfo
;
2237 sigaction (i
, NULL
, &sinfo
);
2238 if (sinfo
.sa_handler
== SIG_DFL
&& (void*)sinfo
.sa_sigaction
== (void*)SIG_DFL
) {
2243 /* fallback to the old way */
2246 #endif /* HOST_WIN32 */
2250 static void CALLBACK
interruption_request_apc (ULONG_PTR param
)
2252 MonoException
* exc
= mono_thread_request_interruption (FALSE
);
2253 if (exc
) mono_raise_exception (exc
);
2255 #endif /* HOST_WIN32 */
2258 * signal_thread_state_change
2260 * Tells the thread that his state has changed and it has to enter the new
2261 * state as soon as possible.
2263 static void signal_thread_state_change (MonoInternalThread
*thread
)
2265 if (thread
== mono_thread_internal_current ()) {
2266 /* Do it synchronously */
2267 MonoException
*exc
= mono_thread_request_interruption (FALSE
);
2269 mono_raise_exception (exc
);
2273 QueueUserAPC ((PAPCFUNC
)interruption_request_apc
, thread
->handle
, NULL
);
2275 /* fixme: store the state somewhere */
2276 #ifdef PTHREAD_POINTER_ID
2277 pthread_kill ((gpointer
)(gsize
)(thread
->tid
), mono_thread_get_abort_signal ());
2279 pthread_kill (thread
->tid
, mono_thread_get_abort_signal ());
2283 * This will cause waits to be broken.
2284 * It will also prevent the thread from entering a wait, so if the thread returns
2285 * from the wait before it receives the abort signal, it will just spin in the wait
2286 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2289 wapi_interrupt_thread (thread
->handle
);
2290 #endif /* HOST_WIN32 */
2294 ves_icall_System_Threading_Thread_Abort (MonoInternalThread
*thread
, MonoObject
*state
)
2296 ensure_synch_cs_set (thread
);
2298 EnterCriticalSection (thread
->synch_cs
);
2300 if ((thread
->state
& ThreadState_AbortRequested
) != 0 ||
2301 (thread
->state
& ThreadState_StopRequested
) != 0 ||
2302 (thread
->state
& ThreadState_Stopped
) != 0)
2304 LeaveCriticalSection (thread
->synch_cs
);
2308 if ((thread
->state
& ThreadState_Unstarted
) != 0) {
2309 thread
->state
|= ThreadState_Aborted
;
2310 LeaveCriticalSection (thread
->synch_cs
);
2314 thread
->state
|= ThreadState_AbortRequested
;
2315 if (thread
->abort_state_handle
)
2316 mono_gchandle_free (thread
->abort_state_handle
);
2318 thread
->abort_state_handle
= mono_gchandle_new (state
, FALSE
);
2319 g_assert (thread
->abort_state_handle
);
2321 thread
->abort_state_handle
= 0;
2323 thread
->abort_exc
= NULL
;
2326 * abort_exc is set in mono_thread_execute_interruption(),
2327 * triggered by the call to signal_thread_state_change(),
2328 * below. There's a point between where we have
2329 * abort_state_handle set, but abort_exc NULL, but that's not
2333 LeaveCriticalSection (thread
->synch_cs
);
2335 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT
") Abort requested for %p (%"G_GSIZE_FORMAT
")", __func__
, GetCurrentThreadId (), thread
, (gsize
)thread
->tid
));
2337 /* During shutdown, we can't wait for other threads */
2339 /* Make sure the thread is awake */
2340 mono_thread_resume (thread
);
2342 signal_thread_state_change (thread
);
2346 ves_icall_System_Threading_Thread_ResetAbort (void)
2348 MonoInternalThread
*thread
= mono_thread_internal_current ();
2349 gboolean was_aborting
;
2351 ensure_synch_cs_set (thread
);
2353 EnterCriticalSection (thread
->synch_cs
);
2354 was_aborting
= thread
->state
& ThreadState_AbortRequested
;
2355 thread
->state
&= ~ThreadState_AbortRequested
;
2356 LeaveCriticalSection (thread
->synch_cs
);
2358 if (!was_aborting
) {
2359 const char *msg
= "Unable to reset abort because no abort was requested";
2360 mono_raise_exception (mono_get_exception_thread_state (msg
));
2362 thread
->abort_exc
= NULL
;
2363 if (thread
->abort_state_handle
) {
2364 mono_gchandle_free (thread
->abort_state_handle
);
2365 /* This is actually not necessary - the handle
2366 only counts if the exception is set */
2367 thread
->abort_state_handle
= 0;
2372 mono_thread_internal_reset_abort (MonoInternalThread
*thread
)
2374 ensure_synch_cs_set (thread
);
2376 EnterCriticalSection (thread
->synch_cs
);
2378 thread
->state
&= ~ThreadState_AbortRequested
;
2380 if (thread
->abort_exc
) {
2381 thread
->abort_exc
= NULL
;
2382 if (thread
->abort_state_handle
) {
2383 mono_gchandle_free (thread
->abort_state_handle
);
2384 /* This is actually not necessary - the handle
2385 only counts if the exception is set */
2386 thread
->abort_state_handle
= 0;
2390 LeaveCriticalSection (thread
->synch_cs
);
2394 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread
*this)
2396 MonoInternalThread
*thread
= this->internal_thread
;
2397 MonoObject
*state
, *deserialized
= NULL
, *exc
;
2400 if (!thread
->abort_state_handle
)
2403 state
= mono_gchandle_get_target (thread
->abort_state_handle
);
2406 domain
= mono_domain_get ();
2407 if (mono_object_domain (state
) == domain
)
2410 deserialized
= mono_object_xdomain_representation (state
, domain
, &exc
);
2412 if (!deserialized
) {
2413 MonoException
*invalid_op_exc
= mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2415 MONO_OBJECT_SETREF (invalid_op_exc
, inner_ex
, exc
);
2416 mono_raise_exception (invalid_op_exc
);
2419 return deserialized
;
2423 mono_thread_suspend (MonoInternalThread
*thread
)
2425 ensure_synch_cs_set (thread
);
2427 EnterCriticalSection (thread
->synch_cs
);
2429 if ((thread
->state
& ThreadState_Unstarted
) != 0 ||
2430 (thread
->state
& ThreadState_Aborted
) != 0 ||
2431 (thread
->state
& ThreadState_Stopped
) != 0)
2433 LeaveCriticalSection (thread
->synch_cs
);
2437 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
2438 (thread
->state
& ThreadState_SuspendRequested
) != 0 ||
2439 (thread
->state
& ThreadState_StopRequested
) != 0)
2441 LeaveCriticalSection (thread
->synch_cs
);
2445 thread
->state
|= ThreadState_SuspendRequested
;
2447 LeaveCriticalSection (thread
->synch_cs
);
2449 signal_thread_state_change (thread
);
2454 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread
*thread
)
2456 if (!mono_thread_suspend (thread
))
2457 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2461 mono_thread_resume (MonoInternalThread
*thread
)
2463 ensure_synch_cs_set (thread
);
2465 EnterCriticalSection (thread
->synch_cs
);
2467 if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
2468 thread
->state
&= ~ThreadState_SuspendRequested
;
2469 LeaveCriticalSection (thread
->synch_cs
);
2473 if ((thread
->state
& ThreadState_Suspended
) == 0 ||
2474 (thread
->state
& ThreadState_Unstarted
) != 0 ||
2475 (thread
->state
& ThreadState_Aborted
) != 0 ||
2476 (thread
->state
& ThreadState_Stopped
) != 0)
2478 LeaveCriticalSection (thread
->synch_cs
);
2482 thread
->resume_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
2483 if (thread
->resume_event
== NULL
) {
2484 LeaveCriticalSection (thread
->synch_cs
);
2488 /* Awake the thread */
2489 SetEvent (thread
->suspend_event
);
2491 LeaveCriticalSection (thread
->synch_cs
);
2493 /* Wait for the thread to awake */
2494 WaitForSingleObject (thread
->resume_event
, INFINITE
);
2495 CloseHandle (thread
->resume_event
);
2496 thread
->resume_event
= NULL
;
2502 ves_icall_System_Threading_Thread_Resume (MonoThread
*thread
)
2504 if (!thread
->internal_thread
|| !mono_thread_resume (thread
->internal_thread
))
2505 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2509 find_wrapper (MonoMethod
*m
, gint no
, gint ilo
, gboolean managed
, gpointer data
)
2514 if (m
->wrapper_type
== MONO_WRAPPER_RUNTIME_INVOKE
||
2515 m
->wrapper_type
== MONO_WRAPPER_XDOMAIN_INVOKE
||
2516 m
->wrapper_type
== MONO_WRAPPER_XDOMAIN_DISPATCH
)
2518 *((gboolean
*)data
) = TRUE
;
2525 is_running_protected_wrapper (void)
2527 gboolean found
= FALSE
;
2528 mono_stack_walk (find_wrapper
, &found
);
2532 void mono_thread_internal_stop (MonoInternalThread
*thread
)
2534 ensure_synch_cs_set (thread
);
2536 EnterCriticalSection (thread
->synch_cs
);
2538 if ((thread
->state
& ThreadState_StopRequested
) != 0 ||
2539 (thread
->state
& ThreadState_Stopped
) != 0)
2541 LeaveCriticalSection (thread
->synch_cs
);
2545 /* Make sure the thread is awake */
2546 mono_thread_resume (thread
);
2548 thread
->state
|= ThreadState_StopRequested
;
2549 thread
->state
&= ~ThreadState_AbortRequested
;
2551 LeaveCriticalSection (thread
->synch_cs
);
2553 signal_thread_state_change (thread
);
2556 void mono_thread_stop (MonoThread
*thread
)
2558 mono_thread_internal_stop (thread
->internal_thread
);
2562 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr
)
2564 return *((volatile gint8
*) (ptr
));
2568 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr
)
2570 return *((volatile gint16
*) (ptr
));
2574 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr
)
2576 return *((volatile gint32
*) (ptr
));
2580 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr
)
2582 return *((volatile gint64
*) (ptr
));
2586 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr
)
2588 return (void *) *((volatile void **) ptr
);
2592 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr
, gint8 value
)
2594 *((volatile gint8
*) ptr
) = value
;
2598 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr
, gint16 value
)
2600 *((volatile gint16
*) ptr
) = value
;
2604 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr
, gint32 value
)
2606 *((volatile gint32
*) ptr
) = value
;
2610 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr
, gint64 value
)
2612 *((volatile gint64
*) ptr
) = value
;
2616 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr
, void *value
)
2618 *((volatile void **) ptr
) = value
;
2622 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr
, void *value
)
2624 mono_gc_wbarrier_generic_store (ptr
, value
);
2627 void mono_thread_init (MonoThreadStartCB start_cb
,
2628 MonoThreadAttachCB attach_cb
)
2630 MONO_GC_REGISTER_ROOT (small_id_table
);
2631 InitializeCriticalSection(&threads_mutex
);
2632 InitializeCriticalSection(&interlocked_mutex
);
2633 InitializeCriticalSection(&contexts_mutex
);
2634 InitializeCriticalSection(&delayed_free_table_mutex
);
2635 InitializeCriticalSection(&small_id_mutex
);
2637 background_change_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
2638 g_assert(background_change_event
!= NULL
);
2640 mono_init_static_data_info (&thread_static_info
);
2641 mono_init_static_data_info (&context_static_info
);
2643 current_object_key
=TlsAlloc();
2644 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__
, current_object_key
));
2646 mono_thread_start_cb
= start_cb
;
2647 mono_thread_attach_cb
= attach_cb
;
2649 delayed_free_table
= g_array_new (FALSE
, FALSE
, sizeof (DelayedFreeItem
));
2651 /* Get a pseudo handle to the current process. This is just a
2652 * kludge so that wapi can build a process handle if needed.
2653 * As a pseudo handle is returned, we don't need to clean
2656 GetCurrentProcess ();
2659 void mono_thread_cleanup (void)
2661 mono_thread_hazardous_try_free_all ();
2663 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2664 /* The main thread must abandon any held mutexes (particularly
2665 * important for named mutexes as they are shared across
2666 * processes, see bug 74680.) This will happen when the
2667 * thread exits, but if it's not running in a subthread it
2668 * won't exit in time.
2670 /* Using non-w32 API is a nasty kludge, but I couldn't find
2671 * anything in the documentation that would let me do this
2672 * here yet still be safe to call on windows.
2674 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2678 /* This stuff needs more testing, it seems one of these
2679 * critical sections can be locked when mono_thread_cleanup is
2682 DeleteCriticalSection (&threads_mutex
);
2683 DeleteCriticalSection (&interlocked_mutex
);
2684 DeleteCriticalSection (&contexts_mutex
);
2685 DeleteCriticalSection (&delayed_free_table_mutex
);
2686 DeleteCriticalSection (&small_id_mutex
);
2687 CloseHandle (background_change_event
);
2690 g_array_free (delayed_free_table
, TRUE
);
2691 delayed_free_table
= NULL
;
2693 TlsFree (current_object_key
);
2697 mono_threads_install_cleanup (MonoThreadCleanupFunc func
)
2699 mono_thread_cleanup_fn
= func
;
2703 mono_thread_set_manage_callback (MonoThread
*thread
, MonoThreadManageCallback func
)
2705 thread
->internal_thread
->manage_callback
= func
;
2708 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func
)
2710 mono_thread_notify_pending_exc_fn
= func
;
2714 static void print_tids (gpointer key
, gpointer value
, gpointer user
)
2716 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2717 * sizeof(uint) and a cast to uint would overflow
2719 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2720 * print this as a pointer.
2722 g_message ("Waiting for: %p", key
);
2727 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
2728 MonoInternalThread
*threads
[MAXIMUM_WAIT_OBJECTS
];
2732 static void wait_for_tids (struct wait_data
*wait
, guint32 timeout
)
2736 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
2738 ret
=WaitForMultipleObjectsEx(wait
->num
, wait
->handles
, TRUE
, timeout
, FALSE
);
2740 if(ret
==WAIT_FAILED
) {
2741 /* See the comment in build_wait_tids() */
2742 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
2746 for(i
=0; i
<wait
->num
; i
++)
2747 CloseHandle (wait
->handles
[i
]);
2749 if (ret
== WAIT_TIMEOUT
)
2752 for(i
=0; i
<wait
->num
; i
++) {
2753 gsize tid
= wait
->threads
[i
]->tid
;
2755 mono_threads_lock ();
2756 if(mono_g_hash_table_lookup (threads
, (gpointer
)tid
)!=NULL
) {
2757 /* This thread must have been killed, because
2758 * it hasn't cleaned itself up. (It's just
2759 * possible that the thread exited before the
2760 * parent thread had a chance to store the
2761 * handle, and now there is another pointer to
2762 * the already-exited thread stored. In this
2763 * case, we'll just get two
2764 * mono_profiler_thread_end() calls for the
2768 mono_threads_unlock ();
2769 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT
")", __func__
, wait
->threads
[i
], tid
));
2770 thread_cleanup (wait
->threads
[i
]);
2772 mono_threads_unlock ();
2777 static void wait_for_tids_or_state_change (struct wait_data
*wait
, guint32 timeout
)
2779 guint32 i
, ret
, count
;
2781 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__
, wait
->num
));
2783 /* Add the thread state change event, so it wakes up if a thread changes
2784 * to background mode.
2787 if (count
< MAXIMUM_WAIT_OBJECTS
) {
2788 wait
->handles
[count
] = background_change_event
;
2792 ret
=WaitForMultipleObjectsEx (count
, wait
->handles
, FALSE
, timeout
, FALSE
);
2794 if(ret
==WAIT_FAILED
) {
2795 /* See the comment in build_wait_tids() */
2796 THREAD_DEBUG (g_message ("%s: Wait failed", __func__
));
2800 for(i
=0; i
<wait
->num
; i
++)
2801 CloseHandle (wait
->handles
[i
]);
2803 if (ret
== WAIT_TIMEOUT
)
2806 if (ret
< wait
->num
) {
2807 gsize tid
= wait
->threads
[ret
]->tid
;
2808 mono_threads_lock ();
2809 if (mono_g_hash_table_lookup (threads
, (gpointer
)tid
)!=NULL
) {
2810 /* See comment in wait_for_tids about thread cleanup */
2811 mono_threads_unlock ();
2812 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT
, __func__
, tid
));
2813 thread_cleanup (wait
->threads
[ret
]);
2815 mono_threads_unlock ();
2819 static void build_wait_tids (gpointer key
, gpointer value
, gpointer user
)
2821 struct wait_data
*wait
=(struct wait_data
*)user
;
2823 if(wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
2825 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
2827 /* Ignore background threads, we abort them later */
2828 /* Do not lock here since it is not needed and the caller holds threads_lock */
2829 if (thread
->state
& ThreadState_Background
) {
2830 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2831 return; /* just leave, ignore */
2834 if (mono_gc_is_finalizer_internal_thread (thread
)) {
2835 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2839 if (thread
== mono_thread_internal_current ()) {
2840 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2844 if (mono_thread_get_main () && (thread
== mono_thread_get_main ()->internal_thread
)) {
2845 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2849 if (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
) {
2850 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT
"with DONT_MANAGE flag set.", __func__
, (gsize
)thread
->tid
));
2854 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
2855 if (handle
== NULL
) {
2856 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2860 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__
, thread
));
2861 if ((thread
->manage_callback
== NULL
) || (thread
->manage_callback (thread
->root_domain_thread
) == TRUE
)) {
2862 wait
->handles
[wait
->num
]=handle
;
2863 wait
->threads
[wait
->num
]=thread
;
2866 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2868 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT
, __func__
, (gsize
)thread
->tid
));
2873 /* Just ignore the rest, we can't do anything with
2880 remove_and_abort_threads (gpointer key
, gpointer value
, gpointer user
)
2882 struct wait_data
*wait
=(struct wait_data
*)user
;
2883 gsize self
= GetCurrentThreadId ();
2884 MonoInternalThread
*thread
= value
;
2887 if (wait
->num
>= MAXIMUM_WAIT_OBJECTS
)
2890 /* The finalizer thread is not a background thread */
2891 if (thread
->tid
!= self
&& (thread
->state
& ThreadState_Background
) != 0 &&
2892 !(thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)) {
2894 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
2898 /* printf ("A: %d\n", wait->num); */
2899 wait
->handles
[wait
->num
]=thread
->handle
;
2900 wait
->threads
[wait
->num
]=thread
;
2903 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT
"\n", __func__
, (gsize
)thread
->tid
));
2904 mono_thread_internal_stop (thread
);
2908 return (thread
->tid
!= self
&& !mono_gc_is_finalizer_internal_thread (thread
));
2912 * mono_threads_set_shutting_down:
2914 * Is called by a thread that wants to shut down Mono. If the runtime is already
2915 * shutting down, the calling thread is suspended/stopped, and this function never
2919 mono_threads_set_shutting_down (void)
2921 MonoInternalThread
*current_thread
= mono_thread_internal_current ();
2923 mono_threads_lock ();
2925 if (shutting_down
) {
2926 mono_threads_unlock ();
2928 /* Make sure we're properly suspended/stopped */
2930 EnterCriticalSection (current_thread
->synch_cs
);
2932 if ((current_thread
->state
& ThreadState_SuspendRequested
) ||
2933 (current_thread
->state
& ThreadState_AbortRequested
) ||
2934 (current_thread
->state
& ThreadState_StopRequested
)) {
2935 LeaveCriticalSection (current_thread
->synch_cs
);
2936 mono_thread_execute_interruption (current_thread
);
2938 current_thread
->state
|= ThreadState_Stopped
;
2939 LeaveCriticalSection (current_thread
->synch_cs
);
2942 /* Wake up other threads potentially waiting for us */
2945 shutting_down
= TRUE
;
2947 /* Not really a background state change, but this will
2948 * interrupt the main thread if it is waiting for all
2949 * the other threads.
2951 SetEvent (background_change_event
);
2953 mono_threads_unlock ();
2958 * mono_threads_is_shutting_down:
2960 * Returns whether a thread has commenced shutdown of Mono. Note that
2961 * if the function returns FALSE the caller must not assume that
2962 * shutdown is not in progress, because the situation might have
2963 * changed since the function returned. For that reason this function
2964 * is of very limited utility.
2967 mono_threads_is_shutting_down (void)
2969 return shutting_down
;
2972 void mono_thread_manage (void)
2974 struct wait_data
*wait
=g_new0 (struct wait_data
, 1);
2976 /* join each thread that's still running */
2977 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__
));
2979 mono_threads_lock ();
2981 THREAD_DEBUG (g_message("%s: No threads", __func__
));
2982 mono_threads_unlock ();
2986 mono_threads_unlock ();
2989 mono_threads_lock ();
2990 if (shutting_down
) {
2991 /* somebody else is shutting down */
2992 mono_threads_unlock ();
2995 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__
, mono_g_hash_table_size (threads
));
2996 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
2998 ResetEvent (background_change_event
);
3000 mono_g_hash_table_foreach (threads
, build_wait_tids
, wait
);
3001 mono_threads_unlock ();
3003 /* Something to wait for */
3004 wait_for_tids_or_state_change (wait
, INFINITE
);
3006 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__
, wait
->num
));
3007 } while(wait
->num
>0);
3009 mono_threads_set_shutting_down ();
3011 /* No new threads will be created after this point */
3013 mono_runtime_set_shutting_down ();
3015 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__
));
3016 mono_thread_pool_cleanup ();
3019 * Remove everything but the finalizer thread and self.
3020 * Also abort all the background threads
3023 mono_threads_lock ();
3026 mono_g_hash_table_foreach_remove (threads
, remove_and_abort_threads
, wait
);
3028 mono_threads_unlock ();
3030 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__
, wait
->num
));
3032 /* Something to wait for */
3033 wait_for_tids (wait
, INFINITE
);
3035 } while (wait
->num
> 0);
3038 * give the subthreads a chance to really quit (this is mainly needed
3039 * to get correct user and system times from getrusage/wait/time(1)).
3040 * This could be removed if we avoid pthread_detach() and use pthread_join().
3049 static void terminate_thread (gpointer key
, gpointer value
, gpointer user
)
3051 MonoInternalThread
*thread
=(MonoInternalThread
*)value
;
3053 if(thread
->tid
!= (gsize
)user
) {
3054 /*TerminateThread (thread->handle, -1);*/
3058 void mono_thread_abort_all_other_threads (void)
3060 gsize self
= GetCurrentThreadId ();
3062 mono_threads_lock ();
3063 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__
,
3064 mono_g_hash_table_size (threads
));
3065 mono_g_hash_table_foreach (threads
, print_tids
, NULL
));
3067 mono_g_hash_table_foreach (threads
, terminate_thread
, (gpointer
)self
);
3069 mono_threads_unlock ();
3073 collect_threads_for_suspend (gpointer key
, gpointer value
, gpointer user_data
)
3075 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3076 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3080 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3082 * This needs no locking.
3084 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3085 (thread
->state
& ThreadState_Stopped
) != 0)
3088 if (wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
3089 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3093 wait
->handles
[wait
->num
] = handle
;
3094 wait
->threads
[wait
->num
] = thread
;
3100 * mono_thread_suspend_all_other_threads:
3102 * Suspend all managed threads except the finalizer thread and this thread. It is
3103 * not possible to resume them later.
3105 void mono_thread_suspend_all_other_threads (void)
3107 struct wait_data
*wait
= g_new0 (struct wait_data
, 1);
3109 gsize self
= GetCurrentThreadId ();
3111 guint32 eventidx
= 0;
3112 gboolean starting
, finished
;
3115 * The other threads could be in an arbitrary state at this point, i.e.
3116 * they could be starting up, shutting down etc. This means that there could be
3117 * threads which are not even in the threads hash table yet.
3121 * First we set a barrier which will be checked by all threads before they
3122 * are added to the threads hash table, and they will exit if the flag is set.
3123 * This ensures that no threads could be added to the hash later.
3124 * We will use shutting_down as the barrier for now.
3126 g_assert (shutting_down
);
3129 * We make multiple calls to WaitForMultipleObjects since:
3130 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3131 * - some threads could exit without becoming suspended
3136 * Make a copy of the hashtable since we can't do anything with
3137 * threads while threads_mutex is held.
3140 mono_threads_lock ();
3141 mono_g_hash_table_foreach (threads
, collect_threads_for_suspend
, wait
);
3142 mono_threads_unlock ();
3144 events
= g_new0 (gpointer
, wait
->num
);
3146 /* Get the suspended events that we'll be waiting for */
3147 for (i
= 0; i
< wait
->num
; ++i
) {
3148 MonoInternalThread
*thread
= wait
->threads
[i
];
3149 gboolean signal_suspend
= FALSE
;
3151 if ((thread
->tid
== self
) || mono_gc_is_finalizer_internal_thread (thread
) || (thread
->flags
& MONO_THREAD_FLAG_DONT_MANAGE
)) {
3152 //CloseHandle (wait->handles [i]);
3153 wait
->threads
[i
] = NULL
; /* ignore this thread in next loop */
3157 ensure_synch_cs_set (thread
);
3159 EnterCriticalSection (thread
->synch_cs
);
3161 if (thread
->suspended_event
== NULL
) {
3162 thread
->suspended_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
3163 if (thread
->suspended_event
== NULL
) {
3164 /* Forget this one and go on to the next */
3165 LeaveCriticalSection (thread
->synch_cs
);
3170 if ((thread
->state
& ThreadState_Suspended
) != 0 ||
3171 (thread
->state
& ThreadState_StopRequested
) != 0 ||
3172 (thread
->state
& ThreadState_Stopped
) != 0) {
3173 LeaveCriticalSection (thread
->synch_cs
);
3174 CloseHandle (wait
->handles
[i
]);
3175 wait
->threads
[i
] = NULL
; /* ignore this thread in next loop */
3179 if ((thread
->state
& ThreadState_SuspendRequested
) == 0)
3180 signal_suspend
= TRUE
;
3182 events
[eventidx
++] = thread
->suspended_event
;
3184 /* Convert abort requests into suspend requests */
3185 if ((thread
->state
& ThreadState_AbortRequested
) != 0)
3186 thread
->state
&= ~ThreadState_AbortRequested
;
3188 thread
->state
|= ThreadState_SuspendRequested
;
3190 LeaveCriticalSection (thread
->synch_cs
);
3192 /* Signal the thread to suspend */
3194 signal_thread_state_change (thread
);
3198 WaitForMultipleObjectsEx (eventidx
, events
, TRUE
, 100, FALSE
);
3199 for (i
= 0; i
< wait
->num
; ++i
) {
3200 MonoInternalThread
*thread
= wait
->threads
[i
];
3205 ensure_synch_cs_set (thread
);
3207 EnterCriticalSection (thread
->synch_cs
);
3208 if ((thread
->state
& ThreadState_Suspended
) != 0) {
3209 CloseHandle (thread
->suspended_event
);
3210 thread
->suspended_event
= NULL
;
3212 LeaveCriticalSection (thread
->synch_cs
);
3216 * If there are threads which are starting up, we wait until they
3217 * are suspended when they try to register in the threads hash.
3218 * This is guaranteed to finish, since the threads which can create new
3219 * threads get suspended after a while.
3220 * FIXME: The finalizer thread can still create new threads.
3222 mono_threads_lock ();
3223 if (threads_starting_up
)
3224 starting
= mono_g_hash_table_size (threads_starting_up
) > 0;
3227 mono_threads_unlock ();
3241 collect_threads (gpointer key
, gpointer value
, gpointer user_data
)
3243 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3244 struct wait_data
*wait
= (struct wait_data
*)user_data
;
3247 if (wait
->num
<MAXIMUM_WAIT_OBJECTS
) {
3248 handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3252 wait
->handles
[wait
->num
] = handle
;
3253 wait
->threads
[wait
->num
] = thread
;
3259 * mono_threads_request_thread_dump:
3261 * Ask all threads except the current to print their stacktrace to stdout.
3264 mono_threads_request_thread_dump (void)
3266 struct wait_data
*wait
= g_new0 (struct wait_data
, 1);
3270 * Make a copy of the hashtable since we can't do anything with
3271 * threads while threads_mutex is held.
3273 mono_threads_lock ();
3274 mono_g_hash_table_foreach (threads
, collect_threads
, wait
);
3275 mono_threads_unlock ();
3277 for (i
= 0; i
< wait
->num
; ++i
) {
3278 MonoInternalThread
*thread
= wait
->threads
[i
];
3280 if (!mono_gc_is_finalizer_internal_thread (thread
) &&
3281 (thread
!= mono_thread_internal_current ()) &&
3282 !thread
->thread_dump_requested
) {
3283 thread
->thread_dump_requested
= TRUE
;
3285 signal_thread_state_change (thread
);
3288 CloseHandle (wait
->handles
[i
]);
3293 * mono_thread_push_appdomain_ref:
3295 * Register that the current thread may have references to objects in domain
3296 * @domain on its stack. Each call to this function should be paired with a
3297 * call to pop_appdomain_ref.
3300 mono_thread_push_appdomain_ref (MonoDomain
*domain
)
3302 MonoInternalThread
*thread
= mono_thread_internal_current ();
3305 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3306 SPIN_LOCK (thread
->lock_thread_id
);
3307 thread
->appdomain_refs
= g_slist_prepend (thread
->appdomain_refs
, domain
);
3308 SPIN_UNLOCK (thread
->lock_thread_id
);
3313 mono_thread_pop_appdomain_ref (void)
3315 MonoInternalThread
*thread
= mono_thread_internal_current ();
3318 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3319 /* FIXME: How can the list be empty ? */
3320 SPIN_LOCK (thread
->lock_thread_id
);
3321 if (thread
->appdomain_refs
)
3322 thread
->appdomain_refs
= g_slist_remove (thread
->appdomain_refs
, thread
->appdomain_refs
->data
);
3323 SPIN_UNLOCK (thread
->lock_thread_id
);
3328 mono_thread_internal_has_appdomain_ref (MonoInternalThread
*thread
, MonoDomain
*domain
)
3331 SPIN_LOCK (thread
->lock_thread_id
);
3332 res
= g_slist_find (thread
->appdomain_refs
, domain
) != NULL
;
3333 SPIN_UNLOCK (thread
->lock_thread_id
);
3338 mono_thread_has_appdomain_ref (MonoThread
*thread
, MonoDomain
*domain
)
3340 return mono_thread_internal_has_appdomain_ref (thread
->internal_thread
, domain
);
3343 typedef struct abort_appdomain_data
{
3344 struct wait_data wait
;
3346 } abort_appdomain_data
;
3349 collect_appdomain_thread (gpointer key
, gpointer value
, gpointer user_data
)
3351 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3352 abort_appdomain_data
*data
= (abort_appdomain_data
*)user_data
;
3353 MonoDomain
*domain
= data
->domain
;
3355 if (mono_thread_internal_has_appdomain_ref (thread
, domain
)) {
3356 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3358 if(data
->wait
.num
<MAXIMUM_WAIT_OBJECTS
) {
3359 HANDLE handle
= OpenThread (THREAD_ALL_ACCESS
, TRUE
, thread
->tid
);
3362 data
->wait
.handles
[data
->wait
.num
] = handle
;
3363 data
->wait
.threads
[data
->wait
.num
] = thread
;
3366 /* Just ignore the rest, we can't do anything with
3374 * mono_threads_abort_appdomain_threads:
3376 * Abort threads which has references to the given appdomain.
3379 mono_threads_abort_appdomain_threads (MonoDomain
*domain
, int timeout
)
3381 abort_appdomain_data user_data
;
3383 int orig_timeout
= timeout
;
3386 THREAD_DEBUG (g_message ("%s: starting abort", __func__
));
3388 start_time
= mono_msec_ticks ();
3390 mono_threads_lock ();
3392 user_data
.domain
= domain
;
3393 user_data
.wait
.num
= 0;
3394 /* This shouldn't take any locks */
3395 mono_g_hash_table_foreach (threads
, collect_appdomain_thread
, &user_data
);
3396 mono_threads_unlock ();
3398 if (user_data
.wait
.num
> 0) {
3399 /* Abort the threads outside the threads lock */
3400 for (i
= 0; i
< user_data
.wait
.num
; ++i
)
3401 ves_icall_System_Threading_Thread_Abort (user_data
.wait
.threads
[i
], NULL
);
3404 * We should wait for the threads either to abort, or to leave the
3405 * domain. We can't do the latter, so we wait with a timeout.
3407 wait_for_tids (&user_data
.wait
, 100);
3410 /* Update remaining time */
3411 timeout
-= mono_msec_ticks () - start_time
;
3412 start_time
= mono_msec_ticks ();
3414 if (orig_timeout
!= -1 && timeout
< 0)
3417 while (user_data
.wait
.num
> 0);
3419 THREAD_DEBUG (g_message ("%s: abort done", __func__
));
3425 clear_cached_culture (gpointer key
, gpointer value
, gpointer user_data
)
3427 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3428 MonoDomain
*domain
= (MonoDomain
*)user_data
;
3431 /* No locking needed here */
3432 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3434 if (thread
->cached_culture_info
) {
3435 for (i
= 0; i
< NUM_CACHED_CULTURES
* 2; ++i
) {
3436 MonoObject
*obj
= mono_array_get (thread
->cached_culture_info
, MonoObject
*, i
);
3437 if (obj
&& obj
->vtable
->domain
== domain
)
3438 mono_array_set (thread
->cached_culture_info
, MonoObject
*, i
, NULL
);
3444 * mono_threads_clear_cached_culture:
3446 * Clear the cached_current_culture from all threads if it is in the
3450 mono_threads_clear_cached_culture (MonoDomain
*domain
)
3452 mono_threads_lock ();
3453 mono_g_hash_table_foreach (threads
, clear_cached_culture
, domain
);
3454 mono_threads_unlock ();
3458 * mono_thread_get_undeniable_exception:
3460 * Return an exception which needs to be raised when leaving a catch clause.
3461 * This is used for undeniable exception propagation.
3464 mono_thread_get_undeniable_exception (void)
3466 MonoInternalThread
*thread
= mono_thread_internal_current ();
3468 if (thread
&& thread
->abort_exc
&& !is_running_protected_wrapper ()) {
3470 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3471 * exception if the thread no longer references a dying appdomain.
3473 thread
->abort_exc
->trace_ips
= NULL
;
3474 thread
->abort_exc
->stack_trace
= NULL
;
3475 return thread
->abort_exc
;
3481 #if MONO_SMALL_CONFIG
3482 #define NUM_STATIC_DATA_IDX 4
3483 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
3487 #define NUM_STATIC_DATA_IDX 8
3488 static const int static_data_size
[NUM_STATIC_DATA_IDX
] = {
3489 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3493 static uintptr_t* static_reference_bitmaps
[NUM_STATIC_DATA_IDX
];
3497 mark_tls_slots (void *addr
, MonoGCMarkFunc mark_func
)
3500 gpointer
*static_data
= addr
;
3501 for (i
= 0; i
< NUM_STATIC_DATA_IDX
; ++i
) {
3504 if (!static_data
[i
])
3506 numwords
= 1 + static_data_size
[i
] / sizeof (gpointer
) / (sizeof(uintptr_t) * 8);
3507 ptr
= static_data
[i
];
3508 for (j
= 0; j
< numwords
; ++j
, ptr
+= sizeof (uintptr_t) * 8) {
3509 uintptr_t bmap
= static_reference_bitmaps
[i
][j
];
3512 if ((bmap
& 1) && *p
) {
3524 * mono_alloc_static_data
3526 * Allocate memory blocks for storing threads or context static data
3529 mono_alloc_static_data (gpointer
**static_data_ptr
, guint32 offset
, gboolean threadlocal
)
3531 guint idx
= (offset
>> 24) - 1;
3534 gpointer
* static_data
= *static_data_ptr
;
3536 static void* tls_desc
= NULL
;
3539 tls_desc
= mono_gc_make_root_descr_user (mark_tls_slots
);
3541 static_data
= mono_gc_alloc_fixed (static_data_size
[0], threadlocal
?tls_desc
:NULL
);
3542 *static_data_ptr
= static_data
;
3543 static_data
[0] = static_data
;
3546 for (i
= 1; i
<= idx
; ++i
) {
3547 if (static_data
[i
])
3550 static_data
[i
] = threadlocal
?g_malloc0 (static_data_size
[i
]):mono_gc_alloc_fixed (static_data_size
[i
], NULL
);
3552 static_data
[i
] = mono_gc_alloc_fixed (static_data_size
[i
], NULL
);
3558 mono_free_static_data (gpointer
* static_data
, gboolean threadlocal
)
3561 for (i
= 1; i
< NUM_STATIC_DATA_IDX
; ++i
) {
3562 if (!static_data
[i
])
3566 g_free (static_data
[i
]);
3568 mono_gc_free_fixed (static_data
[i
]);
3570 mono_gc_free_fixed (static_data
[i
]);
3573 mono_gc_free_fixed (static_data
);
3577 * mono_init_static_data_info
3579 * Initializes static data counters
3581 static void mono_init_static_data_info (StaticDataInfo
*static_data
)
3583 static_data
->idx
= 0;
3584 static_data
->offset
= 0;
3585 static_data
->freelist
= NULL
;
3589 * mono_alloc_static_data_slot
3591 * Generates an offset for static data. static_data contains the counters
3592 * used to generate it.
3595 mono_alloc_static_data_slot (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
3599 if (!static_data
->idx
&& !static_data
->offset
) {
3601 * we use the first chunk of the first allocation also as
3602 * an array for the rest of the data
3604 static_data
->offset
= sizeof (gpointer
) * NUM_STATIC_DATA_IDX
;
3606 static_data
->offset
+= align
- 1;
3607 static_data
->offset
&= ~(align
- 1);
3608 if (static_data
->offset
+ size
>= static_data_size
[static_data
->idx
]) {
3609 static_data
->idx
++;
3610 g_assert (size
<= static_data_size
[static_data
->idx
]);
3611 g_assert (static_data
->idx
< NUM_STATIC_DATA_IDX
);
3612 static_data
->offset
= 0;
3614 offset
= static_data
->offset
| ((static_data
->idx
+ 1) << 24);
3615 static_data
->offset
+= size
;
3620 * ensure thread static fields already allocated are valid for thread
3621 * This function is called when a thread is created or on thread attach.
3624 thread_adjust_static_data (MonoInternalThread
*thread
)
3628 mono_threads_lock ();
3629 if (thread_static_info
.offset
|| thread_static_info
.idx
> 0) {
3630 /* get the current allocated size */
3631 offset
= thread_static_info
.offset
| ((thread_static_info
.idx
+ 1) << 24);
3632 mono_alloc_static_data (&(thread
->static_data
), offset
, TRUE
);
3634 mono_threads_unlock ();
3638 alloc_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
3640 MonoInternalThread
*thread
= value
;
3641 guint32 offset
= GPOINTER_TO_UINT (user
);
3643 mono_alloc_static_data (&(thread
->static_data
), offset
, TRUE
);
3646 static MonoThreadDomainTls
*
3647 search_tls_slot_in_freelist (StaticDataInfo
*static_data
, guint32 size
, guint32 align
)
3649 MonoThreadDomainTls
* prev
= NULL
;
3650 MonoThreadDomainTls
* tmp
= static_data
->freelist
;
3652 if (tmp
->size
== size
) {
3654 prev
->next
= tmp
->next
;
3656 static_data
->freelist
= tmp
->next
;
3665 update_tls_reference_bitmap (guint32 offset
, uintptr_t *bitmap
, int max_set
)
3668 int idx
= (offset
>> 24) - 1;
3670 if (!static_reference_bitmaps
[idx
])
3671 static_reference_bitmaps
[idx
] = g_new0 (uintptr_t, 1 + static_data_size
[idx
] / sizeof(gpointer
) / (sizeof(uintptr_t) * 8));
3672 rb
= static_reference_bitmaps
[idx
];
3674 offset
/= sizeof (gpointer
);
3675 /* offset is now the bitmap offset */
3676 for (i
= 0; i
< max_set
; ++i
) {
3677 if (bitmap
[i
/ sizeof (uintptr_t)] & (1L << (i
& (sizeof (uintptr_t) * 8 -1))))
3678 rb
[(offset
+ i
) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset
+ i
) & (sizeof (uintptr_t) * 8 -1)));
3683 clear_reference_bitmap (guint32 offset
, guint32 size
)
3685 int idx
= (offset
>> 24) - 1;
3687 rb
= static_reference_bitmaps
[idx
];
3689 offset
/= sizeof (gpointer
);
3690 size
/= sizeof (gpointer
);
3692 /* offset is now the bitmap offset */
3693 for (; offset
< size
; ++offset
)
3694 rb
[offset
/ (sizeof (uintptr_t) * 8)] &= ~(1L << (offset
& (sizeof (uintptr_t) * 8 -1)));
3698 * The offset for a special static variable is composed of three parts:
3699 * a bit that indicates the type of static data (0:thread, 1:context),
3700 * an index in the array of chunks of memory for the thread (thread->static_data)
3701 * and an offset in that chunk of mem. This allows allocating less memory in the
3706 mono_alloc_special_static_data (guint32 static_type
, guint32 size
, guint32 align
, uintptr_t *bitmap
, int max_set
)
3709 if (static_type
== SPECIAL_STATIC_THREAD
) {
3710 MonoThreadDomainTls
*item
;
3711 mono_threads_lock ();
3712 item
= search_tls_slot_in_freelist (&thread_static_info
, size
, align
);
3713 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3715 offset
= item
->offset
;
3718 offset
= mono_alloc_static_data_slot (&thread_static_info
, size
, align
);
3720 update_tls_reference_bitmap (offset
, bitmap
, max_set
);
3721 /* This can be called during startup */
3722 if (threads
!= NULL
)
3723 mono_g_hash_table_foreach (threads
, alloc_thread_static_data_helper
, GUINT_TO_POINTER (offset
));
3724 mono_threads_unlock ();
3726 g_assert (static_type
== SPECIAL_STATIC_CONTEXT
);
3727 mono_contexts_lock ();
3728 offset
= mono_alloc_static_data_slot (&context_static_info
, size
, align
);
3729 mono_contexts_unlock ();
3730 offset
|= 0x80000000; /* Set the high bit to indicate context static data */
3736 mono_get_special_static_data (guint32 offset
)
3738 /* The high bit means either thread (0) or static (1) data. */
3740 guint32 static_type
= (offset
& 0x80000000);
3743 offset
&= 0x7fffffff;
3744 idx
= (offset
>> 24) - 1;
3746 if (static_type
== 0) {
3747 return get_thread_static_data (mono_thread_internal_current (), offset
);
3749 /* Allocate static data block under demand, since we don't have a list
3752 MonoAppContext
*context
= mono_context_get ();
3753 if (!context
->static_data
|| !context
->static_data
[idx
]) {
3754 mono_contexts_lock ();
3755 mono_alloc_static_data (&(context
->static_data
), offset
, FALSE
);
3756 mono_contexts_unlock ();
3758 return ((char*) context
->static_data
[idx
]) + (offset
& 0xffffff);
3768 free_thread_static_data_helper (gpointer key
, gpointer value
, gpointer user
)
3770 MonoInternalThread
*thread
= value
;
3771 TlsOffsetSize
*data
= user
;
3772 int idx
= (data
->offset
>> 24) - 1;
3775 if (!thread
->static_data
|| !thread
->static_data
[idx
])
3777 ptr
= ((char*) thread
->static_data
[idx
]) + (data
->offset
& 0xffffff);
3778 memset (ptr
, 0, data
->size
);
3782 do_free_special (gpointer key
, gpointer value
, gpointer data
)
3784 MonoClassField
*field
= key
;
3785 guint32 offset
= GPOINTER_TO_UINT (value
);
3786 guint32 static_type
= (offset
& 0x80000000);
3789 size
= mono_type_size (field
->type
, &align
);
3790 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3791 if (static_type
== 0) {
3793 MonoThreadDomainTls
*item
= g_new0 (MonoThreadDomainTls
, 1);
3794 data
.offset
= offset
& 0x7fffffff;
3796 clear_reference_bitmap (data
.offset
, data
.size
);
3797 if (threads
!= NULL
)
3798 mono_g_hash_table_foreach (threads
, free_thread_static_data_helper
, &data
);
3799 item
->offset
= offset
;
3801 item
->next
= thread_static_info
.freelist
;
3802 thread_static_info
.freelist
= item
;
3804 /* FIXME: free context static data as well */
3809 mono_alloc_special_static_data_free (GHashTable
*special_static_fields
)
3811 mono_threads_lock ();
3812 g_hash_table_foreach (special_static_fields
, do_free_special
, NULL
);
3813 mono_threads_unlock ();
3816 static MonoClassField
*local_slots
= NULL
;
3819 /* local tls data to get locals_slot from a thread */
3822 /* index in the locals_slot array */
3827 clear_local_slot (gpointer key
, gpointer value
, gpointer user_data
)
3829 LocalSlotID
*sid
= user_data
;
3830 MonoInternalThread
*thread
= (MonoInternalThread
*)value
;
3831 MonoArray
*slots_array
;
3833 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3834 * it is for the right domain, so we need to check if it is allocated an initialized
3835 * for the current thread.
3837 /*g_print ("handling thread %p\n", thread);*/
3838 if (!thread
->static_data
|| !thread
->static_data
[sid
->idx
])
3840 slots_array
= *(MonoArray
**)(((char*) thread
->static_data
[sid
->idx
]) + (sid
->offset
& 0xffffff));
3841 if (!slots_array
|| sid
->slot
>= mono_array_length (slots_array
))
3843 mono_array_set (slots_array
, MonoObject
*, sid
->slot
, NULL
);
3847 mono_thread_free_local_slot_values (int slot
, MonoBoolean thread_local
)
3855 local_slots
= mono_class_get_field_from_name (mono_defaults
.thread_class
, "local_slots");
3857 g_warning ("local_slots field not found in Thread class");
3861 domain
= mono_domain_get ();
3862 mono_domain_lock (domain
);
3863 if (domain
->special_static_fields
)
3864 addr
= g_hash_table_lookup (domain
->special_static_fields
, local_slots
);
3865 mono_domain_unlock (domain
);
3868 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3869 sid
.offset
= GPOINTER_TO_UINT (addr
);
3870 sid
.offset
&= 0x7fffffff;
3871 sid
.idx
= (sid
.offset
>> 24) - 1;
3872 mono_threads_lock ();
3873 mono_g_hash_table_foreach (threads
, clear_local_slot
, &sid
);
3874 mono_threads_unlock ();
3876 /* FIXME: clear the slot for MonoAppContexts, too */
3881 static void CALLBACK
dummy_apc (ULONG_PTR param
)
3885 static guint32
dummy_apc (gpointer param
)
3892 * mono_thread_execute_interruption
3894 * Performs the operation that the requested thread state requires (abort,
3897 static MonoException
* mono_thread_execute_interruption (MonoInternalThread
*thread
)
3899 ensure_synch_cs_set (thread
);
3901 EnterCriticalSection (thread
->synch_cs
);
3903 /* MonoThread::interruption_requested can only be changed with atomics */
3904 if (InterlockedCompareExchange (&thread
->interruption_requested
, FALSE
, TRUE
)) {
3905 /* this will consume pending APC calls */
3906 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE
);
3907 InterlockedDecrement (&thread_interruption_requested
);
3909 /* Clear the interrupted flag of the thread so it can wait again */
3910 wapi_clear_interruption ();
3914 if ((thread
->state
& ThreadState_AbortRequested
) != 0) {
3915 LeaveCriticalSection (thread
->synch_cs
);
3916 if (thread
->abort_exc
== NULL
) {
3918 * This might be racy, but it has to be called outside the lock
3919 * since it calls managed code.
3921 MONO_OBJECT_SETREF (thread
, abort_exc
, mono_get_exception_thread_abort ());
3923 return thread
->abort_exc
;
3925 else if ((thread
->state
& ThreadState_SuspendRequested
) != 0) {
3926 thread
->state
&= ~ThreadState_SuspendRequested
;
3927 thread
->state
|= ThreadState_Suspended
;
3928 thread
->suspend_event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
3929 if (thread
->suspend_event
== NULL
) {
3930 LeaveCriticalSection (thread
->synch_cs
);
3933 if (thread
->suspended_event
)
3934 SetEvent (thread
->suspended_event
);
3936 LeaveCriticalSection (thread
->synch_cs
);
3938 if (shutting_down
) {
3939 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3944 WaitForSingleObject (thread
->suspend_event
, INFINITE
);
3946 EnterCriticalSection (thread
->synch_cs
);
3948 CloseHandle (thread
->suspend_event
);
3949 thread
->suspend_event
= NULL
;
3950 thread
->state
&= ~ThreadState_Suspended
;
3952 /* The thread that requested the resume will have replaced this event
3953 * and will be waiting for it
3955 SetEvent (thread
->resume_event
);
3957 LeaveCriticalSection (thread
->synch_cs
);
3961 else if ((thread
->state
& ThreadState_StopRequested
) != 0) {
3962 /* FIXME: do this through the JIT? */
3964 LeaveCriticalSection (thread
->synch_cs
);
3966 mono_thread_exit ();
3968 } else if (thread
->thread_interrupt_requested
) {
3970 thread
->thread_interrupt_requested
= FALSE
;
3971 LeaveCriticalSection (thread
->synch_cs
);
3973 return(mono_get_exception_thread_interrupted ());
3976 LeaveCriticalSection (thread
->synch_cs
);
3982 * mono_thread_request_interruption
3984 * A signal handler can call this method to request the interruption of a
3985 * thread. The result of the interruption will depend on the current state of
3986 * the thread. If the result is an exception that needs to be throw, it is
3987 * provided as return value.
3990 mono_thread_request_interruption (gboolean running_managed
)
3992 MonoInternalThread
*thread
= mono_thread_internal_current ();
3994 /* The thread may already be stopping */
3999 if (thread
->interrupt_on_stop
&&
4000 thread
->state
& ThreadState_StopRequested
&&
4001 thread
->state
& ThreadState_Background
)
4005 if (InterlockedCompareExchange (&thread
->interruption_requested
, 1, 0) == 1)
4008 if (!running_managed
|| is_running_protected_wrapper ()) {
4009 /* Can't stop while in unmanaged code. Increase the global interruption
4010 request count. When exiting the unmanaged method the count will be
4011 checked and the thread will be interrupted. */
4013 InterlockedIncrement (&thread_interruption_requested
);
4015 if (mono_thread_notify_pending_exc_fn
&& !running_managed
)
4016 /* The JIT will notify the thread about the interruption */
4017 /* This shouldn't take any locks */
4018 mono_thread_notify_pending_exc_fn ();
4020 /* this will awake the thread if it is in WaitForSingleObject
4022 /* Our implementation of this function ignores the func argument */
4023 QueueUserAPC ((PAPCFUNC
)dummy_apc
, thread
->handle
, NULL
);
4027 return mono_thread_execute_interruption (thread
);
4031 /*This function should be called by a thread after it has exited all of
4032 * its handle blocks at interruption time.*/
4034 mono_thread_resume_interruption (void)
4036 MonoInternalThread
*thread
= mono_thread_internal_current ();
4037 gboolean still_aborting
;
4039 /* The thread may already be stopping */
4043 ensure_synch_cs_set (thread
);
4044 EnterCriticalSection (thread
->synch_cs
);
4045 still_aborting
= (thread
->state
& ThreadState_AbortRequested
) != 0;
4046 LeaveCriticalSection (thread
->synch_cs
);
4048 /*This can happen if the protected block called Thread::ResetAbort*/
4049 if (!still_aborting
)
4052 if (InterlockedCompareExchange (&thread
->interruption_requested
, 1, 0) == 1)
4054 InterlockedIncrement (&thread_interruption_requested
);
4057 wapi_self_interrupt ();
4059 return mono_thread_execute_interruption (thread
);
4062 gboolean
mono_thread_interruption_requested ()
4064 if (thread_interruption_requested
) {
4065 MonoInternalThread
*thread
= mono_thread_internal_current ();
4066 /* The thread may already be stopping */
4068 return (thread
->interruption_requested
);
4073 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection
)
4075 MonoInternalThread
*thread
= mono_thread_internal_current ();
4077 /* The thread may already be stopping */
4081 mono_debugger_check_interruption ();
4083 if (thread
->interruption_requested
&& (bypass_abort_protection
|| !is_running_protected_wrapper ())) {
4084 MonoException
* exc
= mono_thread_execute_interruption (thread
);
4085 if (exc
) mono_raise_exception (exc
);
4090 * Performs the interruption of the current thread, if one has been requested,
4091 * and the thread is not running a protected wrapper.
4093 void mono_thread_interruption_checkpoint ()
4095 mono_thread_interruption_checkpoint_request (FALSE
);
4099 * Performs the interruption of the current thread, if one has been requested.
4101 void mono_thread_force_interruption_checkpoint ()
4103 mono_thread_interruption_checkpoint_request (TRUE
);
4107 * mono_thread_get_and_clear_pending_exception:
4109 * Return any pending exceptions for the current thread and clear it as a side effect.
4112 mono_thread_get_and_clear_pending_exception (void)
4114 MonoInternalThread
*thread
= mono_thread_internal_current ();
4116 /* The thread may already be stopping */
4120 if (thread
->interruption_requested
&& !is_running_protected_wrapper ()) {
4121 return mono_thread_execute_interruption (thread
);
4124 if (thread
->pending_exception
) {
4125 MonoException
*exc
= thread
->pending_exception
;
4127 thread
->pending_exception
= NULL
;
4135 * mono_set_pending_exception:
4137 * Set the pending exception of the current thread to EXC. On platforms which
4138 * support it, the exception will be thrown when execution returns to managed code.
4139 * On other platforms, this function is equivalent to mono_raise_exception ().
4140 * Internal calls which report exceptions using this function instead of
4141 * raise_exception () might be called by JITted code using a more efficient calling
4145 mono_set_pending_exception (MonoException
*exc
)
4147 MonoInternalThread
*thread
= mono_thread_internal_current ();
4149 /* The thread may already be stopping */
4153 if (mono_thread_notify_pending_exc_fn
) {
4154 MONO_OBJECT_SETREF (thread
, pending_exception
, exc
);
4156 mono_thread_notify_pending_exc_fn ();
4158 /* No way to notify the JIT about the exception, have to throw it now */
4159 mono_raise_exception (exc
);
4164 * mono_thread_interruption_request_flag:
4166 * Returns the address of a flag that will be non-zero if an interruption has
4167 * been requested for a thread. The thread to interrupt may not be the current
4168 * thread, so an additional call to mono_thread_interruption_requested() or
4169 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4172 gint32
* mono_thread_interruption_request_flag ()
4174 return &thread_interruption_requested
;
4178 mono_thread_init_apartment_state (void)
4181 MonoInternalThread
* thread
= mono_thread_internal_current ();
4183 /* Positive return value indicates success, either
4184 * S_OK if this is first CoInitialize call, or
4185 * S_FALSE if CoInitialize already called, but with same
4186 * threading model. A negative value indicates failure,
4187 * probably due to trying to change the threading model.
4189 if (CoInitializeEx(NULL
, (thread
->apartment_state
== ThreadApartmentState_STA
)
4190 ? COINIT_APARTMENTTHREADED
4191 : COINIT_MULTITHREADED
) < 0) {
4192 thread
->apartment_state
= ThreadApartmentState_Unknown
;
4198 mono_thread_cleanup_apartment_state (void)
4201 MonoInternalThread
* thread
= mono_thread_internal_current ();
4203 if (thread
&& thread
->apartment_state
!= ThreadApartmentState_Unknown
) {
4210 mono_thread_set_state (MonoInternalThread
*thread
, MonoThreadState state
)
4212 ensure_synch_cs_set (thread
);
4214 EnterCriticalSection (thread
->synch_cs
);
4215 thread
->state
|= state
;
4216 LeaveCriticalSection (thread
->synch_cs
);
4220 mono_thread_clr_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_test_state (MonoInternalThread
*thread
, MonoThreadState test
)
4232 gboolean ret
= FALSE
;
4234 ensure_synch_cs_set (thread
);
4236 EnterCriticalSection (thread
->synch_cs
);
4238 if ((thread
->state
& test
) != 0) {
4242 LeaveCriticalSection (thread
->synch_cs
);
4247 static MonoClassField
*execution_context_field
;
4250 get_execution_context_addr (void)
4252 MonoDomain
*domain
= mono_domain_get ();
4255 if (!execution_context_field
) {
4256 execution_context_field
= mono_class_get_field_from_name (mono_defaults
.thread_class
,
4258 g_assert (execution_context_field
);
4261 g_assert (mono_class_try_get_vtable (domain
, mono_defaults
.appdomain_class
));
4263 mono_domain_lock (domain
);
4264 offset
= GPOINTER_TO_UINT (g_hash_table_lookup (domain
->special_static_fields
, execution_context_field
));
4265 mono_domain_unlock (domain
);
4268 return (MonoObject
**) mono_get_special_static_data (offset
);
4272 mono_thread_get_execution_context (void)
4274 return *get_execution_context_addr ();
4278 mono_thread_set_execution_context (MonoObject
*ec
)
4280 *get_execution_context_addr () = ec
;
4283 static gboolean has_tls_get
= FALSE
;
4286 mono_runtime_set_has_tls_get (gboolean val
)
4292 mono_runtime_has_tls_get (void)