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 #ifdef PLATFORM_ANDROID
51 extern int tkill (pid_t tid, int signal);
54 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
55 #define THREAD_DEBUG(a)
56 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
57 #define THREAD_WAIT_DEBUG(a)
58 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
59 #define LIBGC_DEBUG(a)
61 #define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
62 #define SPIN_LOCK(i) do { \
63 if (SPIN_TRYLOCK (i)) \
67 #define SPIN_UNLOCK(i) i = 0
69 /* Provide this for systems with glib < 2.6 */
70 #ifndef G_GSIZE_FORMAT
71 # if GLIB_SIZEOF_LONG == 8
72 # define G_GSIZE_FORMAT "lu"
74 # define G_GSIZE_FORMAT "u"
80 guint32 (*func)(void *);
96 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
97 struct _MonoThreadDomainTls {
98 MonoThreadDomainTls *next;
106 MonoThreadDomainTls *freelist;
111 MonoHazardousFreeFunc free_func;
114 /* Number of cached culture objects in the MonoThread->cached_culture_info array
115 * (per-type): we use the first NUM entries for CultureInfo and the last for
116 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
118 #define NUM_CACHED_CULTURES 4
119 #define CULTURES_START_IDX 0
120 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
122 /* Controls access to the 'threads' hash table */
123 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
124 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
125 static CRITICAL_SECTION threads_mutex;
127 /* Controls access to context static data */
128 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
129 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
130 static CRITICAL_SECTION contexts_mutex;
132 /* Holds current status of static data heap */
133 static StaticDataInfo thread_static_info;
134 static StaticDataInfo context_static_info;
136 /* The hash of existing threads (key is thread ID, value is
137 * MonoInternalThread*) that need joining before exit
139 static MonoGHashTable *threads=NULL;
142 * Threads which are starting up and they are not in the 'threads' hash yet.
143 * When handle_store is called for a thread, it will be removed from this hash table.
144 * Protected by mono_threads_lock ().
146 static MonoGHashTable *threads_starting_up = NULL;
148 /* Maps a MonoThread to its start argument */
149 /* Protected by mono_threads_lock () */
150 static MonoGHashTable *thread_start_args = NULL;
152 /* The TLS key that holds the MonoObject assigned to each thread */
153 static guint32 current_object_key = -1;
155 #ifdef HAVE_KW_THREAD
156 /* we need to use both the Tls* functions and __thread because
157 * the gc needs to see all the threads
159 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
160 #define SET_CURRENT_OBJECT(x) do { \
161 tls_current_object = x; \
162 TlsSetValue (current_object_key, x); \
164 #define GET_CURRENT_OBJECT() tls_current_object
166 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
167 #define GET_CURRENT_OBJECT() (MonoInternalThread*) TlsGetValue (current_object_key)
170 /* function called at thread start */
171 static MonoThreadStartCB mono_thread_start_cb = NULL;
173 /* function called at thread attach */
174 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
176 /* function called at thread cleanup */
177 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
179 /* function called to notify the runtime about a pending exception on the current thread */
180 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
182 /* The default stack size for each thread */
183 static guint32 default_stacksize = 0;
184 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
186 static void thread_adjust_static_data (MonoInternalThread *thread);
187 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
188 static void mono_init_static_data_info (StaticDataInfo *static_data);
189 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
190 static gboolean mono_thread_resume (MonoInternalThread* thread);
191 static void mono_thread_start (MonoThread *thread);
192 static void signal_thread_state_change (MonoInternalThread *thread);
194 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
196 /* Spin lock for InterlockedXXX 64 bit functions */
197 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
198 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
199 static CRITICAL_SECTION interlocked_mutex;
201 /* global count of thread interruptions requested */
202 static gint32 thread_interruption_requested = 0;
204 /* Event signaled when a thread changes its background mode */
205 static HANDLE background_change_event;
207 /* The table for small ID assignment */
208 static CRITICAL_SECTION small_id_mutex;
209 static int small_id_table_size = 0;
210 static int small_id_next = 0;
211 static int highest_small_id = -1;
212 static MonoInternalThread **small_id_table = NULL;
214 /* The hazard table */
215 #if MONO_SMALL_CONFIG
216 #define HAZARD_TABLE_MAX_SIZE 256
218 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
220 static volatile int hazard_table_size = 0;
221 static MonoThreadHazardPointers * volatile hazard_table = NULL;
223 /* The table where we keep pointers to blocks to be freed but that
224 have to wait because they're guarded by a hazard pointer. */
225 static CRITICAL_SECTION delayed_free_table_mutex;
226 static GArray *delayed_free_table = NULL;
228 static gboolean shutting_down = FALSE;
231 mono_thread_get_tls_key (void)
233 return current_object_key;
237 mono_thread_get_tls_offset (void)
240 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
244 /* handle_store() and handle_remove() manage the array of threads that
245 * still need to be waited for when the main thread exits.
247 * If handle_store() returns FALSE the thread must not be started
248 * because Mono is shutting down.
250 static gboolean handle_store(MonoThread *thread)
252 mono_threads_lock ();
254 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
256 if (threads_starting_up)
257 mono_g_hash_table_remove (threads_starting_up, thread);
260 mono_threads_unlock ();
265 MONO_GC_REGISTER_ROOT_FIXED (threads);
266 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
269 /* We don't need to duplicate thread->handle, because it is
270 * only closed when the thread object is finalized by the GC.
272 g_assert (thread->internal_thread);
273 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
274 thread->internal_thread);
276 mono_threads_unlock ();
281 static gboolean handle_remove(MonoInternalThread *thread)
284 gsize tid = thread->tid;
286 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
288 mono_threads_lock ();
291 /* We have to check whether the thread object for the
292 * tid is still the same in the table because the
293 * thread might have been destroyed and the tid reused
294 * in the meantime, in which case the tid would be in
295 * the table, but with another thread object.
297 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
298 mono_g_hash_table_remove (threads, (gpointer)tid);
307 mono_threads_unlock ();
309 /* Don't close the handle here, wait for the object finalizer
310 * to do it. Otherwise, the following race condition applies:
312 * 1) Thread exits (and handle_remove() closes the handle)
314 * 2) Some other handle is reassigned the same slot
316 * 3) Another thread tries to join the first thread, and
317 * blocks waiting for the reassigned handle to be signalled
318 * (which might never happen). This is possible, because the
319 * thread calling Join() still has a reference to the first
326 * Allocate a small thread id.
328 * FIXME: The biggest part of this function is very similar to
329 * domain_id_alloc() in domain.c and should be merged.
332 small_id_alloc (MonoInternalThread *thread)
336 EnterCriticalSection (&small_id_mutex);
338 if (!small_id_table) {
339 small_id_table_size = 2;
341 * Enabling this causes problems, because SGEN doesn't track/update the TLS slot holding
342 * the current thread.
344 //small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), mono_gc_make_root_descr_all_refs (small_id_table_size));
345 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
347 for (i = small_id_next; i < small_id_table_size; ++i) {
348 if (!small_id_table [i]) {
354 for (i = 0; i < small_id_next; ++i) {
355 if (!small_id_table [i]) {
362 MonoInternalThread **new_table;
363 int new_size = small_id_table_size * 2;
364 if (new_size >= (1 << 16))
365 g_assert_not_reached ();
366 id = small_id_table_size;
367 //new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), mono_gc_make_root_descr_all_refs (new_size));
368 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
369 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
370 mono_gc_free_fixed (small_id_table);
371 small_id_table = new_table;
372 small_id_table_size = new_size;
374 thread->small_id = id;
375 g_assert (small_id_table [id] == NULL);
376 small_id_table [id] = thread;
378 if (small_id_next > small_id_table_size)
381 g_assert (id < HAZARD_TABLE_MAX_SIZE);
382 if (id >= hazard_table_size) {
383 #if MONO_SMALL_CONFIG
384 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
385 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
388 int pagesize = mono_pagesize ();
389 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
391 if (hazard_table == NULL) {
392 hazard_table = mono_valloc (NULL,
393 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
397 g_assert (hazard_table != NULL);
398 page_addr = (guint8*)hazard_table + num_pages * pagesize;
400 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
403 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
406 g_assert (id < hazard_table_size);
407 hazard_table [id].hazard_pointers [0] = NULL;
408 hazard_table [id].hazard_pointers [1] = NULL;
411 if (id > highest_small_id) {
412 highest_small_id = id;
413 mono_memory_write_barrier ();
416 LeaveCriticalSection (&small_id_mutex);
422 small_id_free (int id)
424 g_assert (id >= 0 && id < small_id_table_size);
425 g_assert (small_id_table [id] != NULL);
427 small_id_table [id] = NULL;
431 is_pointer_hazardous (gpointer p)
434 int highest = highest_small_id;
436 g_assert (highest < hazard_table_size);
438 for (i = 0; i <= highest; ++i) {
439 if (hazard_table [i].hazard_pointers [0] == p
440 || hazard_table [i].hazard_pointers [1] == p)
447 MonoThreadHazardPointers*
448 mono_hazard_pointer_get (void)
450 MonoInternalThread *current_thread = mono_thread_internal_current ();
452 if (!(current_thread && current_thread->small_id >= 0)) {
453 static MonoThreadHazardPointers emerg_hazard_table;
454 g_warning ("Thread %p may have been prematurely finalized", current_thread);
455 return &emerg_hazard_table;
458 return &hazard_table [current_thread->small_id];
462 try_free_delayed_free_item (int index)
464 if (delayed_free_table->len > index) {
465 DelayedFreeItem item = { NULL, NULL };
467 EnterCriticalSection (&delayed_free_table_mutex);
468 /* We have to check the length again because another
469 thread might have freed an item before we acquired
471 if (delayed_free_table->len > index) {
472 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
474 if (!is_pointer_hazardous (item.p))
475 g_array_remove_index_fast (delayed_free_table, index);
479 LeaveCriticalSection (&delayed_free_table_mutex);
482 item.free_func (item.p);
487 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
491 /* First try to free a few entries in the delayed free
493 for (i = 2; i >= 0; --i)
494 try_free_delayed_free_item (i);
496 /* Now see if the pointer we're freeing is hazardous. If it
497 isn't, free it. Otherwise put it in the delay list. */
498 if (is_pointer_hazardous (p)) {
499 DelayedFreeItem item = { p, free_func };
501 ++mono_stats.hazardous_pointer_count;
503 EnterCriticalSection (&delayed_free_table_mutex);
504 g_array_append_val (delayed_free_table, item);
505 LeaveCriticalSection (&delayed_free_table_mutex);
511 mono_thread_hazardous_try_free_all (void)
516 if (!delayed_free_table)
519 len = delayed_free_table->len;
521 for (i = len - 1; i >= 0; --i)
522 try_free_delayed_free_item (i);
525 static void ensure_synch_cs_set (MonoInternalThread *thread)
527 CRITICAL_SECTION *synch_cs;
529 if (thread->synch_cs != NULL) {
533 synch_cs = g_new0 (CRITICAL_SECTION, 1);
534 InitializeCriticalSection (synch_cs);
536 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
537 synch_cs, NULL) != NULL) {
538 /* Another thread must have installed this CS */
539 DeleteCriticalSection (synch_cs);
545 * NOTE: this function can be called also for threads different from the current one:
546 * make sure no code called from it will ever assume it is run on the thread that is
547 * getting cleaned up.
549 static void thread_cleanup (MonoInternalThread *thread)
551 g_assert (thread != NULL);
553 if (thread->abort_state_handle) {
554 mono_gchandle_free (thread->abort_state_handle);
555 thread->abort_state_handle = 0;
557 thread->abort_exc = NULL;
558 thread->current_appcontext = NULL;
561 * This is necessary because otherwise we might have
562 * cross-domain references which will not get cleaned up when
563 * the target domain is unloaded.
565 if (thread->cached_culture_info) {
567 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
568 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
571 /* if the thread is not in the hash it has been removed already */
572 if (!handle_remove (thread)) {
573 /* This needs to be called even if handle_remove () fails */
574 if (mono_thread_cleanup_fn)
575 mono_thread_cleanup_fn (thread);
578 mono_release_type_locks (thread);
580 EnterCriticalSection (thread->synch_cs);
582 thread->state |= ThreadState_Stopped;
583 thread->state &= ~ThreadState_Background;
585 LeaveCriticalSection (thread->synch_cs);
587 mono_profiler_thread_end (thread->tid);
589 if (thread == mono_thread_internal_current ())
590 mono_thread_pop_appdomain_ref ();
592 thread->cached_culture_info = NULL;
594 mono_free_static_data (thread->static_data, TRUE);
595 thread->static_data = NULL;
597 if (mono_thread_cleanup_fn)
598 mono_thread_cleanup_fn (thread);
600 small_id_free (thread->small_id);
601 thread->small_id = -2;
606 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
609 g_assert ((offset & 0x80000000) == 0);
610 offset &= 0x7fffffff;
611 idx = (offset >> 24) - 1;
612 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
616 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
618 static MonoClassField *current_thread_field = NULL;
622 if (!current_thread_field) {
623 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
624 g_assert (current_thread_field);
627 mono_class_vtable (domain, mono_defaults.thread_class);
628 mono_domain_lock (domain);
629 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
630 mono_domain_unlock (domain);
633 return get_thread_static_data (thread, offset);
637 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
639 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
641 g_assert (current->obj.vtable->domain == domain);
643 g_assert (!*current_thread_ptr);
644 *current_thread_ptr = current;
647 static MonoInternalThread*
648 create_internal_thread_object (void)
650 MonoVTable *vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
651 return (MonoInternalThread*)mono_gc_alloc_mature (vt);
655 create_thread_object (MonoDomain *domain)
657 MonoVTable *vt = mono_class_vtable (domain, mono_defaults.thread_class);
658 return (MonoThread*)mono_gc_alloc_mature (vt);
662 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
664 MonoThread *thread = create_thread_object (domain);
665 MONO_OBJECT_SETREF (thread, internal_thread, internal);
670 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
672 MonoDomain *domain = mono_get_root_domain ();
674 if (!candidate || candidate->obj.vtable->domain != domain)
675 candidate = new_thread_with_internal (domain, thread);
676 set_current_thread_for_domain (domain, thread, candidate);
677 g_assert (!thread->root_domain_thread);
678 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
681 static guint32 WINAPI start_wrapper_internal(void *data)
683 struct StartInfo *start_info=(struct StartInfo *)data;
684 guint32 (*start_func)(void *);
688 * We don't create a local to hold start_info->obj, so hopefully it won't get pinned during a
691 MonoInternalThread *internal = start_info->obj->internal_thread;
692 MonoObject *start_delegate = start_info->delegate;
693 MonoDomain *domain = start_info->obj->obj.vtable->domain;
695 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
697 /* We can be sure start_info->obj->tid and
698 * start_info->obj->handle have been set, because the thread
699 * was created suspended, and these values were set before the
705 SET_CURRENT_OBJECT (internal);
707 mono_monitor_init_tls ();
709 /* Every thread references the appdomain which created it */
710 mono_thread_push_appdomain_ref (domain);
712 if (!mono_domain_set (domain, FALSE)) {
713 /* No point in raising an appdomain_unloaded exception here */
714 /* FIXME: Cleanup here */
715 mono_thread_pop_appdomain_ref ();
719 start_func = start_info->func;
720 start_arg = start_info->start_arg;
722 /* We have to do this here because mono_thread_new_init()
723 requires that root_domain_thread is set up. */
724 thread_adjust_static_data (internal);
725 init_root_domain_thread (internal, start_info->obj);
727 /* This MUST be called before any managed code can be
728 * executed, as it calls the callback function that (for the
729 * jit) sets the lmf marker.
731 mono_thread_new_init (tid, &tid, start_func);
732 internal->stack_ptr = &tid;
734 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
736 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
738 /* On 2.0 profile (and higher), set explicitly since state might have been
740 if (internal->apartment_state == ThreadApartmentState_Unknown)
741 internal->apartment_state = ThreadApartmentState_MTA;
743 mono_thread_init_apartment_state ();
745 if(internal->start_notify!=NULL) {
746 /* Let the thread that called Start() know we're
749 ReleaseSemaphore (internal->start_notify, 1, NULL);
752 mono_threads_lock ();
753 mono_g_hash_table_remove (thread_start_args, start_info->obj);
754 mono_threads_unlock ();
756 mono_thread_set_execution_context (start_info->obj->ec_to_set);
757 start_info->obj->ec_to_set = NULL;
761 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
766 * Call this after calling start_notify, since the profiler callback might want
767 * to lock the thread, and the lock is held by thread_start () which waits for
770 mono_profiler_thread_start (tid);
772 /* start_func is set only for unmanaged start functions */
774 start_func (start_arg);
777 g_assert (start_delegate != NULL);
778 args [0] = start_arg;
779 /* we may want to handle the exception here. See comment below on unhandled exceptions */
780 mono_runtime_delegate_invoke (start_delegate, args, NULL);
783 /* If the thread calls ExitThread at all, this remaining code
784 * will not be executed, but the main thread will eventually
785 * call thread_cleanup() on this thread's behalf.
788 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
790 thread_cleanup (internal);
792 /* Do any cleanup needed for apartment state. This
793 * cannot be done in thread_cleanup since thread_cleanup could be
794 * called for a thread other than the current thread.
795 * mono_thread_cleanup_apartment_state cleans up apartment
796 * for the current thead */
797 mono_thread_cleanup_apartment_state ();
799 /* Remove the reference to the thread object in the TLS data,
800 * so the thread object can be finalized. This won't be
801 * reached if the thread threw an uncaught exception, so those
802 * thread handles will stay referenced :-( (This is due to
803 * missing support for scanning thread-specific data in the
804 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
807 SET_CURRENT_OBJECT (NULL);
808 mono_domain_unset ();
813 static guint32 WINAPI start_wrapper(void *data)
818 /* Avoid scanning the frames above this frame during a GC */
819 mono_gc_set_stack_end ((void*)&dummy);
822 return start_wrapper_internal (data);
825 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
827 if (mono_thread_start_cb) {
828 mono_thread_start_cb (tid, stack_start, func);
832 void mono_threads_set_default_stacksize (guint32 stacksize)
834 default_stacksize = stacksize;
837 guint32 mono_threads_get_default_stacksize (void)
839 return default_stacksize;
843 * mono_create_thread:
845 * This is a wrapper around CreateThread which handles differences in the type of
846 * the the 'tid' argument.
848 gpointer mono_create_thread (WapiSecurityAttributes *security,
849 guint32 stacksize, WapiThreadStart start,
850 gpointer param, guint32 create, gsize *tid)
857 res = CreateThread (security, stacksize, start, param, create, &real_tid);
861 res = CreateThread (security, stacksize, start, param, create, tid);
868 * The thread start argument may be an object reference, and there is
869 * no ref to keep it alive when the new thread is started but not yet
870 * registered with the collector. So we store it in a GC tracked hash
873 * LOCKING: Assumes the threads lock is held.
876 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
878 if (thread_start_args == NULL) {
879 MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
880 thread_start_args = mono_g_hash_table_new (NULL, NULL);
882 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
885 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
888 MonoInternalThread *internal;
889 HANDLE thread_handle;
890 struct StartInfo *start_info;
893 thread = create_thread_object (domain);
894 internal = create_internal_thread_object ();
895 MONO_OBJECT_SETREF (thread, internal_thread, internal);
897 start_info=g_new0 (struct StartInfo, 1);
898 start_info->func = func;
899 start_info->obj = thread;
900 start_info->start_arg = arg;
902 mono_threads_lock ();
904 mono_threads_unlock ();
908 if (threads_starting_up == NULL) {
909 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
910 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
913 register_thread_start_argument (thread, start_info);
914 mono_g_hash_table_insert (threads_starting_up, thread, thread);
915 mono_threads_unlock ();
917 /* Create suspended, so we can do some housekeeping before the thread
920 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
921 CREATE_SUSPENDED, &tid);
922 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
923 if (thread_handle == NULL) {
924 /* The thread couldn't be created, so throw an exception */
925 mono_threads_lock ();
926 mono_g_hash_table_remove (threads_starting_up, thread);
927 mono_threads_unlock ();
929 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
933 internal->handle=thread_handle;
935 internal->apartment_state=ThreadApartmentState_Unknown;
936 small_id_alloc (internal);
938 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
939 InitializeCriticalSection (internal->synch_cs);
941 internal->threadpool_thread = threadpool_thread;
942 if (threadpool_thread)
943 mono_thread_set_state (internal, ThreadState_Background);
945 if (handle_store (thread))
946 ResumeThread (thread_handle);
952 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
954 mono_thread_create_internal (domain, func, arg, FALSE);
958 * mono_thread_get_stack_bounds:
960 * Return the address and size of the current threads stack. Return NULL as the
961 * stack address if the stack address cannot be determined.
964 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
966 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
967 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
968 *stsize = pthread_get_stacksize_np (pthread_self ());
969 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
971 /* FIXME: simplify the mess below */
972 #elif !defined(HOST_WIN32)
974 guint8 *current = (guint8*)&attr;
976 pthread_attr_init (&attr);
977 # ifdef HAVE_PTHREAD_GETATTR_NP
978 pthread_getattr_np (pthread_self(), &attr);
980 # ifdef HAVE_PTHREAD_ATTR_GET_NP
981 pthread_attr_get_np (pthread_self(), &attr);
984 pthread_attr_getstacksize (&attr, &stsize);
985 # elif defined(__OpenBSD__)
989 rslt = pthread_stackseg_np(pthread_self(), &ss);
990 g_assert (rslt == 0);
992 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
993 *stsize = ss.ss_size;
1002 # if !defined(__OpenBSD__)
1003 pthread_attr_getstack (&attr, (void**)staddr, stsize);
1006 g_assert ((current > *staddr) && (current < *staddr + *stsize));
1009 pthread_attr_destroy (&attr);
1012 *stsize = (size_t)-1;
1015 /* When running under emacs, sometimes staddr is not aligned to a page size */
1016 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
1020 mono_thread_attach (MonoDomain *domain)
1022 MonoInternalThread *thread;
1023 MonoThread *current_thread;
1024 HANDLE thread_handle;
1027 if ((thread = mono_thread_internal_current ())) {
1028 if (domain != mono_domain_get ())
1029 mono_domain_set (domain, TRUE);
1030 /* Already attached */
1031 return mono_thread_current ();
1034 if (!mono_gc_register_thread (&domain)) {
1035 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 ());
1038 thread = create_internal_thread_object ();
1040 thread_handle = GetCurrentThread ();
1041 g_assert (thread_handle);
1043 tid=GetCurrentThreadId ();
1046 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
1047 * refer to the thread from other threads for things like aborting.
1049 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
1050 THREAD_ALL_ACCESS, TRUE, 0);
1052 thread->handle=thread_handle;
1054 #ifdef PLATFORM_ANDROID
1055 thread->android_tid = (gpointer) gettid ();
1057 thread->apartment_state=ThreadApartmentState_Unknown;
1058 small_id_alloc (thread);
1059 thread->stack_ptr = &tid;
1061 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
1062 InitializeCriticalSection (thread->synch_cs);
1064 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
1066 current_thread = new_thread_with_internal (domain, thread);
1068 if (!handle_store (current_thread)) {
1069 /* Mono is shutting down, so just wait for the end */
1074 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1076 SET_CURRENT_OBJECT (thread);
1077 mono_domain_set (domain, TRUE);
1079 mono_monitor_init_tls ();
1081 thread_adjust_static_data (thread);
1083 init_root_domain_thread (thread, current_thread);
1084 if (domain != mono_get_root_domain ())
1085 set_current_thread_for_domain (domain, thread, current_thread);
1088 if (mono_thread_attach_cb) {
1092 mono_thread_get_stack_bounds (&staddr, &stsize);
1095 mono_thread_attach_cb (tid, &tid);
1097 mono_thread_attach_cb (tid, staddr + stsize);
1100 // FIXME: Need a separate callback
1101 mono_profiler_thread_start (tid);
1103 return current_thread;
1107 mono_thread_detach (MonoThread *thread)
1109 g_return_if_fail (thread != NULL);
1111 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1113 thread_cleanup (thread->internal_thread);
1115 SET_CURRENT_OBJECT (NULL);
1116 mono_domain_unset ();
1118 /* Don't need to CloseHandle this thread, even though we took a
1119 * reference in mono_thread_attach (), because the GC will do it
1120 * when the Thread object is finalised.
1127 MonoInternalThread *thread = mono_thread_internal_current ();
1129 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1131 thread_cleanup (thread);
1132 SET_CURRENT_OBJECT (NULL);
1133 mono_domain_unset ();
1135 /* we could add a callback here for embedders to use. */
1136 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1137 exit (mono_environment_exitcode_get ());
1142 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1144 MonoInternalThread *internal = create_internal_thread_object ();
1146 internal->state = ThreadState_Unstarted;
1147 internal->apartment_state = ThreadApartmentState_Unknown;
1149 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1152 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1155 guint32 (*start_func)(void *);
1156 struct StartInfo *start_info;
1159 MonoInternalThread *internal;
1161 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1163 if (!this->internal_thread)
1164 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1165 internal = this->internal_thread;
1167 ensure_synch_cs_set (internal);
1169 EnterCriticalSection (internal->synch_cs);
1171 if ((internal->state & ThreadState_Unstarted) == 0) {
1172 LeaveCriticalSection (internal->synch_cs);
1173 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1177 internal->small_id = -1;
1179 if ((internal->state & ThreadState_Aborted) != 0) {
1180 LeaveCriticalSection (internal->synch_cs);
1185 /* This is freed in start_wrapper */
1186 start_info = g_new0 (struct StartInfo, 1);
1187 start_info->func = start_func;
1188 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1189 start_info->delegate = start;
1190 start_info->obj = this;
1191 g_assert (this->obj.vtable->domain == mono_domain_get ());
1193 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1194 if (internal->start_notify==NULL) {
1195 LeaveCriticalSection (internal->synch_cs);
1196 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1197 g_free (start_info);
1201 mono_threads_lock ();
1202 register_thread_start_argument (this, start_info);
1203 if (threads_starting_up == NULL) {
1204 MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
1205 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1207 mono_g_hash_table_insert (threads_starting_up, this, this);
1208 mono_threads_unlock ();
1210 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1211 CREATE_SUSPENDED, &tid);
1213 LeaveCriticalSection (internal->synch_cs);
1214 mono_threads_lock ();
1215 mono_g_hash_table_remove (threads_starting_up, this);
1216 mono_threads_unlock ();
1217 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1221 internal->handle=thread;
1223 small_id_alloc (internal);
1225 /* Don't call handle_store() here, delay it to Start.
1226 * We can't join a thread (trying to will just block
1227 * forever) until it actually starts running, so don't
1228 * store the handle till then.
1231 mono_thread_start (this);
1233 internal->state &= ~ThreadState_Unstarted;
1235 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1237 LeaveCriticalSection (internal->synch_cs);
1242 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1244 MONO_ARCH_SAVE_REGS;
1246 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1249 CloseHandle (thread);
1251 if (this->synch_cs) {
1252 DeleteCriticalSection (this->synch_cs);
1253 g_free (this->synch_cs);
1254 this->synch_cs = NULL;
1257 g_free (this->name);
1260 static void mono_thread_start (MonoThread *thread)
1262 MonoInternalThread *internal = thread->internal_thread;
1264 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1266 /* Only store the handle when the thread is about to be
1267 * launched, to avoid the main thread deadlocking while trying
1268 * to clean up a thread that will never be signalled.
1270 if (!handle_store (thread))
1273 ResumeThread (internal->handle);
1275 if(internal->start_notify!=NULL) {
1276 /* Wait for the thread to set up its TLS data etc, so
1277 * theres no potential race condition if someone tries
1278 * to look up the data believing the thread has
1282 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1284 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1285 CloseHandle (internal->start_notify);
1286 internal->start_notify = NULL;
1289 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1292 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1295 MonoInternalThread *thread = mono_thread_internal_current ();
1297 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1299 mono_thread_current_check_pending_interrupt ();
1301 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1303 res = SleepEx(ms,TRUE);
1305 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1307 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1308 MonoException* exc = mono_thread_execute_interruption (thread);
1309 if (exc) mono_raise_exception (exc);
1313 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1318 ves_icall_System_Threading_Thread_GetDomainID (void)
1320 MONO_ARCH_SAVE_REGS;
1322 return mono_domain_get()->domain_id;
1326 ves_icall_System_Threading_Thread_Yield (void)
1329 return SwitchToThread ();
1331 return sched_yield () == 0;
1336 * mono_thread_get_name:
1338 * Return the name of the thread. NAME_LEN is set to the length of the name.
1339 * Return NULL if the thread has no name. The returned memory is owned by the
1343 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1347 ensure_synch_cs_set (this_obj);
1349 EnterCriticalSection (this_obj->synch_cs);
1351 if (!this_obj->name) {
1355 *name_len = this_obj->name_len;
1356 res = g_new (gunichar2, this_obj->name_len);
1357 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1360 LeaveCriticalSection (this_obj->synch_cs);
1366 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1370 ensure_synch_cs_set (this_obj);
1372 EnterCriticalSection (this_obj->synch_cs);
1374 if (!this_obj->name)
1377 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1379 LeaveCriticalSection (this_obj->synch_cs);
1385 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1387 ensure_synch_cs_set (this_obj);
1389 EnterCriticalSection (this_obj->synch_cs);
1391 if (this_obj->name) {
1392 LeaveCriticalSection (this_obj->synch_cs);
1394 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1398 this_obj->name = g_new (gunichar2, mono_string_length (name));
1399 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1400 this_obj->name_len = mono_string_length (name);
1403 this_obj->name = NULL;
1405 LeaveCriticalSection (this_obj->synch_cs);
1406 if (this_obj->name) {
1407 char *tname = mono_string_to_utf8 (name);
1408 mono_profiler_thread_name (this_obj->tid, tname);
1413 /* If the array is already in the requested domain, we just return it,
1414 otherwise we return a copy in that domain. */
1416 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1423 if (mono_object_domain (arr) == domain)
1426 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1427 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1432 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1434 return byte_array_to_domain (arr, mono_get_root_domain ());
1438 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1440 return byte_array_to_domain (arr, mono_domain_get ());
1444 mono_thread_current (void)
1446 MonoDomain *domain = mono_domain_get ();
1447 MonoInternalThread *internal = mono_thread_internal_current ();
1448 MonoThread **current_thread_ptr;
1450 g_assert (internal);
1451 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1453 if (!*current_thread_ptr) {
1454 g_assert (domain != mono_get_root_domain ());
1455 *current_thread_ptr = new_thread_with_internal (domain, internal);
1457 return *current_thread_ptr;
1461 mono_thread_internal_current (void)
1463 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1464 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1468 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1469 int ms, HANDLE thread)
1471 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1474 mono_thread_current_check_pending_interrupt ();
1476 ensure_synch_cs_set (this);
1478 EnterCriticalSection (this->synch_cs);
1480 if ((this->state & ThreadState_Unstarted) != 0) {
1481 LeaveCriticalSection (this->synch_cs);
1483 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1487 LeaveCriticalSection (this->synch_cs);
1492 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1494 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1496 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1498 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1500 if(ret==WAIT_OBJECT_0) {
1501 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1506 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1511 /* FIXME: exitContext isnt documented */
1512 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1518 MonoObject *waitHandle;
1519 MonoInternalThread *thread = mono_thread_internal_current ();
1521 /* Do this WaitSleepJoin check before creating objects */
1522 mono_thread_current_check_pending_interrupt ();
1524 numhandles = mono_array_length(mono_handles);
1525 handles = g_new0(HANDLE, numhandles);
1527 for(i = 0; i < numhandles; i++) {
1528 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1529 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1536 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1538 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1540 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1544 if(ret==WAIT_FAILED) {
1545 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1547 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1548 /* Do we want to try again if we get
1549 * WAIT_IO_COMPLETION? The documentation for
1550 * WaitHandle doesn't give any clues. (We'd have to
1551 * fiddle with the timeout if we retry.)
1553 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1560 /* FIXME: exitContext isnt documented */
1561 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1567 MonoObject *waitHandle;
1568 MonoInternalThread *thread = mono_thread_internal_current ();
1571 /* Do this WaitSleepJoin check before creating objects */
1572 mono_thread_current_check_pending_interrupt ();
1574 numhandles = mono_array_length(mono_handles);
1575 handles = g_new0(HANDLE, numhandles);
1577 for(i = 0; i < numhandles; i++) {
1578 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1579 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1586 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1588 start = (ms == -1) ? 0 : mono_msec_ticks ();
1590 ret = WaitForMultipleObjectsEx (numhandles, handles, FALSE, ms, TRUE);
1591 if (ret != WAIT_IO_COMPLETION)
1596 diff = mono_msec_ticks () - start;
1601 } while (ms == -1 || ms > 0);
1603 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1607 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1610 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1612 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1613 return ret - WAIT_OBJECT_0;
1615 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1616 return ret - WAIT_ABANDONED_0;
1623 /* FIXME: exitContext isnt documented */
1624 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1627 MonoInternalThread *thread = mono_thread_internal_current ();
1629 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1635 mono_thread_current_check_pending_interrupt ();
1637 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1639 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1641 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1643 if(ret==WAIT_FAILED) {
1644 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1646 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1647 /* Do we want to try again if we get
1648 * WAIT_IO_COMPLETION? The documentation for
1649 * WaitHandle doesn't give any clues. (We'd have to
1650 * fiddle with the timeout if we retry.)
1652 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1660 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1663 MonoInternalThread *thread = mono_thread_internal_current ();
1665 MONO_ARCH_SAVE_REGS;
1670 mono_thread_current_check_pending_interrupt ();
1672 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1674 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1676 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1678 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1681 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1685 MONO_ARCH_SAVE_REGS;
1690 mutex = CreateMutex (NULL, owned, NULL);
1692 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1694 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1702 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1703 MONO_ARCH_SAVE_REGS;
1705 return(ReleaseMutex (handle));
1708 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1714 MONO_ARCH_SAVE_REGS;
1716 *error = ERROR_SUCCESS;
1718 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1720 *error = GetLastError ();
1727 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1731 MONO_ARCH_SAVE_REGS;
1736 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1738 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1739 mono_string_chars (name));
1741 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1749 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1753 MONO_ARCH_SAVE_REGS;
1755 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1760 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1764 MONO_ARCH_SAVE_REGS;
1766 *error = ERROR_SUCCESS;
1768 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1770 *error = GetLastError ();
1776 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1780 MONO_ARCH_SAVE_REGS;
1785 event = CreateEvent (NULL, manual, initial, NULL);
1787 event = CreateEvent (NULL, manual, initial,
1788 mono_string_chars (name));
1790 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1798 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1799 MONO_ARCH_SAVE_REGS;
1801 return (SetEvent(handle));
1804 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1805 MONO_ARCH_SAVE_REGS;
1807 return (ResetEvent(handle));
1811 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1812 MONO_ARCH_SAVE_REGS;
1814 CloseHandle (handle);
1817 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1823 MONO_ARCH_SAVE_REGS;
1825 *error = ERROR_SUCCESS;
1827 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1829 *error = GetLastError ();
1835 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1837 MONO_ARCH_SAVE_REGS;
1839 return InterlockedIncrement (location);
1842 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1846 MONO_ARCH_SAVE_REGS;
1848 mono_interlocked_lock ();
1852 mono_interlocked_unlock ();
1858 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1860 MONO_ARCH_SAVE_REGS;
1862 return InterlockedDecrement(location);
1865 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1869 MONO_ARCH_SAVE_REGS;
1871 mono_interlocked_lock ();
1875 mono_interlocked_unlock ();
1880 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1882 MONO_ARCH_SAVE_REGS;
1884 return InterlockedExchange(location, value);
1887 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1890 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1891 mono_gc_wbarrier_generic_nostore (location);
1895 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1897 return InterlockedExchangePointer(location, value);
1900 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1902 IntFloatUnion val, ret;
1904 MONO_ARCH_SAVE_REGS;
1907 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1913 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1915 #if SIZEOF_VOID_P == 8
1916 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1921 * According to MSDN, this function is only atomic with regards to the
1922 * other Interlocked functions on 32 bit platforms.
1924 mono_interlocked_lock ();
1927 mono_interlocked_unlock ();
1934 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1936 #if SIZEOF_VOID_P == 8
1937 LongDoubleUnion val, ret;
1940 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1947 * According to MSDN, this function is only atomic with regards to the
1948 * other Interlocked functions on 32 bit platforms.
1950 mono_interlocked_lock ();
1953 mono_interlocked_unlock ();
1959 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1961 MONO_ARCH_SAVE_REGS;
1963 return InterlockedCompareExchange(location, value, comparand);
1966 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1969 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1970 mono_gc_wbarrier_generic_nostore (location);
1974 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1976 return InterlockedCompareExchangePointer(location, value, comparand);
1979 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1981 IntFloatUnion val, ret, cmp;
1983 MONO_ARCH_SAVE_REGS;
1986 cmp.fval = comparand;
1987 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1993 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1995 #if SIZEOF_VOID_P == 8
1996 LongDoubleUnion val, comp, ret;
1999 comp.fval = comparand;
2000 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2006 mono_interlocked_lock ();
2008 if (old == comparand)
2010 mono_interlocked_unlock ();
2017 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2019 #if SIZEOF_VOID_P == 8
2020 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2024 mono_interlocked_lock ();
2026 if (old == comparand)
2028 mono_interlocked_unlock ();
2035 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2038 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2039 mono_gc_wbarrier_generic_nostore (location);
2044 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2047 res = InterlockedExchangePointer ((gpointer *)location, value);
2048 mono_gc_wbarrier_generic_nostore (location);
2053 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2055 #if SIZEOF_VOID_P == 8
2056 /* Should be implemented as a JIT intrinsic */
2057 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2062 mono_interlocked_lock ();
2064 *location = orig + value;
2065 mono_interlocked_unlock ();
2067 return orig + value;
2072 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2074 #if SIZEOF_VOID_P == 8
2075 /* Should be implemented as a JIT intrinsic */
2076 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2081 mono_interlocked_lock ();
2083 *location = orig + value;
2084 mono_interlocked_unlock ();
2086 return orig + value;
2091 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2093 #if SIZEOF_VOID_P == 8
2094 /* 64 bit reads are already atomic */
2099 mono_interlocked_lock ();
2101 mono_interlocked_unlock ();
2108 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2110 mono_threads_lock ();
2111 mono_threads_unlock ();
2115 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2117 mono_thread_clr_state (this, state);
2119 if (state & ThreadState_Background) {
2120 /* If the thread changes the background mode, the main thread has to
2121 * be notified, since it has to rebuild the list of threads to
2124 SetEvent (background_change_event);
2129 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2131 mono_thread_set_state (this, state);
2133 if (state & ThreadState_Background) {
2134 /* If the thread changes the background mode, the main thread has to
2135 * be notified, since it has to rebuild the list of threads to
2138 SetEvent (background_change_event);
2143 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2147 ensure_synch_cs_set (this);
2149 EnterCriticalSection (this->synch_cs);
2151 state = this->state;
2153 LeaveCriticalSection (this->synch_cs);
2158 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2160 gboolean throw = FALSE;
2162 ensure_synch_cs_set (this);
2164 if (this == mono_thread_internal_current ())
2167 EnterCriticalSection (this->synch_cs);
2169 this->thread_interrupt_requested = TRUE;
2171 if (this->state & ThreadState_WaitSleepJoin) {
2175 LeaveCriticalSection (this->synch_cs);
2178 signal_thread_state_change (this);
2182 void mono_thread_current_check_pending_interrupt ()
2184 MonoInternalThread *thread = mono_thread_internal_current ();
2185 gboolean throw = FALSE;
2187 mono_debugger_check_interruption ();
2189 ensure_synch_cs_set (thread);
2191 EnterCriticalSection (thread->synch_cs);
2193 if (thread->thread_interrupt_requested) {
2195 thread->thread_interrupt_requested = FALSE;
2198 LeaveCriticalSection (thread->synch_cs);
2201 mono_raise_exception (mono_get_exception_thread_interrupted ());
2206 mono_thread_get_abort_signal (void)
2218 static int abort_signum = -1;
2220 if (abort_signum != -1)
2221 return abort_signum;
2222 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2223 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2224 struct sigaction sinfo;
2225 sigaction (i, NULL, &sinfo);
2226 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2231 /* fallback to the old way */
2234 #endif /* HOST_WIN32 */
2238 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2240 MonoException* exc = mono_thread_request_interruption (FALSE);
2241 if (exc) mono_raise_exception (exc);
2243 #endif /* HOST_WIN32 */
2246 * signal_thread_state_change
2248 * Tells the thread that his state has changed and it has to enter the new
2249 * state as soon as possible.
2251 static void signal_thread_state_change (MonoInternalThread *thread)
2253 if (thread == mono_thread_internal_current ()) {
2254 /* Do it synchronously */
2255 MonoException *exc = mono_thread_request_interruption (FALSE);
2257 mono_raise_exception (exc);
2261 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2263 /* fixme: store the state somewhere */
2264 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2267 * This will cause waits to be broken.
2268 * It will also prevent the thread from entering a wait, so if the thread returns
2269 * from the wait before it receives the abort signal, it will just spin in the wait
2270 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2273 wapi_interrupt_thread (thread->handle);
2274 #endif /* HOST_WIN32 */
2278 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2280 ensure_synch_cs_set (thread);
2282 EnterCriticalSection (thread->synch_cs);
2284 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2285 (thread->state & ThreadState_StopRequested) != 0 ||
2286 (thread->state & ThreadState_Stopped) != 0)
2288 LeaveCriticalSection (thread->synch_cs);
2292 if ((thread->state & ThreadState_Unstarted) != 0) {
2293 thread->state |= ThreadState_Aborted;
2294 LeaveCriticalSection (thread->synch_cs);
2298 thread->state |= ThreadState_AbortRequested;
2299 if (thread->abort_state_handle)
2300 mono_gchandle_free (thread->abort_state_handle);
2302 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2303 g_assert (thread->abort_state_handle);
2305 thread->abort_state_handle = 0;
2307 thread->abort_exc = NULL;
2310 * abort_exc is set in mono_thread_execute_interruption(),
2311 * triggered by the call to signal_thread_state_change(),
2312 * below. There's a point between where we have
2313 * abort_state_handle set, but abort_exc NULL, but that's not
2317 LeaveCriticalSection (thread->synch_cs);
2319 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2321 /* During shutdown, we can't wait for other threads */
2323 /* Make sure the thread is awake */
2324 mono_thread_resume (thread);
2326 signal_thread_state_change (thread);
2330 ves_icall_System_Threading_Thread_ResetAbort (void)
2332 MonoInternalThread *thread = mono_thread_internal_current ();
2333 gboolean was_aborting;
2335 ensure_synch_cs_set (thread);
2337 EnterCriticalSection (thread->synch_cs);
2338 was_aborting = thread->state & ThreadState_AbortRequested;
2339 thread->state &= ~ThreadState_AbortRequested;
2340 LeaveCriticalSection (thread->synch_cs);
2342 if (!was_aborting) {
2343 const char *msg = "Unable to reset abort because no abort was requested";
2344 mono_raise_exception (mono_get_exception_thread_state (msg));
2346 thread->abort_exc = NULL;
2347 if (thread->abort_state_handle) {
2348 mono_gchandle_free (thread->abort_state_handle);
2349 /* This is actually not necessary - the handle
2350 only counts if the exception is set */
2351 thread->abort_state_handle = 0;
2356 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2358 ensure_synch_cs_set (thread);
2360 EnterCriticalSection (thread->synch_cs);
2362 thread->state &= ~ThreadState_AbortRequested;
2364 if (thread->abort_exc) {
2365 thread->abort_exc = NULL;
2366 if (thread->abort_state_handle) {
2367 mono_gchandle_free (thread->abort_state_handle);
2368 /* This is actually not necessary - the handle
2369 only counts if the exception is set */
2370 thread->abort_state_handle = 0;
2374 LeaveCriticalSection (thread->synch_cs);
2378 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2380 MonoInternalThread *thread = this->internal_thread;
2381 MonoObject *state, *deserialized = NULL, *exc;
2384 if (!thread->abort_state_handle)
2387 state = mono_gchandle_get_target (thread->abort_state_handle);
2390 domain = mono_domain_get ();
2391 if (mono_object_domain (state) == domain)
2394 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2396 if (!deserialized) {
2397 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2399 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2400 mono_raise_exception (invalid_op_exc);
2403 return deserialized;
2407 mono_thread_suspend (MonoInternalThread *thread)
2409 ensure_synch_cs_set (thread);
2411 EnterCriticalSection (thread->synch_cs);
2413 if ((thread->state & ThreadState_Unstarted) != 0 ||
2414 (thread->state & ThreadState_Aborted) != 0 ||
2415 (thread->state & ThreadState_Stopped) != 0)
2417 LeaveCriticalSection (thread->synch_cs);
2421 if ((thread->state & ThreadState_Suspended) != 0 ||
2422 (thread->state & ThreadState_SuspendRequested) != 0 ||
2423 (thread->state & ThreadState_StopRequested) != 0)
2425 LeaveCriticalSection (thread->synch_cs);
2429 thread->state |= ThreadState_SuspendRequested;
2431 LeaveCriticalSection (thread->synch_cs);
2433 signal_thread_state_change (thread);
2438 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2440 if (!mono_thread_suspend (thread))
2441 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2445 mono_thread_resume (MonoInternalThread *thread)
2447 ensure_synch_cs_set (thread);
2449 EnterCriticalSection (thread->synch_cs);
2451 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2452 thread->state &= ~ThreadState_SuspendRequested;
2453 LeaveCriticalSection (thread->synch_cs);
2457 if ((thread->state & ThreadState_Suspended) == 0 ||
2458 (thread->state & ThreadState_Unstarted) != 0 ||
2459 (thread->state & ThreadState_Aborted) != 0 ||
2460 (thread->state & ThreadState_Stopped) != 0)
2462 LeaveCriticalSection (thread->synch_cs);
2466 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2467 if (thread->resume_event == NULL) {
2468 LeaveCriticalSection (thread->synch_cs);
2472 /* Awake the thread */
2473 SetEvent (thread->suspend_event);
2475 LeaveCriticalSection (thread->synch_cs);
2477 /* Wait for the thread to awake */
2478 WaitForSingleObject (thread->resume_event, INFINITE);
2479 CloseHandle (thread->resume_event);
2480 thread->resume_event = NULL;
2486 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2488 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2489 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2493 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2498 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2499 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2500 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2502 *((gboolean*)data) = TRUE;
2509 is_running_protected_wrapper (void)
2511 gboolean found = FALSE;
2512 mono_stack_walk (find_wrapper, &found);
2516 void mono_thread_internal_stop (MonoInternalThread *thread)
2518 ensure_synch_cs_set (thread);
2520 EnterCriticalSection (thread->synch_cs);
2522 if ((thread->state & ThreadState_StopRequested) != 0 ||
2523 (thread->state & ThreadState_Stopped) != 0)
2525 LeaveCriticalSection (thread->synch_cs);
2529 /* Make sure the thread is awake */
2530 mono_thread_resume (thread);
2532 thread->state |= ThreadState_StopRequested;
2533 thread->state &= ~ThreadState_AbortRequested;
2535 LeaveCriticalSection (thread->synch_cs);
2537 signal_thread_state_change (thread);
2540 void mono_thread_stop (MonoThread *thread)
2542 mono_thread_internal_stop (thread->internal_thread);
2546 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2548 return *((volatile gint8 *) (ptr));
2552 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2554 return *((volatile gint16 *) (ptr));
2558 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2560 return *((volatile gint32 *) (ptr));
2564 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2566 return *((volatile gint64 *) (ptr));
2570 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2572 return (void *) *((volatile void **) ptr);
2576 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2578 *((volatile gint8 *) ptr) = value;
2582 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2584 *((volatile gint16 *) ptr) = value;
2588 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2590 *((volatile gint32 *) ptr) = value;
2594 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2596 *((volatile gint64 *) ptr) = value;
2600 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2602 *((volatile void **) ptr) = value;
2606 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2608 mono_gc_wbarrier_generic_store (ptr, value);
2611 void mono_thread_init (MonoThreadStartCB start_cb,
2612 MonoThreadAttachCB attach_cb)
2614 MONO_GC_REGISTER_ROOT_FIXED (small_id_table);
2615 InitializeCriticalSection(&threads_mutex);
2616 InitializeCriticalSection(&interlocked_mutex);
2617 InitializeCriticalSection(&contexts_mutex);
2618 InitializeCriticalSection(&delayed_free_table_mutex);
2619 InitializeCriticalSection(&small_id_mutex);
2621 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2622 g_assert(background_change_event != NULL);
2624 mono_init_static_data_info (&thread_static_info);
2625 mono_init_static_data_info (&context_static_info);
2627 current_object_key=TlsAlloc();
2628 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2630 mono_thread_start_cb = start_cb;
2631 mono_thread_attach_cb = attach_cb;
2633 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2635 /* Get a pseudo handle to the current process. This is just a
2636 * kludge so that wapi can build a process handle if needed.
2637 * As a pseudo handle is returned, we don't need to clean
2640 GetCurrentProcess ();
2643 void mono_thread_cleanup (void)
2645 mono_thread_hazardous_try_free_all ();
2647 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2648 /* The main thread must abandon any held mutexes (particularly
2649 * important for named mutexes as they are shared across
2650 * processes, see bug 74680.) This will happen when the
2651 * thread exits, but if it's not running in a subthread it
2652 * won't exit in time.
2654 /* Using non-w32 API is a nasty kludge, but I couldn't find
2655 * anything in the documentation that would let me do this
2656 * here yet still be safe to call on windows.
2658 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2662 /* This stuff needs more testing, it seems one of these
2663 * critical sections can be locked when mono_thread_cleanup is
2666 DeleteCriticalSection (&threads_mutex);
2667 DeleteCriticalSection (&interlocked_mutex);
2668 DeleteCriticalSection (&contexts_mutex);
2669 DeleteCriticalSection (&delayed_free_table_mutex);
2670 DeleteCriticalSection (&small_id_mutex);
2671 CloseHandle (background_change_event);
2674 g_array_free (delayed_free_table, TRUE);
2675 delayed_free_table = NULL;
2677 TlsFree (current_object_key);
2681 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2683 mono_thread_cleanup_fn = func;
2687 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2689 thread->internal_thread->manage_callback = func;
2692 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2694 mono_thread_notify_pending_exc_fn = func;
2698 static void print_tids (gpointer key, gpointer value, gpointer user)
2700 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2701 * sizeof(uint) and a cast to uint would overflow
2703 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2704 * print this as a pointer.
2706 g_message ("Waiting for: %p", key);
2711 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2712 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2716 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2720 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2722 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, TRUE);
2724 if(ret==WAIT_FAILED) {
2725 /* See the comment in build_wait_tids() */
2726 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2730 for(i=0; i<wait->num; i++)
2731 CloseHandle (wait->handles[i]);
2733 if (ret == WAIT_TIMEOUT)
2736 for(i=0; i<wait->num; i++) {
2737 gsize tid = wait->threads[i]->tid;
2739 mono_threads_lock ();
2740 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2741 /* This thread must have been killed, because
2742 * it hasn't cleaned itself up. (It's just
2743 * possible that the thread exited before the
2744 * parent thread had a chance to store the
2745 * handle, and now there is another pointer to
2746 * the already-exited thread stored. In this
2747 * case, we'll just get two
2748 * mono_profiler_thread_end() calls for the
2752 mono_threads_unlock ();
2753 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2754 thread_cleanup (wait->threads[i]);
2756 mono_threads_unlock ();
2761 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2763 guint32 i, ret, count;
2765 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2767 /* Add the thread state change event, so it wakes up if a thread changes
2768 * to background mode.
2771 if (count < MAXIMUM_WAIT_OBJECTS) {
2772 wait->handles [count] = background_change_event;
2776 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, TRUE);
2778 if(ret==WAIT_FAILED) {
2779 /* See the comment in build_wait_tids() */
2780 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2784 for(i=0; i<wait->num; i++)
2785 CloseHandle (wait->handles[i]);
2787 if (ret == WAIT_TIMEOUT)
2790 if (ret < wait->num) {
2791 gsize tid = wait->threads[ret]->tid;
2792 mono_threads_lock ();
2793 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2794 /* See comment in wait_for_tids about thread cleanup */
2795 mono_threads_unlock ();
2796 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2797 thread_cleanup (wait->threads [ret]);
2799 mono_threads_unlock ();
2803 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2805 struct wait_data *wait=(struct wait_data *)user;
2807 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2809 MonoInternalThread *thread=(MonoInternalThread *)value;
2811 /* Ignore background threads, we abort them later */
2812 /* Do not lock here since it is not needed and the caller holds threads_lock */
2813 if (thread->state & ThreadState_Background) {
2814 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2815 return; /* just leave, ignore */
2818 if (mono_gc_is_finalizer_internal_thread (thread)) {
2819 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2823 if (thread == mono_thread_internal_current ()) {
2824 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2828 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2829 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2833 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2834 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2838 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2839 if (handle == NULL) {
2840 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2844 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2845 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2846 wait->handles[wait->num]=handle;
2847 wait->threads[wait->num]=thread;
2850 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2852 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2857 /* Just ignore the rest, we can't do anything with
2864 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2866 struct wait_data *wait=(struct wait_data *)user;
2867 gsize self = GetCurrentThreadId ();
2868 MonoInternalThread *thread = value;
2871 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2874 /* The finalizer thread is not a background thread */
2875 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2876 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2878 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2882 /* printf ("A: %d\n", wait->num); */
2883 wait->handles[wait->num]=thread->handle;
2884 wait->threads[wait->num]=thread;
2887 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2888 mono_thread_internal_stop (thread);
2892 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2896 * mono_threads_set_shutting_down:
2898 * Is called by a thread that wants to shut down Mono. If the runtime is already
2899 * shutting down, the calling thread is suspended/stopped, and this function never
2903 mono_threads_set_shutting_down (void)
2905 MonoInternalThread *current_thread = mono_thread_internal_current ();
2907 mono_threads_lock ();
2909 if (shutting_down) {
2910 mono_threads_unlock ();
2912 /* Make sure we're properly suspended/stopped */
2914 EnterCriticalSection (current_thread->synch_cs);
2916 if ((current_thread->state & ThreadState_SuspendRequested) ||
2917 (current_thread->state & ThreadState_AbortRequested) ||
2918 (current_thread->state & ThreadState_StopRequested)) {
2919 LeaveCriticalSection (current_thread->synch_cs);
2920 mono_thread_execute_interruption (current_thread);
2922 current_thread->state |= ThreadState_Stopped;
2923 LeaveCriticalSection (current_thread->synch_cs);
2926 /*since we're killing the thread, unset the current domain.*/
2927 mono_domain_unset ();
2929 /* Wake up other threads potentially waiting for us */
2932 shutting_down = TRUE;
2934 /* Not really a background state change, but this will
2935 * interrupt the main thread if it is waiting for all
2936 * the other threads.
2938 SetEvent (background_change_event);
2940 mono_threads_unlock ();
2945 * mono_threads_is_shutting_down:
2947 * Returns whether a thread has commenced shutdown of Mono. Note that
2948 * if the function returns FALSE the caller must not assume that
2949 * shutdown is not in progress, because the situation might have
2950 * changed since the function returned. For that reason this function
2951 * is of very limited utility.
2954 mono_threads_is_shutting_down (void)
2956 return shutting_down;
2959 void mono_thread_manage (void)
2961 struct wait_data wait_data;
2962 struct wait_data *wait = &wait_data;
2964 memset (wait, 0, sizeof (struct wait_data));
2965 /* join each thread that's still running */
2966 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2968 mono_threads_lock ();
2970 THREAD_DEBUG (g_message("%s: No threads", __func__));
2971 mono_threads_unlock ();
2974 mono_threads_unlock ();
2977 mono_threads_lock ();
2978 if (shutting_down) {
2979 /* somebody else is shutting down */
2980 mono_threads_unlock ();
2983 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2984 mono_g_hash_table_foreach (threads, print_tids, NULL));
2986 ResetEvent (background_change_event);
2988 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
2989 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
2990 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2991 mono_threads_unlock ();
2993 /* Something to wait for */
2994 wait_for_tids_or_state_change (wait, INFINITE);
2996 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2997 } while(wait->num>0);
2999 mono_threads_set_shutting_down ();
3001 /* No new threads will be created after this point */
3003 mono_runtime_set_shutting_down ();
3005 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3006 mono_thread_pool_cleanup ();
3009 * Remove everything but the finalizer thread and self.
3010 * Also abort all the background threads
3013 mono_threads_lock ();
3016 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3017 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3018 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3020 mono_threads_unlock ();
3022 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3024 /* Something to wait for */
3025 wait_for_tids (wait, INFINITE);
3027 } while (wait->num > 0);
3030 * give the subthreads a chance to really quit (this is mainly needed
3031 * to get correct user and system times from getrusage/wait/time(1)).
3032 * This could be removed if we avoid pthread_detach() and use pthread_join().
3039 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3041 MonoInternalThread *thread=(MonoInternalThread *)value;
3043 if(thread->tid != (gsize)user) {
3044 /*TerminateThread (thread->handle, -1);*/
3048 void mono_thread_abort_all_other_threads (void)
3050 gsize self = GetCurrentThreadId ();
3052 mono_threads_lock ();
3053 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3054 mono_g_hash_table_size (threads));
3055 mono_g_hash_table_foreach (threads, print_tids, NULL));
3057 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3059 mono_threads_unlock ();
3063 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3065 MonoInternalThread *thread = (MonoInternalThread*)value;
3066 struct wait_data *wait = (struct wait_data*)user_data;
3070 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3072 * This needs no locking.
3074 if ((thread->state & ThreadState_Suspended) != 0 ||
3075 (thread->state & ThreadState_Stopped) != 0)
3078 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3079 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3083 wait->handles [wait->num] = handle;
3084 wait->threads [wait->num] = thread;
3090 * mono_thread_suspend_all_other_threads:
3092 * Suspend all managed threads except the finalizer thread and this thread. It is
3093 * not possible to resume them later.
3095 void mono_thread_suspend_all_other_threads (void)
3097 struct wait_data wait_data;
3098 struct wait_data *wait = &wait_data;
3100 gsize self = GetCurrentThreadId ();
3102 guint32 eventidx = 0;
3103 gboolean starting, finished;
3105 memset (wait, 0, sizeof (struct wait_data));
3107 * The other threads could be in an arbitrary state at this point, i.e.
3108 * they could be starting up, shutting down etc. This means that there could be
3109 * threads which are not even in the threads hash table yet.
3113 * First we set a barrier which will be checked by all threads before they
3114 * are added to the threads hash table, and they will exit if the flag is set.
3115 * This ensures that no threads could be added to the hash later.
3116 * We will use shutting_down as the barrier for now.
3118 g_assert (shutting_down);
3121 * We make multiple calls to WaitForMultipleObjects since:
3122 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3123 * - some threads could exit without becoming suspended
3128 * Make a copy of the hashtable since we can't do anything with
3129 * threads while threads_mutex is held.
3132 /*We must zero all InternalThread pointers to avoid making the GC unhappy.*/
3133 memset (wait->threads, 0, MAXIMUM_WAIT_OBJECTS * SIZEOF_VOID_P);
3134 mono_threads_lock ();
3135 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3136 mono_threads_unlock ();
3138 events = g_new0 (gpointer, wait->num);
3140 /* Get the suspended events that we'll be waiting for */
3141 for (i = 0; i < wait->num; ++i) {
3142 MonoInternalThread *thread = wait->threads [i];
3143 gboolean signal_suspend = FALSE;
3145 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3146 //CloseHandle (wait->handles [i]);
3147 wait->threads [i] = NULL; /* ignore this thread in next loop */
3151 ensure_synch_cs_set (thread);
3153 EnterCriticalSection (thread->synch_cs);
3155 if (thread->suspended_event == NULL) {
3156 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3157 if (thread->suspended_event == NULL) {
3158 /* Forget this one and go on to the next */
3159 LeaveCriticalSection (thread->synch_cs);
3164 if ((thread->state & ThreadState_Suspended) != 0 ||
3165 (thread->state & ThreadState_StopRequested) != 0 ||
3166 (thread->state & ThreadState_Stopped) != 0) {
3167 LeaveCriticalSection (thread->synch_cs);
3168 CloseHandle (wait->handles [i]);
3169 wait->threads [i] = NULL; /* ignore this thread in next loop */
3173 if ((thread->state & ThreadState_SuspendRequested) == 0)
3174 signal_suspend = TRUE;
3176 events [eventidx++] = thread->suspended_event;
3178 /* Convert abort requests into suspend requests */
3179 if ((thread->state & ThreadState_AbortRequested) != 0)
3180 thread->state &= ~ThreadState_AbortRequested;
3182 thread->state |= ThreadState_SuspendRequested;
3184 LeaveCriticalSection (thread->synch_cs);
3186 /* Signal the thread to suspend */
3188 signal_thread_state_change (thread);
3192 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3193 for (i = 0; i < wait->num; ++i) {
3194 MonoInternalThread *thread = wait->threads [i];
3199 ensure_synch_cs_set (thread);
3201 EnterCriticalSection (thread->synch_cs);
3202 if ((thread->state & ThreadState_Suspended) != 0) {
3203 CloseHandle (thread->suspended_event);
3204 thread->suspended_event = NULL;
3206 LeaveCriticalSection (thread->synch_cs);
3210 * If there are threads which are starting up, we wait until they
3211 * are suspended when they try to register in the threads hash.
3212 * This is guaranteed to finish, since the threads which can create new
3213 * threads get suspended after a while.
3214 * FIXME: The finalizer thread can still create new threads.
3216 mono_threads_lock ();
3217 if (threads_starting_up)
3218 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3221 mono_threads_unlock ();
3233 collect_threads (gpointer key, gpointer value, gpointer user_data)
3235 MonoInternalThread *thread = (MonoInternalThread*)value;
3236 struct wait_data *wait = (struct wait_data*)user_data;
3239 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3240 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3244 wait->handles [wait->num] = handle;
3245 wait->threads [wait->num] = thread;
3251 * mono_threads_request_thread_dump:
3253 * Ask all threads except the current to print their stacktrace to stdout.
3256 mono_threads_request_thread_dump (void)
3258 struct wait_data wait_data;
3259 struct wait_data *wait = &wait_data;
3262 memset (wait, 0, sizeof (struct wait_data));
3265 * Make a copy of the hashtable since we can't do anything with
3266 * threads while threads_mutex is held.
3268 mono_threads_lock ();
3269 mono_g_hash_table_foreach (threads, collect_threads, wait);
3270 mono_threads_unlock ();
3272 for (i = 0; i < wait->num; ++i) {
3273 MonoInternalThread *thread = wait->threads [i];
3275 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3276 (thread != mono_thread_internal_current ()) &&
3277 !thread->thread_dump_requested) {
3278 thread->thread_dump_requested = TRUE;
3280 signal_thread_state_change (thread);
3283 CloseHandle (wait->handles [i]);
3288 * mono_thread_push_appdomain_ref:
3290 * Register that the current thread may have references to objects in domain
3291 * @domain on its stack. Each call to this function should be paired with a
3292 * call to pop_appdomain_ref.
3295 mono_thread_push_appdomain_ref (MonoDomain *domain)
3297 MonoInternalThread *thread = mono_thread_internal_current ();
3300 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3301 SPIN_LOCK (thread->lock_thread_id);
3302 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3303 SPIN_UNLOCK (thread->lock_thread_id);
3308 mono_thread_pop_appdomain_ref (void)
3310 MonoInternalThread *thread = mono_thread_internal_current ();
3313 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3314 /* FIXME: How can the list be empty ? */
3315 SPIN_LOCK (thread->lock_thread_id);
3316 if (thread->appdomain_refs)
3317 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3318 SPIN_UNLOCK (thread->lock_thread_id);
3323 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3326 SPIN_LOCK (thread->lock_thread_id);
3327 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3328 SPIN_UNLOCK (thread->lock_thread_id);
3333 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3335 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3338 typedef struct abort_appdomain_data {
3339 struct wait_data wait;
3341 } abort_appdomain_data;
3344 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3346 MonoInternalThread *thread = (MonoInternalThread*)value;
3347 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3348 MonoDomain *domain = data->domain;
3350 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3351 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3353 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3354 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3357 data->wait.handles [data->wait.num] = handle;
3358 data->wait.threads [data->wait.num] = thread;
3361 /* Just ignore the rest, we can't do anything with
3369 * mono_threads_abort_appdomain_threads:
3371 * Abort threads which has references to the given appdomain.
3374 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3376 abort_appdomain_data user_data;
3378 int orig_timeout = timeout;
3381 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3383 start_time = mono_msec_ticks ();
3385 mono_threads_lock ();
3387 user_data.domain = domain;
3388 user_data.wait.num = 0;
3389 /* This shouldn't take any locks */
3390 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3391 mono_threads_unlock ();
3393 if (user_data.wait.num > 0) {
3394 /* Abort the threads outside the threads lock */
3395 for (i = 0; i < user_data.wait.num; ++i)
3396 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3399 * We should wait for the threads either to abort, or to leave the
3400 * domain. We can't do the latter, so we wait with a timeout.
3402 wait_for_tids (&user_data.wait, 100);
3405 /* Update remaining time */
3406 timeout -= mono_msec_ticks () - start_time;
3407 start_time = mono_msec_ticks ();
3409 if (orig_timeout != -1 && timeout < 0)
3412 while (user_data.wait.num > 0);
3414 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3420 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3422 MonoInternalThread *thread = (MonoInternalThread*)value;
3423 MonoDomain *domain = (MonoDomain*)user_data;
3426 /* No locking needed here */
3427 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3429 if (thread->cached_culture_info) {
3430 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3431 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3432 if (obj && obj->vtable->domain == domain)
3433 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3439 * mono_threads_clear_cached_culture:
3441 * Clear the cached_current_culture from all threads if it is in the
3445 mono_threads_clear_cached_culture (MonoDomain *domain)
3447 mono_threads_lock ();
3448 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3449 mono_threads_unlock ();
3453 * mono_thread_get_undeniable_exception:
3455 * Return an exception which needs to be raised when leaving a catch clause.
3456 * This is used for undeniable exception propagation.
3459 mono_thread_get_undeniable_exception (void)
3461 MonoInternalThread *thread = mono_thread_internal_current ();
3463 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3465 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3466 * exception if the thread no longer references a dying appdomain.
3468 thread->abort_exc->trace_ips = NULL;
3469 thread->abort_exc->stack_trace = NULL;
3470 return thread->abort_exc;
3476 #if MONO_SMALL_CONFIG
3477 #define NUM_STATIC_DATA_IDX 4
3478 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3482 #define NUM_STATIC_DATA_IDX 8
3483 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3484 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3488 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3492 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3495 gpointer *static_data = addr;
3496 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3499 if (!static_data [i])
3501 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3502 ptr = static_data [i];
3503 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3504 uintptr_t bmap = static_reference_bitmaps [i][j];
3507 if ((bmap & 1) && *p) {
3519 * mono_alloc_static_data
3521 * Allocate memory blocks for storing threads or context static data
3524 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3526 guint idx = (offset >> 24) - 1;
3529 gpointer* static_data = *static_data_ptr;
3531 static void* tls_desc = NULL;
3534 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3536 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3537 *static_data_ptr = static_data;
3538 static_data [0] = static_data;
3541 for (i = 1; i <= idx; ++i) {
3542 if (static_data [i])
3545 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3547 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3553 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3556 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3557 if (!static_data [i])
3561 g_free (static_data [i]);
3563 mono_gc_free_fixed (static_data [i]);
3565 mono_gc_free_fixed (static_data [i]);
3568 mono_gc_free_fixed (static_data);
3572 * mono_init_static_data_info
3574 * Initializes static data counters
3576 static void mono_init_static_data_info (StaticDataInfo *static_data)
3578 static_data->idx = 0;
3579 static_data->offset = 0;
3580 static_data->freelist = NULL;
3584 * mono_alloc_static_data_slot
3586 * Generates an offset for static data. static_data contains the counters
3587 * used to generate it.
3590 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3594 if (!static_data->idx && !static_data->offset) {
3596 * we use the first chunk of the first allocation also as
3597 * an array for the rest of the data
3599 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3601 static_data->offset += align - 1;
3602 static_data->offset &= ~(align - 1);
3603 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3604 static_data->idx ++;
3605 g_assert (size <= static_data_size [static_data->idx]);
3606 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3607 static_data->offset = 0;
3609 offset = static_data->offset | ((static_data->idx + 1) << 24);
3610 static_data->offset += size;
3615 * ensure thread static fields already allocated are valid for thread
3616 * This function is called when a thread is created or on thread attach.
3619 thread_adjust_static_data (MonoInternalThread *thread)
3623 mono_threads_lock ();
3624 if (thread_static_info.offset || thread_static_info.idx > 0) {
3625 /* get the current allocated size */
3626 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3627 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3629 mono_threads_unlock ();
3633 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3635 MonoInternalThread *thread = value;
3636 guint32 offset = GPOINTER_TO_UINT (user);
3638 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3641 static MonoThreadDomainTls*
3642 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3644 MonoThreadDomainTls* prev = NULL;
3645 MonoThreadDomainTls* tmp = static_data->freelist;
3647 if (tmp->size == size) {
3649 prev->next = tmp->next;
3651 static_data->freelist = tmp->next;
3660 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3663 int idx = (offset >> 24) - 1;
3665 if (!static_reference_bitmaps [idx])
3666 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3667 rb = static_reference_bitmaps [idx];
3669 offset /= sizeof (gpointer);
3670 /* offset is now the bitmap offset */
3671 for (i = 0; i < max_set; ++i) {
3672 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3673 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3678 clear_reference_bitmap (guint32 offset, guint32 size)
3680 int idx = (offset >> 24) - 1;
3682 rb = static_reference_bitmaps [idx];
3684 offset /= sizeof (gpointer);
3685 size /= sizeof (gpointer);
3687 /* offset is now the bitmap offset */
3688 for (; offset < size; ++offset)
3689 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3693 * The offset for a special static variable is composed of three parts:
3694 * a bit that indicates the type of static data (0:thread, 1:context),
3695 * an index in the array of chunks of memory for the thread (thread->static_data)
3696 * and an offset in that chunk of mem. This allows allocating less memory in the
3701 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3704 if (static_type == SPECIAL_STATIC_THREAD) {
3705 MonoThreadDomainTls *item;
3706 mono_threads_lock ();
3707 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3708 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3710 offset = item->offset;
3713 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3715 update_tls_reference_bitmap (offset, bitmap, max_set);
3716 /* This can be called during startup */
3717 if (threads != NULL)
3718 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3719 mono_threads_unlock ();
3721 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3722 mono_contexts_lock ();
3723 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3724 mono_contexts_unlock ();
3725 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3731 mono_get_special_static_data_for_thread (MonoInternalThread *thread, guint32 offset)
3733 /* The high bit means either thread (0) or static (1) data. */
3735 guint32 static_type = (offset & 0x80000000);
3738 offset &= 0x7fffffff;
3739 idx = (offset >> 24) - 1;
3741 if (static_type == 0) {
3742 return get_thread_static_data (thread, offset);
3744 /* Allocate static data block under demand, since we don't have a list
3747 MonoAppContext *context = mono_context_get ();
3748 if (!context->static_data || !context->static_data [idx]) {
3749 mono_contexts_lock ();
3750 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3751 mono_contexts_unlock ();
3753 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3758 mono_get_special_static_data (guint32 offset)
3760 return mono_get_special_static_data_for_thread (mono_thread_internal_current (), offset);
3769 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3771 MonoInternalThread *thread = value;
3772 TlsOffsetSize *data = user;
3773 int idx = (data->offset >> 24) - 1;
3776 if (!thread->static_data || !thread->static_data [idx])
3778 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3779 memset (ptr, 0, data->size);
3783 do_free_special (gpointer key, gpointer value, gpointer data)
3785 MonoClassField *field = key;
3786 guint32 offset = GPOINTER_TO_UINT (value);
3787 guint32 static_type = (offset & 0x80000000);
3790 size = mono_type_size (field->type, &align);
3791 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3792 if (static_type == 0) {
3794 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3795 data.offset = offset & 0x7fffffff;
3797 clear_reference_bitmap (data.offset, data.size);
3798 if (threads != NULL)
3799 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3800 item->offset = offset;
3803 if (!mono_runtime_is_shutting_down ()) {
3804 item->next = thread_static_info.freelist;
3805 thread_static_info.freelist = item;
3807 /* We could be called during shutdown after mono_thread_cleanup () is called */
3811 /* FIXME: free context static data as well */
3816 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3818 mono_threads_lock ();
3819 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3820 mono_threads_unlock ();
3823 static MonoClassField *local_slots = NULL;
3826 /* local tls data to get locals_slot from a thread */
3829 /* index in the locals_slot array */
3834 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3836 LocalSlotID *sid = user_data;
3837 MonoInternalThread *thread = (MonoInternalThread*)value;
3838 MonoArray *slots_array;
3840 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3841 * it is for the right domain, so we need to check if it is allocated an initialized
3842 * for the current thread.
3844 /*g_print ("handling thread %p\n", thread);*/
3845 if (!thread->static_data || !thread->static_data [sid->idx])
3847 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3848 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3850 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3854 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3862 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3864 g_warning ("local_slots field not found in Thread class");
3868 domain = mono_domain_get ();
3869 mono_domain_lock (domain);
3870 if (domain->special_static_fields)
3871 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3872 mono_domain_unlock (domain);
3875 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3876 sid.offset = GPOINTER_TO_UINT (addr);
3877 sid.offset &= 0x7fffffff;
3878 sid.idx = (sid.offset >> 24) - 1;
3879 mono_threads_lock ();
3880 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3881 mono_threads_unlock ();
3883 /* FIXME: clear the slot for MonoAppContexts, too */
3888 static void CALLBACK dummy_apc (ULONG_PTR param)
3892 static guint32 dummy_apc (gpointer param)
3899 * mono_thread_execute_interruption
3901 * Performs the operation that the requested thread state requires (abort,
3904 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3906 ensure_synch_cs_set (thread);
3908 EnterCriticalSection (thread->synch_cs);
3910 /* MonoThread::interruption_requested can only be changed with atomics */
3911 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3912 /* this will consume pending APC calls */
3913 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3914 InterlockedDecrement (&thread_interruption_requested);
3916 /* Clear the interrupted flag of the thread so it can wait again */
3917 wapi_clear_interruption ();
3921 if ((thread->state & ThreadState_AbortRequested) != 0) {
3922 LeaveCriticalSection (thread->synch_cs);
3923 if (thread->abort_exc == NULL) {
3925 * This might be racy, but it has to be called outside the lock
3926 * since it calls managed code.
3928 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3930 return thread->abort_exc;
3932 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3933 thread->state &= ~ThreadState_SuspendRequested;
3934 thread->state |= ThreadState_Suspended;
3935 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3936 if (thread->suspend_event == NULL) {
3937 LeaveCriticalSection (thread->synch_cs);
3940 if (thread->suspended_event)
3941 SetEvent (thread->suspended_event);
3943 LeaveCriticalSection (thread->synch_cs);
3945 if (shutting_down) {
3946 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3951 WaitForSingleObject (thread->suspend_event, INFINITE);
3953 EnterCriticalSection (thread->synch_cs);
3955 CloseHandle (thread->suspend_event);
3956 thread->suspend_event = NULL;
3957 thread->state &= ~ThreadState_Suspended;
3959 /* The thread that requested the resume will have replaced this event
3960 * and will be waiting for it
3962 SetEvent (thread->resume_event);
3964 LeaveCriticalSection (thread->synch_cs);
3968 else if ((thread->state & ThreadState_StopRequested) != 0) {
3969 /* FIXME: do this through the JIT? */
3971 LeaveCriticalSection (thread->synch_cs);
3973 mono_thread_exit ();
3975 } else if (thread->thread_interrupt_requested) {
3977 thread->thread_interrupt_requested = FALSE;
3978 LeaveCriticalSection (thread->synch_cs);
3980 return(mono_get_exception_thread_interrupted ());
3983 LeaveCriticalSection (thread->synch_cs);
3989 * mono_thread_request_interruption
3991 * A signal handler can call this method to request the interruption of a
3992 * thread. The result of the interruption will depend on the current state of
3993 * the thread. If the result is an exception that needs to be throw, it is
3994 * provided as return value.
3997 mono_thread_request_interruption (gboolean running_managed)
3999 MonoInternalThread *thread = mono_thread_internal_current ();
4001 /* The thread may already be stopping */
4006 if (thread->interrupt_on_stop &&
4007 thread->state & ThreadState_StopRequested &&
4008 thread->state & ThreadState_Background)
4012 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4015 if (!running_managed || is_running_protected_wrapper ()) {
4016 /* Can't stop while in unmanaged code. Increase the global interruption
4017 request count. When exiting the unmanaged method the count will be
4018 checked and the thread will be interrupted. */
4020 InterlockedIncrement (&thread_interruption_requested);
4022 if (mono_thread_notify_pending_exc_fn && !running_managed)
4023 /* The JIT will notify the thread about the interruption */
4024 /* This shouldn't take any locks */
4025 mono_thread_notify_pending_exc_fn ();
4027 /* this will awake the thread if it is in WaitForSingleObject
4029 /* Our implementation of this function ignores the func argument */
4030 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4034 return mono_thread_execute_interruption (thread);
4038 /*This function should be called by a thread after it has exited all of
4039 * its handle blocks at interruption time.*/
4041 mono_thread_resume_interruption (void)
4043 MonoInternalThread *thread = mono_thread_internal_current ();
4044 gboolean still_aborting;
4046 /* The thread may already be stopping */
4050 ensure_synch_cs_set (thread);
4051 EnterCriticalSection (thread->synch_cs);
4052 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4053 LeaveCriticalSection (thread->synch_cs);
4055 /*This can happen if the protected block called Thread::ResetAbort*/
4056 if (!still_aborting)
4059 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4061 InterlockedIncrement (&thread_interruption_requested);
4064 wapi_self_interrupt ();
4066 return mono_thread_execute_interruption (thread);
4069 gboolean mono_thread_interruption_requested ()
4071 if (thread_interruption_requested) {
4072 MonoInternalThread *thread = mono_thread_internal_current ();
4073 /* The thread may already be stopping */
4075 return (thread->interruption_requested);
4080 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4082 MonoInternalThread *thread = mono_thread_internal_current ();
4084 /* The thread may already be stopping */
4088 mono_debugger_check_interruption ();
4090 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4091 MonoException* exc = mono_thread_execute_interruption (thread);
4092 if (exc) mono_raise_exception (exc);
4097 * Performs the interruption of the current thread, if one has been requested,
4098 * and the thread is not running a protected wrapper.
4100 void mono_thread_interruption_checkpoint ()
4102 mono_thread_interruption_checkpoint_request (FALSE);
4106 * Performs the interruption of the current thread, if one has been requested.
4108 void mono_thread_force_interruption_checkpoint ()
4110 mono_thread_interruption_checkpoint_request (TRUE);
4114 * mono_thread_get_and_clear_pending_exception:
4116 * Return any pending exceptions for the current thread and clear it as a side effect.
4119 mono_thread_get_and_clear_pending_exception (void)
4121 MonoInternalThread *thread = mono_thread_internal_current ();
4123 /* The thread may already be stopping */
4127 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4128 return mono_thread_execute_interruption (thread);
4131 if (thread->pending_exception) {
4132 MonoException *exc = thread->pending_exception;
4134 thread->pending_exception = NULL;
4142 * mono_set_pending_exception:
4144 * Set the pending exception of the current thread to EXC. On platforms which
4145 * support it, the exception will be thrown when execution returns to managed code.
4146 * On other platforms, this function is equivalent to mono_raise_exception ().
4147 * Internal calls which report exceptions using this function instead of
4148 * raise_exception () might be called by JITted code using a more efficient calling
4152 mono_set_pending_exception (MonoException *exc)
4154 MonoInternalThread *thread = mono_thread_internal_current ();
4156 /* The thread may already be stopping */
4160 if (mono_thread_notify_pending_exc_fn) {
4161 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4163 mono_thread_notify_pending_exc_fn ();
4165 /* No way to notify the JIT about the exception, have to throw it now */
4166 mono_raise_exception (exc);
4171 * mono_thread_interruption_request_flag:
4173 * Returns the address of a flag that will be non-zero if an interruption has
4174 * been requested for a thread. The thread to interrupt may not be the current
4175 * thread, so an additional call to mono_thread_interruption_requested() or
4176 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4179 gint32* mono_thread_interruption_request_flag ()
4181 return &thread_interruption_requested;
4185 mono_thread_init_apartment_state (void)
4188 MonoInternalThread* thread = mono_thread_internal_current ();
4190 /* Positive return value indicates success, either
4191 * S_OK if this is first CoInitialize call, or
4192 * S_FALSE if CoInitialize already called, but with same
4193 * threading model. A negative value indicates failure,
4194 * probably due to trying to change the threading model.
4196 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4197 ? COINIT_APARTMENTTHREADED
4198 : COINIT_MULTITHREADED) < 0) {
4199 thread->apartment_state = ThreadApartmentState_Unknown;
4205 mono_thread_cleanup_apartment_state (void)
4208 MonoInternalThread* thread = mono_thread_internal_current ();
4210 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4217 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4219 ensure_synch_cs_set (thread);
4221 EnterCriticalSection (thread->synch_cs);
4222 thread->state |= state;
4223 LeaveCriticalSection (thread->synch_cs);
4227 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4229 ensure_synch_cs_set (thread);
4231 EnterCriticalSection (thread->synch_cs);
4232 thread->state &= ~state;
4233 LeaveCriticalSection (thread->synch_cs);
4237 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4239 gboolean ret = FALSE;
4241 ensure_synch_cs_set (thread);
4243 EnterCriticalSection (thread->synch_cs);
4245 if ((thread->state & test) != 0) {
4249 LeaveCriticalSection (thread->synch_cs);
4254 static MonoClassField *execution_context_field;
4257 get_execution_context_addr (void)
4259 MonoDomain *domain = mono_domain_get ();
4262 if (!execution_context_field) {
4263 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4265 g_assert (execution_context_field);
4268 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4270 mono_domain_lock (domain);
4271 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4272 mono_domain_unlock (domain);
4275 return (MonoObject**) mono_get_special_static_data (offset);
4279 mono_thread_get_execution_context (void)
4281 return *get_execution_context_addr ();
4285 mono_thread_set_execution_context (MonoObject *ec)
4287 *get_execution_context_addr () = ec;
4290 static gboolean has_tls_get = FALSE;
4293 mono_runtime_set_has_tls_get (gboolean val)
4299 mono_runtime_has_tls_get (void)
4305 mono_thread_kill (MonoInternalThread *thread, int signal)
4308 /* Win32 uses QueueUserAPC and callers of this are guarded */
4309 g_assert_not_reached ();
4311 # ifdef PTHREAD_POINTER_ID
4312 return pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
4314 # ifdef PLATFORM_ANDROID
4315 if (thread->android_tid != 0) {
4317 int old_errno = errno;
4319 ret = tkill ((pid_t) thread->android_tid, signal);
4328 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());
4330 return pthread_kill (thread->tid, mono_thread_get_abort_signal ());