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>
31 #ifndef PLATFORM_WIN32
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 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 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 mono_profiler_thread_start (tid);
685 /* On 2.0 profile (and higher), set explicitly since state might have been
687 if (mono_framework_version () != 1) {
688 if (internal->apartment_state == ThreadApartmentState_Unknown)
689 internal->apartment_state = ThreadApartmentState_MTA;
692 mono_thread_init_apartment_state ();
694 if(internal->start_notify!=NULL) {
695 /* Let the thread that called Start() know we're
698 ReleaseSemaphore (internal->start_notify, 1, NULL);
701 mono_threads_lock ();
702 mono_g_hash_table_remove (thread_start_args, thread);
703 mono_threads_unlock ();
707 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
711 mono_thread_set_execution_context (thread->ec_to_set);
712 thread->ec_to_set = NULL;
714 /* start_func is set only for unmanaged start functions */
716 start_func (start_arg);
719 g_assert (start_delegate != NULL);
720 args [0] = start_arg;
721 /* we may want to handle the exception here. See comment below on unhandled exceptions */
722 mono_runtime_delegate_invoke (start_delegate, args, NULL);
725 /* If the thread calls ExitThread at all, this remaining code
726 * will not be executed, but the main thread will eventually
727 * call thread_cleanup() on this thread's behalf.
730 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
732 thread_cleanup (internal);
734 /* Do any cleanup needed for apartment state. This
735 * cannot be done in thread_cleanup since thread_cleanup could be
736 * called for a thread other than the current thread.
737 * mono_thread_cleanup_apartment_state cleans up apartment
738 * for the current thead */
739 mono_thread_cleanup_apartment_state ();
741 /* Remove the reference to the thread object in the TLS data,
742 * so the thread object can be finalized. This won't be
743 * reached if the thread threw an uncaught exception, so those
744 * thread handles will stay referenced :-( (This is due to
745 * missing support for scanning thread-specific data in the
746 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
749 SET_CURRENT_OBJECT (NULL);
754 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
756 if (mono_thread_start_cb) {
757 mono_thread_start_cb (tid, stack_start, func);
761 void mono_threads_set_default_stacksize (guint32 stacksize)
763 default_stacksize = stacksize;
766 guint32 mono_threads_get_default_stacksize (void)
768 return default_stacksize;
772 * mono_create_thread:
774 * This is a wrapper around CreateThread which handles differences in the type of
775 * the the 'tid' argument.
777 gpointer mono_create_thread (WapiSecurityAttributes *security,
778 guint32 stacksize, WapiThreadStart start,
779 gpointer param, guint32 create, gsize *tid)
783 #ifdef PLATFORM_WIN32
786 res = CreateThread (security, stacksize, start, param, create, &real_tid);
790 res = CreateThread (security, stacksize, start, param, create, tid);
796 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
799 MonoInternalThread *internal;
800 HANDLE thread_handle;
801 struct StartInfo *start_info;
804 thread=(MonoThread *)mono_object_new (domain,
805 mono_defaults.thread_class);
806 internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (),
807 mono_defaults.internal_thread_class);
808 thread->internal_thread = internal;
810 start_info=g_new0 (struct StartInfo, 1);
811 start_info->func = func;
812 start_info->obj = thread;
813 start_info->start_arg = arg;
815 mono_threads_lock ();
817 mono_threads_unlock ();
821 if (threads_starting_up == NULL) {
822 MONO_GC_REGISTER_ROOT (threads_starting_up);
823 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
825 if (thread_start_args == NULL) {
826 MONO_GC_REGISTER_ROOT (thread_start_args);
827 thread_start_args = mono_g_hash_table_new (NULL, NULL);
829 mono_g_hash_table_insert (threads_starting_up, thread, thread);
831 * The argument may be an object reference, and there is no ref to keep it alive
832 * when the new thread is started but not yet registered with the collector. So
833 * we store it in a GC tracked hash table.
835 mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
836 mono_threads_unlock ();
838 /* Create suspended, so we can do some housekeeping before the thread
841 thread_handle = mono_create_thread (NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
842 CREATE_SUSPENDED, &tid);
843 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
844 if (thread_handle == NULL) {
845 /* The thread couldn't be created, so throw an exception */
846 mono_threads_lock ();
847 mono_g_hash_table_remove (threads_starting_up, thread);
848 mono_threads_unlock ();
850 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
854 internal->handle=thread_handle;
856 internal->apartment_state=ThreadApartmentState_Unknown;
857 small_id_alloc (internal);
859 internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
860 InitializeCriticalSection (internal->synch_cs);
862 internal->threadpool_thread = threadpool_thread;
863 if (threadpool_thread)
864 mono_thread_set_state (internal, ThreadState_Background);
866 if (handle_store (thread))
867 ResumeThread (thread_handle);
873 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
875 mono_thread_create_internal (domain, func, arg, FALSE);
879 * mono_thread_get_stack_bounds:
881 * Return the address and size of the current threads stack. Return NULL as the
882 * stack address if the stack address cannot be determined.
885 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
887 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
888 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
889 *stsize = pthread_get_stacksize_np (pthread_self ());
890 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
892 /* FIXME: simplify the mess below */
893 #elif !defined(PLATFORM_WIN32)
895 guint8 *current = (guint8*)&attr;
897 pthread_attr_init (&attr);
898 # ifdef HAVE_PTHREAD_GETATTR_NP
899 pthread_getattr_np (pthread_self(), &attr);
901 # ifdef HAVE_PTHREAD_ATTR_GET_NP
902 pthread_attr_get_np (pthread_self(), &attr);
905 pthread_attr_getstacksize (&attr, &stsize);
914 pthread_attr_getstack (&attr, (void**)staddr, stsize);
916 g_assert ((current > *staddr) && (current < *staddr + *stsize));
919 pthread_attr_destroy (&attr);
922 /* When running under emacs, sometimes staddr is not aligned to a page size */
923 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
927 mono_thread_attach (MonoDomain *domain)
929 MonoInternalThread *thread;
930 MonoThread *current_thread;
931 HANDLE thread_handle;
934 if ((thread = mono_thread_internal_current ())) {
935 if (domain != mono_domain_get ())
936 mono_domain_set (domain, TRUE);
937 /* Already attached */
938 return mono_thread_current ();
941 if (!mono_gc_register_thread (&domain)) {
942 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 ());
945 thread = (MonoInternalThread *)mono_object_new (domain, mono_defaults.internal_thread_class);
947 thread_handle = GetCurrentThread ();
948 g_assert (thread_handle);
950 tid=GetCurrentThreadId ();
953 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
954 * refer to the thread from other threads for things like aborting.
956 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
957 THREAD_ALL_ACCESS, TRUE, 0);
959 thread->handle=thread_handle;
961 thread->apartment_state=ThreadApartmentState_Unknown;
962 small_id_alloc (thread);
963 thread->stack_ptr = &tid;
965 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
966 InitializeCriticalSection (thread->synch_cs);
968 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
970 current_thread = new_thread_with_internal (domain, thread);
972 if (!handle_store (current_thread)) {
973 /* Mono is shutting down, so just wait for the end */
978 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
980 SET_CURRENT_OBJECT (thread);
981 mono_domain_set (domain, TRUE);
983 mono_monitor_init_tls ();
985 thread_adjust_static_data (thread);
987 init_root_domain_thread (thread, current_thread);
988 if (domain != mono_get_root_domain ())
989 set_current_thread_for_domain (domain, thread, current_thread);
992 if (mono_thread_attach_cb) {
996 mono_thread_get_stack_bounds (&staddr, &stsize);
999 mono_thread_attach_cb (tid, &tid);
1001 mono_thread_attach_cb (tid, staddr + stsize);
1004 return current_thread;
1008 mono_thread_detach (MonoThread *thread)
1010 g_return_if_fail (thread != NULL);
1012 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1014 thread_cleanup (thread->internal_thread);
1016 SET_CURRENT_OBJECT (NULL);
1018 /* Don't need to CloseHandle this thread, even though we took a
1019 * reference in mono_thread_attach (), because the GC will do it
1020 * when the Thread object is finalised.
1027 MonoInternalThread *thread = mono_thread_internal_current ();
1029 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
1031 thread_cleanup (thread);
1032 SET_CURRENT_OBJECT (NULL);
1034 /* we could add a callback here for embedders to use. */
1035 if (thread == mono_thread_get_main ()->internal_thread)
1036 exit (mono_environment_exitcode_get ());
1041 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
1043 MonoInternalThread *internal = (MonoInternalThread*)mono_object_new (mono_get_root_domain (), mono_defaults.internal_thread_class);
1044 internal->state = ThreadState_Unstarted;
1045 internal->apartment_state = ThreadApartmentState_Unknown;
1047 InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
1050 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
1053 guint32 (*start_func)(void *);
1054 struct StartInfo *start_info;
1057 MonoInternalThread *internal;
1059 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
1061 if (!this->internal_thread)
1062 ves_icall_System_Threading_Thread_ConstructInternalThread (this);
1063 internal = this->internal_thread;
1065 ensure_synch_cs_set (internal);
1067 EnterCriticalSection (internal->synch_cs);
1069 if ((internal->state & ThreadState_Unstarted) == 0) {
1070 LeaveCriticalSection (internal->synch_cs);
1071 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
1075 internal->small_id = -1;
1077 if ((internal->state & ThreadState_Aborted) != 0) {
1078 LeaveCriticalSection (internal->synch_cs);
1083 /* This is freed in start_wrapper */
1084 start_info = g_new0 (struct StartInfo, 1);
1085 start_info->func = start_func;
1086 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
1087 start_info->delegate = start;
1088 start_info->obj = this;
1089 g_assert (this->obj.vtable->domain == mono_domain_get ());
1091 internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
1092 if (internal->start_notify==NULL) {
1093 LeaveCriticalSection (internal->synch_cs);
1094 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
1095 g_free (start_info);
1099 mono_threads_lock ();
1100 if (threads_starting_up == NULL) {
1101 MONO_GC_REGISTER_ROOT (threads_starting_up);
1102 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
1104 mono_g_hash_table_insert (threads_starting_up, this, this);
1105 mono_threads_unlock ();
1107 thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
1108 CREATE_SUSPENDED, &tid);
1110 LeaveCriticalSection (internal->synch_cs);
1111 mono_threads_lock ();
1112 mono_g_hash_table_remove (threads_starting_up, this);
1113 mono_threads_unlock ();
1114 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
1118 internal->handle=thread;
1120 small_id_alloc (internal);
1122 /* Don't call handle_store() here, delay it to Start.
1123 * We can't join a thread (trying to will just block
1124 * forever) until it actually starts running, so don't
1125 * store the handle till then.
1128 mono_thread_start (this);
1130 internal->state &= ~ThreadState_Unstarted;
1132 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
1134 LeaveCriticalSection (internal->synch_cs);
1139 void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
1141 MONO_ARCH_SAVE_REGS;
1143 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1146 CloseHandle (thread);
1148 if (this->synch_cs) {
1149 DeleteCriticalSection (this->synch_cs);
1150 g_free (this->synch_cs);
1151 this->synch_cs = NULL;
1154 g_assert (!this->abort_exc && !this->abort_state_handle);
1156 g_free (this->name);
1159 static void mono_thread_start (MonoThread *thread)
1161 MonoInternalThread *internal = thread->internal_thread;
1163 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1165 /* Only store the handle when the thread is about to be
1166 * launched, to avoid the main thread deadlocking while trying
1167 * to clean up a thread that will never be signalled.
1169 if (!handle_store (thread))
1172 ResumeThread (internal->handle);
1174 if(internal->start_notify!=NULL) {
1175 /* Wait for the thread to set up its TLS data etc, so
1176 * theres no potential race condition if someone tries
1177 * to look up the data believing the thread has
1181 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1183 WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
1184 CloseHandle (internal->start_notify);
1185 internal->start_notify = NULL;
1188 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1191 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1194 MonoInternalThread *thread = mono_thread_internal_current ();
1196 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1198 mono_thread_current_check_pending_interrupt ();
1200 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1202 res = SleepEx(ms,TRUE);
1204 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1206 if (res == WAIT_IO_COMPLETION) { /* we might have been interrupted */
1207 MonoException* exc = mono_thread_execute_interruption (thread);
1208 if (exc) mono_raise_exception (exc);
1212 void ves_icall_System_Threading_Thread_SpinWait_nop (void)
1217 ves_icall_System_Threading_Thread_GetDomainID (void)
1219 MONO_ARCH_SAVE_REGS;
1221 return mono_domain_get()->domain_id;
1225 ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj)
1229 ensure_synch_cs_set (this_obj);
1231 EnterCriticalSection (this_obj->synch_cs);
1233 if (!this_obj->name)
1236 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1238 LeaveCriticalSection (this_obj->synch_cs);
1244 ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
1246 ensure_synch_cs_set (this_obj);
1248 EnterCriticalSection (this_obj->synch_cs);
1250 if (this_obj->name) {
1251 LeaveCriticalSection (this_obj->synch_cs);
1253 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1257 this_obj->name = g_new (gunichar2, mono_string_length (name));
1258 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1259 this_obj->name_len = mono_string_length (name);
1262 this_obj->name = NULL;
1264 LeaveCriticalSection (this_obj->synch_cs);
1268 lookup_cached_culture (MonoInternalThread *this, MonoDomain *domain, int start_idx)
1273 if (this->cached_culture_info) {
1274 domain = mono_domain_get ();
1275 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1276 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1277 if (res && res->vtable->domain == domain)
1285 /* If the array is already in the requested domain, we just return it,
1286 otherwise we return a copy in that domain. */
1288 byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
1295 if (mono_object_domain (arr) == domain)
1298 copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
1299 memcpy (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
1304 ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
1306 return byte_array_to_domain (arr, mono_get_root_domain ());
1310 ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
1312 return byte_array_to_domain (arr, mono_domain_get ());
1316 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoInternalThread *this)
1318 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1322 cache_culture (MonoInternalThread *this, MonoObject *culture, int start_idx)
1325 MonoDomain *domain = mono_domain_get ();
1328 int same_domain_slot = -1;
1330 ensure_synch_cs_set (this);
1332 EnterCriticalSection (this->synch_cs);
1334 if (!this->cached_culture_info)
1335 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1337 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1338 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1342 /* we continue, because there may be a slot used with the same domain */
1346 if (obj->vtable->domain == domain) {
1347 same_domain_slot = i;
1351 if (same_domain_slot >= 0)
1352 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1353 else if (free_slot >= 0)
1354 mono_array_setref (this->cached_culture_info, free_slot, culture);
1355 /* we may want to replace an existing entry here, even when no suitable slot is found */
1357 LeaveCriticalSection (this->synch_cs);
1361 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1363 MonoDomain *domain = mono_object_get_domain (&this->obj);
1364 g_assert (domain == mono_domain_get ());
1365 cache_culture (this->internal_thread, culture, CULTURES_START_IDX);
1369 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoInternalThread *this)
1371 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1375 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1377 MonoDomain *domain = mono_object_get_domain (&this->obj);
1378 g_assert (domain == mono_domain_get ());
1379 cache_culture (this->internal_thread, culture, UICULTURES_START_IDX);
1383 mono_thread_current (void)
1385 MonoDomain *domain = mono_domain_get ();
1386 MonoInternalThread *internal = mono_thread_internal_current ();
1387 MonoThread **current_thread_ptr;
1389 g_assert (internal);
1390 current_thread_ptr = get_current_thread_ptr_for_domain (domain, internal);
1392 if (!*current_thread_ptr) {
1393 g_assert (domain != mono_get_root_domain ());
1394 *current_thread_ptr = new_thread_with_internal (domain, internal);
1396 return *current_thread_ptr;
1400 mono_thread_internal_current (void)
1402 MonoInternalThread *res = GET_CURRENT_OBJECT ();
1403 THREAD_DEBUG (g_message ("%s: returning %p", __func__, res));
1407 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *this,
1408 int ms, HANDLE thread)
1410 MonoInternalThread *cur_thread = mono_thread_internal_current ();
1413 mono_thread_current_check_pending_interrupt ();
1415 ensure_synch_cs_set (this);
1417 EnterCriticalSection (this->synch_cs);
1419 if ((this->state & ThreadState_Unstarted) != 0) {
1420 LeaveCriticalSection (this->synch_cs);
1422 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1426 LeaveCriticalSection (this->synch_cs);
1431 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1433 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1435 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1437 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1439 if(ret==WAIT_OBJECT_0) {
1440 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1445 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1450 /* FIXME: exitContext isnt documented */
1451 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1457 MonoObject *waitHandle;
1458 MonoInternalThread *thread = mono_thread_internal_current ();
1460 /* Do this WaitSleepJoin check before creating objects */
1461 mono_thread_current_check_pending_interrupt ();
1463 numhandles = mono_array_length(mono_handles);
1464 handles = g_new0(HANDLE, numhandles);
1466 for(i = 0; i < numhandles; i++) {
1467 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1468 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1475 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1477 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1479 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1483 if(ret==WAIT_FAILED) {
1484 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1486 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1487 /* Do we want to try again if we get
1488 * WAIT_IO_COMPLETION? The documentation for
1489 * WaitHandle doesn't give any clues. (We'd have to
1490 * fiddle with the timeout if we retry.)
1492 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1499 /* FIXME: exitContext isnt documented */
1500 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1506 MonoObject *waitHandle;
1507 MonoInternalThread *thread = mono_thread_internal_current ();
1509 /* Do this WaitSleepJoin check before creating objects */
1510 mono_thread_current_check_pending_interrupt ();
1512 numhandles = mono_array_length(mono_handles);
1513 handles = g_new0(HANDLE, numhandles);
1515 for(i = 0; i < numhandles; i++) {
1516 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1517 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1524 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1526 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1528 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1532 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1535 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1537 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1538 return ret - WAIT_OBJECT_0;
1540 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1541 return ret - WAIT_ABANDONED_0;
1548 /* FIXME: exitContext isnt documented */
1549 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1552 MonoInternalThread *thread = mono_thread_internal_current ();
1554 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1560 mono_thread_current_check_pending_interrupt ();
1562 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1564 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1566 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1568 if(ret==WAIT_FAILED) {
1569 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1571 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1572 /* Do we want to try again if we get
1573 * WAIT_IO_COMPLETION? The documentation for
1574 * WaitHandle doesn't give any clues. (We'd have to
1575 * fiddle with the timeout if we retry.)
1577 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1585 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
1588 MonoInternalThread *thread = mono_thread_internal_current ();
1590 MONO_ARCH_SAVE_REGS;
1595 mono_thread_current_check_pending_interrupt ();
1597 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1599 ret = SignalObjectAndWait (toSignal, toWait, ms, TRUE);
1601 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1603 return (!(ret == WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION || ret == WAIT_FAILED));
1606 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1610 MONO_ARCH_SAVE_REGS;
1615 mutex = CreateMutex (NULL, owned, NULL);
1617 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1619 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1627 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1628 MONO_ARCH_SAVE_REGS;
1630 return(ReleaseMutex (handle));
1633 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1639 MONO_ARCH_SAVE_REGS;
1641 *error = ERROR_SUCCESS;
1643 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1645 *error = GetLastError ();
1652 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1656 MONO_ARCH_SAVE_REGS;
1661 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1663 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1664 mono_string_chars (name));
1666 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1674 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1678 MONO_ARCH_SAVE_REGS;
1680 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1685 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1689 MONO_ARCH_SAVE_REGS;
1691 *error = ERROR_SUCCESS;
1693 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1695 *error = GetLastError ();
1701 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1705 MONO_ARCH_SAVE_REGS;
1710 event = CreateEvent (NULL, manual, initial, NULL);
1712 event = CreateEvent (NULL, manual, initial,
1713 mono_string_chars (name));
1715 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1723 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1724 MONO_ARCH_SAVE_REGS;
1726 return (SetEvent(handle));
1729 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1730 MONO_ARCH_SAVE_REGS;
1732 return (ResetEvent(handle));
1736 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1737 MONO_ARCH_SAVE_REGS;
1739 CloseHandle (handle);
1742 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1748 MONO_ARCH_SAVE_REGS;
1750 *error = ERROR_SUCCESS;
1752 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1754 *error = GetLastError ();
1760 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1762 MONO_ARCH_SAVE_REGS;
1764 return InterlockedIncrement (location);
1767 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1771 MONO_ARCH_SAVE_REGS;
1773 mono_interlocked_lock ();
1777 mono_interlocked_unlock ();
1783 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1785 MONO_ARCH_SAVE_REGS;
1787 return InterlockedDecrement(location);
1790 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1794 MONO_ARCH_SAVE_REGS;
1796 mono_interlocked_lock ();
1800 mono_interlocked_unlock ();
1805 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1807 MONO_ARCH_SAVE_REGS;
1809 return InterlockedExchange(location, value);
1812 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1815 res = (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1816 mono_gc_wbarrier_generic_nostore (location);
1820 gpointer ves_icall_System_Threading_Interlocked_Exchange_IntPtr (gpointer *location, gpointer value)
1822 return InterlockedExchangePointer(location, value);
1825 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1827 IntFloatUnion val, ret;
1829 MONO_ARCH_SAVE_REGS;
1832 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1838 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1840 #if SIZEOF_VOID_P == 8
1841 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1846 * According to MSDN, this function is only atomic with regards to the
1847 * other Interlocked functions on 32 bit platforms.
1849 mono_interlocked_lock ();
1852 mono_interlocked_unlock ();
1859 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1861 #if SIZEOF_VOID_P == 8
1862 LongDoubleUnion val, ret;
1865 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1872 * According to MSDN, this function is only atomic with regards to the
1873 * other Interlocked functions on 32 bit platforms.
1875 mono_interlocked_lock ();
1878 mono_interlocked_unlock ();
1884 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1886 MONO_ARCH_SAVE_REGS;
1888 return InterlockedCompareExchange(location, value, comparand);
1891 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1894 res = (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1895 mono_gc_wbarrier_generic_nostore (location);
1899 gpointer ves_icall_System_Threading_Interlocked_CompareExchange_IntPtr(gpointer *location, gpointer value, gpointer comparand)
1901 return InterlockedCompareExchangePointer(location, value, comparand);
1904 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1906 IntFloatUnion val, ret, cmp;
1908 MONO_ARCH_SAVE_REGS;
1911 cmp.fval = comparand;
1912 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1918 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1920 #if SIZEOF_VOID_P == 8
1921 LongDoubleUnion val, comp, ret;
1924 comp.fval = comparand;
1925 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1931 mono_interlocked_lock ();
1933 if (old == comparand)
1935 mono_interlocked_unlock ();
1942 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1944 #if SIZEOF_VOID_P == 8
1945 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1949 mono_interlocked_lock ();
1951 if (old == comparand)
1953 mono_interlocked_unlock ();
1960 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1963 res = InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1964 mono_gc_wbarrier_generic_nostore (location);
1969 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1972 res = InterlockedExchangePointer ((gpointer *)location, value);
1973 mono_gc_wbarrier_generic_nostore (location);
1978 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1980 #if SIZEOF_VOID_P == 8
1981 /* Should be implemented as a JIT intrinsic */
1982 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1987 mono_interlocked_lock ();
1989 *location = orig + value;
1990 mono_interlocked_unlock ();
1992 return orig + value;
1997 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1999 #if SIZEOF_VOID_P == 8
2000 /* Should be implemented as a JIT intrinsic */
2001 mono_raise_exception (mono_get_exception_not_implemented (NULL));
2006 mono_interlocked_lock ();
2008 *location = orig + value;
2009 mono_interlocked_unlock ();
2011 return orig + value;
2016 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
2018 #if SIZEOF_VOID_P == 8
2019 /* 64 bit reads are already atomic */
2024 mono_interlocked_lock ();
2026 mono_interlocked_unlock ();
2033 ves_icall_System_Threading_Thread_MemoryBarrier (void)
2035 mono_threads_lock ();
2036 mono_threads_unlock ();
2040 ves_icall_System_Threading_Thread_ClrState (MonoInternalThread* this, guint32 state)
2042 mono_thread_clr_state (this, state);
2044 if (state & ThreadState_Background) {
2045 /* If the thread changes the background mode, the main thread has to
2046 * be notified, since it has to rebuild the list of threads to
2049 SetEvent (background_change_event);
2054 ves_icall_System_Threading_Thread_SetState (MonoInternalThread* this, guint32 state)
2056 mono_thread_set_state (this, state);
2058 if (state & ThreadState_Background) {
2059 /* If the thread changes the background mode, the main thread has to
2060 * be notified, since it has to rebuild the list of threads to
2063 SetEvent (background_change_event);
2068 ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
2072 ensure_synch_cs_set (this);
2074 EnterCriticalSection (this->synch_cs);
2076 state = this->state;
2078 LeaveCriticalSection (this->synch_cs);
2083 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *this)
2085 gboolean throw = FALSE;
2087 ensure_synch_cs_set (this);
2089 if (this == mono_thread_internal_current ())
2092 EnterCriticalSection (this->synch_cs);
2094 this->thread_interrupt_requested = TRUE;
2096 if (this->state & ThreadState_WaitSleepJoin) {
2100 LeaveCriticalSection (this->synch_cs);
2103 signal_thread_state_change (this);
2107 void mono_thread_current_check_pending_interrupt ()
2109 MonoInternalThread *thread = mono_thread_internal_current ();
2110 gboolean throw = FALSE;
2112 mono_debugger_check_interruption ();
2114 ensure_synch_cs_set (thread);
2116 EnterCriticalSection (thread->synch_cs);
2118 if (thread->thread_interrupt_requested) {
2120 thread->thread_interrupt_requested = FALSE;
2123 LeaveCriticalSection (thread->synch_cs);
2126 mono_raise_exception (mono_get_exception_thread_interrupted ());
2131 mono_thread_get_abort_signal (void)
2133 #ifdef PLATFORM_WIN32
2143 static int abort_signum = -1;
2145 if (abort_signum != -1)
2146 return abort_signum;
2147 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
2148 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
2149 struct sigaction sinfo;
2150 sigaction (i, NULL, &sinfo);
2151 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2156 /* fallback to the old way */
2159 #endif /* PLATFORM_WIN32 */
2162 #ifdef PLATFORM_WIN32
2163 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2165 MonoException* exc = mono_thread_request_interruption (FALSE);
2166 if (exc) mono_raise_exception (exc);
2168 #endif /* PLATFORM_WIN32 */
2171 * signal_thread_state_change
2173 * Tells the thread that his state has changed and it has to enter the new
2174 * state as soon as possible.
2176 static void signal_thread_state_change (MonoInternalThread *thread)
2178 if (thread == mono_thread_internal_current ()) {
2179 /* Do it synchronously */
2180 MonoException *exc = mono_thread_request_interruption (FALSE);
2182 mono_raise_exception (exc);
2185 #ifdef PLATFORM_WIN32
2186 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2188 /* fixme: store the state somewhere */
2189 #ifdef PTHREAD_POINTER_ID
2190 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2192 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2196 * This will cause waits to be broken.
2197 * It will also prevent the thread from entering a wait, so if the thread returns
2198 * from the wait before it receives the abort signal, it will just spin in the wait
2199 * functions in the io-layer until the signal handler calls QueueUserAPC which will
2202 wapi_interrupt_thread (thread->handle);
2203 #endif /* PLATFORM_WIN32 */
2207 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
2209 ensure_synch_cs_set (thread);
2211 EnterCriticalSection (thread->synch_cs);
2213 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2214 (thread->state & ThreadState_StopRequested) != 0 ||
2215 (thread->state & ThreadState_Stopped) != 0)
2217 LeaveCriticalSection (thread->synch_cs);
2221 if ((thread->state & ThreadState_Unstarted) != 0) {
2222 thread->state |= ThreadState_Aborted;
2223 LeaveCriticalSection (thread->synch_cs);
2227 thread->state |= ThreadState_AbortRequested;
2228 if (thread->abort_state_handle)
2229 mono_gchandle_free (thread->abort_state_handle);
2231 thread->abort_state_handle = mono_gchandle_new (state, FALSE);
2232 g_assert (thread->abort_state_handle);
2234 thread->abort_state_handle = 0;
2236 thread->abort_exc = NULL;
2238 LeaveCriticalSection (thread->synch_cs);
2240 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2242 /* During shutdown, we can't wait for other threads */
2244 /* Make sure the thread is awake */
2245 mono_thread_resume (thread);
2247 signal_thread_state_change (thread);
2251 ves_icall_System_Threading_Thread_ResetAbort (void)
2253 MonoInternalThread *thread = mono_thread_internal_current ();
2255 ensure_synch_cs_set (thread);
2257 EnterCriticalSection (thread->synch_cs);
2259 thread->state &= ~ThreadState_AbortRequested;
2261 if (!thread->abort_exc) {
2262 const char *msg = "Unable to reset abort because no abort was requested";
2263 LeaveCriticalSection (thread->synch_cs);
2264 mono_raise_exception (mono_get_exception_thread_state (msg));
2266 thread->abort_exc = NULL;
2267 if (thread->abort_state_handle) {
2268 mono_gchandle_free (thread->abort_state_handle);
2269 /* This is actually not necessary - the handle
2270 only counts if the exception is set */
2271 thread->abort_state_handle = 0;
2275 LeaveCriticalSection (thread->synch_cs);
2279 serialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2281 static MonoMethod *serialize_method;
2286 if (!serialize_method) {
2287 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2288 serialize_method = mono_class_get_method_from_name (klass, "SerializeCallData", -1);
2291 if (!serialize_method) {
2296 g_assert (!obj->vtable->klass->marshalbyref);
2300 array = mono_runtime_invoke (serialize_method, NULL, params, exc);
2308 deserialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
2310 static MonoMethod *deserialize_method;
2315 if (!deserialize_method) {
2316 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
2317 deserialize_method = mono_class_get_method_from_name (klass, "DeserializeCallData", -1);
2319 if (!deserialize_method) {
2326 result = mono_runtime_invoke (deserialize_method, NULL, params, exc);
2334 make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
2336 static MonoMethod *get_proxy_method;
2338 MonoDomain *domain = mono_domain_get ();
2339 MonoRealProxy *real_proxy;
2340 MonoReflectionType *reflection_type;
2341 MonoTransparentProxy *transparent_proxy;
2343 if (!get_proxy_method)
2344 get_proxy_method = mono_class_get_method_from_name (mono_defaults.real_proxy_class, "GetTransparentProxy", 0);
2346 g_assert (obj->vtable->klass->marshalbyref);
2348 real_proxy = (MonoRealProxy*) mono_object_new (domain, mono_defaults.real_proxy_class);
2349 reflection_type = mono_type_get_object (domain, &obj->vtable->klass->byval_arg);
2351 real_proxy->class_to_proxy = reflection_type;
2352 real_proxy->unwrapped_server = obj;
2355 transparent_proxy = (MonoTransparentProxy*) mono_runtime_invoke (get_proxy_method, real_proxy, NULL, exc);
2359 return (MonoObject*) transparent_proxy;
2363 ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
2365 MonoInternalThread *thread = this->internal_thread;
2366 MonoObject *state, *serialized, *deserialized = NULL, *exc;
2368 gboolean failure = FALSE;
2370 if (!thread->abort_state_handle)
2373 state = mono_gchandle_get_target (thread->abort_state_handle);
2376 domain = mono_domain_get ();
2377 if (state->vtable->domain == domain)
2380 if (state->vtable->klass->marshalbyref) {
2381 deserialized = make_transparent_proxy (state, &failure, &exc);
2383 mono_domain_set_internal_with_options (state->vtable->domain, FALSE);
2384 serialized = serialize_object (state, &failure, &exc);
2385 mono_domain_set_internal_with_options (domain, FALSE);
2387 deserialized = deserialize_object (serialized, &failure, &exc);
2391 MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
2393 MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
2394 mono_raise_exception (invalid_op_exc);
2397 return deserialized;
2401 mono_thread_suspend (MonoInternalThread *thread)
2403 ensure_synch_cs_set (thread);
2405 EnterCriticalSection (thread->synch_cs);
2407 if ((thread->state & ThreadState_Unstarted) != 0 ||
2408 (thread->state & ThreadState_Aborted) != 0 ||
2409 (thread->state & ThreadState_Stopped) != 0)
2411 LeaveCriticalSection (thread->synch_cs);
2415 if ((thread->state & ThreadState_Suspended) != 0 ||
2416 (thread->state & ThreadState_SuspendRequested) != 0 ||
2417 (thread->state & ThreadState_StopRequested) != 0)
2419 LeaveCriticalSection (thread->synch_cs);
2423 thread->state |= ThreadState_SuspendRequested;
2425 LeaveCriticalSection (thread->synch_cs);
2427 signal_thread_state_change (thread);
2432 ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
2434 if (!mono_thread_suspend (thread))
2435 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2439 mono_thread_resume (MonoInternalThread *thread)
2441 ensure_synch_cs_set (thread);
2443 EnterCriticalSection (thread->synch_cs);
2445 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2446 thread->state &= ~ThreadState_SuspendRequested;
2447 LeaveCriticalSection (thread->synch_cs);
2451 if ((thread->state & ThreadState_Suspended) == 0 ||
2452 (thread->state & ThreadState_Unstarted) != 0 ||
2453 (thread->state & ThreadState_Aborted) != 0 ||
2454 (thread->state & ThreadState_Stopped) != 0)
2456 LeaveCriticalSection (thread->synch_cs);
2460 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2461 if (thread->resume_event == NULL) {
2462 LeaveCriticalSection (thread->synch_cs);
2466 /* Awake the thread */
2467 SetEvent (thread->suspend_event);
2469 LeaveCriticalSection (thread->synch_cs);
2471 /* Wait for the thread to awake */
2472 WaitForSingleObject (thread->resume_event, INFINITE);
2473 CloseHandle (thread->resume_event);
2474 thread->resume_event = NULL;
2480 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2482 if (!thread->internal_thread || !mono_thread_resume (thread->internal_thread))
2483 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2487 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2492 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2493 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2494 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2496 *((gboolean*)data) = TRUE;
2503 is_running_protected_wrapper (void)
2505 gboolean found = FALSE;
2506 mono_stack_walk (find_wrapper, &found);
2510 void mono_thread_internal_stop (MonoInternalThread *thread)
2512 ensure_synch_cs_set (thread);
2514 EnterCriticalSection (thread->synch_cs);
2516 if ((thread->state & ThreadState_StopRequested) != 0 ||
2517 (thread->state & ThreadState_Stopped) != 0)
2519 LeaveCriticalSection (thread->synch_cs);
2523 /* Make sure the thread is awake */
2524 mono_thread_resume (thread);
2526 thread->state |= ThreadState_StopRequested;
2527 thread->state &= ~ThreadState_AbortRequested;
2529 LeaveCriticalSection (thread->synch_cs);
2531 signal_thread_state_change (thread);
2534 void mono_thread_stop (MonoThread *thread)
2536 mono_thread_internal_stop (thread->internal_thread);
2540 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2542 return *((volatile gint8 *) (ptr));
2546 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2548 return *((volatile gint16 *) (ptr));
2552 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2554 return *((volatile gint32 *) (ptr));
2558 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2560 return *((volatile gint64 *) (ptr));
2564 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2566 return (void *) *((volatile void **) ptr);
2570 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2572 *((volatile gint8 *) ptr) = value;
2576 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2578 *((volatile gint16 *) ptr) = value;
2582 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2584 *((volatile gint32 *) ptr) = value;
2588 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2590 *((volatile gint64 *) ptr) = value;
2594 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2596 *((volatile void **) ptr) = value;
2600 ves_icall_System_Threading_Thread_VolatileWriteObject (void *ptr, void *value)
2602 mono_gc_wbarrier_generic_store (ptr, value);
2605 void mono_thread_init (MonoThreadStartCB start_cb,
2606 MonoThreadAttachCB attach_cb)
2608 MONO_GC_REGISTER_ROOT (small_id_table);
2609 InitializeCriticalSection(&threads_mutex);
2610 InitializeCriticalSection(&interlocked_mutex);
2611 InitializeCriticalSection(&contexts_mutex);
2612 InitializeCriticalSection(&delayed_free_table_mutex);
2613 InitializeCriticalSection(&small_id_mutex);
2615 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2616 g_assert(background_change_event != NULL);
2618 mono_init_static_data_info (&thread_static_info);
2619 mono_init_static_data_info (&context_static_info);
2621 current_object_key=TlsAlloc();
2622 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2624 mono_thread_start_cb = start_cb;
2625 mono_thread_attach_cb = attach_cb;
2627 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2629 /* Get a pseudo handle to the current process. This is just a
2630 * kludge so that wapi can build a process handle if needed.
2631 * As a pseudo handle is returned, we don't need to clean
2634 GetCurrentProcess ();
2637 void mono_thread_cleanup (void)
2639 mono_thread_hazardous_try_free_all ();
2641 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2642 /* The main thread must abandon any held mutexes (particularly
2643 * important for named mutexes as they are shared across
2644 * processes, see bug 74680.) This will happen when the
2645 * thread exits, but if it's not running in a subthread it
2646 * won't exit in time.
2648 /* Using non-w32 API is a nasty kludge, but I couldn't find
2649 * anything in the documentation that would let me do this
2650 * here yet still be safe to call on windows.
2652 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2656 /* This stuff needs more testing, it seems one of these
2657 * critical sections can be locked when mono_thread_cleanup is
2660 DeleteCriticalSection (&threads_mutex);
2661 DeleteCriticalSection (&interlocked_mutex);
2662 DeleteCriticalSection (&contexts_mutex);
2663 DeleteCriticalSection (&delayed_free_table_mutex);
2664 DeleteCriticalSection (&small_id_mutex);
2665 CloseHandle (background_change_event);
2668 g_array_free (delayed_free_table, TRUE);
2669 delayed_free_table = NULL;
2671 TlsFree (current_object_key);
2675 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2677 mono_thread_cleanup_fn = func;
2681 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2683 thread->internal_thread->manage_callback = func;
2686 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2688 mono_thread_notify_pending_exc_fn = func;
2692 static void print_tids (gpointer key, gpointer value, gpointer user)
2694 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2695 * sizeof(uint) and a cast to uint would overflow
2697 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2698 * print this as a pointer.
2700 g_message ("Waiting for: %p", key);
2705 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2706 MonoInternalThread *threads[MAXIMUM_WAIT_OBJECTS];
2710 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2714 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2716 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2718 if(ret==WAIT_FAILED) {
2719 /* See the comment in build_wait_tids() */
2720 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2724 for(i=0; i<wait->num; i++)
2725 CloseHandle (wait->handles[i]);
2727 if (ret == WAIT_TIMEOUT)
2730 for(i=0; i<wait->num; i++) {
2731 gsize tid = wait->threads[i]->tid;
2733 mono_threads_lock ();
2734 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2735 /* This thread must have been killed, because
2736 * it hasn't cleaned itself up. (It's just
2737 * possible that the thread exited before the
2738 * parent thread had a chance to store the
2739 * handle, and now there is another pointer to
2740 * the already-exited thread stored. In this
2741 * case, we'll just get two
2742 * mono_profiler_thread_end() calls for the
2746 mono_threads_unlock ();
2747 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2748 thread_cleanup (wait->threads[i]);
2750 mono_threads_unlock ();
2755 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2757 guint32 i, ret, count;
2759 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2761 /* Add the thread state change event, so it wakes up if a thread changes
2762 * to background mode.
2765 if (count < MAXIMUM_WAIT_OBJECTS) {
2766 wait->handles [count] = background_change_event;
2770 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2772 if(ret==WAIT_FAILED) {
2773 /* See the comment in build_wait_tids() */
2774 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2778 for(i=0; i<wait->num; i++)
2779 CloseHandle (wait->handles[i]);
2781 if (ret == WAIT_TIMEOUT)
2784 if (ret < wait->num) {
2785 gsize tid = wait->threads[ret]->tid;
2786 mono_threads_lock ();
2787 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2788 /* See comment in wait_for_tids about thread cleanup */
2789 mono_threads_unlock ();
2790 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2791 thread_cleanup (wait->threads [ret]);
2793 mono_threads_unlock ();
2797 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2799 struct wait_data *wait=(struct wait_data *)user;
2801 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2803 MonoInternalThread *thread=(MonoInternalThread *)value;
2805 /* Ignore background threads, we abort them later */
2806 /* Do not lock here since it is not needed and the caller holds threads_lock */
2807 if (thread->state & ThreadState_Background) {
2808 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2809 return; /* just leave, ignore */
2812 if (mono_gc_is_finalizer_internal_thread (thread)) {
2813 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2817 if (thread == mono_thread_internal_current ()) {
2818 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2822 if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread)) {
2823 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2827 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2828 if (handle == NULL) {
2829 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2833 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2834 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread->root_domain_thread) == TRUE)) {
2835 wait->handles[wait->num]=handle;
2836 wait->threads[wait->num]=thread;
2839 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2841 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2846 /* Just ignore the rest, we can't do anything with
2853 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2855 struct wait_data *wait=(struct wait_data *)user;
2856 gsize self = GetCurrentThreadId ();
2857 MonoInternalThread *thread = value;
2860 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2863 /* The finalizer thread is not a background thread */
2864 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2866 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2870 /* printf ("A: %d\n", wait->num); */
2871 wait->handles[wait->num]=thread->handle;
2872 wait->threads[wait->num]=thread;
2875 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2876 mono_thread_internal_stop (thread);
2880 return (thread->tid != self && !mono_gc_is_finalizer_internal_thread (thread));
2884 * mono_threads_set_shutting_down:
2886 * Is called by a thread that wants to shut down Mono. If the runtime is already
2887 * shutting down, the calling thread is suspended/stopped, and this function never
2891 mono_threads_set_shutting_down (void)
2893 MonoInternalThread *current_thread = mono_thread_internal_current ();
2895 mono_threads_lock ();
2897 if (shutting_down) {
2898 mono_threads_unlock ();
2900 /* Make sure we're properly suspended/stopped */
2902 EnterCriticalSection (current_thread->synch_cs);
2904 if ((current_thread->state & ThreadState_SuspendRequested) ||
2905 (current_thread->state & ThreadState_AbortRequested) ||
2906 (current_thread->state & ThreadState_StopRequested)) {
2907 LeaveCriticalSection (current_thread->synch_cs);
2908 mono_thread_execute_interruption (current_thread);
2910 current_thread->state |= ThreadState_Stopped;
2911 LeaveCriticalSection (current_thread->synch_cs);
2914 /* Wake up other threads potentially waiting for us */
2917 shutting_down = TRUE;
2919 /* Not really a background state change, but this will
2920 * interrupt the main thread if it is waiting for all
2921 * the other threads.
2923 SetEvent (background_change_event);
2925 mono_threads_unlock ();
2930 * mono_threads_is_shutting_down:
2932 * Returns whether a thread has commenced shutdown of Mono. Note that
2933 * if the function returns FALSE the caller must not assume that
2934 * shutdown is not in progress, because the situation might have
2935 * changed since the function returned. For that reason this function
2936 * is of very limited utility.
2939 mono_threads_is_shutting_down (void)
2941 return shutting_down;
2944 void mono_thread_manage (void)
2946 struct wait_data *wait=g_new0 (struct wait_data, 1);
2948 /* join each thread that's still running */
2949 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2951 mono_threads_lock ();
2953 THREAD_DEBUG (g_message("%s: No threads", __func__));
2954 mono_threads_unlock ();
2958 mono_threads_unlock ();
2961 mono_threads_lock ();
2962 if (shutting_down) {
2963 /* somebody else is shutting down */
2964 mono_threads_unlock ();
2967 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2968 mono_g_hash_table_foreach (threads, print_tids, NULL));
2970 ResetEvent (background_change_event);
2972 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2973 mono_threads_unlock ();
2975 /* Something to wait for */
2976 wait_for_tids_or_state_change (wait, INFINITE);
2978 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2979 } while(wait->num>0);
2981 mono_threads_set_shutting_down ();
2983 /* No new threads will be created after this point */
2985 mono_runtime_set_shutting_down ();
2987 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2988 mono_thread_pool_cleanup ();
2991 * Remove everything but the finalizer thread and self.
2992 * Also abort all the background threads
2995 mono_threads_lock ();
2998 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
3000 mono_threads_unlock ();
3002 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
3004 /* Something to wait for */
3005 wait_for_tids (wait, INFINITE);
3007 } while (wait->num > 0);
3010 * give the subthreads a chance to really quit (this is mainly needed
3011 * to get correct user and system times from getrusage/wait/time(1)).
3012 * This could be removed if we avoid pthread_detach() and use pthread_join().
3014 #ifndef PLATFORM_WIN32
3021 static void terminate_thread (gpointer key, gpointer value, gpointer user)
3023 MonoInternalThread *thread=(MonoInternalThread *)value;
3025 if(thread->tid != (gsize)user) {
3026 /*TerminateThread (thread->handle, -1);*/
3030 void mono_thread_abort_all_other_threads (void)
3032 gsize self = GetCurrentThreadId ();
3034 mono_threads_lock ();
3035 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
3036 mono_g_hash_table_size (threads));
3037 mono_g_hash_table_foreach (threads, print_tids, NULL));
3039 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
3041 mono_threads_unlock ();
3045 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
3047 MonoInternalThread *thread = (MonoInternalThread*)value;
3048 struct wait_data *wait = (struct wait_data*)user_data;
3052 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
3054 * This needs no locking.
3056 if ((thread->state & ThreadState_Suspended) != 0 ||
3057 (thread->state & ThreadState_Stopped) != 0)
3060 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3061 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3065 wait->handles [wait->num] = handle;
3066 wait->threads [wait->num] = thread;
3072 * mono_thread_suspend_all_other_threads:
3074 * Suspend all managed threads except the finalizer thread and this thread. It is
3075 * not possible to resume them later.
3077 void mono_thread_suspend_all_other_threads (void)
3079 struct wait_data *wait = g_new0 (struct wait_data, 1);
3081 gsize self = GetCurrentThreadId ();
3083 guint32 eventidx = 0;
3084 gboolean starting, finished;
3087 * The other threads could be in an arbitrary state at this point, i.e.
3088 * they could be starting up, shutting down etc. This means that there could be
3089 * threads which are not even in the threads hash table yet.
3093 * First we set a barrier which will be checked by all threads before they
3094 * are added to the threads hash table, and they will exit if the flag is set.
3095 * This ensures that no threads could be added to the hash later.
3096 * We will use shutting_down as the barrier for now.
3098 g_assert (shutting_down);
3101 * We make multiple calls to WaitForMultipleObjects since:
3102 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
3103 * - some threads could exit without becoming suspended
3108 * Make a copy of the hashtable since we can't do anything with
3109 * threads while threads_mutex is held.
3112 mono_threads_lock ();
3113 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
3114 mono_threads_unlock ();
3116 events = g_new0 (gpointer, wait->num);
3118 /* Get the suspended events that we'll be waiting for */
3119 for (i = 0; i < wait->num; ++i) {
3120 MonoInternalThread *thread = wait->threads [i];
3121 gboolean signal_suspend = FALSE;
3123 if ((thread->tid == self) || mono_gc_is_finalizer_internal_thread (thread)) {
3124 //CloseHandle (wait->handles [i]);
3125 wait->threads [i] = NULL; /* ignore this thread in next loop */
3129 ensure_synch_cs_set (thread);
3131 EnterCriticalSection (thread->synch_cs);
3133 if (thread->suspended_event == NULL) {
3134 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3135 if (thread->suspended_event == NULL) {
3136 /* Forget this one and go on to the next */
3137 LeaveCriticalSection (thread->synch_cs);
3142 if ((thread->state & ThreadState_Suspended) != 0 ||
3143 (thread->state & ThreadState_StopRequested) != 0 ||
3144 (thread->state & ThreadState_Stopped) != 0) {
3145 LeaveCriticalSection (thread->synch_cs);
3146 CloseHandle (wait->handles [i]);
3147 wait->threads [i] = NULL; /* ignore this thread in next loop */
3151 if ((thread->state & ThreadState_SuspendRequested) == 0)
3152 signal_suspend = TRUE;
3154 events [eventidx++] = thread->suspended_event;
3156 /* Convert abort requests into suspend requests */
3157 if ((thread->state & ThreadState_AbortRequested) != 0)
3158 thread->state &= ~ThreadState_AbortRequested;
3160 thread->state |= ThreadState_SuspendRequested;
3162 LeaveCriticalSection (thread->synch_cs);
3164 /* Signal the thread to suspend */
3166 signal_thread_state_change (thread);
3170 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
3171 for (i = 0; i < wait->num; ++i) {
3172 MonoInternalThread *thread = wait->threads [i];
3177 EnterCriticalSection (thread->synch_cs);
3178 if ((thread->state & ThreadState_Suspended) != 0) {
3179 CloseHandle (thread->suspended_event);
3180 thread->suspended_event = NULL;
3182 LeaveCriticalSection (thread->synch_cs);
3186 * If there are threads which are starting up, we wait until they
3187 * are suspended when they try to register in the threads hash.
3188 * This is guaranteed to finish, since the threads which can create new
3189 * threads get suspended after a while.
3190 * FIXME: The finalizer thread can still create new threads.
3192 mono_threads_lock ();
3193 if (threads_starting_up)
3194 starting = mono_g_hash_table_size (threads_starting_up) > 0;
3197 mono_threads_unlock ();
3211 collect_threads (gpointer key, gpointer value, gpointer user_data)
3213 MonoInternalThread *thread = (MonoInternalThread*)value;
3214 struct wait_data *wait = (struct wait_data*)user_data;
3217 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
3218 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3222 wait->handles [wait->num] = handle;
3223 wait->threads [wait->num] = thread;
3229 * mono_threads_request_thread_dump:
3231 * Ask all threads except the current to print their stacktrace to stdout.
3234 mono_threads_request_thread_dump (void)
3236 struct wait_data *wait = g_new0 (struct wait_data, 1);
3240 * Make a copy of the hashtable since we can't do anything with
3241 * threads while threads_mutex is held.
3243 mono_threads_lock ();
3244 mono_g_hash_table_foreach (threads, collect_threads, wait);
3245 mono_threads_unlock ();
3247 for (i = 0; i < wait->num; ++i) {
3248 MonoInternalThread *thread = wait->threads [i];
3250 if (!mono_gc_is_finalizer_internal_thread (thread) &&
3251 (thread != mono_thread_internal_current ()) &&
3252 !thread->thread_dump_requested) {
3253 thread->thread_dump_requested = TRUE;
3255 signal_thread_state_change (thread);
3258 CloseHandle (wait->handles [i]);
3263 * mono_thread_push_appdomain_ref:
3265 * Register that the current thread may have references to objects in domain
3266 * @domain on its stack. Each call to this function should be paired with a
3267 * call to pop_appdomain_ref.
3270 mono_thread_push_appdomain_ref (MonoDomain *domain)
3272 MonoInternalThread *thread = mono_thread_internal_current ();
3275 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
3276 mono_threads_lock ();
3277 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
3278 mono_threads_unlock ();
3283 mono_thread_pop_appdomain_ref (void)
3285 MonoInternalThread *thread = mono_thread_internal_current ();
3288 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
3289 mono_threads_lock ();
3290 /* FIXME: How can the list be empty ? */
3291 if (thread->appdomain_refs)
3292 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
3293 mono_threads_unlock ();
3298 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
3301 mono_threads_lock ();
3302 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
3303 mono_threads_unlock ();
3308 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
3310 return mono_thread_internal_has_appdomain_ref (thread->internal_thread, domain);
3313 typedef struct abort_appdomain_data {
3314 struct wait_data wait;
3316 } abort_appdomain_data;
3319 collect_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3321 MonoInternalThread *thread = (MonoInternalThread*)value;
3322 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3323 MonoDomain *domain = data->domain;
3325 if (mono_thread_internal_has_appdomain_ref (thread, domain)) {
3326 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3328 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3329 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3332 data->wait.handles [data->wait.num] = handle;
3333 data->wait.threads [data->wait.num] = thread;
3336 /* Just ignore the rest, we can't do anything with
3344 * mono_threads_abort_appdomain_threads:
3346 * Abort threads which has references to the given appdomain.
3349 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3351 abort_appdomain_data user_data;
3353 int orig_timeout = timeout;
3356 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3358 start_time = mono_msec_ticks ();
3360 mono_threads_lock ();
3362 user_data.domain = domain;
3363 user_data.wait.num = 0;
3364 /* This shouldn't take any locks */
3365 mono_g_hash_table_foreach (threads, collect_appdomain_thread, &user_data);
3366 mono_threads_unlock ();
3368 if (user_data.wait.num > 0) {
3369 /* Abort the threads outside the threads lock */
3370 for (i = 0; i < user_data.wait.num; ++i)
3371 ves_icall_System_Threading_Thread_Abort (user_data.wait.threads [i], NULL);
3374 * We should wait for the threads either to abort, or to leave the
3375 * domain. We can't do the latter, so we wait with a timeout.
3377 wait_for_tids (&user_data.wait, 100);
3380 /* Update remaining time */
3381 timeout -= mono_msec_ticks () - start_time;
3382 start_time = mono_msec_ticks ();
3384 if (orig_timeout != -1 && timeout < 0)
3387 while (user_data.wait.num > 0);
3389 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3395 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3397 MonoInternalThread *thread = (MonoInternalThread*)value;
3398 MonoDomain *domain = (MonoDomain*)user_data;
3401 /* No locking needed here */
3402 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3404 if (thread->cached_culture_info) {
3405 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3406 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3407 if (obj && obj->vtable->domain == domain)
3408 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3414 * mono_threads_clear_cached_culture:
3416 * Clear the cached_current_culture from all threads if it is in the
3420 mono_threads_clear_cached_culture (MonoDomain *domain)
3422 mono_threads_lock ();
3423 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3424 mono_threads_unlock ();
3428 * mono_thread_get_undeniable_exception:
3430 * Return an exception which needs to be raised when leaving a catch clause.
3431 * This is used for undeniable exception propagation.
3434 mono_thread_get_undeniable_exception (void)
3436 MonoInternalThread *thread = mono_thread_internal_current ();
3438 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3440 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3441 * exception if the thread no longer references a dying appdomain.
3443 thread->abort_exc->trace_ips = NULL;
3444 thread->abort_exc->stack_trace = NULL;
3445 return thread->abort_exc;
3451 #define NUM_STATIC_DATA_IDX 8
3452 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3453 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3458 * mono_alloc_static_data
3460 * Allocate memory blocks for storing threads or context static data
3463 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3465 guint idx = (offset >> 24) - 1;
3468 gpointer* static_data = *static_data_ptr;
3470 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3471 *static_data_ptr = static_data;
3472 static_data [0] = static_data;
3475 for (i = 1; i <= idx; ++i) {
3476 if (static_data [i])
3478 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3483 * mono_init_static_data_info
3485 * Initializes static data counters
3487 static void mono_init_static_data_info (StaticDataInfo *static_data)
3489 static_data->idx = 0;
3490 static_data->offset = 0;
3491 static_data->freelist = NULL;
3495 * mono_alloc_static_data_slot
3497 * Generates an offset for static data. static_data contains the counters
3498 * used to generate it.
3501 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3505 if (!static_data->idx && !static_data->offset) {
3507 * we use the first chunk of the first allocation also as
3508 * an array for the rest of the data
3510 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3512 static_data->offset += align - 1;
3513 static_data->offset &= ~(align - 1);
3514 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3515 static_data->idx ++;
3516 g_assert (size <= static_data_size [static_data->idx]);
3517 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3518 static_data->offset = 0;
3520 offset = static_data->offset | ((static_data->idx + 1) << 24);
3521 static_data->offset += size;
3526 * ensure thread static fields already allocated are valid for thread
3527 * This function is called when a thread is created or on thread attach.
3530 thread_adjust_static_data (MonoInternalThread *thread)
3534 mono_threads_lock ();
3535 if (thread_static_info.offset || thread_static_info.idx > 0) {
3536 /* get the current allocated size */
3537 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3538 mono_alloc_static_data (&(thread->static_data), offset);
3540 mono_threads_unlock ();
3544 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3546 MonoInternalThread *thread = value;
3547 guint32 offset = GPOINTER_TO_UINT (user);
3549 mono_alloc_static_data (&(thread->static_data), offset);
3552 static MonoThreadDomainTls*
3553 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3555 MonoThreadDomainTls* prev = NULL;
3556 MonoThreadDomainTls* tmp = static_data->freelist;
3558 if (tmp->size == size) {
3560 prev->next = tmp->next;
3562 static_data->freelist = tmp->next;
3571 * The offset for a special static variable is composed of three parts:
3572 * a bit that indicates the type of static data (0:thread, 1:context),
3573 * an index in the array of chunks of memory for the thread (thread->static_data)
3574 * and an offset in that chunk of mem. This allows allocating less memory in the
3579 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3582 if (static_type == SPECIAL_STATIC_THREAD)
3584 MonoThreadDomainTls *item;
3585 mono_threads_lock ();
3586 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3587 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3589 offset = item->offset;
3592 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3594 /* This can be called during startup */
3595 if (threads != NULL)
3596 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3597 mono_threads_unlock ();
3601 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3602 mono_contexts_lock ();
3603 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3604 mono_contexts_unlock ();
3605 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3611 mono_get_special_static_data (guint32 offset)
3613 /* The high bit means either thread (0) or static (1) data. */
3615 guint32 static_type = (offset & 0x80000000);
3618 offset &= 0x7fffffff;
3619 idx = (offset >> 24) - 1;
3621 if (static_type == 0) {
3622 return get_thread_static_data (mono_thread_internal_current (), offset);
3624 /* Allocate static data block under demand, since we don't have a list
3627 MonoAppContext *context = mono_context_get ();
3628 if (!context->static_data || !context->static_data [idx]) {
3629 mono_contexts_lock ();
3630 mono_alloc_static_data (&(context->static_data), offset);
3631 mono_contexts_unlock ();
3633 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3643 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3645 MonoInternalThread *thread = value;
3646 TlsOffsetSize *data = user;
3647 int idx = (data->offset >> 24) - 1;
3650 if (!thread->static_data || !thread->static_data [idx])
3652 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3653 memset (ptr, 0, data->size);
3657 do_free_special (gpointer key, gpointer value, gpointer data)
3659 MonoClassField *field = key;
3660 guint32 offset = GPOINTER_TO_UINT (value);
3661 guint32 static_type = (offset & 0x80000000);
3664 size = mono_type_size (field->type, &align);
3665 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3666 if (static_type == 0) {
3668 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3669 data.offset = offset & 0x7fffffff;
3671 if (threads != NULL)
3672 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3673 item->offset = offset;
3675 item->next = thread_static_info.freelist;
3676 thread_static_info.freelist = item;
3678 /* FIXME: free context static data as well */
3683 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3685 mono_threads_lock ();
3686 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3687 mono_threads_unlock ();
3690 static MonoClassField *local_slots = NULL;
3693 /* local tls data to get locals_slot from a thread */
3696 /* index in the locals_slot array */
3701 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3703 LocalSlotID *sid = user_data;
3704 MonoInternalThread *thread = (MonoInternalThread*)value;
3705 MonoArray *slots_array;
3707 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3708 * it is for the right domain, so we need to check if it is allocated an initialized
3709 * for the current thread.
3711 /*g_print ("handling thread %p\n", thread);*/
3712 if (!thread->static_data || !thread->static_data [sid->idx])
3714 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3715 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3717 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3721 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3729 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3731 g_warning ("local_slots field not found in Thread class");
3735 domain = mono_domain_get ();
3736 mono_domain_lock (domain);
3737 if (domain->special_static_fields)
3738 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3739 mono_domain_unlock (domain);
3742 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3743 sid.offset = GPOINTER_TO_UINT (addr);
3744 sid.offset &= 0x7fffffff;
3745 sid.idx = (sid.offset >> 24) - 1;
3746 mono_threads_lock ();
3747 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3748 mono_threads_unlock ();
3750 /* FIXME: clear the slot for MonoAppContexts, too */
3754 #ifdef PLATFORM_WIN32
3755 static void CALLBACK dummy_apc (ULONG_PTR param)
3759 static guint32 dummy_apc (gpointer param)
3766 * mono_thread_execute_interruption
3768 * Performs the operation that the requested thread state requires (abort,
3771 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
3773 ensure_synch_cs_set (thread);
3775 EnterCriticalSection (thread->synch_cs);
3777 /* MonoThread::interruption_requested can only be changed with atomics */
3778 if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
3779 /* this will consume pending APC calls */
3780 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3781 InterlockedDecrement (&thread_interruption_requested);
3782 #ifndef PLATFORM_WIN32
3783 /* Clear the interrupted flag of the thread so it can wait again */
3784 wapi_clear_interruption ();
3788 if ((thread->state & ThreadState_AbortRequested) != 0) {
3789 LeaveCriticalSection (thread->synch_cs);
3790 if (thread->abort_exc == NULL) {
3792 * This might be racy, but it has to be called outside the lock
3793 * since it calls managed code.
3795 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3797 return thread->abort_exc;
3799 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3800 thread->state &= ~ThreadState_SuspendRequested;
3801 thread->state |= ThreadState_Suspended;
3802 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3803 if (thread->suspend_event == NULL) {
3804 LeaveCriticalSection (thread->synch_cs);
3807 if (thread->suspended_event)
3808 SetEvent (thread->suspended_event);
3810 LeaveCriticalSection (thread->synch_cs);
3812 if (shutting_down) {
3813 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3818 WaitForSingleObject (thread->suspend_event, INFINITE);
3820 EnterCriticalSection (thread->synch_cs);
3822 CloseHandle (thread->suspend_event);
3823 thread->suspend_event = NULL;
3824 thread->state &= ~ThreadState_Suspended;
3826 /* The thread that requested the resume will have replaced this event
3827 * and will be waiting for it
3829 SetEvent (thread->resume_event);
3831 LeaveCriticalSection (thread->synch_cs);
3835 else if ((thread->state & ThreadState_StopRequested) != 0) {
3836 /* FIXME: do this through the JIT? */
3838 LeaveCriticalSection (thread->synch_cs);
3840 mono_thread_exit ();
3842 } else if (thread->thread_interrupt_requested) {
3844 thread->thread_interrupt_requested = FALSE;
3845 LeaveCriticalSection (thread->synch_cs);
3847 return(mono_get_exception_thread_interrupted ());
3850 LeaveCriticalSection (thread->synch_cs);
3856 * mono_thread_request_interruption
3858 * A signal handler can call this method to request the interruption of a
3859 * thread. The result of the interruption will depend on the current state of
3860 * the thread. If the result is an exception that needs to be throw, it is
3861 * provided as return value.
3864 mono_thread_request_interruption (gboolean running_managed)
3866 MonoInternalThread *thread = mono_thread_internal_current ();
3868 /* The thread may already be stopping */
3872 #ifdef PLATFORM_WIN32
3873 if (thread->interrupt_on_stop &&
3874 thread->state & ThreadState_StopRequested &&
3875 thread->state & ThreadState_Background)
3879 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3882 if (!running_managed || is_running_protected_wrapper ()) {
3883 /* Can't stop while in unmanaged code. Increase the global interruption
3884 request count. When exiting the unmanaged method the count will be
3885 checked and the thread will be interrupted. */
3887 InterlockedIncrement (&thread_interruption_requested);
3889 if (mono_thread_notify_pending_exc_fn && !running_managed)
3890 /* The JIT will notify the thread about the interruption */
3891 /* This shouldn't take any locks */
3892 mono_thread_notify_pending_exc_fn ();
3894 /* this will awake the thread if it is in WaitForSingleObject
3896 /* Our implementation of this function ignores the func argument */
3897 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3901 return mono_thread_execute_interruption (thread);
3905 gboolean mono_thread_interruption_requested ()
3907 if (thread_interruption_requested) {
3908 MonoInternalThread *thread = mono_thread_internal_current ();
3909 /* The thread may already be stopping */
3911 return (thread->interruption_requested);
3916 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3918 MonoInternalThread *thread = mono_thread_internal_current ();
3920 /* The thread may already be stopping */
3924 mono_debugger_check_interruption ();
3926 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3927 MonoException* exc = mono_thread_execute_interruption (thread);
3928 if (exc) mono_raise_exception (exc);
3933 * Performs the interruption of the current thread, if one has been requested,
3934 * and the thread is not running a protected wrapper.
3936 void mono_thread_interruption_checkpoint ()
3938 mono_thread_interruption_checkpoint_request (FALSE);
3942 * Performs the interruption of the current thread, if one has been requested.
3944 void mono_thread_force_interruption_checkpoint ()
3946 mono_thread_interruption_checkpoint_request (TRUE);
3950 * mono_thread_get_and_clear_pending_exception:
3952 * Return any pending exceptions for the current thread and clear it as a side effect.
3955 mono_thread_get_and_clear_pending_exception (void)
3957 MonoInternalThread *thread = mono_thread_internal_current ();
3959 /* The thread may already be stopping */
3963 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3964 return mono_thread_execute_interruption (thread);
3967 if (thread->pending_exception) {
3968 MonoException *exc = thread->pending_exception;
3970 thread->pending_exception = NULL;
3978 * mono_set_pending_exception:
3980 * Set the pending exception of the current thread to EXC. On platforms which
3981 * support it, the exception will be thrown when execution returns to managed code.
3982 * On other platforms, this function is equivalent to mono_raise_exception ().
3983 * Internal calls which report exceptions using this function instead of
3984 * raise_exception () might be called by JITted code using a more efficient calling
3988 mono_set_pending_exception (MonoException *exc)
3990 MonoInternalThread *thread = mono_thread_internal_current ();
3992 /* The thread may already be stopping */
3996 if (mono_thread_notify_pending_exc_fn) {
3997 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3999 mono_thread_notify_pending_exc_fn ();
4001 /* No way to notify the JIT about the exception, have to throw it now */
4002 mono_raise_exception (exc);
4007 * mono_thread_interruption_request_flag:
4009 * Returns the address of a flag that will be non-zero if an interruption has
4010 * been requested for a thread. The thread to interrupt may not be the current
4011 * thread, so an additional call to mono_thread_interruption_requested() or
4012 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
4015 gint32* mono_thread_interruption_request_flag ()
4017 return &thread_interruption_requested;
4021 mono_thread_init_apartment_state (void)
4023 #ifdef PLATFORM_WIN32
4024 MonoInternalThread* thread = mono_thread_internal_current ();
4026 /* Positive return value indicates success, either
4027 * S_OK if this is first CoInitialize call, or
4028 * S_FALSE if CoInitialize already called, but with same
4029 * threading model. A negative value indicates failure,
4030 * probably due to trying to change the threading model.
4032 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
4033 ? COINIT_APARTMENTTHREADED
4034 : COINIT_MULTITHREADED) < 0) {
4035 thread->apartment_state = ThreadApartmentState_Unknown;
4041 mono_thread_cleanup_apartment_state (void)
4043 #ifdef PLATFORM_WIN32
4044 MonoInternalThread* thread = mono_thread_internal_current ();
4046 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
4053 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
4055 ensure_synch_cs_set (thread);
4057 EnterCriticalSection (thread->synch_cs);
4058 thread->state |= state;
4059 LeaveCriticalSection (thread->synch_cs);
4063 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
4065 ensure_synch_cs_set (thread);
4067 EnterCriticalSection (thread->synch_cs);
4068 thread->state &= ~state;
4069 LeaveCriticalSection (thread->synch_cs);
4073 mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
4075 gboolean ret = FALSE;
4077 ensure_synch_cs_set (thread);
4079 EnterCriticalSection (thread->synch_cs);
4081 if ((thread->state & test) != 0) {
4085 LeaveCriticalSection (thread->synch_cs);
4090 static MonoClassField *execution_context_field;
4093 get_execution_context_addr (void)
4095 MonoDomain *domain = mono_domain_get ();
4098 if (!execution_context_field) {
4099 execution_context_field = mono_class_get_field_from_name (mono_defaults.thread_class,
4101 g_assert (execution_context_field);
4104 g_assert (mono_class_try_get_vtable (domain, mono_defaults.appdomain_class));
4106 mono_domain_lock (domain);
4107 offset = GPOINTER_TO_UINT (g_hash_table_lookup (domain->special_static_fields, execution_context_field));
4108 mono_domain_unlock (domain);
4111 return (MonoObject**) mono_get_special_static_data (offset);
4115 mono_thread_get_execution_context (void)
4117 return *get_execution_context_addr ();
4121 mono_thread_set_execution_context (MonoObject *ec)
4123 *get_execution_context_addr () = ec;
4126 static gboolean has_tls_get = FALSE;
4129 mono_runtime_set_has_tls_get (gboolean val)
4135 mono_runtime_has_tls_get (void)