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_init_static_data_info (StaticDataInfo *static_data);
169 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
170 static gboolean mono_thread_resume (MonoInternalThread* thread);
171 static void mono_thread_start (MonoThread *thread);
172 static void signal_thread_state_change (MonoInternalThread *thread);
174 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread);
176 /* Spin lock for InterlockedXXX 64 bit functions */
177 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
178 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
179 static CRITICAL_SECTION interlocked_mutex;
181 /* global count of thread interruptions requested */
182 static gint32 thread_interruption_requested = 0;
184 /* Event signaled when a thread changes its background mode */
185 static HANDLE background_change_event;
187 /* The table for small ID assignment */
188 static CRITICAL_SECTION small_id_mutex;
189 static int small_id_table_size = 0;
190 static int small_id_next = 0;
191 static int highest_small_id = -1;
192 static MonoInternalThread **small_id_table = NULL;
194 /* The hazard table */
195 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
196 static volatile int hazard_table_size = 0;
197 static MonoThreadHazardPointers * volatile hazard_table = NULL;
199 /* The table where we keep pointers to blocks to be freed but that
200 have to wait because they're guarded by a hazard pointer. */
201 static CRITICAL_SECTION delayed_free_table_mutex;
202 static GArray *delayed_free_table = NULL;
204 static gboolean shutting_down = FALSE;
207 mono_thread_get_tls_key (void)
209 return current_object_key;
213 mono_thread_get_tls_offset (void)
216 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
220 /* handle_store() and handle_remove() manage the array of threads that
221 * still need to be waited for when the main thread exits.
223 * If handle_store() returns FALSE the thread must not be started
224 * because Mono is shutting down.
226 static gboolean handle_store(MonoThread *thread)
228 mono_threads_lock ();
230 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
232 if (threads_starting_up)
233 mono_g_hash_table_remove (threads_starting_up, thread);
236 mono_threads_unlock ();
241 MONO_GC_REGISTER_ROOT (threads);
242 threads=mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
245 /* We don't need to duplicate thread->handle, because it is
246 * only closed when the thread object is finalized by the GC.
248 g_assert (thread->internal_thread);
249 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->internal_thread->tid),
250 thread->internal_thread);
252 mono_threads_unlock ();
257 static gboolean handle_remove(MonoInternalThread *thread)
260 gsize tid = thread->tid;
262 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
264 mono_threads_lock ();
267 /* We have to check whether the thread object for the
268 * tid is still the same in the table because the
269 * thread might have been destroyed and the tid reused
270 * in the meantime, in which case the tid would be in
271 * the table, but with another thread object.
273 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
274 mono_g_hash_table_remove (threads, (gpointer)tid);
283 mono_threads_unlock ();
285 /* Don't close the handle here, wait for the object finalizer
286 * to do it. Otherwise, the following race condition applies:
288 * 1) Thread exits (and handle_remove() closes the handle)
290 * 2) Some other handle is reassigned the same slot
292 * 3) Another thread tries to join the first thread, and
293 * blocks waiting for the reassigned handle to be signalled
294 * (which might never happen). This is possible, because the
295 * thread calling Join() still has a reference to the first
302 * Allocate a small thread id.
304 * FIXME: The biggest part of this function is very similar to
305 * domain_id_alloc() in domain.c and should be merged.
308 small_id_alloc (MonoInternalThread *thread)
312 EnterCriticalSection (&small_id_mutex);
314 if (!small_id_table) {
315 small_id_table_size = 2;
316 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoInternalThread*), NULL);
318 for (i = small_id_next; i < small_id_table_size; ++i) {
319 if (!small_id_table [i]) {
325 for (i = 0; i < small_id_next; ++i) {
326 if (!small_id_table [i]) {
333 MonoInternalThread **new_table;
334 int new_size = small_id_table_size * 2;
335 if (new_size >= (1 << 16))
336 g_assert_not_reached ();
337 id = small_id_table_size;
338 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoInternalThread*), NULL);
339 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
340 mono_gc_free_fixed (small_id_table);
341 small_id_table = new_table;
342 small_id_table_size = new_size;
344 thread->small_id = id;
345 g_assert (small_id_table [id] == NULL);
346 small_id_table [id] = thread;
348 if (small_id_next > small_id_table_size)
351 if (id >= hazard_table_size) {
353 int pagesize = mono_pagesize ();
354 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
356 if (hazard_table == NULL) {
357 hazard_table = mono_valloc (NULL,
358 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
362 g_assert (hazard_table != NULL);
363 page_addr = (guint8*)hazard_table + num_pages * pagesize;
365 g_assert (id < HAZARD_TABLE_MAX_SIZE);
367 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
370 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
372 g_assert (id < hazard_table_size);
374 hazard_table [id].hazard_pointers [0] = NULL;
375 hazard_table [id].hazard_pointers [1] = NULL;
378 if (id > highest_small_id) {
379 highest_small_id = id;
380 mono_memory_write_barrier ();
383 LeaveCriticalSection (&small_id_mutex);
389 small_id_free (int id)
391 g_assert (id >= 0 && id < small_id_table_size);
392 g_assert (small_id_table [id] != NULL);
394 small_id_table [id] = NULL;
398 is_pointer_hazardous (gpointer p)
401 int highest = highest_small_id;
403 g_assert (highest < hazard_table_size);
405 for (i = 0; i <= highest; ++i) {
406 if (hazard_table [i].hazard_pointers [0] == p
407 || hazard_table [i].hazard_pointers [1] == p)
414 MonoThreadHazardPointers*
415 mono_hazard_pointer_get (void)
417 MonoInternalThread *current_thread = mono_thread_internal_current ();
419 if (!(current_thread && current_thread->small_id >= 0)) {
420 static MonoThreadHazardPointers emerg_hazard_table;
421 g_warning ("Thread %p may have been prematurely finalized", current_thread);
422 return &emerg_hazard_table;
425 return &hazard_table [current_thread->small_id];
429 try_free_delayed_free_item (int index)
431 if (delayed_free_table->len > index) {
432 DelayedFreeItem item = { NULL, NULL };
434 EnterCriticalSection (&delayed_free_table_mutex);
435 /* We have to check the length again because another
436 thread might have freed an item before we acquired
438 if (delayed_free_table->len > index) {
439 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
441 if (!is_pointer_hazardous (item.p))
442 g_array_remove_index_fast (delayed_free_table, index);
446 LeaveCriticalSection (&delayed_free_table_mutex);
449 item.free_func (item.p);
454 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
458 /* First try to free a few entries in the delayed free
460 for (i = 2; i >= 0; --i)
461 try_free_delayed_free_item (i);
463 /* Now see if the pointer we're freeing is hazardous. If it
464 isn't, free it. Otherwise put it in the delay list. */
465 if (is_pointer_hazardous (p)) {
466 DelayedFreeItem item = { p, free_func };
468 ++mono_stats.hazardous_pointer_count;
470 EnterCriticalSection (&delayed_free_table_mutex);
471 g_array_append_val (delayed_free_table, item);
472 LeaveCriticalSection (&delayed_free_table_mutex);
478 mono_thread_hazardous_try_free_all (void)
483 if (!delayed_free_table)
486 len = delayed_free_table->len;
488 for (i = len - 1; i >= 0; --i)
489 try_free_delayed_free_item (i);
492 static void ensure_synch_cs_set (MonoInternalThread *thread)
494 CRITICAL_SECTION *synch_cs;
496 if (thread->synch_cs != NULL) {
500 synch_cs = g_new0 (CRITICAL_SECTION, 1);
501 InitializeCriticalSection (synch_cs);
503 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
504 synch_cs, NULL) != NULL) {
505 /* Another thread must have installed this CS */
506 DeleteCriticalSection (synch_cs);
512 * NOTE: this function can be called also for threads different from the current one:
513 * make sure no code called from it will ever assume it is run on the thread that is
514 * getting cleaned up.
516 static void thread_cleanup (MonoInternalThread *thread)
518 g_assert (thread != NULL);
520 if (thread->abort_state_handle) {
521 g_assert (thread->abort_exc);
522 mono_gchandle_free (thread->abort_state_handle);
523 thread->abort_state_handle = 0;
525 thread->abort_exc = NULL;
526 thread->current_appcontext = NULL;
529 * This is necessary because otherwise we might have
530 * cross-domain references which will not get cleaned up when
531 * the target domain is unloaded.
533 if (thread->cached_culture_info) {
535 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i)
536 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
539 /* if the thread is not in the hash it has been removed already */
540 if (!handle_remove (thread))
542 mono_release_type_locks (thread);
544 EnterCriticalSection (thread->synch_cs);
546 thread->state |= ThreadState_Stopped;
547 thread->state &= ~ThreadState_Background;
549 LeaveCriticalSection (thread->synch_cs);
551 mono_profiler_thread_end (thread->tid);
553 if (thread == mono_thread_internal_current ())
554 mono_thread_pop_appdomain_ref ();
556 thread->cached_culture_info = NULL;
558 mono_gc_free_fixed (thread->static_data);
559 thread->static_data = NULL;
561 if (mono_thread_cleanup_fn)
562 mono_thread_cleanup_fn (thread->root_domain_thread);
564 small_id_free (thread->small_id);
565 thread->small_id = -2;
569 get_thread_static_data (MonoInternalThread *thread, guint32 offset)
572 g_assert ((offset & 0x80000000) == 0);
573 offset &= 0x7fffffff;
574 idx = (offset >> 24) - 1;
575 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
579 get_current_thread_ptr_for_domain (MonoDomain *domain, MonoInternalThread *thread)
581 static MonoClassField *current_thread_field = NULL;
585 if (!current_thread_field) {
586 current_thread_field = mono_class_get_field_from_name (mono_defaults.thread_class, "current_thread");
587 g_assert (current_thread_field);
590 mono_class_vtable (domain, mono_defaults.thread_class);
591 mono_domain_lock (domain);
592 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, current_thread_field));
593 mono_domain_unlock (domain);
596 return get_thread_static_data (thread, offset);
600 set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, MonoThread *current)
602 MonoThread **current_thread_ptr = get_current_thread_ptr_for_domain (domain, thread);
604 g_assert (current->obj.vtable->domain == domain);
606 g_assert (!*current_thread_ptr);
607 *current_thread_ptr = current;
611 new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
613 MonoThread *thread = (MonoThread*) mono_object_new (domain, mono_defaults.thread_class);
614 MONO_OBJECT_SETREF (thread, internal_thread, internal);
619 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
621 MonoDomain *domain = mono_get_root_domain ();
623 if (!candidate || candidate->obj.vtable->domain != domain)
624 candidate = new_thread_with_internal (domain, thread);
625 set_current_thread_for_domain (domain, thread, candidate);
626 g_assert (!thread->root_domain_thread);
627 MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
630 static guint32 WINAPI start_wrapper(void *data)
632 struct StartInfo *start_info=(struct StartInfo *)data;
633 guint32 (*start_func)(void *);
636 MonoThread *thread=start_info->obj;
637 MonoInternalThread *internal = thread->internal_thread;
638 MonoObject *start_delegate = start_info->delegate;
640 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
642 /* We can be sure start_info->obj->tid and
643 * start_info->obj->handle have been set, because the thread
644 * was created suspended, and these values were set before the
650 SET_CURRENT_OBJECT (internal);
652 mono_monitor_init_tls ();
654 /* Every thread references the appdomain which created it */
655 mono_thread_push_appdomain_ref (thread->obj.vtable->domain);
657 if (!mono_domain_set (thread->obj.vtable->domain, FALSE)) {
658 /* No point in raising an appdomain_unloaded exception here */
659 /* FIXME: Cleanup here */
660 mono_thread_pop_appdomain_ref ();
664 start_func = start_info->func;
665 start_arg = start_info->start_arg;
667 /* We have to do this here because mono_thread_new_init()
668 requires that root_domain_thread is set up. */
669 thread_adjust_static_data (internal);
670 init_root_domain_thread (internal, thread);
672 /* This MUST be called before any managed code can be
673 * executed, as it calls the callback function that (for the
674 * jit) sets the lmf marker.
676 mono_thread_new_init (tid, &tid, start_func);
677 internal->stack_ptr = &tid;
679 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
681 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
683 /* On 2.0 profile (and higher), set explicitly since state might have been
685 if (mono_framework_version () != 1) {
686 if (internal->apartment_state == ThreadApartmentState_Unknown)
687 internal->apartment_state = ThreadApartmentState_MTA;
690 mono_thread_init_apartment_state ();
692 if(internal->start_notify!=NULL) {
693 /* Let the thread that called Start() know we're
696 ReleaseSemaphore (internal->start_notify, 1, NULL);
699 mono_threads_lock ();
700 mono_g_hash_table_remove (thread_start_args, thread);
701 mono_threads_unlock ();
705 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
709 mono_thread_set_execution_context (thread->ec_to_set);
710 thread->ec_to_set = NULL;
713 * Call this after calling start_notify, since the profiler callback might want
714 * to lock the thread, and the lock is held by thread_start () which waits for
717 mono_profiler_thread_start (tid);
719 /* start_func is set only for unmanaged start functions */
721 start_func (start_arg);
724 g_assert (start_delegate != NULL);
725 args [0] = start_arg;
726 /* we may want to handle the exception here. See comment below on unhandled exceptions */
727 mono_runtime_delegate_invoke (start_delegate, args, NULL);
730 /* If the thread calls ExitThread at all, this remaining code
731 * will not be executed, but the main thread will eventually
732 * call thread_cleanup() on this thread's behalf.
735 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
737 thread_cleanup (internal);
739 /* Do any cleanup needed for apartment state. This
740 * cannot be done in thread_cleanup since thread_cleanup could be
741 * called for a thread other than the current thread.
742 * mono_thread_cleanup_apartment_state cleans up apartment
743 * for the current thead */
744 mono_thread_cleanup_apartment_state ();
746 /* Remove the reference to the thread object in the TLS data,
747 * so the thread object can be finalized. This won't be
748 * reached if the thread threw an uncaught exception, so those
749 * thread handles will stay referenced :-( (This is due to
750 * missing support for scanning thread-specific data in the
751 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
754 SET_CURRENT_OBJECT (NULL);
755 mono_domain_unset ();
760 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
762 if (mono_thread_start_cb) {
763 mono_thread_start_cb (tid, stack_start, func);
767 void mono_threads_set_default_stacksize (guint32 stacksize)
769 default_stacksize = stacksize;
772 guint32 mono_threads_get_default_stacksize (void)
774 return default_stacksize;
778 * mono_create_thread:
780 * This is a wrapper around CreateThread which handles differences in the type of
781 * the the 'tid' argument.
783 gpointer mono_create_thread (WapiSecurityAttributes *security,
784 guint32 stacksize, WapiThreadStart start,
785 gpointer param, guint32 create, gsize *tid)
792 res = CreateThread (security, stacksize, start, param, create, &real_tid);
796 res = CreateThread (security, stacksize, start, param, create, tid);
803 * The thread start argument may be an object reference, and there is
804 * no ref to keep it alive when the new thread is started but not yet
805 * registered with the collector. So we store it in a GC tracked hash
808 * LOCKING: Assumes the threads lock is held.
811 register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
813 if (thread_start_args == NULL) {
814 MONO_GC_REGISTER_ROOT (thread_start_args);
815 thread_start_args = mono_g_hash_table_new (NULL, NULL);
817 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
820 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
823 MonoInternalThread *internal;
824 HANDLE thread_handle;
825 struct StartInfo *start_info;
828 thread=(MonoThread *)mono_object_new (domain,
829 mono_defaults.thread_class);
830 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
831 mono_defaults.internal_thread_class);
832 MONO_OBJECT_SETREF (thread, internal_thread, internal);
834 start_info=g_new0 (struct StartInfo, 1);
835 start_info->func = func;
836 start_info->obj = thread;
837 start_info->start_arg = arg;
839 mono_threads_lock ();
841 mono_threads_unlock ();
845 if (threads_starting_up == NULL) {
846 MONO_GC_REGISTER_ROOT (threads_starting_up);
847 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
850 register_thread_start_argument (thread, start_info);
851 mono_g_hash_table_insert (threads_starting_up, thread, thread);
852 mono_threads_unlock ();
854 /* Create suspended, so we can do some housekeeping before the thread
857 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
858 CREATE_SUSPENDED, &tid);
859 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
860 if (thread_handle == NULL) {
861 /* The thread couldn't be created, so throw an exception */
862 mono_threads_lock ();
863 mono_g_hash_table_remove (threads_starting_up, thread);
864 mono_threads_unlock ();
866 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
870 internal->handle=thread_handle;
872 internal->apartment_state=ThreadApartmentState_Unknown;
873 small_id_alloc (internal);
875 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
876 InitializeCriticalSection (internal->synch_cs);
878 internal->threadpool_thread = threadpool_thread;
879 if (threadpool_thread)
880 mono_thread_set_state (internal, ThreadState_Background);
882 if (handle_store (thread))
883 ResumeThread (thread_handle);
889 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
891 mono_thread_create_internal (domain, func, arg, FALSE);
895 * mono_thread_get_stack_bounds:
897 * Return the address and size of the current threads stack. Return NULL as the
898 * stack address if the stack address cannot be determined.
901 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
903 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
904 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
905 *stsize = pthread_get_stacksize_np (pthread_self ());
906 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
908 /* FIXME: simplify the mess below */
909 #elif !defined(HOST_WIN32)
911 guint8 *current = (guint8*)&attr;
913 pthread_attr_init (&attr);
914 # ifdef HAVE_PTHREAD_GETATTR_NP
915 pthread_getattr_np (pthread_self(), &attr);
917 # ifdef HAVE_PTHREAD_ATTR_GET_NP
918 pthread_attr_get_np (pthread_self(), &attr);
921 pthread_attr_getstacksize (&attr, &stsize);
930 pthread_attr_getstack (&attr, (void**)staddr, stsize);
932 g_assert ((current > *staddr) && (current < *staddr + *stsize));
935 pthread_attr_destroy (&attr);
938 /* When running under emacs, sometimes staddr is not aligned to a page size */
939 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
943 mono_thread_attach (MonoDomain *domain)
945 MonoInternalThread *thread;
946 MonoThread *current_thread;
947 HANDLE thread_handle;
950 if ((thread = mono_thread_internal_current ())) {
951 if (domain != mono_domain_get ())
952 mono_domain_set (domain, TRUE);
953 /* Already attached */
954 return mono_thread_current ();
957 if (!mono_gc_register_thread (&domain)) {
958 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 ());
961 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
963 thread_handle = GetCurrentThread ();
964 g_assert (thread_handle);
966 tid=GetCurrentThreadId ();
969 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
970 * refer to the thread from other threads for things like aborting.
972 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
973 THREAD_ALL_ACCESS, TRUE, 0);
975 thread->handle=thread_handle;
977 thread->apartment_state=ThreadApartmentState_Unknown;
978 small_id_alloc (thread);
979 thread->stack_ptr = &tid;
981 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
982 InitializeCriticalSection (thread->synch_cs);
984 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
986 current_thread = new_thread_with_internal (domain, thread);
988 if (!handle_store (current_thread)) {
989 /* Mono is shutting down, so just wait for the end */
994 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
996 SET_CURRENT_OBJECT (thread);
997 mono_domain_set (domain, TRUE);
999 mono_monitor_init_tls ();
1001 thread_adjust_static_data (thread);
1003 init_root_domain_thread (thread, current_thread);
1004 if (domain != mono_get_root_domain ())
1005 set_current_thread_for_domain (domain, thread, current_thread);
1008 if (mono_thread_attach_cb) {
1012 mono_thread_get_stack_bounds (&staddr, &stsize);
1015 mono_thread_attach_cb (tid, &tid);
1017 mono_thread_attach_cb (tid, staddr + stsize);
1020 // FIXME: Need a separate callback
1021 mono_profiler_thread_start (tid);
1023 return current_thread;
1027 mono_thread_detach (MonoThread *thread)
1029 g_return_if_fail (thread != NULL);
1031 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1033 thread_cleanup (thread->internal_thread);
1035 SET_CURRENT_OBJECT (NULL);
1036 mono_domain_unset ();
1038 /* Don't need to CloseHandle this thread, even though we took a
1039 * reference in mono_thread_attach (), because the GC will do it
1040 * when the Thread object is finalised.
1047 MonoInternalThread *thread = mono_thread_internal_current ();
1049 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1051 thread_cleanup (thread);
1052 SET_CURRENT_OBJECT (NULL);
1053 mono_domain_unset ();
1055 /* we could add a callback here for embedders to use. */
1056 if (thread == mono_thread_get_main ()->internal_thread)
1057 exit (mono_environment_exitcode_get ());
1062 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1064 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1065 internal->state = ThreadState_Unstarted;
1066 internal->apartment_state = ThreadApartmentState_Unknown;
1068 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1071 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1074 guint32 (*start_func)(void *);
1075 struct StartInfo *start_info;
1078 MonoInternalThread *internal;
1080 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1082 if (!this->internal_thread)
1083 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1084 internal = this->internal_thread;
1086 ensure_synch_cs_set (internal);
1088 EnterCriticalSection (internal->synch_cs);
1090 if ((internal->state & ThreadState_Unstarted) == 0) {
1091 LeaveCriticalSection (internal->synch_cs);
1092 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1096 internal->small_id = -1;
1098 if ((internal->state & ThreadState_Aborted) != 0) {
1099 LeaveCriticalSection (internal->synch_cs);
1104 /* This is freed in start_wrapper */
1105 start_info = g_new0 (struct StartInfo, 1);
1106 start_info->func = start_func;
1107 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1108 start_info->delegate = start;
1109 start_info->obj = this;
1110 g_assert (this->obj.vtable->domain == mono_domain_get ());
1112 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1113 if (internal->start_notify==NULL) {
1114 LeaveCriticalSection (internal->synch_cs);
1115 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1116 g_free (start_info);
1120 mono_threads_lock ();
1121 register_thread_start_argument (this, start_info);
1122 if (threads_starting_up == NULL) {
1123 MONO_GC_REGISTER_ROOT (threads_starting_up);
1124 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
1126 mono_g_hash_table_insert (threads_starting_up, this, this);
1127 mono_threads_unlock ();
1129 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1130 CREATE_SUSPENDED, &tid);
1132 LeaveCriticalSection (internal->synch_cs);
1133 mono_threads_lock ();
1134 mono_g_hash_table_remove (threads_starting_up, this);
1135 mono_threads_unlock ();
1136 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1140 internal->handle=thread;
1142 small_id_alloc (internal);
1144 /* Don't call handle_store() here, delay it to Start.
1145 * We can't join a thread (trying to will just block
1146 * forever) until it actually starts running, so don't
1147 * store the handle till then.
1150 mono_thread_start (this);
1152 internal->state &= ~ThreadState_Unstarted;
1154 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1156 LeaveCriticalSection (internal->synch_cs);
1161 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1163 MONO_ARCH_SAVE_REGS;
1165 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1168 CloseHandle (thread);
1170 if (this->synch_cs) {
1171 DeleteCriticalSection (this->synch_cs);
1172 g_free (this->synch_cs);
1173 this->synch_cs = NULL;
1176 g_assert (!this->abort_exc && !this->abort_state_handle);
1178 g_free (this->name);
1181 static void mono_thread_start (MonoThread *thread)
1183 MonoInternalThread *internal = thread->internal_thread;
1185 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1187 /* Only store the handle when the thread is about to be
1188 * launched, to avoid the main thread deadlocking while trying
1189 * to clean up a thread that will never be signalled.
1191 if (!handle_store (thread))
1194 ResumeThread (internal->handle);
1196 if(internal->start_notify!=NULL) {
1197 /* Wait for the thread to set up its TLS data etc, so
1198 * theres no potential race condition if someone tries
1199 * to look up the data believing the thread has
1203 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1205 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1206 CloseHandle (internal->start_notify);
1207 internal->start_notify = NULL;
1210 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1213 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1216 MonoInternalThread *thread = mono_thread_internal_current ();
1218 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1220 mono_thread_current_check_pending_interrupt ();
1222 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1224 res = SleepEx(ms,TRUE);
1226 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1228 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1229 MonoException* exc = mono_thread_execute_interruption (thread);
1230 if (exc) mono_raise_exception (exc);
1234 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1239 ves_icall_System_Threading_Thread_GetDomainID (void)
1241 MONO_ARCH_SAVE_REGS;
1243 return mono_domain_get()->domain_id;
1247 * mono_thread_get_name:
1249 * Return the name of the thread. NAME_LEN is set to the length of the name.
1250 * Return NULL if the thread has no name. The returned memory is owned by the
1254 mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
1258 ensure_synch_cs_set (this_obj);
1260 EnterCriticalSection (this_obj->synch_cs);
1262 if (!this_obj->name) {
1266 *name_len = this_obj->name_len;
1267 res = g_new (gunichar2, this_obj->name_len);
1268 memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
1271 LeaveCriticalSection (this_obj->synch_cs);
1277 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1281 ensure_synch_cs_set (this_obj);
1283 EnterCriticalSection (this_obj->synch_cs);
1285 if (!this_obj->name)
1288 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1290 LeaveCriticalSection (this_obj->synch_cs);
1296 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1298 ensure_synch_cs_set (this_obj);
1300 EnterCriticalSection (this_obj->synch_cs);
1302 if (this_obj->name) {
1303 LeaveCriticalSection (this_obj->synch_cs);
1305 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1309 this_obj->name = g_new (gunichar2, mono_string_length (name));
1310 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1311 this_obj->name_len = mono_string_length (name);
1314 this_obj->name = NULL;
1316 LeaveCriticalSection (this_obj->synch_cs);
1320 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1325 if (this->cached_culture_info) {
1326 domain = mono_domain_get ();
1327 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1328 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1329 if (res && res->vtable->domain == domain)
1337 /* If the array is already in the requested domain, we just return it,
1338 otherwise we return a copy in that domain. */
1340 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1347 if (mono_object_domain (arr) == domain)
1350 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1351 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1356 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1358 return byte_array_to_domain (arr, mono_get_root_domain ());
1362 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1364 return byte_array_to_domain (arr, mono_domain_get ());
1368 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1370 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1374 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1377 MonoDomain *domain = mono_domain_get ();
1380 int same_domain_slot = -1;
1382 ensure_synch_cs_set (this);
1384 EnterCriticalSection (this->synch_cs);
1386 if (!this->cached_culture_info)
1387 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1389 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1390 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1394 /* we continue, because there may be a slot used with the same domain */
1398 if (obj->vtable->domain == domain) {
1399 same_domain_slot = i;
1403 if (same_domain_slot >= 0)
1404 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1405 else if (free_slot >= 0)
1406 mono_array_setref (this->cached_culture_info, free_slot, culture);
1407 /* we may want to replace an existing entry here, even when no suitable slot is found */
1409 LeaveCriticalSection (this->synch_cs);
1413 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1415 MonoDomain *domain = mono_object_get_domain (&this->obj);
1416 g_assert (domain == mono_domain_get ());
1417 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1421 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1423 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1427 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1429 MonoDomain *domain = mono_object_get_domain (&this->obj);
1430 g_assert (domain == mono_domain_get ());
1431 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1435 mono_thread_current (void)
1437 MonoDomain *domain = mono_domain_get ();
1438 MonoInternalThread *internal = mono_thread_internal_current ();
1439 MonoThread **current_thread_ptr;
1441 g_assert (internal);
1442 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1444 if (!*current_thread_ptr) {
1445 g_assert (domain != mono_get_root_domain ());
1446 *current_thread_ptr = new_thread_with_internal (domain, internal);
1448 return *current_thread_ptr;
1452 mono_thread_internal_current (void)
1454 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1455 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1459 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1460 int ms, HANDLE thread)
1462 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1465 mono_thread_current_check_pending_interrupt ();
1467 ensure_synch_cs_set (this);
1469 EnterCriticalSection (this->synch_cs);
1471 if ((this->state & ThreadState_Unstarted) != 0) {
1472 LeaveCriticalSection (this->synch_cs);
1474 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1478 LeaveCriticalSection (this->synch_cs);
1483 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1485 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1487 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1489 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1491 if(ret==WAIT_OBJECT_0) {
1492 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1497 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1502 /* FIXME: exitContext isnt documented */
1503 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1509 MonoObject *waitHandle;
1510 MonoInternalThread *thread = mono_thread_internal_current ();
1512 /* Do this WaitSleepJoin check before creating objects */
1513 mono_thread_current_check_pending_interrupt ();
1515 numhandles = mono_array_length(mono_handles);
1516 handles = g_new0(HANDLE, numhandles);
1518 for(i = 0; i < numhandles; i++) {
1519 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1520 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1527 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1529 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1531 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1535 if(ret==WAIT_FAILED) {
1536 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1538 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1539 /* Do we want to try again if we get
1540 * WAIT_IO_COMPLETION? The documentation for
1541 * WaitHandle doesn't give any clues. (We'd have to
1542 * fiddle with the timeout if we retry.)
1544 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1551 /* FIXME: exitContext isnt documented */
1552 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1558 MonoObject *waitHandle;
1559 MonoInternalThread *thread = mono_thread_internal_current ();
1561 /* Do this WaitSleepJoin check before creating objects */
1562 mono_thread_current_check_pending_interrupt ();
1564 numhandles = mono_array_length(mono_handles);
1565 handles = g_new0(HANDLE, numhandles);
1567 for(i = 0; i < numhandles; i++) {
1568 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1569 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1576 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1578 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1580 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1584 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1587 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1589 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1590 return ret - WAIT_OBJECT_0;
1592 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1593 return ret - WAIT_ABANDONED_0;
1600 /* FIXME: exitContext isnt documented */
1601 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1604 MonoInternalThread *thread = mono_thread_internal_current ();
1606 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1612 mono_thread_current_check_pending_interrupt ();
1614 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1616 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1618 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1620 if(ret==WAIT_FAILED) {
1621 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1623 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1624 /* Do we want to try again if we get
1625 * WAIT_IO_COMPLETION? The documentation for
1626 * WaitHandle doesn't give any clues. (We'd have to
1627 * fiddle with the timeout if we retry.)
1629 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1637 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1640 MonoInternalThread *thread = mono_thread_internal_current ();
1642 MONO_ARCH_SAVE_REGS;
1647 mono_thread_current_check_pending_interrupt ();
1649 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1651 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1653 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1655 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1658 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1662 MONO_ARCH_SAVE_REGS;
1667 mutex = CreateMutex (NULL, owned, NULL);
1669 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1671 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1679 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1680 MONO_ARCH_SAVE_REGS;
1682 return(ReleaseMutex (handle));
1685 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1691 MONO_ARCH_SAVE_REGS;
1693 *error = ERROR_SUCCESS;
1695 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1697 *error = GetLastError ();
1704 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1708 MONO_ARCH_SAVE_REGS;
1713 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1715 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1716 mono_string_chars (name));
1718 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1726 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1730 MONO_ARCH_SAVE_REGS;
1732 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1737 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1741 MONO_ARCH_SAVE_REGS;
1743 *error = ERROR_SUCCESS;
1745 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1747 *error = GetLastError ();
1753 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1757 MONO_ARCH_SAVE_REGS;
1762 event = CreateEvent (NULL, manual, initial, NULL);
1764 event = CreateEvent (NULL, manual, initial,
1765 mono_string_chars (name));
1767 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1775 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1776 MONO_ARCH_SAVE_REGS;
1778 return (SetEvent(handle));
1781 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1782 MONO_ARCH_SAVE_REGS;
1784 return (ResetEvent(handle));
1788 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1789 MONO_ARCH_SAVE_REGS;
1791 CloseHandle (handle);
1794 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1800 MONO_ARCH_SAVE_REGS;
1802 *error = ERROR_SUCCESS;
1804 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1806 *error = GetLastError ();
1812 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1814 MONO_ARCH_SAVE_REGS;
1816 return InterlockedIncrement (location);
1819 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1823 MONO_ARCH_SAVE_REGS;
1825 mono_interlocked_lock ();
1829 mono_interlocked_unlock ();
1835 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1837 MONO_ARCH_SAVE_REGS;
1839 return InterlockedDecrement(location);
1842 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1846 MONO_ARCH_SAVE_REGS;
1848 mono_interlocked_lock ();
1852 mono_interlocked_unlock ();
1857 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1859 MONO_ARCH_SAVE_REGS;
1861 return InterlockedExchange(location, value);
1864 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1867 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1868 mono_gc_wbarrier_generic_nostore (location);
1872 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1874 return InterlockedExchangePointer(location, value);
1877 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1879 IntFloatUnion val, ret;
1881 MONO_ARCH_SAVE_REGS;
1884 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1890 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1892 #if SIZEOF_VOID_P == 8
1893 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1898 * According to MSDN, this function is only atomic with regards to the
1899 * other Interlocked functions on 32 bit platforms.
1901 mono_interlocked_lock ();
1904 mono_interlocked_unlock ();
1911 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1913 #if SIZEOF_VOID_P == 8
1914 LongDoubleUnion val, ret;
1917 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1924 * According to MSDN, this function is only atomic with regards to the
1925 * other Interlocked functions on 32 bit platforms.
1927 mono_interlocked_lock ();
1930 mono_interlocked_unlock ();
1936 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1938 MONO_ARCH_SAVE_REGS;
1940 return InterlockedCompareExchange(location, value, comparand);
1943 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1946 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1947 mono_gc_wbarrier_generic_nostore (location);
1951 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1953 return InterlockedCompareExchangePointer(location, value, comparand);
1956 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1958 IntFloatUnion val, ret, cmp;
1960 MONO_ARCH_SAVE_REGS;
1963 cmp.fval = comparand;
1964 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1970 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1972 #if SIZEOF_VOID_P == 8
1973 LongDoubleUnion val, comp, ret;
1976 comp.fval = comparand;
1977 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1983 mono_interlocked_lock ();
1985 if (old == comparand)
1987 mono_interlocked_unlock ();
1994 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1996 #if SIZEOF_VOID_P == 8
1997 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
2001 mono_interlocked_lock ();
2003 if (old == comparand)
2005 mono_interlocked_unlock ();
2012 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
2015 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
2016 mono_gc_wbarrier_generic_nostore (location);
2021 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
2024 res = InterlockedExchangePointer ((gpointer *)location, value);
2025 mono_gc_wbarrier_generic_nostore (location);
2030 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
2032 #if SIZEOF_VOID_P == 8
2033 /* Should be implemented as a JIT intrinsic */
2034 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2039 mono_interlocked_lock ();
2041 *location = orig + value;
2042 mono_interlocked_unlock ();
2044 return orig + value;
2049 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
2051 #if SIZEOF_VOID_P == 8
2052 /* Should be implemented as a JIT intrinsic */
2053 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2058 mono_interlocked_lock ();
2060 *location = orig + value;
2061 mono_interlocked_unlock ();
2063 return orig + value;
2068 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2070 #if SIZEOF_VOID_P == 8
2071 /* 64 bit reads are already atomic */
2076 mono_interlocked_lock ();
2078 mono_interlocked_unlock ();
2085 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2087 mono_threads_lock ();
2088 mono_threads_unlock ();
2092 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2094 mono_thread_clr_state (this, state);
2096 if (state & ThreadState_Background) {
2097 /* If the thread changes the background mode, the main thread has to
2098 * be notified, since it has to rebuild the list of threads to
2101 SetEvent (background_change_event);
2106 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2108 mono_thread_set_state (this, state);
2110 if (state & ThreadState_Background) {
2111 /* If the thread changes the background mode, the main thread has to
2112 * be notified, since it has to rebuild the list of threads to
2115 SetEvent (background_change_event);
2120 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2124 ensure_synch_cs_set (this);
2126 EnterCriticalSection (this->synch_cs);
2128 state = this->state;
2130 LeaveCriticalSection (this->synch_cs);
2135 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2137 gboolean throw = FALSE;
2139 ensure_synch_cs_set (this);
2141 if (this == mono_thread_internal_current ())
2144 EnterCriticalSection (this->synch_cs);
2146 this->thread_interrupt_requested = TRUE;
2148 if (this->state & ThreadState_WaitSleepJoin) {
2152 LeaveCriticalSection (this->synch_cs);
2155 signal_thread_state_change (this);
2159 void mono_thread_current_check_pending_interrupt ()
2161 MonoInternalThread *thread = mono_thread_internal_current ();
2162 gboolean throw = FALSE;
2164 mono_debugger_check_interruption ();
2166 ensure_synch_cs_set (thread);
2168 EnterCriticalSection (thread->synch_cs);
2170 if (thread->thread_interrupt_requested) {
2172 thread->thread_interrupt_requested = FALSE;
2175 LeaveCriticalSection (thread->synch_cs);
2178 mono_raise_exception (mono_get_exception_thread_interrupted ());
2183 mono_thread_get_abort_signal (void)
2195 static int abort_signum = -1;
2197 if (abort_signum != -1)
2198 return abort_signum;
2199 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2200 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2201 struct sigaction sinfo;
2202 sigaction (i, NULL, &sinfo);
2203 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2208 /* fallback to the old way */
2211 #endif /* HOST_WIN32 */
2215 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2217 MonoException* exc = mono_thread_request_interruption (FALSE);
2218 if (exc) mono_raise_exception (exc);
2220 #endif /* HOST_WIN32 */
2223 * signal_thread_state_change
2225 * Tells the thread that his state has changed and it has to enter the new
2226 * state as soon as possible.
2228 static void signal_thread_state_change (MonoInternalThread *thread)
2230 if (thread == mono_thread_internal_current ()) {
2231 /* Do it synchronously */
2232 MonoException *exc = mono_thread_request_interruption (FALSE);
2234 mono_raise_exception (exc);
2238 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2240 /* fixme: store the state somewhere */
2241 #ifdef PTHREAD_POINTER_ID
2242 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2244 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2248 * This will cause waits to be broken.
2249 * It will also prevent the thread from entering a wait, so if the thread returns
2250 * from the wait before it receives the abort signal, it will just spin in the wait
2251 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2254 wapi_interrupt_thread (thread->handle);
2255 #endif /* HOST_WIN32 */
2259 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2261 ensure_synch_cs_set (thread);
2263 EnterCriticalSection (thread->synch_cs);
2265 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2266 (thread->state & ThreadState_StopRequested) != 0 ||
2267 (thread->state & ThreadState_Stopped) != 0)
2269 LeaveCriticalSection (thread->synch_cs);
2273 if ((thread->state & ThreadState_Unstarted) != 0) {
2274 thread->state |= ThreadState_Aborted;
2275 LeaveCriticalSection (thread->synch_cs);
2279 thread->state |= ThreadState_AbortRequested;
2280 if (thread->abort_state_handle)
2281 mono_gchandle_free (thread->abort_state_handle);
2283 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2284 g_assert (thread->abort_state_handle);
2286 thread->abort_state_handle = 0;
2288 thread->abort_exc = NULL;
2290 LeaveCriticalSection (thread->synch_cs);
2292 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2294 /* During shutdown, we can't wait for other threads */
2296 /* Make sure the thread is awake */
2297 mono_thread_resume (thread);
2299 signal_thread_state_change (thread);
2303 ves_icall_System_Threading_Thread_ResetAbort (void)
2305 MonoInternalThread *thread = mono_thread_internal_current ();
2307 ensure_synch_cs_set (thread);
2309 EnterCriticalSection (thread->synch_cs);
2311 thread->state &= ~ThreadState_AbortRequested;
2313 if (!thread->abort_exc) {
2314 const char *msg = "Unable to reset abort because no abort was requested";
2315 LeaveCriticalSection (thread->synch_cs);
2316 mono_raise_exception (mono_get_exception_thread_state (msg));
2318 thread->abort_exc = NULL;
2319 if (thread->abort_state_handle) {
2320 mono_gchandle_free (thread->abort_state_handle);
2321 /* This is actually not necessary - the handle
2322 only counts if the exception is set */
2323 thread->abort_state_handle = 0;
2327 LeaveCriticalSection (thread->synch_cs);
2331 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2333 MonoInternalThread *thread = this->internal_thread;
2334 MonoObject *state, *deserialized = NULL, *exc;
2337 if (!thread->abort_state_handle)
2340 state = mono_gchandle_get_target (thread->abort_state_handle);
2343 domain = mono_domain_get ();
2344 if (mono_object_domain (state) == domain)
2347 deserialized = mono_object_xdomain_representation (state, domain, &exc);
2349 if (!deserialized) {
2350 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2352 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2353 mono_raise_exception (invalid_op_exc);
2356 return deserialized;
2360 mono_thread_suspend (MonoInternalThread *thread)
2362 ensure_synch_cs_set (thread);
2364 EnterCriticalSection (thread->synch_cs);
2366 if ((thread->state & ThreadState_Unstarted) != 0 ||
2367 (thread->state & ThreadState_Aborted) != 0 ||
2368 (thread->state & ThreadState_Stopped) != 0)
2370 LeaveCriticalSection (thread->synch_cs);
2374 if ((thread->state & ThreadState_Suspended) != 0 ||
2375 (thread->state & ThreadState_SuspendRequested) != 0 ||
2376 (thread->state & ThreadState_StopRequested) != 0)
2378 LeaveCriticalSection (thread->synch_cs);
2382 thread->state |= ThreadState_SuspendRequested;
2384 LeaveCriticalSection (thread->synch_cs);
2386 signal_thread_state_change (thread);
2391 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2393 if (!mono_thread_suspend (thread))
2394 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2398 mono_thread_resume (MonoInternalThread *thread)
2400 ensure_synch_cs_set (thread);
2402 EnterCriticalSection (thread->synch_cs);
2404 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2405 thread->state &= ~ThreadState_SuspendRequested;
2406 LeaveCriticalSection (thread->synch_cs);
2410 if ((thread->state & ThreadState_Suspended) == 0 ||
2411 (thread->state & ThreadState_Unstarted) != 0 ||
2412 (thread->state & ThreadState_Aborted) != 0 ||
2413 (thread->state & ThreadState_Stopped) != 0)
2415 LeaveCriticalSection (thread->synch_cs);
2419 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2420 if (thread->resume_event == NULL) {
2421 LeaveCriticalSection (thread->synch_cs);
2425 /* Awake the thread */
2426 SetEvent (thread->suspend_event);
2428 LeaveCriticalSection (thread->synch_cs);
2430 /* Wait for the thread to awake */
2431 WaitForSingleObject (thread->resume_event, INFINITE);
2432 CloseHandle (thread->resume_event);
2433 thread->resume_event = NULL;
2439 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2441 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2442 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2446 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2451 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2452 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2453 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2455 *((gboolean*)data) = TRUE;
2462 is_running_protected_wrapper (void)
2464 gboolean found = FALSE;
2465 mono_stack_walk (find_wrapper, &found);
2469 void mono_thread_internal_stop (MonoInternalThread *thread)
2471 ensure_synch_cs_set (thread);
2473 EnterCriticalSection (thread->synch_cs);
2475 if ((thread->state & ThreadState_StopRequested) != 0 ||
2476 (thread->state & ThreadState_Stopped) != 0)
2478 LeaveCriticalSection (thread->synch_cs);
2482 /* Make sure the thread is awake */
2483 mono_thread_resume (thread);
2485 thread->state |= ThreadState_StopRequested;
2486 thread->state &= ~ThreadState_AbortRequested;
2488 LeaveCriticalSection (thread->synch_cs);
2490 signal_thread_state_change (thread);
2493 void mono_thread_stop (MonoThread *thread)
2495 mono_thread_internal_stop (thread->internal_thread);
2499 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2501 return *((volatile gint8 *) (ptr));
2505 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2507 return *((volatile gint16 *) (ptr));
2511 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2513 return *((volatile gint32 *) (ptr));
2517 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2519 return *((volatile gint64 *) (ptr));
2523 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2525 return (void *) *((volatile void **) ptr);
2529 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2531 *((volatile gint8 *) ptr) = value;
2535 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2537 *((volatile gint16 *) ptr) = value;
2541 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2543 *((volatile gint32 *) ptr) = value;
2547 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2549 *((volatile gint64 *) ptr) = value;
2553 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2555 *((volatile void **) ptr) = value;
2559 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2561 mono_gc_wbarrier_generic_store (ptr, value);
2564 void mono_thread_init (MonoThreadStartCB start_cb,
2565 MonoThreadAttachCB attach_cb)
2567 MONO_GC_REGISTER_ROOT (small_id_table);
2568 InitializeCriticalSection(&threads_mutex);
2569 InitializeCriticalSection(&interlocked_mutex);
2570 InitializeCriticalSection(&contexts_mutex);
2571 InitializeCriticalSection(&delayed_free_table_mutex);
2572 InitializeCriticalSection(&small_id_mutex);
2574 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2575 g_assert(background_change_event != NULL);
2577 mono_init_static_data_info (&thread_static_info);
2578 mono_init_static_data_info (&context_static_info);
2580 current_object_key=TlsAlloc();
2581 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2583 mono_thread_start_cb = start_cb;
2584 mono_thread_attach_cb = attach_cb;
2586 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2588 /* Get a pseudo handle to the current process. This is just a
2589 * kludge so that wapi can build a process handle if needed.
2590 * As a pseudo handle is returned, we don't need to clean
2593 GetCurrentProcess ();
2596 void mono_thread_cleanup (void)
2598 mono_thread_hazardous_try_free_all ();
2600 #if !defined(HOST_WIN32) && !defined(RUN_IN_SUBTHREAD)
2601 /* The main thread must abandon any held mutexes (particularly
2602 * important for named mutexes as they are shared across
2603 * processes, see bug 74680.) This will happen when the
2604 * thread exits, but if it's not running in a subthread it
2605 * won't exit in time.
2607 /* Using non-w32 API is a nasty kludge, but I couldn't find
2608 * anything in the documentation that would let me do this
2609 * here yet still be safe to call on windows.
2611 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2615 /* This stuff needs more testing, it seems one of these
2616 * critical sections can be locked when mono_thread_cleanup is
2619 DeleteCriticalSection (&threads_mutex);
2620 DeleteCriticalSection (&interlocked_mutex);
2621 DeleteCriticalSection (&contexts_mutex);
2622 DeleteCriticalSection (&delayed_free_table_mutex);
2623 DeleteCriticalSection (&small_id_mutex);
2624 CloseHandle (background_change_event);
2627 g_array_free (delayed_free_table, TRUE);
2628 delayed_free_table = NULL;
2630 TlsFree (current_object_key);
2634 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2636 mono_thread_cleanup_fn = func;
2640 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2642 thread->internal_thread->manage_callback = func;
2645 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2647 mono_thread_notify_pending_exc_fn = func;
2651 static void print_tids (gpointer key, gpointer value, gpointer user)
2653 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2654 * sizeof(uint) and a cast to uint would overflow
2656 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2657 * print this as a pointer.
2659 g_message ("Waiting for: %p", key);
2664 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2665 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2669 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2673 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2675 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2677 if(ret==WAIT_FAILED) {
2678 /* See the comment in build_wait_tids() */
2679 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2683 for(i=0; i<wait->num; i++)
2684 CloseHandle (wait->handles[i]);
2686 if (ret == WAIT_TIMEOUT)
2689 for(i=0; i<wait->num; i++) {
2690 gsize tid = wait->threads[i]->tid;
2692 mono_threads_lock ();
2693 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2694 /* This thread must have been killed, because
2695 * it hasn't cleaned itself up. (It's just
2696 * possible that the thread exited before the
2697 * parent thread had a chance to store the
2698 * handle, and now there is another pointer to
2699 * the already-exited thread stored. In this
2700 * case, we'll just get two
2701 * mono_profiler_thread_end() calls for the
2705 mono_threads_unlock ();
2706 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2707 thread_cleanup (wait->threads[i]);
2709 mono_threads_unlock ();
2714 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2716 guint32 i, ret, count;
2718 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2720 /* Add the thread state change event, so it wakes up if a thread changes
2721 * to background mode.
2724 if (count < MAXIMUM_WAIT_OBJECTS) {
2725 wait->handles [count] = background_change_event;
2729 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2731 if(ret==WAIT_FAILED) {
2732 /* See the comment in build_wait_tids() */
2733 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2737 for(i=0; i<wait->num; i++)
2738 CloseHandle (wait->handles[i]);
2740 if (ret == WAIT_TIMEOUT)
2743 if (ret < wait->num) {
2744 gsize tid = wait->threads[ret]->tid;
2745 mono_threads_lock ();
2746 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2747 /* See comment in wait_for_tids about thread cleanup */
2748 mono_threads_unlock ();
2749 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2750 thread_cleanup (wait->threads [ret]);
2752 mono_threads_unlock ();
2756 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2758 struct wait_data *wait=(struct wait_data *)user;
2760 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2762 MonoInternalThread *thread=(MonoInternalThread *)value;
2764 /* Ignore background threads, we abort them later */
2765 /* Do not lock here since it is not needed and the caller holds threads_lock */
2766 if (thread->state & ThreadState_Background) {
2767 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2768 return; /* just leave, ignore */
2771 if (mono_gc_is_finalizer_internal_thread (thread)) {
2772 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2776 if (thread == mono_thread_internal_current ()) {
2777 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2781 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2782 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2786 if (thread->flags & MONO_THREAD_FLAG_DONT_MANAGE) {
2787 THREAD_DEBUG (g_message ("%s: ignoring thread %" G_GSIZE_FORMAT "with DONT_MANAGE flag set.", __func__, (gsize)thread->tid));
2791 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2792 if (handle == NULL) {
2793 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2797 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2798 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2799 wait->handles[wait->num]=handle;
2800 wait->threads[wait->num]=thread;
2803 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2805 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2810 /* Just ignore the rest, we can't do anything with
2817 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2819 struct wait_data *wait=(struct wait_data *)user;
2820 gsize self = GetCurrentThreadId ();
2821 MonoInternalThread *thread = value;
2824 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2827 /* The finalizer thread is not a background thread */
2828 if (thread->tid != self && (thread->state & ThreadState_Background) != 0 &&
2829 !(thread->flags & MONO_THREAD_FLAG_DONT_MANAGE)) {
2831 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2835 /* printf ("A: %d\n", wait->num); */
2836 wait->handles[wait->num]=thread->handle;
2837 wait->threads[wait->num]=thread;
2840 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2841 mono_thread_internal_stop (thread);
2845 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2849 * mono_threads_set_shutting_down:
2851 * Is called by a thread that wants to shut down Mono. If the runtime is already
2852 * shutting down, the calling thread is suspended/stopped, and this function never
2856 mono_threads_set_shutting_down (void)
2858 MonoInternalThread *current_thread = mono_thread_internal_current ();
2860 mono_threads_lock ();
2862 if (shutting_down) {
2863 mono_threads_unlock ();
2865 /* Make sure we're properly suspended/stopped */
2867 EnterCriticalSection (current_thread->synch_cs);
2869 if ((current_thread->state & ThreadState_SuspendRequested) ||
2870 (current_thread->state & ThreadState_AbortRequested) ||
2871 (current_thread->state & ThreadState_StopRequested)) {
2872 LeaveCriticalSection (current_thread->synch_cs);
2873 mono_thread_execute_interruption (current_thread);
2875 current_thread->state |= ThreadState_Stopped;
2876 LeaveCriticalSection (current_thread->synch_cs);
2879 /* Wake up other threads potentially waiting for us */
2882 shutting_down = TRUE;
2884 /* Not really a background state change, but this will
2885 * interrupt the main thread if it is waiting for all
2886 * the other threads.
2888 SetEvent (background_change_event);
2890 mono_threads_unlock ();
2895 * mono_threads_is_shutting_down:
2897 * Returns whether a thread has commenced shutdown of Mono. Note that
2898 * if the function returns FALSE the caller must not assume that
2899 * shutdown is not in progress, because the situation might have
2900 * changed since the function returned. For that reason this function
2901 * is of very limited utility.
2904 mono_threads_is_shutting_down (void)
2906 return shutting_down;
2909 void mono_thread_manage (void)
2911 struct wait_data *wait=g_new0 (struct wait_data, 1);
2913 /* join each thread that's still running */
2914 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2916 mono_threads_lock ();
2918 THREAD_DEBUG (g_message("%s: No threads", __func__));
2919 mono_threads_unlock ();
2923 mono_threads_unlock ();
2926 mono_threads_lock ();
2927 if (shutting_down) {
2928 /* somebody else is shutting down */
2929 mono_threads_unlock ();
2932 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2933 mono_g_hash_table_foreach (threads, print_tids, NULL));
2935 ResetEvent (background_change_event);
2937 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2938 mono_threads_unlock ();
2940 /* Something to wait for */
2941 wait_for_tids_or_state_change (wait, INFINITE);
2943 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2944 } while(wait->num>0);
2946 mono_threads_set_shutting_down ();
2948 /* No new threads will be created after this point */
2950 mono_runtime_set_shutting_down ();
2952 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2953 mono_thread_pool_cleanup ();
2956 * Remove everything but the finalizer thread and self.
2957 * Also abort all the background threads
2960 mono_threads_lock ();
2963 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2965 mono_threads_unlock ();
2967 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2969 /* Something to wait for */
2970 wait_for_tids (wait, INFINITE);
2972 } while (wait->num > 0);
2975 * give the subthreads a chance to really quit (this is mainly needed
2976 * to get correct user and system times from getrusage/wait/time(1)).
2977 * This could be removed if we avoid pthread_detach() and use pthread_join().
2986 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2988 MonoInternalThread *thread=(MonoInternalThread *)value;
2990 if(thread->tid != (gsize)user) {
2991 /*TerminateThread (thread->handle, -1);*/
2995 void mono_thread_abort_all_other_threads (void)
2997 gsize self = GetCurrentThreadId ();
2999 mono_threads_lock ();
3000 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3001 mono_g_hash_table_size (threads));
3002 mono_g_hash_table_foreach (threads, print_tids, NULL));
3004 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3006 mono_threads_unlock ();
3010 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3012 MonoInternalThread *thread = (MonoInternalThread*)value;
3013 struct wait_data *wait = (struct wait_data*)user_data;
3017 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3019 * This needs no locking.
3021 if ((thread->state & ThreadState_Suspended) != 0 ||
3022 (thread->state & ThreadState_Stopped) != 0)
3025 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3026 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3030 wait->handles [wait->num] = handle;
3031 wait->threads [wait->num] = thread;
3037 * mono_thread_suspend_all_other_threads:
3039 * Suspend all managed threads except the finalizer thread and this thread. It is
3040 * not possible to resume them later.
3042 void mono_thread_suspend_all_other_threads (void)
3044 struct wait_data *wait = g_new0 (struct wait_data, 1);
3046 gsize self = GetCurrentThreadId ();
3048 guint32 eventidx = 0;
3049 gboolean starting, finished;
3052 * The other threads could be in an arbitrary state at this point, i.e.
3053 * they could be starting up, shutting down etc. This means that there could be
3054 * threads which are not even in the threads hash table yet.
3058 * First we set a barrier which will be checked by all threads before they
3059 * are added to the threads hash table, and they will exit if the flag is set.
3060 * This ensures that no threads could be added to the hash later.
3061 * We will use shutting_down as the barrier for now.
3063 g_assert (shutting_down);
3066 * We make multiple calls to WaitForMultipleObjects since:
3067 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3068 * - some threads could exit without becoming suspended
3073 * Make a copy of the hashtable since we can't do anything with
3074 * threads while threads_mutex is held.
3077 mono_threads_lock ();
3078 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3079 mono_threads_unlock ();
3081 events = g_new0 (gpointer, wait->num);
3083 /* Get the suspended events that we'll be waiting for */
3084 for (i = 0; i < wait->num; ++i) {
3085 MonoInternalThread *thread = wait->threads [i];
3086 gboolean signal_suspend = FALSE;
3088 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread)) {
3089 //CloseHandle (wait->handles [i]);
3090 wait->threads [i] = NULL; /* ignore this thread in next loop */
3094 ensure_synch_cs_set (thread);
3096 EnterCriticalSection (thread->synch_cs);
3098 if (thread->suspended_event == NULL) {
3099 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3100 if (thread->suspended_event == NULL) {
3101 /* Forget this one and go on to the next */
3102 LeaveCriticalSection (thread->synch_cs);
3107 if ((thread->state & ThreadState_Suspended) != 0 ||
3108 (thread->state & ThreadState_StopRequested) != 0 ||
3109 (thread->state & ThreadState_Stopped) != 0) {
3110 LeaveCriticalSection (thread->synch_cs);
3111 CloseHandle (wait->handles [i]);
3112 wait->threads [i] = NULL; /* ignore this thread in next loop */
3116 if ((thread->state & ThreadState_SuspendRequested) == 0)
3117 signal_suspend = TRUE;
3119 events [eventidx++] = thread->suspended_event;
3121 /* Convert abort requests into suspend requests */
3122 if ((thread->state & ThreadState_AbortRequested) != 0)
3123 thread->state &= ~ThreadState_AbortRequested;
3125 thread->state |= ThreadState_SuspendRequested;
3127 LeaveCriticalSection (thread->synch_cs);
3129 /* Signal the thread to suspend */
3131 signal_thread_state_change (thread);
3135 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3136 for (i = 0; i < wait->num; ++i) {
3137 MonoInternalThread *thread = wait->threads [i];
3142 EnterCriticalSection (thread->synch_cs);
3143 if ((thread->state & ThreadState_Suspended) != 0) {
3144 CloseHandle (thread->suspended_event);
3145 thread->suspended_event = NULL;
3147 LeaveCriticalSection (thread->synch_cs);
3151 * If there are threads which are starting up, we wait until they
3152 * are suspended when they try to register in the threads hash.
3153 * This is guaranteed to finish, since the threads which can create new
3154 * threads get suspended after a while.
3155 * FIXME: The finalizer thread can still create new threads.
3157 mono_threads_lock ();
3158 if (threads_starting_up)
3159 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3162 mono_threads_unlock ();
3176 collect_threads (gpointer key, gpointer value, gpointer user_data)
3178 MonoInternalThread *thread = (MonoInternalThread*)value;
3179 struct wait_data *wait = (struct wait_data*)user_data;
3182 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3183 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3187 wait->handles [wait->num] = handle;
3188 wait->threads [wait->num] = thread;
3194 * mono_threads_request_thread_dump:
3196 * Ask all threads except the current to print their stacktrace to stdout.
3199 mono_threads_request_thread_dump (void)
3201 struct wait_data *wait = g_new0 (struct wait_data, 1);
3205 * Make a copy of the hashtable since we can't do anything with
3206 * threads while threads_mutex is held.
3208 mono_threads_lock ();
3209 mono_g_hash_table_foreach (threads, collect_threads, wait);
3210 mono_threads_unlock ();
3212 for (i = 0; i < wait->num; ++i) {
3213 MonoInternalThread *thread = wait->threads [i];
3215 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3216 (thread != mono_thread_internal_current ()) &&
3217 !thread->thread_dump_requested) {
3218 thread->thread_dump_requested = TRUE;
3220 signal_thread_state_change (thread);
3223 CloseHandle (wait->handles [i]);
3228 * mono_thread_push_appdomain_ref:
3230 * Register that the current thread may have references to objects in domain
3231 * @domain on its stack. Each call to this function should be paired with a
3232 * call to pop_appdomain_ref.
3235 mono_thread_push_appdomain_ref (MonoDomain *domain)
3237 MonoInternalThread *thread = mono_thread_internal_current ();
3240 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3241 mono_threads_lock ();
3242 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3243 mono_threads_unlock ();
3248 mono_thread_pop_appdomain_ref (void)
3250 MonoInternalThread *thread = mono_thread_internal_current ();
3253 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3254 mono_threads_lock ();
3255 /* FIXME: How can the list be empty ? */
3256 if (thread->appdomain_refs)
3257 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3258 mono_threads_unlock ();
3263 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3266 mono_threads_lock ();
3267 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3268 mono_threads_unlock ();
3273 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3275 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3278 typedef struct abort_appdomain_data {
3279 struct wait_data wait;
3281 } abort_appdomain_data;
3284 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3286 MonoInternalThread *thread = (MonoInternalThread*)value;
3287 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3288 MonoDomain *domain = data->domain;
3290 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3291 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3293 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3294 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3297 data->wait.handles [data->wait.num] = handle;
3298 data->wait.threads [data->wait.num] = thread;
3301 /* Just ignore the rest, we can't do anything with
3309 * mono_threads_abort_appdomain_threads:
3311 * Abort threads which has references to the given appdomain.
3314 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3316 abort_appdomain_data user_data;
3318 int orig_timeout = timeout;
3321 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3323 start_time = mono_msec_ticks ();
3325 mono_threads_lock ();
3327 user_data.domain = domain;
3328 user_data.wait.num = 0;
3329 /* This shouldn't take any locks */
3330 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3331 mono_threads_unlock ();
3333 if (user_data.wait.num > 0) {
3334 /* Abort the threads outside the threads lock */
3335 for (i = 0; i < user_data.wait.num; ++i)
3336 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3339 * We should wait for the threads either to abort, or to leave the
3340 * domain. We can't do the latter, so we wait with a timeout.
3342 wait_for_tids (&user_data.wait, 100);
3345 /* Update remaining time */
3346 timeout -= mono_msec_ticks () - start_time;
3347 start_time = mono_msec_ticks ();
3349 if (orig_timeout != -1 && timeout < 0)
3352 while (user_data.wait.num > 0);
3354 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3360 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3362 MonoInternalThread *thread = (MonoInternalThread*)value;
3363 MonoDomain *domain = (MonoDomain*)user_data;
3366 /* No locking needed here */
3367 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3369 if (thread->cached_culture_info) {
3370 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3371 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3372 if (obj && obj->vtable->domain == domain)
3373 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3379 * mono_threads_clear_cached_culture:
3381 * Clear the cached_current_culture from all threads if it is in the
3385 mono_threads_clear_cached_culture (MonoDomain *domain)
3387 mono_threads_lock ();
3388 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3389 mono_threads_unlock ();
3393 * mono_thread_get_undeniable_exception:
3395 * Return an exception which needs to be raised when leaving a catch clause.
3396 * This is used for undeniable exception propagation.
3399 mono_thread_get_undeniable_exception (void)
3401 MonoInternalThread *thread = mono_thread_internal_current ();
3403 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3405 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3406 * exception if the thread no longer references a dying appdomain.
3408 thread->abort_exc->trace_ips = NULL;
3409 thread->abort_exc->stack_trace = NULL;
3410 return thread->abort_exc;
3416 #define NUM_STATIC_DATA_IDX 8
3417 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3418 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3423 * mono_alloc_static_data
3425 * Allocate memory blocks for storing threads or context static data
3428 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3430 guint idx = (offset >> 24) - 1;
3433 gpointer* static_data = *static_data_ptr;
3435 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3436 *static_data_ptr = static_data;
3437 static_data [0] = static_data;
3440 for (i = 1; i <= idx; ++i) {
3441 if (static_data [i])
3443 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3448 * mono_init_static_data_info
3450 * Initializes static data counters
3452 static void mono_init_static_data_info (StaticDataInfo *static_data)
3454 static_data->idx = 0;
3455 static_data->offset = 0;
3456 static_data->freelist = NULL;
3460 * mono_alloc_static_data_slot
3462 * Generates an offset for static data. static_data contains the counters
3463 * used to generate it.
3466 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3470 if (!static_data->idx && !static_data->offset) {
3472 * we use the first chunk of the first allocation also as
3473 * an array for the rest of the data
3475 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3477 static_data->offset += align - 1;
3478 static_data->offset &= ~(align - 1);
3479 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3480 static_data->idx ++;
3481 g_assert (size <= static_data_size [static_data->idx]);
3482 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3483 static_data->offset = 0;
3485 offset = static_data->offset | ((static_data->idx + 1) << 24);
3486 static_data->offset += size;
3491 * ensure thread static fields already allocated are valid for thread
3492 * This function is called when a thread is created or on thread attach.
3495 thread_adjust_static_data (MonoInternalThread *thread)
3499 mono_threads_lock ();
3500 if (thread_static_info.offset || thread_static_info.idx > 0) {
3501 /* get the current allocated size */
3502 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3503 mono_alloc_static_data (&(thread->static_data), offset);
3505 mono_threads_unlock ();
3509 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3511 MonoInternalThread *thread = value;
3512 guint32 offset = GPOINTER_TO_UINT (user);
3514 mono_alloc_static_data (&(thread->static_data), offset);
3517 static MonoThreadDomainTls*
3518 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3520 MonoThreadDomainTls* prev = NULL;
3521 MonoThreadDomainTls* tmp = static_data->freelist;
3523 if (tmp->size == size) {
3525 prev->next = tmp->next;
3527 static_data->freelist = tmp->next;
3536 * The offset for a special static variable is composed of three parts:
3537 * a bit that indicates the type of static data (0:thread, 1:context),
3538 * an index in the array of chunks of memory for the thread (thread->static_data)
3539 * and an offset in that chunk of mem. This allows allocating less memory in the
3544 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3547 if (static_type == SPECIAL_STATIC_THREAD)
3549 MonoThreadDomainTls *item;
3550 mono_threads_lock ();
3551 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3552 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3554 offset = item->offset;
3557 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3559 /* This can be called during startup */
3560 if (threads != NULL)
3561 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3562 mono_threads_unlock ();
3566 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3567 mono_contexts_lock ();
3568 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3569 mono_contexts_unlock ();
3570 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3576 mono_get_special_static_data (guint32 offset)
3578 /* The high bit means either thread (0) or static (1) data. */
3580 guint32 static_type = (offset & 0x80000000);
3583 offset &= 0x7fffffff;
3584 idx = (offset >> 24) - 1;
3586 if (static_type == 0) {
3587 return get_thread_static_data (mono_thread_internal_current (), offset);
3589 /* Allocate static data block under demand, since we don't have a list
3592 MonoAppContext *context = mono_context_get ();
3593 if (!context->static_data || !context->static_data [idx]) {
3594 mono_contexts_lock ();
3595 mono_alloc_static_data (&(context->static_data), offset);
3596 mono_contexts_unlock ();
3598 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3608 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3610 MonoInternalThread *thread = value;
3611 TlsOffsetSize *data = user;
3612 int idx = (data->offset >> 24) - 1;
3615 if (!thread->static_data || !thread->static_data [idx])
3617 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3618 memset (ptr, 0, data->size);
3622 do_free_special (gpointer key, gpointer value, gpointer data)
3624 MonoClassField *field = key;
3625 guint32 offset = GPOINTER_TO_UINT (value);
3626 guint32 static_type = (offset & 0x80000000);
3629 size = mono_type_size (field->type, &align);
3630 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3631 if (static_type == 0) {
3633 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3634 data.offset = offset & 0x7fffffff;
3636 if (threads != NULL)
3637 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3638 item->offset = offset;
3640 item->next = thread_static_info.freelist;
3641 thread_static_info.freelist = item;
3643 /* FIXME: free context static data as well */
3648 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3650 mono_threads_lock ();
3651 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3652 mono_threads_unlock ();
3655 static MonoClassField *local_slots = NULL;
3658 /* local tls data to get locals_slot from a thread */
3661 /* index in the locals_slot array */
3666 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3668 LocalSlotID *sid = user_data;
3669 MonoInternalThread *thread = (MonoInternalThread*)value;
3670 MonoArray *slots_array;
3672 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3673 * it is for the right domain, so we need to check if it is allocated an initialized
3674 * for the current thread.
3676 /*g_print ("handling thread %p\n", thread);*/
3677 if (!thread->static_data || !thread->static_data [sid->idx])
3679 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3680 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3682 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3686 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3694 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3696 g_warning ("local_slots field not found in Thread class");
3700 domain = mono_domain_get ();
3701 mono_domain_lock (domain);
3702 if (domain->special_static_fields)
3703 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3704 mono_domain_unlock (domain);
3707 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3708 sid.offset = GPOINTER_TO_UINT (addr);
3709 sid.offset &= 0x7fffffff;
3710 sid.idx = (sid.offset >> 24) - 1;
3711 mono_threads_lock ();
3712 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3713 mono_threads_unlock ();
3715 /* FIXME: clear the slot for MonoAppContexts, too */
3720 static void CALLBACK dummy_apc (ULONG_PTR param)
3724 static guint32 dummy_apc (gpointer param)
3731 * mono_thread_execute_interruption
3733 * Performs the operation that the requested thread state requires (abort,
3736 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3738 ensure_synch_cs_set (thread);
3740 EnterCriticalSection (thread->synch_cs);
3742 /* MonoThread::interruption_requested can only be changed with atomics */
3743 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3744 /* this will consume pending APC calls */
3745 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3746 InterlockedDecrement (&thread_interruption_requested);
3748 /* Clear the interrupted flag of the thread so it can wait again */
3749 wapi_clear_interruption ();
3753 if ((thread->state & ThreadState_AbortRequested) != 0) {
3754 LeaveCriticalSection (thread->synch_cs);
3755 if (thread->abort_exc == NULL) {
3757 * This might be racy, but it has to be called outside the lock
3758 * since it calls managed code.
3760 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3762 return thread->abort_exc;
3764 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3765 thread->state &= ~ThreadState_SuspendRequested;
3766 thread->state |= ThreadState_Suspended;
3767 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3768 if (thread->suspend_event == NULL) {
3769 LeaveCriticalSection (thread->synch_cs);
3772 if (thread->suspended_event)
3773 SetEvent (thread->suspended_event);
3775 LeaveCriticalSection (thread->synch_cs);
3777 if (shutting_down) {
3778 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3783 WaitForSingleObject (thread->suspend_event, INFINITE);
3785 EnterCriticalSection (thread->synch_cs);
3787 CloseHandle (thread->suspend_event);
3788 thread->suspend_event = NULL;
3789 thread->state &= ~ThreadState_Suspended;
3791 /* The thread that requested the resume will have replaced this event
3792 * and will be waiting for it
3794 SetEvent (thread->resume_event);
3796 LeaveCriticalSection (thread->synch_cs);
3800 else if ((thread->state & ThreadState_StopRequested) != 0) {
3801 /* FIXME: do this through the JIT? */
3803 LeaveCriticalSection (thread->synch_cs);
3805 mono_thread_exit ();
3807 } else if (thread->thread_interrupt_requested) {
3809 thread->thread_interrupt_requested = FALSE;
3810 LeaveCriticalSection (thread->synch_cs);
3812 return(mono_get_exception_thread_interrupted ());
3815 LeaveCriticalSection (thread->synch_cs);
3821 * mono_thread_request_interruption
3823 * A signal handler can call this method to request the interruption of a
3824 * thread. The result of the interruption will depend on the current state of
3825 * the thread. If the result is an exception that needs to be throw, it is
3826 * provided as return value.
3829 mono_thread_request_interruption (gboolean running_managed)
3831 MonoInternalThread *thread = mono_thread_internal_current ();
3833 /* The thread may already be stopping */
3838 if (thread->interrupt_on_stop &&
3839 thread->state & ThreadState_StopRequested &&
3840 thread->state & ThreadState_Background)
3844 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3847 if (!running_managed || is_running_protected_wrapper ()) {
3848 /* Can't stop while in unmanaged code. Increase the global interruption
3849 request count. When exiting the unmanaged method the count will be
3850 checked and the thread will be interrupted. */
3852 InterlockedIncrement (&thread_interruption_requested);
3854 if (mono_thread_notify_pending_exc_fn && !running_managed)
3855 /* The JIT will notify the thread about the interruption */
3856 /* This shouldn't take any locks */
3857 mono_thread_notify_pending_exc_fn ();
3859 /* this will awake the thread if it is in WaitForSingleObject
3861 /* Our implementation of this function ignores the func argument */
3862 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3866 return mono_thread_execute_interruption (thread);
3870 gboolean mono_thread_interruption_requested ()
3872 if (thread_interruption_requested) {
3873 MonoInternalThread *thread = mono_thread_internal_current ();
3874 /* The thread may already be stopping */
3876 return (thread->interruption_requested);
3881 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3883 MonoInternalThread *thread = mono_thread_internal_current ();
3885 /* The thread may already be stopping */
3889 mono_debugger_check_interruption ();
3891 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3892 MonoException* exc = mono_thread_execute_interruption (thread);
3893 if (exc) mono_raise_exception (exc);
3898 * Performs the interruption of the current thread, if one has been requested,
3899 * and the thread is not running a protected wrapper.
3901 void mono_thread_interruption_checkpoint ()
3903 mono_thread_interruption_checkpoint_request (FALSE);
3907 * Performs the interruption of the current thread, if one has been requested.
3909 void mono_thread_force_interruption_checkpoint ()
3911 mono_thread_interruption_checkpoint_request (TRUE);
3915 * mono_thread_get_and_clear_pending_exception:
3917 * Return any pending exceptions for the current thread and clear it as a side effect.
3920 mono_thread_get_and_clear_pending_exception (void)
3922 MonoInternalThread *thread = mono_thread_internal_current ();
3924 /* The thread may already be stopping */
3928 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3929 return mono_thread_execute_interruption (thread);
3932 if (thread->pending_exception) {
3933 MonoException *exc = thread->pending_exception;
3935 thread->pending_exception = NULL;
3943 * mono_set_pending_exception:
3945 * Set the pending exception of the current thread to EXC. On platforms which
3946 * support it, the exception will be thrown when execution returns to managed code.
3947 * On other platforms, this function is equivalent to mono_raise_exception ().
3948 * Internal calls which report exceptions using this function instead of
3949 * raise_exception () might be called by JITted code using a more efficient calling
3953 mono_set_pending_exception (MonoException *exc)
3955 MonoInternalThread *thread = mono_thread_internal_current ();
3957 /* The thread may already be stopping */
3961 if (mono_thread_notify_pending_exc_fn) {
3962 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3964 mono_thread_notify_pending_exc_fn ();
3966 /* No way to notify the JIT about the exception, have to throw it now */
3967 mono_raise_exception (exc);
3972 * mono_thread_interruption_request_flag:
3974 * Returns the address of a flag that will be non-zero if an interruption has
3975 * been requested for a thread. The thread to interrupt may not be the current
3976 * thread, so an additional call to mono_thread_interruption_requested() or
3977 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3980 gint32* mono_thread_interruption_request_flag ()
3982 return &thread_interruption_requested;
3986 mono_thread_init_apartment_state (void)
3989 MonoInternalThread* thread = mono_thread_internal_current ();
3991 /* Positive return value indicates success, either
3992 * S_OK if this is first CoInitialize call, or
3993 * S_FALSE if CoInitialize already called, but with same
3994 * threading model. A negative value indicates failure,
3995 * probably due to trying to change the threading model.
3997 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3998 ? COINIT_APARTMENTTHREADED
3999 : COINIT_MULTITHREADED) < 0) {
4000 thread->apartment_state = ThreadApartmentState_Unknown;
4006 mono_thread_cleanup_apartment_state (void)
4009 MonoInternalThread* thread = mono_thread_internal_current ();
4011 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4018 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4020 ensure_synch_cs_set (thread);
4022 EnterCriticalSection (thread->synch_cs);
4023 thread->state |= state;
4024 LeaveCriticalSection (thread->synch_cs);
4028 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4030 ensure_synch_cs_set (thread);
4032 EnterCriticalSection (thread->synch_cs);
4033 thread->state &= ~state;
4034 LeaveCriticalSection (thread->synch_cs);
4038 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4040 gboolean ret = FALSE;
4042 ensure_synch_cs_set (thread);
4044 EnterCriticalSection (thread->synch_cs);
4046 if ((thread->state & test) != 0) {
4050 LeaveCriticalSection (thread->synch_cs);
4055 static MonoClassField *execution_context_field;
4058 get_execution_context_addr (void)
4060 MonoDomain *domain = mono_domain_get ();
4063 if (!execution_context_field) {
4064 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4066 g_assert (execution_context_field);
4069 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4071 mono_domain_lock (domain);
4072 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4073 mono_domain_unlock (domain);
4076 return (MonoObject**) mono_get_special_static_data (offset);
4080 mono_thread_get_execution_context (void)
4082 return *get_execution_context_addr ();
4086 mono_thread_set_execution_context (MonoObject *ec)
4088 *get_execution_context_addr () = ec;
4091 static gboolean has_tls_get = FALSE;
4094 mono_runtime_set_has_tls_get (gboolean val)
4100 mono_runtime_has_tls_get (void)