2 * threads.c: Thread support internal calls
5 * Dick Porter (dick@ximian.com)
6 * Paolo Molaro (lupus@ximian.com)
7 * Patrik Torstensson (patrik.torstensson@labs2.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
19 #if defined(__OpenBSD__)
21 #include <pthread_np.h>
24 #include <mono/metadata/object.h>
25 #include <mono/metadata/domain-internals.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/threads.h>
28 #include <mono/metadata/threadpool.h>
29 #include <mono/metadata/threads-types.h>
30 #include <mono/metadata/exception.h>
31 #include <mono/metadata/environment.h>
32 #include <mono/metadata/monitor.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/marshal.h>
35 #include <mono/io-layer/io-layer.h>
37 #include <mono/io-layer/threads.h>
39 #include <mono/metadata/object-internals.h>
40 #include <mono/metadata/mono-debug-debugger.h>
41 #include <mono/utils/mono-compiler.h>
42 #include <mono/utils/mono-mmap.h>
43 #include <mono/utils/mono-membar.h>
44 #include <mono/utils/mono-time.h>
46 #include <mono/metadata/gc-internal.h>
48 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
49 #define THREAD_DEBUG(a)
50 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
51 #define THREAD_WAIT_DEBUG(a)
52 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
53 #define LIBGC_DEBUG(a)
55 /* Provide this for systems with glib < 2.6 */
56 #ifndef G_GSIZE_FORMAT
57 # if GLIB_SIZEOF_LONG == 8
58 # define G_GSIZE_FORMAT "lu"
60 # define G_GSIZE_FORMAT "u"
66 guint32 (*func)(void *);
82 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
83 struct _MonoThreadDomainTls {
84 MonoThreadDomainTls *next;
92 MonoThreadDomainTls *freelist;
97 MonoHazardousFreeFunc free_func;
100 /* Number of cached culture objects in the MonoThread->cached_culture_info array
101 * (per-type): we use the first NUM entries for CultureInfo and the last for
102 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
104 #define NUM_CACHED_CULTURES 4
105 #define CULTURES_START_IDX 0
106 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
108 /* Controls access to the 'threads' hash table */
109 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
110 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
111 static CRITICAL_SECTION threads_mutex;
113 /* Controls access to context static data */
114 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
115 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
116 static CRITICAL_SECTION contexts_mutex;
118 /* Holds current status of static data heap */
119 static StaticDataInfo thread_static_info;
120 static StaticDataInfo context_static_info;
122 /* The hash of existing threads (key is thread ID, value is
123 * MonoInternalThread*) that need joining before exit
125 static MonoGHashTable *threads=NULL;
128 * Threads which are starting up and they are not in the 'threads' hash yet.
129 * When handle_store is called for a thread, it will be removed from this hash table.
130 * Protected by mono_threads_lock ().
132 static MonoGHashTable *threads_starting_up = NULL;
134 /* Maps a MonoThread to its start argument */
135 /* Protected by mono_threads_lock () */
136 static MonoGHashTable *thread_start_args = NULL;
138 /* The TLS key that holds the MonoObject assigned to each thread */
139 static guint32 current_object_key = -1;
141 #ifdef HAVE_KW_THREAD
142 /* we need to use both the Tls* functions and __thread because
143 * the gc needs to see all the threads
145 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
146 #define SET_CURRENT_OBJECT(x) do { \
147 tls_current_object = x; \
148 TlsSetValue (current_object_key, x); \
150 #define GET_CURRENT_OBJECT() tls_current_object
152 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
153 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
156 /* function called at thread start */
157 static MonoThreadStartCB mono_thread_start_cb = NULL;
159 /* function called at thread attach */
160 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
162 /* function called at thread cleanup */
163 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
165 /* function called to notify the runtime about a pending exception on the current thread */
166 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
168 /* The default stack size for each thread */
169 static guint32 default_stacksize = 0;
170 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
172 static void thread_adjust_static_data (MonoInternalThread *thread);
173 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
174 static void mono_init_static_data_info (StaticDataInfo *static_data);
175 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
176 static gboolean mono_thread_resume (MonoInternalThread* thread);
177 static void mono_thread_start (MonoThread *thread);
178 static void signal_thread_state_change (MonoInternalThread *thread);
180 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
182 /* Spin lock for InterlockedXXX 64 bit functions */
183 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
184 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
185 static CRITICAL_SECTION interlocked_mutex;
187 /* global count of thread interruptions requested */
188 static gint32 thread_interruption_requested = 0;
190 /* Event signaled when a thread changes its background mode */
191 static HANDLE background_change_event;
193 /* The table for small ID assignment */
194 static CRITICAL_SECTION small_id_mutex;
195 static int small_id_table_size = 0;
196 static int small_id_next = 0;
197 static int highest_small_id = -1;
198 static MonoInternalThread **small_id_table = NULL;
200 /* The hazard table */
201 #if MONO_SMALL_CONFIG
202 #define HAZARD_TABLE_MAX_SIZE 256
204 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
206 static volatile int hazard_table_size = 0;
207 static MonoThreadHazardPointers * volatile hazard_table = NULL;
209 /* The table where we keep pointers to blocks to be freed but that
210 have to wait because they're guarded by a hazard pointer. */
211 static CRITICAL_SECTION delayed_free_table_mutex;
212 static GArray *delayed_free_table = NULL;
214 static gboolean shutting_down = FALSE;
217 mono_thread_get_tls_key (void)
219 return current_object_key;
223 mono_thread_get_tls_offset (void)
226 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
230 /* handle_store() and handle_remove() manage the array of threads that
231 * still need to be waited for when the main thread exits.
233 * If handle_store() returns FALSE the thread must not be started
234 * because Mono is shutting down.
236 static gboolean handle_store(MonoThread *thread)
238 mono_threads_lock ();
240 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
242 if (threads_starting_up)
243 mono_g_hash_table_remove (threads_starting_up, thread);
246 mono_threads_unlock ();
251 MONO_GC_REGISTER_ROOT (threads);
252 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
255 /* We don't need to duplicate thread->handle, because it is
256 * only closed when the thread object is finalized by the GC.
258 g_assert (thread->internal_thread);
259 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
260 thread->internal_thread);
262 mono_threads_unlock ();
267 static gboolean handle_remove(MonoInternalThread *thread)
270 gsize tid = thread->tid;
272 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
274 mono_threads_lock ();
277 /* We have to check whether the thread object for the
278 * tid is still the same in the table because the
279 * thread might have been destroyed and the tid reused
280 * in the meantime, in which case the tid would be in
281 * the table, but with another thread object.
283 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
284 mono_g_hash_table_remove (threads, (gpointer)tid);
293 mono_threads_unlock ();
295 /* Don't close the handle here, wait for the object finalizer
296 * to do it. Otherwise, the following race condition applies:
298 * 1) Thread exits (and handle_remove() closes the handle)
300 * 2) Some other handle is reassigned the same slot
302 * 3) Another thread tries to join the first thread, and
303 * blocks waiting for the reassigned handle to be signalled
304 * (which might never happen). This is possible, because the
305 * thread calling Join() still has a reference to the first
312 * Allocate a small thread id.
314 * FIXME: The biggest part of this function is very similar to
315 * domain_id_alloc() in domain.c and should be merged.
318 small_id_alloc (MonoInternalThread *thread)
322 EnterCriticalSection (&small_id_mutex);
324 if (!small_id_table) {
325 small_id_table_size = 2;
326 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
328 for (i = small_id_next; i < small_id_table_size; ++i) {
329 if (!small_id_table [i]) {
335 for (i = 0; i < small_id_next; ++i) {
336 if (!small_id_table [i]) {
343 MonoInternalThread **new_table;
344 int new_size = small_id_table_size * 2;
345 if (new_size >= (1 << 16))
346 g_assert_not_reached ();
347 id = small_id_table_size;
348 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
349 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
350 mono_gc_free_fixed (small_id_table);
351 small_id_table = new_table;
352 small_id_table_size = new_size;
354 thread->small_id = id;
355 g_assert (small_id_table [id] == NULL);
356 small_id_table [id] = thread;
358 if (small_id_next > small_id_table_size)
361 g_assert (id < HAZARD_TABLE_MAX_SIZE);
362 if (id >= hazard_table_size) {
363 #if MONO_SMALL_CONFIG
364 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
365 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
368 int pagesize = mono_pagesize ();
369 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
371 if (hazard_table == NULL) {
372 hazard_table = mono_valloc (NULL,
373 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
377 g_assert (hazard_table != NULL);
378 page_addr = (guint8*)hazard_table + num_pages * pagesize;
380 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
383 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
386 g_assert (id < hazard_table_size);
387 hazard_table [id].hazard_pointers [0] = NULL;
388 hazard_table [id].hazard_pointers [1] = NULL;
391 if (id > highest_small_id) {
392 highest_small_id = id;
393 mono_memory_write_barrier ();
396 LeaveCriticalSection (&small_id_mutex);
402 small_id_free (int id)
404 g_assert (id >= 0 && id < small_id_table_size);
405 g_assert (small_id_table [id] != NULL);
407 small_id_table [id] = NULL;
411 is_pointer_hazardous (gpointer p)
414 int highest = highest_small_id;
416 g_assert (highest < hazard_table_size);
418 for (i = 0; i <= highest; ++i) {
419 if (hazard_table [i].hazard_pointers [0] == p
420 || hazard_table [i].hazard_pointers [1] == p)
427 MonoThreadHazardPointers*
428 mono_hazard_pointer_get (void)
430 MonoInternalThread *current_thread = mono_thread_internal_current ();
432 if (!(current_thread && current_thread->small_id >= 0)) {
433 static MonoThreadHazardPointers emerg_hazard_table;
434 g_warning ("Thread %p may have been prematurely finalized", current_thread);
435 return &emerg_hazard_table;
438 return &hazard_table [current_thread->small_id];
442 try_free_delayed_free_item (int index)
444 if (delayed_free_table->len > index) {
445 DelayedFreeItem item = { NULL, NULL };
447 EnterCriticalSection (&delayed_free_table_mutex);
448 /* We have to check the length again because another
449 thread might have freed an item before we acquired
451 if (delayed_free_table->len > index) {
452 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
454 if (!is_pointer_hazardous (item.p))
455 g_array_remove_index_fast (delayed_free_table, index);
459 LeaveCriticalSection (&delayed_free_table_mutex);
462 item.free_func (item.p);
467 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
471 /* First try to free a few entries in the delayed free
473 for (i = 2; i >= 0; --i)
474 try_free_delayed_free_item (i);
476 /* Now see if the pointer we're freeing is hazardous. If it
477 isn't, free it. Otherwise put it in the delay list. */
478 if (is_pointer_hazardous (p)) {
479 DelayedFreeItem item = { p, free_func };
481 ++mono_stats.hazardous_pointer_count;
483 EnterCriticalSection (&delayed_free_table_mutex);
484 g_array_append_val (delayed_free_table, item);
485 LeaveCriticalSection (&delayed_free_table_mutex);
491 mono_thread_hazardous_try_free_all (void)
496 if (!delayed_free_table)
499 len = delayed_free_table->len;
501 for (i = len - 1; i >= 0; --i)
502 try_free_delayed_free_item (i);
505 static void ensure_synch_cs_set (MonoInternalThread *thread)
507 CRITICAL_SECTION *synch_cs;
509 if (thread->synch_cs != NULL) {
513 synch_cs = g_new0 (CRITICAL_SECTION, 1);
514 InitializeCriticalSection (synch_cs);
516 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
517 synch_cs, NULL) != NULL) {
518 /* Another thread must have installed this CS */
519 DeleteCriticalSection (synch_cs);
525 * NOTE: this function can be called also for threads different from the current one:
526 * make sure no code called from it will ever assume it is run on the thread that is
527 * getting cleaned up.
529 static void thread_cleanup (MonoInternalThread *thread)
531 g_assert (thread != NULL);
533 if (thread->abort_state_handle) {
534 mono_gchandle_free (thread->abort_state_handle);
535 thread->abort_state_handle = 0;
537 thread->abort_exc = NULL;
538 thread->current_appcontext = NULL;
541 * This is necessary because otherwise we might have
542 * cross-domain references which will not get cleaned up when
543 * the target domain is unloaded.
545 if (thread->cached_culture_info) {
547 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
548 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
551 /* if the thread is not in the hash it has been removed already */
552 if (!handle_remove (thread))
554 mono_release_type_locks (thread);
556 EnterCriticalSection (thread->synch_cs);
558 thread->state |= ThreadState_Stopped;
559 thread->state &= ~ThreadState_Background;
561 LeaveCriticalSection (thread->synch_cs);
563 mono_profiler_thread_end (thread->tid);
565 if (thread == mono_thread_internal_current ())
566 mono_thread_pop_appdomain_ref ();
568 thread->cached_culture_info = NULL;
570 mono_free_static_data (thread->static_data, TRUE);
571 thread->static_data = NULL;
574 * FIXME: The check for shutting_down here is a kludge and
575 * should be removed. The reason we need it here is because
576 * mono_thread_manage() does not wait for finalizer threads,
577 * so we might still be at this point in a finalizer thread
578 * after the main thread has cleared the root domain, so
579 * thread could have been zeroed out.
581 if (mono_thread_cleanup_fn && !shutting_down)
582 mono_thread_cleanup_fn (thread->root_domain_thread);
584 small_id_free (thread->small_id);
585 thread->small_id = -2;
589 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
592 g_assert ((offset & 0x80000000) == 0);
593 offset &= 0x7fffffff;
594 idx = (offset >> 24) - 1;
595 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
599 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
601 static MonoClassField *current_thread_field = NULL;
605 if (!current_thread_field) {
606 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
607 g_assert (current_thread_field);
610 mono_class_vtable (domain, mono_defaults.thread_class);
611 mono_domain_lock (domain);
612 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
613 mono_domain_unlock (domain);
616 return get_thread_static_data (thread, offset);
620 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
622 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
624 g_assert (current->obj.vtable->domain == domain);
626 g_assert (!*current_thread_ptr);
627 *current_thread_ptr = current;
631 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
633 MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
634 MONO_OBJECT_SETREF (thread, internal_thread, internal);
639 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
641 MonoDomain *domain = mono_get_root_domain ();
643 if (!candidate || candidate->obj.vtable->domain != domain)
644 candidate = new_thread_with_internal (domain, thread);
645 set_current_thread_for_domain (domain, thread, candidate);
646 g_assert (!thread->root_domain_thread);
647 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
650 static guint32 WINAPI start_wrapper(void *data)
652 struct StartInfo *start_info=(struct StartInfo *)data;
653 guint32 (*start_func)(void *);
656 MonoThread *thread=start_info->obj;
657 MonoInternalThread *internal = thread->internal_thread;
658 MonoObject *start_delegate = start_info->delegate;
660 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
662 /* We can be sure start_info->obj->tid and
663 * start_info->obj->handle have been set, because the thread
664 * was created suspended, and these values were set before the
670 SET_CURRENT_OBJECT (internal);
672 mono_monitor_init_tls ();
674 /* Every thread references the appdomain which created it */
675 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
677 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
678 /* No point in raising an appdomain_unloaded exception here */
679 /* FIXME: Cleanup here */
680 mono_thread_pop_appdomain_ref ();
684 start_func = start_info->func;
685 start_arg = start_info->start_arg;
687 /* We have to do this here because mono_thread_new_init()
688 requires that root_domain_thread is set up. */
689 thread_adjust_static_data (internal);
690 init_root_domain_thread (internal, thread);
692 /* This MUST be called before any managed code can be
693 * executed, as it calls the callback function that (for the
694 * jit) sets the lmf marker.
696 mono_thread_new_init (tid, &tid, start_func);
697 internal->stack_ptr = &tid;
699 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
701 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
703 /* On 2.0 profile (and higher), set explicitly since state might have been
705 if (internal->apartment_state == ThreadApartmentState_Unknown)
706 internal->apartment_state = ThreadApartmentState_MTA;
708 mono_thread_init_apartment_state ();
710 if(internal->start_notify!=NULL) {
711 /* Let the thread that called Start() know we're
714 ReleaseSemaphore (internal->start_notify, 1, NULL);
717 mono_threads_lock ();
718 mono_g_hash_table_remove (thread_start_args, thread);
719 mono_threads_unlock ();
723 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
727 mono_thread_set_execution_context (thread->ec_to_set);
728 thread->ec_to_set = NULL;
731 * Call this after calling start_notify, since the profiler callback might want
732 * to lock the thread, and the lock is held by thread_start () which waits for
735 mono_profiler_thread_start (tid);
737 /* start_func is set only for unmanaged start functions */
739 start_func (start_arg);
742 g_assert (start_delegate != NULL);
743 args [0] = start_arg;
744 /* we may want to handle the exception here. See comment below on unhandled exceptions */
745 mono_runtime_delegate_invoke (start_delegate, args, NULL);
748 /* If the thread calls ExitThread at all, this remaining code
749 * will not be executed, but the main thread will eventually
750 * call thread_cleanup() on this thread's behalf.
753 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
755 thread_cleanup (internal);
757 /* Do any cleanup needed for apartment state. This
758 * cannot be done in thread_cleanup since thread_cleanup could be
759 * called for a thread other than the current thread.
760 * mono_thread_cleanup_apartment_state cleans up apartment
761 * for the current thead */
762 mono_thread_cleanup_apartment_state ();
764 /* Remove the reference to the thread object in the TLS data,
765 * so the thread object can be finalized. This won't be
766 * reached if the thread threw an uncaught exception, so those
767 * thread handles will stay referenced :-( (This is due to
768 * missing support for scanning thread-specific data in the
769 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
772 SET_CURRENT_OBJECT (NULL);
773 mono_domain_unset ();
778 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
780 if (mono_thread_start_cb) {
781 mono_thread_start_cb (tid, stack_start, func);
785 void mono_threads_set_default_stacksize (guint32 stacksize)
787 default_stacksize = stacksize;
790 guint32 mono_threads_get_default_stacksize (void)
792 return default_stacksize;
796 * mono_create_thread:
798 * This is a wrapper around CreateThread which handles differences in the type of
799 * the the 'tid' argument.
801 gpointer mono_create_thread (WapiSecurityAttributes *security,
802 guint32 stacksize, WapiThreadStart start,
803 gpointer param, guint32 create, gsize *tid)
810 res = CreateThread (security, stacksize, start, param, create, &real_tid);
814 res = CreateThread (security, stacksize, start, param, create, tid);
821 * The thread start argument may be an object reference, and there is
822 * no ref to keep it alive when the new thread is started but not yet
823 * registered with the collector. So we store it in a GC tracked hash
826 * LOCKING: Assumes the threads lock is held.
829 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
831 if (thread_start_args == NULL) {
832 MONO_GC_REGISTER_ROOT (thread_start_args);
833 thread_start_args = mono_g_hash_table_new (NULL, NULL);
835 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
838 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
841 MonoInternalThread *internal;
842 HANDLE thread_handle;
843 struct StartInfo *start_info;
846 thread=(MonoThread *)mono_object_new (domain,
847 mono_defaults.thread_class);
848 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
849 mono_defaults.internal_thread_class);
850 MONO_OBJECT_SETREF (thread, internal_thread, internal);
852 start_info=g_new0 (struct StartInfo, 1);
853 start_info->func = func;
854 start_info->obj = thread;
855 start_info->start_arg = arg;
857 mono_threads_lock ();
859 mono_threads_unlock ();
863 if (threads_starting_up == NULL) {
864 MONO_GC_REGISTER_ROOT (threads_starting_up);
865 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
868 register_thread_start_argument (thread, start_info);
869 mono_g_hash_table_insert (threads_starting_up, thread, thread);
870 mono_threads_unlock ();
872 /* Create suspended, so we can do some housekeeping before the thread
875 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
876 CREATE_SUSPENDED, &tid);
877 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
878 if (thread_handle == NULL) {
879 /* The thread couldn't be created, so throw an exception */
880 mono_threads_lock ();
881 mono_g_hash_table_remove (threads_starting_up, thread);
882 mono_threads_unlock ();
884 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
888 internal->handle=thread_handle;
890 internal->apartment_state=ThreadApartmentState_Unknown;
891 small_id_alloc (internal);
893 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
894 InitializeCriticalSection (internal->synch_cs);
896 internal->threadpool_thread = threadpool_thread;
897 if (threadpool_thread)
898 mono_thread_set_state (internal, ThreadState_Background);
900 if (handle_store (thread))
901 ResumeThread (thread_handle);
907 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
909 mono_thread_create_internal (domain, func, arg, FALSE);
913 * mono_thread_get_stack_bounds:
915 * Return the address and size of the current threads stack. Return NULL as the
916 * stack address if the stack address cannot be determined.
919 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
921 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
922 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
923 *stsize = pthread_get_stacksize_np (pthread_self ());
924 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
926 /* FIXME: simplify the mess below */
927 #elif !defined(HOST_WIN32)
929 guint8 *current = (guint8*)&attr;
931 pthread_attr_init (&attr);
932 # ifdef HAVE_PTHREAD_GETATTR_NP
933 pthread_getattr_np (pthread_self(), &attr);
935 # ifdef HAVE_PTHREAD_ATTR_GET_NP
936 pthread_attr_get_np (pthread_self(), &attr);
939 pthread_attr_getstacksize (&attr, &stsize);
940 # elif defined(__OpenBSD__)
944 rslt = pthread_stackseg_np(pthread_self(), &ss);
945 g_assert (rslt == 0);
947 *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
948 *stsize = ss.ss_size;
957 # if !defined(__OpenBSD__)
958 pthread_attr_getstack (&attr, (void**)staddr, stsize);
961 g_assert ((current > *staddr) && (current < *staddr + *stsize));
964 pthread_attr_destroy (&attr);
967 /* When running under emacs, sometimes staddr is not aligned to a page size */
968 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
972 mono_thread_attach (MonoDomain *domain)
974 MonoInternalThread *thread;
975 MonoThread *current_thread;
976 HANDLE thread_handle;
979 if ((thread = mono_thread_internal_current ())) {
980 if (domain != mono_domain_get ())
981 mono_domain_set (domain, TRUE);
982 /* Already attached */
983 return mono_thread_current ();
986 if (!mono_gc_register_thread (&domain)) {
987 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 ());
990 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
992 thread_handle = GetCurrentThread ();
993 g_assert (thread_handle);
995 tid=GetCurrentThreadId ();
998 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
999 * refer to the thread from other threads for things like aborting.
1001 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
1002 THREAD_ALL_ACCESS, TRUE, 0);
1004 thread->handle=thread_handle;
1006 thread->apartment_state=ThreadApartmentState_Unknown;
1007 small_id_alloc (thread);
1008 thread->stack_ptr = &tid;
1010 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
1011 InitializeCriticalSection (thread->synch_cs);
1013 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
1015 current_thread = new_thread_with_internal (domain, thread);
1017 if (!handle_store (current_thread)) {
1018 /* Mono is shutting down, so just wait for the end */
1023 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1025 SET_CURRENT_OBJECT (thread);
1026 mono_domain_set (domain, TRUE);
1028 mono_monitor_init_tls ();
1030 thread_adjust_static_data (thread);
1032 init_root_domain_thread (thread, current_thread);
1033 if (domain != mono_get_root_domain ())
1034 set_current_thread_for_domain (domain, thread, current_thread);
1037 if (mono_thread_attach_cb) {
1041 mono_thread_get_stack_bounds (&staddr, &stsize);
1044 mono_thread_attach_cb (tid, &tid);
1046 mono_thread_attach_cb (tid, staddr + stsize);
1049 // FIXME: Need a separate callback
1050 mono_profiler_thread_start (tid);
1052 return current_thread;
1056 mono_thread_detach (MonoThread *thread)
1058 g_return_if_fail (thread != NULL);
1060 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1062 thread_cleanup (thread->internal_thread);
1064 SET_CURRENT_OBJECT (NULL);
1065 mono_domain_unset ();
1067 /* Don't need to CloseHandle this thread, even though we took a
1068 * reference in mono_thread_attach (), because the GC will do it
1069 * when the Thread object is finalised.
1076 MonoInternalThread *thread = mono_thread_internal_current ();
1078 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1080 thread_cleanup (thread);
1081 SET_CURRENT_OBJECT (NULL);
1082 mono_domain_unset ();
1084 /* we could add a callback here for embedders to use. */
1085 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1086 exit (mono_environment_exitcode_get ());
1091 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1093 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1094 internal->state = ThreadState_Unstarted;
1095 internal->apartment_state = ThreadApartmentState_Unknown;
1097 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1100 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1103 guint32 (*start_func)(void *);
1104 struct StartInfo *start_info;
1107 MonoInternalThread *internal;
1109 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1111 if (!this->internal_thread)
1112 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1113 internal = this->internal_thread;
1115 ensure_synch_cs_set (internal);
1117 EnterCriticalSection (internal->synch_cs);
1119 if ((internal->state & ThreadState_Unstarted) == 0) {
1120 LeaveCriticalSection (internal->synch_cs);
1121 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1125 internal->small_id = -1;
1127 if ((internal->state & ThreadState_Aborted) != 0) {
1128 LeaveCriticalSection (internal->synch_cs);
1133 /* This is freed in start_wrapper */
1134 start_info = g_new0 (struct StartInfo, 1);
1135 start_info->func = start_func;
1136 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1137 start_info->delegate = start;
1138 start_info->obj = this;
1139 g_assert (this->obj.vtable->domain == mono_domain_get ());
1141 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1142 if (internal->start_notify==NULL) {
1143 LeaveCriticalSection (internal->synch_cs);
1144 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1145 g_free (start_info);
1149 mono_threads_lock ();
1150 register_thread_start_argument (this, start_info);
1151 if (threads_starting_up == NULL) {
1152 MONO_GC_REGISTER_ROOT (threads_starting_up);
1153 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1155 mono_g_hash_table_insert (threads_starting_up, this, this);
1156 mono_threads_unlock ();
1158 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1159 CREATE_SUSPENDED, &tid);
1161 LeaveCriticalSection (internal->synch_cs);
1162 mono_threads_lock ();
1163 mono_g_hash_table_remove (threads_starting_up, this);
1164 mono_threads_unlock ();
1165 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1169 internal->handle=thread;
1171 small_id_alloc (internal);
1173 /* Don't call handle_store() here, delay it to Start.
1174 * We can't join a thread (trying to will just block
1175 * forever) until it actually starts running, so don't
1176 * store the handle till then.
1179 mono_thread_start (this);
1181 internal->state &= ~ThreadState_Unstarted;
1183 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1185 LeaveCriticalSection (internal->synch_cs);
1190 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1192 MONO_ARCH_SAVE_REGS;
1194 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1197 CloseHandle (thread);
1199 if (this->synch_cs) {
1200 DeleteCriticalSection (this->synch_cs);
1201 g_free (this->synch_cs);
1202 this->synch_cs = NULL;
1205 g_free (this->name);
1208 static void mono_thread_start (MonoThread *thread)
1210 MonoInternalThread *internal = thread->internal_thread;
1212 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1214 /* Only store the handle when the thread is about to be
1215 * launched, to avoid the main thread deadlocking while trying
1216 * to clean up a thread that will never be signalled.
1218 if (!handle_store (thread))
1221 ResumeThread (internal->handle);
1223 if(internal->start_notify!=NULL) {
1224 /* Wait for the thread to set up its TLS data etc, so
1225 * theres no potential race condition if someone tries
1226 * to look up the data believing the thread has
1230 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1232 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1233 CloseHandle (internal->start_notify);
1234 internal->start_notify = NULL;
1237 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1240 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1243 MonoInternalThread *thread = mono_thread_internal_current ();
1245 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1247 mono_thread_current_check_pending_interrupt ();
1249 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1251 res = SleepEx(ms,TRUE);
1253 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1255 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1256 MonoException* exc = mono_thread_execute_interruption (thread);
1257 if (exc) mono_raise_exception (exc);
1261 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1266 ves_icall_System_Threading_Thread_GetDomainID (void)
1268 MONO_ARCH_SAVE_REGS;
1270 return mono_domain_get()->domain_id;
1274 * mono_thread_get_name:
1276 * Return the name of the thread. NAME_LEN is set to the length of the name.
1277 * Return NULL if the thread has no name. The returned memory is owned by the
1281 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1285 ensure_synch_cs_set (this_obj);
1287 EnterCriticalSection (this_obj->synch_cs);
1289 if (!this_obj->name) {
1293 *name_len = this_obj->name_len;
1294 res = g_new (gunichar2, this_obj->name_len);
1295 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1298 LeaveCriticalSection (this_obj->synch_cs);
1304 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1308 ensure_synch_cs_set (this_obj);
1310 EnterCriticalSection (this_obj->synch_cs);
1312 if (!this_obj->name)
1315 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1317 LeaveCriticalSection (this_obj->synch_cs);
1323 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1325 ensure_synch_cs_set (this_obj);
1327 EnterCriticalSection (this_obj->synch_cs);
1329 if (this_obj->name) {
1330 LeaveCriticalSection (this_obj->synch_cs);
1332 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1336 this_obj->name = g_new (gunichar2, mono_string_length (name));
1337 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1338 this_obj->name_len = mono_string_length (name);
1341 this_obj->name = NULL;
1343 LeaveCriticalSection (this_obj->synch_cs);
1347 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1352 if (this->cached_culture_info) {
1353 domain = mono_domain_get ();
1354 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1355 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1356 if (res && res->vtable->domain == domain)
1364 /* If the array is already in the requested domain, we just return it,
1365 otherwise we return a copy in that domain. */
1367 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1374 if (mono_object_domain (arr) == domain)
1377 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1378 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1383 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1385 return byte_array_to_domain (arr, mono_get_root_domain ());
1389 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1391 return byte_array_to_domain (arr, mono_domain_get ());
1395 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1397 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1401 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1404 MonoDomain *domain = mono_domain_get ();
1407 int same_domain_slot = -1;
1409 ensure_synch_cs_set (this);
1411 EnterCriticalSection (this->synch_cs);
1413 if (!this->cached_culture_info)
1414 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1416 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1417 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1421 /* we continue, because there may be a slot used with the same domain */
1425 if (obj->vtable->domain == domain) {
1426 same_domain_slot = i;
1430 if (same_domain_slot >= 0)
1431 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1432 else if (free_slot >= 0)
1433 mono_array_setref (this->cached_culture_info, free_slot, culture);
1434 /* we may want to replace an existing entry here, even when no suitable slot is found */
1436 LeaveCriticalSection (this->synch_cs);
1440 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1442 MonoDomain *domain = mono_object_get_domain (&this->obj);
1443 g_assert (domain == mono_domain_get ());
1444 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1448 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1450 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1454 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1456 MonoDomain *domain = mono_object_get_domain (&this->obj);
1457 g_assert (domain == mono_domain_get ());
1458 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1462 mono_thread_current (void)
1464 MonoDomain *domain = mono_domain_get ();
1465 MonoInternalThread *internal = mono_thread_internal_current ();
1466 MonoThread **current_thread_ptr;
1468 g_assert (internal);
1469 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1471 if (!*current_thread_ptr) {
1472 g_assert (domain != mono_get_root_domain ());
1473 *current_thread_ptr = new_thread_with_internal (domain, internal);
1475 return *current_thread_ptr;
1479 mono_thread_internal_current (void)
1481 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1482 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1486 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1487 int ms, HANDLE thread)
1489 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1492 mono_thread_current_check_pending_interrupt ();
1494 ensure_synch_cs_set (this);
1496 EnterCriticalSection (this->synch_cs);
1498 if ((this->state & ThreadState_Unstarted) != 0) {
1499 LeaveCriticalSection (this->synch_cs);
1501 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1505 LeaveCriticalSection (this->synch_cs);
1510 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1512 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1514 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1516 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1518 if(ret==WAIT_OBJECT_0) {
1519 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1524 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1529 /* FIXME: exitContext isnt documented */
1530 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1536 MonoObject *waitHandle;
1537 MonoInternalThread *thread = mono_thread_internal_current ();
1539 /* Do this WaitSleepJoin check before creating objects */
1540 mono_thread_current_check_pending_interrupt ();
1542 numhandles = mono_array_length(mono_handles);
1543 handles = g_new0(HANDLE, numhandles);
1545 for(i = 0; i < numhandles; i++) {
1546 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1547 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1554 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1556 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1558 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1562 if(ret==WAIT_FAILED) {
1563 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1565 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1566 /* Do we want to try again if we get
1567 * WAIT_IO_COMPLETION? The documentation for
1568 * WaitHandle doesn't give any clues. (We'd have to
1569 * fiddle with the timeout if we retry.)
1571 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1578 /* FIXME: exitContext isnt documented */
1579 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1585 MonoObject *waitHandle;
1586 MonoInternalThread *thread = mono_thread_internal_current ();
1588 /* Do this WaitSleepJoin check before creating objects */
1589 mono_thread_current_check_pending_interrupt ();
1591 numhandles = mono_array_length(mono_handles);
1592 handles = g_new0(HANDLE, numhandles);
1594 for(i = 0; i < numhandles; i++) {
1595 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1596 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1603 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1605 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1607 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1611 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1614 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1616 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1617 return ret - WAIT_OBJECT_0;
1619 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1620 return ret - WAIT_ABANDONED_0;
1627 /* FIXME: exitContext isnt documented */
1628 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1631 MonoInternalThread *thread = mono_thread_internal_current ();
1633 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1639 mono_thread_current_check_pending_interrupt ();
1641 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1643 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1645 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1647 if(ret==WAIT_FAILED) {
1648 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1650 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1651 /* Do we want to try again if we get
1652 * WAIT_IO_COMPLETION? The documentation for
1653 * WaitHandle doesn't give any clues. (We'd have to
1654 * fiddle with the timeout if we retry.)
1656 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1664 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1667 MonoInternalThread *thread = mono_thread_internal_current ();
1669 MONO_ARCH_SAVE_REGS;
1674 mono_thread_current_check_pending_interrupt ();
1676 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1678 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1680 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1682 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1685 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1689 MONO_ARCH_SAVE_REGS;
1694 mutex = CreateMutex (NULL, owned, NULL);
1696 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1698 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1706 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1707 MONO_ARCH_SAVE_REGS;
1709 return(ReleaseMutex (handle));
1712 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1718 MONO_ARCH_SAVE_REGS;
1720 *error = ERROR_SUCCESS;
1722 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1724 *error = GetLastError ();
1731 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1735 MONO_ARCH_SAVE_REGS;
1740 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1742 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1743 mono_string_chars (name));
1745 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1753 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1757 MONO_ARCH_SAVE_REGS;
1759 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1764 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1768 MONO_ARCH_SAVE_REGS;
1770 *error = ERROR_SUCCESS;
1772 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1774 *error = GetLastError ();
1780 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1784 MONO_ARCH_SAVE_REGS;
1789 event = CreateEvent (NULL, manual, initial, NULL);
1791 event = CreateEvent (NULL, manual, initial,
1792 mono_string_chars (name));
1794 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1802 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1803 MONO_ARCH_SAVE_REGS;
1805 return (SetEvent(handle));
1808 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1809 MONO_ARCH_SAVE_REGS;
1811 return (ResetEvent(handle));
1815 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1816 MONO_ARCH_SAVE_REGS;
1818 CloseHandle (handle);
1821 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1827 MONO_ARCH_SAVE_REGS;
1829 *error = ERROR_SUCCESS;
1831 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1833 *error = GetLastError ();
1839 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1841 MONO_ARCH_SAVE_REGS;
1843 return InterlockedIncrement (location);
1846 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1850 MONO_ARCH_SAVE_REGS;
1852 mono_interlocked_lock ();
1856 mono_interlocked_unlock ();
1862 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1864 MONO_ARCH_SAVE_REGS;
1866 return InterlockedDecrement(location);
1869 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1873 MONO_ARCH_SAVE_REGS;
1875 mono_interlocked_lock ();
1879 mono_interlocked_unlock ();
1884 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1886 MONO_ARCH_SAVE_REGS;
1888 return InterlockedExchange(location, value);
1891 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1894 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1895 mono_gc_wbarrier_generic_nostore (location);
1899 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1901 return InterlockedExchangePointer(location, value);
1904 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1906 IntFloatUnion val, ret;
1908 MONO_ARCH_SAVE_REGS;
1911 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1917 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1919 #if SIZEOF_VOID_P == 8
1920 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1925 * According to MSDN, this function is only atomic with regards to the
1926 * other Interlocked functions on 32 bit platforms.
1928 mono_interlocked_lock ();
1931 mono_interlocked_unlock ();
1938 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1940 #if SIZEOF_VOID_P == 8
1941 LongDoubleUnion val, ret;
1944 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1951 * According to MSDN, this function is only atomic with regards to the
1952 * other Interlocked functions on 32 bit platforms.
1954 mono_interlocked_lock ();
1957 mono_interlocked_unlock ();
1963 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1965 MONO_ARCH_SAVE_REGS;
1967 return InterlockedCompareExchange(location, value, comparand);
1970 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1973 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1974 mono_gc_wbarrier_generic_nostore (location);
1978 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1980 return InterlockedCompareExchangePointer(location, value, comparand);
1983 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1985 IntFloatUnion val, ret, cmp;
1987 MONO_ARCH_SAVE_REGS;
1990 cmp.fval = comparand;
1991 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1997 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1999 #if SIZEOF_VOID_P == 8
2000 LongDoubleUnion val, comp, ret;
2003 comp.fval = comparand;
2004 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
2010 mono_interlocked_lock ();
2012 if (old == comparand)
2014 mono_interlocked_unlock ();
2021 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2023 #if SIZEOF_VOID_P == 8
2024 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2028 mono_interlocked_lock ();
2030 if (old == comparand)
2032 mono_interlocked_unlock ();
2039 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2042 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2043 mono_gc_wbarrier_generic_nostore (location);
2048 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2051 res = InterlockedExchangePointer ((gpointer *)location, value);
2052 mono_gc_wbarrier_generic_nostore (location);
2057 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2059 #if SIZEOF_VOID_P == 8
2060 /* Should be implemented as a JIT intrinsic */
2061 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2066 mono_interlocked_lock ();
2068 *location = orig + value;
2069 mono_interlocked_unlock ();
2071 return orig + value;
2076 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2078 #if SIZEOF_VOID_P == 8
2079 /* Should be implemented as a JIT intrinsic */
2080 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2085 mono_interlocked_lock ();
2087 *location = orig + value;
2088 mono_interlocked_unlock ();
2090 return orig + value;
2095 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2097 #if SIZEOF_VOID_P == 8
2098 /* 64 bit reads are already atomic */
2103 mono_interlocked_lock ();
2105 mono_interlocked_unlock ();
2112 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2114 mono_threads_lock ();
2115 mono_threads_unlock ();
2119 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2121 mono_thread_clr_state (this, state);
2123 if (state & ThreadState_Background) {
2124 /* If the thread changes the background mode, the main thread has to
2125 * be notified, since it has to rebuild the list of threads to
2128 SetEvent (background_change_event);
2133 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2135 mono_thread_set_state (this, state);
2137 if (state & ThreadState_Background) {
2138 /* If the thread changes the background mode, the main thread has to
2139 * be notified, since it has to rebuild the list of threads to
2142 SetEvent (background_change_event);
2147 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2151 ensure_synch_cs_set (this);
2153 EnterCriticalSection (this->synch_cs);
2155 state = this->state;
2157 LeaveCriticalSection (this->synch_cs);
2162 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2164 gboolean throw = FALSE;
2166 ensure_synch_cs_set (this);
2168 if (this == mono_thread_internal_current ())
2171 EnterCriticalSection (this->synch_cs);
2173 this->thread_interrupt_requested = TRUE;
2175 if (this->state & ThreadState_WaitSleepJoin) {
2179 LeaveCriticalSection (this->synch_cs);
2182 signal_thread_state_change (this);
2186 void mono_thread_current_check_pending_interrupt ()
2188 MonoInternalThread *thread = mono_thread_internal_current ();
2189 gboolean throw = FALSE;
2191 mono_debugger_check_interruption ();
2193 ensure_synch_cs_set (thread);
2195 EnterCriticalSection (thread->synch_cs);
2197 if (thread->thread_interrupt_requested) {
2199 thread->thread_interrupt_requested = FALSE;
2202 LeaveCriticalSection (thread->synch_cs);
2205 mono_raise_exception (mono_get_exception_thread_interrupted ());
2210 mono_thread_get_abort_signal (void)
2222 static int abort_signum = -1;
2224 if (abort_signum != -1)
2225 return abort_signum;
2226 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2227 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2228 struct sigaction sinfo;
2229 sigaction (i, NULL, &sinfo);
2230 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2235 /* fallback to the old way */
2238 #endif /* HOST_WIN32 */
2242 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2244 MonoException* exc = mono_thread_request_interruption (FALSE);
2245 if (exc) mono_raise_exception (exc);
2247 #endif /* HOST_WIN32 */
2250 * signal_thread_state_change
2252 * Tells the thread that his state has changed and it has to enter the new
2253 * state as soon as possible.
2255 static void signal_thread_state_change (MonoInternalThread *thread)
2257 if (thread == mono_thread_internal_current ()) {
2258 /* Do it synchronously */
2259 MonoException *exc = mono_thread_request_interruption (FALSE);
2261 mono_raise_exception (exc);
2265 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2267 /* fixme: store the state somewhere */
2268 #ifdef PTHREAD_POINTER_ID
2269 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2271 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2275 * This will cause waits to be broken.
2276 * It will also prevent the thread from entering a wait, so if the thread returns
2277 * from the wait before it receives the abort signal, it will just spin in the wait
2278 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2281 wapi_interrupt_thread (thread->handle);
2282 #endif /* HOST_WIN32 */
2286 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2288 ensure_synch_cs_set (thread);
2290 EnterCriticalSection (thread->synch_cs);
2292 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2293 (thread->state & ThreadState_StopRequested) != 0 ||
2294 (thread->state & ThreadState_Stopped) != 0)
2296 LeaveCriticalSection (thread->synch_cs);
2300 if ((thread->state & ThreadState_Unstarted) != 0) {
2301 thread->state |= ThreadState_Aborted;
2302 LeaveCriticalSection (thread->synch_cs);
2306 thread->state |= ThreadState_AbortRequested;
2307 if (thread->abort_state_handle)
2308 mono_gchandle_free (thread->abort_state_handle);
2310 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2311 g_assert (thread->abort_state_handle);
2313 thread->abort_state_handle = 0;
2315 thread->abort_exc = NULL;
2318 * abort_exc is set in mono_thread_execute_interruption(),
2319 * triggered by the call to signal_thread_state_change(),
2320 * below. There's a point between where we have
2321 * abort_state_handle set, but abort_exc NULL, but that's not
2325 LeaveCriticalSection (thread->synch_cs);
2327 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2329 /* During shutdown, we can't wait for other threads */
2331 /* Make sure the thread is awake */
2332 mono_thread_resume (thread);
2334 signal_thread_state_change (thread);
2338 ves_icall_System_Threading_Thread_ResetAbort (void)
2340 MonoInternalThread *thread = mono_thread_internal_current ();
2341 gboolean was_aborting;
2343 ensure_synch_cs_set (thread);
2345 EnterCriticalSection (thread->synch_cs);
2346 was_aborting = thread->state & ThreadState_AbortRequested;
2347 thread->state &= ~ThreadState_AbortRequested;
2348 LeaveCriticalSection (thread->synch_cs);
2350 if (!was_aborting) {
2351 const char *msg = "Unable to reset abort because no abort was requested";
2352 mono_raise_exception (mono_get_exception_thread_state (msg));
2354 thread->abort_exc = NULL;
2355 if (thread->abort_state_handle) {
2356 mono_gchandle_free (thread->abort_state_handle);
2357 /* This is actually not necessary - the handle
2358 only counts if the exception is set */
2359 thread->abort_state_handle = 0;
2364 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2366 ensure_synch_cs_set (thread);
2368 EnterCriticalSection (thread->synch_cs);
2370 thread->state &= ~ThreadState_AbortRequested;
2372 if (thread->abort_exc) {
2373 thread->abort_exc = NULL;
2374 if (thread->abort_state_handle) {
2375 mono_gchandle_free (thread->abort_state_handle);
2376 /* This is actually not necessary - the handle
2377 only counts if the exception is set */
2378 thread->abort_state_handle = 0;
2382 LeaveCriticalSection (thread->synch_cs);
2386 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2388 MonoInternalThread *thread = this->internal_thread;
2389 MonoObject *state, *deserialized = NULL, *exc;
2392 if (!thread->abort_state_handle)
2395 state = mono_gchandle_get_target (thread->abort_state_handle);
2398 domain = mono_domain_get ();
2399 if (mono_object_domain (state) == domain)
2402 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2404 if (!deserialized) {
2405 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2407 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2408 mono_raise_exception (invalid_op_exc);
2411 return deserialized;
2415 mono_thread_suspend (MonoInternalThread *thread)
2417 ensure_synch_cs_set (thread);
2419 EnterCriticalSection (thread->synch_cs);
2421 if ((thread->state & ThreadState_Unstarted) != 0 ||
2422 (thread->state & ThreadState_Aborted) != 0 ||
2423 (thread->state & ThreadState_Stopped) != 0)
2425 LeaveCriticalSection (thread->synch_cs);
2429 if ((thread->state & ThreadState_Suspended) != 0 ||
2430 (thread->state & ThreadState_SuspendRequested) != 0 ||
2431 (thread->state & ThreadState_StopRequested) != 0)
2433 LeaveCriticalSection (thread->synch_cs);
2437 thread->state |= ThreadState_SuspendRequested;
2439 LeaveCriticalSection (thread->synch_cs);
2441 signal_thread_state_change (thread);
2446 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2448 if (!mono_thread_suspend (thread))
2449 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2453 mono_thread_resume (MonoInternalThread *thread)
2455 ensure_synch_cs_set (thread);
2457 EnterCriticalSection (thread->synch_cs);
2459 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2460 thread->state &= ~ThreadState_SuspendRequested;
2461 LeaveCriticalSection (thread->synch_cs);
2465 if ((thread->state & ThreadState_Suspended) == 0 ||
2466 (thread->state & ThreadState_Unstarted) != 0 ||
2467 (thread->state & ThreadState_Aborted) != 0 ||
2468 (thread->state & ThreadState_Stopped) != 0)
2470 LeaveCriticalSection (thread->synch_cs);
2474 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2475 if (thread->resume_event == NULL) {
2476 LeaveCriticalSection (thread->synch_cs);
2480 /* Awake the thread */
2481 SetEvent (thread->suspend_event);
2483 LeaveCriticalSection (thread->synch_cs);
2485 /* Wait for the thread to awake */
2486 WaitForSingleObject (thread->resume_event, INFINITE);
2487 CloseHandle (thread->resume_event);
2488 thread->resume_event = NULL;
2494 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2496 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2497 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2501 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2506 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2507 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2508 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2510 *((gboolean*)data) = TRUE;
2517 is_running_protected_wrapper (void)
2519 gboolean found = FALSE;
2520 mono_stack_walk (find_wrapper, &found);
2524 void mono_thread_internal_stop (MonoInternalThread *thread)
2526 ensure_synch_cs_set (thread);
2528 EnterCriticalSection (thread->synch_cs);
2530 if ((thread->state & ThreadState_StopRequested) != 0 ||
2531 (thread->state & ThreadState_Stopped) != 0)
2533 LeaveCriticalSection (thread->synch_cs);
2537 /* Make sure the thread is awake */
2538 mono_thread_resume (thread);
2540 thread->state |= ThreadState_StopRequested;
2541 thread->state &= ~ThreadState_AbortRequested;
2543 LeaveCriticalSection (thread->synch_cs);
2545 signal_thread_state_change (thread);
2548 void mono_thread_stop (MonoThread *thread)
2550 mono_thread_internal_stop (thread->internal_thread);
2554 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2556 return *((volatile gint8 *) (ptr));
2560 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2562 return *((volatile gint16 *) (ptr));
2566 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2568 return *((volatile gint32 *) (ptr));
2572 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2574 return *((volatile gint64 *) (ptr));
2578 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2580 return (void *) *((volatile void **) ptr);
2584 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2586 *((volatile gint8 *) ptr) = value;
2590 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2592 *((volatile gint16 *) ptr) = value;
2596 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2598 *((volatile gint32 *) ptr) = value;
2602 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2604 *((volatile gint64 *) ptr) = value;
2608 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2610 *((volatile void **) ptr) = value;
2614 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2616 mono_gc_wbarrier_generic_store (ptr, value);
2619 void mono_thread_init (MonoThreadStartCB start_cb,
2620 MonoThreadAttachCB attach_cb)
2622 MONO_GC_REGISTER_ROOT (small_id_table);
2623 InitializeCriticalSection(&threads_mutex);
2624 InitializeCriticalSection(&interlocked_mutex);
2625 InitializeCriticalSection(&contexts_mutex);
2626 InitializeCriticalSection(&delayed_free_table_mutex);
2627 InitializeCriticalSection(&small_id_mutex);
2629 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2630 g_assert(background_change_event != NULL);
2632 mono_init_static_data_info (&thread_static_info);
2633 mono_init_static_data_info (&context_static_info);
2635 current_object_key=TlsAlloc();
2636 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2638 mono_thread_start_cb = start_cb;
2639 mono_thread_attach_cb = attach_cb;
2641 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2643 /* Get a pseudo handle to the current process. This is just a
2644 * kludge so that wapi can build a process handle if needed.
2645 * As a pseudo handle is returned, we don't need to clean
2648 GetCurrentProcess ();
2651 void mono_thread_cleanup (void)
2653 mono_thread_hazardous_try_free_all ();
2655 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2656 /* The main thread must abandon any held mutexes (particularly
2657 * important for named mutexes as they are shared across
2658 * processes, see bug 74680.) This will happen when the
2659 * thread exits, but if it's not running in a subthread it
2660 * won't exit in time.
2662 /* Using non-w32 API is a nasty kludge, but I couldn't find
2663 * anything in the documentation that would let me do this
2664 * here yet still be safe to call on windows.
2666 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2670 /* This stuff needs more testing, it seems one of these
2671 * critical sections can be locked when mono_thread_cleanup is
2674 DeleteCriticalSection (&threads_mutex);
2675 DeleteCriticalSection (&interlocked_mutex);
2676 DeleteCriticalSection (&contexts_mutex);
2677 DeleteCriticalSection (&delayed_free_table_mutex);
2678 DeleteCriticalSection (&small_id_mutex);
2679 CloseHandle (background_change_event);
2682 g_array_free (delayed_free_table, TRUE);
2683 delayed_free_table = NULL;
2685 TlsFree (current_object_key);
2689 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2691 mono_thread_cleanup_fn = func;
2695 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2697 thread->internal_thread->manage_callback = func;
2700 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2702 mono_thread_notify_pending_exc_fn = func;
2706 static void print_tids (gpointer key, gpointer value, gpointer user)
2708 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2709 * sizeof(uint) and a cast to uint would overflow
2711 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2712 * print this as a pointer.
2714 g_message ("Waiting for: %p", key);
2719 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2720 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2724 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2728 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2730 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2732 if(ret==WAIT_FAILED) {
2733 /* See the comment in build_wait_tids() */
2734 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2738 for(i=0; i<wait->num; i++)
2739 CloseHandle (wait->handles[i]);
2741 if (ret == WAIT_TIMEOUT)
2744 for(i=0; i<wait->num; i++) {
2745 gsize tid = wait->threads[i]->tid;
2747 mono_threads_lock ();
2748 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2749 /* This thread must have been killed, because
2750 * it hasn't cleaned itself up. (It's just
2751 * possible that the thread exited before the
2752 * parent thread had a chance to store the
2753 * handle, and now there is another pointer to
2754 * the already-exited thread stored. In this
2755 * case, we'll just get two
2756 * mono_profiler_thread_end() calls for the
2760 mono_threads_unlock ();
2761 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2762 thread_cleanup (wait->threads[i]);
2764 mono_threads_unlock ();
2769 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2771 guint32 i, ret, count;
2773 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2775 /* Add the thread state change event, so it wakes up if a thread changes
2776 * to background mode.
2779 if (count < MAXIMUM_WAIT_OBJECTS) {
2780 wait->handles [count] = background_change_event;
2784 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2786 if(ret==WAIT_FAILED) {
2787 /* See the comment in build_wait_tids() */
2788 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2792 for(i=0; i<wait->num; i++)
2793 CloseHandle (wait->handles[i]);
2795 if (ret == WAIT_TIMEOUT)
2798 if (ret < wait->num) {
2799 gsize tid = wait->threads[ret]->tid;
2800 mono_threads_lock ();
2801 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2802 /* See comment in wait_for_tids about thread cleanup */
2803 mono_threads_unlock ();
2804 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2805 thread_cleanup (wait->threads [ret]);
2807 mono_threads_unlock ();
2811 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2813 struct wait_data *wait=(struct wait_data *)user;
2815 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2817 MonoInternalThread *thread=(MonoInternalThread *)value;
2819 /* Ignore background threads, we abort them later */
2820 /* Do not lock here since it is not needed and the caller holds threads_lock */
2821 if (thread->state & ThreadState_Background) {
2822 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2823 return; /* just leave, ignore */
2826 if (mono_gc_is_finalizer_internal_thread (thread)) {
2827 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2831 if (thread == mono_thread_internal_current ()) {
2832 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2836 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2837 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2841 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2842 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2846 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2847 if (handle == NULL) {
2848 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2852 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2853 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2854 wait->handles[wait->num]=handle;
2855 wait->threads[wait->num]=thread;
2858 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2860 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2865 /* Just ignore the rest, we can't do anything with
2872 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2874 struct wait_data *wait=(struct wait_data *)user;
2875 gsize self = GetCurrentThreadId ();
2876 MonoInternalThread *thread = value;
2879 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2882 /* The finalizer thread is not a background thread */
2883 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2884 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2886 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2890 /* printf ("A: %d\n", wait->num); */
2891 wait->handles[wait->num]=thread->handle;
2892 wait->threads[wait->num]=thread;
2895 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2896 mono_thread_internal_stop (thread);
2900 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2904 * mono_threads_set_shutting_down:
2906 * Is called by a thread that wants to shut down Mono. If the runtime is already
2907 * shutting down, the calling thread is suspended/stopped, and this function never
2911 mono_threads_set_shutting_down (void)
2913 MonoInternalThread *current_thread = mono_thread_internal_current ();
2915 mono_threads_lock ();
2917 if (shutting_down) {
2918 mono_threads_unlock ();
2920 /* Make sure we're properly suspended/stopped */
2922 EnterCriticalSection (current_thread->synch_cs);
2924 if ((current_thread->state & ThreadState_SuspendRequested) ||
2925 (current_thread->state & ThreadState_AbortRequested) ||
2926 (current_thread->state & ThreadState_StopRequested)) {
2927 LeaveCriticalSection (current_thread->synch_cs);
2928 mono_thread_execute_interruption (current_thread);
2930 current_thread->state |= ThreadState_Stopped;
2931 LeaveCriticalSection (current_thread->synch_cs);
2934 /* Wake up other threads potentially waiting for us */
2937 shutting_down = TRUE;
2939 /* Not really a background state change, but this will
2940 * interrupt the main thread if it is waiting for all
2941 * the other threads.
2943 SetEvent (background_change_event);
2945 mono_threads_unlock ();
2950 * mono_threads_is_shutting_down:
2952 * Returns whether a thread has commenced shutdown of Mono. Note that
2953 * if the function returns FALSE the caller must not assume that
2954 * shutdown is not in progress, because the situation might have
2955 * changed since the function returned. For that reason this function
2956 * is of very limited utility.
2959 mono_threads_is_shutting_down (void)
2961 return shutting_down;
2964 void mono_thread_manage (void)
2966 struct wait_data *wait=g_new0 (struct wait_data, 1);
2968 /* join each thread that's still running */
2969 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2971 mono_threads_lock ();
2973 THREAD_DEBUG (g_message("%s: No threads", __func__));
2974 mono_threads_unlock ();
2978 mono_threads_unlock ();
2981 mono_threads_lock ();
2982 if (shutting_down) {
2983 /* somebody else is shutting down */
2984 mono_threads_unlock ();
2987 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2988 mono_g_hash_table_foreach (threads, print_tids, NULL));
2990 ResetEvent (background_change_event);
2992 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2993 mono_threads_unlock ();
2995 /* Something to wait for */
2996 wait_for_tids_or_state_change (wait, INFINITE);
2998 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2999 } while(wait->num>0);
3001 mono_threads_set_shutting_down ();
3003 /* No new threads will be created after this point */
3005 mono_runtime_set_shutting_down ();
3007 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
3008 mono_thread_pool_cleanup ();
3011 * Remove everything but the finalizer thread and self.
3012 * Also abort all the background threads
3015 mono_threads_lock ();
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().
3041 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3043 MonoInternalThread *thread=(MonoInternalThread *)value;
3045 if(thread->tid != (gsize)user) {
3046 /*TerminateThread (thread->handle, -1);*/
3050 void mono_thread_abort_all_other_threads (void)
3052 gsize self = GetCurrentThreadId ();
3054 mono_threads_lock ();
3055 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3056 mono_g_hash_table_size (threads));
3057 mono_g_hash_table_foreach (threads, print_tids, NULL));
3059 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3061 mono_threads_unlock ();
3065 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3067 MonoInternalThread *thread = (MonoInternalThread*)value;
3068 struct wait_data *wait = (struct wait_data*)user_data;
3072 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3074 * This needs no locking.
3076 if ((thread->state & ThreadState_Suspended) != 0 ||
3077 (thread->state & ThreadState_Stopped) != 0)
3080 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3081 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3085 wait->handles [wait->num] = handle;
3086 wait->threads [wait->num] = thread;
3092 * mono_thread_suspend_all_other_threads:
3094 * Suspend all managed threads except the finalizer thread and this thread. It is
3095 * not possible to resume them later.
3097 void mono_thread_suspend_all_other_threads (void)
3099 struct wait_data *wait = g_new0 (struct wait_data, 1);
3101 gsize self = GetCurrentThreadId ();
3103 guint32 eventidx = 0;
3104 gboolean starting, finished;
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 mono_threads_lock ();
3133 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3134 mono_threads_unlock ();
3136 events = g_new0 (gpointer, wait->num);
3138 /* Get the suspended events that we'll be waiting for */
3139 for (i = 0; i < wait->num; ++i) {
3140 MonoInternalThread *thread = wait->threads [i];
3141 gboolean signal_suspend = FALSE;
3143 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3144 //CloseHandle (wait->handles [i]);
3145 wait->threads [i] = NULL; /* ignore this thread in next loop */
3149 ensure_synch_cs_set (thread);
3151 EnterCriticalSection (thread->synch_cs);
3153 if (thread->suspended_event == NULL) {
3154 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3155 if (thread->suspended_event == NULL) {
3156 /* Forget this one and go on to the next */
3157 LeaveCriticalSection (thread->synch_cs);
3162 if ((thread->state & ThreadState_Suspended) != 0 ||
3163 (thread->state & ThreadState_StopRequested) != 0 ||
3164 (thread->state & ThreadState_Stopped) != 0) {
3165 LeaveCriticalSection (thread->synch_cs);
3166 CloseHandle (wait->handles [i]);
3167 wait->threads [i] = NULL; /* ignore this thread in next loop */
3171 if ((thread->state & ThreadState_SuspendRequested) == 0)
3172 signal_suspend = TRUE;
3174 events [eventidx++] = thread->suspended_event;
3176 /* Convert abort requests into suspend requests */
3177 if ((thread->state & ThreadState_AbortRequested) != 0)
3178 thread->state &= ~ThreadState_AbortRequested;
3180 thread->state |= ThreadState_SuspendRequested;
3182 LeaveCriticalSection (thread->synch_cs);
3184 /* Signal the thread to suspend */
3186 signal_thread_state_change (thread);
3190 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3191 for (i = 0; i < wait->num; ++i) {
3192 MonoInternalThread *thread = wait->threads [i];
3197 EnterCriticalSection (thread->synch_cs);
3198 if ((thread->state & ThreadState_Suspended) != 0) {
3199 CloseHandle (thread->suspended_event);
3200 thread->suspended_event = NULL;
3202 LeaveCriticalSection (thread->synch_cs);
3206 * If there are threads which are starting up, we wait until they
3207 * are suspended when they try to register in the threads hash.
3208 * This is guaranteed to finish, since the threads which can create new
3209 * threads get suspended after a while.
3210 * FIXME: The finalizer thread can still create new threads.
3212 mono_threads_lock ();
3213 if (threads_starting_up)
3214 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3217 mono_threads_unlock ();
3231 collect_threads (gpointer key, gpointer value, gpointer user_data)
3233 MonoInternalThread *thread = (MonoInternalThread*)value;
3234 struct wait_data *wait = (struct wait_data*)user_data;
3237 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3238 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3242 wait->handles [wait->num] = handle;
3243 wait->threads [wait->num] = thread;
3249 * mono_threads_request_thread_dump:
3251 * Ask all threads except the current to print their stacktrace to stdout.
3254 mono_threads_request_thread_dump (void)
3256 struct wait_data *wait = g_new0 (struct wait_data, 1);
3260 * Make a copy of the hashtable since we can't do anything with
3261 * threads while threads_mutex is held.
3263 mono_threads_lock ();
3264 mono_g_hash_table_foreach (threads, collect_threads, wait);
3265 mono_threads_unlock ();
3267 for (i = 0; i < wait->num; ++i) {
3268 MonoInternalThread *thread = wait->threads [i];
3270 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3271 (thread != mono_thread_internal_current ()) &&
3272 !thread->thread_dump_requested) {
3273 thread->thread_dump_requested = TRUE;
3275 signal_thread_state_change (thread);
3278 CloseHandle (wait->handles [i]);
3283 * mono_thread_push_appdomain_ref:
3285 * Register that the current thread may have references to objects in domain
3286 * @domain on its stack. Each call to this function should be paired with a
3287 * call to pop_appdomain_ref.
3290 mono_thread_push_appdomain_ref (MonoDomain *domain)
3292 MonoInternalThread *thread = mono_thread_internal_current ();
3295 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3296 mono_threads_lock ();
3297 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3298 mono_threads_unlock ();
3303 mono_thread_pop_appdomain_ref (void)
3305 MonoInternalThread *thread = mono_thread_internal_current ();
3308 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3309 mono_threads_lock ();
3310 /* FIXME: How can the list be empty ? */
3311 if (thread->appdomain_refs)
3312 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3313 mono_threads_unlock ();
3318 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3321 mono_threads_lock ();
3322 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3323 mono_threads_unlock ();
3328 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3330 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3333 typedef struct abort_appdomain_data {
3334 struct wait_data wait;
3336 } abort_appdomain_data;
3339 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3341 MonoInternalThread *thread = (MonoInternalThread*)value;
3342 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3343 MonoDomain *domain = data->domain;
3345 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3346 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3348 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3349 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3352 data->wait.handles [data->wait.num] = handle;
3353 data->wait.threads [data->wait.num] = thread;
3356 /* Just ignore the rest, we can't do anything with
3364 * mono_threads_abort_appdomain_threads:
3366 * Abort threads which has references to the given appdomain.
3369 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3371 abort_appdomain_data user_data;
3373 int orig_timeout = timeout;
3376 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3378 start_time = mono_msec_ticks ();
3380 mono_threads_lock ();
3382 user_data.domain = domain;
3383 user_data.wait.num = 0;
3384 /* This shouldn't take any locks */
3385 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3386 mono_threads_unlock ();
3388 if (user_data.wait.num > 0) {
3389 /* Abort the threads outside the threads lock */
3390 for (i = 0; i < user_data.wait.num; ++i)
3391 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3394 * We should wait for the threads either to abort, or to leave the
3395 * domain. We can't do the latter, so we wait with a timeout.
3397 wait_for_tids (&user_data.wait, 100);
3400 /* Update remaining time */
3401 timeout -= mono_msec_ticks () - start_time;
3402 start_time = mono_msec_ticks ();
3404 if (orig_timeout != -1 && timeout < 0)
3407 while (user_data.wait.num > 0);
3409 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3415 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3417 MonoInternalThread *thread = (MonoInternalThread*)value;
3418 MonoDomain *domain = (MonoDomain*)user_data;
3421 /* No locking needed here */
3422 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3424 if (thread->cached_culture_info) {
3425 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3426 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3427 if (obj && obj->vtable->domain == domain)
3428 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3434 * mono_threads_clear_cached_culture:
3436 * Clear the cached_current_culture from all threads if it is in the
3440 mono_threads_clear_cached_culture (MonoDomain *domain)
3442 mono_threads_lock ();
3443 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3444 mono_threads_unlock ();
3448 * mono_thread_get_undeniable_exception:
3450 * Return an exception which needs to be raised when leaving a catch clause.
3451 * This is used for undeniable exception propagation.
3454 mono_thread_get_undeniable_exception (void)
3456 MonoInternalThread *thread = mono_thread_internal_current ();
3458 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3460 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3461 * exception if the thread no longer references a dying appdomain.
3463 thread->abort_exc->trace_ips = NULL;
3464 thread->abort_exc->stack_trace = NULL;
3465 return thread->abort_exc;
3471 #if MONO_SMALL_CONFIG
3472 #define NUM_STATIC_DATA_IDX 4
3473 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3477 #define NUM_STATIC_DATA_IDX 8
3478 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3479 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3483 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3487 mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
3490 gpointer *static_data = addr;
3491 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3494 if (!static_data [i])
3496 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3497 ptr = static_data [i];
3498 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3499 uintptr_t bmap = static_reference_bitmaps [i][j];
3502 if ((bmap & 1) && *p) {
3514 * mono_alloc_static_data
3516 * Allocate memory blocks for storing threads or context static data
3519 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3521 guint idx = (offset >> 24) - 1;
3524 gpointer* static_data = *static_data_ptr;
3526 static void* tls_desc = NULL;
3529 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3531 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3532 *static_data_ptr = static_data;
3533 static_data [0] = static_data;
3536 for (i = 1; i <= idx; ++i) {
3537 if (static_data [i])
3540 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3542 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3548 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3551 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3552 if (!static_data [i])
3556 g_free (static_data [i]);
3558 mono_gc_free_fixed (static_data [i]);
3560 mono_gc_free_fixed (static_data [i]);
3563 mono_gc_free_fixed (static_data);
3567 * mono_init_static_data_info
3569 * Initializes static data counters
3571 static void mono_init_static_data_info (StaticDataInfo *static_data)
3573 static_data->idx = 0;
3574 static_data->offset = 0;
3575 static_data->freelist = NULL;
3579 * mono_alloc_static_data_slot
3581 * Generates an offset for static data. static_data contains the counters
3582 * used to generate it.
3585 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3589 if (!static_data->idx && !static_data->offset) {
3591 * we use the first chunk of the first allocation also as
3592 * an array for the rest of the data
3594 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3596 static_data->offset += align - 1;
3597 static_data->offset &= ~(align - 1);
3598 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3599 static_data->idx ++;
3600 g_assert (size <= static_data_size [static_data->idx]);
3601 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3602 static_data->offset = 0;
3604 offset = static_data->offset | ((static_data->idx + 1) << 24);
3605 static_data->offset += size;
3610 * ensure thread static fields already allocated are valid for thread
3611 * This function is called when a thread is created or on thread attach.
3614 thread_adjust_static_data (MonoInternalThread *thread)
3618 mono_threads_lock ();
3619 if (thread_static_info.offset || thread_static_info.idx > 0) {
3620 /* get the current allocated size */
3621 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3622 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3624 mono_threads_unlock ();
3628 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3630 MonoInternalThread *thread = value;
3631 guint32 offset = GPOINTER_TO_UINT (user);
3633 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3636 static MonoThreadDomainTls*
3637 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3639 MonoThreadDomainTls* prev = NULL;
3640 MonoThreadDomainTls* tmp = static_data->freelist;
3642 if (tmp->size == size) {
3644 prev->next = tmp->next;
3646 static_data->freelist = tmp->next;
3655 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3658 int idx = (offset >> 24) - 1;
3660 if (!static_reference_bitmaps [idx])
3661 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3662 rb = static_reference_bitmaps [idx];
3664 offset /= sizeof (gpointer);
3665 /* offset is now the bitmap offset */
3666 for (i = 0; i < max_set; ++i) {
3667 if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
3668 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3673 clear_reference_bitmap (guint32 offset, guint32 size)
3675 int idx = (offset >> 24) - 1;
3677 rb = static_reference_bitmaps [idx];
3679 offset /= sizeof (gpointer);
3680 size /= sizeof (gpointer);
3682 /* offset is now the bitmap offset */
3683 for (; offset < size; ++offset)
3684 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
3688 * The offset for a special static variable is composed of three parts:
3689 * a bit that indicates the type of static data (0:thread, 1:context),
3690 * an index in the array of chunks of memory for the thread (thread->static_data)
3691 * and an offset in that chunk of mem. This allows allocating less memory in the
3696 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3699 if (static_type == SPECIAL_STATIC_THREAD) {
3700 MonoThreadDomainTls *item;
3701 mono_threads_lock ();
3702 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3703 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3705 offset = item->offset;
3708 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3710 update_tls_reference_bitmap (offset, bitmap, max_set);
3711 /* This can be called during startup */
3712 if (threads != NULL)
3713 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3714 mono_threads_unlock ();
3716 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3717 mono_contexts_lock ();
3718 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3719 mono_contexts_unlock ();
3720 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3726 mono_get_special_static_data (guint32 offset)
3728 /* The high bit means either thread (0) or static (1) data. */
3730 guint32 static_type = (offset & 0x80000000);
3733 offset &= 0x7fffffff;
3734 idx = (offset >> 24) - 1;
3736 if (static_type == 0) {
3737 return get_thread_static_data (mono_thread_internal_current (), offset);
3739 /* Allocate static data block under demand, since we don't have a list
3742 MonoAppContext *context = mono_context_get ();
3743 if (!context->static_data || !context->static_data [idx]) {
3744 mono_contexts_lock ();
3745 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3746 mono_contexts_unlock ();
3748 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3758 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3760 MonoInternalThread *thread = value;
3761 TlsOffsetSize *data = user;
3762 int idx = (data->offset >> 24) - 1;
3765 if (!thread->static_data || !thread->static_data [idx])
3767 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3768 memset (ptr, 0, data->size);
3772 do_free_special (gpointer key, gpointer value, gpointer data)
3774 MonoClassField *field = key;
3775 guint32 offset = GPOINTER_TO_UINT (value);
3776 guint32 static_type = (offset & 0x80000000);
3779 size = mono_type_size (field->type, &align);
3780 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3781 if (static_type == 0) {
3783 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3784 data.offset = offset & 0x7fffffff;
3786 clear_reference_bitmap (data.offset, data.size);
3787 if (threads != NULL)
3788 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3789 item->offset = offset;
3791 item->next = thread_static_info.freelist;
3792 thread_static_info.freelist = item;
3794 /* FIXME: free context static data as well */
3799 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3801 mono_threads_lock ();
3802 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3803 mono_threads_unlock ();
3806 static MonoClassField *local_slots = NULL;
3809 /* local tls data to get locals_slot from a thread */
3812 /* index in the locals_slot array */
3817 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3819 LocalSlotID *sid = user_data;
3820 MonoInternalThread *thread = (MonoInternalThread*)value;
3821 MonoArray *slots_array;
3823 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3824 * it is for the right domain, so we need to check if it is allocated an initialized
3825 * for the current thread.
3827 /*g_print ("handling thread %p\n", thread);*/
3828 if (!thread->static_data || !thread->static_data [sid->idx])
3830 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3831 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3833 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3837 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3845 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3847 g_warning ("local_slots field not found in Thread class");
3851 domain = mono_domain_get ();
3852 mono_domain_lock (domain);
3853 if (domain->special_static_fields)
3854 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3855 mono_domain_unlock (domain);
3858 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3859 sid.offset = GPOINTER_TO_UINT (addr);
3860 sid.offset &= 0x7fffffff;
3861 sid.idx = (sid.offset >> 24) - 1;
3862 mono_threads_lock ();
3863 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3864 mono_threads_unlock ();
3866 /* FIXME: clear the slot for MonoAppContexts, too */
3871 static void CALLBACK dummy_apc (ULONG_PTR param)
3875 static guint32 dummy_apc (gpointer param)
3882 * mono_thread_execute_interruption
3884 * Performs the operation that the requested thread state requires (abort,
3887 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3889 ensure_synch_cs_set (thread);
3891 EnterCriticalSection (thread->synch_cs);
3893 /* MonoThread::interruption_requested can only be changed with atomics */
3894 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3895 /* this will consume pending APC calls */
3896 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3897 InterlockedDecrement (&thread_interruption_requested);
3899 /* Clear the interrupted flag of the thread so it can wait again */
3900 wapi_clear_interruption ();
3904 if ((thread->state & ThreadState_AbortRequested) != 0) {
3905 LeaveCriticalSection (thread->synch_cs);
3906 if (thread->abort_exc == NULL) {
3908 * This might be racy, but it has to be called outside the lock
3909 * since it calls managed code.
3911 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3913 return thread->abort_exc;
3915 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3916 thread->state &= ~ThreadState_SuspendRequested;
3917 thread->state |= ThreadState_Suspended;
3918 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3919 if (thread->suspend_event == NULL) {
3920 LeaveCriticalSection (thread->synch_cs);
3923 if (thread->suspended_event)
3924 SetEvent (thread->suspended_event);
3926 LeaveCriticalSection (thread->synch_cs);
3928 if (shutting_down) {
3929 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3934 WaitForSingleObject (thread->suspend_event, INFINITE);
3936 EnterCriticalSection (thread->synch_cs);
3938 CloseHandle (thread->suspend_event);
3939 thread->suspend_event = NULL;
3940 thread->state &= ~ThreadState_Suspended;
3942 /* The thread that requested the resume will have replaced this event
3943 * and will be waiting for it
3945 SetEvent (thread->resume_event);
3947 LeaveCriticalSection (thread->synch_cs);
3951 else if ((thread->state & ThreadState_StopRequested) != 0) {
3952 /* FIXME: do this through the JIT? */
3954 LeaveCriticalSection (thread->synch_cs);
3956 mono_thread_exit ();
3958 } else if (thread->thread_interrupt_requested) {
3960 thread->thread_interrupt_requested = FALSE;
3961 LeaveCriticalSection (thread->synch_cs);
3963 return(mono_get_exception_thread_interrupted ());
3966 LeaveCriticalSection (thread->synch_cs);
3972 * mono_thread_request_interruption
3974 * A signal handler can call this method to request the interruption of a
3975 * thread. The result of the interruption will depend on the current state of
3976 * the thread. If the result is an exception that needs to be throw, it is
3977 * provided as return value.
3980 mono_thread_request_interruption (gboolean running_managed)
3982 MonoInternalThread *thread = mono_thread_internal_current ();
3984 /* The thread may already be stopping */
3989 if (thread->interrupt_on_stop &&
3990 thread->state & ThreadState_StopRequested &&
3991 thread->state & ThreadState_Background)
3995 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3998 if (!running_managed || is_running_protected_wrapper ()) {
3999 /* Can't stop while in unmanaged code. Increase the global interruption
4000 request count. When exiting the unmanaged method the count will be
4001 checked and the thread will be interrupted. */
4003 InterlockedIncrement (&thread_interruption_requested);
4005 if (mono_thread_notify_pending_exc_fn && !running_managed)
4006 /* The JIT will notify the thread about the interruption */
4007 /* This shouldn't take any locks */
4008 mono_thread_notify_pending_exc_fn ();
4010 /* this will awake the thread if it is in WaitForSingleObject
4012 /* Our implementation of this function ignores the func argument */
4013 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4017 return mono_thread_execute_interruption (thread);
4021 /*This function should be called by a thread after it has exited all of
4022 * its handle blocks at interruption time.*/
4024 mono_thread_resume_interruption (void)
4026 MonoInternalThread *thread = mono_thread_internal_current ();
4027 gboolean still_aborting;
4029 /* The thread may already be stopping */
4033 ensure_synch_cs_set (thread);
4034 EnterCriticalSection (thread->synch_cs);
4035 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4036 LeaveCriticalSection (thread->synch_cs);
4038 /*This can happen if the protected block called Thread::ResetAbort*/
4039 if (!still_aborting)
4042 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4044 InterlockedIncrement (&thread_interruption_requested);
4047 wapi_self_interrupt ();
4049 return mono_thread_execute_interruption (thread);
4052 gboolean mono_thread_interruption_requested ()
4054 if (thread_interruption_requested) {
4055 MonoInternalThread *thread = mono_thread_internal_current ();
4056 /* The thread may already be stopping */
4058 return (thread->interruption_requested);
4063 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4065 MonoInternalThread *thread = mono_thread_internal_current ();
4067 /* The thread may already be stopping */
4071 mono_debugger_check_interruption ();
4073 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4074 MonoException* exc = mono_thread_execute_interruption (thread);
4075 if (exc) mono_raise_exception (exc);
4080 * Performs the interruption of the current thread, if one has been requested,
4081 * and the thread is not running a protected wrapper.
4083 void mono_thread_interruption_checkpoint ()
4085 mono_thread_interruption_checkpoint_request (FALSE);
4089 * Performs the interruption of the current thread, if one has been requested.
4091 void mono_thread_force_interruption_checkpoint ()
4093 mono_thread_interruption_checkpoint_request (TRUE);
4097 * mono_thread_get_and_clear_pending_exception:
4099 * Return any pending exceptions for the current thread and clear it as a side effect.
4102 mono_thread_get_and_clear_pending_exception (void)
4104 MonoInternalThread *thread = mono_thread_internal_current ();
4106 /* The thread may already be stopping */
4110 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4111 return mono_thread_execute_interruption (thread);
4114 if (thread->pending_exception) {
4115 MonoException *exc = thread->pending_exception;
4117 thread->pending_exception = NULL;
4125 * mono_set_pending_exception:
4127 * Set the pending exception of the current thread to EXC. On platforms which
4128 * support it, the exception will be thrown when execution returns to managed code.
4129 * On other platforms, this function is equivalent to mono_raise_exception ().
4130 * Internal calls which report exceptions using this function instead of
4131 * raise_exception () might be called by JITted code using a more efficient calling
4135 mono_set_pending_exception (MonoException *exc)
4137 MonoInternalThread *thread = mono_thread_internal_current ();
4139 /* The thread may already be stopping */
4143 if (mono_thread_notify_pending_exc_fn) {
4144 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4146 mono_thread_notify_pending_exc_fn ();
4148 /* No way to notify the JIT about the exception, have to throw it now */
4149 mono_raise_exception (exc);
4154 * mono_thread_interruption_request_flag:
4156 * Returns the address of a flag that will be non-zero if an interruption has
4157 * been requested for a thread. The thread to interrupt may not be the current
4158 * thread, so an additional call to mono_thread_interruption_requested() or
4159 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4162 gint32* mono_thread_interruption_request_flag ()
4164 return &thread_interruption_requested;
4168 mono_thread_init_apartment_state (void)
4171 MonoInternalThread* thread = mono_thread_internal_current ();
4173 /* Positive return value indicates success, either
4174 * S_OK if this is first CoInitialize call, or
4175 * S_FALSE if CoInitialize already called, but with same
4176 * threading model. A negative value indicates failure,
4177 * probably due to trying to change the threading model.
4179 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4180 ? COINIT_APARTMENTTHREADED
4181 : COINIT_MULTITHREADED) < 0) {
4182 thread->apartment_state = ThreadApartmentState_Unknown;
4188 mono_thread_cleanup_apartment_state (void)
4191 MonoInternalThread* thread = mono_thread_internal_current ();
4193 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4200 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4202 ensure_synch_cs_set (thread);
4204 EnterCriticalSection (thread->synch_cs);
4205 thread->state |= state;
4206 LeaveCriticalSection (thread->synch_cs);
4210 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4212 ensure_synch_cs_set (thread);
4214 EnterCriticalSection (thread->synch_cs);
4215 thread->state &= ~state;
4216 LeaveCriticalSection (thread->synch_cs);
4220 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4222 gboolean ret = FALSE;
4224 ensure_synch_cs_set (thread);
4226 EnterCriticalSection (thread->synch_cs);
4228 if ((thread->state & test) != 0) {
4232 LeaveCriticalSection (thread->synch_cs);
4237 static MonoClassField *execution_context_field;
4240 get_execution_context_addr (void)
4242 MonoDomain *domain = mono_domain_get ();
4245 if (!execution_context_field) {
4246 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4248 g_assert (execution_context_field);
4251 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4253 mono_domain_lock (domain);
4254 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4255 mono_domain_unlock (domain);
4258 return (MonoObject**) mono_get_special_static_data (offset);
4262 mono_thread_get_execution_context (void)
4264 return *get_execution_context_addr ();
4268 mono_thread_set_execution_context (MonoObject *ec)
4270 *get_execution_context_addr () = ec;
4273 static gboolean has_tls_get = FALSE;
4276 mono_runtime_set_has_tls_get (gboolean val)
4282 mono_runtime_has_tls_get (void)