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 #include <mono/metadata/object.h>
20 #include <mono/metadata/domain-internals.h>
21 #include <mono/metadata/profiler-private.h>
22 #include <mono/metadata/threads.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/metadata/threads-types.h>
25 #include <mono/metadata/exception.h>
26 #include <mono/metadata/environment.h>
27 #include <mono/metadata/monitor.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/metadata/marshal.h>
30 #include <mono/io-layer/io-layer.h>
32 #include <mono/io-layer/threads.h>
34 #include <mono/metadata/object-internals.h>
35 #include <mono/metadata/mono-debug-debugger.h>
36 #include <mono/utils/mono-compiler.h>
37 #include <mono/utils/mono-mmap.h>
38 #include <mono/utils/mono-membar.h>
39 #include <mono/utils/mono-time.h>
41 #include <mono/metadata/gc-internal.h>
43 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
44 #define THREAD_DEBUG(a)
45 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
46 #define THREAD_WAIT_DEBUG(a)
47 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
48 #define LIBGC_DEBUG(a)
50 /* Provide this for systems with glib < 2.6 */
51 #ifndef G_GSIZE_FORMAT
52 # if GLIB_SIZEOF_LONG == 8
53 # define G_GSIZE_FORMAT "lu"
55 # define G_GSIZE_FORMAT "u"
61 guint32 (*func)(void *);
77 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
78 struct _MonoThreadDomainTls {
79 MonoThreadDomainTls *next;
87 MonoThreadDomainTls *freelist;
92 MonoHazardousFreeFunc free_func;
95 /* Number of cached culture objects in the MonoThread->cached_culture_info array
96 * (per-type): we use the first NUM entries for CultureInfo and the last for
97 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
99 #define NUM_CACHED_CULTURES 4
100 #define CULTURES_START_IDX 0
101 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
103 /* Controls access to the 'threads' hash table */
104 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
105 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
106 static CRITICAL_SECTION threads_mutex;
108 /* Controls access to context static data */
109 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
110 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
111 static CRITICAL_SECTION contexts_mutex;
113 /* Holds current status of static data heap */
114 static StaticDataInfo thread_static_info;
115 static StaticDataInfo context_static_info;
117 /* The hash of existing threads (key is thread ID, value is
118 * MonoInternalThread*) that need joining before exit
120 static MonoGHashTable *threads=NULL;
123 * Threads which are starting up and they are not in the 'threads' hash yet.
124 * When handle_store is called for a thread, it will be removed from this hash table.
125 * Protected by mono_threads_lock ().
127 static MonoGHashTable *threads_starting_up = NULL;
129 /* Maps a MonoThread to its start argument */
130 /* Protected by mono_threads_lock () */
131 static MonoGHashTable *thread_start_args = NULL;
133 /* The TLS key that holds the MonoObject assigned to each thread */
134 static guint32 current_object_key = -1;
136 #ifdef HAVE_KW_THREAD
137 /* we need to use both the Tls* functions and __thread because
138 * the gc needs to see all the threads
140 static __thread MonoInternalThread * tls_current_object MONO_TLS_FAST;
141 #define SET_CURRENT_OBJECT(x) do { \
142 tls_current_object = x; \
143 TlsSetValue (current_object_key, x); \
145 #define GET_CURRENT_OBJECT() tls_current_object
147 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x)
148 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key)
151 /* function called at thread start */
152 static MonoThreadStartCB mono_thread_start_cb = NULL;
154 /* function called at thread attach */
155 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
157 /* function called at thread cleanup */
158 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
160 /* function called to notify the runtime about a pending exception on the current thread */
161 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
163 /* The default stack size for each thread */
164 static guint32 default_stacksize = 0;
165 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
167 static void thread_adjust_static_data (MonoInternalThread *thread);
168 static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
169 static void mono_init_static_data_info (StaticDataInfo *static_data);
170 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
171 static gboolean mono_thread_resume (MonoInternalThread* thread);
172 static void mono_thread_start (MonoThread *thread);
173 static void signal_thread_state_change (MonoInternalThread *thread);
175 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
177 /* Spin lock for InterlockedXXX 64 bit functions */
178 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
179 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
180 static CRITICAL_SECTION interlocked_mutex;
182 /* global count of thread interruptions requested */
183 static gint32 thread_interruption_requested = 0;
185 /* Event signaled when a thread changes its background mode */
186 static HANDLE background_change_event;
188 /* The table for small ID assignment */
189 static CRITICAL_SECTION small_id_mutex;
190 static int small_id_table_size = 0;
191 static int small_id_next = 0;
192 static int highest_small_id = -1;
193 static MonoInternalThread **small_id_table = NULL;
195 /* The hazard table */
196 #if MONO_SMALL_CONFIG
197 #define HAZARD_TABLE_MAX_SIZE 256
199 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
201 static volatile int hazard_table_size = 0;
202 static MonoThreadHazardPointers * volatile hazard_table = NULL;
204 /* The table where we keep pointers to blocks to be freed but that
205 have to wait because they're guarded by a hazard pointer. */
206 static CRITICAL_SECTION delayed_free_table_mutex;
207 static GArray *delayed_free_table = NULL;
209 static gboolean shutting_down = FALSE;
212 mono_thread_get_tls_key (void)
214 return current_object_key;
218 mono_thread_get_tls_offset (void)
221 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
225 /* handle_store() and handle_remove() manage the array of threads that
226 * still need to be waited for when the main thread exits.
228 * If handle_store() returns FALSE the thread must not be started
229 * because Mono is shutting down.
231 static gboolean handle_store(MonoThread *thread)
233 mono_threads_lock ();
235 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
237 if (threads_starting_up)
238 mono_g_hash_table_remove (threads_starting_up, thread);
241 mono_threads_unlock ();
246 MONO_GC_REGISTER_ROOT (threads);
247 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
250 /* We don't need to duplicate thread->handle, because it is
251 * only closed when the thread object is finalized by the GC.
253 g_assert (thread->internal_thread);
254 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
255 thread->internal_thread);
257 mono_threads_unlock ();
262 static gboolean handle_remove(MonoInternalThread *thread)
265 gsize tid = thread->tid;
267 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
269 mono_threads_lock ();
272 /* We have to check whether the thread object for the
273 * tid is still the same in the table because the
274 * thread might have been destroyed and the tid reused
275 * in the meantime, in which case the tid would be in
276 * the table, but with another thread object.
278 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
279 mono_g_hash_table_remove (threads, (gpointer)tid);
288 mono_threads_unlock ();
290 /* Don't close the handle here, wait for the object finalizer
291 * to do it. Otherwise, the following race condition applies:
293 * 1) Thread exits (and handle_remove() closes the handle)
295 * 2) Some other handle is reassigned the same slot
297 * 3) Another thread tries to join the first thread, and
298 * blocks waiting for the reassigned handle to be signalled
299 * (which might never happen). This is possible, because the
300 * thread calling Join() still has a reference to the first
307 * Allocate a small thread id.
309 * FIXME: The biggest part of this function is very similar to
310 * domain_id_alloc() in domain.c and should be merged.
313 small_id_alloc (MonoInternalThread *thread)
317 EnterCriticalSection (&small_id_mutex);
319 if (!small_id_table) {
320 small_id_table_size = 2;
321 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
323 for (i = small_id_next; i < small_id_table_size; ++i) {
324 if (!small_id_table [i]) {
330 for (i = 0; i < small_id_next; ++i) {
331 if (!small_id_table [i]) {
338 MonoInternalThread **new_table;
339 int new_size = small_id_table_size * 2;
340 if (new_size >= (1 << 16))
341 g_assert_not_reached ();
342 id = small_id_table_size;
343 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
344 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
345 mono_gc_free_fixed (small_id_table);
346 small_id_table = new_table;
347 small_id_table_size = new_size;
349 thread->small_id = id;
350 g_assert (small_id_table [id] == NULL);
351 small_id_table [id] = thread;
353 if (small_id_next > small_id_table_size)
356 g_assert (id < HAZARD_TABLE_MAX_SIZE);
357 if (id >= hazard_table_size) {
358 #if MONO_SMALL_CONFIG
359 hazard_table = g_malloc0 (sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE);
360 hazard_table_size = HAZARD_TABLE_MAX_SIZE;
363 int pagesize = mono_pagesize ();
364 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
366 if (hazard_table == NULL) {
367 hazard_table = mono_valloc (NULL,
368 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
372 g_assert (hazard_table != NULL);
373 page_addr = (guint8*)hazard_table + num_pages * pagesize;
375 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
378 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
381 g_assert (id < hazard_table_size);
382 hazard_table [id].hazard_pointers [0] = NULL;
383 hazard_table [id].hazard_pointers [1] = NULL;
386 if (id > highest_small_id) {
387 highest_small_id = id;
388 mono_memory_write_barrier ();
391 LeaveCriticalSection (&small_id_mutex);
397 small_id_free (int id)
399 g_assert (id >= 0 && id < small_id_table_size);
400 g_assert (small_id_table [id] != NULL);
402 small_id_table [id] = NULL;
406 is_pointer_hazardous (gpointer p)
409 int highest = highest_small_id;
411 g_assert (highest < hazard_table_size);
413 for (i = 0; i <= highest; ++i) {
414 if (hazard_table [i].hazard_pointers [0] == p
415 || hazard_table [i].hazard_pointers [1] == p)
422 MonoThreadHazardPointers*
423 mono_hazard_pointer_get (void)
425 MonoInternalThread *current_thread = mono_thread_internal_current ();
427 if (!(current_thread && current_thread->small_id >= 0)) {
428 static MonoThreadHazardPointers emerg_hazard_table;
429 g_warning ("Thread %p may have been prematurely finalized", current_thread);
430 return &emerg_hazard_table;
433 return &hazard_table [current_thread->small_id];
437 try_free_delayed_free_item (int index)
439 if (delayed_free_table->len > index) {
440 DelayedFreeItem item = { NULL, NULL };
442 EnterCriticalSection (&delayed_free_table_mutex);
443 /* We have to check the length again because another
444 thread might have freed an item before we acquired
446 if (delayed_free_table->len > index) {
447 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
449 if (!is_pointer_hazardous (item.p))
450 g_array_remove_index_fast (delayed_free_table, index);
454 LeaveCriticalSection (&delayed_free_table_mutex);
457 item.free_func (item.p);
462 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
466 /* First try to free a few entries in the delayed free
468 for (i = 2; i >= 0; --i)
469 try_free_delayed_free_item (i);
471 /* Now see if the pointer we're freeing is hazardous. If it
472 isn't, free it. Otherwise put it in the delay list. */
473 if (is_pointer_hazardous (p)) {
474 DelayedFreeItem item = { p, free_func };
476 ++mono_stats.hazardous_pointer_count;
478 EnterCriticalSection (&delayed_free_table_mutex);
479 g_array_append_val (delayed_free_table, item);
480 LeaveCriticalSection (&delayed_free_table_mutex);
486 mono_thread_hazardous_try_free_all (void)
491 if (!delayed_free_table)
494 len = delayed_free_table->len;
496 for (i = len - 1; i >= 0; --i)
497 try_free_delayed_free_item (i);
500 static void ensure_synch_cs_set (MonoInternalThread *thread)
502 CRITICAL_SECTION *synch_cs;
504 if (thread->synch_cs != NULL) {
508 synch_cs = g_new0 (CRITICAL_SECTION, 1);
509 InitializeCriticalSection (synch_cs);
511 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
512 synch_cs, NULL) != NULL) {
513 /* Another thread must have installed this CS */
514 DeleteCriticalSection (synch_cs);
520 * NOTE: this function can be called also for threads different from the current one:
521 * make sure no code called from it will ever assume it is run on the thread that is
522 * getting cleaned up.
524 static void thread_cleanup (MonoInternalThread *thread)
526 g_assert (thread != NULL);
528 if (thread->abort_state_handle) {
529 mono_gchandle_free (thread->abort_state_handle);
530 thread->abort_state_handle = 0;
532 thread->abort_exc = NULL;
533 thread->current_appcontext = NULL;
536 * This is necessary because otherwise we might have
537 * cross-domain references which will not get cleaned up when
538 * the target domain is unloaded.
540 if (thread->cached_culture_info) {
542 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
543 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
546 /* if the thread is not in the hash it has been removed already */
547 if (!handle_remove (thread))
549 mono_release_type_locks (thread);
551 EnterCriticalSection (thread->synch_cs);
553 thread->state |= ThreadState_Stopped;
554 thread->state &= ~ThreadState_Background;
556 LeaveCriticalSection (thread->synch_cs);
558 mono_profiler_thread_end (thread->tid);
560 if (thread == mono_thread_internal_current ())
561 mono_thread_pop_appdomain_ref ();
563 thread->cached_culture_info = NULL;
565 mono_free_static_data (thread->static_data, TRUE);
566 thread->static_data = NULL;
569 * FIXME: The check for shutting_down here is a kludge and
570 * should be removed. The reason we need it here is because
571 * mono_thread_manage() does not wait for finalizer threads,
572 * so we might still be at this point in a finalizer thread
573 * after the main thread has cleared the root domain, so
574 * thread could have been zeroed out.
576 if (mono_thread_cleanup_fn && !shutting_down)
577 mono_thread_cleanup_fn (thread->root_domain_thread);
579 small_id_free (thread->small_id);
580 thread->small_id = -2;
584 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
587 g_assert ((offset & 0x80000000) == 0);
588 offset &= 0x7fffffff;
589 idx = (offset >> 24) - 1;
590 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
594 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
596 static MonoClassField *current_thread_field = NULL;
600 if (!current_thread_field) {
601 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
602 g_assert (current_thread_field);
605 mono_class_vtable (domain, mono_defaults.thread_class);
606 mono_domain_lock (domain);
607 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
608 mono_domain_unlock (domain);
611 return get_thread_static_data (thread, offset);
615 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
617 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
619 g_assert (current->obj.vtable->domain == domain);
621 g_assert (!*current_thread_ptr);
622 *current_thread_ptr = current;
626 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
628 MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
629 MONO_OBJECT_SETREF (thread, internal_thread, internal);
634 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
636 MonoDomain *domain = mono_get_root_domain ();
638 if (!candidate || candidate->obj.vtable->domain != domain)
639 candidate = new_thread_with_internal (domain, thread);
640 set_current_thread_for_domain (domain, thread, candidate);
641 g_assert (!thread->root_domain_thread);
642 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
645 static guint32 WINAPI start_wrapper(void *data)
647 struct StartInfo *start_info=(struct StartInfo *)data;
648 guint32 (*start_func)(void *);
651 MonoThread *thread=start_info->obj;
652 MonoInternalThread *internal = thread->internal_thread;
653 MonoObject *start_delegate = start_info->delegate;
655 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
657 /* We can be sure start_info->obj->tid and
658 * start_info->obj->handle have been set, because the thread
659 * was created suspended, and these values were set before the
665 SET_CURRENT_OBJECT (internal);
667 mono_monitor_init_tls ();
669 /* Every thread references the appdomain which created it */
670 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
672 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
673 /* No point in raising an appdomain_unloaded exception here */
674 /* FIXME: Cleanup here */
675 mono_thread_pop_appdomain_ref ();
679 start_func = start_info->func;
680 start_arg = start_info->start_arg;
682 /* We have to do this here because mono_thread_new_init()
683 requires that root_domain_thread is set up. */
684 thread_adjust_static_data (internal);
685 init_root_domain_thread (internal, thread);
687 /* This MUST be called before any managed code can be
688 * executed, as it calls the callback function that (for the
689 * jit) sets the lmf marker.
691 mono_thread_new_init (tid, &tid, start_func);
692 internal->stack_ptr = &tid;
694 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
696 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
698 /* On 2.0 profile (and higher), set explicitly since state might have been
700 if (internal->apartment_state == ThreadApartmentState_Unknown)
701 internal->apartment_state = ThreadApartmentState_MTA;
703 mono_thread_init_apartment_state ();
705 if(internal->start_notify!=NULL) {
706 /* Let the thread that called Start() know we're
709 ReleaseSemaphore (internal->start_notify, 1, NULL);
712 mono_threads_lock ();
713 mono_g_hash_table_remove (thread_start_args, thread);
714 mono_threads_unlock ();
718 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
722 mono_thread_set_execution_context (thread->ec_to_set);
723 thread->ec_to_set = NULL;
726 * Call this after calling start_notify, since the profiler callback might want
727 * to lock the thread, and the lock is held by thread_start () which waits for
730 mono_profiler_thread_start (tid);
732 /* start_func is set only for unmanaged start functions */
734 start_func (start_arg);
737 g_assert (start_delegate != NULL);
738 args [0] = start_arg;
739 /* we may want to handle the exception here. See comment below on unhandled exceptions */
740 mono_runtime_delegate_invoke (start_delegate, args, NULL);
743 /* If the thread calls ExitThread at all, this remaining code
744 * will not be executed, but the main thread will eventually
745 * call thread_cleanup() on this thread's behalf.
748 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
750 thread_cleanup (internal);
752 /* Do any cleanup needed for apartment state. This
753 * cannot be done in thread_cleanup since thread_cleanup could be
754 * called for a thread other than the current thread.
755 * mono_thread_cleanup_apartment_state cleans up apartment
756 * for the current thead */
757 mono_thread_cleanup_apartment_state ();
759 /* Remove the reference to the thread object in the TLS data,
760 * so the thread object can be finalized. This won't be
761 * reached if the thread threw an uncaught exception, so those
762 * thread handles will stay referenced :-( (This is due to
763 * missing support for scanning thread-specific data in the
764 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
767 SET_CURRENT_OBJECT (NULL);
768 mono_domain_unset ();
773 void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
775 if (mono_thread_start_cb) {
776 mono_thread_start_cb (tid, stack_start, func);
780 void mono_threads_set_default_stacksize (guint32 stacksize)
782 default_stacksize = stacksize;
785 guint32 mono_threads_get_default_stacksize (void)
787 return default_stacksize;
791 * mono_create_thread:
793 * This is a wrapper around CreateThread which handles differences in the type of
794 * the the 'tid' argument.
796 gpointer mono_create_thread (WapiSecurityAttributes *security,
797 guint32 stacksize, WapiThreadStart start,
798 gpointer param, guint32 create, gsize *tid)
805 res = CreateThread (security, stacksize, start, param, create, &real_tid);
809 res = CreateThread (security, stacksize, start, param, create, tid);
816 * The thread start argument may be an object reference, and there is
817 * no ref to keep it alive when the new thread is started but not yet
818 * registered with the collector. So we store it in a GC tracked hash
821 * LOCKING: Assumes the threads lock is held.
824 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
826 if (thread_start_args == NULL) {
827 MONO_GC_REGISTER_ROOT (thread_start_args);
828 thread_start_args = mono_g_hash_table_new (NULL, NULL);
830 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
833 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
836 MonoInternalThread *internal;
837 HANDLE thread_handle;
838 struct StartInfo *start_info;
841 thread=(MonoThread *)mono_object_new (domain,
842 mono_defaults.thread_class);
843 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
844 mono_defaults.internal_thread_class);
845 MONO_OBJECT_SETREF (thread, internal_thread, internal);
847 start_info=g_new0 (struct StartInfo, 1);
848 start_info->func = func;
849 start_info->obj = thread;
850 start_info->start_arg = arg;
852 mono_threads_lock ();
854 mono_threads_unlock ();
858 if (threads_starting_up == NULL) {
859 MONO_GC_REGISTER_ROOT (threads_starting_up);
860 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
863 register_thread_start_argument (thread, start_info);
864 mono_g_hash_table_insert (threads_starting_up, thread, thread);
865 mono_threads_unlock ();
867 /* Create suspended, so we can do some housekeeping before the thread
870 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
871 CREATE_SUSPENDED, &tid);
872 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
873 if (thread_handle == NULL) {
874 /* The thread couldn't be created, so throw an exception */
875 mono_threads_lock ();
876 mono_g_hash_table_remove (threads_starting_up, thread);
877 mono_threads_unlock ();
879 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
883 internal->handle=thread_handle;
885 internal->apartment_state=ThreadApartmentState_Unknown;
886 small_id_alloc (internal);
888 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
889 InitializeCriticalSection (internal->synch_cs);
891 internal->threadpool_thread = threadpool_thread;
892 if (threadpool_thread)
893 mono_thread_set_state (internal, ThreadState_Background);
895 if (handle_store (thread))
896 ResumeThread (thread_handle);
902 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
904 mono_thread_create_internal (domain, func, arg, FALSE);
908 * mono_thread_get_stack_bounds:
910 * Return the address and size of the current threads stack. Return NULL as the
911 * stack address if the stack address cannot be determined.
914 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
916 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
917 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
918 *stsize = pthread_get_stacksize_np (pthread_self ());
919 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
921 /* FIXME: simplify the mess below */
922 #elif !defined(HOST_WIN32)
924 guint8 *current = (guint8*)&attr;
926 pthread_attr_init (&attr);
927 # ifdef HAVE_PTHREAD_GETATTR_NP
928 pthread_getattr_np (pthread_self(), &attr);
930 # ifdef HAVE_PTHREAD_ATTR_GET_NP
931 pthread_attr_get_np (pthread_self(), &attr);
934 pthread_attr_getstacksize (&attr, &stsize);
943 pthread_attr_getstack (&attr, (void**)staddr, stsize);
945 g_assert ((current > *staddr) && (current < *staddr + *stsize));
948 pthread_attr_destroy (&attr);
951 /* When running under emacs, sometimes staddr is not aligned to a page size */
952 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
956 mono_thread_attach (MonoDomain *domain)
958 MonoInternalThread *thread;
959 MonoThread *current_thread;
960 HANDLE thread_handle;
963 if ((thread = mono_thread_internal_current ())) {
964 if (domain != mono_domain_get ())
965 mono_domain_set (domain, TRUE);
966 /* Already attached */
967 return mono_thread_current ();
970 if (!mono_gc_register_thread (&domain)) {
971 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 ());
974 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
976 thread_handle = GetCurrentThread ();
977 g_assert (thread_handle);
979 tid=GetCurrentThreadId ();
982 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
983 * refer to the thread from other threads for things like aborting.
985 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
986 THREAD_ALL_ACCESS, TRUE, 0);
988 thread->handle=thread_handle;
990 thread->apartment_state=ThreadApartmentState_Unknown;
991 small_id_alloc (thread);
992 thread->stack_ptr = &tid;
994 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
995 InitializeCriticalSection (thread->synch_cs);
997 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
999 current_thread = new_thread_with_internal (domain, thread);
1001 if (!handle_store (current_thread)) {
1002 /* Mono is shutting down, so just wait for the end */
1007 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
1009 SET_CURRENT_OBJECT (thread);
1010 mono_domain_set (domain, TRUE);
1012 mono_monitor_init_tls ();
1014 thread_adjust_static_data (thread);
1016 init_root_domain_thread (thread, current_thread);
1017 if (domain != mono_get_root_domain ())
1018 set_current_thread_for_domain (domain, thread, current_thread);
1021 if (mono_thread_attach_cb) {
1025 mono_thread_get_stack_bounds (&staddr, &stsize);
1028 mono_thread_attach_cb (tid, &tid);
1030 mono_thread_attach_cb (tid, staddr + stsize);
1033 // FIXME: Need a separate callback
1034 mono_profiler_thread_start (tid);
1036 return current_thread;
1040 mono_thread_detach (MonoThread *thread)
1042 g_return_if_fail (thread != NULL);
1044 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1046 thread_cleanup (thread->internal_thread);
1048 SET_CURRENT_OBJECT (NULL);
1049 mono_domain_unset ();
1051 /* Don't need to CloseHandle this thread, even though we took a
1052 * reference in mono_thread_attach (), because the GC will do it
1053 * when the Thread object is finalised.
1060 MonoInternalThread *thread = mono_thread_internal_current ();
1062 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1064 thread_cleanup (thread);
1065 SET_CURRENT_OBJECT (NULL);
1066 mono_domain_unset ();
1068 /* we could add a callback here for embedders to use. */
1069 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
1070 exit (mono_environment_exitcode_get ());
1075 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1077 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1078 internal->state = ThreadState_Unstarted;
1079 internal->apartment_state = ThreadApartmentState_Unknown;
1081 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1084 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1087 guint32 (*start_func)(void *);
1088 struct StartInfo *start_info;
1091 MonoInternalThread *internal;
1093 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1095 if (!this->internal_thread)
1096 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1097 internal = this->internal_thread;
1099 ensure_synch_cs_set (internal);
1101 EnterCriticalSection (internal->synch_cs);
1103 if ((internal->state & ThreadState_Unstarted) == 0) {
1104 LeaveCriticalSection (internal->synch_cs);
1105 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1109 internal->small_id = -1;
1111 if ((internal->state & ThreadState_Aborted) != 0) {
1112 LeaveCriticalSection (internal->synch_cs);
1117 /* This is freed in start_wrapper */
1118 start_info = g_new0 (struct StartInfo, 1);
1119 start_info->func = start_func;
1120 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1121 start_info->delegate = start;
1122 start_info->obj = this;
1123 g_assert (this->obj.vtable->domain == mono_domain_get ());
1125 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1126 if (internal->start_notify==NULL) {
1127 LeaveCriticalSection (internal->synch_cs);
1128 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1129 g_free (start_info);
1133 mono_threads_lock ();
1134 register_thread_start_argument (this, start_info);
1135 if (threads_starting_up == NULL) {
1136 MONO_GC_REGISTER_ROOT (threads_starting_up);
1137 threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
1139 mono_g_hash_table_insert (threads_starting_up, this, this);
1140 mono_threads_unlock ();
1142 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1143 CREATE_SUSPENDED, &tid);
1145 LeaveCriticalSection (internal->synch_cs);
1146 mono_threads_lock ();
1147 mono_g_hash_table_remove (threads_starting_up, this);
1148 mono_threads_unlock ();
1149 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1153 internal->handle=thread;
1155 small_id_alloc (internal);
1157 /* Don't call handle_store() here, delay it to Start.
1158 * We can't join a thread (trying to will just block
1159 * forever) until it actually starts running, so don't
1160 * store the handle till then.
1163 mono_thread_start (this);
1165 internal->state &= ~ThreadState_Unstarted;
1167 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1169 LeaveCriticalSection (internal->synch_cs);
1174 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1176 MONO_ARCH_SAVE_REGS;
1178 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1181 CloseHandle (thread);
1183 if (this->synch_cs) {
1184 DeleteCriticalSection (this->synch_cs);
1185 g_free (this->synch_cs);
1186 this->synch_cs = NULL;
1189 g_free (this->name);
1192 static void mono_thread_start (MonoThread *thread)
1194 MonoInternalThread *internal = thread->internal_thread;
1196 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1198 /* Only store the handle when the thread is about to be
1199 * launched, to avoid the main thread deadlocking while trying
1200 * to clean up a thread that will never be signalled.
1202 if (!handle_store (thread))
1205 ResumeThread (internal->handle);
1207 if(internal->start_notify!=NULL) {
1208 /* Wait for the thread to set up its TLS data etc, so
1209 * theres no potential race condition if someone tries
1210 * to look up the data believing the thread has
1214 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1216 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1217 CloseHandle (internal->start_notify);
1218 internal->start_notify = NULL;
1221 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1224 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1227 MonoInternalThread *thread = mono_thread_internal_current ();
1229 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1231 mono_thread_current_check_pending_interrupt ();
1233 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1235 res = SleepEx(ms,TRUE);
1237 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1239 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1240 MonoException* exc = mono_thread_execute_interruption (thread);
1241 if (exc) mono_raise_exception (exc);
1245 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1250 ves_icall_System_Threading_Thread_GetDomainID (void)
1252 MONO_ARCH_SAVE_REGS;
1254 return mono_domain_get()->domain_id;
1258 * mono_thread_get_name:
1260 * Return the name of the thread. NAME_LEN is set to the length of the name.
1261 * Return NULL if the thread has no name. The returned memory is owned by the
1265 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1269 ensure_synch_cs_set (this_obj);
1271 EnterCriticalSection (this_obj->synch_cs);
1273 if (!this_obj->name) {
1277 *name_len = this_obj->name_len;
1278 res = g_new (gunichar2, this_obj->name_len);
1279 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1282 LeaveCriticalSection (this_obj->synch_cs);
1288 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1292 ensure_synch_cs_set (this_obj);
1294 EnterCriticalSection (this_obj->synch_cs);
1296 if (!this_obj->name)
1299 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1301 LeaveCriticalSection (this_obj->synch_cs);
1307 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1309 ensure_synch_cs_set (this_obj);
1311 EnterCriticalSection (this_obj->synch_cs);
1313 if (this_obj->name) {
1314 LeaveCriticalSection (this_obj->synch_cs);
1316 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1320 this_obj->name = g_new (gunichar2, mono_string_length (name));
1321 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1322 this_obj->name_len = mono_string_length (name);
1325 this_obj->name = NULL;
1327 LeaveCriticalSection (this_obj->synch_cs);
1331 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1336 if (this->cached_culture_info) {
1337 domain = mono_domain_get ();
1338 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1339 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1340 if (res && res->vtable->domain == domain)
1348 /* If the array is already in the requested domain, we just return it,
1349 otherwise we return a copy in that domain. */
1351 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1358 if (mono_object_domain (arr) == domain)
1361 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1362 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1367 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1369 return byte_array_to_domain (arr, mono_get_root_domain ());
1373 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1375 return byte_array_to_domain (arr, mono_domain_get ());
1379 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1381 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1385 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1388 MonoDomain *domain = mono_domain_get ();
1391 int same_domain_slot = -1;
1393 ensure_synch_cs_set (this);
1395 EnterCriticalSection (this->synch_cs);
1397 if (!this->cached_culture_info)
1398 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1400 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1401 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1405 /* we continue, because there may be a slot used with the same domain */
1409 if (obj->vtable->domain == domain) {
1410 same_domain_slot = i;
1414 if (same_domain_slot >= 0)
1415 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1416 else if (free_slot >= 0)
1417 mono_array_setref (this->cached_culture_info, free_slot, culture);
1418 /* we may want to replace an existing entry here, even when no suitable slot is found */
1420 LeaveCriticalSection (this->synch_cs);
1424 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1426 MonoDomain *domain = mono_object_get_domain (&this->obj);
1427 g_assert (domain == mono_domain_get ());
1428 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1432 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1434 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1438 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1440 MonoDomain *domain = mono_object_get_domain (&this->obj);
1441 g_assert (domain == mono_domain_get ());
1442 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1446 mono_thread_current (void)
1448 MonoDomain *domain = mono_domain_get ();
1449 MonoInternalThread *internal = mono_thread_internal_current ();
1450 MonoThread **current_thread_ptr;
1452 g_assert (internal);
1453 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1455 if (!*current_thread_ptr) {
1456 g_assert (domain != mono_get_root_domain ());
1457 *current_thread_ptr = new_thread_with_internal (domain, internal);
1459 return *current_thread_ptr;
1463 mono_thread_internal_current (void)
1465 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1466 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1470 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1471 int ms, HANDLE thread)
1473 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1476 mono_thread_current_check_pending_interrupt ();
1478 ensure_synch_cs_set (this);
1480 EnterCriticalSection (this->synch_cs);
1482 if ((this->state & ThreadState_Unstarted) != 0) {
1483 LeaveCriticalSection (this->synch_cs);
1485 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1489 LeaveCriticalSection (this->synch_cs);
1494 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1496 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1498 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1500 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1502 if(ret==WAIT_OBJECT_0) {
1503 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1508 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1513 /* FIXME: exitContext isnt documented */
1514 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1520 MonoObject *waitHandle;
1521 MonoInternalThread *thread = mono_thread_internal_current ();
1523 /* Do this WaitSleepJoin check before creating objects */
1524 mono_thread_current_check_pending_interrupt ();
1526 numhandles = mono_array_length(mono_handles);
1527 handles = g_new0(HANDLE, numhandles);
1529 for(i = 0; i < numhandles; i++) {
1530 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1531 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1538 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1540 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1542 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1546 if(ret==WAIT_FAILED) {
1547 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1549 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1550 /* Do we want to try again if we get
1551 * WAIT_IO_COMPLETION? The documentation for
1552 * WaitHandle doesn't give any clues. (We'd have to
1553 * fiddle with the timeout if we retry.)
1555 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1562 /* FIXME: exitContext isnt documented */
1563 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1569 MonoObject *waitHandle;
1570 MonoInternalThread *thread = mono_thread_internal_current ();
1572 /* Do this WaitSleepJoin check before creating objects */
1573 mono_thread_current_check_pending_interrupt ();
1575 numhandles = mono_array_length(mono_handles);
1576 handles = g_new0(HANDLE, numhandles);
1578 for(i = 0; i < numhandles; i++) {
1579 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1580 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1587 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1589 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1591 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1595 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1598 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1600 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1601 return ret - WAIT_OBJECT_0;
1603 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1604 return ret - WAIT_ABANDONED_0;
1611 /* FIXME: exitContext isnt documented */
1612 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1615 MonoInternalThread *thread = mono_thread_internal_current ();
1617 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1623 mono_thread_current_check_pending_interrupt ();
1625 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1627 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1629 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1631 if(ret==WAIT_FAILED) {
1632 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1634 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1635 /* Do we want to try again if we get
1636 * WAIT_IO_COMPLETION? The documentation for
1637 * WaitHandle doesn't give any clues. (We'd have to
1638 * fiddle with the timeout if we retry.)
1640 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1648 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1651 MonoInternalThread *thread = mono_thread_internal_current ();
1653 MONO_ARCH_SAVE_REGS;
1658 mono_thread_current_check_pending_interrupt ();
1660 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1662 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1664 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1666 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1669 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1673 MONO_ARCH_SAVE_REGS;
1678 mutex = CreateMutex (NULL, owned, NULL);
1680 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1682 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1690 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1691 MONO_ARCH_SAVE_REGS;
1693 return(ReleaseMutex (handle));
1696 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1702 MONO_ARCH_SAVE_REGS;
1704 *error = ERROR_SUCCESS;
1706 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1708 *error = GetLastError ();
1715 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1719 MONO_ARCH_SAVE_REGS;
1724 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1726 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1727 mono_string_chars (name));
1729 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1737 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1741 MONO_ARCH_SAVE_REGS;
1743 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1748 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1752 MONO_ARCH_SAVE_REGS;
1754 *error = ERROR_SUCCESS;
1756 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1758 *error = GetLastError ();
1764 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1768 MONO_ARCH_SAVE_REGS;
1773 event = CreateEvent (NULL, manual, initial, NULL);
1775 event = CreateEvent (NULL, manual, initial,
1776 mono_string_chars (name));
1778 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1786 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1787 MONO_ARCH_SAVE_REGS;
1789 return (SetEvent(handle));
1792 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1793 MONO_ARCH_SAVE_REGS;
1795 return (ResetEvent(handle));
1799 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1800 MONO_ARCH_SAVE_REGS;
1802 CloseHandle (handle);
1805 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1811 MONO_ARCH_SAVE_REGS;
1813 *error = ERROR_SUCCESS;
1815 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1817 *error = GetLastError ();
1823 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1825 MONO_ARCH_SAVE_REGS;
1827 return InterlockedIncrement (location);
1830 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1834 MONO_ARCH_SAVE_REGS;
1836 mono_interlocked_lock ();
1840 mono_interlocked_unlock ();
1846 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1848 MONO_ARCH_SAVE_REGS;
1850 return InterlockedDecrement(location);
1853 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1857 MONO_ARCH_SAVE_REGS;
1859 mono_interlocked_lock ();
1863 mono_interlocked_unlock ();
1868 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1870 MONO_ARCH_SAVE_REGS;
1872 return InterlockedExchange(location, value);
1875 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1878 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1879 mono_gc_wbarrier_generic_nostore (location);
1883 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1885 return InterlockedExchangePointer(location, value);
1888 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1890 IntFloatUnion val, ret;
1892 MONO_ARCH_SAVE_REGS;
1895 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1901 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1903 #if SIZEOF_VOID_P == 8
1904 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1909 * According to MSDN, this function is only atomic with regards to the
1910 * other Interlocked functions on 32 bit platforms.
1912 mono_interlocked_lock ();
1915 mono_interlocked_unlock ();
1922 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1924 #if SIZEOF_VOID_P == 8
1925 LongDoubleUnion val, ret;
1928 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1935 * According to MSDN, this function is only atomic with regards to the
1936 * other Interlocked functions on 32 bit platforms.
1938 mono_interlocked_lock ();
1941 mono_interlocked_unlock ();
1947 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1949 MONO_ARCH_SAVE_REGS;
1951 return InterlockedCompareExchange(location, value, comparand);
1954 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1957 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1958 mono_gc_wbarrier_generic_nostore (location);
1962 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1964 return InterlockedCompareExchangePointer(location, value, comparand);
1967 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1969 IntFloatUnion val, ret, cmp;
1971 MONO_ARCH_SAVE_REGS;
1974 cmp.fval = comparand;
1975 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1981 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1983 #if SIZEOF_VOID_P == 8
1984 LongDoubleUnion val, comp, ret;
1987 comp.fval = comparand;
1988 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1994 mono_interlocked_lock ();
1996 if (old == comparand)
1998 mono_interlocked_unlock ();
2005 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
2007 #if SIZEOF_VOID_P == 8
2008 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2012 mono_interlocked_lock ();
2014 if (old == comparand)
2016 mono_interlocked_unlock ();
2023 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2026 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2027 mono_gc_wbarrier_generic_nostore (location);
2032 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2035 res = InterlockedExchangePointer ((gpointer *)location, value);
2036 mono_gc_wbarrier_generic_nostore (location);
2041 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2043 #if SIZEOF_VOID_P == 8
2044 /* Should be implemented as a JIT intrinsic */
2045 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2050 mono_interlocked_lock ();
2052 *location = orig + value;
2053 mono_interlocked_unlock ();
2055 return orig + value;
2060 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2062 #if SIZEOF_VOID_P == 8
2063 /* Should be implemented as a JIT intrinsic */
2064 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2069 mono_interlocked_lock ();
2071 *location = orig + value;
2072 mono_interlocked_unlock ();
2074 return orig + value;
2079 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2081 #if SIZEOF_VOID_P == 8
2082 /* 64 bit reads are already atomic */
2087 mono_interlocked_lock ();
2089 mono_interlocked_unlock ();
2096 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2098 mono_threads_lock ();
2099 mono_threads_unlock ();
2103 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2105 mono_thread_clr_state (this, state);
2107 if (state & ThreadState_Background) {
2108 /* If the thread changes the background mode, the main thread has to
2109 * be notified, since it has to rebuild the list of threads to
2112 SetEvent (background_change_event);
2117 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2119 mono_thread_set_state (this, state);
2121 if (state & ThreadState_Background) {
2122 /* If the thread changes the background mode, the main thread has to
2123 * be notified, since it has to rebuild the list of threads to
2126 SetEvent (background_change_event);
2131 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2135 ensure_synch_cs_set (this);
2137 EnterCriticalSection (this->synch_cs);
2139 state = this->state;
2141 LeaveCriticalSection (this->synch_cs);
2146 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2148 gboolean throw = FALSE;
2150 ensure_synch_cs_set (this);
2152 if (this == mono_thread_internal_current ())
2155 EnterCriticalSection (this->synch_cs);
2157 this->thread_interrupt_requested = TRUE;
2159 if (this->state & ThreadState_WaitSleepJoin) {
2163 LeaveCriticalSection (this->synch_cs);
2166 signal_thread_state_change (this);
2170 void mono_thread_current_check_pending_interrupt ()
2172 MonoInternalThread *thread = mono_thread_internal_current ();
2173 gboolean throw = FALSE;
2175 mono_debugger_check_interruption ();
2177 ensure_synch_cs_set (thread);
2179 EnterCriticalSection (thread->synch_cs);
2181 if (thread->thread_interrupt_requested) {
2183 thread->thread_interrupt_requested = FALSE;
2186 LeaveCriticalSection (thread->synch_cs);
2189 mono_raise_exception (mono_get_exception_thread_interrupted ());
2194 mono_thread_get_abort_signal (void)
2206 static int abort_signum = -1;
2208 if (abort_signum != -1)
2209 return abort_signum;
2210 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2211 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2212 struct sigaction sinfo;
2213 sigaction (i, NULL, &sinfo);
2214 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2219 /* fallback to the old way */
2222 #endif /* HOST_WIN32 */
2226 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2228 MonoException* exc = mono_thread_request_interruption (FALSE);
2229 if (exc) mono_raise_exception (exc);
2231 #endif /* HOST_WIN32 */
2234 * signal_thread_state_change
2236 * Tells the thread that his state has changed and it has to enter the new
2237 * state as soon as possible.
2239 static void signal_thread_state_change (MonoInternalThread *thread)
2241 if (thread == mono_thread_internal_current ()) {
2242 /* Do it synchronously */
2243 MonoException *exc = mono_thread_request_interruption (FALSE);
2245 mono_raise_exception (exc);
2249 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2251 /* fixme: store the state somewhere */
2252 #ifdef PTHREAD_POINTER_ID
2253 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2255 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2259 * This will cause waits to be broken.
2260 * It will also prevent the thread from entering a wait, so if the thread returns
2261 * from the wait before it receives the abort signal, it will just spin in the wait
2262 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2265 wapi_interrupt_thread (thread->handle);
2266 #endif /* HOST_WIN32 */
2270 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2272 ensure_synch_cs_set (thread);
2274 EnterCriticalSection (thread->synch_cs);
2276 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2277 (thread->state & ThreadState_StopRequested) != 0 ||
2278 (thread->state & ThreadState_Stopped) != 0)
2280 LeaveCriticalSection (thread->synch_cs);
2284 if ((thread->state & ThreadState_Unstarted) != 0) {
2285 thread->state |= ThreadState_Aborted;
2286 LeaveCriticalSection (thread->synch_cs);
2290 thread->state |= ThreadState_AbortRequested;
2291 if (thread->abort_state_handle)
2292 mono_gchandle_free (thread->abort_state_handle);
2294 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2295 g_assert (thread->abort_state_handle);
2297 thread->abort_state_handle = 0;
2299 thread->abort_exc = NULL;
2302 * abort_exc is set in mono_thread_execute_interruption(),
2303 * triggered by the call to signal_thread_state_change(),
2304 * below. There's a point between where we have
2305 * abort_state_handle set, but abort_exc NULL, but that's not
2309 LeaveCriticalSection (thread->synch_cs);
2311 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2313 /* During shutdown, we can't wait for other threads */
2315 /* Make sure the thread is awake */
2316 mono_thread_resume (thread);
2318 signal_thread_state_change (thread);
2322 ves_icall_System_Threading_Thread_ResetAbort (void)
2324 MonoInternalThread *thread = mono_thread_internal_current ();
2325 gboolean was_aborting;
2327 ensure_synch_cs_set (thread);
2329 EnterCriticalSection (thread->synch_cs);
2330 was_aborting = thread->state & ThreadState_AbortRequested;
2331 thread->state &= ~ThreadState_AbortRequested;
2332 LeaveCriticalSection (thread->synch_cs);
2334 if (!was_aborting) {
2335 const char *msg = "Unable to reset abort because no abort was requested";
2336 mono_raise_exception (mono_get_exception_thread_state (msg));
2338 thread->abort_exc = NULL;
2339 if (thread->abort_state_handle) {
2340 mono_gchandle_free (thread->abort_state_handle);
2341 /* This is actually not necessary - the handle
2342 only counts if the exception is set */
2343 thread->abort_state_handle = 0;
2348 mono_thread_internal_reset_abort (MonoInternalThread *thread)
2350 ensure_synch_cs_set (thread);
2352 EnterCriticalSection (thread->synch_cs);
2354 thread->state &= ~ThreadState_AbortRequested;
2356 if (thread->abort_exc) {
2357 thread->abort_exc = NULL;
2358 if (thread->abort_state_handle) {
2359 mono_gchandle_free (thread->abort_state_handle);
2360 /* This is actually not necessary - the handle
2361 only counts if the exception is set */
2362 thread->abort_state_handle = 0;
2366 LeaveCriticalSection (thread->synch_cs);
2370 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2372 MonoInternalThread *thread = this->internal_thread;
2373 MonoObject *state, *deserialized = NULL, *exc;
2376 if (!thread->abort_state_handle)
2379 state = mono_gchandle_get_target (thread->abort_state_handle);
2382 domain = mono_domain_get ();
2383 if (mono_object_domain (state) == domain)
2386 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2388 if (!deserialized) {
2389 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2391 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2392 mono_raise_exception (invalid_op_exc);
2395 return deserialized;
2399 mono_thread_suspend (MonoInternalThread *thread)
2401 ensure_synch_cs_set (thread);
2403 EnterCriticalSection (thread->synch_cs);
2405 if ((thread->state & ThreadState_Unstarted) != 0 ||
2406 (thread->state & ThreadState_Aborted) != 0 ||
2407 (thread->state & ThreadState_Stopped) != 0)
2409 LeaveCriticalSection (thread->synch_cs);
2413 if ((thread->state & ThreadState_Suspended) != 0 ||
2414 (thread->state & ThreadState_SuspendRequested) != 0 ||
2415 (thread->state & ThreadState_StopRequested) != 0)
2417 LeaveCriticalSection (thread->synch_cs);
2421 thread->state |= ThreadState_SuspendRequested;
2423 LeaveCriticalSection (thread->synch_cs);
2425 signal_thread_state_change (thread);
2430 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2432 if (!mono_thread_suspend (thread))
2433 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2437 mono_thread_resume (MonoInternalThread *thread)
2439 ensure_synch_cs_set (thread);
2441 EnterCriticalSection (thread->synch_cs);
2443 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2444 thread->state &= ~ThreadState_SuspendRequested;
2445 LeaveCriticalSection (thread->synch_cs);
2449 if ((thread->state & ThreadState_Suspended) == 0 ||
2450 (thread->state & ThreadState_Unstarted) != 0 ||
2451 (thread->state & ThreadState_Aborted) != 0 ||
2452 (thread->state & ThreadState_Stopped) != 0)
2454 LeaveCriticalSection (thread->synch_cs);
2458 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2459 if (thread->resume_event == NULL) {
2460 LeaveCriticalSection (thread->synch_cs);
2464 /* Awake the thread */
2465 SetEvent (thread->suspend_event);
2467 LeaveCriticalSection (thread->synch_cs);
2469 /* Wait for the thread to awake */
2470 WaitForSingleObject (thread->resume_event, INFINITE);
2471 CloseHandle (thread->resume_event);
2472 thread->resume_event = NULL;
2478 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2480 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2481 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2485 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2490 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2491 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2492 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2494 *((gboolean*)data) = TRUE;
2501 is_running_protected_wrapper (void)
2503 gboolean found = FALSE;
2504 mono_stack_walk (find_wrapper, &found);
2508 void mono_thread_internal_stop (MonoInternalThread *thread)
2510 ensure_synch_cs_set (thread);
2512 EnterCriticalSection (thread->synch_cs);
2514 if ((thread->state & ThreadState_StopRequested) != 0 ||
2515 (thread->state & ThreadState_Stopped) != 0)
2517 LeaveCriticalSection (thread->synch_cs);
2521 /* Make sure the thread is awake */
2522 mono_thread_resume (thread);
2524 thread->state |= ThreadState_StopRequested;
2525 thread->state &= ~ThreadState_AbortRequested;
2527 LeaveCriticalSection (thread->synch_cs);
2529 signal_thread_state_change (thread);
2532 void mono_thread_stop (MonoThread *thread)
2534 mono_thread_internal_stop (thread->internal_thread);
2538 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2540 return *((volatile gint8 *) (ptr));
2544 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2546 return *((volatile gint16 *) (ptr));
2550 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2552 return *((volatile gint32 *) (ptr));
2556 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2558 return *((volatile gint64 *) (ptr));
2562 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2564 return (void *) *((volatile void **) ptr);
2568 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2570 *((volatile gint8 *) ptr) = value;
2574 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2576 *((volatile gint16 *) ptr) = value;
2580 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2582 *((volatile gint32 *) ptr) = value;
2586 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2588 *((volatile gint64 *) ptr) = value;
2592 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2594 *((volatile void **) ptr) = value;
2598 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2600 mono_gc_wbarrier_generic_store (ptr, value);
2603 void mono_thread_init (MonoThreadStartCB start_cb,
2604 MonoThreadAttachCB attach_cb)
2606 MONO_GC_REGISTER_ROOT (small_id_table);
2607 InitializeCriticalSection(&threads_mutex);
2608 InitializeCriticalSection(&interlocked_mutex);
2609 InitializeCriticalSection(&contexts_mutex);
2610 InitializeCriticalSection(&delayed_free_table_mutex);
2611 InitializeCriticalSection(&small_id_mutex);
2613 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2614 g_assert(background_change_event != NULL);
2616 mono_init_static_data_info (&thread_static_info);
2617 mono_init_static_data_info (&context_static_info);
2619 current_object_key=TlsAlloc();
2620 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2622 mono_thread_start_cb = start_cb;
2623 mono_thread_attach_cb = attach_cb;
2625 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2627 /* Get a pseudo handle to the current process. This is just a
2628 * kludge so that wapi can build a process handle if needed.
2629 * As a pseudo handle is returned, we don't need to clean
2632 GetCurrentProcess ();
2635 void mono_thread_cleanup (void)
2637 mono_thread_hazardous_try_free_all ();
2639 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2640 /* The main thread must abandon any held mutexes (particularly
2641 * important for named mutexes as they are shared across
2642 * processes, see bug 74680.) This will happen when the
2643 * thread exits, but if it's not running in a subthread it
2644 * won't exit in time.
2646 /* Using non-w32 API is a nasty kludge, but I couldn't find
2647 * anything in the documentation that would let me do this
2648 * here yet still be safe to call on windows.
2650 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2654 /* This stuff needs more testing, it seems one of these
2655 * critical sections can be locked when mono_thread_cleanup is
2658 DeleteCriticalSection (&threads_mutex);
2659 DeleteCriticalSection (&interlocked_mutex);
2660 DeleteCriticalSection (&contexts_mutex);
2661 DeleteCriticalSection (&delayed_free_table_mutex);
2662 DeleteCriticalSection (&small_id_mutex);
2663 CloseHandle (background_change_event);
2666 g_array_free (delayed_free_table, TRUE);
2667 delayed_free_table = NULL;
2669 TlsFree (current_object_key);
2673 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2675 mono_thread_cleanup_fn = func;
2679 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2681 thread->internal_thread->manage_callback = func;
2684 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2686 mono_thread_notify_pending_exc_fn = func;
2690 static void print_tids (gpointer key, gpointer value, gpointer user)
2692 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2693 * sizeof(uint) and a cast to uint would overflow
2695 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2696 * print this as a pointer.
2698 g_message ("Waiting for: %p", key);
2703 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2704 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2708 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2712 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2714 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2716 if(ret==WAIT_FAILED) {
2717 /* See the comment in build_wait_tids() */
2718 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2722 for(i=0; i<wait->num; i++)
2723 CloseHandle (wait->handles[i]);
2725 if (ret == WAIT_TIMEOUT)
2728 for(i=0; i<wait->num; i++) {
2729 gsize tid = wait->threads[i]->tid;
2731 mono_threads_lock ();
2732 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2733 /* This thread must have been killed, because
2734 * it hasn't cleaned itself up. (It's just
2735 * possible that the thread exited before the
2736 * parent thread had a chance to store the
2737 * handle, and now there is another pointer to
2738 * the already-exited thread stored. In this
2739 * case, we'll just get two
2740 * mono_profiler_thread_end() calls for the
2744 mono_threads_unlock ();
2745 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2746 thread_cleanup (wait->threads[i]);
2748 mono_threads_unlock ();
2753 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2755 guint32 i, ret, count;
2757 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2759 /* Add the thread state change event, so it wakes up if a thread changes
2760 * to background mode.
2763 if (count < MAXIMUM_WAIT_OBJECTS) {
2764 wait->handles [count] = background_change_event;
2768 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2770 if(ret==WAIT_FAILED) {
2771 /* See the comment in build_wait_tids() */
2772 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2776 for(i=0; i<wait->num; i++)
2777 CloseHandle (wait->handles[i]);
2779 if (ret == WAIT_TIMEOUT)
2782 if (ret < wait->num) {
2783 gsize tid = wait->threads[ret]->tid;
2784 mono_threads_lock ();
2785 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2786 /* See comment in wait_for_tids about thread cleanup */
2787 mono_threads_unlock ();
2788 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2789 thread_cleanup (wait->threads [ret]);
2791 mono_threads_unlock ();
2795 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2797 struct wait_data *wait=(struct wait_data *)user;
2799 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2801 MonoInternalThread *thread=(MonoInternalThread *)value;
2803 /* Ignore background threads, we abort them later */
2804 /* Do not lock here since it is not needed and the caller holds threads_lock */
2805 if (thread->state & ThreadState_Background) {
2806 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2807 return; /* just leave, ignore */
2810 if (mono_gc_is_finalizer_internal_thread (thread)) {
2811 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2815 if (thread == mono_thread_internal_current ()) {
2816 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2820 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2821 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2825 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2826 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2830 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2831 if (handle == NULL) {
2832 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2836 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2837 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2838 wait->handles[wait->num]=handle;
2839 wait->threads[wait->num]=thread;
2842 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2844 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2849 /* Just ignore the rest, we can't do anything with
2856 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2858 struct wait_data *wait=(struct wait_data *)user;
2859 gsize self = GetCurrentThreadId ();
2860 MonoInternalThread *thread = value;
2863 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2866 /* The finalizer thread is not a background thread */
2867 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2868 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2870 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2874 /* printf ("A: %d\n", wait->num); */
2875 wait->handles[wait->num]=thread->handle;
2876 wait->threads[wait->num]=thread;
2879 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2880 mono_thread_internal_stop (thread);
2884 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2888 * mono_threads_set_shutting_down:
2890 * Is called by a thread that wants to shut down Mono. If the runtime is already
2891 * shutting down, the calling thread is suspended/stopped, and this function never
2895 mono_threads_set_shutting_down (void)
2897 MonoInternalThread *current_thread = mono_thread_internal_current ();
2899 mono_threads_lock ();
2901 if (shutting_down) {
2902 mono_threads_unlock ();
2904 /* Make sure we're properly suspended/stopped */
2906 EnterCriticalSection (current_thread->synch_cs);
2908 if ((current_thread->state & ThreadState_SuspendRequested) ||
2909 (current_thread->state & ThreadState_AbortRequested) ||
2910 (current_thread->state & ThreadState_StopRequested)) {
2911 LeaveCriticalSection (current_thread->synch_cs);
2912 mono_thread_execute_interruption (current_thread);
2914 current_thread->state |= ThreadState_Stopped;
2915 LeaveCriticalSection (current_thread->synch_cs);
2918 /* Wake up other threads potentially waiting for us */
2921 shutting_down = TRUE;
2923 /* Not really a background state change, but this will
2924 * interrupt the main thread if it is waiting for all
2925 * the other threads.
2927 SetEvent (background_change_event);
2929 mono_threads_unlock ();
2934 * mono_threads_is_shutting_down:
2936 * Returns whether a thread has commenced shutdown of Mono. Note that
2937 * if the function returns FALSE the caller must not assume that
2938 * shutdown is not in progress, because the situation might have
2939 * changed since the function returned. For that reason this function
2940 * is of very limited utility.
2943 mono_threads_is_shutting_down (void)
2945 return shutting_down;
2948 void mono_thread_manage (void)
2950 struct wait_data *wait=g_new0 (struct wait_data, 1);
2952 /* join each thread that's still running */
2953 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2955 mono_threads_lock ();
2957 THREAD_DEBUG (g_message("%s: No threads", __func__));
2958 mono_threads_unlock ();
2962 mono_threads_unlock ();
2965 mono_threads_lock ();
2966 if (shutting_down) {
2967 /* somebody else is shutting down */
2968 mono_threads_unlock ();
2971 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2972 mono_g_hash_table_foreach (threads, print_tids, NULL));
2974 ResetEvent (background_change_event);
2976 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2977 mono_threads_unlock ();
2979 /* Something to wait for */
2980 wait_for_tids_or_state_change (wait, INFINITE);
2982 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2983 } while(wait->num>0);
2985 mono_threads_set_shutting_down ();
2987 /* No new threads will be created after this point */
2989 mono_runtime_set_shutting_down ();
2991 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2992 mono_thread_pool_cleanup ();
2995 * Remove everything but the finalizer thread and self.
2996 * Also abort all the background threads
2999 mono_threads_lock ();
3002 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3004 mono_threads_unlock ();
3006 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3008 /* Something to wait for */
3009 wait_for_tids (wait, INFINITE);
3011 } while (wait->num > 0);
3014 * give the subthreads a chance to really quit (this is mainly needed
3015 * to get correct user and system times from getrusage/wait/time(1)).
3016 * This could be removed if we avoid pthread_detach() and use pthread_join().
3025 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3027 MonoInternalThread *thread=(MonoInternalThread *)value;
3029 if(thread->tid != (gsize)user) {
3030 /*TerminateThread (thread->handle, -1);*/
3034 void mono_thread_abort_all_other_threads (void)
3036 gsize self = GetCurrentThreadId ();
3038 mono_threads_lock ();
3039 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3040 mono_g_hash_table_size (threads));
3041 mono_g_hash_table_foreach (threads, print_tids, NULL));
3043 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3045 mono_threads_unlock ();
3049 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3051 MonoInternalThread *thread = (MonoInternalThread*)value;
3052 struct wait_data *wait = (struct wait_data*)user_data;
3056 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3058 * This needs no locking.
3060 if ((thread->state & ThreadState_Suspended) != 0 ||
3061 (thread->state & ThreadState_Stopped) != 0)
3064 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3065 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3069 wait->handles [wait->num] = handle;
3070 wait->threads [wait->num] = thread;
3076 * mono_thread_suspend_all_other_threads:
3078 * Suspend all managed threads except the finalizer thread and this thread. It is
3079 * not possible to resume them later.
3081 void mono_thread_suspend_all_other_threads (void)
3083 struct wait_data *wait = g_new0 (struct wait_data, 1);
3085 gsize self = GetCurrentThreadId ();
3087 guint32 eventidx = 0;
3088 gboolean starting, finished;
3091 * The other threads could be in an arbitrary state at this point, i.e.
3092 * they could be starting up, shutting down etc. This means that there could be
3093 * threads which are not even in the threads hash table yet.
3097 * First we set a barrier which will be checked by all threads before they
3098 * are added to the threads hash table, and they will exit if the flag is set.
3099 * This ensures that no threads could be added to the hash later.
3100 * We will use shutting_down as the barrier for now.
3102 g_assert (shutting_down);
3105 * We make multiple calls to WaitForMultipleObjects since:
3106 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3107 * - some threads could exit without becoming suspended
3112 * Make a copy of the hashtable since we can't do anything with
3113 * threads while threads_mutex is held.
3116 mono_threads_lock ();
3117 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3118 mono_threads_unlock ();
3120 events = g_new0 (gpointer, wait->num);
3122 /* Get the suspended events that we'll be waiting for */
3123 for (i = 0; i < wait->num; ++i) {
3124 MonoInternalThread *thread = wait->threads [i];
3125 gboolean signal_suspend = FALSE;
3127 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread) || (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
3128 //CloseHandle (wait->handles [i]);
3129 wait->threads [i] = NULL; /* ignore this thread in next loop */
3133 ensure_synch_cs_set (thread);
3135 EnterCriticalSection (thread->synch_cs);
3137 if (thread->suspended_event == NULL) {
3138 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3139 if (thread->suspended_event == NULL) {
3140 /* Forget this one and go on to the next */
3141 LeaveCriticalSection (thread->synch_cs);
3146 if ((thread->state & ThreadState_Suspended) != 0 ||
3147 (thread->state & ThreadState_StopRequested) != 0 ||
3148 (thread->state & ThreadState_Stopped) != 0) {
3149 LeaveCriticalSection (thread->synch_cs);
3150 CloseHandle (wait->handles [i]);
3151 wait->threads [i] = NULL; /* ignore this thread in next loop */
3155 if ((thread->state & ThreadState_SuspendRequested) == 0)
3156 signal_suspend = TRUE;
3158 events [eventidx++] = thread->suspended_event;
3160 /* Convert abort requests into suspend requests */
3161 if ((thread->state & ThreadState_AbortRequested) != 0)
3162 thread->state &= ~ThreadState_AbortRequested;
3164 thread->state |= ThreadState_SuspendRequested;
3166 LeaveCriticalSection (thread->synch_cs);
3168 /* Signal the thread to suspend */
3170 signal_thread_state_change (thread);
3174 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3175 for (i = 0; i < wait->num; ++i) {
3176 MonoInternalThread *thread = wait->threads [i];
3181 EnterCriticalSection (thread->synch_cs);
3182 if ((thread->state & ThreadState_Suspended) != 0) {
3183 CloseHandle (thread->suspended_event);
3184 thread->suspended_event = NULL;
3186 LeaveCriticalSection (thread->synch_cs);
3190 * If there are threads which are starting up, we wait until they
3191 * are suspended when they try to register in the threads hash.
3192 * This is guaranteed to finish, since the threads which can create new
3193 * threads get suspended after a while.
3194 * FIXME: The finalizer thread can still create new threads.
3196 mono_threads_lock ();
3197 if (threads_starting_up)
3198 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3201 mono_threads_unlock ();
3215 collect_threads (gpointer key, gpointer value, gpointer user_data)
3217 MonoInternalThread *thread = (MonoInternalThread*)value;
3218 struct wait_data *wait = (struct wait_data*)user_data;
3221 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3222 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3226 wait->handles [wait->num] = handle;
3227 wait->threads [wait->num] = thread;
3233 * mono_threads_request_thread_dump:
3235 * Ask all threads except the current to print their stacktrace to stdout.
3238 mono_threads_request_thread_dump (void)
3240 struct wait_data *wait = g_new0 (struct wait_data, 1);
3244 * Make a copy of the hashtable since we can't do anything with
3245 * threads while threads_mutex is held.
3247 mono_threads_lock ();
3248 mono_g_hash_table_foreach (threads, collect_threads, wait);
3249 mono_threads_unlock ();
3251 for (i = 0; i < wait->num; ++i) {
3252 MonoInternalThread *thread = wait->threads [i];
3254 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3255 (thread != mono_thread_internal_current ()) &&
3256 !thread->thread_dump_requested) {
3257 thread->thread_dump_requested = TRUE;
3259 signal_thread_state_change (thread);
3262 CloseHandle (wait->handles [i]);
3267 * mono_thread_push_appdomain_ref:
3269 * Register that the current thread may have references to objects in domain
3270 * @domain on its stack. Each call to this function should be paired with a
3271 * call to pop_appdomain_ref.
3274 mono_thread_push_appdomain_ref (MonoDomain *domain)
3276 MonoInternalThread *thread = mono_thread_internal_current ();
3279 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3280 mono_threads_lock ();
3281 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3282 mono_threads_unlock ();
3287 mono_thread_pop_appdomain_ref (void)
3289 MonoInternalThread *thread = mono_thread_internal_current ();
3292 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3293 mono_threads_lock ();
3294 /* FIXME: How can the list be empty ? */
3295 if (thread->appdomain_refs)
3296 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3297 mono_threads_unlock ();
3302 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3305 mono_threads_lock ();
3306 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3307 mono_threads_unlock ();
3312 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3314 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3317 typedef struct abort_appdomain_data {
3318 struct wait_data wait;
3320 } abort_appdomain_data;
3323 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3325 MonoInternalThread *thread = (MonoInternalThread*)value;
3326 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3327 MonoDomain *domain = data->domain;
3329 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3330 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3332 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3333 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3336 data->wait.handles [data->wait.num] = handle;
3337 data->wait.threads [data->wait.num] = thread;
3340 /* Just ignore the rest, we can't do anything with
3348 * mono_threads_abort_appdomain_threads:
3350 * Abort threads which has references to the given appdomain.
3353 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3355 abort_appdomain_data user_data;
3357 int orig_timeout = timeout;
3360 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3362 start_time = mono_msec_ticks ();
3364 mono_threads_lock ();
3366 user_data.domain = domain;
3367 user_data.wait.num = 0;
3368 /* This shouldn't take any locks */
3369 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3370 mono_threads_unlock ();
3372 if (user_data.wait.num > 0) {
3373 /* Abort the threads outside the threads lock */
3374 for (i = 0; i < user_data.wait.num; ++i)
3375 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3378 * We should wait for the threads either to abort, or to leave the
3379 * domain. We can't do the latter, so we wait with a timeout.
3381 wait_for_tids (&user_data.wait, 100);
3384 /* Update remaining time */
3385 timeout -= mono_msec_ticks () - start_time;
3386 start_time = mono_msec_ticks ();
3388 if (orig_timeout != -1 && timeout < 0)
3391 while (user_data.wait.num > 0);
3393 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3399 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3401 MonoInternalThread *thread = (MonoInternalThread*)value;
3402 MonoDomain *domain = (MonoDomain*)user_data;
3405 /* No locking needed here */
3406 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3408 if (thread->cached_culture_info) {
3409 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3410 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3411 if (obj && obj->vtable->domain == domain)
3412 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3418 * mono_threads_clear_cached_culture:
3420 * Clear the cached_current_culture from all threads if it is in the
3424 mono_threads_clear_cached_culture (MonoDomain *domain)
3426 mono_threads_lock ();
3427 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3428 mono_threads_unlock ();
3432 * mono_thread_get_undeniable_exception:
3434 * Return an exception which needs to be raised when leaving a catch clause.
3435 * This is used for undeniable exception propagation.
3438 mono_thread_get_undeniable_exception (void)
3440 MonoInternalThread *thread = mono_thread_internal_current ();
3442 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3444 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3445 * exception if the thread no longer references a dying appdomain.
3447 thread->abort_exc->trace_ips = NULL;
3448 thread->abort_exc->stack_trace = NULL;
3449 return thread->abort_exc;
3455 #if MONO_SMALL_CONFIG
3456 #define NUM_STATIC_DATA_IDX 4
3457 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3461 #define NUM_STATIC_DATA_IDX 8
3462 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3463 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3467 static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
3471 mark_tls_slots (void *addr, MonoGCCopyFunc mark_func)
3474 gpointer *static_data = addr;
3475 for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
3478 if (!static_data [i])
3480 numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
3481 ptr = static_data [i];
3482 for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
3483 uintptr_t bmap = static_reference_bitmaps [i][j];
3486 if ((bmap & 1) && *p) {
3487 *p = mark_func (*p);
3498 * mono_alloc_static_data
3500 * Allocate memory blocks for storing threads or context static data
3503 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
3505 guint idx = (offset >> 24) - 1;
3508 gpointer* static_data = *static_data_ptr;
3510 static void* tls_desc = NULL;
3513 tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
3515 static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
3516 *static_data_ptr = static_data;
3517 static_data [0] = static_data;
3520 for (i = 1; i <= idx; ++i) {
3521 if (static_data [i])
3524 static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
3526 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3532 mono_free_static_data (gpointer* static_data, gboolean threadlocal)
3535 for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
3536 if (!static_data [i])
3540 g_free (static_data [i]);
3542 mono_gc_free_fixed (static_data [i]);
3544 mono_gc_free_fixed (static_data [i]);
3547 mono_gc_free_fixed (static_data);
3551 * mono_init_static_data_info
3553 * Initializes static data counters
3555 static void mono_init_static_data_info (StaticDataInfo *static_data)
3557 static_data->idx = 0;
3558 static_data->offset = 0;
3559 static_data->freelist = NULL;
3563 * mono_alloc_static_data_slot
3565 * Generates an offset for static data. static_data contains the counters
3566 * used to generate it.
3569 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3573 if (!static_data->idx && !static_data->offset) {
3575 * we use the first chunk of the first allocation also as
3576 * an array for the rest of the data
3578 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3580 static_data->offset += align - 1;
3581 static_data->offset &= ~(align - 1);
3582 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3583 static_data->idx ++;
3584 g_assert (size <= static_data_size [static_data->idx]);
3585 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3586 static_data->offset = 0;
3588 offset = static_data->offset | ((static_data->idx + 1) << 24);
3589 static_data->offset += size;
3594 * ensure thread static fields already allocated are valid for thread
3595 * This function is called when a thread is created or on thread attach.
3598 thread_adjust_static_data (MonoInternalThread *thread)
3602 mono_threads_lock ();
3603 if (thread_static_info.offset || thread_static_info.idx > 0) {
3604 /* get the current allocated size */
3605 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3606 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3608 mono_threads_unlock ();
3612 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3614 MonoInternalThread *thread = value;
3615 guint32 offset = GPOINTER_TO_UINT (user);
3617 mono_alloc_static_data (&(thread->static_data), offset, TRUE);
3620 static MonoThreadDomainTls*
3621 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3623 MonoThreadDomainTls* prev = NULL;
3624 MonoThreadDomainTls* tmp = static_data->freelist;
3626 if (tmp->size == size) {
3628 prev->next = tmp->next;
3630 static_data->freelist = tmp->next;
3639 update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
3642 int idx = (offset >> 24) - 1;
3644 if (!static_reference_bitmaps [idx])
3645 static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
3646 rb = static_reference_bitmaps [idx];
3648 offset /= sizeof (gpointer);
3649 /* offset is now the bitmap offset */
3650 for (i = 0; i < max_set; ++i) {
3651 if (bitmap [i / sizeof (uintptr_t)] & (1 << (i & (sizeof (uintptr_t) * 8 -1))))
3652 rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1 << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
3657 clear_reference_bitmap (guint32 offset, guint32 size)
3659 int idx = (offset >> 24) - 1;
3661 rb = static_reference_bitmaps [idx];
3663 offset /= sizeof (gpointer);
3664 size /= sizeof (gpointer);
3666 /* offset is now the bitmap offset */
3667 for (; offset < size; ++offset)
3668 rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1 << (offset & (sizeof (uintptr_t) * 8 -1)));
3672 * The offset for a special static variable is composed of three parts:
3673 * a bit that indicates the type of static data (0:thread, 1:context),
3674 * an index in the array of chunks of memory for the thread (thread->static_data)
3675 * and an offset in that chunk of mem. This allows allocating less memory in the
3680 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
3683 if (static_type == SPECIAL_STATIC_THREAD) {
3684 MonoThreadDomainTls *item;
3685 mono_threads_lock ();
3686 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3687 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3689 offset = item->offset;
3692 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3694 update_tls_reference_bitmap (offset, bitmap, max_set);
3695 /* This can be called during startup */
3696 if (threads != NULL)
3697 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3698 mono_threads_unlock ();
3700 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3701 mono_contexts_lock ();
3702 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3703 mono_contexts_unlock ();
3704 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3710 mono_get_special_static_data (guint32 offset)
3712 /* The high bit means either thread (0) or static (1) data. */
3714 guint32 static_type = (offset & 0x80000000);
3717 offset &= 0x7fffffff;
3718 idx = (offset >> 24) - 1;
3720 if (static_type == 0) {
3721 return get_thread_static_data (mono_thread_internal_current (), offset);
3723 /* Allocate static data block under demand, since we don't have a list
3726 MonoAppContext *context = mono_context_get ();
3727 if (!context->static_data || !context->static_data [idx]) {
3728 mono_contexts_lock ();
3729 mono_alloc_static_data (&(context->static_data), offset, FALSE);
3730 mono_contexts_unlock ();
3732 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3742 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3744 MonoInternalThread *thread = value;
3745 TlsOffsetSize *data = user;
3746 int idx = (data->offset >> 24) - 1;
3749 if (!thread->static_data || !thread->static_data [idx])
3751 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3752 memset (ptr, 0, data->size);
3756 do_free_special (gpointer key, gpointer value, gpointer data)
3758 MonoClassField *field = key;
3759 guint32 offset = GPOINTER_TO_UINT (value);
3760 guint32 static_type = (offset & 0x80000000);
3763 size = mono_type_size (field->type, &align);
3764 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3765 if (static_type == 0) {
3767 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3768 data.offset = offset & 0x7fffffff;
3770 clear_reference_bitmap (data.offset, data.size);
3771 if (threads != NULL)
3772 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3773 item->offset = offset;
3775 item->next = thread_static_info.freelist;
3776 thread_static_info.freelist = item;
3778 /* FIXME: free context static data as well */
3783 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3785 mono_threads_lock ();
3786 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3787 mono_threads_unlock ();
3790 static MonoClassField *local_slots = NULL;
3793 /* local tls data to get locals_slot from a thread */
3796 /* index in the locals_slot array */
3801 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3803 LocalSlotID *sid = user_data;
3804 MonoInternalThread *thread = (MonoInternalThread*)value;
3805 MonoArray *slots_array;
3807 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3808 * it is for the right domain, so we need to check if it is allocated an initialized
3809 * for the current thread.
3811 /*g_print ("handling thread %p\n", thread);*/
3812 if (!thread->static_data || !thread->static_data [sid->idx])
3814 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3815 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3817 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3821 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3829 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3831 g_warning ("local_slots field not found in Thread class");
3835 domain = mono_domain_get ();
3836 mono_domain_lock (domain);
3837 if (domain->special_static_fields)
3838 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3839 mono_domain_unlock (domain);
3842 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3843 sid.offset = GPOINTER_TO_UINT (addr);
3844 sid.offset &= 0x7fffffff;
3845 sid.idx = (sid.offset >> 24) - 1;
3846 mono_threads_lock ();
3847 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3848 mono_threads_unlock ();
3850 /* FIXME: clear the slot for MonoAppContexts, too */
3855 static void CALLBACK dummy_apc (ULONG_PTR param)
3859 static guint32 dummy_apc (gpointer param)
3866 * mono_thread_execute_interruption
3868 * Performs the operation that the requested thread state requires (abort,
3871 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3873 ensure_synch_cs_set (thread);
3875 EnterCriticalSection (thread->synch_cs);
3877 /* MonoThread::interruption_requested can only be changed with atomics */
3878 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3879 /* this will consume pending APC calls */
3880 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3881 InterlockedDecrement (&thread_interruption_requested);
3883 /* Clear the interrupted flag of the thread so it can wait again */
3884 wapi_clear_interruption ();
3888 if ((thread->state & ThreadState_AbortRequested) != 0) {
3889 LeaveCriticalSection (thread->synch_cs);
3890 if (thread->abort_exc == NULL) {
3892 * This might be racy, but it has to be called outside the lock
3893 * since it calls managed code.
3895 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3897 return thread->abort_exc;
3899 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3900 thread->state &= ~ThreadState_SuspendRequested;
3901 thread->state |= ThreadState_Suspended;
3902 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3903 if (thread->suspend_event == NULL) {
3904 LeaveCriticalSection (thread->synch_cs);
3907 if (thread->suspended_event)
3908 SetEvent (thread->suspended_event);
3910 LeaveCriticalSection (thread->synch_cs);
3912 if (shutting_down) {
3913 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3918 WaitForSingleObject (thread->suspend_event, INFINITE);
3920 EnterCriticalSection (thread->synch_cs);
3922 CloseHandle (thread->suspend_event);
3923 thread->suspend_event = NULL;
3924 thread->state &= ~ThreadState_Suspended;
3926 /* The thread that requested the resume will have replaced this event
3927 * and will be waiting for it
3929 SetEvent (thread->resume_event);
3931 LeaveCriticalSection (thread->synch_cs);
3935 else if ((thread->state & ThreadState_StopRequested) != 0) {
3936 /* FIXME: do this through the JIT? */
3938 LeaveCriticalSection (thread->synch_cs);
3940 mono_thread_exit ();
3942 } else if (thread->thread_interrupt_requested) {
3944 thread->thread_interrupt_requested = FALSE;
3945 LeaveCriticalSection (thread->synch_cs);
3947 return(mono_get_exception_thread_interrupted ());
3950 LeaveCriticalSection (thread->synch_cs);
3956 * mono_thread_request_interruption
3958 * A signal handler can call this method to request the interruption of a
3959 * thread. The result of the interruption will depend on the current state of
3960 * the thread. If the result is an exception that needs to be throw, it is
3961 * provided as return value.
3964 mono_thread_request_interruption (gboolean running_managed)
3966 MonoInternalThread *thread = mono_thread_internal_current ();
3968 /* The thread may already be stopping */
3973 if (thread->interrupt_on_stop &&
3974 thread->state & ThreadState_StopRequested &&
3975 thread->state & ThreadState_Background)
3979 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3982 if (!running_managed || is_running_protected_wrapper ()) {
3983 /* Can't stop while in unmanaged code. Increase the global interruption
3984 request count. When exiting the unmanaged method the count will be
3985 checked and the thread will be interrupted. */
3987 InterlockedIncrement (&thread_interruption_requested);
3989 if (mono_thread_notify_pending_exc_fn && !running_managed)
3990 /* The JIT will notify the thread about the interruption */
3991 /* This shouldn't take any locks */
3992 mono_thread_notify_pending_exc_fn ();
3994 /* this will awake the thread if it is in WaitForSingleObject
3996 /* Our implementation of this function ignores the func argument */
3997 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
4001 return mono_thread_execute_interruption (thread);
4005 /*This function should be called by a thread after it has exited all of
4006 * its handle blocks at interruption time.*/
4008 mono_thread_resume_interruption (void)
4010 MonoInternalThread *thread = mono_thread_internal_current ();
4011 gboolean still_aborting;
4013 /* The thread may already be stopping */
4017 ensure_synch_cs_set (thread);
4018 EnterCriticalSection (thread->synch_cs);
4019 still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
4020 LeaveCriticalSection (thread->synch_cs);
4022 /*This can happen if the protected block called Thread::ResetAbort*/
4023 if (!still_aborting)
4026 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
4028 InterlockedIncrement (&thread_interruption_requested);
4031 wapi_self_interrupt ();
4033 return mono_thread_execute_interruption (thread);
4036 gboolean mono_thread_interruption_requested ()
4038 if (thread_interruption_requested) {
4039 MonoInternalThread *thread = mono_thread_internal_current ();
4040 /* The thread may already be stopping */
4042 return (thread->interruption_requested);
4047 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
4049 MonoInternalThread *thread = mono_thread_internal_current ();
4051 /* The thread may already be stopping */
4055 mono_debugger_check_interruption ();
4057 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
4058 MonoException* exc = mono_thread_execute_interruption (thread);
4059 if (exc) mono_raise_exception (exc);
4064 * Performs the interruption of the current thread, if one has been requested,
4065 * and the thread is not running a protected wrapper.
4067 void mono_thread_interruption_checkpoint ()
4069 mono_thread_interruption_checkpoint_request (FALSE);
4073 * Performs the interruption of the current thread, if one has been requested.
4075 void mono_thread_force_interruption_checkpoint ()
4077 mono_thread_interruption_checkpoint_request (TRUE);
4081 * mono_thread_get_and_clear_pending_exception:
4083 * Return any pending exceptions for the current thread and clear it as a side effect.
4086 mono_thread_get_and_clear_pending_exception (void)
4088 MonoInternalThread *thread = mono_thread_internal_current ();
4090 /* The thread may already be stopping */
4094 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
4095 return mono_thread_execute_interruption (thread);
4098 if (thread->pending_exception) {
4099 MonoException *exc = thread->pending_exception;
4101 thread->pending_exception = NULL;
4109 * mono_set_pending_exception:
4111 * Set the pending exception of the current thread to EXC. On platforms which
4112 * support it, the exception will be thrown when execution returns to managed code.
4113 * On other platforms, this function is equivalent to mono_raise_exception ().
4114 * Internal calls which report exceptions using this function instead of
4115 * raise_exception () might be called by JITted code using a more efficient calling
4119 mono_set_pending_exception (MonoException *exc)
4121 MonoInternalThread *thread = mono_thread_internal_current ();
4123 /* The thread may already be stopping */
4127 if (mono_thread_notify_pending_exc_fn) {
4128 MONO_OBJECT_SETREF (thread, pending_exception, exc);
4130 mono_thread_notify_pending_exc_fn ();
4132 /* No way to notify the JIT about the exception, have to throw it now */
4133 mono_raise_exception (exc);
4138 * mono_thread_interruption_request_flag:
4140 * Returns the address of a flag that will be non-zero if an interruption has
4141 * been requested for a thread. The thread to interrupt may not be the current
4142 * thread, so an additional call to mono_thread_interruption_requested() or
4143 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4146 gint32* mono_thread_interruption_request_flag ()
4148 return &thread_interruption_requested;
4152 mono_thread_init_apartment_state (void)
4155 MonoInternalThread* thread = mono_thread_internal_current ();
4157 /* Positive return value indicates success, either
4158 * S_OK if this is first CoInitialize call, or
4159 * S_FALSE if CoInitialize already called, but with same
4160 * threading model. A negative value indicates failure,
4161 * probably due to trying to change the threading model.
4163 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4164 ? COINIT_APARTMENTTHREADED
4165 : COINIT_MULTITHREADED) < 0) {
4166 thread->apartment_state = ThreadApartmentState_Unknown;
4172 mono_thread_cleanup_apartment_state (void)
4175 MonoInternalThread* thread = mono_thread_internal_current ();
4177 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4184 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4186 ensure_synch_cs_set (thread);
4188 EnterCriticalSection (thread->synch_cs);
4189 thread->state |= state;
4190 LeaveCriticalSection (thread->synch_cs);
4194 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4196 ensure_synch_cs_set (thread);
4198 EnterCriticalSection (thread->synch_cs);
4199 thread->state &= ~state;
4200 LeaveCriticalSection (thread->synch_cs);
4204 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4206 gboolean ret = FALSE;
4208 ensure_synch_cs_set (thread);
4210 EnterCriticalSection (thread->synch_cs);
4212 if ((thread->state & test) != 0) {
4216 LeaveCriticalSection (thread->synch_cs);
4221 static MonoClassField *execution_context_field;
4224 get_execution_context_addr (void)
4226 MonoDomain *domain = mono_domain_get ();
4229 if (!execution_context_field) {
4230 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4232 g_assert (execution_context_field);
4235 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4237 mono_domain_lock (domain);
4238 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4239 mono_domain_unlock (domain);
4242 return (MonoObject**) mono_get_special_static_data (offset);
4246 mono_thread_get_execution_context (void)
4248 return *get_execution_context_addr ();
4252 mono_thread_set_execution_context (MonoObject *ec)
4254 *get_execution_context_addr () = ec;
4257 static gboolean has_tls_get = FALSE;
4260 mono_runtime_set_has_tls_get (gboolean val)
4266 mono_runtime_has_tls_get (void)