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 * (C) 2001 Ximian, Inc.
18 #include <mono/metadata/object.h>
19 #include <mono/metadata/domain-internals.h>
20 #include <mono/metadata/profiler-private.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/threadpool.h>
23 #include <mono/metadata/threads-types.h>
24 #include <mono/metadata/exception.h>
25 #include <mono/metadata/environment.h>
26 #include <mono/metadata/monitor.h>
27 #include <mono/metadata/gc-internal.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/io-layer/io-layer.h>
30 #include <mono/metadata/object-internals.h>
31 #include <mono/metadata/mono-debug-debugger.h>
32 #include <mono/utils/mono-compiler.h>
33 #include <mono/utils/mono-mmap.h>
34 #include <mono/utils/mono-membar.h>
35 #include <mono/utils/mono-time.h>
37 #include <mono/metadata/gc-internal.h>
39 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
40 #define THREAD_DEBUG(a)
41 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
42 #define THREAD_WAIT_DEBUG(a)
43 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
44 #define LIBGC_DEBUG(a)
46 /* Provide this for systems with glib < 2.6 */
47 #ifndef G_GSIZE_FORMAT
48 # if GLIB_SIZEOF_LONG == 8
49 # define G_GSIZE_FORMAT "lu"
51 # define G_GSIZE_FORMAT "u"
57 guint32 (*func)(void *);
74 typedef struct _MonoThreadDomainTls MonoThreadDomainTls;
75 struct _MonoThreadDomainTls {
76 MonoThreadDomainTls *next;
84 MonoThreadDomainTls *freelist;
89 MonoHazardousFreeFunc free_func;
92 /* Number of cached culture objects in the MonoThread->cached_culture_info array
93 * (per-type): we use the first NUM entries for CultureInfo and the last for
94 * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
96 #define NUM_CACHED_CULTURES 4
97 #define CULTURES_START_IDX 0
98 #define UICULTURES_START_IDX NUM_CACHED_CULTURES
100 /* Controls access to the 'threads' hash table */
101 #define mono_threads_lock() EnterCriticalSection (&threads_mutex)
102 #define mono_threads_unlock() LeaveCriticalSection (&threads_mutex)
103 static CRITICAL_SECTION threads_mutex;
105 /* Controls access to context static data */
106 #define mono_contexts_lock() EnterCriticalSection (&contexts_mutex)
107 #define mono_contexts_unlock() LeaveCriticalSection (&contexts_mutex)
108 static CRITICAL_SECTION contexts_mutex;
110 /* Holds current status of static data heap */
111 static StaticDataInfo thread_static_info;
112 static StaticDataInfo context_static_info;
114 /* The hash of existing threads (key is thread ID) that need joining
117 static MonoGHashTable *threads=NULL;
120 * Threads which are starting up and they are not in the 'threads' hash yet.
121 * When handle_store is called for a thread, it will be removed from this hash table.
122 * Protected by mono_threads_lock ().
124 static MonoGHashTable *threads_starting_up = NULL;
126 /* The TLS key that holds the MonoObject assigned to each thread */
127 static guint32 current_object_key = -1;
129 #ifdef HAVE_KW_THREAD
130 /* we need to use both the Tls* functions and __thread because
131 * the gc needs to see all the threads
133 static __thread MonoThread * tls_current_object MONO_TLS_FAST;
134 #define SET_CURRENT_OBJECT(x) do { \
135 tls_current_object = x; \
136 TlsSetValue (current_object_key, x); \
138 #define GET_CURRENT_OBJECT() tls_current_object
140 #define SET_CURRENT_OBJECT(x) TlsSetValue (current_object_key, x);
141 #define GET_CURRENT_OBJECT() (MonoThread*) TlsGetValue (current_object_key);
144 /* function called at thread start */
145 static MonoThreadStartCB mono_thread_start_cb = NULL;
147 /* function called at thread attach */
148 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
150 /* function called at thread cleanup */
151 static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
153 /* function called to notify the runtime about a pending exception on the current thread */
154 static MonoThreadNotifyPendingExcFunc mono_thread_notify_pending_exc_fn = NULL;
156 /* The default stack size for each thread */
157 static guint32 default_stacksize = 0;
158 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
160 static void thread_adjust_static_data (MonoThread *thread);
161 static void mono_init_static_data_info (StaticDataInfo *static_data);
162 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
163 static gboolean mono_thread_resume (MonoThread* thread);
164 static void mono_thread_start (MonoThread *thread);
165 static void signal_thread_state_change (MonoThread *thread);
167 /* Spin lock for InterlockedXXX 64 bit functions */
168 #define mono_interlocked_lock() EnterCriticalSection (&interlocked_mutex)
169 #define mono_interlocked_unlock() LeaveCriticalSection (&interlocked_mutex)
170 static CRITICAL_SECTION interlocked_mutex;
172 /* global count of thread interruptions requested */
173 static gint32 thread_interruption_requested = 0;
175 /* Event signaled when a thread changes its background mode */
176 static HANDLE background_change_event;
178 /* The table for small ID assignment */
179 static CRITICAL_SECTION small_id_mutex;
180 static int small_id_table_size = 0;
181 static int small_id_next = 0;
182 static int highest_small_id = -1;
183 static MonoThread **small_id_table = NULL;
185 /* The hazard table */
186 #define HAZARD_TABLE_MAX_SIZE 16384 /* There cannot be more threads than this number. */
187 static volatile int hazard_table_size = 0;
188 static MonoThreadHazardPointers * volatile hazard_table = NULL;
190 /* The table where we keep pointers to blocks to be freed but that
191 have to wait because they're guarded by a hazard pointer. */
192 static CRITICAL_SECTION delayed_free_table_mutex;
193 static GArray *delayed_free_table = NULL;
195 static gboolean shutting_down = FALSE;
198 mono_thread_get_tls_key (void)
200 return current_object_key;
204 mono_thread_get_tls_offset (void)
207 MONO_THREAD_VAR_OFFSET (tls_current_object,offset);
211 /* handle_store() and handle_remove() manage the array of threads that
212 * still need to be waited for when the main thread exits.
214 * If handle_store() returns FALSE the thread must not be started
215 * because Mono is shutting down.
217 static gboolean handle_store(MonoThread *thread)
219 mono_threads_lock ();
221 THREAD_DEBUG (g_message ("%s: thread %p ID %"G_GSIZE_FORMAT, __func__, thread, (gsize)thread->tid));
223 if (threads_starting_up)
224 mono_g_hash_table_remove (threads_starting_up, thread);
227 mono_threads_unlock ();
232 MONO_GC_REGISTER_ROOT (threads);
233 threads=mono_g_hash_table_new(NULL, NULL);
236 /* We don't need to duplicate thread->handle, because it is
237 * only closed when the thread object is finalized by the GC.
239 mono_g_hash_table_insert(threads, (gpointer)(gsize)(thread->tid),
242 mono_threads_unlock ();
247 static gboolean handle_remove(MonoThread *thread)
250 gsize tid = thread->tid;
252 THREAD_DEBUG (g_message ("%s: thread ID %"G_GSIZE_FORMAT, __func__, tid));
254 mono_threads_lock ();
257 /* We have to check whether the thread object for the
258 * tid is still the same in the table because the
259 * thread might have been destroyed and the tid reused
260 * in the meantime, in which case the tid would be in
261 * the table, but with another thread object.
263 if (mono_g_hash_table_lookup (threads, (gpointer)tid) == thread) {
264 mono_g_hash_table_remove (threads, (gpointer)tid);
273 mono_threads_unlock ();
275 /* Don't close the handle here, wait for the object finalizer
276 * to do it. Otherwise, the following race condition applies:
278 * 1) Thread exits (and handle_remove() closes the handle)
280 * 2) Some other handle is reassigned the same slot
282 * 3) Another thread tries to join the first thread, and
283 * blocks waiting for the reassigned handle to be signalled
284 * (which might never happen). This is possible, because the
285 * thread calling Join() still has a reference to the first
292 * Allocate a small thread id.
294 * FIXME: The biggest part of this function is very similar to
295 * domain_id_alloc() in domain.c and should be merged.
298 small_id_alloc (MonoThread *thread)
302 EnterCriticalSection (&small_id_mutex);
304 if (!small_id_table) {
305 small_id_table_size = 2;
306 small_id_table = mono_gc_alloc_fixed (small_id_table_size * sizeof (MonoThread*), NULL);
308 for (i = small_id_next; i < small_id_table_size; ++i) {
309 if (!small_id_table [i]) {
315 for (i = 0; i < small_id_next; ++i) {
316 if (!small_id_table [i]) {
323 MonoThread **new_table;
324 int new_size = small_id_table_size * 2;
325 if (new_size >= (1 << 16))
326 g_assert_not_reached ();
327 id = small_id_table_size;
328 new_table = mono_gc_alloc_fixed (new_size * sizeof (MonoThread*), NULL);
329 memcpy (new_table, small_id_table, small_id_table_size * sizeof (void*));
330 mono_gc_free_fixed (small_id_table);
331 small_id_table = new_table;
332 small_id_table_size = new_size;
334 thread->small_id = id;
335 g_assert (small_id_table [id] == NULL);
336 small_id_table [id] = thread;
338 if (small_id_next > small_id_table_size)
341 if (id >= hazard_table_size) {
343 int pagesize = mono_pagesize ();
344 int num_pages = (hazard_table_size * sizeof (MonoThreadHazardPointers) + pagesize - 1) / pagesize;
346 if (hazard_table == NULL) {
347 hazard_table = mono_valloc (NULL,
348 sizeof (MonoThreadHazardPointers) * HAZARD_TABLE_MAX_SIZE,
352 g_assert (hazard_table != NULL);
353 page_addr = (guint8*)hazard_table + num_pages * pagesize;
355 g_assert (id < HAZARD_TABLE_MAX_SIZE);
357 mono_mprotect (page_addr, pagesize, MONO_MMAP_READ | MONO_MMAP_WRITE);
360 hazard_table_size = num_pages * pagesize / sizeof (MonoThreadHazardPointers);
362 g_assert (id < hazard_table_size);
364 hazard_table [id].hazard_pointers [0] = NULL;
365 hazard_table [id].hazard_pointers [1] = NULL;
368 if (id > highest_small_id) {
369 highest_small_id = id;
370 mono_memory_write_barrier ();
373 LeaveCriticalSection (&small_id_mutex);
379 small_id_free (int id)
381 g_assert (id >= 0 && id < small_id_table_size);
382 g_assert (small_id_table [id] != NULL);
384 small_id_table [id] = NULL;
388 is_pointer_hazardous (gpointer p)
391 int highest = highest_small_id;
393 g_assert (highest < hazard_table_size);
395 for (i = 0; i <= highest; ++i) {
396 if (hazard_table [i].hazard_pointers [0] == p
397 || hazard_table [i].hazard_pointers [1] == p)
404 MonoThreadHazardPointers*
405 mono_hazard_pointer_get (void)
407 MonoThread *current_thread = mono_thread_current ();
409 if (!(current_thread && current_thread->small_id >= 0)) {
410 static MonoThreadHazardPointers emerg_hazard_table;
411 g_warning ("Thread %p may have been prematurely finalized", current_thread);
412 return &emerg_hazard_table;
415 return &hazard_table [current_thread->small_id];
419 try_free_delayed_free_item (int index)
421 if (delayed_free_table->len > index) {
422 DelayedFreeItem item;
425 EnterCriticalSection (&delayed_free_table_mutex);
426 /* We have to check the length again because another
427 thread might have freed an item before we acquired
429 if (delayed_free_table->len > index) {
430 item = g_array_index (delayed_free_table, DelayedFreeItem, index);
432 if (!is_pointer_hazardous (item.p))
433 g_array_remove_index_fast (delayed_free_table, index);
437 LeaveCriticalSection (&delayed_free_table_mutex);
440 item.free_func (item.p);
445 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
449 /* First try to free a few entries in the delayed free
451 for (i = 2; i >= 0; --i)
452 try_free_delayed_free_item (i);
454 /* Now see if the pointer we're freeing is hazardous. If it
455 isn't, free it. Otherwise put it in the delay list. */
456 if (is_pointer_hazardous (p)) {
457 DelayedFreeItem item = { p, free_func };
459 ++mono_stats.hazardous_pointer_count;
461 EnterCriticalSection (&delayed_free_table_mutex);
462 g_array_append_val (delayed_free_table, item);
463 LeaveCriticalSection (&delayed_free_table_mutex);
469 mono_thread_hazardous_try_free_all (void)
474 if (!delayed_free_table)
477 len = delayed_free_table->len;
479 for (i = len - 1; i >= 0; --i)
480 try_free_delayed_free_item (i);
483 static void ensure_synch_cs_set (MonoThread *thread)
485 CRITICAL_SECTION *synch_cs;
487 if (thread->synch_cs != NULL) {
491 synch_cs = g_new0 (CRITICAL_SECTION, 1);
492 InitializeCriticalSection (synch_cs);
494 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
495 synch_cs, NULL) != NULL) {
496 /* Another thread must have installed this CS */
497 DeleteCriticalSection (synch_cs);
503 * NOTE: this function can be called also for threads different from the current one:
504 * make sure no code called from it will ever assume it is run on the thread that is
505 * getting cleaned up.
507 static void thread_cleanup (MonoThread *thread)
509 g_assert (thread != NULL);
511 /* if the thread is not in the hash it has been removed already */
512 if (!handle_remove (thread))
514 mono_release_type_locks (thread);
516 EnterCriticalSection (thread->synch_cs);
518 thread->state |= ThreadState_Stopped;
519 thread->state &= ~ThreadState_Background;
521 LeaveCriticalSection (thread->synch_cs);
523 mono_profiler_thread_end (thread->tid);
525 if (thread == mono_thread_current ())
526 mono_thread_pop_appdomain_ref ();
528 if (thread->serialized_culture_info)
529 g_free (thread->serialized_culture_info);
531 g_free (thread->name);
533 thread->cached_culture_info = NULL;
535 mono_gc_free_fixed (thread->static_data);
536 thread->static_data = NULL;
538 if (mono_thread_cleanup_fn)
539 mono_thread_cleanup_fn (thread);
541 small_id_free (thread->small_id);
542 thread->small_id = -2;
545 static guint32 WINAPI start_wrapper(void *data)
547 struct StartInfo *start_info=(struct StartInfo *)data;
548 guint32 (*start_func)(void *);
551 MonoThread *thread=start_info->obj;
552 MonoObject *start_delegate = start_info->delegate;
554 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
556 /* We can be sure start_info->obj->tid and
557 * start_info->obj->handle have been set, because the thread
558 * was created suspended, and these values were set before the
564 SET_CURRENT_OBJECT (thread);
566 mono_monitor_init_tls ();
568 /* Every thread references the appdomain which created it */
569 mono_thread_push_appdomain_ref (start_info->domain);
571 if (!mono_domain_set (start_info->domain, FALSE)) {
572 /* No point in raising an appdomain_unloaded exception here */
573 /* FIXME: Cleanup here */
574 mono_thread_pop_appdomain_ref ();
578 start_func = start_info->func;
579 start_arg = start_info->start_arg;
581 /* This MUST be called before any managed code can be
582 * executed, as it calls the callback function that (for the
583 * jit) sets the lmf marker.
585 mono_thread_new_init (tid, &tid, start_func);
586 thread->stack_ptr = &tid;
588 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
590 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
592 mono_profiler_thread_start (tid);
594 /* On 2.0 profile (and higher), set explicitly since state might have been
596 if (mono_get_runtime_info ()->framework_version [0] != '1') {
597 if (thread->apartment_state == ThreadApartmentState_Unknown)
598 thread->apartment_state = ThreadApartmentState_MTA;
601 mono_thread_init_apartment_state ();
603 if(thread->start_notify!=NULL) {
604 /* Let the thread that called Start() know we're
607 ReleaseSemaphore (thread->start_notify, 1, NULL);
610 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
613 thread_adjust_static_data (thread);
615 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
619 /* start_func is set only for unmanaged start functions */
621 start_func (start_arg);
624 g_assert (start_delegate != NULL);
625 args [0] = start_arg;
626 /* we may want to handle the exception here. See comment below on unhandled exceptions */
627 mono_runtime_delegate_invoke (start_delegate, args, NULL);
630 /* If the thread calls ExitThread at all, this remaining code
631 * will not be executed, but the main thread will eventually
632 * call thread_cleanup() on this thread's behalf.
635 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
637 thread_cleanup (thread);
639 /* Do any cleanup needed for apartment state. This
640 * cannot be done in thread_cleanup since thread_cleanup could be
641 * called for a thread other than the current thread.
642 * mono_thread_cleanup_apartment_state cleans up apartment
643 * for the current thead */
644 mono_thread_cleanup_apartment_state ();
646 /* Remove the reference to the thread object in the TLS data,
647 * so the thread object can be finalized. This won't be
648 * reached if the thread threw an uncaught exception, so those
649 * thread handles will stay referenced :-( (This is due to
650 * missing support for scanning thread-specific data in the
651 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
654 SET_CURRENT_OBJECT (NULL);
659 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
661 if (mono_thread_start_cb) {
662 mono_thread_start_cb (tid, stack_start, func);
666 void mono_threads_set_default_stacksize (guint32 stacksize)
668 default_stacksize = stacksize;
671 guint32 mono_threads_get_default_stacksize (void)
673 return default_stacksize;
676 void mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
679 HANDLE thread_handle;
680 struct StartInfo *start_info;
683 thread=(MonoThread *)mono_object_new (domain,
684 mono_defaults.thread_class);
686 start_info=g_new0 (struct StartInfo, 1);
687 start_info->func = func;
688 start_info->obj = thread;
689 start_info->domain = domain;
690 start_info->start_arg = arg;
693 * The argument may be an object reference, and there is no ref to keep it alive
694 * when the new thread is started but not yet registered with the collector.
696 MONO_GC_REGISTER_ROOT (start_info->start_arg);
698 mono_threads_lock ();
700 mono_threads_unlock ();
703 if (threads_starting_up == NULL) {
704 MONO_GC_REGISTER_ROOT (threads_starting_up);
705 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
707 mono_g_hash_table_insert (threads_starting_up, thread, thread);
708 mono_threads_unlock ();
710 /* Create suspended, so we can do some housekeeping before the thread
713 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
714 CREATE_SUSPENDED, &tid);
715 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
716 if (thread_handle == NULL) {
717 /* The thread couldn't be created, so throw an exception */
718 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
719 mono_threads_lock ();
720 mono_g_hash_table_remove (threads_starting_up, thread);
721 mono_threads_unlock ();
723 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
727 thread->handle=thread_handle;
729 thread->apartment_state=ThreadApartmentState_Unknown;
730 small_id_alloc (thread);
732 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
733 InitializeCriticalSection (thread->synch_cs);
735 thread->threadpool_thread = threadpool_thread;
737 if (handle_store (thread))
738 ResumeThread (thread_handle);
742 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
744 mono_thread_create_internal (domain, func, arg, FALSE);
748 * mono_thread_get_stack_bounds:
750 * Return the address and size of the current threads stack. Return NULL as the
751 * stack address if the stack address cannot be determined.
754 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
756 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
757 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
758 *stsize = pthread_get_stacksize_np (pthread_self ());
759 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
761 /* FIXME: simplify the mess below */
762 #elif !defined(PLATFORM_WIN32)
764 guint8 *current = (guint8*)&attr;
766 pthread_attr_init (&attr);
767 #ifdef HAVE_PTHREAD_GETATTR_NP
768 pthread_getattr_np (pthread_self(), &attr);
770 #ifdef HAVE_PTHREAD_ATTR_GET_NP
771 pthread_attr_get_np (pthread_self(), &attr);
774 pthread_attr_getstacksize (&attr, &stsize);
783 pthread_attr_getstack (&attr, (void**)staddr, stsize);
785 g_assert ((current > *staddr) && (current < *staddr + *stsize));
788 pthread_attr_destroy (&attr);
791 /* When running under emacs, sometimes staddr is not aligned to a page size */
792 *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
796 mono_thread_attach (MonoDomain *domain)
799 HANDLE thread_handle;
802 if ((thread = mono_thread_current ())) {
803 if (domain != mono_domain_get ())
804 mono_domain_set (domain, TRUE);
805 /* Already attached */
809 if (!mono_gc_register_thread (&domain)) {
810 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 ());
813 thread = (MonoThread *)mono_object_new (domain,
814 mono_defaults.thread_class);
816 thread_handle = GetCurrentThread ();
817 g_assert (thread_handle);
819 tid=GetCurrentThreadId ();
822 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
823 * refer to the thread from other threads for things like aborting.
825 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
826 THREAD_ALL_ACCESS, TRUE, 0);
828 thread->handle=thread_handle;
830 thread->apartment_state=ThreadApartmentState_Unknown;
831 small_id_alloc (thread);
832 thread->stack_ptr = &tid;
834 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
835 InitializeCriticalSection (thread->synch_cs);
837 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
839 if (!handle_store (thread)) {
840 /* Mono is shutting down, so just wait for the end */
845 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
847 SET_CURRENT_OBJECT (thread);
848 mono_domain_set (domain, TRUE);
850 mono_monitor_init_tls ();
852 thread_adjust_static_data (thread);
854 if (mono_thread_attach_cb) {
858 mono_thread_get_stack_bounds (&staddr, &stsize);
861 mono_thread_attach_cb (tid, &tid);
863 mono_thread_attach_cb (tid, staddr + stsize);
870 mono_thread_detach (MonoThread *thread)
872 g_return_if_fail (thread != NULL);
874 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
876 thread_cleanup (thread);
878 SET_CURRENT_OBJECT (NULL);
880 /* Don't need to CloseHandle this thread, even though we took a
881 * reference in mono_thread_attach (), because the GC will do it
882 * when the Thread object is finalised.
889 MonoThread *thread = mono_thread_current ();
891 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
893 thread_cleanup (thread);
894 SET_CURRENT_OBJECT (NULL);
896 /* we could add a callback here for embedders to use. */
897 if (thread == mono_thread_get_main ())
898 exit (mono_environment_exitcode_get ());
902 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
905 guint32 (*start_func)(void *);
906 struct StartInfo *start_info;
912 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
914 ensure_synch_cs_set (this);
916 EnterCriticalSection (this->synch_cs);
918 if ((this->state & ThreadState_Unstarted) == 0) {
919 LeaveCriticalSection (this->synch_cs);
920 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
926 if ((this->state & ThreadState_Aborted) != 0) {
927 LeaveCriticalSection (this->synch_cs);
932 /* This is freed in start_wrapper */
933 start_info = g_new0 (struct StartInfo, 1);
934 start_info->func = start_func;
935 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
936 start_info->delegate = start;
937 start_info->obj = this;
938 start_info->domain = mono_domain_get ();
940 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
941 if(this->start_notify==NULL) {
942 LeaveCriticalSection (this->synch_cs);
943 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
947 mono_threads_lock ();
948 if (threads_starting_up == NULL) {
949 MONO_GC_REGISTER_ROOT (threads_starting_up);
950 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
952 mono_g_hash_table_insert (threads_starting_up, this, this);
953 mono_threads_unlock ();
955 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
956 CREATE_SUSPENDED, &tid);
958 LeaveCriticalSection (this->synch_cs);
959 mono_threads_lock ();
960 mono_g_hash_table_remove (threads_starting_up, this);
961 mono_threads_unlock ();
962 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
968 small_id_alloc (this);
970 /* Don't call handle_store() here, delay it to Start.
971 * We can't join a thread (trying to will just block
972 * forever) until it actually starts running, so don't
973 * store the handle till then.
976 mono_thread_start (this);
978 this->state &= ~ThreadState_Unstarted;
980 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
982 LeaveCriticalSection (this->synch_cs);
987 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
991 ensure_synch_cs_set (this);
994 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
999 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
1001 CloseHandle (thread);
1003 DeleteCriticalSection (this->synch_cs);
1004 g_free (this->synch_cs);
1005 this->synch_cs = NULL;
1008 static void mono_thread_start (MonoThread *thread)
1010 MONO_ARCH_SAVE_REGS;
1012 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1014 /* Only store the handle when the thread is about to be
1015 * launched, to avoid the main thread deadlocking while trying
1016 * to clean up a thread that will never be signalled.
1018 if (!handle_store (thread))
1021 ResumeThread (thread->handle);
1023 if(thread->start_notify!=NULL) {
1024 /* Wait for the thread to set up its TLS data etc, so
1025 * theres no potential race condition if someone tries
1026 * to look up the data believing the thread has
1030 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1032 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1033 CloseHandle (thread->start_notify);
1034 thread->start_notify = NULL;
1037 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1040 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1042 MonoThread *thread = mono_thread_current ();
1044 MONO_ARCH_SAVE_REGS;
1046 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1048 mono_thread_current_check_pending_interrupt ();
1050 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1054 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1057 void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
1061 for(i = 0; i < iterations; i++) {
1062 /* We're busy waiting, but at least we can tell the
1063 * scheduler to let someone else have a go...
1070 ves_icall_System_Threading_Thread_GetDomainID (void)
1072 MONO_ARCH_SAVE_REGS;
1074 return mono_domain_get()->domain_id;
1078 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1082 ensure_synch_cs_set (this_obj);
1084 EnterCriticalSection (this_obj->synch_cs);
1086 if (!this_obj->name)
1089 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1091 LeaveCriticalSection (this_obj->synch_cs);
1097 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1099 ensure_synch_cs_set (this_obj);
1101 EnterCriticalSection (this_obj->synch_cs);
1103 if (this_obj->name) {
1104 LeaveCriticalSection (this_obj->synch_cs);
1106 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1110 this_obj->name = g_new (gunichar2, mono_string_length (name));
1111 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1112 this_obj->name_len = mono_string_length (name);
1115 this_obj->name = NULL;
1117 LeaveCriticalSection (this_obj->synch_cs);
1121 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1126 if (this->cached_culture_info) {
1127 domain = mono_domain_get ();
1128 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1129 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1130 if (res && res->vtable->domain == domain)
1139 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1141 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1145 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1149 ensure_synch_cs_set (this);
1151 EnterCriticalSection (this->synch_cs);
1153 if (this->serialized_culture_info) {
1154 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1155 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1160 LeaveCriticalSection (this->synch_cs);
1166 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1169 MonoDomain *domain = mono_domain_get ();
1172 int same_domain_slot = -1;
1174 ensure_synch_cs_set (this);
1176 EnterCriticalSection (this->synch_cs);
1178 if (!this->cached_culture_info)
1179 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1181 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1182 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1186 /* we continue, because there may be a slot used with the same domain */
1190 if (obj->vtable->domain == domain) {
1191 same_domain_slot = i;
1195 if (same_domain_slot >= 0)
1196 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1197 else if (free_slot >= 0)
1198 mono_array_setref (this->cached_culture_info, free_slot, culture);
1199 /* we may want to replace an existing entry here, even when no suitable slot is found */
1201 LeaveCriticalSection (this->synch_cs);
1205 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1207 cache_culture (this, culture, CULTURES_START_IDX);
1211 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1213 ensure_synch_cs_set (this);
1215 EnterCriticalSection (this->synch_cs);
1217 if (this->serialized_culture_info)
1218 g_free (this->serialized_culture_info);
1219 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1220 this->serialized_culture_info_len = mono_array_length (arr);
1221 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1223 LeaveCriticalSection (this->synch_cs);
1228 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1230 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1234 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1238 ensure_synch_cs_set (this);
1240 EnterCriticalSection (this->synch_cs);
1242 if (this->serialized_ui_culture_info) {
1243 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1244 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1249 LeaveCriticalSection (this->synch_cs);
1255 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1257 cache_culture (this, culture, UICULTURES_START_IDX);
1261 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1263 ensure_synch_cs_set (this);
1265 EnterCriticalSection (this->synch_cs);
1267 if (this->serialized_ui_culture_info)
1268 g_free (this->serialized_ui_culture_info);
1269 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1270 this->serialized_ui_culture_info_len = mono_array_length (arr);
1271 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1273 LeaveCriticalSection (this->synch_cs);
1276 /* the jit may read the compiled code of this function */
1278 mono_thread_current (void)
1280 THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
1281 return GET_CURRENT_OBJECT ();
1284 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1285 int ms, HANDLE thread)
1287 MonoThread *cur_thread = mono_thread_current ();
1290 MONO_ARCH_SAVE_REGS;
1292 mono_thread_current_check_pending_interrupt ();
1294 ensure_synch_cs_set (this);
1296 EnterCriticalSection (this->synch_cs);
1298 if ((this->state & ThreadState_Unstarted) != 0) {
1299 LeaveCriticalSection (this->synch_cs);
1301 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1305 LeaveCriticalSection (this->synch_cs);
1310 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1312 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1314 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1316 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1318 if(ret==WAIT_OBJECT_0) {
1319 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1324 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1329 /* FIXME: exitContext isnt documented */
1330 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1336 MonoObject *waitHandle;
1337 MonoThread *thread = mono_thread_current ();
1339 MONO_ARCH_SAVE_REGS;
1341 /* Do this WaitSleepJoin check before creating objects */
1342 mono_thread_current_check_pending_interrupt ();
1344 numhandles = mono_array_length(mono_handles);
1345 handles = g_new0(HANDLE, numhandles);
1347 for(i = 0; i < numhandles; i++) {
1348 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1349 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1356 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1358 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1360 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1364 if(ret==WAIT_FAILED) {
1365 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1367 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1368 /* Do we want to try again if we get
1369 * WAIT_IO_COMPLETION? The documentation for
1370 * WaitHandle doesn't give any clues. (We'd have to
1371 * fiddle with the timeout if we retry.)
1373 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1380 /* FIXME: exitContext isnt documented */
1381 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1387 MonoObject *waitHandle;
1388 MonoThread *thread = mono_thread_current ();
1390 MONO_ARCH_SAVE_REGS;
1392 /* Do this WaitSleepJoin check before creating objects */
1393 mono_thread_current_check_pending_interrupt ();
1395 numhandles = mono_array_length(mono_handles);
1396 handles = g_new0(HANDLE, numhandles);
1398 for(i = 0; i < numhandles; i++) {
1399 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1400 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1407 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1409 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1411 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1415 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1418 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1420 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1421 return ret - WAIT_OBJECT_0;
1423 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1424 return ret - WAIT_ABANDONED_0;
1431 /* FIXME: exitContext isnt documented */
1432 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1435 MonoThread *thread = mono_thread_current ();
1437 MONO_ARCH_SAVE_REGS;
1439 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1445 mono_thread_current_check_pending_interrupt ();
1447 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1449 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1451 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1453 if(ret==WAIT_FAILED) {
1454 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1456 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1457 /* Do we want to try again if we get
1458 * WAIT_IO_COMPLETION? The documentation for
1459 * WaitHandle doesn't give any clues. (We'd have to
1460 * fiddle with the timeout if we retry.)
1462 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1469 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1473 MONO_ARCH_SAVE_REGS;
1478 mutex = CreateMutex (NULL, owned, NULL);
1480 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1482 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1490 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1491 MONO_ARCH_SAVE_REGS;
1493 return(ReleaseMutex (handle));
1496 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1502 MONO_ARCH_SAVE_REGS;
1504 *error = ERROR_SUCCESS;
1506 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1508 *error = GetLastError ();
1515 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1519 MONO_ARCH_SAVE_REGS;
1524 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1526 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1527 mono_string_chars (name));
1529 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1537 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1541 MONO_ARCH_SAVE_REGS;
1543 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1548 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1552 MONO_ARCH_SAVE_REGS;
1554 *error = ERROR_SUCCESS;
1556 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1558 *error = GetLastError ();
1564 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1568 MONO_ARCH_SAVE_REGS;
1573 event = CreateEvent (NULL, manual, initial, NULL);
1575 event = CreateEvent (NULL, manual, initial,
1576 mono_string_chars (name));
1578 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1586 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1587 MONO_ARCH_SAVE_REGS;
1589 return (SetEvent(handle));
1592 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1593 MONO_ARCH_SAVE_REGS;
1595 return (ResetEvent(handle));
1599 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1600 MONO_ARCH_SAVE_REGS;
1602 CloseHandle (handle);
1605 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1611 MONO_ARCH_SAVE_REGS;
1613 *error = ERROR_SUCCESS;
1615 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1617 *error = GetLastError ();
1623 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1625 MONO_ARCH_SAVE_REGS;
1627 return InterlockedIncrement (location);
1630 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1634 MONO_ARCH_SAVE_REGS;
1636 mono_interlocked_lock ();
1640 mono_interlocked_unlock ();
1646 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1648 MONO_ARCH_SAVE_REGS;
1650 return InterlockedDecrement(location);
1653 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1657 MONO_ARCH_SAVE_REGS;
1659 mono_interlocked_lock ();
1663 mono_interlocked_unlock ();
1668 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1670 MONO_ARCH_SAVE_REGS;
1672 return InterlockedExchange(location, value);
1675 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1677 MONO_ARCH_SAVE_REGS;
1679 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1682 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1684 IntFloatUnion val, ret;
1686 MONO_ARCH_SAVE_REGS;
1689 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1695 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1697 #if SIZEOF_VOID_P == 8
1698 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1703 * According to MSDN, this function is only atomic with regards to the
1704 * other Interlocked functions on 32 bit platforms.
1706 mono_interlocked_lock ();
1709 mono_interlocked_unlock ();
1716 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1718 #if SIZEOF_VOID_P == 8
1719 LongDoubleUnion val, ret;
1722 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1729 * According to MSDN, this function is only atomic with regards to the
1730 * other Interlocked functions on 32 bit platforms.
1732 mono_interlocked_lock ();
1735 mono_interlocked_unlock ();
1741 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1743 MONO_ARCH_SAVE_REGS;
1745 return InterlockedCompareExchange(location, value, comparand);
1748 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1750 MONO_ARCH_SAVE_REGS;
1752 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1755 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1757 IntFloatUnion val, ret, cmp;
1759 MONO_ARCH_SAVE_REGS;
1762 cmp.fval = comparand;
1763 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1769 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1771 #if SIZEOF_VOID_P == 8
1772 LongDoubleUnion val, comp, ret;
1775 comp.fval = comparand;
1776 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1782 mono_interlocked_lock ();
1784 if (old == comparand)
1786 mono_interlocked_unlock ();
1793 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1795 #if SIZEOF_VOID_P == 8
1796 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1800 mono_interlocked_lock ();
1802 if (old == comparand)
1804 mono_interlocked_unlock ();
1811 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1813 MONO_ARCH_SAVE_REGS;
1815 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1819 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1821 MONO_ARCH_SAVE_REGS;
1823 return InterlockedExchangePointer ((gpointer *)location, value);
1827 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1829 #if SIZEOF_VOID_P == 8
1830 /* Should be implemented as a JIT intrinsic */
1831 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1836 mono_interlocked_lock ();
1838 *location = orig + value;
1839 mono_interlocked_unlock ();
1841 return orig + value;
1846 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1848 #if SIZEOF_VOID_P == 8
1849 /* Should be implemented as a JIT intrinsic */
1850 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1855 mono_interlocked_lock ();
1857 *location = orig + value;
1858 mono_interlocked_unlock ();
1860 return orig + value;
1865 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1867 #if SIZEOF_VOID_P == 8
1868 /* 64 bit reads are already atomic */
1873 mono_interlocked_lock ();
1875 mono_interlocked_unlock ();
1882 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1884 mono_threads_lock ();
1885 mono_threads_unlock ();
1889 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1891 mono_thread_clr_state (this, state);
1893 if (state & ThreadState_Background) {
1894 /* If the thread changes the background mode, the main thread has to
1895 * be notified, since it has to rebuild the list of threads to
1898 SetEvent (background_change_event);
1903 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1905 mono_thread_set_state (this, state);
1907 if (state & ThreadState_Background) {
1908 /* If the thread changes the background mode, the main thread has to
1909 * be notified, since it has to rebuild the list of threads to
1912 SetEvent (background_change_event);
1917 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1921 ensure_synch_cs_set (this);
1923 EnterCriticalSection (this->synch_cs);
1925 state = this->state;
1927 LeaveCriticalSection (this->synch_cs);
1932 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1934 gboolean throw = FALSE;
1936 ensure_synch_cs_set (this);
1938 if (this == mono_thread_current ())
1941 EnterCriticalSection (this->synch_cs);
1943 this->thread_interrupt_requested = TRUE;
1945 if (this->state & ThreadState_WaitSleepJoin) {
1949 LeaveCriticalSection (this->synch_cs);
1952 signal_thread_state_change (this);
1956 void mono_thread_current_check_pending_interrupt ()
1958 MonoThread *thread = mono_thread_current ();
1959 gboolean throw = FALSE;
1961 mono_debugger_check_interruption ();
1963 ensure_synch_cs_set (thread);
1965 EnterCriticalSection (thread->synch_cs);
1967 if (thread->thread_interrupt_requested) {
1969 thread->thread_interrupt_requested = FALSE;
1972 LeaveCriticalSection (thread->synch_cs);
1975 mono_raise_exception (mono_get_exception_thread_interrupted ());
1980 mono_thread_get_abort_signal (void)
1982 #ifdef PLATFORM_WIN32
1988 static int abort_signum = -1;
1990 if (abort_signum != -1)
1991 return abort_signum;
1992 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1993 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1994 struct sigaction sinfo;
1995 sigaction (i, NULL, &sinfo);
1996 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
2001 /* fallback to the old way */
2004 #endif /* PLATFORM_WIN32 */
2007 #ifdef PLATFORM_WIN32
2008 static void CALLBACK interruption_request_apc (ULONG_PTR param)
2010 MonoException* exc = mono_thread_request_interruption (FALSE);
2011 if (exc) mono_raise_exception (exc);
2013 #endif /* PLATFORM_WIN32 */
2016 * signal_thread_state_change
2018 * Tells the thread that his state has changed and it has to enter the new
2019 * state as soon as possible.
2021 static void signal_thread_state_change (MonoThread *thread)
2023 if (thread == mono_thread_current ()) {
2024 /* Do it synchronously */
2025 MonoException *exc = mono_thread_request_interruption (FALSE);
2027 mono_raise_exception (exc);
2030 #ifdef PLATFORM_WIN32
2031 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
2033 /* fixme: store the state somewhere */
2034 #ifdef PTHREAD_POINTER_ID
2035 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2037 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2039 #endif /* PLATFORM_WIN32 */
2043 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2045 MONO_ARCH_SAVE_REGS;
2047 ensure_synch_cs_set (thread);
2049 EnterCriticalSection (thread->synch_cs);
2051 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2052 (thread->state & ThreadState_StopRequested) != 0 ||
2053 (thread->state & ThreadState_Stopped) != 0)
2055 LeaveCriticalSection (thread->synch_cs);
2059 if ((thread->state & ThreadState_Unstarted) != 0) {
2060 thread->state |= ThreadState_Aborted;
2061 LeaveCriticalSection (thread->synch_cs);
2065 thread->state |= ThreadState_AbortRequested;
2066 MONO_OBJECT_SETREF (thread, abort_state, state);
2067 thread->abort_exc = NULL;
2069 LeaveCriticalSection (thread->synch_cs);
2071 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2073 /* During shutdown, we can't wait for other threads */
2075 /* Make sure the thread is awake */
2076 mono_thread_resume (thread);
2078 signal_thread_state_change (thread);
2082 ves_icall_System_Threading_Thread_ResetAbort (void)
2084 MonoThread *thread = mono_thread_current ();
2086 MONO_ARCH_SAVE_REGS;
2088 ensure_synch_cs_set (thread);
2090 EnterCriticalSection (thread->synch_cs);
2092 thread->state &= ~ThreadState_AbortRequested;
2094 if (!thread->abort_exc) {
2095 const char *msg = "Unable to reset abort because no abort was requested";
2096 LeaveCriticalSection (thread->synch_cs);
2097 mono_raise_exception (mono_get_exception_thread_state (msg));
2099 thread->abort_exc = NULL;
2100 thread->abort_state = NULL;
2103 LeaveCriticalSection (thread->synch_cs);
2107 mono_thread_suspend (MonoThread *thread)
2109 MONO_ARCH_SAVE_REGS;
2111 ensure_synch_cs_set (thread);
2113 EnterCriticalSection (thread->synch_cs);
2115 if ((thread->state & ThreadState_Unstarted) != 0 ||
2116 (thread->state & ThreadState_Aborted) != 0 ||
2117 (thread->state & ThreadState_Stopped) != 0)
2119 LeaveCriticalSection (thread->synch_cs);
2123 if ((thread->state & ThreadState_Suspended) != 0 ||
2124 (thread->state & ThreadState_SuspendRequested) != 0 ||
2125 (thread->state & ThreadState_StopRequested) != 0)
2127 LeaveCriticalSection (thread->synch_cs);
2131 thread->state |= ThreadState_SuspendRequested;
2133 LeaveCriticalSection (thread->synch_cs);
2135 signal_thread_state_change (thread);
2140 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2142 if (!mono_thread_suspend (thread))
2143 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2147 mono_thread_resume (MonoThread *thread)
2149 MONO_ARCH_SAVE_REGS;
2151 ensure_synch_cs_set (thread);
2153 EnterCriticalSection (thread->synch_cs);
2155 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2156 thread->state &= ~ThreadState_SuspendRequested;
2157 LeaveCriticalSection (thread->synch_cs);
2161 if ((thread->state & ThreadState_Suspended) == 0 ||
2162 (thread->state & ThreadState_Unstarted) != 0 ||
2163 (thread->state & ThreadState_Aborted) != 0 ||
2164 (thread->state & ThreadState_Stopped) != 0)
2166 LeaveCriticalSection (thread->synch_cs);
2170 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2171 if (thread->resume_event == NULL) {
2172 LeaveCriticalSection (thread->synch_cs);
2176 /* Awake the thread */
2177 SetEvent (thread->suspend_event);
2179 LeaveCriticalSection (thread->synch_cs);
2181 /* Wait for the thread to awake */
2182 WaitForSingleObject (thread->resume_event, INFINITE);
2183 CloseHandle (thread->resume_event);
2184 thread->resume_event = NULL;
2190 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2192 if (!mono_thread_resume (thread))
2193 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2197 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2202 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2203 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2204 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2206 *((gboolean*)data) = TRUE;
2213 is_running_protected_wrapper (void)
2215 gboolean found = FALSE;
2216 mono_stack_walk (find_wrapper, &found);
2220 void mono_thread_stop (MonoThread *thread)
2222 ensure_synch_cs_set (thread);
2224 EnterCriticalSection (thread->synch_cs);
2226 if ((thread->state & ThreadState_StopRequested) != 0 ||
2227 (thread->state & ThreadState_Stopped) != 0)
2229 LeaveCriticalSection (thread->synch_cs);
2233 /* Make sure the thread is awake */
2234 mono_thread_resume (thread);
2236 thread->state |= ThreadState_StopRequested;
2237 thread->state &= ~ThreadState_AbortRequested;
2239 LeaveCriticalSection (thread->synch_cs);
2241 signal_thread_state_change (thread);
2245 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2247 return *((volatile gint8 *) (ptr));
2251 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2253 return *((volatile gint16 *) (ptr));
2257 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2259 return *((volatile gint32 *) (ptr));
2263 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2265 return *((volatile gint64 *) (ptr));
2269 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2271 return (void *) *((volatile void **) ptr);
2275 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2277 *((volatile gint8 *) ptr) = value;
2281 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2283 *((volatile gint16 *) ptr) = value;
2287 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2289 *((volatile gint32 *) ptr) = value;
2293 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2295 *((volatile gint64 *) ptr) = value;
2299 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2301 *((volatile void **) ptr) = value;
2304 void mono_thread_init (MonoThreadStartCB start_cb,
2305 MonoThreadAttachCB attach_cb)
2307 MONO_GC_REGISTER_ROOT (small_id_table);
2308 InitializeCriticalSection(&threads_mutex);
2309 InitializeCriticalSection(&interlocked_mutex);
2310 InitializeCriticalSection(&contexts_mutex);
2311 InitializeCriticalSection(&delayed_free_table_mutex);
2312 InitializeCriticalSection(&small_id_mutex);
2314 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2315 g_assert(background_change_event != NULL);
2317 mono_init_static_data_info (&thread_static_info);
2318 mono_init_static_data_info (&context_static_info);
2320 current_object_key=TlsAlloc();
2321 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2323 mono_thread_start_cb = start_cb;
2324 mono_thread_attach_cb = attach_cb;
2326 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2328 /* Get a pseudo handle to the current process. This is just a
2329 * kludge so that wapi can build a process handle if needed.
2330 * As a pseudo handle is returned, we don't need to clean
2333 GetCurrentProcess ();
2336 void mono_thread_cleanup (void)
2338 mono_thread_hazardous_try_free_all ();
2340 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2341 /* The main thread must abandon any held mutexes (particularly
2342 * important for named mutexes as they are shared across
2343 * processes, see bug 74680.) This will happen when the
2344 * thread exits, but if it's not running in a subthread it
2345 * won't exit in time.
2347 /* Using non-w32 API is a nasty kludge, but I couldn't find
2348 * anything in the documentation that would let me do this
2349 * here yet still be safe to call on windows.
2351 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2355 /* This stuff needs more testing, it seems one of these
2356 * critical sections can be locked when mono_thread_cleanup is
2359 DeleteCriticalSection (&threads_mutex);
2360 DeleteCriticalSection (&interlocked_mutex);
2361 DeleteCriticalSection (&contexts_mutex);
2362 DeleteCriticalSection (&delayed_free_table_mutex);
2363 DeleteCriticalSection (&small_id_mutex);
2364 CloseHandle (background_change_event);
2367 g_array_free (delayed_free_table, TRUE);
2368 delayed_free_table = NULL;
2370 TlsFree (current_object_key);
2374 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2376 mono_thread_cleanup_fn = func;
2380 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2382 thread->manage_callback = func;
2385 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2387 mono_thread_notify_pending_exc_fn = func;
2391 static void print_tids (gpointer key, gpointer value, gpointer user)
2393 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2394 * sizeof(uint) and a cast to uint would overflow
2396 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2397 * print this as a pointer.
2399 g_message ("Waiting for: %p", key);
2404 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2405 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2409 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2413 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2415 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2417 if(ret==WAIT_FAILED) {
2418 /* See the comment in build_wait_tids() */
2419 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2423 for(i=0; i<wait->num; i++)
2424 CloseHandle (wait->handles[i]);
2426 if (ret == WAIT_TIMEOUT)
2429 for(i=0; i<wait->num; i++) {
2430 gsize tid = wait->threads[i]->tid;
2432 mono_threads_lock ();
2433 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2434 /* This thread must have been killed, because
2435 * it hasn't cleaned itself up. (It's just
2436 * possible that the thread exited before the
2437 * parent thread had a chance to store the
2438 * handle, and now there is another pointer to
2439 * the already-exited thread stored. In this
2440 * case, we'll just get two
2441 * mono_profiler_thread_end() calls for the
2445 mono_threads_unlock ();
2446 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2447 thread_cleanup (wait->threads[i]);
2449 mono_threads_unlock ();
2454 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2456 guint32 i, ret, count;
2458 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2460 /* Add the thread state change event, so it wakes up if a thread changes
2461 * to background mode.
2464 if (count < MAXIMUM_WAIT_OBJECTS) {
2465 wait->handles [count] = background_change_event;
2469 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2471 if(ret==WAIT_FAILED) {
2472 /* See the comment in build_wait_tids() */
2473 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2477 for(i=0; i<wait->num; i++)
2478 CloseHandle (wait->handles[i]);
2480 if (ret == WAIT_TIMEOUT)
2483 if (ret < wait->num) {
2484 gsize tid = wait->threads[ret]->tid;
2485 mono_threads_lock ();
2486 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2487 /* See comment in wait_for_tids about thread cleanup */
2488 mono_threads_unlock ();
2489 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2490 thread_cleanup (wait->threads [ret]);
2492 mono_threads_unlock ();
2496 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2498 struct wait_data *wait=(struct wait_data *)user;
2500 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2502 MonoThread *thread=(MonoThread *)value;
2504 /* Ignore background threads, we abort them later */
2505 /* Do not lock here since it is not needed and the caller holds threads_lock */
2506 if (thread->state & ThreadState_Background) {
2507 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2508 return; /* just leave, ignore */
2511 if (mono_gc_is_finalizer_thread (thread)) {
2512 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2516 if (thread == mono_thread_current ()) {
2517 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2521 if (thread == mono_thread_get_main ()) {
2522 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2526 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2527 if (handle == NULL) {
2528 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2532 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2533 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2534 wait->handles[wait->num]=handle;
2535 wait->threads[wait->num]=thread;
2538 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2540 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2545 /* Just ignore the rest, we can't do anything with
2552 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2554 struct wait_data *wait=(struct wait_data *)user;
2555 gsize self = GetCurrentThreadId ();
2556 MonoThread *thread = (MonoThread *) value;
2559 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2562 /* The finalizer thread is not a background thread */
2563 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2565 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2569 /* printf ("A: %d\n", wait->num); */
2570 wait->handles[wait->num]=thread->handle;
2571 wait->threads[wait->num]=thread;
2574 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2575 mono_thread_stop (thread);
2579 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2582 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
2585 * mono_threads_set_shutting_down:
2587 * Is called by a thread that wants to shut down Mono. If the runtime is already
2588 * shutting down, the calling thread is suspended/stopped, and this function never
2592 mono_threads_set_shutting_down (void)
2594 MonoThread *current_thread = mono_thread_current ();
2596 mono_threads_lock ();
2598 if (shutting_down) {
2599 mono_threads_unlock ();
2601 /* Make sure we're properly suspended/stopped */
2603 EnterCriticalSection (current_thread->synch_cs);
2605 if ((current_thread->state & ThreadState_SuspendRequested) ||
2606 (current_thread->state & ThreadState_AbortRequested) ||
2607 (current_thread->state & ThreadState_StopRequested)) {
2608 LeaveCriticalSection (current_thread->synch_cs);
2609 mono_thread_execute_interruption (current_thread);
2611 current_thread->state |= ThreadState_Stopped;
2612 LeaveCriticalSection (current_thread->synch_cs);
2615 /* Wake up other threads potentially waiting for us */
2618 shutting_down = TRUE;
2620 /* Not really a background state change, but this will
2621 * interrupt the main thread if it is waiting for all
2622 * the other threads.
2624 SetEvent (background_change_event);
2626 mono_threads_unlock ();
2631 * mono_threads_is_shutting_down:
2633 * Returns whether a thread has commenced shutdown of Mono. Note that
2634 * if the function returns FALSE the caller must not assume that
2635 * shutdown is not in progress, because the situation might have
2636 * changed since the function returned. For that reason this function
2637 * is of very limited utility.
2640 mono_threads_is_shutting_down (void)
2642 return shutting_down;
2645 void mono_thread_manage (void)
2647 struct wait_data *wait=g_new0 (struct wait_data, 1);
2649 /* join each thread that's still running */
2650 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2652 mono_threads_lock ();
2654 THREAD_DEBUG (g_message("%s: No threads", __func__));
2655 mono_threads_unlock ();
2658 mono_threads_unlock ();
2661 mono_threads_lock ();
2662 if (shutting_down) {
2663 /* somebody else is shutting down */
2664 mono_threads_unlock ();
2667 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2668 mono_g_hash_table_foreach (threads, print_tids, NULL));
2670 ResetEvent (background_change_event);
2672 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2673 mono_threads_unlock ();
2675 /* Something to wait for */
2676 wait_for_tids_or_state_change (wait, INFINITE);
2678 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2679 } while(wait->num>0);
2681 mono_threads_set_shutting_down ();
2683 /* No new threads will be created after this point */
2685 mono_runtime_set_shutting_down ();
2687 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2688 mono_thread_pool_cleanup ();
2691 * Remove everything but the finalizer thread and self.
2692 * Also abort all the background threads
2695 mono_threads_lock ();
2698 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2700 mono_threads_unlock ();
2702 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2704 /* Something to wait for */
2705 wait_for_tids (wait, INFINITE);
2707 } while (wait->num > 0);
2710 * give the subthreads a chance to really quit (this is mainly needed
2711 * to get correct user and system times from getrusage/wait/time(1)).
2712 * This could be removed if we avoid pthread_detach() and use pthread_join().
2714 #ifndef PLATFORM_WIN32
2721 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2723 MonoThread *thread=(MonoThread *)value;
2725 if(thread->tid != (gsize)user) {
2726 /*TerminateThread (thread->handle, -1);*/
2730 void mono_thread_abort_all_other_threads (void)
2732 gsize self = GetCurrentThreadId ();
2734 mono_threads_lock ();
2735 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2736 mono_g_hash_table_size (threads));
2737 mono_g_hash_table_foreach (threads, print_tids, NULL));
2739 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2741 mono_threads_unlock ();
2745 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2747 MonoThread *thread = (MonoThread*)value;
2748 struct wait_data *wait = (struct wait_data*)user_data;
2752 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2754 * This needs no locking.
2756 if ((thread->state & ThreadState_Suspended) != 0 ||
2757 (thread->state & ThreadState_Stopped) != 0)
2760 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2761 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2765 wait->handles [wait->num] = handle;
2766 wait->threads [wait->num] = thread;
2772 * mono_thread_suspend_all_other_threads:
2774 * Suspend all managed threads except the finalizer thread and this thread. It is
2775 * not possible to resume them later.
2777 void mono_thread_suspend_all_other_threads (void)
2779 struct wait_data *wait = g_new0 (struct wait_data, 1);
2781 gsize self = GetCurrentThreadId ();
2783 guint32 eventidx = 0;
2784 gboolean starting, finished;
2787 * The other threads could be in an arbitrary state at this point, i.e.
2788 * they could be starting up, shutting down etc. This means that there could be
2789 * threads which are not even in the threads hash table yet.
2793 * First we set a barrier which will be checked by all threads before they
2794 * are added to the threads hash table, and they will exit if the flag is set.
2795 * This ensures that no threads could be added to the hash later.
2796 * We will use shutting_down as the barrier for now.
2798 g_assert (shutting_down);
2801 * We make multiple calls to WaitForMultipleObjects since:
2802 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2803 * - some threads could exit without becoming suspended
2808 * Make a copy of the hashtable since we can't do anything with
2809 * threads while threads_mutex is held.
2812 mono_threads_lock ();
2813 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2814 mono_threads_unlock ();
2816 events = g_new0 (gpointer, wait->num);
2818 /* Get the suspended events that we'll be waiting for */
2819 for (i = 0; i < wait->num; ++i) {
2820 MonoThread *thread = wait->threads [i];
2822 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2823 //CloseHandle (wait->handles [i]);
2824 wait->threads [i] = NULL; /* ignore this thread in next loop */
2828 ensure_synch_cs_set (thread);
2830 EnterCriticalSection (thread->synch_cs);
2832 if ((thread->state & ThreadState_Suspended) != 0 ||
2833 (thread->state & ThreadState_SuspendRequested) != 0 ||
2834 (thread->state & ThreadState_StopRequested) != 0 ||
2835 (thread->state & ThreadState_Stopped) != 0) {
2836 LeaveCriticalSection (thread->synch_cs);
2837 CloseHandle (wait->handles [i]);
2838 wait->threads [i] = NULL; /* ignore this thread in next loop */
2842 /* Convert abort requests into suspend requests */
2843 if ((thread->state & ThreadState_AbortRequested) != 0)
2844 thread->state &= ~ThreadState_AbortRequested;
2846 thread->state |= ThreadState_SuspendRequested;
2848 if (thread->suspended_event == NULL) {
2849 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2850 if (thread->suspended_event == NULL) {
2851 /* Forget this one and go on to the next */
2852 LeaveCriticalSection (thread->synch_cs);
2857 events [eventidx++] = thread->suspended_event;
2858 LeaveCriticalSection (thread->synch_cs);
2860 /* Signal the thread to suspend */
2861 signal_thread_state_change (thread);
2865 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2866 for (i = 0; i < wait->num; ++i) {
2867 MonoThread *thread = wait->threads [i];
2872 EnterCriticalSection (thread->synch_cs);
2873 if ((thread->state & ThreadState_Suspended) != 0) {
2874 CloseHandle (thread->suspended_event);
2875 thread->suspended_event = NULL;
2877 LeaveCriticalSection (thread->synch_cs);
2881 * If there are threads which are starting up, we wait until they
2882 * are suspended when they try to register in the threads hash.
2883 * This is guaranteed to finish, since the threads which can create new
2884 * threads get suspended after a while.
2885 * FIXME: The finalizer thread can still create new threads.
2887 mono_threads_lock ();
2888 starting = mono_g_hash_table_size (threads_starting_up) > 0;
2889 mono_threads_unlock ();
2903 collect_threads (gpointer key, gpointer value, gpointer user_data)
2905 MonoThread *thread = (MonoThread*)value;
2906 struct wait_data *wait = (struct wait_data*)user_data;
2909 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2910 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2914 wait->handles [wait->num] = handle;
2915 wait->threads [wait->num] = thread;
2921 * mono_threads_request_thread_dump:
2923 * Ask all threads except the current to print their stacktrace to stdout.
2926 mono_threads_request_thread_dump (void)
2928 struct wait_data *wait = g_new0 (struct wait_data, 1);
2932 * Make a copy of the hashtable since we can't do anything with
2933 * threads while threads_mutex is held.
2935 mono_threads_lock ();
2936 mono_g_hash_table_foreach (threads, collect_threads, wait);
2937 mono_threads_unlock ();
2939 for (i = 0; i < wait->num; ++i) {
2940 MonoThread *thread = wait->threads [i];
2942 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2943 thread->thread_dump_requested = TRUE;
2945 signal_thread_state_change (thread);
2948 CloseHandle (wait->handles [i]);
2953 * mono_thread_push_appdomain_ref:
2955 * Register that the current thread may have references to objects in domain
2956 * @domain on its stack. Each call to this function should be paired with a
2957 * call to pop_appdomain_ref.
2960 mono_thread_push_appdomain_ref (MonoDomain *domain)
2962 MonoThread *thread = mono_thread_current ();
2965 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2966 mono_threads_lock ();
2967 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2968 mono_threads_unlock ();
2973 mono_thread_pop_appdomain_ref (void)
2975 MonoThread *thread = mono_thread_current ();
2978 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2979 mono_threads_lock ();
2980 /* FIXME: How can the list be empty ? */
2981 if (thread->appdomain_refs)
2982 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2983 mono_threads_unlock ();
2988 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2991 mono_threads_lock ();
2992 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2993 mono_threads_unlock ();
2997 typedef struct abort_appdomain_data {
2998 struct wait_data wait;
3000 } abort_appdomain_data;
3003 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
3005 MonoThread *thread = (MonoThread*)value;
3006 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
3007 MonoDomain *domain = data->domain;
3009 if (mono_thread_has_appdomain_ref (thread, domain)) {
3010 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
3012 ves_icall_System_Threading_Thread_Abort (thread, NULL);
3014 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
3015 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
3018 data->wait.handles [data->wait.num] = handle;
3019 data->wait.threads [data->wait.num] = thread;
3022 /* Just ignore the rest, we can't do anything with
3030 * mono_threads_abort_appdomain_threads:
3032 * Abort threads which has references to the given appdomain.
3035 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
3037 abort_appdomain_data user_data;
3039 int orig_timeout = timeout;
3041 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3043 start_time = mono_msec_ticks ();
3045 mono_threads_lock ();
3047 user_data.domain = domain;
3048 user_data.wait.num = 0;
3049 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
3050 mono_threads_unlock ();
3052 if (user_data.wait.num > 0)
3054 * We should wait for the threads either to abort, or to leave the
3055 * domain. We can't do the latter, so we wait with a timeout.
3057 wait_for_tids (&user_data.wait, 100);
3059 /* Update remaining time */
3060 timeout -= mono_msec_ticks () - start_time;
3061 start_time = mono_msec_ticks ();
3063 if (orig_timeout != -1 && timeout < 0)
3066 while (user_data.wait.num > 0);
3068 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3074 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3076 MonoThread *thread = (MonoThread*)value;
3077 MonoDomain *domain = (MonoDomain*)user_data;
3080 /* No locking needed here */
3081 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3083 if (thread->cached_culture_info) {
3084 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3085 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3086 if (obj && obj->vtable->domain == domain)
3087 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3093 * mono_threads_clear_cached_culture:
3095 * Clear the cached_current_culture from all threads if it is in the
3099 mono_threads_clear_cached_culture (MonoDomain *domain)
3101 mono_threads_lock ();
3102 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3103 mono_threads_unlock ();
3107 * mono_thread_get_undeniable_exception:
3109 * Return an exception which needs to be raised when leaving a catch clause.
3110 * This is used for undeniable exception propagation.
3113 mono_thread_get_undeniable_exception (void)
3115 MonoThread *thread = mono_thread_current ();
3117 MONO_ARCH_SAVE_REGS;
3119 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3121 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3122 * exception if the thread no longer references a dying appdomain.
3124 thread->abort_exc->trace_ips = NULL;
3125 thread->abort_exc->stack_trace = NULL;
3126 return thread->abort_exc;
3132 #define NUM_STATIC_DATA_IDX 8
3133 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3134 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3139 * mono_alloc_static_data
3141 * Allocate memory blocks for storing threads or context static data
3144 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3146 guint idx = (offset >> 24) - 1;
3149 gpointer* static_data = *static_data_ptr;
3151 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3152 *static_data_ptr = static_data;
3153 static_data [0] = static_data;
3156 for (i = 1; i <= idx; ++i) {
3157 if (static_data [i])
3159 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3164 * mono_init_static_data_info
3166 * Initializes static data counters
3168 static void mono_init_static_data_info (StaticDataInfo *static_data)
3170 static_data->idx = 0;
3171 static_data->offset = 0;
3172 static_data->freelist = NULL;
3176 * mono_alloc_static_data_slot
3178 * Generates an offset for static data. static_data contains the counters
3179 * used to generate it.
3182 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3186 if (!static_data->idx && !static_data->offset) {
3188 * we use the first chunk of the first allocation also as
3189 * an array for the rest of the data
3191 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3193 static_data->offset += align - 1;
3194 static_data->offset &= ~(align - 1);
3195 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3196 static_data->idx ++;
3197 g_assert (size <= static_data_size [static_data->idx]);
3198 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3199 static_data->offset = 0;
3201 offset = static_data->offset | ((static_data->idx + 1) << 24);
3202 static_data->offset += size;
3207 * ensure thread static fields already allocated are valid for thread
3208 * This function is called when a thread is created or on thread attach.
3211 thread_adjust_static_data (MonoThread *thread)
3215 mono_threads_lock ();
3216 if (thread_static_info.offset || thread_static_info.idx > 0) {
3217 /* get the current allocated size */
3218 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3219 mono_alloc_static_data (&(thread->static_data), offset);
3221 mono_threads_unlock ();
3225 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3227 MonoThread *thread = value;
3228 guint32 offset = GPOINTER_TO_UINT (user);
3230 mono_alloc_static_data (&(thread->static_data), offset);
3233 static MonoThreadDomainTls*
3234 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3236 MonoThreadDomainTls* prev = NULL;
3237 MonoThreadDomainTls* tmp = static_data->freelist;
3239 if (tmp->size == size) {
3241 prev->next = tmp->next;
3243 static_data->freelist = tmp->next;
3252 * The offset for a special static variable is composed of three parts:
3253 * a bit that indicates the type of static data (0:thread, 1:context),
3254 * an index in the array of chunks of memory for the thread (thread->static_data)
3255 * and an offset in that chunk of mem. This allows allocating less memory in the
3260 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3263 if (static_type == SPECIAL_STATIC_THREAD)
3265 MonoThreadDomainTls *item;
3266 mono_threads_lock ();
3267 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3268 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3270 offset = item->offset;
3273 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3275 /* This can be called during startup */
3276 if (threads != NULL)
3277 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3278 mono_threads_unlock ();
3282 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3283 mono_contexts_lock ();
3284 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3285 mono_contexts_unlock ();
3286 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3292 mono_get_special_static_data (guint32 offset)
3294 /* The high bit means either thread (0) or static (1) data. */
3296 guint32 static_type = (offset & 0x80000000);
3299 offset &= 0x7fffffff;
3300 idx = (offset >> 24) - 1;
3302 if (static_type == 0)
3304 MonoThread *thread = mono_thread_current ();
3305 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3309 /* Allocate static data block under demand, since we don't have a list
3312 MonoAppContext *context = mono_context_get ();
3313 if (!context->static_data || !context->static_data [idx]) {
3314 mono_contexts_lock ();
3315 mono_alloc_static_data (&(context->static_data), offset);
3316 mono_contexts_unlock ();
3318 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3328 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3330 MonoThread *thread = value;
3331 TlsOffsetSize *data = user;
3332 int idx = (data->offset >> 24) - 1;
3335 if (!thread->static_data || !thread->static_data [idx])
3337 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3338 memset (ptr, 0, data->size);
3342 do_free_special (gpointer key, gpointer value, gpointer data)
3344 MonoClassField *field = key;
3345 guint32 offset = GPOINTER_TO_UINT (value);
3346 guint32 static_type = (offset & 0x80000000);
3349 size = mono_type_size (field->type, &align);
3350 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3351 if (static_type == 0) {
3353 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3354 data.offset = offset & 0x7fffffff;
3356 if (threads != NULL)
3357 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3358 item->offset = offset;
3360 item->next = thread_static_info.freelist;
3361 thread_static_info.freelist = item;
3363 /* FIXME: free context static data as well */
3368 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3370 mono_threads_lock ();
3371 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3372 mono_threads_unlock ();
3375 static MonoClassField *local_slots = NULL;
3378 /* local tls data to get locals_slot from a thread */
3381 /* index in the locals_slot array */
3386 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3388 LocalSlotID *sid = user_data;
3389 MonoThread *thread = (MonoThread*)value;
3390 MonoArray *slots_array;
3392 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3393 * it is for the right domain, so we need to check if it is allocated an initialized
3394 * for the current thread.
3396 /*g_print ("handling thread %p\n", thread);*/
3397 if (!thread->static_data || !thread->static_data [sid->idx])
3399 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3400 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3402 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3406 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3414 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3416 g_warning ("local_slots field not found in Thread class");
3420 domain = mono_domain_get ();
3421 mono_domain_lock (domain);
3422 if (domain->special_static_fields)
3423 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3424 mono_domain_unlock (domain);
3427 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3428 sid.offset = GPOINTER_TO_UINT (addr);
3429 sid.offset &= 0x7fffffff;
3430 sid.idx = (sid.offset >> 24) - 1;
3431 mono_threads_lock ();
3432 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3433 mono_threads_unlock ();
3435 /* FIXME: clear the slot for MonoAppContexts, too */
3439 #ifdef PLATFORM_WIN32
3440 static void CALLBACK dummy_apc (ULONG_PTR param)
3444 static guint32 dummy_apc (gpointer param)
3451 * mono_thread_execute_interruption
3453 * Performs the operation that the requested thread state requires (abort,
3456 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3458 ensure_synch_cs_set (thread);
3460 EnterCriticalSection (thread->synch_cs);
3462 if (thread->interruption_requested) {
3463 /* this will consume pending APC calls */
3464 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3465 InterlockedDecrement (&thread_interruption_requested);
3466 thread->interruption_requested = FALSE;
3469 if ((thread->state & ThreadState_AbortRequested) != 0) {
3470 if (thread->abort_exc == NULL)
3471 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3472 LeaveCriticalSection (thread->synch_cs);
3473 return thread->abort_exc;
3475 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3476 thread->state &= ~ThreadState_SuspendRequested;
3477 thread->state |= ThreadState_Suspended;
3478 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3479 if (thread->suspend_event == NULL) {
3480 LeaveCriticalSection (thread->synch_cs);
3483 if (thread->suspended_event)
3484 SetEvent (thread->suspended_event);
3486 LeaveCriticalSection (thread->synch_cs);
3488 if (shutting_down) {
3489 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3494 WaitForSingleObject (thread->suspend_event, INFINITE);
3496 EnterCriticalSection (thread->synch_cs);
3498 CloseHandle (thread->suspend_event);
3499 thread->suspend_event = NULL;
3500 thread->state &= ~ThreadState_Suspended;
3502 /* The thread that requested the resume will have replaced this event
3503 * and will be waiting for it
3505 SetEvent (thread->resume_event);
3507 LeaveCriticalSection (thread->synch_cs);
3511 else if ((thread->state & ThreadState_StopRequested) != 0) {
3512 /* FIXME: do this through the JIT? */
3514 LeaveCriticalSection (thread->synch_cs);
3516 mono_thread_exit ();
3518 } else if (thread->thread_interrupt_requested) {
3520 thread->thread_interrupt_requested = FALSE;
3521 LeaveCriticalSection (thread->synch_cs);
3523 return(mono_get_exception_thread_interrupted ());
3526 LeaveCriticalSection (thread->synch_cs);
3532 * mono_thread_request_interruption
3534 * A signal handler can call this method to request the interruption of a
3535 * thread. The result of the interruption will depend on the current state of
3536 * the thread. If the result is an exception that needs to be throw, it is
3537 * provided as return value.
3540 mono_thread_request_interruption (gboolean running_managed)
3542 MonoThread *thread = mono_thread_current ();
3544 /* The thread may already be stopping */
3548 if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
3551 if (!running_managed || is_running_protected_wrapper ()) {
3552 /* Can't stop while in unmanaged code. Increase the global interruption
3553 request count. When exiting the unmanaged method the count will be
3554 checked and the thread will be interrupted. */
3556 InterlockedIncrement (&thread_interruption_requested);
3558 if (mono_thread_notify_pending_exc_fn && !running_managed)
3559 /* The JIT will notify the thread about the interruption */
3560 /* This shouldn't take any locks */
3561 mono_thread_notify_pending_exc_fn ();
3563 /* this will awake the thread if it is in WaitForSingleObject
3565 /* Our implementation of this function ignores the func argument */
3566 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3570 return mono_thread_execute_interruption (thread);
3574 gboolean mono_thread_interruption_requested ()
3576 if (thread_interruption_requested) {
3577 MonoThread *thread = mono_thread_current ();
3578 /* The thread may already be stopping */
3580 return (thread->interruption_requested);
3585 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3587 MonoThread *thread = mono_thread_current ();
3589 /* The thread may already be stopping */
3593 mono_debugger_check_interruption ();
3595 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3596 MonoException* exc = mono_thread_execute_interruption (thread);
3597 if (exc) mono_raise_exception (exc);
3602 * Performs the interruption of the current thread, if one has been requested,
3603 * and the thread is not running a protected wrapper.
3605 void mono_thread_interruption_checkpoint ()
3607 mono_thread_interruption_checkpoint_request (FALSE);
3611 * Performs the interruption of the current thread, if one has been requested.
3613 void mono_thread_force_interruption_checkpoint ()
3615 mono_thread_interruption_checkpoint_request (TRUE);
3619 * mono_thread_get_and_clear_pending_exception:
3621 * Return any pending exceptions for the current thread and clear it as a side effect.
3624 mono_thread_get_and_clear_pending_exception (void)
3626 MonoThread *thread = mono_thread_current ();
3628 /* The thread may already be stopping */
3632 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3633 return mono_thread_execute_interruption (thread);
3636 if (thread->pending_exception) {
3637 MonoException *exc = thread->pending_exception;
3639 thread->pending_exception = NULL;
3647 * mono_set_pending_exception:
3649 * Set the pending exception of the current thread to EXC. On platforms which
3650 * support it, the exception will be thrown when execution returns to managed code.
3651 * On other platforms, this function is equivalent to mono_raise_exception ().
3652 * Internal calls which report exceptions using this function instead of
3653 * raise_exception () might be called by JITted code using a more efficient calling
3657 mono_set_pending_exception (MonoException *exc)
3659 MonoThread *thread = mono_thread_current ();
3661 /* The thread may already be stopping */
3665 if (mono_thread_notify_pending_exc_fn) {
3666 MONO_OBJECT_SETREF (thread, pending_exception, exc);
3668 mono_thread_notify_pending_exc_fn ();
3670 /* No way to notify the JIT about the exception, have to throw it now */
3671 mono_raise_exception (exc);
3676 * mono_thread_interruption_request_flag:
3678 * Returns the address of a flag that will be non-zero if an interruption has
3679 * been requested for a thread. The thread to interrupt may not be the current
3680 * thread, so an additional call to mono_thread_interruption_requested() or
3681 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3684 gint32* mono_thread_interruption_request_flag ()
3686 return &thread_interruption_requested;
3690 mono_thread_init_apartment_state (void)
3693 thread = mono_thread_current ();
3695 #ifdef PLATFORM_WIN32
3696 /* Positive return value indicates success, either
3697 * S_OK if this is first CoInitialize call, or
3698 * S_FALSE if CoInitialize already called, but with same
3699 * threading model. A negative value indicates failure,
3700 * probably due to trying to change the threading model.
3702 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3703 ? COINIT_APARTMENTTHREADED
3704 : COINIT_MULTITHREADED) < 0) {
3705 thread->apartment_state = ThreadApartmentState_Unknown;
3711 mono_thread_cleanup_apartment_state (void)
3713 #ifdef PLATFORM_WIN32
3715 thread = mono_thread_current ();
3717 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3724 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3726 ensure_synch_cs_set (thread);
3728 EnterCriticalSection (thread->synch_cs);
3729 thread->state |= state;
3730 LeaveCriticalSection (thread->synch_cs);
3734 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3736 ensure_synch_cs_set (thread);
3738 EnterCriticalSection (thread->synch_cs);
3739 thread->state &= ~state;
3740 LeaveCriticalSection (thread->synch_cs);
3744 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3746 gboolean ret = FALSE;
3748 ensure_synch_cs_set (thread);
3750 EnterCriticalSection (thread->synch_cs);
3752 if ((thread->state & test) != 0) {
3756 LeaveCriticalSection (thread->synch_cs);