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 mono_thread_hazardous_free_or_queue (gpointer p, MonoHazardousFreeFunc free_func)
423 /* First try to free a few entries in the delayed free
425 for (i = 2; i >= 0; --i) {
426 if (delayed_free_table->len > i) {
427 DelayedFreeItem item;
430 EnterCriticalSection (&delayed_free_table_mutex);
431 /* We have to check the length again because another
432 thread might have freed an item before we acquired
434 if (delayed_free_table->len > i) {
435 item = g_array_index (delayed_free_table, DelayedFreeItem, i);
437 if (!is_pointer_hazardous (item.p))
438 g_array_remove_index_fast (delayed_free_table, i);
442 LeaveCriticalSection (&delayed_free_table_mutex);
445 item.free_func (item.p);
449 /* Now see if the pointer we're freeing is hazardous. If it
450 isn't, free it. Otherwise put it in the delay list. */
451 if (is_pointer_hazardous (p)) {
452 DelayedFreeItem item = { p, free_func };
454 ++mono_stats.hazardous_pointer_count;
456 EnterCriticalSection (&delayed_free_table_mutex);
457 g_array_append_val (delayed_free_table, item);
458 LeaveCriticalSection (&delayed_free_table_mutex);
463 static void ensure_synch_cs_set (MonoThread *thread)
465 CRITICAL_SECTION *synch_cs;
467 if (thread->synch_cs != NULL) {
471 synch_cs = g_new0 (CRITICAL_SECTION, 1);
472 InitializeCriticalSection (synch_cs);
474 if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
475 synch_cs, NULL) != NULL) {
476 /* Another thread must have installed this CS */
477 DeleteCriticalSection (synch_cs);
483 * NOTE: this function can be called also for threads different from the current one:
484 * make sure no code called from it will ever assume it is run on the thread that is
485 * getting cleaned up.
487 static void thread_cleanup (MonoThread *thread)
489 g_assert (thread != NULL);
491 /* if the thread is not in the hash it has been removed already */
492 if (!handle_remove (thread))
494 mono_release_type_locks (thread);
496 EnterCriticalSection (thread->synch_cs);
498 thread->state |= ThreadState_Stopped;
499 thread->state &= ~ThreadState_Background;
501 LeaveCriticalSection (thread->synch_cs);
503 mono_profiler_thread_end (thread->tid);
505 if (thread == mono_thread_current ())
506 mono_thread_pop_appdomain_ref ();
508 if (thread->serialized_culture_info)
509 g_free (thread->serialized_culture_info);
511 thread->cached_culture_info = NULL;
513 mono_gc_free_fixed (thread->static_data);
514 thread->static_data = NULL;
516 if (mono_thread_cleanup_fn)
517 mono_thread_cleanup_fn (thread);
519 small_id_free (thread->small_id);
520 thread->small_id = -2;
523 static guint32 WINAPI start_wrapper(void *data)
525 struct StartInfo *start_info=(struct StartInfo *)data;
526 guint32 (*start_func)(void *);
529 MonoThread *thread=start_info->obj;
530 MonoObject *start_delegate = start_info->delegate;
532 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
534 /* We can be sure start_info->obj->tid and
535 * start_info->obj->handle have been set, because the thread
536 * was created suspended, and these values were set before the
542 SET_CURRENT_OBJECT (thread);
544 /* Every thread references the appdomain which created it */
545 mono_thread_push_appdomain_ref (start_info->domain);
547 if (!mono_domain_set (start_info->domain, FALSE)) {
548 /* No point in raising an appdomain_unloaded exception here */
549 /* FIXME: Cleanup here */
550 mono_thread_pop_appdomain_ref ();
554 start_func = start_info->func;
555 start_arg = start_info->start_arg;
557 /* This MUST be called before any managed code can be
558 * executed, as it calls the callback function that (for the
559 * jit) sets the lmf marker.
561 mono_thread_new_init (tid, &tid, start_func);
562 thread->stack_ptr = &tid;
564 LIBGC_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT",%d) Setting thread stack to %p", __func__, GetCurrentThreadId (), getpid (), thread->stack_ptr));
566 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
568 mono_profiler_thread_start (tid);
570 /* On 2.0 profile (and higher), set explicitly since state might have been
572 if (mono_get_runtime_info ()->framework_version [0] != '1') {
573 if (thread->apartment_state == ThreadApartmentState_Unknown)
574 thread->apartment_state = ThreadApartmentState_MTA;
577 mono_thread_init_apartment_state ();
579 if(thread->start_notify!=NULL) {
580 /* Let the thread that called Start() know we're
583 ReleaseSemaphore (thread->start_notify, 1, NULL);
586 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
589 thread_adjust_static_data (thread);
591 g_message ("%s: start_wrapper for %"G_GSIZE_FORMAT, __func__,
595 /* start_func is set only for unmanaged start functions */
597 start_func (start_arg);
600 g_assert (start_delegate != NULL);
601 args [0] = start_arg;
602 /* we may want to handle the exception here. See comment below on unhandled exceptions */
603 mono_runtime_delegate_invoke (start_delegate, args, NULL);
606 /* If the thread calls ExitThread at all, this remaining code
607 * will not be executed, but the main thread will eventually
608 * call thread_cleanup() on this thread's behalf.
611 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper terminating", __func__, GetCurrentThreadId ()));
613 thread_cleanup (thread);
615 /* Do any cleanup needed for apartment state. This
616 * cannot be done in thread_cleanup since thread_cleanup could be
617 * called for a thread other than the current thread.
618 * mono_thread_cleanup_apartment_state cleans up apartment
619 * for the current thead */
620 mono_thread_cleanup_apartment_state ();
622 /* Remove the reference to the thread object in the TLS data,
623 * so the thread object can be finalized. This won't be
624 * reached if the thread threw an uncaught exception, so those
625 * thread handles will stay referenced :-( (This is due to
626 * missing support for scanning thread-specific data in the
627 * Boehm GC - the io-layer keeps a GC-visible hash of pointers
630 SET_CURRENT_OBJECT (NULL);
635 void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
637 if (mono_thread_start_cb) {
638 mono_thread_start_cb (tid, stack_start, func);
642 void mono_threads_set_default_stacksize (guint32 stacksize)
644 default_stacksize = stacksize;
647 guint32 mono_threads_get_default_stacksize (void)
649 return default_stacksize;
652 void mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread)
655 HANDLE thread_handle;
656 struct StartInfo *start_info;
659 thread=(MonoThread *)mono_object_new (domain,
660 mono_defaults.thread_class);
662 start_info=g_new0 (struct StartInfo, 1);
663 start_info->func = func;
664 start_info->obj = thread;
665 start_info->domain = domain;
666 start_info->start_arg = arg;
669 * The argument may be an object reference, and there is no ref to keep it alive
670 * when the new thread is started but not yet registered with the collector.
672 MONO_GC_REGISTER_ROOT (start_info->start_arg);
674 mono_threads_lock ();
676 mono_threads_unlock ();
679 if (threads_starting_up == NULL) {
680 MONO_GC_REGISTER_ROOT (threads_starting_up);
681 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
683 mono_g_hash_table_insert (threads_starting_up, thread, thread);
684 mono_threads_unlock ();
686 /* Create suspended, so we can do some housekeeping before the thread
689 thread_handle = CreateThread(NULL, default_stacksize_for_thread (thread), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
690 CREATE_SUSPENDED, &tid);
691 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
692 if (thread_handle == NULL) {
693 /* The thread couldn't be created, so throw an exception */
694 MONO_GC_UNREGISTER_ROOT (start_info->start_arg);
695 mono_threads_lock ();
696 mono_g_hash_table_remove (threads_starting_up, thread);
697 mono_threads_unlock ();
699 mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
703 thread->handle=thread_handle;
705 thread->apartment_state=ThreadApartmentState_Unknown;
706 small_id_alloc (thread);
708 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
709 InitializeCriticalSection (thread->synch_cs);
711 thread->threadpool_thread = threadpool_thread;
713 if (handle_store (thread))
714 ResumeThread (thread_handle);
718 mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
720 mono_thread_create_internal (domain, func, arg, FALSE);
724 * mono_thread_get_stack_bounds:
726 * Return the address and size of the current threads stack. Return NULL as the stack
727 * address if the stack address cannot be determined.
730 mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
732 #if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
733 *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self ());
734 *stsize = pthread_get_stacksize_np (pthread_self ());
736 /* FIXME: simplify the mess below */
737 #elif !defined(PLATFORM_WIN32)
739 guint8 *current = (guint8*)&attr;
741 pthread_attr_init (&attr);
742 #ifdef HAVE_PTHREAD_GETATTR_NP
743 pthread_getattr_np (pthread_self(), &attr);
745 #ifdef HAVE_PTHREAD_ATTR_GET_NP
746 pthread_attr_get_np (pthread_self(), &attr);
749 pthread_attr_getstacksize (&attr, &stsize);
758 pthread_attr_getstack (&attr, (void**)staddr, stsize);
760 g_assert ((current > *staddr) && (current < *staddr + *stsize));
763 pthread_attr_destroy (&attr);
768 mono_thread_attach (MonoDomain *domain)
771 HANDLE thread_handle;
774 if ((thread = mono_thread_current ())) {
775 if (domain != mono_domain_get ())
776 mono_domain_set (domain, TRUE);
777 /* Already attached */
781 if (!mono_gc_register_thread (&domain)) {
782 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 ());
785 thread = (MonoThread *)mono_object_new (domain,
786 mono_defaults.thread_class);
788 thread_handle = GetCurrentThread ();
789 g_assert (thread_handle);
791 tid=GetCurrentThreadId ();
794 * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
795 * refer to the thread from other threads for things like aborting.
797 DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle,
798 THREAD_ALL_ACCESS, TRUE, 0);
800 thread->handle=thread_handle;
802 thread->apartment_state=ThreadApartmentState_Unknown;
803 small_id_alloc (thread);
804 thread->stack_ptr = &tid;
806 thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
807 InitializeCriticalSection (thread->synch_cs);
809 THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
811 if (!handle_store (thread)) {
812 /* Mono is shutting down, so just wait for the end */
817 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Setting current_object_key to %p", __func__, GetCurrentThreadId (), thread));
819 SET_CURRENT_OBJECT (thread);
820 mono_domain_set (domain, TRUE);
822 thread_adjust_static_data (thread);
824 if (mono_thread_attach_cb) {
828 mono_thread_get_stack_bounds (&staddr, &stsize);
831 mono_thread_attach_cb (tid, &tid);
833 mono_thread_attach_cb (tid, staddr + stsize);
840 mono_thread_detach (MonoThread *thread)
842 g_return_if_fail (thread != NULL);
844 THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
846 thread_cleanup (thread);
848 SET_CURRENT_OBJECT (NULL);
850 /* Don't need to CloseHandle this thread, even though we took a
851 * reference in mono_thread_attach (), because the GC will do it
852 * when the Thread object is finalised.
859 MonoThread *thread = mono_thread_current ();
861 THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
863 thread_cleanup (thread);
864 SET_CURRENT_OBJECT (NULL);
866 /* we could add a callback here for embedders to use. */
867 if (thread == mono_thread_get_main ())
868 exit (mono_environment_exitcode_get ());
872 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
875 guint32 (*start_func)(void *);
876 struct StartInfo *start_info;
882 THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
884 ensure_synch_cs_set (this);
886 EnterCriticalSection (this->synch_cs);
888 if ((this->state & ThreadState_Unstarted) == 0) {
889 LeaveCriticalSection (this->synch_cs);
890 mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
896 if ((this->state & ThreadState_Aborted) != 0) {
897 LeaveCriticalSection (this->synch_cs);
902 /* This is freed in start_wrapper */
903 start_info = g_new0 (struct StartInfo, 1);
904 start_info->func = start_func;
905 start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
906 start_info->delegate = start;
907 start_info->obj = this;
908 start_info->domain = mono_domain_get ();
910 this->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
911 if(this->start_notify==NULL) {
912 LeaveCriticalSection (this->synch_cs);
913 g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
917 mono_threads_lock ();
918 if (threads_starting_up == NULL) {
919 MONO_GC_REGISTER_ROOT (threads_starting_up);
920 threads_starting_up = mono_g_hash_table_new (NULL, NULL);
922 mono_g_hash_table_insert (threads_starting_up, this, this);
923 mono_threads_unlock ();
925 thread=CreateThread(NULL, default_stacksize_for_thread (this), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
926 CREATE_SUSPENDED, &tid);
928 LeaveCriticalSection (this->synch_cs);
929 mono_threads_lock ();
930 mono_g_hash_table_remove (threads_starting_up, this);
931 mono_threads_unlock ();
932 g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
938 small_id_alloc (this);
940 /* Don't call handle_store() here, delay it to Start.
941 * We can't join a thread (trying to will just block
942 * forever) until it actually starts running, so don't
943 * store the handle till then.
946 mono_thread_start (this);
948 this->state &= ~ThreadState_Unstarted;
950 THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
952 LeaveCriticalSection (this->synch_cs);
957 void ves_icall_System_Threading_Thread_Thread_init (MonoThread *this)
961 ensure_synch_cs_set (this);
964 void ves_icall_System_Threading_Thread_Thread_free_internal (MonoThread *this,
969 THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
971 CloseHandle (thread);
973 DeleteCriticalSection (this->synch_cs);
974 g_free (this->synch_cs);
975 this->synch_cs = NULL;
978 static void mono_thread_start (MonoThread *thread)
982 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
984 /* Only store the handle when the thread is about to be
985 * launched, to avoid the main thread deadlocking while trying
986 * to clean up a thread that will never be signalled.
988 if (!handle_store (thread))
991 ResumeThread (thread->handle);
993 if(thread->start_notify!=NULL) {
994 /* Wait for the thread to set up its TLS data etc, so
995 * theres no potential race condition if someone tries
996 * to look up the data believing the thread has
1000 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1002 WaitForSingleObjectEx (thread->start_notify, INFINITE, FALSE);
1003 CloseHandle (thread->start_notify);
1004 thread->start_notify = NULL;
1007 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
1010 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
1012 MonoThread *thread = mono_thread_current ();
1014 MONO_ARCH_SAVE_REGS;
1016 THREAD_DEBUG (g_message ("%s: Sleeping for %d ms", __func__, ms));
1018 mono_thread_current_check_pending_interrupt ();
1020 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1024 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1027 void ves_icall_System_Threading_Thread_SpinWait_internal (gint32 iterations)
1031 for(i = 0; i < iterations; i++) {
1032 /* We're busy waiting, but at least we can tell the
1033 * scheduler to let someone else have a go...
1040 ves_icall_System_Threading_Thread_GetDomainID (void)
1042 MONO_ARCH_SAVE_REGS;
1044 return mono_domain_get()->domain_id;
1048 ves_icall_System_Threading_Thread_GetName_internal (MonoThread *this_obj)
1052 ensure_synch_cs_set (this_obj);
1054 EnterCriticalSection (this_obj->synch_cs);
1056 if (!this_obj->name)
1059 str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
1061 LeaveCriticalSection (this_obj->synch_cs);
1067 ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoString *name)
1069 ensure_synch_cs_set (this_obj);
1071 EnterCriticalSection (this_obj->synch_cs);
1073 if (this_obj->name) {
1074 LeaveCriticalSection (this_obj->synch_cs);
1076 mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
1080 this_obj->name = g_new (gunichar2, mono_string_length (name));
1081 memcpy (this_obj->name, mono_string_chars (name), mono_string_length (name) * 2);
1082 this_obj->name_len = mono_string_length (name);
1085 this_obj->name = NULL;
1087 LeaveCriticalSection (this_obj->synch_cs);
1091 lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
1096 if (this->cached_culture_info) {
1097 domain = mono_domain_get ();
1098 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1099 res = mono_array_get (this->cached_culture_info, MonoObject*, i);
1100 if (res && res->vtable->domain == domain)
1109 ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
1111 return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
1115 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
1119 ensure_synch_cs_set (this);
1121 EnterCriticalSection (this->synch_cs);
1123 if (this->serialized_culture_info) {
1124 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
1125 memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
1130 LeaveCriticalSection (this->synch_cs);
1136 cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
1139 MonoDomain *domain = mono_domain_get ();
1142 int same_domain_slot = -1;
1144 ensure_synch_cs_set (this);
1146 EnterCriticalSection (this->synch_cs);
1148 if (!this->cached_culture_info)
1149 MONO_OBJECT_SETREF (this, cached_culture_info, mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2));
1151 for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
1152 obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
1156 /* we continue, because there may be a slot used with the same domain */
1160 if (obj->vtable->domain == domain) {
1161 same_domain_slot = i;
1165 if (same_domain_slot >= 0)
1166 mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
1167 else if (free_slot >= 0)
1168 mono_array_setref (this->cached_culture_info, free_slot, culture);
1169 /* we may want to replace an existing entry here, even when no suitable slot is found */
1171 LeaveCriticalSection (this->synch_cs);
1175 ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
1177 cache_culture (this, culture, CULTURES_START_IDX);
1181 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
1183 ensure_synch_cs_set (this);
1185 EnterCriticalSection (this->synch_cs);
1187 if (this->serialized_culture_info)
1188 g_free (this->serialized_culture_info);
1189 this->serialized_culture_info = g_new0 (guint8, mono_array_length (arr));
1190 this->serialized_culture_info_len = mono_array_length (arr);
1191 memcpy (this->serialized_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1193 LeaveCriticalSection (this->synch_cs);
1198 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
1200 return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
1204 ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *this)
1208 ensure_synch_cs_set (this);
1210 EnterCriticalSection (this->synch_cs);
1212 if (this->serialized_ui_culture_info) {
1213 res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
1214 memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
1219 LeaveCriticalSection (this->synch_cs);
1225 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
1227 cache_culture (this, culture, UICULTURES_START_IDX);
1231 ves_icall_System_Threading_Thread_SetSerializedCurrentUICulture (MonoThread *this, MonoArray *arr)
1233 ensure_synch_cs_set (this);
1235 EnterCriticalSection (this->synch_cs);
1237 if (this->serialized_ui_culture_info)
1238 g_free (this->serialized_ui_culture_info);
1239 this->serialized_ui_culture_info = g_new0 (guint8, mono_array_length (arr));
1240 this->serialized_ui_culture_info_len = mono_array_length (arr);
1241 memcpy (this->serialized_ui_culture_info, mono_array_addr (arr, guint8, 0), mono_array_length (arr));
1243 LeaveCriticalSection (this->synch_cs);
1246 /* the jit may read the compiled code of this function */
1248 mono_thread_current (void)
1250 THREAD_DEBUG (g_message ("%s: returning %p", __func__, GET_CURRENT_OBJECT ()));
1251 return GET_CURRENT_OBJECT ();
1254 gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
1255 int ms, HANDLE thread)
1257 MonoThread *cur_thread = mono_thread_current ();
1260 MONO_ARCH_SAVE_REGS;
1262 mono_thread_current_check_pending_interrupt ();
1264 ensure_synch_cs_set (this);
1266 EnterCriticalSection (this->synch_cs);
1268 if ((this->state & ThreadState_Unstarted) != 0) {
1269 LeaveCriticalSection (this->synch_cs);
1271 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
1275 LeaveCriticalSection (this->synch_cs);
1280 THREAD_DEBUG (g_message ("%s: joining thread handle %p, %d ms", __func__, thread, ms));
1282 mono_thread_set_state (cur_thread, ThreadState_WaitSleepJoin);
1284 ret=WaitForSingleObjectEx (thread, ms, TRUE);
1286 mono_thread_clr_state (cur_thread, ThreadState_WaitSleepJoin);
1288 if(ret==WAIT_OBJECT_0) {
1289 THREAD_DEBUG (g_message ("%s: join successful", __func__));
1294 THREAD_DEBUG (g_message ("%s: join failed", __func__));
1299 /* FIXME: exitContext isnt documented */
1300 gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1306 MonoObject *waitHandle;
1307 MonoThread *thread = mono_thread_current ();
1309 MONO_ARCH_SAVE_REGS;
1311 /* Do this WaitSleepJoin check before creating objects */
1312 mono_thread_current_check_pending_interrupt ();
1314 numhandles = mono_array_length(mono_handles);
1315 handles = g_new0(HANDLE, numhandles);
1317 for(i = 0; i < numhandles; i++) {
1318 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1319 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1326 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1328 ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
1330 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1334 if(ret==WAIT_FAILED) {
1335 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1337 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1338 /* Do we want to try again if we get
1339 * WAIT_IO_COMPLETION? The documentation for
1340 * WaitHandle doesn't give any clues. (We'd have to
1341 * fiddle with the timeout if we retry.)
1343 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1350 /* FIXME: exitContext isnt documented */
1351 gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
1357 MonoObject *waitHandle;
1358 MonoThread *thread = mono_thread_current ();
1360 MONO_ARCH_SAVE_REGS;
1362 /* Do this WaitSleepJoin check before creating objects */
1363 mono_thread_current_check_pending_interrupt ();
1365 numhandles = mono_array_length(mono_handles);
1366 handles = g_new0(HANDLE, numhandles);
1368 for(i = 0; i < numhandles; i++) {
1369 waitHandle = mono_array_get(mono_handles, MonoObject*, i);
1370 handles [i] = mono_wait_handle_get_handle ((MonoWaitHandle *) waitHandle);
1377 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1379 ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
1381 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1385 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") returning %d", __func__, GetCurrentThreadId (), ret));
1388 * These need to be here. See MSDN dos on WaitForMultipleObjects.
1390 if (ret >= WAIT_OBJECT_0 && ret <= WAIT_OBJECT_0 + numhandles - 1) {
1391 return ret - WAIT_OBJECT_0;
1393 else if (ret >= WAIT_ABANDONED_0 && ret <= WAIT_ABANDONED_0 + numhandles - 1) {
1394 return ret - WAIT_ABANDONED_0;
1401 /* FIXME: exitContext isnt documented */
1402 gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this, HANDLE handle, gint32 ms, gboolean exitContext)
1405 MonoThread *thread = mono_thread_current ();
1407 MONO_ARCH_SAVE_REGS;
1409 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for %p, %d ms", __func__, GetCurrentThreadId (), handle, ms));
1415 mono_thread_current_check_pending_interrupt ();
1417 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1419 ret=WaitForSingleObjectEx (handle, ms, TRUE);
1421 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1423 if(ret==WAIT_FAILED) {
1424 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait failed", __func__, GetCurrentThreadId ()));
1426 } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
1427 /* Do we want to try again if we get
1428 * WAIT_IO_COMPLETION? The documentation for
1429 * WaitHandle doesn't give any clues. (We'd have to
1430 * fiddle with the timeout if we retry.)
1432 THREAD_WAIT_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Wait timed out", __func__, GetCurrentThreadId ()));
1439 HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
1443 MONO_ARCH_SAVE_REGS;
1448 mutex = CreateMutex (NULL, owned, NULL);
1450 mutex = CreateMutex (NULL, owned, mono_string_chars (name));
1452 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1460 MonoBoolean ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) {
1461 MONO_ARCH_SAVE_REGS;
1463 return(ReleaseMutex (handle));
1466 HANDLE ves_icall_System_Threading_Mutex_OpenMutex_internal (MonoString *name,
1472 MONO_ARCH_SAVE_REGS;
1474 *error = ERROR_SUCCESS;
1476 ret = OpenMutex (rights, FALSE, mono_string_chars (name));
1478 *error = GetLastError ();
1485 HANDLE ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, MonoBoolean *created)
1489 MONO_ARCH_SAVE_REGS;
1494 sem = CreateSemaphore (NULL, initialCount, maximumCount, NULL);
1496 sem = CreateSemaphore (NULL, initialCount, maximumCount,
1497 mono_string_chars (name));
1499 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1507 gint32 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (HANDLE handle, gint32 releaseCount, MonoBoolean *fail)
1511 MONO_ARCH_SAVE_REGS;
1513 *fail = !ReleaseSemaphore (handle, releaseCount, &prevcount);
1518 HANDLE ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error)
1522 MONO_ARCH_SAVE_REGS;
1524 *error = ERROR_SUCCESS;
1526 ret = OpenSemaphore (rights, FALSE, mono_string_chars (name));
1528 *error = GetLastError ();
1534 HANDLE ves_icall_System_Threading_Events_CreateEvent_internal (MonoBoolean manual, MonoBoolean initial, MonoString *name, MonoBoolean *created)
1538 MONO_ARCH_SAVE_REGS;
1543 event = CreateEvent (NULL, manual, initial, NULL);
1545 event = CreateEvent (NULL, manual, initial,
1546 mono_string_chars (name));
1548 if (GetLastError () == ERROR_ALREADY_EXISTS) {
1556 gboolean ves_icall_System_Threading_Events_SetEvent_internal (HANDLE handle) {
1557 MONO_ARCH_SAVE_REGS;
1559 return (SetEvent(handle));
1562 gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle) {
1563 MONO_ARCH_SAVE_REGS;
1565 return (ResetEvent(handle));
1569 ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle) {
1570 MONO_ARCH_SAVE_REGS;
1572 CloseHandle (handle);
1575 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name,
1581 MONO_ARCH_SAVE_REGS;
1583 *error = ERROR_SUCCESS;
1585 ret = OpenEvent (rights, FALSE, mono_string_chars (name));
1587 *error = GetLastError ();
1593 gint32 ves_icall_System_Threading_Interlocked_Increment_Int (gint32 *location)
1595 MONO_ARCH_SAVE_REGS;
1597 return InterlockedIncrement (location);
1600 gint64 ves_icall_System_Threading_Interlocked_Increment_Long (gint64 *location)
1604 MONO_ARCH_SAVE_REGS;
1606 mono_interlocked_lock ();
1610 mono_interlocked_unlock ();
1616 gint32 ves_icall_System_Threading_Interlocked_Decrement_Int (gint32 *location)
1618 MONO_ARCH_SAVE_REGS;
1620 return InterlockedDecrement(location);
1623 gint64 ves_icall_System_Threading_Interlocked_Decrement_Long (gint64 * location)
1627 MONO_ARCH_SAVE_REGS;
1629 mono_interlocked_lock ();
1633 mono_interlocked_unlock ();
1638 gint32 ves_icall_System_Threading_Interlocked_Exchange_Int (gint32 *location, gint32 value)
1640 MONO_ARCH_SAVE_REGS;
1642 return InterlockedExchange(location, value);
1645 MonoObject * ves_icall_System_Threading_Interlocked_Exchange_Object (MonoObject **location, MonoObject *value)
1647 MONO_ARCH_SAVE_REGS;
1649 return (MonoObject *) InterlockedExchangePointer((gpointer *) location, value);
1652 gfloat ves_icall_System_Threading_Interlocked_Exchange_Single (gfloat *location, gfloat value)
1654 IntFloatUnion val, ret;
1656 MONO_ARCH_SAVE_REGS;
1659 ret.ival = InterlockedExchange((gint32 *) location, val.ival);
1665 ves_icall_System_Threading_Interlocked_Exchange_Long (gint64 *location, gint64 value)
1667 #if SIZEOF_VOID_P == 8
1668 return (gint64) InterlockedExchangePointer((gpointer *) location, (gpointer)value);
1673 * According to MSDN, this function is only atomic with regards to the
1674 * other Interlocked functions on 32 bit platforms.
1676 mono_interlocked_lock ();
1679 mono_interlocked_unlock ();
1686 ves_icall_System_Threading_Interlocked_Exchange_Double (gdouble *location, gdouble value)
1688 #if SIZEOF_VOID_P == 8
1689 LongDoubleUnion val, ret;
1692 ret.ival = (gint64)InterlockedExchangePointer((gpointer *) location, (gpointer)val.ival);
1699 * According to MSDN, this function is only atomic with regards to the
1700 * other Interlocked functions on 32 bit platforms.
1702 mono_interlocked_lock ();
1705 mono_interlocked_unlock ();
1711 gint32 ves_icall_System_Threading_Interlocked_CompareExchange_Int(gint32 *location, gint32 value, gint32 comparand)
1713 MONO_ARCH_SAVE_REGS;
1715 return InterlockedCompareExchange(location, value, comparand);
1718 MonoObject * ves_icall_System_Threading_Interlocked_CompareExchange_Object (MonoObject **location, MonoObject *value, MonoObject *comparand)
1720 MONO_ARCH_SAVE_REGS;
1722 return (MonoObject *) InterlockedCompareExchangePointer((gpointer *) location, value, comparand);
1725 gfloat ves_icall_System_Threading_Interlocked_CompareExchange_Single (gfloat *location, gfloat value, gfloat comparand)
1727 IntFloatUnion val, ret, cmp;
1729 MONO_ARCH_SAVE_REGS;
1732 cmp.fval = comparand;
1733 ret.ival = InterlockedCompareExchange((gint32 *) location, val.ival, cmp.ival);
1739 ves_icall_System_Threading_Interlocked_CompareExchange_Double (gdouble *location, gdouble value, gdouble comparand)
1741 #if SIZEOF_VOID_P == 8
1742 LongDoubleUnion val, comp, ret;
1745 comp.fval = comparand;
1746 ret.ival = (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)val.ival, (gpointer)comp.ival);
1752 mono_interlocked_lock ();
1754 if (old == comparand)
1756 mono_interlocked_unlock ();
1763 ves_icall_System_Threading_Interlocked_CompareExchange_Long (gint64 *location, gint64 value, gint64 comparand)
1765 #if SIZEOF_VOID_P == 8
1766 return (gint64)InterlockedCompareExchangePointer((gpointer *) location, (gpointer)value, (gpointer)comparand);
1770 mono_interlocked_lock ();
1772 if (old == comparand)
1774 mono_interlocked_unlock ();
1781 ves_icall_System_Threading_Interlocked_CompareExchange_T (MonoObject **location, MonoObject *value, MonoObject *comparand)
1783 MONO_ARCH_SAVE_REGS;
1785 return InterlockedCompareExchangePointer ((gpointer *)location, value, comparand);
1789 ves_icall_System_Threading_Interlocked_Exchange_T (MonoObject **location, MonoObject *value)
1791 MONO_ARCH_SAVE_REGS;
1793 return InterlockedExchangePointer ((gpointer *)location, value);
1797 ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
1799 #if SIZEOF_VOID_P == 8
1800 /* Should be implemented as a JIT intrinsic */
1801 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1806 mono_interlocked_lock ();
1808 *location = orig + value;
1809 mono_interlocked_unlock ();
1811 return orig + value;
1816 ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
1818 #if SIZEOF_VOID_P == 8
1819 /* Should be implemented as a JIT intrinsic */
1820 mono_raise_exception (mono_get_exception_not_implemented (NULL));
1825 mono_interlocked_lock ();
1827 *location = orig + value;
1828 mono_interlocked_unlock ();
1830 return orig + value;
1835 ves_icall_System_Threading_Interlocked_Read_Long (gint64 *location)
1837 #if SIZEOF_VOID_P == 8
1838 /* 64 bit reads are already atomic */
1843 mono_interlocked_lock ();
1845 mono_interlocked_unlock ();
1852 ves_icall_System_Threading_Thread_MemoryBarrier (void)
1854 mono_threads_lock ();
1855 mono_threads_unlock ();
1859 ves_icall_System_Threading_Thread_ClrState (MonoThread* this, guint32 state)
1861 mono_thread_clr_state (this, state);
1863 if (state & ThreadState_Background) {
1864 /* If the thread changes the background mode, the main thread has to
1865 * be notified, since it has to rebuild the list of threads to
1868 SetEvent (background_change_event);
1873 ves_icall_System_Threading_Thread_SetState (MonoThread* this, guint32 state)
1875 mono_thread_set_state (this, state);
1877 if (state & ThreadState_Background) {
1878 /* If the thread changes the background mode, the main thread has to
1879 * be notified, since it has to rebuild the list of threads to
1882 SetEvent (background_change_event);
1887 ves_icall_System_Threading_Thread_GetState (MonoThread* this)
1891 ensure_synch_cs_set (this);
1893 EnterCriticalSection (this->synch_cs);
1895 state = this->state;
1897 LeaveCriticalSection (this->synch_cs);
1902 void ves_icall_System_Threading_Thread_Interrupt_internal (MonoThread *this)
1904 gboolean throw = FALSE;
1906 ensure_synch_cs_set (this);
1908 EnterCriticalSection (this->synch_cs);
1910 this->thread_interrupt_requested = TRUE;
1912 if (this->state & ThreadState_WaitSleepJoin) {
1916 LeaveCriticalSection (this->synch_cs);
1919 signal_thread_state_change (this);
1923 void mono_thread_current_check_pending_interrupt ()
1925 MonoThread *thread = mono_thread_current ();
1926 gboolean throw = FALSE;
1928 ensure_synch_cs_set (thread);
1930 EnterCriticalSection (thread->synch_cs);
1932 if (thread->thread_interrupt_requested) {
1934 thread->thread_interrupt_requested = FALSE;
1937 LeaveCriticalSection (thread->synch_cs);
1940 mono_raise_exception (mono_get_exception_thread_interrupted ());
1945 mono_thread_get_abort_signal (void)
1947 #ifdef PLATFORM_WIN32
1953 static int abort_signum = -1;
1955 if (abort_signum != -1)
1956 return abort_signum;
1957 /* we try to avoid SIGRTMIN and any one that might have been set already, see bug #75387 */
1958 for (i = SIGRTMIN + 1; i < SIGRTMAX; ++i) {
1959 struct sigaction sinfo;
1960 sigaction (i, NULL, &sinfo);
1961 if (sinfo.sa_handler == SIG_DFL && (void*)sinfo.sa_sigaction == (void*)SIG_DFL) {
1966 /* fallback to the old way */
1969 #endif /* PLATFORM_WIN32 */
1972 #ifdef PLATFORM_WIN32
1973 static void CALLBACK interruption_request_apc (ULONG_PTR param)
1975 MonoException* exc = mono_thread_request_interruption (FALSE);
1976 if (exc) mono_raise_exception (exc);
1978 #endif /* PLATFORM_WIN32 */
1981 * signal_thread_state_change
1983 * Tells the thread that his state has changed and it has to enter the new
1984 * state as soon as possible.
1986 static void signal_thread_state_change (MonoThread *thread)
1988 if (thread == mono_thread_current ()) {
1989 /* Do it synchronously */
1990 MonoException *exc = mono_thread_request_interruption (FALSE);
1992 mono_raise_exception (exc);
1995 #ifdef PLATFORM_WIN32
1996 QueueUserAPC ((PAPCFUNC)interruption_request_apc, thread->handle, NULL);
1998 /* fixme: store the state somewhere */
1999 #ifdef PTHREAD_POINTER_ID
2000 pthread_kill ((gpointer)(gsize)(thread->tid), mono_thread_get_abort_signal ());
2002 pthread_kill (thread->tid, mono_thread_get_abort_signal ());
2004 #endif /* PLATFORM_WIN32 */
2008 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
2010 MONO_ARCH_SAVE_REGS;
2012 ensure_synch_cs_set (thread);
2014 EnterCriticalSection (thread->synch_cs);
2016 if ((thread->state & ThreadState_AbortRequested) != 0 ||
2017 (thread->state & ThreadState_StopRequested) != 0 ||
2018 (thread->state & ThreadState_Stopped) != 0)
2020 LeaveCriticalSection (thread->synch_cs);
2024 if ((thread->state & ThreadState_Unstarted) != 0) {
2025 thread->state |= ThreadState_Aborted;
2026 LeaveCriticalSection (thread->synch_cs);
2030 thread->state |= ThreadState_AbortRequested;
2031 MONO_OBJECT_SETREF (thread, abort_state, state);
2032 thread->abort_exc = NULL;
2034 LeaveCriticalSection (thread->synch_cs);
2036 THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
2038 /* Make sure the thread is awake */
2039 mono_thread_resume (thread);
2041 signal_thread_state_change (thread);
2045 ves_icall_System_Threading_Thread_ResetAbort (void)
2047 MonoThread *thread = mono_thread_current ();
2049 MONO_ARCH_SAVE_REGS;
2051 ensure_synch_cs_set (thread);
2053 EnterCriticalSection (thread->synch_cs);
2055 thread->state &= ~ThreadState_AbortRequested;
2057 if (!thread->abort_exc) {
2058 const char *msg = "Unable to reset abort because no abort was requested";
2059 LeaveCriticalSection (thread->synch_cs);
2060 mono_raise_exception (mono_get_exception_thread_state (msg));
2062 thread->abort_exc = NULL;
2063 thread->abort_state = NULL;
2066 LeaveCriticalSection (thread->synch_cs);
2070 mono_thread_suspend (MonoThread *thread)
2072 MONO_ARCH_SAVE_REGS;
2074 ensure_synch_cs_set (thread);
2076 EnterCriticalSection (thread->synch_cs);
2078 if ((thread->state & ThreadState_Unstarted) != 0 ||
2079 (thread->state & ThreadState_Aborted) != 0 ||
2080 (thread->state & ThreadState_Stopped) != 0)
2082 LeaveCriticalSection (thread->synch_cs);
2086 if ((thread->state & ThreadState_Suspended) != 0 ||
2087 (thread->state & ThreadState_SuspendRequested) != 0 ||
2088 (thread->state & ThreadState_StopRequested) != 0)
2090 LeaveCriticalSection (thread->synch_cs);
2094 thread->state |= ThreadState_SuspendRequested;
2096 LeaveCriticalSection (thread->synch_cs);
2098 signal_thread_state_change (thread);
2103 ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
2105 if (!mono_thread_suspend (thread))
2106 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2110 mono_thread_resume (MonoThread *thread)
2112 MONO_ARCH_SAVE_REGS;
2114 ensure_synch_cs_set (thread);
2116 EnterCriticalSection (thread->synch_cs);
2118 if ((thread->state & ThreadState_SuspendRequested) != 0) {
2119 thread->state &= ~ThreadState_SuspendRequested;
2120 LeaveCriticalSection (thread->synch_cs);
2124 if ((thread->state & ThreadState_Suspended) == 0 ||
2125 (thread->state & ThreadState_Unstarted) != 0 ||
2126 (thread->state & ThreadState_Aborted) != 0 ||
2127 (thread->state & ThreadState_Stopped) != 0)
2129 LeaveCriticalSection (thread->synch_cs);
2133 thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2134 if (thread->resume_event == NULL) {
2135 LeaveCriticalSection (thread->synch_cs);
2139 /* Awake the thread */
2140 SetEvent (thread->suspend_event);
2142 LeaveCriticalSection (thread->synch_cs);
2144 /* Wait for the thread to awake */
2145 WaitForSingleObject (thread->resume_event, INFINITE);
2146 CloseHandle (thread->resume_event);
2147 thread->resume_event = NULL;
2153 ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
2155 if (!mono_thread_resume (thread))
2156 mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started, or is dead."));
2160 find_wrapper (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2165 if (m->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
2166 m->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE ||
2167 m->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH)
2169 *((gboolean*)data) = TRUE;
2176 is_running_protected_wrapper (void)
2178 gboolean found = FALSE;
2179 mono_stack_walk (find_wrapper, &found);
2183 void mono_thread_stop (MonoThread *thread)
2185 ensure_synch_cs_set (thread);
2187 EnterCriticalSection (thread->synch_cs);
2189 if ((thread->state & ThreadState_StopRequested) != 0 ||
2190 (thread->state & ThreadState_Stopped) != 0)
2192 LeaveCriticalSection (thread->synch_cs);
2196 /* Make sure the thread is awake */
2197 mono_thread_resume (thread);
2199 thread->state |= ThreadState_StopRequested;
2200 thread->state &= ~ThreadState_AbortRequested;
2202 LeaveCriticalSection (thread->synch_cs);
2204 signal_thread_state_change (thread);
2208 ves_icall_System_Threading_Thread_VolatileRead1 (void *ptr)
2210 return *((volatile gint8 *) (ptr));
2214 ves_icall_System_Threading_Thread_VolatileRead2 (void *ptr)
2216 return *((volatile gint16 *) (ptr));
2220 ves_icall_System_Threading_Thread_VolatileRead4 (void *ptr)
2222 return *((volatile gint32 *) (ptr));
2226 ves_icall_System_Threading_Thread_VolatileRead8 (void *ptr)
2228 return *((volatile gint64 *) (ptr));
2232 ves_icall_System_Threading_Thread_VolatileReadIntPtr (void *ptr)
2234 return (void *) *((volatile void **) ptr);
2238 ves_icall_System_Threading_Thread_VolatileWrite1 (void *ptr, gint8 value)
2240 *((volatile gint8 *) ptr) = value;
2244 ves_icall_System_Threading_Thread_VolatileWrite2 (void *ptr, gint16 value)
2246 *((volatile gint16 *) ptr) = value;
2250 ves_icall_System_Threading_Thread_VolatileWrite4 (void *ptr, gint32 value)
2252 *((volatile gint32 *) ptr) = value;
2256 ves_icall_System_Threading_Thread_VolatileWrite8 (void *ptr, gint64 value)
2258 *((volatile gint64 *) ptr) = value;
2262 ves_icall_System_Threading_Thread_VolatileWriteIntPtr (void *ptr, void *value)
2264 *((volatile void **) ptr) = value;
2267 void mono_thread_init (MonoThreadStartCB start_cb,
2268 MonoThreadAttachCB attach_cb)
2270 MONO_GC_REGISTER_ROOT (small_id_table);
2271 InitializeCriticalSection(&threads_mutex);
2272 InitializeCriticalSection(&interlocked_mutex);
2273 InitializeCriticalSection(&contexts_mutex);
2274 InitializeCriticalSection(&delayed_free_table_mutex);
2275 InitializeCriticalSection(&small_id_mutex);
2277 background_change_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2278 g_assert(background_change_event != NULL);
2280 mono_init_static_data_info (&thread_static_info);
2281 mono_init_static_data_info (&context_static_info);
2283 current_object_key=TlsAlloc();
2284 THREAD_DEBUG (g_message ("%s: Allocated current_object_key %d", __func__, current_object_key));
2286 mono_thread_start_cb = start_cb;
2287 mono_thread_attach_cb = attach_cb;
2289 delayed_free_table = g_array_new (FALSE, FALSE, sizeof (DelayedFreeItem));
2291 /* Get a pseudo handle to the current process. This is just a
2292 * kludge so that wapi can build a process handle if needed.
2293 * As a pseudo handle is returned, we don't need to clean
2296 GetCurrentProcess ();
2299 void mono_thread_cleanup (void)
2301 #if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
2302 /* The main thread must abandon any held mutexes (particularly
2303 * important for named mutexes as they are shared across
2304 * processes, see bug 74680.) This will happen when the
2305 * thread exits, but if it's not running in a subthread it
2306 * won't exit in time.
2308 /* Using non-w32 API is a nasty kludge, but I couldn't find
2309 * anything in the documentation that would let me do this
2310 * here yet still be safe to call on windows.
2312 _wapi_thread_signal_self (mono_environment_exitcode_get ());
2316 /* This stuff needs more testing, it seems one of these
2317 * critical sections can be locked when mono_thread_cleanup is
2320 DeleteCriticalSection (&threads_mutex);
2321 DeleteCriticalSection (&interlocked_mutex);
2322 DeleteCriticalSection (&contexts_mutex);
2323 DeleteCriticalSection (&delayed_free_table_mutex);
2324 DeleteCriticalSection (&small_id_mutex);
2325 CloseHandle (background_change_event);
2328 g_array_free (delayed_free_table, TRUE);
2330 TlsFree (current_object_key);
2334 mono_threads_install_cleanup (MonoThreadCleanupFunc func)
2336 mono_thread_cleanup_fn = func;
2340 mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCallback func)
2342 thread->manage_callback = func;
2345 void mono_threads_install_notify_pending_exc (MonoThreadNotifyPendingExcFunc func)
2347 mono_thread_notify_pending_exc_fn = func;
2351 static void print_tids (gpointer key, gpointer value, gpointer user)
2353 /* GPOINTER_TO_UINT breaks horribly if sizeof(void *) >
2354 * sizeof(uint) and a cast to uint would overflow
2356 /* Older versions of glib don't have G_GSIZE_FORMAT, so just
2357 * print this as a pointer.
2359 g_message ("Waiting for: %p", key);
2364 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
2365 MonoThread *threads[MAXIMUM_WAIT_OBJECTS];
2369 static void wait_for_tids (struct wait_data *wait, guint32 timeout)
2373 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2375 ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
2377 if(ret==WAIT_FAILED) {
2378 /* See the comment in build_wait_tids() */
2379 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2383 for(i=0; i<wait->num; i++)
2384 CloseHandle (wait->handles[i]);
2386 if (ret == WAIT_TIMEOUT)
2389 for(i=0; i<wait->num; i++) {
2390 gsize tid = wait->threads[i]->tid;
2392 mono_threads_lock ();
2393 if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2394 /* This thread must have been killed, because
2395 * it hasn't cleaned itself up. (It's just
2396 * possible that the thread exited before the
2397 * parent thread had a chance to store the
2398 * handle, and now there is another pointer to
2399 * the already-exited thread stored. In this
2400 * case, we'll just get two
2401 * mono_profiler_thread_end() calls for the
2405 mono_threads_unlock ();
2406 THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
2407 thread_cleanup (wait->threads[i]);
2409 mono_threads_unlock ();
2414 static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeout)
2416 guint32 i, ret, count;
2418 THREAD_DEBUG (g_message("%s: %d threads to wait for in this batch", __func__, wait->num));
2420 /* Add the thread state change event, so it wakes up if a thread changes
2421 * to background mode.
2424 if (count < MAXIMUM_WAIT_OBJECTS) {
2425 wait->handles [count] = background_change_event;
2429 ret=WaitForMultipleObjectsEx (count, wait->handles, FALSE, timeout, FALSE);
2431 if(ret==WAIT_FAILED) {
2432 /* See the comment in build_wait_tids() */
2433 THREAD_DEBUG (g_message ("%s: Wait failed", __func__));
2437 for(i=0; i<wait->num; i++)
2438 CloseHandle (wait->handles[i]);
2440 if (ret == WAIT_TIMEOUT)
2443 if (ret < wait->num) {
2444 gsize tid = wait->threads[ret]->tid;
2445 mono_threads_lock ();
2446 if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
2447 /* See comment in wait_for_tids about thread cleanup */
2448 mono_threads_unlock ();
2449 THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
2450 thread_cleanup (wait->threads [ret]);
2452 mono_threads_unlock ();
2456 static void build_wait_tids (gpointer key, gpointer value, gpointer user)
2458 struct wait_data *wait=(struct wait_data *)user;
2460 if(wait->num<MAXIMUM_WAIT_OBJECTS) {
2462 MonoThread *thread=(MonoThread *)value;
2464 /* Ignore background threads, we abort them later */
2465 /* Do not lock here since it is not needed and the caller holds threads_lock */
2466 if (thread->state & ThreadState_Background) {
2467 THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2468 return; /* just leave, ignore */
2471 if (mono_gc_is_finalizer_thread (thread)) {
2472 THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2476 if (thread == mono_thread_current ()) {
2477 THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2481 if (thread == mono_thread_get_main ()) {
2482 THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2486 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2487 if (handle == NULL) {
2488 THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2492 THREAD_DEBUG (g_message ("%s: Invoking mono_thread_manage callback on thread %p", __func__, thread));
2493 if ((thread->manage_callback == NULL) || (thread->manage_callback (thread) == TRUE)) {
2494 wait->handles[wait->num]=handle;
2495 wait->threads[wait->num]=thread;
2498 THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2500 THREAD_DEBUG (g_message ("%s: ignoring (because of callback) thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
2505 /* Just ignore the rest, we can't do anything with
2512 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
2514 struct wait_data *wait=(struct wait_data *)user;
2515 gsize self = GetCurrentThreadId ();
2516 MonoThread *thread = (MonoThread *) value;
2519 if (wait->num >= MAXIMUM_WAIT_OBJECTS)
2522 /* The finalizer thread is not a background thread */
2523 if (thread->tid != self && (thread->state & ThreadState_Background) != 0) {
2525 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2529 /* printf ("A: %d\n", wait->num); */
2530 wait->handles[wait->num]=thread->handle;
2531 wait->threads[wait->num]=thread;
2534 THREAD_DEBUG (g_print ("%s: Aborting id: %"G_GSIZE_FORMAT"\n", __func__, (gsize)thread->tid));
2535 mono_thread_stop (thread);
2539 return (thread->tid != self && !mono_gc_is_finalizer_thread (thread));
2542 static MonoException* mono_thread_execute_interruption (MonoThread *thread);
2545 * mono_threads_set_shutting_down:
2547 * Is called by a thread that wants to shut down Mono. If the runtime is already
2548 * shutting down, the calling thread is suspended/stopped, and this function never
2552 mono_threads_set_shutting_down (void)
2554 MonoThread *current_thread = mono_thread_current ();
2556 mono_threads_lock ();
2558 if (shutting_down) {
2559 mono_threads_unlock ();
2561 /* Make sure we're properly suspended/stopped */
2563 EnterCriticalSection (current_thread->synch_cs);
2565 if ((current_thread->state & ThreadState_SuspendRequested) ||
2566 (current_thread->state & ThreadState_AbortRequested) ||
2567 (current_thread->state & ThreadState_StopRequested)) {
2568 LeaveCriticalSection (current_thread->synch_cs);
2569 mono_thread_execute_interruption (current_thread);
2571 current_thread->state |= ThreadState_Stopped;
2572 LeaveCriticalSection (current_thread->synch_cs);
2575 /* Wake up other threads potentially waiting for us */
2578 shutting_down = TRUE;
2580 /* Not really a background state change, but this will
2581 * interrupt the main thread if it is waiting for all
2582 * the other threads.
2584 SetEvent (background_change_event);
2586 mono_threads_unlock ();
2591 * mono_threads_is_shutting_down:
2593 * Returns whether a thread has commenced shutdown of Mono. Note that
2594 * if the function returns FALSE the caller must not assume that
2595 * shutdown is not in progress, because the situation might have
2596 * changed since the function returned. For that reason this function
2597 * is of very limited utility.
2600 mono_threads_is_shutting_down (void)
2602 return shutting_down;
2605 void mono_thread_manage (void)
2607 struct wait_data *wait=g_new0 (struct wait_data, 1);
2609 /* join each thread that's still running */
2610 THREAD_DEBUG (g_message ("%s: Joining each running thread...", __func__));
2612 mono_threads_lock ();
2614 THREAD_DEBUG (g_message("%s: No threads", __func__));
2615 mono_threads_unlock ();
2618 mono_threads_unlock ();
2621 mono_threads_lock ();
2622 if (shutting_down) {
2623 /* somebody else is shutting down */
2624 mono_threads_unlock ();
2627 THREAD_DEBUG (g_message ("%s: There are %d threads to join", __func__, mono_g_hash_table_size (threads));
2628 mono_g_hash_table_foreach (threads, print_tids, NULL));
2630 ResetEvent (background_change_event);
2632 mono_g_hash_table_foreach (threads, build_wait_tids, wait);
2633 mono_threads_unlock ();
2635 /* Something to wait for */
2636 wait_for_tids_or_state_change (wait, INFINITE);
2638 THREAD_DEBUG (g_message ("%s: I have %d threads after waiting.", __func__, wait->num));
2639 } while(wait->num>0);
2641 mono_threads_set_shutting_down ();
2643 /* No new threads will be created after this point */
2645 mono_runtime_set_shutting_down ();
2647 THREAD_DEBUG (g_message ("%s: threadpool cleanup", __func__));
2648 mono_thread_pool_cleanup ();
2651 * Remove everything but the finalizer thread and self.
2652 * Also abort all the background threads
2655 mono_threads_lock ();
2658 mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
2660 mono_threads_unlock ();
2662 THREAD_DEBUG (g_message ("%s: wait->num is now %d", __func__, wait->num));
2664 /* Something to wait for */
2665 wait_for_tids (wait, INFINITE);
2667 } while (wait->num > 0);
2670 * give the subthreads a chance to really quit (this is mainly needed
2671 * to get correct user and system times from getrusage/wait/time(1)).
2672 * This could be removed if we avoid pthread_detach() and use pthread_join().
2674 #ifndef PLATFORM_WIN32
2681 static void terminate_thread (gpointer key, gpointer value, gpointer user)
2683 MonoThread *thread=(MonoThread *)value;
2685 if(thread->tid != (gsize)user) {
2686 /*TerminateThread (thread->handle, -1);*/
2690 void mono_thread_abort_all_other_threads (void)
2692 gsize self = GetCurrentThreadId ();
2694 mono_threads_lock ();
2695 THREAD_DEBUG (g_message ("%s: There are %d threads to abort", __func__,
2696 mono_g_hash_table_size (threads));
2697 mono_g_hash_table_foreach (threads, print_tids, NULL));
2699 mono_g_hash_table_foreach (threads, terminate_thread, (gpointer)self);
2701 mono_threads_unlock ();
2705 collect_threads_for_suspend (gpointer key, gpointer value, gpointer user_data)
2707 MonoThread *thread = (MonoThread*)value;
2708 struct wait_data *wait = (struct wait_data*)user_data;
2712 * We try to exclude threads early, to avoid running into the MAXIMUM_WAIT_OBJECTS
2714 * This needs no locking.
2716 if ((thread->state & ThreadState_Suspended) != 0 ||
2717 (thread->state & ThreadState_Stopped) != 0)
2720 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2721 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2725 wait->handles [wait->num] = handle;
2726 wait->threads [wait->num] = thread;
2732 * mono_thread_suspend_all_other_threads:
2734 * Suspend all managed threads except the finalizer thread and this thread. It is
2735 * not possible to resume them later.
2737 void mono_thread_suspend_all_other_threads (void)
2739 struct wait_data *wait = g_new0 (struct wait_data, 1);
2741 gsize self = GetCurrentThreadId ();
2743 guint32 eventidx = 0;
2744 gboolean starting, finished;
2747 * The other threads could be in an arbitrary state at this point, i.e.
2748 * they could be starting up, shutting down etc. This means that there could be
2749 * threads which are not even in the threads hash table yet.
2753 * First we set a barrier which will be checked by all threads before they
2754 * are added to the threads hash table, and they will exit if the flag is set.
2755 * This ensures that no threads could be added to the hash later.
2756 * We will use shutting_down as the barrier for now.
2758 g_assert (shutting_down);
2761 * We make multiple calls to WaitForMultipleObjects since:
2762 * - we can only wait for MAXIMUM_WAIT_OBJECTS threads
2763 * - some threads could exit without becoming suspended
2768 * Make a copy of the hashtable since we can't do anything with
2769 * threads while threads_mutex is held.
2772 mono_threads_lock ();
2773 mono_g_hash_table_foreach (threads, collect_threads_for_suspend, wait);
2774 mono_threads_unlock ();
2776 events = g_new0 (gpointer, wait->num);
2778 /* Get the suspended events that we'll be waiting for */
2779 for (i = 0; i < wait->num; ++i) {
2780 MonoThread *thread = wait->threads [i];
2782 if ((thread->tid == self) || mono_gc_is_finalizer_thread (thread)) {
2783 //CloseHandle (wait->handles [i]);
2784 wait->threads [i] = NULL; /* ignore this thread in next loop */
2788 ensure_synch_cs_set (thread);
2790 EnterCriticalSection (thread->synch_cs);
2792 if ((thread->state & ThreadState_Suspended) != 0 ||
2793 (thread->state & ThreadState_SuspendRequested) != 0 ||
2794 (thread->state & ThreadState_StopRequested) != 0 ||
2795 (thread->state & ThreadState_Stopped) != 0) {
2796 LeaveCriticalSection (thread->synch_cs);
2797 CloseHandle (wait->handles [i]);
2798 wait->threads [i] = NULL; /* ignore this thread in next loop */
2802 /* Convert abort requests into suspend requests */
2803 if ((thread->state & ThreadState_AbortRequested) != 0)
2804 thread->state &= ~ThreadState_AbortRequested;
2806 thread->state |= ThreadState_SuspendRequested;
2808 if (thread->suspended_event == NULL) {
2809 thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
2810 if (thread->suspended_event == NULL) {
2811 /* Forget this one and go on to the next */
2812 LeaveCriticalSection (thread->synch_cs);
2817 events [eventidx++] = thread->suspended_event;
2818 LeaveCriticalSection (thread->synch_cs);
2820 /* Signal the thread to suspend */
2821 signal_thread_state_change (thread);
2825 WaitForMultipleObjectsEx (eventidx, events, TRUE, 100, FALSE);
2826 for (i = 0; i < wait->num; ++i) {
2827 MonoThread *thread = wait->threads [i];
2832 EnterCriticalSection (thread->synch_cs);
2833 if ((thread->state & ThreadState_Suspended) != 0) {
2834 CloseHandle (thread->suspended_event);
2835 thread->suspended_event = NULL;
2837 LeaveCriticalSection (thread->synch_cs);
2841 * If there are threads which are starting up, we wait until they
2842 * are suspended when they try to register in the threads hash.
2843 * This is guaranteed to finish, since the threads which can create new
2844 * threads get suspended after a while.
2845 * FIXME: The finalizer thread can still create new threads.
2847 mono_threads_lock ();
2848 starting = mono_g_hash_table_size (threads_starting_up) > 0;
2849 mono_threads_unlock ();
2863 collect_threads (gpointer key, gpointer value, gpointer user_data)
2865 MonoThread *thread = (MonoThread*)value;
2866 struct wait_data *wait = (struct wait_data*)user_data;
2869 if (wait->num<MAXIMUM_WAIT_OBJECTS) {
2870 handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2874 wait->handles [wait->num] = handle;
2875 wait->threads [wait->num] = thread;
2881 * mono_threads_request_thread_dump:
2883 * Ask all threads except the current to print their stacktrace to stdout.
2886 mono_threads_request_thread_dump (void)
2888 struct wait_data *wait = g_new0 (struct wait_data, 1);
2892 * Make a copy of the hashtable since we can't do anything with
2893 * threads while threads_mutex is held.
2895 mono_threads_lock ();
2896 mono_g_hash_table_foreach (threads, collect_threads, wait);
2897 mono_threads_unlock ();
2899 for (i = 0; i < wait->num; ++i) {
2900 MonoThread *thread = wait->threads [i];
2902 if (!mono_gc_is_finalizer_thread (thread) && (thread != mono_thread_current ()) && !thread->thread_dump_requested) {
2903 thread->thread_dump_requested = TRUE;
2905 signal_thread_state_change (thread);
2908 CloseHandle (wait->handles [i]);
2913 * mono_thread_push_appdomain_ref:
2915 * Register that the current thread may have references to objects in domain
2916 * @domain on its stack. Each call to this function should be paired with a
2917 * call to pop_appdomain_ref.
2920 mono_thread_push_appdomain_ref (MonoDomain *domain)
2922 MonoThread *thread = mono_thread_current ();
2925 /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
2926 mono_threads_lock ();
2927 thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
2928 mono_threads_unlock ();
2933 mono_thread_pop_appdomain_ref (void)
2935 MonoThread *thread = mono_thread_current ();
2938 /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
2939 mono_threads_lock ();
2940 /* FIXME: How can the list be empty ? */
2941 if (thread->appdomain_refs)
2942 thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
2943 mono_threads_unlock ();
2948 mono_thread_has_appdomain_ref (MonoThread *thread, MonoDomain *domain)
2951 mono_threads_lock ();
2952 res = g_slist_find (thread->appdomain_refs, domain) != NULL;
2953 mono_threads_unlock ();
2957 typedef struct abort_appdomain_data {
2958 struct wait_data wait;
2960 } abort_appdomain_data;
2963 abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
2965 MonoThread *thread = (MonoThread*)value;
2966 abort_appdomain_data *data = (abort_appdomain_data*)user_data;
2967 MonoDomain *domain = data->domain;
2969 if (mono_thread_has_appdomain_ref (thread, domain)) {
2970 /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread->tid, domain->friendly_name); */
2972 ves_icall_System_Threading_Thread_Abort (thread, NULL);
2974 if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
2975 HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
2978 data->wait.handles [data->wait.num] = handle;
2979 data->wait.threads [data->wait.num] = thread;
2982 /* Just ignore the rest, we can't do anything with
2990 * mono_threads_abort_appdomain_threads:
2992 * Abort threads which has references to the given appdomain.
2995 mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
2997 abort_appdomain_data user_data;
3000 THREAD_DEBUG (g_message ("%s: starting abort", __func__));
3002 start_time = mono_msec_ticks ();
3004 mono_threads_lock ();
3006 user_data.domain = domain;
3007 user_data.wait.num = 0;
3008 mono_g_hash_table_foreach (threads, abort_appdomain_thread, &user_data);
3009 mono_threads_unlock ();
3011 if (user_data.wait.num > 0)
3013 * We should wait for the threads either to abort, or to leave the
3014 * domain. We can't do the latter, so we wait with a timeout.
3016 wait_for_tids (&user_data.wait, 100);
3018 /* Update remaining time */
3019 timeout -= mono_msec_ticks () - start_time;
3020 start_time = mono_msec_ticks ();
3025 while (user_data.wait.num > 0);
3027 THREAD_DEBUG (g_message ("%s: abort done", __func__));
3033 clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
3035 MonoThread *thread = (MonoThread*)value;
3036 MonoDomain *domain = (MonoDomain*)user_data;
3039 /* No locking needed here */
3040 /* FIXME: why no locking? writes to the cache are protected with synch_cs above */
3042 if (thread->cached_culture_info) {
3043 for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
3044 MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
3045 if (obj && obj->vtable->domain == domain)
3046 mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
3052 * mono_threads_clear_cached_culture:
3054 * Clear the cached_current_culture from all threads if it is in the
3058 mono_threads_clear_cached_culture (MonoDomain *domain)
3060 mono_threads_lock ();
3061 mono_g_hash_table_foreach (threads, clear_cached_culture, domain);
3062 mono_threads_unlock ();
3066 * mono_thread_get_undeniable_exception:
3068 * Return an exception which needs to be raised when leaving a catch clause.
3069 * This is used for undeniable exception propagation.
3072 mono_thread_get_undeniable_exception (void)
3074 MonoThread *thread = mono_thread_current ();
3076 MONO_ARCH_SAVE_REGS;
3078 if (thread && thread->abort_exc && !is_running_protected_wrapper ()) {
3080 * FIXME: Clear the abort exception and return an AppDomainUnloaded
3081 * exception if the thread no longer references a dying appdomain.
3083 thread->abort_exc->trace_ips = NULL;
3084 thread->abort_exc->stack_trace = NULL;
3085 return thread->abort_exc;
3091 #define NUM_STATIC_DATA_IDX 8
3092 static const int static_data_size [NUM_STATIC_DATA_IDX] = {
3093 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216
3098 * mono_alloc_static_data
3100 * Allocate memory blocks for storing threads or context static data
3103 mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
3105 guint idx = (offset >> 24) - 1;
3108 gpointer* static_data = *static_data_ptr;
3110 static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
3111 *static_data_ptr = static_data;
3112 static_data [0] = static_data;
3115 for (i = 1; i <= idx; ++i) {
3116 if (static_data [i])
3118 static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
3123 * mono_init_static_data_info
3125 * Initializes static data counters
3127 static void mono_init_static_data_info (StaticDataInfo *static_data)
3129 static_data->idx = 0;
3130 static_data->offset = 0;
3131 static_data->freelist = NULL;
3135 * mono_alloc_static_data_slot
3137 * Generates an offset for static data. static_data contains the counters
3138 * used to generate it.
3141 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align)
3145 if (!static_data->idx && !static_data->offset) {
3147 * we use the first chunk of the first allocation also as
3148 * an array for the rest of the data
3150 static_data->offset = sizeof (gpointer) * NUM_STATIC_DATA_IDX;
3152 static_data->offset += align - 1;
3153 static_data->offset &= ~(align - 1);
3154 if (static_data->offset + size >= static_data_size [static_data->idx]) {
3155 static_data->idx ++;
3156 g_assert (size <= static_data_size [static_data->idx]);
3157 g_assert (static_data->idx < NUM_STATIC_DATA_IDX);
3158 static_data->offset = 0;
3160 offset = static_data->offset | ((static_data->idx + 1) << 24);
3161 static_data->offset += size;
3166 * ensure thread static fields already allocated are valid for thread
3167 * This function is called when a thread is created or on thread attach.
3170 thread_adjust_static_data (MonoThread *thread)
3174 mono_threads_lock ();
3175 if (thread_static_info.offset || thread_static_info.idx > 0) {
3176 /* get the current allocated size */
3177 offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
3178 mono_alloc_static_data (&(thread->static_data), offset);
3180 mono_threads_unlock ();
3184 alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3186 MonoThread *thread = value;
3187 guint32 offset = GPOINTER_TO_UINT (user);
3189 mono_alloc_static_data (&(thread->static_data), offset);
3192 static MonoThreadDomainTls*
3193 search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32 align)
3195 MonoThreadDomainTls* prev = NULL;
3196 MonoThreadDomainTls* tmp = static_data->freelist;
3198 if (tmp->size == size) {
3200 prev->next = tmp->next;
3202 static_data->freelist = tmp->next;
3211 * The offset for a special static variable is composed of three parts:
3212 * a bit that indicates the type of static data (0:thread, 1:context),
3213 * an index in the array of chunks of memory for the thread (thread->static_data)
3214 * and an offset in that chunk of mem. This allows allocating less memory in the
3219 mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
3222 if (static_type == SPECIAL_STATIC_THREAD)
3224 MonoThreadDomainTls *item;
3225 mono_threads_lock ();
3226 item = search_tls_slot_in_freelist (&thread_static_info, size, align);
3227 /*g_print ("TLS alloc: %d in domain %p (total: %d), cached: %p\n", size, mono_domain_get (), thread_static_info.offset, item);*/
3229 offset = item->offset;
3232 offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
3234 /* This can be called during startup */
3235 if (threads != NULL)
3236 mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
3237 mono_threads_unlock ();
3241 g_assert (static_type == SPECIAL_STATIC_CONTEXT);
3242 mono_contexts_lock ();
3243 offset = mono_alloc_static_data_slot (&context_static_info, size, align);
3244 mono_contexts_unlock ();
3245 offset |= 0x80000000; /* Set the high bit to indicate context static data */
3251 mono_get_special_static_data (guint32 offset)
3253 /* The high bit means either thread (0) or static (1) data. */
3255 guint32 static_type = (offset & 0x80000000);
3258 offset &= 0x7fffffff;
3259 idx = (offset >> 24) - 1;
3261 if (static_type == 0)
3263 MonoThread *thread = mono_thread_current ();
3264 return ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3268 /* Allocate static data block under demand, since we don't have a list
3271 MonoAppContext *context = mono_context_get ();
3272 if (!context->static_data || !context->static_data [idx]) {
3273 mono_contexts_lock ();
3274 mono_alloc_static_data (&(context->static_data), offset);
3275 mono_contexts_unlock ();
3277 return ((char*) context->static_data [idx]) + (offset & 0xffffff);
3287 free_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
3289 MonoThread *thread = value;
3290 TlsOffsetSize *data = user;
3291 int idx = (data->offset >> 24) - 1;
3294 if (!thread->static_data || !thread->static_data [idx])
3296 ptr = ((char*) thread->static_data [idx]) + (data->offset & 0xffffff);
3297 memset (ptr, 0, data->size);
3301 do_free_special (gpointer key, gpointer value, gpointer data)
3303 MonoClassField *field = key;
3304 guint32 offset = GPOINTER_TO_UINT (value);
3305 guint32 static_type = (offset & 0x80000000);
3308 size = mono_type_size (field->type, &align);
3309 /*g_print ("free %s , size: %d, offset: %x\n", field->name, size, offset);*/
3310 if (static_type == 0) {
3312 MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
3313 data.offset = offset & 0x7fffffff;
3315 if (threads != NULL)
3316 mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
3317 item->offset = offset;
3319 item->next = thread_static_info.freelist;
3320 thread_static_info.freelist = item;
3322 /* FIXME: free context static data as well */
3327 mono_alloc_special_static_data_free (GHashTable *special_static_fields)
3329 mono_threads_lock ();
3330 g_hash_table_foreach (special_static_fields, do_free_special, NULL);
3331 mono_threads_unlock ();
3334 static MonoClassField *local_slots = NULL;
3337 /* local tls data to get locals_slot from a thread */
3340 /* index in the locals_slot array */
3345 clear_local_slot (gpointer key, gpointer value, gpointer user_data)
3347 LocalSlotID *sid = user_data;
3348 MonoThread *thread = (MonoThread*)value;
3349 MonoArray *slots_array;
3351 * the static field is stored at: ((char*) thread->static_data [idx]) + (offset & 0xffffff);
3352 * it is for the right domain, so we need to check if it is allocated an initialized
3353 * for the current thread.
3355 /*g_print ("handling thread %p\n", thread);*/
3356 if (!thread->static_data || !thread->static_data [sid->idx])
3358 slots_array = *(MonoArray **)(((char*) thread->static_data [sid->idx]) + (sid->offset & 0xffffff));
3359 if (!slots_array || sid->slot >= mono_array_length (slots_array))
3361 mono_array_set (slots_array, MonoObject*, sid->slot, NULL);
3365 mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
3373 local_slots = mono_class_get_field_from_name (mono_defaults.thread_class, "local_slots");
3375 g_warning ("local_slots field not found in Thread class");
3379 domain = mono_domain_get ();
3380 mono_domain_lock (domain);
3381 if (domain->special_static_fields)
3382 addr = g_hash_table_lookup (domain->special_static_fields, local_slots);
3383 mono_domain_unlock (domain);
3386 /*g_print ("freeing slot %d at %p\n", slot, addr);*/
3387 sid.offset = GPOINTER_TO_UINT (addr);
3388 sid.offset &= 0x7fffffff;
3389 sid.idx = (sid.offset >> 24) - 1;
3390 mono_threads_lock ();
3391 mono_g_hash_table_foreach (threads, clear_local_slot, &sid);
3392 mono_threads_unlock ();
3394 /* FIXME: clear the slot for MonoAppContexts, too */
3398 #ifdef PLATFORM_WIN32
3399 static void CALLBACK dummy_apc (ULONG_PTR param)
3403 static guint32 dummy_apc (gpointer param)
3410 * mono_thread_execute_interruption
3412 * Performs the operation that the requested thread state requires (abort,
3415 static MonoException* mono_thread_execute_interruption (MonoThread *thread)
3417 ensure_synch_cs_set (thread);
3419 EnterCriticalSection (thread->synch_cs);
3421 if (thread->interruption_requested) {
3422 /* this will consume pending APC calls */
3423 WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
3424 InterlockedDecrement (&thread_interruption_requested);
3425 thread->interruption_requested = FALSE;
3428 if ((thread->state & ThreadState_AbortRequested) != 0) {
3429 if (thread->abort_exc == NULL)
3430 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
3431 LeaveCriticalSection (thread->synch_cs);
3432 return thread->abort_exc;
3434 else if ((thread->state & ThreadState_SuspendRequested) != 0) {
3435 thread->state &= ~ThreadState_SuspendRequested;
3436 thread->state |= ThreadState_Suspended;
3437 thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
3438 if (thread->suspend_event == NULL) {
3439 LeaveCriticalSection (thread->synch_cs);
3442 if (thread->suspended_event)
3443 SetEvent (thread->suspended_event);
3445 LeaveCriticalSection (thread->synch_cs);
3447 if (shutting_down) {
3448 /* After we left the lock, the runtime might shut down so everything becomes invalid */
3453 WaitForSingleObject (thread->suspend_event, INFINITE);
3455 EnterCriticalSection (thread->synch_cs);
3457 CloseHandle (thread->suspend_event);
3458 thread->suspend_event = NULL;
3459 thread->state &= ~ThreadState_Suspended;
3461 /* The thread that requested the resume will have replaced this event
3462 * and will be waiting for it
3464 SetEvent (thread->resume_event);
3466 LeaveCriticalSection (thread->synch_cs);
3470 else if ((thread->state & ThreadState_StopRequested) != 0) {
3471 /* FIXME: do this through the JIT? */
3473 LeaveCriticalSection (thread->synch_cs);
3475 mono_thread_exit ();
3477 } else if (thread->thread_interrupt_requested) {
3479 LeaveCriticalSection (thread->synch_cs);
3481 return(mono_get_exception_thread_interrupted ());
3484 LeaveCriticalSection (thread->synch_cs);
3490 * mono_thread_request_interruption
3492 * A signal handler can call this method to request the interruption of a
3493 * thread. The result of the interruption will depend on the current state of
3494 * the thread. If the result is an exception that needs to be throw, it is
3495 * provided as return value.
3497 MonoException* mono_thread_request_interruption (gboolean running_managed)
3499 MonoThread *thread = mono_thread_current ();
3501 /* The thread may already be stopping */
3505 ensure_synch_cs_set (thread);
3507 /* FIXME: This is NOT signal safe */
3508 EnterCriticalSection (thread->synch_cs);
3510 if (thread->interruption_requested) {
3511 LeaveCriticalSection (thread->synch_cs);
3516 if (!running_managed || is_running_protected_wrapper ()) {
3517 /* Can't stop while in unmanaged code. Increase the global interruption
3518 request count. When exiting the unmanaged method the count will be
3519 checked and the thread will be interrupted. */
3521 InterlockedIncrement (&thread_interruption_requested);
3522 thread->interruption_requested = TRUE;
3524 LeaveCriticalSection (thread->synch_cs);
3526 if (mono_thread_notify_pending_exc_fn && !running_managed)
3527 /* The JIT will notify the thread about the interruption */
3528 /* This shouldn't take any locks */
3529 mono_thread_notify_pending_exc_fn ();
3531 /* this will awake the thread if it is in WaitForSingleObject
3533 /* FIXME: This is NOT signal-safe, since it allocates memory and uses locking */
3534 QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
3538 LeaveCriticalSection (thread->synch_cs);
3540 return mono_thread_execute_interruption (thread);
3544 gboolean mono_thread_interruption_requested ()
3546 if (thread_interruption_requested) {
3547 MonoThread *thread = mono_thread_current ();
3548 /* The thread may already be stopping */
3550 return (thread->interruption_requested);
3555 static void mono_thread_interruption_checkpoint_request (gboolean bypass_abort_protection)
3557 MonoThread *thread = mono_thread_current ();
3559 /* The thread may already be stopping */
3563 if (thread->interruption_requested && (bypass_abort_protection || !is_running_protected_wrapper ())) {
3564 MonoException* exc = mono_thread_execute_interruption (thread);
3565 if (exc) mono_raise_exception (exc);
3570 * Performs the interruption of the current thread, if one has been requested,
3571 * and the thread is not running a protected wrapper.
3573 void mono_thread_interruption_checkpoint ()
3575 mono_thread_interruption_checkpoint_request (FALSE);
3579 * Performs the interruption of the current thread, if one has been requested.
3581 void mono_thread_force_interruption_checkpoint ()
3583 mono_thread_interruption_checkpoint_request (TRUE);
3587 * mono_thread_get_and_clear_pending_exception:
3589 * Return any pending exceptions for the current thread and clear it as a side effect.
3592 mono_thread_get_and_clear_pending_exception (void)
3594 MonoThread *thread = mono_thread_current ();
3596 /* The thread may already be stopping */
3600 if (thread->interruption_requested && !is_running_protected_wrapper ()) {
3601 return mono_thread_execute_interruption (thread);
3608 * mono_thread_interruption_request_flag:
3610 * Returns the address of a flag that will be non-zero if an interruption has
3611 * been requested for a thread. The thread to interrupt may not be the current
3612 * thread, so an additional call to mono_thread_interruption_requested() or
3613 * mono_thread_interruption_checkpoint() is allways needed if the flag is not
3616 gint32* mono_thread_interruption_request_flag ()
3618 return &thread_interruption_requested;
3622 mono_thread_init_apartment_state (void)
3625 thread = mono_thread_current ();
3627 #ifdef PLATFORM_WIN32
3628 /* Positive return value indicates success, either
3629 * S_OK if this is first CoInitialize call, or
3630 * S_FALSE if CoInitialize already called, but with same
3631 * threading model. A negative value indicates failure,
3632 * probably due to trying to change the threading model.
3634 if (CoInitializeEx(NULL, (thread->apartment_state == ThreadApartmentState_STA)
3635 ? COINIT_APARTMENTTHREADED
3636 : COINIT_MULTITHREADED) < 0) {
3637 thread->apartment_state = ThreadApartmentState_Unknown;
3643 mono_thread_cleanup_apartment_state (void)
3645 #ifdef PLATFORM_WIN32
3647 thread = mono_thread_current ();
3649 if (thread && thread->apartment_state != ThreadApartmentState_Unknown) {
3656 mono_thread_set_state (MonoThread *thread, MonoThreadState state)
3658 ensure_synch_cs_set (thread);
3660 EnterCriticalSection (thread->synch_cs);
3661 thread->state |= state;
3662 LeaveCriticalSection (thread->synch_cs);
3666 mono_thread_clr_state (MonoThread *thread, MonoThreadState state)
3668 ensure_synch_cs_set (thread);
3670 EnterCriticalSection (thread->synch_cs);
3671 thread->state &= ~state;
3672 LeaveCriticalSection (thread->synch_cs);
3676 mono_thread_test_state (MonoThread *thread, MonoThreadState test)
3678 gboolean ret = FALSE;
3680 ensure_synch_cs_set (thread);
3682 EnterCriticalSection (thread->synch_cs);
3684 if ((thread->state & test) != 0) {
3688 LeaveCriticalSection (thread->synch_cs);